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-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/FlinkConfigExtractor.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.flink.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
final class FlinkConfigExtractor {
/**
* Reflectively extracts Flink {@link Configuration} from a {@link StreamExecutionEnvironment}.
* The Flink configuration contains Stateful Functions specific configurations. This is currently
* a private method in the {@code StreamExecutionEnvironment} class.
*/
static Configuration reflectivelyExtractFromEnv(StreamExecutionEnvironment env) {
try {
return (Configuration) getConfigurationMethod().invoke(env);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(
"Failed to acquire the Flink configuration from the current environment", e);
}
}
private static Method getConfigurationMethod() throws NoSuchMethodException {
Method getConfiguration =
StreamExecutionEnvironment.class.getDeclaredMethod("getConfiguration");
getConfiguration.setAccessible(true);
return getConfiguration;
}
}
| 6,100 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/StatefulFunctionsJobConstants.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.flink.core;
@SuppressWarnings("WeakerAccess")
public final class StatefulFunctionsJobConstants {
public static final String FEEDBACK_UNION_OPERATOR_NAME = "feedback-union";
public static final String FEEDBACK_UNION_OPERATOR_UID = "feedback_union_uid1";
public static final String FUNCTION_OPERATOR_NAME = "functions";
public static final String FUNCTION_OPERATOR_UID = "functions_uid1";
public static final String WRITE_BACK_OPERATOR_NAME = "feedback";
public static final String WRITE_BACK_OPERATOR_UID = "feedback_uid1";
public static final String ROUTER_NAME = "router";
private StatefulFunctionsJobConstants() {}
}
| 6,101 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FunctionDispatcherMetrics.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.flink.core.metrics;
public interface FunctionDispatcherMetrics {
void asyncOperationRegistered();
void asyncOperationCompleted();
}
| 6,102 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FlinkMetricUtil.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.flink.core.metrics;
import org.apache.flink.statefun.sdk.metrics.Counter;
final class FlinkMetricUtil {
private FlinkMetricUtil() {}
static Counter wrapFlinkCounterAsSdkCounter(org.apache.flink.metrics.Counter internalCounter) {
return new Counter() {
@Override
public void inc(long amount) {
internalCounter.inc(amount);
}
@Override
public void dec(long amount) {
internalCounter.dec(amount);
}
};
}
}
| 6,103 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FunctionTypeMetricsRepository.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.flink.core.metrics;
import org.apache.flink.statefun.sdk.FunctionType;
public interface FunctionTypeMetricsRepository {
FunctionTypeMetrics getMetrics(FunctionType functionType);
}
| 6,104 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FuncionTypeMetricsFactory.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.flink.core.metrics;
import org.apache.flink.statefun.sdk.FunctionType;
public interface FuncionTypeMetricsFactory {
FunctionTypeMetrics forType(FunctionType functionType);
}
| 6,105 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FlinkUserMetrics.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.flink.core.metrics;
import static org.apache.flink.statefun.flink.core.metrics.FlinkMetricUtil.wrapFlinkCounterAsSdkCounter;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashMap;
import java.util.Objects;
import org.apache.flink.annotation.Internal;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.statefun.sdk.metrics.Counter;
import org.apache.flink.statefun.sdk.metrics.Metrics;
@Internal
public final class FlinkUserMetrics implements Metrics {
private final ObjectOpenHashMap<String, Counter> counters = new ObjectOpenHashMap<>();
private final MetricGroup typeGroup;
public FlinkUserMetrics(MetricGroup typeGroup) {
this.typeGroup = Objects.requireNonNull(typeGroup);
}
@Override
public Counter counter(String name) {
Objects.requireNonNull(name);
Counter counter = counters.get(name);
if (counter == null) {
SimpleCounter internalCounter = typeGroup.counter(name, new SimpleCounter());
counters.put(name, counter = wrapFlinkCounterAsSdkCounter(internalCounter));
}
return counter;
}
}
| 6,106 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FlinkFuncionTypeMetricsFactory.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.flink.core.metrics;
import java.util.Objects;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.metrics.Metrics;
public class FlinkFuncionTypeMetricsFactory implements FuncionTypeMetricsFactory {
private final MetricGroup metricGroup;
public FlinkFuncionTypeMetricsFactory(MetricGroup metricGroup) {
this.metricGroup = Objects.requireNonNull(metricGroup);
}
@Override
public FunctionTypeMetrics forType(FunctionType functionType) {
MetricGroup namespace = metricGroup.addGroup(functionType.namespace());
MetricGroup typeGroup = namespace.addGroup(functionType.name());
Metrics functionTypeScopedMetrics = new FlinkUserMetrics(typeGroup);
return new FlinkFunctionTypeMetrics(typeGroup, functionTypeScopedMetrics);
}
}
| 6,107 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/RemoteInvocationMetrics.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.flink.core.metrics;
public interface RemoteInvocationMetrics {
void remoteInvocationFailures();
void remoteInvocationLatency(long elapsed);
}
| 6,108 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FunctionTypeMetrics.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.flink.core.metrics;
import org.apache.flink.statefun.sdk.metrics.Metrics;
public interface FunctionTypeMetrics extends RemoteInvocationMetrics {
void incomingMessage();
void outgoingLocalMessage();
void outgoingRemoteMessage();
void outgoingEgressMessage();
void blockedAddress();
void unblockedAddress();
void asyncOperationRegistered();
void asyncOperationCompleted();
void appendBacklogMessages(int count);
void consumeBacklogMessages(int count);
Metrics functionTypeScopedMetrics();
}
| 6,109 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FlinkFunctionDispatcherMetrics.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.flink.core.metrics;
import java.util.Objects;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.MetricGroup;
public class FlinkFunctionDispatcherMetrics implements FunctionDispatcherMetrics {
private final Counter inflightAsyncOperations;
public FlinkFunctionDispatcherMetrics(MetricGroup operatorGroup) {
Objects.requireNonNull(operatorGroup, "operatorGroup");
this.inflightAsyncOperations = operatorGroup.counter("inflightAsyncOps");
}
@Override
public void asyncOperationRegistered() {
inflightAsyncOperations.inc();
}
@Override
public void asyncOperationCompleted() {
inflightAsyncOperations.dec();
}
}
| 6,110 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/FlinkFunctionTypeMetrics.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.flink.core.metrics;
import com.codahale.metrics.UniformReservoir;
import java.util.Objects;
import org.apache.flink.dropwizard.metrics.DropwizardHistogramWrapper;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.Histogram;
import org.apache.flink.metrics.MeterView;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.statefun.sdk.metrics.Metrics;
final class FlinkFunctionTypeMetrics implements FunctionTypeMetrics {
private final Counter incoming;
private final Counter outgoingLocalMessage;
private final Counter outgoingRemoteMessage;
private final Counter outgoingEgress;
private final Counter blockedAddress;
private final Counter inflightAsyncOps;
private final Counter backlogMessage;
private final Counter remoteInvocationFailures;
private final Histogram remoteInvocationLatency;
private final Metrics functionTypeScopedMetrics;
FlinkFunctionTypeMetrics(MetricGroup typeGroup, Metrics functionTypeScopedMetrics) {
this.incoming = metered(typeGroup, "in");
this.outgoingLocalMessage = metered(typeGroup, "outLocal");
this.outgoingRemoteMessage = metered(typeGroup, "outRemote");
this.outgoingEgress = metered(typeGroup, "outEgress");
this.blockedAddress = typeGroup.counter("numBlockedAddress");
this.inflightAsyncOps = typeGroup.counter("inflightAsyncOps");
this.backlogMessage = typeGroup.counter("numBacklog", new NonNegativeCounter());
this.remoteInvocationFailures = metered(typeGroup, "remoteInvocationFailures");
this.remoteInvocationLatency = typeGroup.histogram("remoteInvocationLatency", histogram());
this.functionTypeScopedMetrics = Objects.requireNonNull(functionTypeScopedMetrics);
}
@Override
public void incomingMessage() {
incoming.inc();
}
@Override
public void outgoingLocalMessage() {
this.outgoingLocalMessage.inc();
}
@Override
public void outgoingRemoteMessage() {
this.outgoingRemoteMessage.inc();
}
@Override
public void outgoingEgressMessage() {
this.outgoingEgress.inc();
}
@Override
public void blockedAddress() {
this.blockedAddress.inc();
}
@Override
public void unblockedAddress() {
this.blockedAddress.dec();
}
@Override
public void asyncOperationRegistered() {
this.inflightAsyncOps.inc();
}
@Override
public void asyncOperationCompleted() {
this.inflightAsyncOps.dec();
}
@Override
public void appendBacklogMessages(int count) {
backlogMessage.inc(count);
}
@Override
public void consumeBacklogMessages(int count) {
backlogMessage.dec(count);
}
@Override
public Metrics functionTypeScopedMetrics() {
return functionTypeScopedMetrics;
}
@Override
public void remoteInvocationFailures() {
remoteInvocationFailures.inc();
}
@Override
public void remoteInvocationLatency(long elapsed) {
remoteInvocationLatency.update(elapsed);
}
private static SimpleCounter metered(MetricGroup metrics, String name) {
SimpleCounter counter = metrics.counter(name, new SimpleCounter());
metrics.meter(name + "Rate", new MeterView(counter, 60));
return counter;
}
private static DropwizardHistogramWrapper histogram() {
com.codahale.metrics.Histogram dropwizardHistogram =
new com.codahale.metrics.Histogram(new UniformReservoir());
return new DropwizardHistogramWrapper(dropwizardHistogram);
}
}
| 6,111 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/metrics/NonNegativeCounter.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.flink.core.metrics;
import org.apache.flink.metrics.Counter;
/**
* A simple counter that can never go below zero.
*
* <p>This class is used in a non-thread safe manner, so it is important all modifications are
* checked before updating the count. Otherwise, negative values might be reported.
*/
public class NonNegativeCounter implements Counter {
private long count;
@Override
public void inc() {
inc(1);
}
@Override
public void inc(long value) {
count += value;
}
@Override
public void dec() {
dec(1);
}
@Override
public void dec(long value) {
if (value > count) {
count = 0;
} else {
count -= value;
}
}
@Override
public long getCount() {
return count;
}
}
| 6,112 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/StaticallyRegisteredTypes.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.flink.core.types;
import com.google.protobuf.Message;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufTypeInformation;
import org.apache.flink.statefun.flink.core.message.MessageFactoryKey;
import org.apache.flink.statefun.flink.core.message.MessageTypeInformation;
/**
* StaticallyRegisteredTypes are types that were registered during the creation of the Stateful
* Functions universe.
*/
@NotThreadSafe
@SuppressWarnings("unchecked")
public final class StaticallyRegisteredTypes {
private final Map<Class<?>, TypeInformation<?>> registeredTypes = new HashMap<>();
public StaticallyRegisteredTypes(MessageFactoryKey messageFactoryKey) {
this.messageFactoryKey = messageFactoryKey;
}
private final MessageFactoryKey messageFactoryKey;
public <T> TypeInformation<T> registerType(Class<T> type) {
return (TypeInformation<T>) registeredTypes.computeIfAbsent(type, this::typeInformation);
}
/**
* Retrieves the previously registered type. This is safe to access concurrently, after the
* translation phase is over.
*/
@Nullable
<T> TypeInformation<T> getType(Class<T> valueType) {
return (TypeInformation<T>) registeredTypes.get(valueType);
}
private TypeInformation<?> typeInformation(Class<?> valueType) {
if (Message.class.isAssignableFrom(valueType)) {
Class<Message> message = (Class<Message>) valueType;
return new ProtobufTypeInformation<>(message);
}
if (org.apache.flink.statefun.flink.core.message.Message.class.isAssignableFrom(valueType)) {
return new MessageTypeInformation(messageFactoryKey);
}
// TODO: we may want to restrict the allowed typeInfo here to theses that respect shcema
// evaluation.
return TypeInformation.of(valueType);
}
}
| 6,113 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/DynamicallyRegisteredTypes.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.flink.core.types;
import com.google.protobuf.Message;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufTypeInformation;
import org.apache.flink.statefun.sdk.state.PersistedValue;
/**
* DynamicallyRegisteredTypes are types that are types that were discovered during runtime, for
* example registered {@linkplain PersistedValue}s.
*/
@NotThreadSafe
public final class DynamicallyRegisteredTypes {
private final StaticallyRegisteredTypes staticallyKnownTypes;
private final Map<Class<?>, TypeInformation<?>> registeredTypes = new HashMap<>();
public DynamicallyRegisteredTypes(StaticallyRegisteredTypes staticallyKnownTypes) {
this.staticallyKnownTypes = Objects.requireNonNull(staticallyKnownTypes);
}
@SuppressWarnings("unchecked")
public <T> TypeInformation<T> registerType(Class<T> type) {
TypeInformation<T> typeInfo = staticallyKnownTypes.getType(type);
if (typeInfo != null) {
return typeInfo;
}
return (TypeInformation<T>) registeredTypes.computeIfAbsent(type, this::typeInformation);
}
@SuppressWarnings("unchecked")
private TypeInformation<?> typeInformation(Class<?> valueType) {
if (Message.class.isAssignableFrom(valueType)) {
Class<Message> message = (Class<Message>) valueType;
return new ProtobufTypeInformation<>(message);
}
// TODO: we may want to restrict the allowed typeInfo here to theses that respect schema
// evaluation.
return TypeInformation.of(valueType);
}
}
| 6,114 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/remote/RemoteValueSerializerSnapshot.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.flink.core.types.remote;
import java.io.IOException;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSchemaCompatibility;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.statefun.sdk.TypeName;
public class RemoteValueSerializerSnapshot implements TypeSerializerSnapshot<byte[]> {
private static final Integer VERSION = 1;
private TypeName type;
// empty constructor for restore paths
public RemoteValueSerializerSnapshot() {}
RemoteValueSerializerSnapshot(TypeName type) {
this.type = type;
}
public TypeName type() {
return type;
}
@Override
public int getCurrentVersion() {
return VERSION;
}
@Override
public void writeSnapshot(DataOutputView dataOutputView) throws IOException {
dataOutputView.writeUTF(type.namespace());
dataOutputView.writeUTF(type.name());
}
@Override
public void readSnapshot(int i, DataInputView dataInputView, ClassLoader classLoader)
throws IOException {
final String namespace = dataInputView.readUTF();
final String name = dataInputView.readUTF();
this.type = new TypeName(namespace, name);
}
@Override
public TypeSerializer<byte[]> restoreSerializer() {
return new RemoteValueSerializer(type);
}
@Override
public TypeSerializerSchemaCompatibility<byte[]> resolveSchemaCompatibility(
TypeSerializer<byte[]> otherSerializer) {
if (!(otherSerializer instanceof RemoteValueSerializer)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
final RemoteValueSerializer otherRemoteTypeSerializer = (RemoteValueSerializer) otherSerializer;
if (!type.equals(otherRemoteTypeSerializer.getType())) {
// throw an exception to bubble up information about the previous snapshotted typename
// TODO would this mess with Flink's schema compatibility checks?
// TODO this should be fine, since at the moment, if we return incompatible, Flink immediately
// fails anyways
throw new RemoteValueTypeMismatchException(type, otherRemoteTypeSerializer.getType());
}
return TypeSerializerSchemaCompatibility.compatibleAsIs();
}
}
| 6,115 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/remote/RemoteValueSerializer.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.flink.core.types.remote;
import java.io.IOException;
import java.util.Objects;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.statefun.sdk.TypeName;
final class RemoteValueSerializer extends TypeSerializer<byte[]> {
private static final long serialVersionUID = 1L;
private static final byte[] EMPTY = new byte[0];
private final TypeName type;
public RemoteValueSerializer(TypeName type) {
this.type = Objects.requireNonNull(type);
}
public TypeName getType() {
return type;
}
@Override
public boolean isImmutableType() {
return false;
}
@Override
public byte[] createInstance() {
return EMPTY;
}
@Override
public byte[] copy(byte[] from) {
byte[] copy = new byte[from.length];
System.arraycopy(from, 0, copy, 0, from.length);
return copy;
}
@Override
public byte[] copy(byte[] from, byte[] reuse) {
return copy(from);
}
@Override
public int getLength() {
return -1;
}
@Override
public void serialize(byte[] record, DataOutputView target) throws IOException {
if (record == null) {
throw new IllegalArgumentException("The record must not be null.");
}
final int len = record.length;
target.writeInt(len);
target.write(record);
}
@Override
public byte[] deserialize(DataInputView source) throws IOException {
final int len = source.readInt();
byte[] result = new byte[len];
source.readFully(result);
return result;
}
@Override
public byte[] deserialize(byte[] reuse, DataInputView source) throws IOException {
return deserialize(source);
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
final int len = source.readInt();
target.writeInt(len);
target.write(source, len);
}
@Override
public TypeSerializer<byte[]> duplicate() {
return new RemoteValueSerializer(type);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || RemoteValueSerializer.class != o.getClass()) return false;
RemoteValueSerializer that = (RemoteValueSerializer) o;
return Objects.equals(type, that.type);
}
@Override
public int hashCode() {
return Objects.hash(type);
}
@Override
public TypeSerializerSnapshot<byte[]> snapshotConfiguration() {
return new RemoteValueSerializerSnapshot(type);
}
}
| 6,116 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/remote/RemoteValueTypeMismatchException.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.flink.core.types.remote;
import org.apache.flink.statefun.sdk.TypeName;
public final class RemoteValueTypeMismatchException extends IllegalStateException {
private static final long serialVersionUID = 1L;
public RemoteValueTypeMismatchException(TypeName previousValueType, TypeName newValueType) {
super(String.format("Previous type was: %s, new type is: %s", previousValueType, newValueType));
}
}
| 6,117 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/types/remote/RemoteValueTypeInfo.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.flink.core.types.remote;
import java.util.Objects;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.statefun.sdk.TypeName;
public final class RemoteValueTypeInfo extends TypeInformation<byte[]> {
private static final long serialVersionUID = 1L;
private final TypeName type;
public RemoteValueTypeInfo(TypeName type) {
this.type = Objects.requireNonNull(type);
}
@Override
public TypeSerializer<byte[]> createSerializer(ExecutionConfig executionConfig) {
return new RemoteValueSerializer(type);
}
@Override
public boolean isBasicType() {
return false;
}
@Override
public boolean isTupleType() {
return false;
}
@Override
public int getArity() {
return 0;
}
@Override
public int getTotalFields() {
return 0;
}
@Override
public Class<byte[]> getTypeClass() {
return byte[].class;
}
@Override
public boolean isKeyType() {
return false;
}
@Override
public String toString() {
return "RemoteValueTypeInfo{" + "type=" + type + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RemoteValueTypeInfo that = (RemoteValueTypeInfo) o;
return type.equals(that.type);
}
@Override
public int hashCode() {
return Objects.hashCode(type);
}
@Override
public boolean canEqual(Object obj) {
return obj instanceof RemoteValueTypeInfo;
}
}
| 6,118 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/di/Label.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.flink.core.di;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Label {
String value();
}
| 6,119 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/di/Inject.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.flink.core.di;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
public @interface Inject {}
| 6,120 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/di/Lazy.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.flink.core.di;
import java.util.Objects;
import javax.annotation.Nullable;
@SuppressWarnings({"unchecked", "unused", "WeakerAccess"})
public final class Lazy<T> {
private final Class<T> type;
private final String label;
private ObjectContainer container;
@Nullable private T instance;
public Lazy(Class<T> type) {
this(type, null);
}
public Lazy(Class<T> type, String label) {
this.type = type;
this.label = label;
}
public Lazy(T instance) {
this((Class<T>) instance.getClass(), null);
this.instance = instance;
}
Lazy<T> withContainer(ObjectContainer container) {
this.container = Objects.requireNonNull(container);
return this;
}
public T get() {
@Nullable T instance = this.instance;
if (instance == null) {
instance = container.get(type, label);
this.instance = instance;
}
return instance;
}
}
| 6,121 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/di/ObjectContainer.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.flink.core.di;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.apache.flink.annotation.Internal;
/** Minimal dependency injection. */
@Internal
public class ObjectContainer {
private final Map<Key, Supplier<Object>> factories = new HashMap<>();
private final Map<Key, Object> instances = new HashMap<>();
public <T> void add(T singleton) {
Class<?> type = singleton.getClass();
factories.put(new Key(type), () -> singleton);
}
public <T> void add(Class<T> type) {
factories.put(new Key(type), () -> createReflectively(type));
}
public <T> void add(String label, Class<? super T> type, T singleton) {
factories.put(new Key(type, label), () -> singleton);
}
public <T> void add(String label, Class<? super T> type, Class<?> actual) {
factories.put(new Key(type, label), () -> createReflectively(actual));
}
public <T, ET> void addAlias(
String newLabel,
Class<? super T> newType,
String existingLabel,
Class<? super ET> existingType) {
factories.put(new Key(newType, newLabel), () -> get(existingType, existingLabel));
}
public <T> void add(String label, Lazy<T> lazyValue) {
factories.put(new Key(Lazy.class, label), () -> lazyValue.withContainer(this));
}
public <T> T get(Class<T> type) {
return get(type, null);
}
public <T> T get(Class<T> type, String label) {
Key key = new Key(type, label);
return getOrCreateInstance(key);
}
@SuppressWarnings("unchecked")
private <T> T getOrCreateInstance(Key key) {
@Nullable Object instance = instances.get(key);
if (instance == null) {
instances.put(key, instance = create(key));
}
return (T) instance;
}
private Object create(Key key) {
Supplier<Object> factory = factories.get(key);
if (factory == null) {
throw new IllegalArgumentException("was not able to find a factory for " + key);
}
return factory.get();
}
private Object createReflectively(Class<?> type) {
Constructor<?> constructor = findConstructorForInjection(type);
Class<?>[] dependencies = constructor.getParameterTypes();
Annotation[][] annotations = constructor.getParameterAnnotations();
Object[] resolvedDependencies = new Object[dependencies.length];
int i = 0;
for (Class<?> dependency : dependencies) {
@Nullable String label = findLabel(annotations[i]);
Key key = new Key(dependency, label);
resolvedDependencies[i] = getOrCreateInstance(key);
i++;
}
try {
constructor.setAccessible(true);
return constructor.newInstance(resolvedDependencies);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Nullable
private static String findLabel(Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType() == Label.class) {
return ((Label) annotation).value();
}
}
return null;
}
private static Constructor<?> findConstructorForInjection(Class<?> type) {
Constructor<?>[] constructors = type.getDeclaredConstructors();
Constructor<?> defaultCont = null;
for (Constructor<?> constructor : constructors) {
Annotation annotation = constructor.getAnnotation(Inject.class);
if (annotation != null) {
return constructor;
}
if (constructor.getParameterCount() == 0) {
defaultCont = constructor;
}
}
if (defaultCont != null) {
return defaultCont;
}
throw new RuntimeException("not injectable type " + type);
}
private static final class Key {
final Class<?> type;
@Nullable final String label;
Key(Class<?> type, @Nullable String label) {
this.type = type;
this.label = label;
}
Key(Class<?> type) {
this(type, null);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key key = (Key) o;
return Objects.equals(type, key.type) && Objects.equals(label, key.label);
}
@Override
public int hashCode() {
return Objects.hash(type, label);
}
@Override
public String toString() {
return "Key{" + "type=" + type + ", label='" + label + '\'' + '}';
}
}
}
| 6,122 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/UnboundedFeedbackLoggerFactory.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.flink.core.logger;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.statefun.flink.core.di.Inject;
import org.apache.flink.statefun.flink.core.di.Label;
public final class UnboundedFeedbackLoggerFactory<T> {
private final Supplier<KeyGroupStream<T>> supplier;
private final ToIntFunction<T> keyGroupAssigner;
private final CheckpointedStreamOperations checkpointedStreamOperations;
private final TypeSerializer<T> serializer;
@Inject
public UnboundedFeedbackLoggerFactory(
@Label("key-group-supplier") Supplier<KeyGroupStream<T>> supplier,
@Label("key-group-assigner") ToIntFunction<T> keyGroupAssigner,
@Label("checkpoint-stream-ops") CheckpointedStreamOperations ops,
@Label("envelope-serializer") TypeSerializer<T> serializer) {
this.supplier = Objects.requireNonNull(supplier);
this.keyGroupAssigner = Objects.requireNonNull(keyGroupAssigner);
this.serializer = Objects.requireNonNull(serializer);
this.checkpointedStreamOperations = Objects.requireNonNull(ops);
}
public UnboundedFeedbackLogger<T> create() {
return new UnboundedFeedbackLogger<>(
supplier, keyGroupAssigner, checkpointedStreamOperations, serializer);
}
}
| 6,123 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/MemorySegmentPool.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.flink.core.logger;
import java.util.ArrayDeque;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.core.memory.MemorySegmentSource;
@NotThreadSafe
final class MemorySegmentPool implements MemorySegmentSource {
static final int PAGE_SIZE = 64 * 1024;
private final ArrayDeque<MemorySegment> pool;
private final long inMemoryBufferSize;
private long totalAllocatedMemory;
MemorySegmentPool(long inMemoryBufferSize) {
this.pool = new ArrayDeque<>();
this.inMemoryBufferSize = inMemoryBufferSize;
}
@Nullable
@Override
public MemorySegment nextSegment() {
MemorySegment segment = pool.pollFirst();
if (segment != null) {
return segment;
}
//
// no segments in the pool, try to allocate one.
//
if (!hasRemainingCapacity()) {
return null;
}
segment = MemorySegmentFactory.allocateUnpooledSegment(PAGE_SIZE);
totalAllocatedMemory += PAGE_SIZE;
return segment;
}
void release(MemorySegment segment) {
if (totalAllocatedMemory > inMemoryBufferSize) {
//
// we previously overdraft.
//
segment.free();
totalAllocatedMemory -= PAGE_SIZE;
return;
}
pool.add(segment);
}
int getSegmentSize() {
return PAGE_SIZE;
}
void ensureAtLeastOneSegmentPresent() {
if (!pool.isEmpty()) {
//
// the next allocation would succeeded because the pool is not empty
//
return;
}
if (hasRemainingCapacity()) {
//
// the next allocation would succeeded because the total allocated size is within the allowed
// range
//
return;
}
//
// we overdraft momentarily.
//
MemorySegment segment = MemorySegmentFactory.allocateUnpooledSegment(PAGE_SIZE);
totalAllocatedMemory += PAGE_SIZE;
pool.add(segment);
}
private boolean hasRemainingCapacity() {
return totalAllocatedMemory + PAGE_SIZE <= inMemoryBufferSize;
}
}
| 6,124 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/KeyGroupStreamFactory.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.flink.core.logger;
import java.util.function.Supplier;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.statefun.flink.core.di.Inject;
import org.apache.flink.statefun.flink.core.di.Label;
public final class KeyGroupStreamFactory<T> implements Supplier<KeyGroupStream<T>> {
private final IOManager ioManager;
private final MemorySegmentPool memorySegmentPool;
private final TypeSerializer<T> serializer;
@Inject
KeyGroupStreamFactory(
@Label("io-manager") IOManager ioManager,
@Label("in-memory-max-buffer-size") long inMemoryBufferSize,
@Label("envelope-serializer") TypeSerializer<T> serializer) {
this.ioManager = ioManager;
this.serializer = serializer;
this.memorySegmentPool = new MemorySegmentPool(inMemoryBufferSize);
}
@Override
public KeyGroupStream<T> get() {
return new KeyGroupStream<>(serializer, ioManager, memorySegmentPool);
}
}
| 6,125 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/Loggers.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.flink.core.logger;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.state.KeyGroupRangeAssignment;
import org.apache.flink.runtime.state.KeyedStateCheckpointOutputStream;
import org.apache.flink.statefun.flink.core.di.ObjectContainer;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.ResourceGuard.Lease;
public final class Loggers {
private Loggers() {}
public static UnboundedFeedbackLoggerFactory<?> unboundedSpillableLoggerFactory(
IOManager ioManager,
int maxParallelism,
long inMemoryMaxBufferSize,
TypeSerializer<?> serializer,
Function<?, ?> keySelector) {
ObjectContainer container =
unboundedSpillableLoggerContainer(
ioManager, maxParallelism, inMemoryMaxBufferSize, serializer, keySelector);
return container.get(UnboundedFeedbackLoggerFactory.class);
}
/** Wires the required dependencies to construct an {@link UnboundedFeedbackLogger}. */
@VisibleForTesting
static ObjectContainer unboundedSpillableLoggerContainer(
IOManager ioManager,
int maxParallelism,
long inMemoryMaxBufferSize,
TypeSerializer<?> serializer,
Function<?, ?> keySelector) {
ObjectContainer container = new ObjectContainer();
container.add("max-parallelism", int.class, maxParallelism);
container.add("in-memory-max-buffer-size", long.class, inMemoryMaxBufferSize);
container.add("io-manager", IOManager.class, ioManager);
container.add("key-group-supplier", Supplier.class, KeyGroupStreamFactory.class);
container.add(
"key-group-assigner", ToIntFunction.class, new KeyAssigner<>(keySelector, maxParallelism));
container.add("envelope-serializer", TypeSerializer.class, serializer);
container.add(
"checkpoint-stream-ops",
CheckpointedStreamOperations.class,
KeyedStateCheckpointOutputStreamOps.INSTANCE);
container.add(UnboundedFeedbackLoggerFactory.class);
return container;
}
private enum KeyedStateCheckpointOutputStreamOps implements CheckpointedStreamOperations {
INSTANCE;
@Override
public void requireKeyedStateCheckpointed(OutputStream stream) {
if (stream instanceof KeyedStateCheckpointOutputStream) {
return;
}
throw new IllegalStateException("Not a KeyedStateCheckpointOutputStream");
}
@Override
public Iterable<Integer> keyGroupList(OutputStream stream) {
return cast(stream).getKeyGroupList();
}
@Override
public void startNewKeyGroup(OutputStream stream, int keyGroup) throws IOException {
cast(stream).startNewKeyGroup(keyGroup);
}
@Override
@SuppressWarnings("resource")
public Closeable acquireLease(OutputStream stream) {
Preconditions.checkState(stream instanceof KeyedStateCheckpointOutputStream);
try {
Lease lease = cast(stream).acquireLease();
return lease::close;
} catch (IOException e) {
throw new IllegalStateException("Unable to obtain a lease for the input stream.", e);
}
}
private static KeyedStateCheckpointOutputStream cast(OutputStream stream) {
Preconditions.checkState(stream instanceof KeyedStateCheckpointOutputStream);
return (KeyedStateCheckpointOutputStream) stream;
}
}
private static final class KeyAssigner<T> implements ToIntFunction<T> {
private final Function<T, ?> keySelector;
private final int maxParallelism;
private KeyAssigner(Function<T, ?> keySelector, int maxParallelism) {
this.keySelector = Objects.requireNonNull(keySelector);
this.maxParallelism = maxParallelism;
}
@Override
public int applyAsInt(T value) {
Object key = keySelector.apply(value);
return KeyGroupRangeAssignment.assignToKeyGroup(key, maxParallelism);
}
}
}
| 6,126 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/UnboundedFeedbackLogger.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.flink.core.logger;
import static org.apache.flink.util.Preconditions.checkState;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import org.apache.flink.statefun.flink.core.feedback.FeedbackConsumer;
import org.apache.flink.util.IOUtils;
public final class UnboundedFeedbackLogger<T> implements FeedbackLogger<T> {
private final Supplier<KeyGroupStream<T>> supplier;
private final ToIntFunction<T> keyGroupAssigner;
private final Map<Integer, KeyGroupStream<T>> keyGroupStreams;
private final CheckpointedStreamOperations checkpointedStreamOperations;
@Nullable private OutputStream keyedStateOutputStream;
private TypeSerializer<T> serializer;
private Closeable snapshotLease;
public UnboundedFeedbackLogger(
Supplier<KeyGroupStream<T>> supplier,
ToIntFunction<T> keyGroupAssigner,
CheckpointedStreamOperations ops,
TypeSerializer<T> serializer) {
this.supplier = Objects.requireNonNull(supplier);
this.keyGroupAssigner = Objects.requireNonNull(keyGroupAssigner);
this.serializer = Objects.requireNonNull(serializer);
this.keyGroupStreams = new TreeMap<>();
this.checkpointedStreamOperations = Objects.requireNonNull(ops);
}
@Override
public void startLogging(OutputStream keyedStateCheckpointOutputStream) {
this.checkpointedStreamOperations.requireKeyedStateCheckpointed(
keyedStateCheckpointOutputStream);
this.keyedStateOutputStream = Objects.requireNonNull(keyedStateCheckpointOutputStream);
this.snapshotLease =
checkpointedStreamOperations.acquireLease(keyedStateCheckpointOutputStream);
}
@Override
public void append(T message) {
if (keyedStateOutputStream == null) {
//
// we are not currently logging.
//
return;
}
KeyGroupStream<T> keyGroup = keyGroupStreamFor(message);
keyGroup.append(message);
}
@Override
public void commit() {
try {
flushToKeyedStateOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
keyGroupStreams.clear();
IOUtils.closeQuietly(snapshotLease);
snapshotLease = null;
keyedStateOutputStream = null;
}
}
private void flushToKeyedStateOutputStream() throws IOException {
checkState(keyedStateOutputStream != null, "Trying to flush envelopes not in a logging state");
final DataOutputView target = new DataOutputViewStreamWrapper(keyedStateOutputStream);
final Iterable<Integer> assignedKeyGroupIds =
checkpointedStreamOperations.keyGroupList(keyedStateOutputStream);
// the underlying checkpointed raw stream, requires that all key groups assigned
// to this operator must be written to the underlying stream.
for (Integer keyGroupId : assignedKeyGroupIds) {
checkpointedStreamOperations.startNewKeyGroup(keyedStateOutputStream, keyGroupId);
Header.writeHeader(target);
@Nullable KeyGroupStream<T> stream = keyGroupStreams.get(keyGroupId);
if (stream == null) {
KeyGroupStream.writeEmptyTo(target);
} else {
stream.writeTo(target);
}
}
}
public void replyLoggedEnvelops(InputStream rawKeyedStateInputs, FeedbackConsumer<T> consumer)
throws Exception {
DataInputView in =
new DataInputViewStreamWrapper(Header.skipHeaderSilently(rawKeyedStateInputs));
KeyGroupStream.readFrom(in, serializer, consumer);
}
@Nonnull
private KeyGroupStream<T> keyGroupStreamFor(T target) {
final int keyGroupId = keyGroupAssigner.applyAsInt(target);
KeyGroupStream<T> keyGroup = keyGroupStreams.get(keyGroupId);
if (keyGroup == null) {
keyGroupStreams.put(keyGroupId, keyGroup = supplier.get());
}
return keyGroup;
}
@Override
public void close() {
IOUtils.closeQuietly(snapshotLease);
snapshotLease = null;
keyedStateOutputStream = null;
keyGroupStreams.clear();
}
@VisibleForTesting
static final class Header {
private static final int STATEFUN_VERSION = 0;
private static final int STATEFUN_MAGIC = 710818519;
private static final byte[] HEADER_BYTES = headerBytes();
public static void writeHeader(DataOutputView target) throws IOException {
target.write(HEADER_BYTES);
}
public static InputStream skipHeaderSilently(InputStream rawKeyedInput) throws IOException {
byte[] header = new byte[HEADER_BYTES.length];
PushbackInputStream input = new PushbackInputStream(rawKeyedInput, header.length);
int bytesRead = InputStreamUtils.tryReadFully(input, header);
if (bytesRead > 0 && !Arrays.equals(header, HEADER_BYTES)) {
input.unread(header, 0, bytesRead);
}
return input;
}
private static byte[] headerBytes() {
DataOutputSerializer out = new DataOutputSerializer(8);
try {
out.writeInt(STATEFUN_VERSION);
out.writeInt(STATEFUN_MAGIC);
} catch (IOException e) {
throw new IllegalStateException("Unable to compute the header bytes");
}
return out.getCopyOfBuffer();
}
}
}
| 6,127 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/KeyGroupStream.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.flink.core.logger;
import java.io.IOException;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.SpillingBuffer;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.statefun.flink.core.feedback.FeedbackConsumer;
final class KeyGroupStream<T> {
private final TypeSerializer<T> serializer;
private final SpillingBuffer target;
private final MemorySegmentPool memoryPool;
private final DataOutputSerializer output = new DataOutputSerializer(256);
private long totalSize;
private int elementCount;
KeyGroupStream(
TypeSerializer<T> serializer, IOManager ioManager, MemorySegmentPool memorySegmentPool) {
this.serializer = Objects.requireNonNull(serializer);
this.memoryPool = Objects.requireNonNull(memorySegmentPool);
// SpillingBuffer requires at least 1 memory segment to be present at construction, otherwise it
// fails
// so we
memorySegmentPool.ensureAtLeastOneSegmentPresent();
this.target =
new SpillingBuffer(ioManager, memorySegmentPool, memorySegmentPool.getSegmentSize());
}
static <T> void readFrom(
DataInputView source, TypeSerializer<T> serializer, FeedbackConsumer<T> consumer)
throws Exception {
final int elementCount = source.readInt();
for (int i = 0; i < elementCount; i++) {
T envelope = serializer.deserialize(source);
consumer.processFeedback(envelope);
}
}
private static void copy(@Nonnull DataInputView source, @Nonnull DataOutputView target, long size)
throws IOException {
while (size > 0) {
final int len = (int) Math.min(4 * 1024, size); // read no more then 4k bytes at a time
target.write(source, len);
size -= len;
}
}
void append(T envelope) {
elementCount++;
try {
output.clear();
serializer.serialize(envelope, output);
totalSize += output.length();
target.write(output.getSharedBuffer(), 0, output.length());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
void writeTo(DataOutputView target) throws IOException {
target.writeInt(elementCount);
copy(this.target.flip(), target, totalSize);
for (MemorySegment segment : this.target.close()) {
memoryPool.release(segment);
}
}
public static void writeEmptyTo(DataOutputView target) throws IOException {
target.writeInt(0);
}
}
| 6,128 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/FeedbackLogger.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.flink.core.logger;
import java.io.OutputStream;
public interface FeedbackLogger<T> extends AutoCloseable {
/** Start logging messages into the supplied output stream. */
void startLogging(OutputStream keyedStateCheckpointOutputStream);
/** Append a message to the currently logging logger. */
void append(T message);
/** Commit the currently logging logger. */
void commit();
}
| 6,129 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/InputStreamUtils.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.flink.core.logger;
import java.io.IOException;
import java.io.InputStream;
import org.apache.flink.util.Preconditions;
final class InputStreamUtils {
private InputStreamUtils() {}
/**
* Attempt to fill the provided read buffer with bytes from the given {@link InputStream}, and
* returns the total number of bytes read into the read buffer.
*
* <p>This method repeatedly reads the {@link InputStream} until either:
*
* <ul>
* <li>the read buffer is filled, or
* <li>EOF of the input stream is reached.
* </ul>
*
* <p>TODO we can remove this once we upgrade to Flink 1.12.x, since {@link
* org.apache.flink.util.IOUtils} would have a new utility for exactly this.
*
* @param in the input stream to read from
* @param readBuffer the read buffer to fill
* @return the total number of bytes read into the read buffer
*/
static int tryReadFully(final InputStream in, final byte[] readBuffer) throws IOException {
Preconditions.checkState(readBuffer.length > 0, "read buffer size must be larger than 0.");
int totalRead = 0;
while (totalRead != readBuffer.length) {
int read = in.read(readBuffer, totalRead, readBuffer.length - totalRead);
if (read == -1) {
break;
}
totalRead += read;
}
return totalRead;
}
}
| 6,130 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/logger/CheckpointedStreamOperations.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.flink.core.logger;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
public interface CheckpointedStreamOperations {
void requireKeyedStateCheckpointed(OutputStream keyedStateCheckpointOutputStream);
Iterable<Integer> keyGroupList(OutputStream stream);
void startNewKeyGroup(OutputStream stream, int keyGroup) throws IOException;
Closeable acquireLease(OutputStream keyedStateCheckpointOutputStream);
}
| 6,131 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/cache/SingleThreadedLruCache.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.flink.core.cache;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
@NotThreadSafe
public final class SingleThreadedLruCache<K, V> {
private final Cache<K, V> cache;
public SingleThreadedLruCache(int maxCapacity) {
this.cache = new Cache<>(maxCapacity, maxCapacity);
}
public void put(K key, V value) {
cache.put(key, value);
}
@Nullable
public V get(K key) {
return cache.get(key);
}
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
return cache.computeIfAbsent(key, mappingFunction);
}
private static final class Cache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1;
private final int maxCapacity;
private Cache(int initialCapacity, int maxCapacity) {
super(initialCapacity, 0.75f, true);
this.maxCapacity = maxCapacity;
}
@Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return size() > maxCapacity;
}
}
}
| 6,132 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/CheckpointToMessage.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.flink.core.translation;
import java.io.Serializable;
import java.util.function.LongFunction;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.flink.core.message.MessageFactory;
import org.apache.flink.statefun.flink.core.message.MessageFactoryKey;
final class CheckpointToMessage implements Serializable, LongFunction<Message> {
private static final long serialVersionUID = 2L;
private final MessageFactoryKey messageFactoryKey;
private transient MessageFactory factory;
CheckpointToMessage(MessageFactoryKey messageFactoryKey) {
this.messageFactoryKey = messageFactoryKey;
}
@Override
public Message apply(long checkpointId) {
return factory().from(checkpointId);
}
private MessageFactory factory() {
if (factory == null) {
factory = MessageFactory.forKey(messageFactoryKey);
}
return factory;
}
}
| 6,133 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/EmbeddedTranslator.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.flink.core.translation;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverseProvider;
import org.apache.flink.statefun.flink.core.feedback.FeedbackKey;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.flink.core.message.RoutableMessage;
import org.apache.flink.statefun.flink.core.types.StaticallyRegisteredTypes;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.streaming.api.datastream.DataStream;
public class EmbeddedTranslator {
private final StatefulFunctionsConfig configuration;
private final FeedbackKey<Message> feedbackKey;
public EmbeddedTranslator(StatefulFunctionsConfig config, FeedbackKey<Message> feedbackKey) {
this.configuration = config;
this.feedbackKey = feedbackKey;
}
public <T extends StatefulFunctionProvider & Serializable>
Map<EgressIdentifier<?>, DataStream<?>> translate(
List<DataStream<RoutableMessage>> ingresses,
Iterable<EgressIdentifier<?>> egressesIds,
Map<FunctionType, T> functions) {
configuration.setProvider(new EmbeddedUniverseProvider<>(functions));
StaticallyRegisteredTypes types = new StaticallyRegisteredTypes(configuration.getFactoryKey());
Sources sources = Sources.create(types, ingresses);
Sinks sinks = Sinks.create(types, egressesIds);
StatefulFunctionTranslator translator =
new StatefulFunctionTranslator(feedbackKey, configuration);
return translator.translate(sources, sinks);
}
private static class EmbeddedUniverseProvider<T extends StatefulFunctionProvider & Serializable>
implements StatefulFunctionsUniverseProvider {
private static final long serialVersionUID = 1;
private Map<FunctionType, T> functions;
public EmbeddedUniverseProvider(Map<FunctionType, T> functions) {
this.functions = Objects.requireNonNull(functions);
}
@Override
public StatefulFunctionsUniverse get(
ClassLoader classLoader, StatefulFunctionsConfig configuration) {
StatefulFunctionsUniverse u = new StatefulFunctionsUniverse(configuration.getFactoryKey());
functions.forEach(u::bindFunctionProvider);
return u;
}
}
}
| 6,134 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/StatefulFunctionTranslator.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.flink.core.translation;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.function.LongFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsJobConstants;
import org.apache.flink.statefun.flink.core.common.KeyBy;
import org.apache.flink.statefun.flink.core.common.SerializableFunction;
import org.apache.flink.statefun.flink.core.feedback.FeedbackKey;
import org.apache.flink.statefun.flink.core.feedback.FeedbackSinkOperator;
import org.apache.flink.statefun.flink.core.feedback.FeedbackUnionOperatorFactory;
import org.apache.flink.statefun.flink.core.functions.FunctionGroupDispatchFactory;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.flink.core.message.MessageKeySelector;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamUtils;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.util.OutputTag;
final class StatefulFunctionTranslator {
private final FeedbackKey<Message> feedbackKey;
private final StatefulFunctionsConfig configuration;
StatefulFunctionTranslator(
FeedbackKey<Message> feedbackKey, StatefulFunctionsConfig configuration) {
this.feedbackKey = Objects.requireNonNull(feedbackKey);
this.configuration = Objects.requireNonNull(configuration);
}
Map<EgressIdentifier<?>, DataStream<?>> translate(Sources sources, Sinks sinks) {
SingleOutputStreamOperator<Message> feedbackUnionOperator =
feedbackUnionOperator(sources.unionStream());
SingleOutputStreamOperator<Message> functionOutputStream =
functionOperator(feedbackUnionOperator, sinks.sideOutputTags());
SingleOutputStreamOperator<Void> writeBackOut = feedbackOperator(functionOutputStream);
coLocate(feedbackUnionOperator, functionOutputStream, writeBackOut);
return sinks.sideOutputStreams(functionOutputStream);
}
private SingleOutputStreamOperator<Message> feedbackUnionOperator(DataStream<Message> input) {
TypeInformation<Message> typeInfo = input.getType();
FeedbackUnionOperatorFactory<Message> factory =
new FeedbackUnionOperatorFactory<>(
configuration, feedbackKey, new IsCheckpointBarrier(), new FeedbackKeySelector());
return input
.keyBy(new MessageKeySelector())
.transform(StatefulFunctionsJobConstants.FEEDBACK_UNION_OPERATOR_NAME, typeInfo, factory)
.uid(StatefulFunctionsJobConstants.FEEDBACK_UNION_OPERATOR_UID);
}
private SingleOutputStreamOperator<Message> functionOperator(
DataStream<Message> input, Map<EgressIdentifier<?>, OutputTag<Object>> sideOutputs) {
TypeInformation<Message> typeInfo = input.getType();
FunctionGroupDispatchFactory operatorFactory =
new FunctionGroupDispatchFactory(configuration, sideOutputs);
return DataStreamUtils.reinterpretAsKeyedStream(input, new MessageKeySelector())
.transform(StatefulFunctionsJobConstants.FUNCTION_OPERATOR_NAME, typeInfo, operatorFactory)
.uid(StatefulFunctionsJobConstants.FUNCTION_OPERATOR_UID);
}
private SingleOutputStreamOperator<Void> feedbackOperator(
SingleOutputStreamOperator<Message> functionOut) {
LongFunction<Message> toMessage = new CheckpointToMessage(configuration.getFactoryKey());
FeedbackSinkOperator<Message> sinkOperator = new FeedbackSinkOperator<>(feedbackKey, toMessage);
return functionOut
.keyBy(new MessageKeySelector())
.transform(
StatefulFunctionsJobConstants.WRITE_BACK_OPERATOR_NAME,
TypeInformation.of(Void.class),
sinkOperator)
.uid(StatefulFunctionsJobConstants.WRITE_BACK_OPERATOR_UID);
}
private void coLocate(DataStream<?> a, DataStream<?> b, DataStream<?> c) {
String stringKey = feedbackKey.asColocationKey();
a.getTransformation().setCoLocationGroupKey(stringKey);
b.getTransformation().setCoLocationGroupKey(stringKey);
c.getTransformation().setCoLocationGroupKey(stringKey);
a.getTransformation().setParallelism(b.getParallelism());
c.getTransformation().setParallelism(b.getParallelism());
}
private static final class IsCheckpointBarrier
implements SerializableFunction<Message, OptionalLong> {
private static final long serialVersionUID = 1;
@Override
public OptionalLong apply(Message message) {
return message.isBarrierMessage();
}
}
private static final class FeedbackKeySelector implements SerializableFunction<Message, String> {
private static final long serialVersionUID = 1;
@Override
public String apply(Message message) {
return KeyBy.apply(message.target());
}
}
}
| 6,135 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/FlinkUniverse.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.flink.core.translation;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.feedback.FeedbackKey;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
public final class FlinkUniverse {
private final StatefulFunctionsUniverse universe;
private final StatefulFunctionsConfig configuration;
private final FeedbackKey<Message> feedbackKey;
public FlinkUniverse(
FeedbackKey<Message> feedbackKey,
StatefulFunctionsConfig configuration,
StatefulFunctionsUniverse universe) {
this.feedbackKey = Objects.requireNonNull(feedbackKey);
this.universe = Objects.requireNonNull(universe);
this.configuration = Objects.requireNonNull(configuration);
}
public void configure(StreamExecutionEnvironment env) {
Sources sources = Sources.create(env, universe, configuration);
Sinks sinks = Sinks.create(universe);
StatefulFunctionTranslator translator =
new StatefulFunctionTranslator(feedbackKey, configuration);
Map<EgressIdentifier<?>, DataStream<?>> sideOutputs = translator.translate(sources, sinks);
sinks.consumeFrom(sideOutputs);
}
}
| 6,136 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/EgressToSinkTranslator.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.flink.core.translation;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.common.Maps;
import org.apache.flink.statefun.flink.io.spi.SinkProvider;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.io.EgressSpec;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
final class EgressToSinkTranslator {
private final StatefulFunctionsUniverse universe;
EgressToSinkTranslator(StatefulFunctionsUniverse universe) {
this.universe = Objects.requireNonNull(universe);
}
Map<EgressIdentifier<?>, DecoratedSink> translate() {
return Maps.transformValues(universe.egress(), this::sinkFromSpec);
}
private DecoratedSink sinkFromSpec(EgressIdentifier<?> key, EgressSpec<?> spec) {
SinkProvider provider = universe.sinks().get(spec.type());
if (provider == null) {
throw new IllegalStateException(
"Unable to find a sink translation for egress of type "
+ spec.type()
+ ", which is bound for key "
+ key);
}
SinkFunction<?> sink = provider.forSpec(spec);
if (sink == null) {
throw new NullPointerException(
"A sink provider for type " + spec.type() + ", has produced a NULL sink.");
}
return DecoratedSink.of(spec, sink);
}
}
| 6,137 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/IngressToSourceFunctionTranslator.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.flink.core.translation;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.common.Maps;
import org.apache.flink.statefun.flink.io.spi.SourceProvider;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.IngressSpec;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
final class IngressToSourceFunctionTranslator {
private final StatefulFunctionsUniverse universe;
IngressToSourceFunctionTranslator(StatefulFunctionsUniverse universe) {
this.universe = Objects.requireNonNull(universe);
}
Map<IngressIdentifier<?>, DecoratedSource> translate() {
return Maps.transformValues(universe.ingress(), this::sourceFromSpec);
}
private DecoratedSource sourceFromSpec(IngressIdentifier<?> key, IngressSpec<?> spec) {
SourceProvider provider = universe.sources().get(spec.type());
if (provider == null) {
throw new IllegalStateException(
"Unable to find a source translation for ingress of type "
+ spec.type()
+ ", which is bound for key "
+ key);
}
SourceFunction<?> source = provider.forSpec(spec);
if (source == null) {
throw new NullPointerException(
"A source provider for type " + spec.type() + ", has produced a NULL source.");
}
return DecoratedSource.of(spec, source);
}
}
| 6,138 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/DecoratedSink.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.flink.core.translation;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.io.EgressSpec;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
final class DecoratedSink {
final String name;
final String uid;
final SinkFunction<?> sink;
private DecoratedSink(String name, String uid, SinkFunction<?> sink) {
this.name = name;
this.uid = uid;
this.sink = sink;
}
public static DecoratedSink of(EgressSpec<?> spec, SinkFunction<?> sink) {
EgressIdentifier<?> identifier = spec.id();
String name = String.format("%s-%s-egress", identifier.namespace(), identifier.name());
String uid =
String.format(
"%s-%s-%s-%s-egress",
spec.type().namespace(), spec.type().type(), identifier.namespace(), identifier.name());
return new DecoratedSink(name, uid, sink);
}
}
| 6,139 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/Sinks.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.flink.core.translation;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.common.Maps;
import org.apache.flink.statefun.flink.core.types.StaticallyRegisteredTypes;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.util.OutputTag;
final class Sinks {
private final Map<EgressIdentifier<?>, OutputTag<Object>> sideOutputs;
private final Map<EgressIdentifier<?>, DecoratedSink> sinks;
private Sinks(
Map<EgressIdentifier<?>, OutputTag<Object>> sideOutputs,
Map<EgressIdentifier<?>, DecoratedSink> sinks) {
this.sideOutputs = Objects.requireNonNull(sideOutputs);
this.sinks = Objects.requireNonNull(sinks);
}
static Sinks create(StatefulFunctionsUniverse universe) {
return new Sinks(sideOutputs(universe), sinkFunctions(universe));
}
static Sinks create(
StaticallyRegisteredTypes types, Iterable<EgressIdentifier<?>> egressIdentifiers) {
SideOutputTranslator translator = new SideOutputTranslator(types, egressIdentifiers);
return new Sinks(translator.translate(), Collections.emptyMap());
}
private static Map<EgressIdentifier<?>, DecoratedSink> sinkFunctions(
StatefulFunctionsUniverse universe) {
EgressToSinkTranslator egressTranslator = new EgressToSinkTranslator(universe);
return egressTranslator.translate();
}
private static Map<EgressIdentifier<?>, OutputTag<Object>> sideOutputs(
StatefulFunctionsUniverse universe) {
SideOutputTranslator sideOutputTranslator = new SideOutputTranslator(universe);
return sideOutputTranslator.translate();
}
Map<EgressIdentifier<?>, OutputTag<Object>> sideOutputTags() {
return sideOutputs;
}
Map<EgressIdentifier<?>, DataStream<?>> sideOutputStreams(
SingleOutputStreamOperator<?> mainOutput) {
return Maps.transformValues(sideOutputs, (id, tag) -> mainOutput.getSideOutput(tag));
}
void consumeFrom(Map<EgressIdentifier<?>, DataStream<?>> sideOutputs) {
sideOutputs.forEach(
(egressIdentifier, rawSideOutputStream) -> {
DecoratedSink decoratedSink = sinks.get(egressIdentifier);
@SuppressWarnings("unchecked")
SinkFunction<Object> sink = (SinkFunction<Object>) decoratedSink.sink;
@SuppressWarnings("unchecked")
DataStream<Object> sideOutputStream = (DataStream<Object>) rawSideOutputStream;
DataStreamSink<Object> streamSink = sideOutputStream.addSink(sink);
streamSink.name(decoratedSink.name);
streamSink.uid(decoratedSink.uid);
});
}
}
| 6,140 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/IngressRouterOperator.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.flink.core.translation;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverses;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.flink.core.message.MessageFactory;
import org.apache.flink.statefun.flink.core.message.MessageFactoryKey;
import org.apache.flink.statefun.flink.core.metrics.FlinkUserMetrics;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.Router;
import org.apache.flink.statefun.sdk.io.Router.Downstream;
import org.apache.flink.statefun.sdk.metrics.Metrics;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.ChainingStrategy;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.Output;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class IngressRouterOperator<T> extends AbstractStreamOperator<Message>
implements OneInputStreamOperator<T, Message> {
private static final Logger LOG = LoggerFactory.getLogger(IngressRouterOperator.class);
private static final long serialVersionUID = 1;
private final StatefulFunctionsConfig configuration;
private final IngressIdentifier<T> id;
private transient List<Router<T>> routers;
private transient DownstreamCollector<T> downstream;
IngressRouterOperator(StatefulFunctionsConfig configuration, IngressIdentifier<T> id) {
this.configuration = configuration;
this.id = Objects.requireNonNull(id);
this.chainingStrategy = ChainingStrategy.ALWAYS;
}
@Override
public void open() throws Exception {
super.open();
StatefulFunctionsUniverse universe =
StatefulFunctionsUniverses.get(
Thread.currentThread().getContextClassLoader(), configuration);
LOG.info("Using message factory key " + universe.messageFactoryKey());
MetricGroup routersMetricGroup =
getMetricGroup().addGroup("routers").addGroup(id.namespace()).addGroup(id.name());
Metrics routersMetrics = new FlinkUserMetrics(routersMetricGroup);
this.routers = loadRoutersAttachedToIngress(id, universe.routers());
this.downstream =
new DownstreamCollector<>(universe.messageFactoryKey(), output, routersMetrics);
}
@Override
public void processElement(StreamRecord<T> element) {
final T value = element.getValue();
for (Router<T> router : routers) {
router.route(value, downstream);
}
}
@SuppressWarnings("unchecked")
private static <T> List<Router<T>> loadRoutersAttachedToIngress(
IngressIdentifier<T> id, Map<IngressIdentifier<?>, List<Router<?>>> definedRouters) {
List<Router<?>> routerList = definedRouters.get(id);
Preconditions.checkState(routerList != null, "unable to find a router for ingress " + id);
return (List<Router<T>>) (List<?>) routerList;
}
@VisibleForTesting
static final class DownstreamCollector<T> implements Downstream<T> {
private final MessageFactory factory;
private final StreamRecord<Message> reuse = new StreamRecord<>(null);
private final Output<StreamRecord<Message>> output;
private final Metrics metrics;
DownstreamCollector(
MessageFactoryKey messageFactoryKey,
Output<StreamRecord<Message>> output,
Metrics metrics) {
this.factory = MessageFactory.forKey(messageFactoryKey);
this.output = Objects.requireNonNull(output);
this.metrics = Objects.requireNonNull(metrics);
}
@Override
public void forward(Address to, Object message) {
if (to == null) {
throw new NullPointerException("Unable to send a message downstream without an address.");
}
if (message == null) {
throw new NullPointerException("message is mandatory parameter and can not be NULL.");
}
// create an envelope out of the source, destination addresses, and the payload.
// This is the first instance where a user supplied payload that comes off a source
// is wrapped into a (statefun) Message envelope.
Message envelope = factory.from(null, to, message);
output.collect(reuse.replace(envelope));
}
@Override
public Metrics metrics() {
return metrics;
}
}
}
| 6,141 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/DecoratedSource.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.flink.core.translation;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.IngressSpec;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
final class DecoratedSource {
final String name;
final String uid;
final SourceFunction<?> source;
private DecoratedSource(String name, String uid, SourceFunction<?> source) {
this.name = name;
this.uid = uid;
this.source = source;
}
public static DecoratedSource of(IngressSpec<?> spec, SourceFunction<?> source) {
IngressIdentifier<?> identifier = spec.id();
String name = String.format("%s-%s-ingress", identifier.namespace(), identifier.name());
String uid =
String.format(
"%s-%s-%s-%s-ingress",
spec.type().namespace(), spec.type().type(), identifier.namespace(), identifier.name());
return new DecoratedSource(name, uid, source);
}
}
| 6,142 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/RouterTranslator.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.flink.core.translation;
import java.util.Map;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsJobConstants;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.common.Maps;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.IngressSpec;
import org.apache.flink.streaming.api.datastream.DataStream;
final class RouterTranslator {
private final StatefulFunctionsUniverse universe;
private final StatefulFunctionsConfig configuration;
RouterTranslator(StatefulFunctionsUniverse universe, StatefulFunctionsConfig configuration) {
this.universe = universe;
this.configuration = configuration;
}
Map<IngressIdentifier<?>, DataStream<Message>> translate(
Map<IngressIdentifier<?>, DataStream<?>> sources) {
return Maps.transformValues(
universe.routers(), (id, unused) -> createRoutersForSource(id, sources.get(id)));
}
/**
* For each input {@linkplain DataStream} (created as a result of {@linkplain IngressSpec}
* translation) we attach a single FlatMap function that would invoke all the defined routers for
* that spec. Please note that the FlatMap function must have the same parallelism as the
* {@linkplain DataStream} it is attached to, so that we keep per key ordering.
*/
@SuppressWarnings("unchecked")
private DataStream<Message> createRoutersForSource(
IngressIdentifier<?> id, DataStream<?> sourceStream) {
IngressIdentifier<Object> castedId = (IngressIdentifier<Object>) id;
DataStream<Object> castedSource = (DataStream<Object>) sourceStream;
IngressRouterOperator<Object> router = new IngressRouterOperator<>(configuration, castedId);
TypeInformation<Message> typeInfo = universe.types().registerType(Message.class);
int sourceParallelism = castedSource.getParallelism();
String operatorName = StatefulFunctionsJobConstants.ROUTER_NAME + " (" + castedId.name() + ")";
return castedSource
.transform(operatorName, typeInfo, router)
.setParallelism(sourceParallelism)
.uid(routerUID(id))
.returns(typeInfo);
}
private String routerUID(IngressIdentifier<?> identifier) {
return String.format("%s-%s-router", identifier.namespace(), identifier.name());
}
}
| 6,143 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/SideOutputTranslator.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.flink.core.translation;
import java.util.HashMap;
import java.util.Map;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.types.StaticallyRegisteredTypes;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.util.OutputTag;
final class SideOutputTranslator {
private final StaticallyRegisteredTypes types;
private final Iterable<EgressIdentifier<?>> egressIdentifiers;
SideOutputTranslator(StatefulFunctionsUniverse universe) {
this(universe.types(), universe.egress().keySet());
}
SideOutputTranslator(
StaticallyRegisteredTypes types, Iterable<EgressIdentifier<?>> egressIdentifiers) {
this.types = types;
this.egressIdentifiers = egressIdentifiers;
}
Map<EgressIdentifier<?>, OutputTag<Object>> translate() {
Map<EgressIdentifier<?>, OutputTag<Object>> outputTags = new HashMap<>();
for (EgressIdentifier<?> id : egressIdentifiers) {
outputTags.put(id, outputTagFromId(id, types));
}
return outputTags;
}
private static OutputTag<Object> outputTagFromId(
EgressIdentifier<?> id, StaticallyRegisteredTypes types) {
@SuppressWarnings("unchecked")
EgressIdentifier<Object> casted = (EgressIdentifier<Object>) id;
String name = String.format("%s.%s", id.namespace(), id.name());
TypeInformation<Object> typeInformation = types.registerType(casted.consumedType());
return new OutputTag<>(name, typeInformation);
}
}
| 6,144 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/translation/Sources.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.flink.core.translation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.statefun.flink.common.UnimplementedTypeInfo;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.StatefulFunctionsUniverse;
import org.apache.flink.statefun.flink.core.message.Message;
import org.apache.flink.statefun.flink.core.message.RoutableMessage;
import org.apache.flink.statefun.flink.core.types.StaticallyRegisteredTypes;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
final class Sources {
private final DataStream<Message> sourceUnion;
private Sources(DataStream<Message> union) {
this.sourceUnion = union;
}
static Sources create(
StreamExecutionEnvironment env,
StatefulFunctionsUniverse universe,
StatefulFunctionsConfig configuration) {
final Map<IngressIdentifier<?>, DecoratedSource> sourceFunctions =
ingressToSourceFunction(universe);
final Map<IngressIdentifier<?>, DataStream<?>> sourceStreams =
sourceFunctionToDataStream(env, sourceFunctions);
final Map<IngressIdentifier<?>, DataStream<Message>> envelopeSources =
dataStreamToEnvelopStream(universe, sourceStreams, configuration);
return new Sources(union(envelopeSources.values()));
}
static Sources create(
StaticallyRegisteredTypes types, Iterable<DataStream<RoutableMessage>> envelopeSources) {
TypeInformation<Message> messageOutputType = types.registerType(Message.class);
List<DataStream<Message>> messages = new ArrayList<>();
for (DataStream<? extends RoutableMessage> input : envelopeSources) {
/* This is safe, since the SDK is producing Messages. */
@SuppressWarnings("unchecked")
DataStream<Message> casted = (DataStream<Message>) input;
casted.getTransformation().setOutputType(messageOutputType);
messages.add(casted);
}
return new Sources(union(messages));
}
private static Map<IngressIdentifier<?>, DataStream<Message>> dataStreamToEnvelopStream(
StatefulFunctionsUniverse universe,
Map<IngressIdentifier<?>, DataStream<?>> sourceStreams,
StatefulFunctionsConfig configuration) {
RouterTranslator routerTranslator = new RouterTranslator(universe, configuration);
return routerTranslator.translate(sourceStreams);
}
private static Map<IngressIdentifier<?>, DataStream<?>> sourceFunctionToDataStream(
StreamExecutionEnvironment env, Map<IngressIdentifier<?>, DecoratedSource> sourceFunctions) {
Map<IngressIdentifier<?>, DataStream<?>> sourceStreams = new HashMap<>();
sourceFunctions.forEach(
(id, sourceFunction) -> {
DataStreamSource<?> stream = env.addSource(sourceFunction.source);
stream.name(sourceFunction.name);
stream.uid(sourceFunction.uid);
// we erase whatever type information present at the source, since the source is always
// chained to the IngressRouterFlatMap, and that operator is always emitting records of
// type
// Message.
eraseTypeInformation(stream.getTransformation());
sourceStreams.put(id, stream);
});
return sourceStreams;
}
private static void eraseTypeInformation(Transformation<?> transformation) {
transformation.setOutputType(new UnimplementedTypeInfo<>());
}
private static Map<IngressIdentifier<?>, DecoratedSource> ingressToSourceFunction(
StatefulFunctionsUniverse universe) {
IngressToSourceFunctionTranslator translator = new IngressToSourceFunctionTranslator(universe);
return translator.translate();
}
DataStream<Message> unionStream() {
return sourceUnion;
}
private static <T> DataStream<T> union(Collection<DataStream<T>> sources) {
if (sources.isEmpty()) {
throw new IllegalStateException("There are no routers defined.");
}
final int sourceCount = sources.size();
final Iterator<DataStream<T>> iterator = sources.iterator();
if (sourceCount == 1) {
return iterator.next();
}
DataStream<T> first = iterator.next();
@SuppressWarnings("unchecked")
DataStream<T>[] rest = new DataStream[sourceCount - 1];
for (int i = 0; i < sourceCount - 1; i++) {
rest[i] = iterator.next();
}
return first.union(rest);
}
}
| 6,145 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/ModuleConfigurationException.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.flink.core.jsonmodule;
public final class ModuleConfigurationException extends RuntimeException {
private static final long serialVersionUID = 1;
public ModuleConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public ModuleConfigurationException(String message) {
super(message);
}
}
| 6,146 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/FormatVersion.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.flink.core.jsonmodule;
enum FormatVersion {
// ============================================================
// EOL versions
// ============================================================
v1_0("1.0"),
v2_0("2.0"),
// ============================================================
// Supported versions
// ============================================================
v3_0("3.0"),
v3_1("3.1");
private String versionStr;
FormatVersion(String versionStr) {
this.versionStr = versionStr;
}
@Override
public String toString() {
return versionStr;
}
static FormatVersion fromString(String versionStr) {
switch (versionStr) {
case "1.0":
return v1_0;
case "2.0":
return v2_0;
case "3.0":
return v3_0;
case "3.1":
return v3_1;
default:
throw new IllegalArgumentException("Unrecognized format version: " + versionStr);
}
}
}
| 6,147 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonServiceLoader.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.flink.core.jsonmodule;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonPointer;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import org.apache.flink.statefun.flink.common.ResourceLocator;
import org.apache.flink.statefun.flink.common.json.Selectors;
import org.apache.flink.statefun.sdk.spi.StatefulFunctionModule;
public final class JsonServiceLoader {
// =======================================================================
// Json pointers for backwards compatibility with legacy format v3.0
// =======================================================================
private static final JsonPointer FORMAT_VERSION = JsonPointer.compile("/version");
private static final JsonPointer MODULE_SPEC = JsonPointer.compile("/module/spec");
private static final JsonPointer MODULE_META_TYPE = JsonPointer.compile("/module/meta/type");
public static Iterable<StatefulFunctionModule> load(String moduleName) {
ObjectMapper mapper = mapper();
Iterable<URL> namedResources = ResourceLocator.findResources(moduleName);
return StreamSupport.stream(namedResources.spliterator(), false)
.map(moduleUrl -> fromUrl(mapper, moduleUrl))
.collect(Collectors.toList());
}
@VisibleForTesting
static StatefulFunctionModule fromUrl(ObjectMapper mapper, URL moduleUrl) {
try {
final List<JsonNode> allComponentNodes = readAllComponentNodes(mapper, moduleUrl);
if (isLegacySingleRootFormat(allComponentNodes)) {
return createLegacyRemoteModule(allComponentNodes.get(0), moduleUrl);
}
return new RemoteModule(allComponentNodes);
} catch (Throwable t) {
throw new RuntimeException("Failed loading a module at " + moduleUrl, t);
}
}
/**
* Read a {@code StatefulFunction} module definition.
*
* <p>A valid resource module definition has to contain the metadata associated with this module,
* such as its type.
*/
private static List<JsonNode> readAllComponentNodes(ObjectMapper mapper, URL moduleYamlFile)
throws IOException {
YAMLFactory yaml = new YAMLFactory();
YAMLParser yamlParser = yaml.createParser(moduleYamlFile);
return mapper.readValues(yamlParser, JsonNode.class).readAll();
}
private static void validateMeta(URL moduleYamlFile, JsonNode root) {
JsonNode typeNode = root.at(MODULE_META_TYPE);
if (typeNode.isMissingNode()) {
throw new IllegalStateException("Unable to find a module type in " + moduleYamlFile);
}
if (!typeNode.asText().equalsIgnoreCase(ModuleType.REMOTE.name())) {
throw new IllegalStateException(
"Unknown module type "
+ typeNode.asText()
+ ", currently supported: "
+ ModuleType.REMOTE);
}
}
private static JsonNode requireValidModuleSpecNode(URL moduleYamlFile, JsonNode root) {
final JsonNode moduleSpecNode = root.at(MODULE_SPEC);
if (moduleSpecNode.isMissingNode()) {
throw new IllegalStateException("A module without a spec at " + moduleYamlFile);
}
return moduleSpecNode;
}
private static boolean isLegacySingleRootFormat(List<JsonNode> allComponentNodes) {
if (allComponentNodes.size() == 1) {
final JsonNode singleRootNode = allComponentNodes.get(0);
return hasLegacyFormatVersionField(singleRootNode);
}
return false;
}
private static boolean hasLegacyFormatVersionField(JsonNode singleRootNode) {
return Selectors.optionalTextAt(singleRootNode, FORMAT_VERSION).isPresent();
}
private static StatefulFunctionModule createLegacyRemoteModule(
JsonNode singleRootNode, URL moduleUrl) {
validateMeta(moduleUrl, singleRootNode);
final FormatVersion version = requireValidFormatVersion(singleRootNode);
switch (version) {
case v3_0:
return new LegacyRemoteModuleV30(requireValidModuleSpecNode(moduleUrl, singleRootNode));
default:
throw new IllegalStateException("Unrecognized format version: " + version);
}
}
private static FormatVersion requireValidFormatVersion(JsonNode root) {
final String formatVersionStr = Selectors.textAt(root, FORMAT_VERSION);
final FormatVersion formatVersion = FormatVersion.fromString(formatVersionStr);
if (formatVersion.compareTo(FormatVersion.v3_0) < 0) {
throw new IllegalArgumentException(
"Only format versions higher than or equal to 3.0 is supported. Was version "
+ formatVersion
+ ".");
}
return formatVersion;
}
@VisibleForTesting
static ObjectMapper mapper() {
return new ObjectMapper(new YAMLFactory());
}
}
| 6,148 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/ModuleType.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.flink.core.jsonmodule;
public enum ModuleType {
REMOTE
}
| 6,149 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/RemoteModule.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.flink.core.jsonmodule;
import static org.apache.flink.statefun.flink.core.spi.ExtensionResolverAccessor.getExtensionResolver;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.statefun.extensions.ComponentBinder;
import org.apache.flink.statefun.extensions.ComponentJsonObject;
import org.apache.flink.statefun.flink.core.spi.ExtensionResolver;
import org.apache.flink.statefun.sdk.spi.StatefulFunctionModule;
public final class RemoteModule implements StatefulFunctionModule {
private final List<JsonNode> componentNodes;
RemoteModule(List<JsonNode> componentNodes) {
this.componentNodes = Objects.requireNonNull(componentNodes);
}
@Override
public void configure(Map<String, String> globalConfiguration, Binder moduleBinder) {
parseComponentNodes(componentNodes)
.forEach(component -> bindComponent(component, moduleBinder));
}
private static List<ComponentJsonObject> parseComponentNodes(
Iterable<? extends JsonNode> componentNodes) {
return StreamSupport.stream(componentNodes.spliterator(), false)
.filter(node -> !node.isNull())
.map(ComponentJsonObject::new)
.collect(Collectors.toList());
}
private static void bindComponent(ComponentJsonObject component, Binder moduleBinder) {
final ExtensionResolver extensionResolver = getExtensionResolver(moduleBinder);
final ComponentBinder componentBinder =
extensionResolver.resolveExtension(component.binderTypename(), ComponentBinder.class);
componentBinder.bind(component, moduleBinder);
}
}
| 6,150 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/LegacyRemoteModuleV30.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.flink.core.jsonmodule;
import static org.apache.flink.statefun.flink.core.spi.ExtensionResolverAccessor.getExtensionResolver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonPointer;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.statefun.extensions.ComponentBinder;
import org.apache.flink.statefun.extensions.ComponentJsonObject;
import org.apache.flink.statefun.flink.common.json.Selectors;
import org.apache.flink.statefun.flink.core.spi.ExtensionResolver;
import org.apache.flink.statefun.sdk.TypeName;
import org.apache.flink.statefun.sdk.spi.StatefulFunctionModule;
@Deprecated
public final class LegacyRemoteModuleV30 implements StatefulFunctionModule {
private final JsonNode moduleSpecNode;
// =====================================================================
// Json pointers for backwards compatibility
// =====================================================================
private static final JsonPointer ENDPOINTS = JsonPointer.compile("/endpoints");
private static final JsonPointer INGRESSES = JsonPointer.compile("/ingresses");
private static final JsonPointer EGRESSES = JsonPointer.compile("/egresses");
private static final JsonPointer ENDPOINT_KIND = JsonPointer.compile("/endpoint/meta/kind");
private static final JsonPointer ENDPOINT_SPEC = JsonPointer.compile("/endpoint/spec");
private static final JsonPointer INGRESS_KIND = JsonPointer.compile("/ingress/meta/type");
private static final JsonPointer INGRESS_ID = JsonPointer.compile("/ingress/meta/id");
private static final JsonPointer INGRESS_SPEC = JsonPointer.compile("/ingress/spec");
private static final JsonPointer EGRESS_KIND = JsonPointer.compile("/egress/meta/type");
private static final JsonPointer EGRESS_ID = JsonPointer.compile("/egress/meta/id");
private static final JsonPointer EGRESS_SPEC = JsonPointer.compile("/egress/spec");
private static final Map<String, TypeName> LEGACY_KIND_CONVERSIONS = new HashMap<>();
static {
LEGACY_KIND_CONVERSIONS.put("http", TypeName.parseFrom("io.statefun.endpoints.v1/http"));
LEGACY_KIND_CONVERSIONS.put(
"io.statefun.kafka/ingress", TypeName.parseFrom("io.statefun.kafka.v1/ingress"));
LEGACY_KIND_CONVERSIONS.put(
"io.statefun.kafka/egress", TypeName.parseFrom("io.statefun.kafka.v1/egress"));
LEGACY_KIND_CONVERSIONS.put(
"io.statefun.kinesis/ingress", TypeName.parseFrom("io.statefun.kinesis.v1/ingress"));
LEGACY_KIND_CONVERSIONS.put(
"io.statefun.kinesis/egress", TypeName.parseFrom("io.statefun.kinesis.v1/egress"));
}
LegacyRemoteModuleV30(JsonNode moduleSpecNode) {
this.moduleSpecNode = Objects.requireNonNull(moduleSpecNode);
}
@Override
public void configure(Map<String, String> globalConfiguration, Binder moduleBinder) {
components(moduleSpecNode).forEach(component -> bindComponent(component, moduleBinder));
}
private static Iterable<ComponentJsonObject> components(JsonNode moduleRootNode) {
final List<ComponentJsonObject> components = new ArrayList<>();
components.addAll(endpointComponents(moduleRootNode));
components.addAll(ingressComponents(moduleRootNode));
components.addAll(egressComponents(moduleRootNode));
return components;
}
private static List<ComponentJsonObject> endpointComponents(JsonNode moduleRootNode) {
final Iterable<? extends JsonNode> endpointComponentNodes =
Selectors.listAt(moduleRootNode, ENDPOINTS);
return StreamSupport.stream(endpointComponentNodes.spliterator(), false)
.map(LegacyRemoteModuleV30::parseEndpointComponentNode)
.collect(Collectors.toList());
}
private static List<ComponentJsonObject> ingressComponents(JsonNode moduleRootNode) {
final Iterable<? extends JsonNode> ingressComponentNodes =
Selectors.listAt(moduleRootNode, INGRESSES);
return StreamSupport.stream(ingressComponentNodes.spliterator(), false)
.map(LegacyRemoteModuleV30::parseIngressComponentNode)
.collect(Collectors.toList());
}
private static List<ComponentJsonObject> egressComponents(JsonNode moduleRootNode) {
final Iterable<? extends JsonNode> egressComponentNodes =
Selectors.listAt(moduleRootNode, EGRESSES);
return StreamSupport.stream(egressComponentNodes.spliterator(), false)
.map(LegacyRemoteModuleV30::parseEgressComponentNode)
.collect(Collectors.toList());
}
private static ComponentJsonObject parseEndpointComponentNode(JsonNode node) {
final TypeName binderKind =
tryConvertLegacyBinderKindTypeName(Selectors.textAt(node, ENDPOINT_KIND));
// backwards compatibility path
return reconstructComponentJsonObject(binderKind, node.at(ENDPOINT_SPEC));
}
private static ComponentJsonObject parseIngressComponentNode(JsonNode node) {
final TypeName binderKind =
tryConvertLegacyBinderKindTypeName(Selectors.textAt(node, INGRESS_KIND));
// backwards compatibility path
final JsonNode specNode = node.at(INGRESS_SPEC);
final String idString = Selectors.textAt(node, INGRESS_ID);
((ObjectNode) specNode).put("id", idString);
return reconstructComponentJsonObject(binderKind, specNode);
}
private static ComponentJsonObject parseEgressComponentNode(JsonNode node) {
final TypeName binderKind =
tryConvertLegacyBinderKindTypeName(Selectors.textAt(node, EGRESS_KIND));
// backwards compatibility path
final JsonNode specNode = node.at(EGRESS_SPEC);
final String idString = Selectors.textAt(node, EGRESS_ID);
((ObjectNode) specNode).put("id", idString);
return reconstructComponentJsonObject(binderKind, specNode);
}
private static TypeName tryConvertLegacyBinderKindTypeName(String binderKindString) {
final TypeName binderKind = LEGACY_KIND_CONVERSIONS.get(binderKindString);
if (binderKind != null) {
return binderKind;
}
// if it isn't one of the recognized legacy kinds, it could be something custom added by the
// user
return TypeName.parseFrom(binderKindString);
}
private static ComponentJsonObject reconstructComponentJsonObject(
TypeName binderTypename, JsonNode specJsonNode) {
final ObjectNode reconstructedNode = new ObjectMapper().createObjectNode();
reconstructedNode.put(
ComponentJsonObject.BINDER_KIND_FIELD, binderTypename.canonicalTypenameString());
reconstructedNode.set(ComponentJsonObject.SPEC_FIELD, specJsonNode);
return new ComponentJsonObject(reconstructedNode);
}
private static void bindComponent(ComponentJsonObject component, Binder moduleBinder) {
final ExtensionResolver extensionResolver = getExtensionResolver(moduleBinder);
final ComponentBinder componentBinder =
extensionResolver.resolveExtension(component.binderTypename(), ComponentBinder.class);
componentBinder.bind(component, moduleBinder);
}
}
| 6,151 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/RequestReplyClientFactory.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.flink.core.reqreply;
import java.net.URI;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
@PublicEvolving
public interface RequestReplyClientFactory {
RequestReplyClient createTransportClient(ObjectNode transportProperties, URI endpointUrl);
void cleanup();
}
| 6,152 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/RequestReplyClient.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.flink.core.reqreply;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.statefun.flink.core.metrics.RemoteInvocationMetrics;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
@PublicEvolving
public interface RequestReplyClient {
CompletableFuture<FromFunction> call(
ToFunctionRequestSummary requestSummary,
RemoteInvocationMetrics metrics,
ToFunction toFunction);
}
| 6,153 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/RequestReplyFunction.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.flink.core.reqreply;
import static org.apache.flink.statefun.flink.core.common.PolyglotUtil.polyglotAddressToSdkAddress;
import static org.apache.flink.statefun.flink.core.common.PolyglotUtil.sdkAddressToPolyglotAddress;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.statefun.flink.core.backpressure.InternalContext;
import org.apache.flink.statefun.flink.core.metrics.RemoteInvocationMetrics;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.AsyncOperationResult;
import org.apache.flink.statefun.sdk.Context;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.EgressMessage;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.IncompleteInvocationContext;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.InvocationResponse;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction.Invocation;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction.InvocationBatchRequest;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.state.PersistedAppendingBuffer;
import org.apache.flink.statefun.sdk.state.PersistedValue;
import org.apache.flink.types.Either;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class RequestReplyFunction implements StatefulFunction {
public static final Logger LOG = LoggerFactory.getLogger(RequestReplyFunction.class);
private final FunctionType functionType;
private final RequestReplyClient client;
private final int maxNumBatchRequests;
/**
* This flag indicates whether or not at least one request has already been sent to the remote
* function. It is toggled by the {@link #sendToFunction(InternalContext, ToFunction)} method upon
* sending the first request.
*
* <p>For the first request, we block until response is received; for stateful applications,
* especially at restore time of a restored execution where there may be a large backlog of events
* and checkpointed inflight requests, this helps mitigate excessive hoards of
* IncompleteInvocationContext responses and retry attempt round-trips.
*
* <p>After this flag is toggled upon sending the first request, all successive requests will be
* performed as usual async operations.
*/
private boolean isFirstRequestSent;
/**
* A request state keeps tracks of the number of inflight & batched requests.
*
* <p>A tracking state can have one of the following values:
*
* <ul>
* <li>NULL - there is no inflight request, and there is nothing in the backlog.
* <li>0 - there's an inflight request, but nothing in the backlog.
* <li>{@code > 0} There is an in flight request, and @requestState items in the backlog.
* </ul>
*/
@Persisted
private final PersistedValue<Integer> requestState =
PersistedValue.of("request-state", Integer.class);
@Persisted
private final PersistedAppendingBuffer<ToFunction.Invocation> batch =
PersistedAppendingBuffer.of("batch", ToFunction.Invocation.class);
@Persisted private final PersistedRemoteFunctionValues managedStates;
public RequestReplyFunction(
FunctionType functionType, int maxNumBatchRequests, RequestReplyClient client) {
this(functionType, new PersistedRemoteFunctionValues(), maxNumBatchRequests, client, false);
}
@VisibleForTesting
RequestReplyFunction(
FunctionType functionType,
PersistedRemoteFunctionValues states,
int maxNumBatchRequests,
RequestReplyClient client,
boolean isFirstRequestSent) {
this.functionType = Objects.requireNonNull(functionType);
this.managedStates = Objects.requireNonNull(states);
this.maxNumBatchRequests = maxNumBatchRequests;
this.client = Objects.requireNonNull(client);
this.isFirstRequestSent = isFirstRequestSent;
}
@Override
public void invoke(Context context, Object input) {
InternalContext castedContext = (InternalContext) context;
if (!(input instanceof AsyncOperationResult)) {
onRequest(castedContext, (TypedValue) input);
return;
}
@SuppressWarnings("unchecked")
AsyncOperationResult<ToFunction, FromFunction> result =
(AsyncOperationResult<ToFunction, FromFunction>) input;
onAsyncResult(castedContext, result);
}
private void onRequest(InternalContext context, TypedValue message) {
Invocation.Builder invocationBuilder = singeInvocationBuilder(context, message);
int inflightOrBatched = requestState.getOrDefault(-1);
if (inflightOrBatched < 0) {
// no inflight requests, and nothing in the batch.
// so we let this request to go through, and change state to indicate that:
// a) there is a request in flight.
// b) there is nothing in the batch.
requestState.set(0);
sendToFunction(context, invocationBuilder);
return;
}
// there is at least one request in flight (inflightOrBatched >= 0),
// so we add that request to the batch.
batch.append(invocationBuilder.build());
inflightOrBatched++;
requestState.set(inflightOrBatched);
context.functionTypeMetrics().appendBacklogMessages(1);
if (isMaxNumBatchRequestsExceeded(inflightOrBatched)) {
// we are at capacity, can't add anything to the batch.
// we need to signal to the runtime that we are unable to process any new input
// and we must wait for our in flight asynchronous operation to complete before
// we are able to process more input.
context.awaitAsyncOperationComplete();
}
}
private void onAsyncResult(
InternalContext context, AsyncOperationResult<ToFunction, FromFunction> asyncResult) {
if (asyncResult.unknown()) {
ToFunction batch = asyncResult.metadata();
// According to the request-reply protocol, on recovery
// we re-send the uncompleted (in-flight during a failure)
// messages. But we shouldn't assume that the state
// definitions are the same as in the previous attempt.
// We create a retry batch and let the SDK reply
// with the correct state specs.
sendToFunction(context, createRetryBatch(batch));
return;
}
if (asyncResult.failure()) {
throw new IllegalStateException(
"Failure forwarding a message to a remote function " + context.self(),
asyncResult.throwable());
}
final Either<InvocationResponse, IncompleteInvocationContext> response =
unpackResponse(asyncResult.value());
if (response.isRight()) {
handleIncompleteInvocationContextResponse(context, response.right(), asyncResult.metadata());
} else {
handleInvocationResultResponse(context, response.left());
}
}
private static Either<InvocationResponse, IncompleteInvocationContext> unpackResponse(
FromFunction fromFunction) {
if (fromFunction.hasIncompleteInvocationContext()) {
return Either.Right(fromFunction.getIncompleteInvocationContext());
}
if (fromFunction.hasInvocationResult()) {
return Either.Left(fromFunction.getInvocationResult());
}
// function had no side effects
return Either.Left(InvocationResponse.getDefaultInstance());
}
private void handleIncompleteInvocationContextResponse(
InternalContext context,
IncompleteInvocationContext incompleteContext,
ToFunction originalBatch) {
managedStates.registerStates(incompleteContext.getMissingValuesList());
final InvocationBatchRequest.Builder retryBatch = createRetryBatch(originalBatch);
sendToFunction(context, retryBatch);
}
private void handleInvocationResultResponse(InternalContext context, InvocationResponse result) {
handleOutgoingMessages(context, result);
handleOutgoingDelayedMessages(context, result);
handleEgressMessages(context, result);
managedStates.updateStateValues(result.getStateMutationsList());
final int numBatched = requestState.getOrDefault(-1);
if (numBatched < 0) {
throw new IllegalStateException("Got an unexpected async result");
} else if (numBatched == 0) {
requestState.clear();
} else {
final InvocationBatchRequest.Builder nextBatch = getNextBatch();
// an async request was just completed, but while it was in flight we have
// accumulated a batch, we now proceed with:
// a) clearing the batch from our own persisted state (the batch moves to the async
// operation
// state)
// b) sending the accumulated batch to the remote function.
requestState.set(0);
batch.clear();
context.functionTypeMetrics().consumeBacklogMessages(numBatched);
sendToFunction(context, nextBatch);
}
}
private InvocationBatchRequest.Builder getNextBatch() {
InvocationBatchRequest.Builder builder = InvocationBatchRequest.newBuilder();
Iterable<Invocation> view = batch.view();
builder.addAllInvocations(view);
return builder;
}
private InvocationBatchRequest.Builder createRetryBatch(ToFunction toFunction) {
InvocationBatchRequest.Builder builder = InvocationBatchRequest.newBuilder();
builder.addAllInvocations(toFunction.getInvocation().getInvocationsList());
return builder;
}
private void handleEgressMessages(Context context, InvocationResponse invocationResult) {
for (EgressMessage egressMessage : invocationResult.getOutgoingEgressesList()) {
EgressIdentifier<TypedValue> id =
new EgressIdentifier<>(
egressMessage.getEgressNamespace(), egressMessage.getEgressType(), TypedValue.class);
context.send(id, egressMessage.getArgument());
}
}
private void handleOutgoingMessages(Context context, InvocationResponse invocationResult) {
for (FromFunction.Invocation invokeCommand : invocationResult.getOutgoingMessagesList()) {
final Address to = polyglotAddressToSdkAddress(invokeCommand.getTarget());
final TypedValue message = invokeCommand.getArgument();
context.send(to, message);
}
}
private void handleOutgoingDelayedMessages(Context context, InvocationResponse invocationResult) {
for (FromFunction.DelayedInvocation delayedInvokeCommand :
invocationResult.getDelayedInvocationsList()) {
if (delayedInvokeCommand.getIsCancellationRequest()) {
handleDelayedMessageCancellation(context, delayedInvokeCommand);
} else {
handleDelayedMessageSending(context, delayedInvokeCommand);
}
}
}
private void handleDelayedMessageSending(
Context context, FromFunction.DelayedInvocation delayedInvokeCommand) {
final Address to = polyglotAddressToSdkAddress(delayedInvokeCommand.getTarget());
final TypedValue message = delayedInvokeCommand.getArgument();
final long delay = delayedInvokeCommand.getDelayInMs();
final String token = delayedInvokeCommand.getCancellationToken();
Duration duration = Duration.ofMillis(delay);
if (token.isEmpty()) {
context.sendAfter(duration, to, message);
} else {
context.sendAfter(duration, to, message, token);
}
}
private void handleDelayedMessageCancellation(
Context context, FromFunction.DelayedInvocation delayedInvokeCommand) {
String token = delayedInvokeCommand.getCancellationToken();
if (token.isEmpty()) {
throw new IllegalArgumentException(
"Can not handle a cancellation request without a cancellation token.");
}
context.cancelDelayedMessage(token);
}
// --------------------------------------------------------------------------------
// Send Message to Remote Function
// --------------------------------------------------------------------------------
/**
* Returns an {@link Invocation.Builder} set with the input {@code message} and the caller
* information (is present).
*/
private static Invocation.Builder singeInvocationBuilder(Context context, TypedValue message) {
Invocation.Builder invocationBuilder = Invocation.newBuilder();
if (context.caller() != null) {
invocationBuilder.setCaller(sdkAddressToPolyglotAddress(context.caller()));
}
invocationBuilder.setArgument(message);
return invocationBuilder;
}
/**
* Sends a {@link InvocationBatchRequest} to the remote function consisting out of a single
* invocation represented by {@code invocationBuilder}.
*/
private void sendToFunction(InternalContext context, Invocation.Builder invocationBuilder) {
InvocationBatchRequest.Builder batchBuilder = InvocationBatchRequest.newBuilder();
batchBuilder.addInvocations(invocationBuilder);
sendToFunction(context, batchBuilder);
}
/** Sends a {@link InvocationBatchRequest} to the remote function. */
private void sendToFunction(
InternalContext context, InvocationBatchRequest.Builder batchBuilder) {
batchBuilder.setTarget(sdkAddressToPolyglotAddress(context.self()));
managedStates.attachStateValues(batchBuilder);
ToFunction toFunction = ToFunction.newBuilder().setInvocation(batchBuilder).build();
sendToFunction(context, toFunction);
}
private void sendToFunction(InternalContext context, ToFunction toFunction) {
ToFunctionRequestSummary requestSummary =
new ToFunctionRequestSummary(
context.self(),
toFunction.getSerializedSize(),
toFunction.getInvocation().getStateCount(),
toFunction.getInvocation().getInvocationsCount());
RemoteInvocationMetrics metrics = context.functionTypeMetrics();
CompletableFuture<FromFunction> responseFuture =
client.call(requestSummary, metrics, toFunction);
if (isFirstRequestSent) {
context.registerAsyncOperation(toFunction, responseFuture);
} else {
LOG.info(
"Bootstrapping function {}. Blocking processing until first request is completed. Successive requests will be performed asynchronously.",
functionType);
// it is important to toggle the flag *before* handling the response. As a result of handling
// the first response, we may send retry requests in the case of an
// IncompleteInvocationContext response. For those requests, we already want to handle them as
// usual async operations.
isFirstRequestSent = true;
onAsyncResult(context, joinResponse(responseFuture, toFunction));
}
}
private boolean isMaxNumBatchRequestsExceeded(final int currentNumBatchRequests) {
return maxNumBatchRequests > 0 && currentNumBatchRequests >= maxNumBatchRequests;
}
private AsyncOperationResult<ToFunction, FromFunction> joinResponse(
CompletableFuture<FromFunction> responseFuture, ToFunction originalRequest) {
FromFunction response;
try {
response = responseFuture.join();
} catch (Exception e) {
return new AsyncOperationResult<>(
originalRequest, AsyncOperationResult.Status.FAILURE, null, e.getCause());
}
return new AsyncOperationResult<>(
originalRequest, AsyncOperationResult.Status.SUCCESS, response, null);
}
}
| 6,154 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/ToFunctionRequestSummary.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.flink.core.reqreply;
import java.util.Objects;
import org.apache.flink.statefun.sdk.Address;
/**
* ToFunctionRequestSummary - represents a summary of that request, it is indented to be used as an
* additional context for logging.
*/
public final class ToFunctionRequestSummary {
private final Address address;
private final int batchSize;
private final int totalSizeInBytes;
private final int numberOfStates;
public ToFunctionRequestSummary(
Address address, int totalSizeInBytes, int numberOfStates, int batchSize) {
this.address = Objects.requireNonNull(address);
this.totalSizeInBytes = totalSizeInBytes;
this.numberOfStates = numberOfStates;
this.batchSize = batchSize;
}
@Override
public String toString() {
return "ToFunctionRequestSummary("
+ "address="
+ address
+ ", batchSize="
+ batchSize
+ ", totalSizeInBytes="
+ totalSizeInBytes
+ ", numberOfStates="
+ numberOfStates
+ ')';
}
}
| 6,155 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/PersistedRemoteFunctionValues.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.flink.core.reqreply;
import com.google.protobuf.MoreByteStrings;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.flink.statefun.flink.core.types.remote.RemoteValueTypeMismatchException;
import org.apache.flink.statefun.sdk.TypeName;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.ExpirationSpec;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.PersistedValueMutation;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.PersistedValueSpec;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction.InvocationBatchRequest;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.state.Expiration;
import org.apache.flink.statefun.sdk.state.PersistedStateRegistry;
import org.apache.flink.statefun.sdk.state.RemotePersistedValue;
public final class PersistedRemoteFunctionValues {
private static final TypeName UNSET_STATE_TYPE = TypeName.parseFrom("io.statefun.types/unset");
@Persisted private final PersistedStateRegistry stateRegistry = new PersistedStateRegistry();
private final Map<String, RemotePersistedValue> managedStates = new HashMap<>();
void attachStateValues(InvocationBatchRequest.Builder batchBuilder) {
for (Map.Entry<String, RemotePersistedValue> managedStateEntry : managedStates.entrySet()) {
final ToFunction.PersistedValue.Builder valueBuilder =
ToFunction.PersistedValue.newBuilder().setStateName(managedStateEntry.getKey());
final RemotePersistedValue registeredHandle = managedStateEntry.getValue();
final byte[] stateBytes = registeredHandle.get();
if (stateBytes != null) {
final TypedValue stateValue =
TypedValue.newBuilder()
.setTypename(registeredHandle.type().canonicalTypenameString())
.setHasValue(true)
.setValue(MoreByteStrings.wrap(stateBytes))
.build();
valueBuilder.setStateValue(stateValue);
}
batchBuilder.addState(valueBuilder);
}
}
void updateStateValues(List<PersistedValueMutation> valueMutations) {
for (PersistedValueMutation mutate : valueMutations) {
final String stateName = mutate.getStateName();
switch (mutate.getMutationType()) {
case DELETE:
{
getStateHandleOrThrow(stateName).clear();
break;
}
case MODIFY:
{
final RemotePersistedValue registeredHandle = getStateHandleOrThrow(stateName);
final TypedValue newStateValue = mutate.getStateValue();
validateType(registeredHandle, newStateValue.getTypename());
registeredHandle.set(newStateValue.getValue().toByteArray());
break;
}
case UNRECOGNIZED:
throw new IllegalStateException(
"Received an UNRECOGNIZED PersistedValueMutation type. This may be caused by a mismatch or incompatibility with the remote function SDK version and the Stateful Functions version.");
default:
throw new IllegalStateException("Unexpected value: " + mutate.getMutationType());
}
}
}
/**
* Registers states that were indicated to be missing by remote functions via the remote
* invocation protocol.
*
* <p>A state is registered with the provided specification only if it wasn't registered already
* under the same name (identified by {@link PersistedValueSpec#getStateName()}). This means that
* you cannot change the specifications of an already registered state name, e.g. state TTL
* expiration configuration cannot be changed.
*
* @param protocolPersistedValueSpecs list of specifications for the indicated missing states.
*/
void registerStates(List<PersistedValueSpec> protocolPersistedValueSpecs) {
protocolPersistedValueSpecs.forEach(this::createAndRegisterValueStateIfAbsent);
}
private void createAndRegisterValueStateIfAbsent(PersistedValueSpec protocolPersistedValueSpec) {
final RemotePersistedValue stateHandle =
managedStates.get(protocolPersistedValueSpec.getStateName());
if (stateHandle == null) {
registerValueState(protocolPersistedValueSpec);
} else {
validateType(stateHandle, protocolPersistedValueSpec.getTypeTypename());
}
}
private void registerValueState(PersistedValueSpec protocolPersistedValueSpec) {
final String stateName = protocolPersistedValueSpec.getStateName();
final RemotePersistedValue remoteValueState =
RemotePersistedValue.of(
stateName,
sdkStateType(protocolPersistedValueSpec.getTypeTypename()),
sdkTtlExpiration(protocolPersistedValueSpec.getExpirationSpec()));
managedStates.put(stateName, remoteValueState);
try {
stateRegistry.registerRemoteValue(remoteValueState);
} catch (RemoteValueTypeMismatchException e) {
throw new RemoteFunctionStateException(stateName, e);
}
}
private void validateType(
RemotePersistedValue previousStateHandle, String protocolTypenameString) {
final TypeName newStateType = sdkStateType(protocolTypenameString);
if (!newStateType.equals(previousStateHandle.type())) {
throw new RemoteFunctionStateException(
previousStateHandle.name(),
new RemoteValueTypeMismatchException(previousStateHandle.type(), newStateType));
}
}
private static TypeName sdkStateType(String protocolTypenameString) {
// TODO type field may be empty in current master only because SDKs are not yet updated;
// TODO once SDKs are updated, we should expect that the type is always specified
return protocolTypenameString.isEmpty()
? UNSET_STATE_TYPE
: TypeName.parseFrom(protocolTypenameString);
}
private static Expiration sdkTtlExpiration(ExpirationSpec protocolExpirationSpec) {
final long expirationTtlMillis = protocolExpirationSpec.getExpireAfterMillis();
switch (protocolExpirationSpec.getMode()) {
case AFTER_INVOKE:
return Expiration.expireAfterReadingOrWriting(Duration.ofMillis(expirationTtlMillis));
case AFTER_WRITE:
return Expiration.expireAfterWriting(Duration.ofMillis(expirationTtlMillis));
default:
case NONE:
return Expiration.none();
}
}
private RemotePersistedValue getStateHandleOrThrow(String stateName) {
final RemotePersistedValue handle = managedStates.get(stateName);
if (handle == null) {
throw new IllegalStateException(
"Accessing a non-existing function state: "
+ stateName
+ ". This can happen if you forgot to declare this state using the language SDKs.");
}
return handle;
}
public static class RemoteFunctionStateException extends RuntimeException {
private static final long serialVersionUID = 1;
private RemoteFunctionStateException(String stateName, Throwable cause) {
super("An error occurred for state [" + stateName + "].", cause);
}
}
}
| 6,156 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/reqreply/ClassLoaderSafeRequestReplyClient.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.flink.core.reqreply;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.flink.core.metrics.RemoteInvocationMetrics;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
/**
* Decorator for a {@link RequestReplyClient} that makes sure we always use the correct classloader.
* This is required since client implementation may be user provided.
*/
public final class ClassLoaderSafeRequestReplyClient implements RequestReplyClient {
private final ClassLoader delegateClassLoader;
private final RequestReplyClient delegate;
public ClassLoaderSafeRequestReplyClient(RequestReplyClient delegate) {
this.delegate = Objects.requireNonNull(delegate);
this.delegateClassLoader = delegate.getClass().getClassLoader();
}
@Override
public CompletableFuture<FromFunction> call(
ToFunctionRequestSummary requestSummary,
RemoteInvocationMetrics metrics,
ToFunction toFunction) {
final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(delegateClassLoader);
return delegate.call(requestSummary, metrics, toFunction);
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
| 6,157 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/InternalContext.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.flink.core.backpressure;
import org.apache.flink.annotation.Internal;
import org.apache.flink.statefun.flink.core.metrics.FunctionTypeMetrics;
import org.apache.flink.statefun.sdk.Context;
@Internal
public interface InternalContext extends Context {
/**
* Signals the runtime to stop invoking the currently executing function with new input until at
* least one {@link org.apache.flink.statefun.sdk.AsyncOperationResult} belonging to this function
* would be delivered.
*
* <p>NOTE: If a function would request to block without actually registering any async operations
* either previously or during its current invocation, then it would remain blocked. Since this is
* an internal API to be used by the remote functions we don't do anything to prevent that.
*
* <p>If we would like it to be a part of the SDK then we would have to make sure that we track
* every async operation registered per each address.
*/
void awaitAsyncOperationComplete();
/**
* Returns the metrics handle for the current invoked function's type.
*
* @return the metrics handle for the current invoked function's type.
*/
FunctionTypeMetrics functionTypeMetrics();
}
| 6,158 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/Timer.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.flink.core.backpressure;
interface Timer {
long now();
void sleep(long durationNanos);
}
| 6,159 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BackPressureValve.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.flink.core.backpressure;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.Address;
public interface BackPressureValve {
/**
* Indicates rather a back pressure is needed.
*
* @return true if a back pressure should be applied.
*/
boolean shouldBackPressure();
/**
* Notifies the back pressure mechanism that a async operation was registered via {@link
* org.apache.flink.statefun.sdk.Context#registerAsyncOperation(Object, CompletableFuture)}.
*/
void notifyAsyncOperationRegistered();
/**
* Notifies when a async operation, registered by @owningAddress was completed.
*
* @param owningAddress the owner of the completed async operation.
*/
void notifyAsyncOperationCompleted(Address owningAddress);
/**
* Requests to stop processing any further input for that address, as long as there is an
* uncompleted async operation (registered by @address).
*
* <p>NOTE: The address would unblocked as soon as some (one) async operation registered by that
* address completes.
*
* @param address the address
*/
void blockAddress(Address address);
/**
* Checks whether a given address was previously blocked with {@link #blockAddress(Address)}.
*
* @param address the address to check
* @return boolean indicating whether or not the address was blocked.
*/
boolean isAddressBlocked(Address address);
}
| 6,160 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoff.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.flink.core.backpressure;
import java.time.Duration;
import java.util.Objects;
import org.apache.flink.annotation.VisibleForTesting;
public final class BoundedExponentialBackoff {
private final Timer timer;
private final long requestStartTimeInNanos;
private final long maxRequestDurationInNanos;
private long nextSleepTimeNanos;
public BoundedExponentialBackoff(Duration initialBackoffDuration, Duration maxRequestDuration) {
this(SystemNanoTimer.instance(), initialBackoffDuration, maxRequestDuration);
}
@VisibleForTesting
BoundedExponentialBackoff(
Timer timer, Duration initialBackoffDuration, Duration maxRequestDuration) {
this.timer = Objects.requireNonNull(timer);
this.requestStartTimeInNanos = timer.now();
this.maxRequestDurationInNanos = maxRequestDuration.toNanos();
this.nextSleepTimeNanos = initialBackoffDuration.toNanos();
}
public boolean applyNow() {
final long remainingNanos = remainingNanosUntilDeadLine();
final long nextAmountOfNanosToSleep = nextAmountOfNanosToSleep();
final long actualSleep = Math.min(remainingNanos, nextAmountOfNanosToSleep);
if (actualSleep <= 0) {
return false;
}
timer.sleep(actualSleep);
return true;
}
private long remainingNanosUntilDeadLine() {
final long totalElapsedTime = timer.now() - requestStartTimeInNanos;
return maxRequestDurationInNanos - totalElapsedTime;
}
private long nextAmountOfNanosToSleep() {
final long current = nextSleepTimeNanos;
nextSleepTimeNanos *= 2;
return current;
}
}
| 6,161 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/ThresholdBackPressureValve.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.flink.core.backpressure;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashMap;
import java.util.Objects;
import org.apache.flink.statefun.sdk.Address;
/**
* A simple Threshold based {@link BackPressureValve}.
*
* <p>There are two cases where a backpressure would be triggered:
*
* <ul>
* <li>The total number of in-flight async operations in a StreamTask exceeds a predefined
* threshold. This is tracked by {@link
* ThresholdBackPressureValve#pendingAsynchronousOperationsCount}, it is incremented when an
* async operation is registered, and decremented when it is completed.
* <li>A specific address has requested to stop processing new inputs, this is tracked by the
* {@link ThresholdBackPressureValve#blockedAddressSet}. The method {@link
* ThresholdBackPressureValve#notifyAsyncOperationCompleted(Address)} is meant to be called
* when ANY async operation has been completed.
* </ul>
*/
public final class ThresholdBackPressureValve implements BackPressureValve {
private final int maximumPendingAsynchronousOperations;
/**
* a set of address that had explicitly requested to stop processing any new inputs (via {@link
* InternalContext#awaitAsyncOperationComplete()}. Note that this is a set implemented on top of a
* map, and the value (Boolean) has no meaning.
*/
private final ObjectOpenHashMap<Address, Boolean> blockedAddressSet =
new ObjectOpenHashMap<>(1024);
private int pendingAsynchronousOperationsCount;
/**
* Constructs a ThresholdBackPressureValve.
*
* @param maximumPendingAsynchronousOperations the total allowed async operations to be inflight
* per StreamTask, or {@code -1} to disable back pressure.
*/
public ThresholdBackPressureValve(int maximumPendingAsynchronousOperations) {
this.maximumPendingAsynchronousOperations = maximumPendingAsynchronousOperations;
}
/** {@inheritDoc} */
@Override
public boolean shouldBackPressure() {
return totalPendingAsyncOperationsAtCapacity() || hasBlockedAddress();
}
/** {@inheritDoc} */
@Override
public void blockAddress(Address address) {
Objects.requireNonNull(address);
blockedAddressSet.put(address, Boolean.TRUE);
}
/** {@inheritDoc} */
@Override
public void notifyAsyncOperationRegistered() {
pendingAsynchronousOperationsCount++;
}
/** {@inheritDoc} */
@Override
public void notifyAsyncOperationCompleted(Address owningAddress) {
Objects.requireNonNull(owningAddress);
pendingAsynchronousOperationsCount = Math.max(0, pendingAsynchronousOperationsCount - 1);
blockedAddressSet.remove(owningAddress);
}
/** {@inheritDoc} */
@Override
public boolean isAddressBlocked(Address address) {
return blockedAddressSet.containsKey(address);
}
private boolean totalPendingAsyncOperationsAtCapacity() {
return maximumPendingAsynchronousOperations > 0
&& pendingAsynchronousOperationsCount >= maximumPendingAsynchronousOperations;
}
private boolean hasBlockedAddress() {
return !blockedAddressSet.isEmpty();
}
}
| 6,162 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.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.flink.core.backpressure;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/** A {@code Timer} backed by {@link System#nanoTime()}. */
final class SystemNanoTimer implements Timer {
private static final SystemNanoTimer INSTANCE = new SystemNanoTimer();
public static SystemNanoTimer instance() {
return INSTANCE;
}
private SystemNanoTimer() {}
@Override
public long now() {
return System.nanoTime();
}
@Override
public void sleep(long sleepTimeNanos) {
try {
final long sleepTimeMs = NANOSECONDS.toMillis(sleepTimeNanos);
Thread.sleep(sleepTimeMs);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException("interrupted while sleeping", ex);
}
}
}
| 6,163 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageFactory.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.flink.core.message;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Objects;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufSerializer;
import org.apache.flink.statefun.flink.core.generated.Checkpoint;
import org.apache.flink.statefun.flink.core.generated.Envelope;
import org.apache.flink.statefun.flink.core.generated.Payload;
import org.apache.flink.statefun.sdk.Address;
public final class MessageFactory {
public static MessageFactory forKey(MessageFactoryKey key) {
return new MessageFactory(forPayloadKey(key));
}
private final ProtobufSerializer<Envelope> envelopeSerializer;
private final MessagePayloadSerializer userMessagePayloadSerializer;
private MessageFactory(MessagePayloadSerializer userMessagePayloadSerializer) {
this.envelopeSerializer = ProtobufSerializer.forMessageGeneratedClass(Envelope.class);
this.userMessagePayloadSerializer = Objects.requireNonNull(userMessagePayloadSerializer);
}
public Message from(long checkpointId) {
return from(envelopeWithCheckpointId(checkpointId));
}
public Message from(DataInputView input) throws IOException {
return from(deserializeEnvelope(input));
}
public Message from(Address from, Address to, Object payload) {
return new SdkMessage(from, to, payload);
}
public Message from(Address from, Address to, Object payload, String cancellationToken) {
return new SdkMessage(from, to, payload, cancellationToken);
}
// -------------------------------------------------------------------------------------------------------
void copy(DataInputView source, DataOutputView target) throws IOException {
copyEnvelope(source, target);
}
private Message from(Envelope envelope) {
return new ProtobufMessage(envelope);
}
Payload serializeUserMessagePayload(Object payloadObject) {
return userMessagePayloadSerializer.serialize(payloadObject);
}
Object deserializeUserMessagePayload(ClassLoader targetClassLoader, Payload payload) {
return userMessagePayloadSerializer.deserialize(targetClassLoader, payload);
}
Object copyUserMessagePayload(ClassLoader targetClassLoader, Object payload) {
return userMessagePayloadSerializer.copy(targetClassLoader, payload);
}
void serializeEnvelope(Envelope envelope, DataOutputView target) throws IOException {
envelopeSerializer.serialize(envelope, target);
}
private Envelope deserializeEnvelope(DataInputView source) throws IOException {
return envelopeSerializer.deserialize(source);
}
private void copyEnvelope(DataInputView source, DataOutputView target) throws IOException {
envelopeSerializer.copy(source, target);
}
private static Envelope envelopeWithCheckpointId(long checkpointId) {
Checkpoint checkpoint = Checkpoint.newBuilder().setCheckpointId(checkpointId).build();
return Envelope.newBuilder().setCheckpoint(checkpoint).build();
}
private static MessagePayloadSerializer forPayloadKey(MessageFactoryKey key) {
switch (key.getType()) {
case WITH_KRYO_PAYLOADS:
return new MessagePayloadSerializerKryo();
case WITH_PROTOBUF_PAYLOADS:
return new MessagePayloadSerializerPb();
case WITH_RAW_PAYLOADS:
return new MessagePayloadSerializerRaw();
case WITH_CUSTOM_PAYLOADS:
String className =
key.getCustomPayloadSerializerClassName()
.orElseThrow(
() ->
new UnsupportedOperationException(
"WITH_CUSTOM_PAYLOADS requires custom payload serializer class name to be specified in MessageFactoryKey"));
return forCustomPayloadSerializer(className);
default:
throw new IllegalArgumentException("unknown serialization method " + key.getType());
}
}
private static MessagePayloadSerializer forCustomPayloadSerializer(String className) {
try {
Class<?> clazz =
Class.forName(className, true, Thread.currentThread().getContextClassLoader());
Constructor<?> constructor = clazz.getConstructor();
return (MessagePayloadSerializer) constructor.newInstance();
} catch (Throwable ex) {
throw new UnsupportedOperationException(
String.format("Failed to create custom payload serializer: %s", className), ex);
}
}
}
| 6,164 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/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.flink.core.message;
import java.io.IOException;
import java.util.Optional;
import java.util.OptionalLong;
import org.apache.flink.core.memory.DataOutputView;
public interface Message extends RoutableMessage {
Object payload(MessageFactory context, ClassLoader targetClassLoader);
/**
* isBarrierMessage - returns an empty optional for non barrier messages or wrapped checkpointId
* for barrier messages.
*
* <p>When this message represents a checkpoint barrier, this method returns an {@code Optional}
* of a checkpoint id that produced that barrier. For other types of messages (i.e. {@code
* Payload}) this method returns an empty {@code Optional}.
*/
OptionalLong isBarrierMessage();
Optional<String> cancellationToken();
Message copy(MessageFactory context);
void writeTo(MessageFactory context, DataOutputView target) throws IOException;
default void postApply() {}
}
| 6,165 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageTypeInformation.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.flink.core.message;
import java.util.Objects;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
public class MessageTypeInformation extends TypeInformation<Message> {
private static final long serialVersionUID = 2L;
private final MessageFactoryKey messageFactoryKey;
public MessageTypeInformation(MessageFactoryKey messageFactoryKey) {
this.messageFactoryKey = Objects.requireNonNull(messageFactoryKey);
}
@Override
public boolean isBasicType() {
return false;
}
@Override
public boolean isTupleType() {
return false;
}
@Override
public int getArity() {
return 0;
}
@Override
public int getTotalFields() {
return 0;
}
@Override
public Class<Message> getTypeClass() {
return Message.class;
}
@Override
public boolean isKeyType() {
return false;
}
@Override
public TypeSerializer<Message> createSerializer(ExecutionConfig executionConfig) {
return new MessageTypeSerializer(messageFactoryKey);
}
@Override
public String toString() {
return String.format(
"MessageTypeInformation(%s: %s",
messageFactoryKey.getType(), messageFactoryKey.getCustomPayloadSerializerClassName());
}
@Override
public boolean equals(Object o) {
return o instanceof MessageTypeInformation;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public boolean canEqual(Object o) {
return o instanceof MessageTypeInformation;
}
}
| 6,166 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessagePayloadSerializerKryo.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.flink.core.message;
import com.google.protobuf.ByteString;
import java.io.IOException;
import javax.annotation.Nonnull;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer;
import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.statefun.flink.core.generated.Payload;
public final class MessagePayloadSerializerKryo implements MessagePayloadSerializer {
private KryoSerializer<Object> kryo = new KryoSerializer<>(Object.class, new ExecutionConfig());
private DataInputDeserializer source = new DataInputDeserializer();
private DataOutputSerializer target = new DataOutputSerializer(4096);
@Override
public Payload serialize(@Nonnull Object payloadObject) {
target.clear();
try {
kryo.serialize(payloadObject, target);
} catch (IOException e) {
throw new IllegalStateException(e);
}
ByteString serializedBytes = ByteString.copyFrom(target.getSharedBuffer(), 0, target.length());
return Payload.newBuilder()
.setClassName(payloadObject.getClass().getName())
.setPayloadBytes(serializedBytes)
.build();
}
@Override
public Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload) {
source.setBuffer(payload.getPayloadBytes().asReadOnlyByteBuffer());
try {
return kryo.deserialize(source);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what) {
target.clear();
try {
kryo.serialize(what, target);
source.setBuffer(target.getSharedBuffer(), 0, target.length());
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(targetClassLoader);
try {
final ClassLoader originalKryoCl = kryo.getKryo().getClassLoader();
kryo.getKryo().setClassLoader(targetClassLoader);
try {
return kryo.deserialize(source);
} finally {
kryo.getKryo().setClassLoader(originalKryoCl);
}
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 6,167 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/RoutableMessage.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.flink.core.message;
import javax.annotation.Nullable;
import org.apache.flink.statefun.sdk.Address;
/** A message with source and target {@link Address}s. */
public interface RoutableMessage {
/**
* Gets the address of the sender.
*
* @return the address (optinal) address of the sender.
*/
@Nullable
Address source();
/**
* Gets the target address.
*
* @return the target address that this message is designated to.
*/
Address target();
}
| 6,168 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageKeySelector.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.flink.core.message;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.statefun.flink.core.common.KeyBy;
public final class MessageKeySelector implements KeySelector<Message, String> {
private static final long serialVersionUID = 1;
@Override
public String getKey(Message value) {
return KeyBy.apply(value.target());
}
}
| 6,169 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/SdkMessage.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.flink.core.message;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import javax.annotation.Nullable;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.statefun.flink.core.generated.Envelope;
import org.apache.flink.statefun.flink.core.generated.Envelope.Builder;
import org.apache.flink.statefun.flink.core.generated.EnvelopeAddress;
import org.apache.flink.statefun.sdk.Address;
final class SdkMessage implements Message {
private final Address target;
@Nullable private final Address source;
@Nullable private final String cancellationToken;
@Nullable private Envelope cachedEnvelope;
private Object payload;
SdkMessage(@Nullable Address source, Address target, Object payload) {
this(source, target, payload, null);
}
SdkMessage(
@Nullable Address source,
Address target,
Object payload,
@Nullable String cancellationToken) {
this.source = source;
this.target = Objects.requireNonNull(target);
this.payload = Objects.requireNonNull(payload);
this.cancellationToken = cancellationToken;
}
@Override
@Nullable
public Address source() {
return source;
}
@Override
public Address target() {
return target;
}
@Override
public Object payload(MessageFactory factory, ClassLoader targetClassLoader) {
if (!sameClassLoader(targetClassLoader, payload)) {
payload = factory.copyUserMessagePayload(targetClassLoader, payload);
}
return payload;
}
@Override
public OptionalLong isBarrierMessage() {
return OptionalLong.empty();
}
@Override
public Optional<String> cancellationToken() {
return Optional.ofNullable(cancellationToken);
}
@Override
public Message copy(MessageFactory factory) {
return new SdkMessage(source, target, payload, cancellationToken);
}
@Override
public void writeTo(MessageFactory factory, DataOutputView target) throws IOException {
Envelope envelope = envelope(factory);
factory.serializeEnvelope(envelope, target);
}
private Envelope envelope(MessageFactory factory) {
if (cachedEnvelope == null) {
Builder builder = Envelope.newBuilder();
if (source != null) {
builder.setSource(sdkAddressToProtobufAddress(source));
}
builder.setTarget(sdkAddressToProtobufAddress(target));
builder.setPayload(factory.serializeUserMessagePayload(payload));
if (cancellationToken != null) {
builder.setCancellationToken(cancellationToken);
}
cachedEnvelope = builder.build();
}
return cachedEnvelope;
}
private static boolean sameClassLoader(ClassLoader targetClassLoader, Object payload) {
return payload.getClass().getClassLoader() == targetClassLoader;
}
private static EnvelopeAddress sdkAddressToProtobufAddress(Address source) {
return EnvelopeAddress.newBuilder()
.setNamespace(source.type().namespace())
.setType(source.type().name())
.setId(source.id())
.build();
}
}
| 6,170 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageFactoryKey.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.flink.core.message;
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
public final class MessageFactoryKey implements Serializable {
private static final long serialVersionUID = 1L;
private final MessageFactoryType type;
private final String customPayloadSerializerClassName;
private MessageFactoryKey(MessageFactoryType type, String customPayloadSerializerClassName) {
this.type = Objects.requireNonNull(type);
this.customPayloadSerializerClassName = customPayloadSerializerClassName;
}
public static MessageFactoryKey forType(
MessageFactoryType type, String customPayloadSerializerClassName) {
return new MessageFactoryKey(type, customPayloadSerializerClassName);
}
public MessageFactoryType getType() {
return this.type;
}
public Optional<String> getCustomPayloadSerializerClassName() {
return Optional.ofNullable(customPayloadSerializerClassName);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageFactoryKey that = (MessageFactoryKey) o;
return type == that.type
&& Objects.equals(customPayloadSerializerClassName, that.customPayloadSerializerClassName);
}
@Override
public int hashCode() {
return Objects.hash(type, customPayloadSerializerClassName);
}
}
| 6,171 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessagePayloadSerializerRaw.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.flink.core.message;
import com.google.protobuf.ByteString;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.flink.statefun.flink.core.generated.Payload;
@NotThreadSafe
public class MessagePayloadSerializerRaw implements MessagePayloadSerializer {
@Override
public Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload) {
return payload.getPayloadBytes().toByteArray();
}
@Override
public Payload serialize(@Nonnull Object what) {
byte[] bytes = (byte[]) what;
ByteString bs = ByteString.copyFrom(bytes);
return Payload.newBuilder().setPayloadBytes(bs).build();
}
@Override
public Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what) {
return what;
}
}
| 6,172 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessagePayloadSerializer.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.flink.core.message;
import javax.annotation.Nonnull;
import org.apache.flink.statefun.flink.core.generated.Payload;
public interface MessagePayloadSerializer {
Payload serialize(@Nonnull Object payloadObject);
Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload);
Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what);
}
| 6,173 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/RoutableMessageBuilder.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.flink.core.message;
import java.util.Objects;
import javax.annotation.Nullable;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
/** A {@link RoutableMessage} Builder. */
public final class RoutableMessageBuilder {
public static RoutableMessageBuilder builder() {
return new RoutableMessageBuilder();
}
@Nullable private Address source;
private Address target;
private Object payload;
private RoutableMessageBuilder() {}
public RoutableMessageBuilder withTargetAddress(FunctionType functionType, String id) {
return withTargetAddress(new Address(functionType, id));
}
public RoutableMessageBuilder withTargetAddress(Address target) {
this.target = Objects.requireNonNull(target);
return this;
}
public RoutableMessageBuilder withSourceAddress(FunctionType functionType, String id) {
return withSourceAddress(new Address(functionType, id));
}
public RoutableMessageBuilder withSourceAddress(@Nullable Address from) {
this.source = from;
return this;
}
public RoutableMessageBuilder withMessageBody(Object payload) {
this.payload = Objects.requireNonNull(payload);
return this;
}
public RoutableMessage build() {
return new SdkMessage(source, target, payload);
}
}
| 6,174 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageFactoryType.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.flink.core.message;
public enum MessageFactoryType {
WITH_KRYO_PAYLOADS,
WITH_PROTOBUF_PAYLOADS,
WITH_RAW_PAYLOADS,
WITH_CUSTOM_PAYLOADS,
}
| 6,175 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessageTypeSerializer.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.flink.core.message;
import java.io.IOException;
import java.util.Objects;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSchemaCompatibility;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
public final class MessageTypeSerializer extends TypeSerializer<Message> {
private static final long serialVersionUID = 2L;
// -- configuration --
private final MessageFactoryKey messageFactoryKey;
// -- runtime --
private transient MessageFactory factory;
MessageTypeSerializer(MessageFactoryKey messageFactoryKey) {
this.messageFactoryKey = Objects.requireNonNull(messageFactoryKey);
}
@Override
public boolean isImmutableType() {
return false;
}
@Override
public TypeSerializer<Message> duplicate() {
return new MessageTypeSerializer(messageFactoryKey);
}
@Override
public Message createInstance() {
return null;
}
@Override
public Message copy(Message message) {
return message.copy(factory());
}
@Override
public Message copy(Message message, Message reuse) {
return message.copy(factory());
}
@Override
public int getLength() {
return -1;
}
@Override
public void serialize(Message message, DataOutputView dataOutputView) throws IOException {
message.writeTo(factory(), dataOutputView);
}
@Override
public Message deserialize(DataInputView dataInputView) throws IOException {
return factory().from(dataInputView);
}
@Override
public Message deserialize(Message message, DataInputView dataInputView) throws IOException {
return deserialize(dataInputView);
}
@Override
public void copy(DataInputView dataInputView, DataOutputView dataOutputView) throws IOException {
factory().copy(dataInputView, dataOutputView);
}
@Override
public boolean equals(Object o) {
return o instanceof MessageTypeSerializer;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public TypeSerializerSnapshot<Message> snapshotConfiguration() {
return new Snapshot(messageFactoryKey);
}
private MessageFactory factory() {
if (factory == null) {
factory = MessageFactory.forKey(messageFactoryKey);
}
return factory;
}
public static final class Snapshot implements TypeSerializerSnapshot<Message> {
private MessageFactoryKey messageFactoryKey;
@SuppressWarnings("unused")
public Snapshot() {}
Snapshot(MessageFactoryKey messageFactoryKey) {
this.messageFactoryKey = messageFactoryKey;
}
@VisibleForTesting
MessageFactoryKey getMessageFactoryKey() {
return messageFactoryKey;
}
@Override
public int getCurrentVersion() {
return 2;
}
@Override
public void writeSnapshot(DataOutputView dataOutputView) throws IOException {
// version 1
dataOutputView.writeUTF(messageFactoryKey.getType().name());
// added in version 2
writeNullableString(
messageFactoryKey.getCustomPayloadSerializerClassName().orElse(null), dataOutputView);
}
@Override
public void readSnapshot(int version, DataInputView dataInputView, ClassLoader classLoader)
throws IOException {
// read values and assign defaults appropriate for version 1
MessageFactoryType messageFactoryType = MessageFactoryType.valueOf(dataInputView.readUTF());
String customPayloadSerializerClassName = null;
// if at least version 2, read in the custom payload serializer class name
if (version >= 2) {
customPayloadSerializerClassName = readNullableString(dataInputView);
}
this.messageFactoryKey =
MessageFactoryKey.forType(messageFactoryType, customPayloadSerializerClassName);
}
@Override
public TypeSerializer<Message> restoreSerializer() {
return new MessageTypeSerializer(messageFactoryKey);
}
@Override
public TypeSerializerSchemaCompatibility<Message> resolveSchemaCompatibility(
TypeSerializer<Message> typeSerializer) {
if (!(typeSerializer instanceof MessageTypeSerializer)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
MessageTypeSerializer casted = (MessageTypeSerializer) typeSerializer;
if (casted.messageFactoryKey.equals(messageFactoryKey)) {
return TypeSerializerSchemaCompatibility.compatibleAsIs();
}
return TypeSerializerSchemaCompatibility.incompatible();
}
private static void writeNullableString(String value, DataOutputView out) throws IOException {
if (value != null) {
out.writeBoolean(true);
out.writeUTF(value);
} else {
out.writeBoolean(false);
}
}
private static String readNullableString(DataInputView in) throws IOException {
boolean isPresent = in.readBoolean();
if (isPresent) {
return in.readUTF();
} else {
return null;
}
}
}
}
| 6,176 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/MessagePayloadSerializerPb.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.flink.core.message;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashMap;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufReflectionUtil;
import org.apache.flink.statefun.flink.core.generated.Payload;
@NotThreadSafe
public class MessagePayloadSerializerPb implements MessagePayloadSerializer {
private final ObjectOpenHashMap<String, ObjectOpenHashMap<ClassLoader, Parser<? extends Message>>>
PARSER_CACHE = new ObjectOpenHashMap<>();
@Override
public Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload) {
try {
Parser<? extends Message> parser =
parserForClassName(targetClassLoader, payload.getClassName());
return parser.parseFrom(payload.getPayloadBytes());
} catch (InvalidProtocolBufferException | ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
@Override
public Payload serialize(@Nonnull Object what) {
final Message message = (Message) what;
final String className = what.getClass().getName();
final ByteString body = message.toByteString();
return Payload.newBuilder().setClassName(className).setPayloadBytes(body).build();
}
@Override
public Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what) {
Objects.requireNonNull(targetClassLoader);
if (!(what instanceof Message)) {
throw new IllegalStateException();
}
Message message = (Message) what;
ByteString messageBytes = message.toByteString();
try {
Parser<? extends Message> parser =
parserForClassName(targetClassLoader, what.getClass().getName());
return parser.parseFrom(messageBytes);
} catch (InvalidProtocolBufferException | ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
private Parser<? extends Message> parserForClassName(
ClassLoader userCodeClassLoader, String messageClassName) throws ClassNotFoundException {
ObjectOpenHashMap<ClassLoader, Parser<? extends Message>> classLoaders =
PARSER_CACHE.get(messageClassName);
if (classLoaders == null) {
PARSER_CACHE.put(messageClassName, classLoaders = new ObjectOpenHashMap<>());
}
Parser<? extends Message> parser = classLoaders.get(userCodeClassLoader);
if (parser == null) {
classLoaders.put(
userCodeClassLoader, parser = findParser(userCodeClassLoader, messageClassName));
}
return parser;
}
private Parser<? extends Message> findParser(
ClassLoader userCodeClassLoader, String messageClassName) throws ClassNotFoundException {
Class<? extends Message> messageType =
Class.forName(messageClassName, true, userCodeClassLoader).asSubclass(Message.class);
return ProtobufReflectionUtil.protobufParser(messageType);
}
}
| 6,177 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/message/ProtobufMessage.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.flink.core.message;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import javax.annotation.Nullable;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.statefun.flink.core.generated.Envelope;
import org.apache.flink.statefun.flink.core.generated.EnvelopeAddress;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
final class ProtobufMessage implements Message {
private final Envelope envelope;
private Address source;
private Address target;
private Object payload;
ProtobufMessage(Envelope envelope) {
this.envelope = Objects.requireNonNull(envelope);
}
@Override
@Nullable
public Address source() {
if (source != null) {
return source;
}
if ((source = protobufAddressToSdkAddress(envelope.getSource())) == null) {
return null;
}
return source;
}
@Override
public Address target() {
if (target != null) {
return target;
}
if ((target = protobufAddressToSdkAddress(envelope.getTarget())) == null) {
throw new IllegalStateException("A mandatory target address is missing");
}
return target;
}
@Override
public Object payload(MessageFactory factory, ClassLoader targetClassLoader) {
if (payload == null) {
payload = factory.deserializeUserMessagePayload(targetClassLoader, envelope.getPayload());
} else if (!sameClassLoader(targetClassLoader, payload)) {
payload = factory.copyUserMessagePayload(targetClassLoader, payload);
}
return payload;
}
@Override
public OptionalLong isBarrierMessage() {
if (!envelope.hasCheckpoint()) {
return OptionalLong.empty();
}
final long checkpointId = envelope.getCheckpoint().getCheckpointId();
return OptionalLong.of(checkpointId);
}
@Override
public Optional<String> cancellationToken() {
String token = envelope.getCancellationToken();
if (token.isEmpty()) {
return Optional.empty();
}
return Optional.of(token);
}
@Override
public Message copy(MessageFactory unused) {
return new ProtobufMessage(envelope);
}
@Override
public void writeTo(MessageFactory factory, DataOutputView target) throws IOException {
Objects.requireNonNull(target);
factory.serializeEnvelope(envelope, target);
}
private static boolean sameClassLoader(ClassLoader targetClassLoader, Object payload) {
return payload.getClass().getClassLoader() == targetClassLoader;
}
@Nullable
private static Address protobufAddressToSdkAddress(EnvelopeAddress address) {
if (address == null
|| (address.getId().isEmpty()
&& address.getNamespace().isEmpty()
&& address.getType().isEmpty())) {
return null;
}
FunctionType functionType = new FunctionType(address.getNamespace(), address.getType());
return new Address(functionType, address.getId());
}
}
| 6,178 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/PersistedStates.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.flink.core.state;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.state.ApiExtension;
import org.apache.flink.statefun.sdk.state.PersistedAppendingBuffer;
import org.apache.flink.statefun.sdk.state.PersistedStateRegistry;
import org.apache.flink.statefun.sdk.state.PersistedTable;
import org.apache.flink.statefun.sdk.state.PersistedValue;
import org.apache.flink.statefun.sdk.state.RemotePersistedValue;
public final class PersistedStates {
public static void findReflectivelyAndBind(
@Nullable Object instance, FlinkStateBinder stateBinder) {
List<?> states = findReflectively(instance);
for (Object persisted : states) {
if (persisted instanceof PersistedStateRegistry) {
PersistedStateRegistry stateRegistry = (PersistedStateRegistry) persisted;
ApiExtension.bindPersistedStateRegistry(stateRegistry, stateBinder);
} else {
stateBinder.bind(persisted);
}
}
}
private static List<?> findReflectively(@Nullable Object instance) {
PersistedStates visitor = new PersistedStates();
visitor.visit(instance);
return visitor.getPersistedStates();
}
private final List<Object> persistedStates = new ArrayList<>();
private void visit(@Nullable Object instance) {
if (instance == null) {
return;
}
for (Field field : findAnnotatedFields(instance.getClass(), Persisted.class)) {
visitField(instance, field);
}
}
private List<Object> getPersistedStates() {
return persistedStates;
}
private void visitField(@Nonnull Object instance, @Nonnull Field field) {
if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalArgumentException(
"Static persisted states are not legal in: "
+ field.getType()
+ " on "
+ instance.getClass().getName());
}
Object persistedState = getPersistedStateReflectively(instance, field);
if (persistedState == null) {
throw new IllegalStateException(
"The field " + field + " of a " + instance.getClass().getName() + " was not initialized");
}
Class<?> fieldType = field.getType();
if (isPersistedState(fieldType)) {
persistedStates.add(persistedState);
} else {
List<?> innerFields = findReflectively(persistedState);
persistedStates.addAll(innerFields);
}
}
private static boolean isPersistedState(Class<?> fieldType) {
return fieldType == PersistedValue.class
|| fieldType == PersistedTable.class
|| fieldType == PersistedAppendingBuffer.class
|| fieldType == PersistedStateRegistry.class
|| fieldType == RemotePersistedValue.class;
}
private static Object getPersistedStateReflectively(Object instance, Field persistedField) {
try {
persistedField.setAccessible(true);
return persistedField.get(instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(
"Unable access field " + persistedField.getName() + " of " + instance.getClass());
}
}
public static Iterable<Field> findAnnotatedFields(
Class<?> javaClass, Class<? extends Annotation> annotation) {
Stream<Field> fields =
definedFields(javaClass).filter(field -> field.getAnnotation(annotation) != null);
return fields::iterator;
}
private static Stream<Field> definedFields(Class<?> javaClass) {
if (javaClass == null || javaClass == Object.class) {
return Stream.empty();
}
Stream<Field> selfMethods = Arrays.stream(javaClass.getDeclaredFields());
Stream<Field> superMethods = definedFields(javaClass.getSuperclass());
return Stream.concat(selfMethods, superMethods);
}
}
| 6,179 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/FlinkAppendingBufferAccessor.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.flink.core.state;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.statefun.sdk.state.AppendingBufferAccessor;
final class FlinkAppendingBufferAccessor<E> implements AppendingBufferAccessor<E> {
private final ListState<E> handle;
FlinkAppendingBufferAccessor(ListState<E> handle) {
this.handle = Objects.requireNonNull(handle);
}
@Override
public void append(@Nonnull E element) {
try {
this.handle.add(element);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void appendAll(@Nonnull List<E> elements) {
try {
this.handle.addAll(elements);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void replaceWith(@Nonnull List<E> elements) {
try {
this.handle.update(elements);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Nonnull
@Override
public Iterable<E> view() {
try {
return this.handle.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void clear() {
try {
this.handle.clear();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 6,180 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/FlinkStateBinder.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.flink.core.state;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.di.Inject;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.state.Accessor;
import org.apache.flink.statefun.sdk.state.ApiExtension;
import org.apache.flink.statefun.sdk.state.AppendingBufferAccessor;
import org.apache.flink.statefun.sdk.state.PersistedAppendingBuffer;
import org.apache.flink.statefun.sdk.state.PersistedTable;
import org.apache.flink.statefun.sdk.state.PersistedValue;
import org.apache.flink.statefun.sdk.state.RemotePersistedValue;
import org.apache.flink.statefun.sdk.state.StateBinder;
import org.apache.flink.statefun.sdk.state.TableAccessor;
/**
* A {@link StateBinder} that binds persisted state objects to Flink state for a specific {@link
* FunctionType}.
*/
public final class FlinkStateBinder extends StateBinder {
private final State state;
private final FunctionType functionType;
@Inject
public FlinkStateBinder(State state, FunctionType functionType) {
this.state = Objects.requireNonNull(state);
this.functionType = Objects.requireNonNull(functionType);
}
@Override
public void bind(Object stateObject) {
if (stateObject instanceof PersistedValue) {
bindValue((PersistedValue<?>) stateObject);
} else if (stateObject instanceof PersistedTable) {
bindTable((PersistedTable<?, ?>) stateObject);
} else if (stateObject instanceof PersistedAppendingBuffer) {
bindAppendingBuffer((PersistedAppendingBuffer<?>) stateObject);
} else if (stateObject instanceof RemotePersistedValue) {
bindRemoteValue((RemotePersistedValue) stateObject);
} else {
throw new IllegalArgumentException("Unknown persisted state object " + stateObject);
}
}
private void bindValue(PersistedValue<?> persistedValue) {
Accessor<?> accessor = state.createFlinkStateAccessor(functionType, persistedValue);
setAccessorRaw(persistedValue, accessor);
}
private void bindTable(PersistedTable<?, ?> persistedTable) {
TableAccessor<?, ?> accessor =
state.createFlinkStateTableAccessor(functionType, persistedTable);
setAccessorRaw(persistedTable, accessor);
}
private void bindAppendingBuffer(PersistedAppendingBuffer<?> persistedAppendingBuffer) {
AppendingBufferAccessor<?> accessor =
state.createFlinkStateAppendingBufferAccessor(functionType, persistedAppendingBuffer);
setAccessorRaw(persistedAppendingBuffer, accessor);
}
private void bindRemoteValue(RemotePersistedValue remotePersistedValue) {
Accessor<byte[]> accessor =
state.createFlinkRemoteStateAccessor(functionType, remotePersistedValue);
setAccessorRaw(remotePersistedValue, accessor);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void setAccessorRaw(PersistedTable<?, ?> persistedTable, TableAccessor<?, ?> accessor) {
ApiExtension.setPersistedTableAccessor((PersistedTable) persistedTable, accessor);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static void setAccessorRaw(PersistedValue<?> persistedValue, Accessor<?> accessor) {
ApiExtension.setPersistedValueAccessor((PersistedValue) persistedValue, accessor);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static void setAccessorRaw(
PersistedAppendingBuffer<?> persistedAppendingBuffer, AppendingBufferAccessor<?> accessor) {
ApiExtension.setPersistedAppendingBufferAccessor(
(PersistedAppendingBuffer) persistedAppendingBuffer, accessor);
}
private static void setAccessorRaw(
RemotePersistedValue remotePersistedValue, Accessor<byte[]> accessor) {
ApiExtension.setRemotePersistedValueAccessor(remotePersistedValue, accessor);
}
}
| 6,181 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/ExpirationUtil.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.flink.core.state;
import org.apache.flink.api.common.state.StateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.StateTtlConfig.Builder;
import org.apache.flink.api.common.state.StateTtlConfig.StateVisibility;
import org.apache.flink.api.common.state.StateTtlConfig.TtlTimeCharacteristic;
import org.apache.flink.api.common.state.StateTtlConfig.UpdateType;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.statefun.sdk.state.Expiration;
import org.apache.flink.statefun.sdk.state.Expiration.Mode;
final class ExpirationUtil {
private ExpirationUtil() {}
static void configureStateTtl(StateDescriptor<?, ?> handle, Expiration expiration) {
if (expiration.mode() == Mode.NONE) {
return;
}
StateTtlConfig ttlConfig = from(expiration);
handle.enableTimeToLive(ttlConfig);
}
private static StateTtlConfig from(Expiration expiration) {
final long millis = expiration.duration().toMillis();
Builder builder = StateTtlConfig.newBuilder(Time.milliseconds(millis));
builder.setTtlTimeCharacteristic(TtlTimeCharacteristic.ProcessingTime);
builder.setStateVisibility(StateVisibility.NeverReturnExpired);
switch (expiration.mode()) {
case AFTER_WRITE:
{
builder.setUpdateType(UpdateType.OnCreateAndWrite);
break;
}
case AFTER_READ_OR_WRITE:
{
builder.setUpdateType(UpdateType.OnReadAndWrite);
break;
}
default:
throw new IllegalArgumentException("Unknown expiration mode " + expiration.mode());
}
return builder.build();
}
}
| 6,182 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/FlinkTableAccessor.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.flink.core.state;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.statefun.sdk.state.TableAccessor;
final class FlinkTableAccessor<K, V> implements TableAccessor<K, V> {
private final MapState<K, V> handle;
FlinkTableAccessor(MapState<K, V> handle) {
this.handle = Objects.requireNonNull(handle);
}
@Override
public void set(K key, V value) {
try {
handle.put(key, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public V get(K key) {
try {
return handle.get(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void remove(K key) {
try {
handle.remove(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Iterable<Map.Entry<K, V>> entries() {
try {
return handle.entries();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Iterable<K> keys() {
try {
return handle.keys();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Iterable<V> values() {
try {
return handle.values();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void clear() {
handle.clear();
}
}
| 6,183 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/FlinkValueAccessor.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.flink.core.state;
import java.io.IOException;
import java.util.Objects;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.statefun.sdk.state.Accessor;
final class FlinkValueAccessor<T> implements Accessor<T> {
private final ValueState<T> handle;
FlinkValueAccessor(ValueState<T> handle) {
this.handle = Objects.requireNonNull(handle);
}
@Override
public void set(T value) {
try {
if (value == null) {
handle.clear();
} else {
handle.update(value);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public T get() {
try {
return handle.value();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void clear() {
handle.clear();
}
}
| 6,184 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/FlinkState.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.flink.core.state;
import static org.apache.flink.statefun.flink.core.state.ExpirationUtil.configureStateTtl;
import java.util.Objects;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.runtime.state.KeyedStateBackend;
import org.apache.flink.statefun.flink.core.common.KeyBy;
import org.apache.flink.statefun.flink.core.di.Inject;
import org.apache.flink.statefun.flink.core.di.Label;
import org.apache.flink.statefun.flink.core.types.DynamicallyRegisteredTypes;
import org.apache.flink.statefun.flink.core.types.remote.RemoteValueTypeInfo;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.state.Accessor;
import org.apache.flink.statefun.sdk.state.AppendingBufferAccessor;
import org.apache.flink.statefun.sdk.state.PersistedAppendingBuffer;
import org.apache.flink.statefun.sdk.state.PersistedTable;
import org.apache.flink.statefun.sdk.state.PersistedValue;
import org.apache.flink.statefun.sdk.state.RemotePersistedValue;
import org.apache.flink.statefun.sdk.state.TableAccessor;
public final class FlinkState implements State {
private final RuntimeContext runtimeContext;
private final KeyedStateBackend<Object> keyedStateBackend;
private final DynamicallyRegisteredTypes types;
@Inject
public FlinkState(
@Label("runtime-context") RuntimeContext runtimeContext,
@Label("keyed-state-backend") KeyedStateBackend<Object> keyedStateBackend,
DynamicallyRegisteredTypes types) {
this.runtimeContext = Objects.requireNonNull(runtimeContext);
this.keyedStateBackend = Objects.requireNonNull(keyedStateBackend);
this.types = Objects.requireNonNull(types);
}
@Override
public <T> Accessor<T> createFlinkStateAccessor(
FunctionType functionType, PersistedValue<T> persistedValue) {
TypeInformation<T> typeInfo = types.registerType(persistedValue.type());
String stateName = flinkStateName(functionType, persistedValue.name());
ValueStateDescriptor<T> descriptor = new ValueStateDescriptor<>(stateName, typeInfo);
configureStateTtl(descriptor, persistedValue.expiration());
ValueState<T> handle = runtimeContext.getState(descriptor);
return new FlinkValueAccessor<>(handle);
}
@Override
public <K, V> TableAccessor<K, V> createFlinkStateTableAccessor(
FunctionType functionType, PersistedTable<K, V> persistedTable) {
MapStateDescriptor<K, V> descriptor =
new MapStateDescriptor<>(
flinkStateName(functionType, persistedTable.name()),
types.registerType(persistedTable.keyType()),
types.registerType(persistedTable.valueType()));
configureStateTtl(descriptor, persistedTable.expiration());
MapState<K, V> handle = runtimeContext.getMapState(descriptor);
return new FlinkTableAccessor<>(handle);
}
@Override
public <E> AppendingBufferAccessor<E> createFlinkStateAppendingBufferAccessor(
FunctionType functionType, PersistedAppendingBuffer<E> persistedAppendingBuffer) {
ListStateDescriptor<E> descriptor =
new ListStateDescriptor<>(
flinkStateName(functionType, persistedAppendingBuffer.name()),
types.registerType(persistedAppendingBuffer.elementType()));
configureStateTtl(descriptor, persistedAppendingBuffer.expiration());
ListState<E> handle = runtimeContext.getListState(descriptor);
return new FlinkAppendingBufferAccessor<>(handle);
}
@Override
public Accessor<byte[]> createFlinkRemoteStateAccessor(
FunctionType functionType, RemotePersistedValue remotePersistedValue) {
// Note: we do not need to use the DynamicallyRegisteredTypes registry to retrieve the type info
// for this specific
// case, because remote values are always handled simply as primitive byte arrays in Flink
TypeInformation<byte[]> typeInfo = new RemoteValueTypeInfo(remotePersistedValue.type());
String stateName = flinkStateName(functionType, remotePersistedValue.name());
ValueStateDescriptor<byte[]> descriptor = new ValueStateDescriptor<>(stateName, typeInfo);
configureStateTtl(descriptor, remotePersistedValue.expiration());
ValueState<byte[]> handle = runtimeContext.getState(descriptor);
return new FlinkValueAccessor<>(handle);
}
@Override
public void setCurrentKey(Address address) {
keyedStateBackend.setCurrentKey(KeyBy.apply(address));
}
public static String flinkStateName(FunctionType functionType, String name) {
return String.format("%s.%s.%s", functionType.namespace(), functionType.name(), name);
}
}
| 6,185 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/state/State.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.flink.core.state;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.state.Accessor;
import org.apache.flink.statefun.sdk.state.AppendingBufferAccessor;
import org.apache.flink.statefun.sdk.state.PersistedAppendingBuffer;
import org.apache.flink.statefun.sdk.state.PersistedTable;
import org.apache.flink.statefun.sdk.state.PersistedValue;
import org.apache.flink.statefun.sdk.state.RemotePersistedValue;
import org.apache.flink.statefun.sdk.state.TableAccessor;
public interface State {
<T> Accessor<T> createFlinkStateAccessor(
FunctionType functionType, PersistedValue<T> persistedValue);
<K, V> TableAccessor<K, V> createFlinkStateTableAccessor(
FunctionType functionType, PersistedTable<K, V> persistedTable);
<E> AppendingBufferAccessor<E> createFlinkStateAppendingBufferAccessor(
FunctionType functionType, PersistedAppendingBuffer<E> persistedAppendingBuffer);
Accessor<byte[]> createFlinkRemoteStateAccessor(
FunctionType functionType, RemotePersistedValue remotePersistedValue);
void setCurrentKey(Address address);
}
| 6,186 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/exceptions/StatefulFunctionsInvalidConfigException.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.flink.core.exceptions;
import org.apache.flink.configuration.ConfigOption;
public final class StatefulFunctionsInvalidConfigException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
public StatefulFunctionsInvalidConfigException(ConfigOption<?> invalidConfig, String message) {
super(String.format("Invalid configuration: %s; %s", invalidConfig.key(), message));
}
}
| 6,187 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackUnionOperatorFactory.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.flink.core.feedback;
import java.util.Objects;
import java.util.OptionalLong;
import org.apache.flink.api.common.operators.MailboxExecutor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.statefun.flink.core.StatefulFunctionsConfig;
import org.apache.flink.statefun.flink.core.common.SerializableFunction;
import org.apache.flink.streaming.api.operators.*;
public final class FeedbackUnionOperatorFactory<E>
implements OneInputStreamOperatorFactory<E, E>, YieldingOperatorFactory<E> {
private static final long serialVersionUID = 1;
private final StatefulFunctionsConfig configuration;
private final FeedbackKey<E> feedbackKey;
private final SerializableFunction<E, OptionalLong> isBarrierMessage;
private final SerializableFunction<E, ?> keySelector;
private transient MailboxExecutor mailboxExecutor;
public FeedbackUnionOperatorFactory(
StatefulFunctionsConfig configuration,
FeedbackKey<E> feedbackKey,
SerializableFunction<E, OptionalLong> isBarrierMessage,
SerializableFunction<E, ?> keySelector) {
this.feedbackKey = Objects.requireNonNull(feedbackKey);
this.isBarrierMessage = Objects.requireNonNull(isBarrierMessage);
this.keySelector = Objects.requireNonNull(keySelector);
this.configuration = Objects.requireNonNull(configuration);
}
@Override
@SuppressWarnings("unchecked")
public <T extends StreamOperator<E>> T createStreamOperator(
StreamOperatorParameters<E> streamOperatorParameters) {
final TypeSerializer<E> serializer =
streamOperatorParameters
.getStreamConfig()
.getTypeSerializerIn(
0, streamOperatorParameters.getContainingTask().getUserCodeClassLoader());
FeedbackUnionOperator<E> op =
new FeedbackUnionOperator<>(
feedbackKey,
isBarrierMessage,
keySelector,
configuration.getFeedbackBufferSize().getBytes(),
serializer,
mailboxExecutor,
streamOperatorParameters.getProcessingTimeService());
op.setup(
streamOperatorParameters.getContainingTask(),
streamOperatorParameters.getStreamConfig(),
streamOperatorParameters.getOutput());
return (T) op;
}
@Override
public void setMailboxExecutor(MailboxExecutor mailboxExecutor) {
this.mailboxExecutor =
Objects.requireNonNull(mailboxExecutor, "Mailbox executor can't be NULL");
}
@Override
public void setChainingStrategy(ChainingStrategy chainingStrategy) {
// ignored
}
@Override
public ChainingStrategy getChainingStrategy() {
return ChainingStrategy.ALWAYS;
}
@Override
public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) {
return FeedbackUnionOperator.class;
}
}
| 6,188 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackChannelBroker.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.flink.core.feedback;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* HandOffChannelBroker.
*
* <p>It is used together with the co-location constrain so that two tasks can access the same
* "hand-off" channel, and communicate directly (not via the network stack) by simply passing
* references in one direction.
*
* <p>To obtain a feedback channel one must first obtain an {@link SubtaskFeedbackKey} and simply
* call {@link #get()}. A channel is removed from this broker on a call to {@link
* FeedbackChannel#close()}.
*/
public final class FeedbackChannelBroker {
private static final FeedbackChannelBroker INSTANCE = new FeedbackChannelBroker();
private final ConcurrentHashMap<SubtaskFeedbackKey<?>, FeedbackChannel<?>> channels =
new ConcurrentHashMap<>();
public static FeedbackChannelBroker get() {
return INSTANCE;
}
@SuppressWarnings({"unchecked"})
public <V> FeedbackChannel<V> getChannel(SubtaskFeedbackKey<V> key) {
Objects.requireNonNull(key);
FeedbackChannel<?> channel = channels.computeIfAbsent(key, FeedbackChannelBroker::newChannel);
return (FeedbackChannel<V>) channel;
}
@SuppressWarnings("resource")
void removeChannel(SubtaskFeedbackKey<?> key) {
channels.remove(key);
}
private static <V> FeedbackChannel<V> newChannel(SubtaskFeedbackKey<V> key) {
FeedbackQueue<V> queue = new LockFreeBatchFeedbackQueue<>();
return new FeedbackChannel<>(key, queue);
}
}
| 6,189 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/SubtaskFeedbackKey.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.flink.core.feedback;
import java.io.Serializable;
import java.util.Objects;
/** A FeedbackKey bounded to a subtask index. */
@SuppressWarnings("unused")
public final class SubtaskFeedbackKey<V> implements Serializable {
private static final long serialVersionUID = 1;
private final String pipelineName;
private final int subtaskIndex;
private final long invocationId;
private final int attemptId;
SubtaskFeedbackKey(String pipeline, long invocationId, int subtaskIndex, int attemptId) {
this.pipelineName = Objects.requireNonNull(pipeline);
this.invocationId = invocationId;
this.subtaskIndex = subtaskIndex;
this.attemptId = attemptId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubtaskFeedbackKey<?> that = (SubtaskFeedbackKey<?>) o;
return subtaskIndex == that.subtaskIndex
&& invocationId == that.invocationId
&& attemptId == that.attemptId
&& Objects.equals(pipelineName, that.pipelineName);
}
@Override
public int hashCode() {
return Objects.hash(pipelineName, subtaskIndex, invocationId, attemptId);
}
}
| 6,190 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackConsumer.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.flink.core.feedback;
/** HandOffConsumer. */
@FunctionalInterface
public interface FeedbackConsumer<T> {
void processFeedback(T element) throws Exception;
}
| 6,191 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackKey.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.flink.core.feedback;
import java.io.Serializable;
import java.util.Objects;
/** A FeedbackKey without runtime information. */
public final class FeedbackKey<V> implements Serializable {
private static final long serialVersionUID = 1;
private final String pipelineName;
private final long invocationId;
public FeedbackKey(String pipelineName, long invocationId) {
this.pipelineName = Objects.requireNonNull(pipelineName);
this.invocationId = invocationId;
}
public SubtaskFeedbackKey<V> withSubTaskIndex(int subTaskIndex, int attemptId) {
return new SubtaskFeedbackKey<>(pipelineName, invocationId, subTaskIndex, attemptId);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeedbackKey<?> that = (FeedbackKey<?>) o;
return invocationId == that.invocationId && Objects.equals(pipelineName, that.pipelineName);
}
@Override
public int hashCode() {
return Objects.hash(pipelineName, invocationId);
}
public String asColocationKey() {
return String.format("CO-LOCATION/%s/%d", pipelineName, invocationId);
}
}
| 6,192 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/LockFreeBatchFeedbackQueue.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.flink.core.feedback;
import java.util.Deque;
import org.apache.flink.statefun.flink.core.queue.Locks;
import org.apache.flink.statefun.flink.core.queue.MpscQueue;
public final class LockFreeBatchFeedbackQueue<ElementT> implements FeedbackQueue<ElementT> {
private static final int INITIAL_BUFFER_SIZE = 32 * 1024; // 32k
private final MpscQueue<ElementT> queue = new MpscQueue<>(INITIAL_BUFFER_SIZE, Locks.spinLock());
@Override
public boolean addAndCheckIfWasEmpty(ElementT element) {
final int size = queue.add(element);
return size == 1;
}
@Override
public Deque<ElementT> drainAll() {
return queue.drainAll();
}
}
| 6,193 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackUnionOperator.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.flink.core.feedback;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.concurrent.Executor;
import org.apache.flink.api.common.operators.MailboxExecutor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.state.KeyGroupStatePartitionStreamProvider;
import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.statefun.flink.core.common.MailboxExecutorFacade;
import org.apache.flink.statefun.flink.core.common.SerializableFunction;
import org.apache.flink.statefun.flink.core.logger.Loggers;
import org.apache.flink.statefun.flink.core.logger.UnboundedFeedbackLogger;
import org.apache.flink.statefun.flink.core.logger.UnboundedFeedbackLoggerFactory;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.ChainingStrategy;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.util.IOUtils;
public final class FeedbackUnionOperator<T> extends AbstractStreamOperator<T>
implements FeedbackConsumer<T>, OneInputStreamOperator<T, T> {
private static final long serialVersionUID = 1L;
// -- configuration
private final FeedbackKey<T> feedbackKey;
private final SerializableFunction<T, OptionalLong> isBarrierMessage;
private final SerializableFunction<T, ?> keySelector;
private final long totalMemoryUsedForFeedbackCheckpointing;
private final TypeSerializer<T> elementSerializer;
// -- runtime
private transient Checkpoints<T> checkpoints;
private transient boolean closedOrDisposed;
private transient MailboxExecutor mailboxExecutor;
private transient StreamRecord<T> reusable;
FeedbackUnionOperator(
FeedbackKey<T> feedbackKey,
SerializableFunction<T, OptionalLong> isBarrierMessage,
SerializableFunction<T, ?> keySelector,
long totalMemoryUsedForFeedbackCheckpointing,
TypeSerializer<T> elementSerializer,
MailboxExecutor mailboxExecutor,
ProcessingTimeService processingTimeService) {
this.feedbackKey = Objects.requireNonNull(feedbackKey);
this.isBarrierMessage = Objects.requireNonNull(isBarrierMessage);
this.keySelector = Objects.requireNonNull(keySelector);
this.totalMemoryUsedForFeedbackCheckpointing = totalMemoryUsedForFeedbackCheckpointing;
this.elementSerializer = Objects.requireNonNull(elementSerializer);
this.mailboxExecutor = Objects.requireNonNull(mailboxExecutor);
this.chainingStrategy = ChainingStrategy.ALWAYS;
// Even though this operator does not use the processing
// time service, AbstractStreamOperator requires this
// field is non-null, otherwise we get a NullPointerException
super.processingTimeService = processingTimeService;
}
// ------------------------------------------------------------------------------------------------------------------
// API
// ------------------------------------------------------------------------------------------------------------------
@Override
public void processElement(StreamRecord<T> streamRecord) {
sendDownstream(streamRecord.getValue());
}
@Override
public void processFeedback(T element) {
if (closedOrDisposed) {
return;
}
OptionalLong maybeCheckpoint = isBarrierMessage.apply(element);
if (maybeCheckpoint.isPresent()) {
checkpoints.commitCheckpointsUntil(maybeCheckpoint.getAsLong());
} else {
sendDownstream(element);
checkpoints.append(element);
}
}
@Override
public void initializeState(StateInitializationContext context) throws Exception {
super.initializeState(context);
final IOManager ioManager = getContainingTask().getEnvironment().getIOManager();
final int maxParallelism = getRuntimeContext().getMaxNumberOfParallelSubtasks();
this.reusable = new StreamRecord<>(null);
//
// Initialize the unbounded feedback logger
//
@SuppressWarnings("unchecked")
UnboundedFeedbackLoggerFactory<T> feedbackLoggerFactory =
(UnboundedFeedbackLoggerFactory<T>)
Loggers.unboundedSpillableLoggerFactory(
ioManager,
maxParallelism,
totalMemoryUsedForFeedbackCheckpointing,
elementSerializer,
keySelector);
this.checkpoints = new Checkpoints<>(feedbackLoggerFactory::create);
//
// we first must reply previously check-pointed envelopes before we start
// processing any new envelopes.
//
UnboundedFeedbackLogger<T> logger = feedbackLoggerFactory.create();
for (KeyGroupStatePartitionStreamProvider keyedStateInput : context.getRawKeyedStateInputs()) {
logger.replyLoggedEnvelops(keyedStateInput.getStream(), this);
}
//
// now we can start processing new messages. We do so by registering ourselves as a
// FeedbackConsumer
//
registerFeedbackConsumer(new MailboxExecutorFacade(mailboxExecutor, "Feedback Consumer"));
}
@Override
public void snapshotState(StateSnapshotContext context) throws Exception {
super.snapshotState(context);
checkpoints.startLogging(context.getCheckpointId(), context.getRawKeyedOperatorStateOutput());
}
@Override
protected boolean isUsingCustomRawKeyedState() {
return true;
}
@Override
public void close() throws Exception {
closeInternally();
super.close();
}
// ------------------------------------------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------------------------------------------
private void closeInternally() {
IOUtils.closeQuietly(checkpoints);
checkpoints = null;
closedOrDisposed = true;
}
private void registerFeedbackConsumer(Executor mailboxExecutor) {
final int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
final int attemptNum = getRuntimeContext().getAttemptNumber();
final SubtaskFeedbackKey<T> key = feedbackKey.withSubTaskIndex(indexOfThisSubtask, attemptNum);
FeedbackChannelBroker broker = FeedbackChannelBroker.get();
FeedbackChannel<T> channel = broker.getChannel(key);
channel.registerConsumer(this, mailboxExecutor);
}
private void sendDownstream(T element) {
reusable.replace(element);
output.collect(reusable);
}
}
| 6,194 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackChannel.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.flink.core.feedback;
import java.io.Closeable;
import java.util.Deque;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.flink.util.IOUtils;
/** Single producer, single consumer channel. */
public final class FeedbackChannel<T> implements Closeable {
/** The key that used to identify this channel. */
private final SubtaskFeedbackKey<T> key;
/** The underlying queue used to hold the feedback results. */
private final FeedbackQueue<T> queue;
/** A single registered consumer */
private final AtomicReference<ConsumerTask<T>> consumerRef = new AtomicReference<>();
FeedbackChannel(SubtaskFeedbackKey<T> key, FeedbackQueue<T> queue) {
this.key = Objects.requireNonNull(key);
this.queue = Objects.requireNonNull(queue);
}
// --------------------------------------------------------------------------------------------------------------
// API
// --------------------------------------------------------------------------------------------------------------
/** Adds a feedback result to this channel. */
public void put(T value) {
if (!queue.addAndCheckIfWasEmpty(value)) {
// successfully added @value into the queue, but the queue wasn't (atomically) drained yet,
// so there is nothing more to do.
return;
}
@SuppressWarnings("resource")
final ConsumerTask<T> consumer = consumerRef.get();
if (consumer == null) {
// the queue has become non empty at the first time, yet at the same time the (single)
// consumer has not yet registered, so there is nothing to do.
// once the consumer would register a drain would be scheduled for the first time.
return;
}
// the queue was previously empty, and now it is not, therefore we schedule a drain.
consumer.scheduleDrainAll();
}
/**
* Register a feedback iteration consumer
*
* @param consumer the feedback events consumer.
* @param executor the executor to schedule feedback consumption on.
*/
void registerConsumer(final FeedbackConsumer<T> consumer, Executor executor) {
Objects.requireNonNull(consumer);
ConsumerTask<T> consumerTask = new ConsumerTask<>(executor, consumer, queue);
if (!this.consumerRef.compareAndSet(null, consumerTask)) {
throw new IllegalStateException("There can be only a single consumer in a FeedbackChannel.");
}
// we must try to drain the underlying queue on registration (by scheduling the consumerTask)
// because
// the consumer might be registered after the producer has already started producing data into
// the feedback channel.
consumerTask.scheduleDrainAll();
}
// --------------------------------------------------------------------------------------------------------------
// Internal
// --------------------------------------------------------------------------------------------------------------
/** Closes this channel. */
@Override
public void close() {
ConsumerTask<T> consumer = consumerRef.getAndSet(null);
IOUtils.closeQuietly(consumer);
// remove this channel.
FeedbackChannelBroker broker = FeedbackChannelBroker.get();
broker.removeChannel(key);
}
private static final class ConsumerTask<T> implements Runnable, Closeable {
private final Executor executor;
private final FeedbackConsumer<T> consumer;
private final FeedbackQueue<T> queue;
ConsumerTask(Executor executor, FeedbackConsumer<T> consumer, FeedbackQueue<T> queue) {
this.executor = Objects.requireNonNull(executor);
this.consumer = Objects.requireNonNull(consumer);
this.queue = Objects.requireNonNull(queue);
}
void scheduleDrainAll() {
executor.execute(this);
}
@Override
public void run() {
final Deque<T> buffer = queue.drainAll();
try {
T element;
while ((element = buffer.pollFirst()) != null) {
consumer.processFeedback(element);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {}
}
}
| 6,195 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackQueue.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.flink.core.feedback;
import java.util.Deque;
/**
* HandOffQueue - is a single producer single consumer (spsc) queue that supports adding and
* draining atomically.
*
* <p>Implementors of this queue supports atomic addition operation (via {@link
* #addAndCheckIfWasEmpty(Object)} and atomic, bulk retrieving of the content of this queue (via
* {@link #drainAll()})}.
*
* @param <ElementT> element type that is stored in this queue.
*/
interface FeedbackQueue<ElementT> {
/**
* Adds an element to the queue atomically.
*
* @param element the element to add to the queue.
* @return true, if prior to this addition the queue was empty.
*/
boolean addAndCheckIfWasEmpty(ElementT element);
/**
* Atomically grabs all that elements of this queue.
*
* @return the elements present at the queue at the moment of this operation.
*/
Deque<ElementT> drainAll();
}
| 6,196 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/FeedbackSinkOperator.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.flink.core.feedback;
import java.util.Objects;
import java.util.function.LongFunction;
import org.apache.flink.metrics.MeterView;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.util.IOUtils;
/** IterationSinkOperator. */
public final class FeedbackSinkOperator<V> extends AbstractStreamOperator<Void>
implements OneInputStreamOperator<V, Void> {
private static final long serialVersionUID = 1;
// ----- configuration -----
private final FeedbackKey<V> key;
private final LongFunction<V> barrierSentinelSupplier;
// ----- runtime -----
private transient FeedbackChannel<V> channel;
private transient SimpleCounter totalProduced;
public FeedbackSinkOperator(FeedbackKey<V> key, LongFunction<V> barrierSentinelSupplier) {
this.key = Objects.requireNonNull(key);
this.barrierSentinelSupplier = Objects.requireNonNull(barrierSentinelSupplier);
}
// ----------------------------------------------------------------------------------------------------------
// Runtime
// ----------------------------------------------------------------------------------------------------------
@Override
public void processElement(StreamRecord<V> record) {
V value = record.getValue();
channel.put(value);
totalProduced.inc();
}
// ----------------------------------------------------------------------------------------------------------
// Operator lifecycle
// ----------------------------------------------------------------------------------------------------------
@Override
public void open() throws Exception {
super.open();
final int indexOfThisSubtask = getRuntimeContext().getIndexOfThisSubtask();
final int attemptNum = getRuntimeContext().getAttemptNumber();
final SubtaskFeedbackKey<V> key = this.key.withSubTaskIndex(indexOfThisSubtask, attemptNum);
FeedbackChannelBroker broker = FeedbackChannelBroker.get();
this.channel = broker.getChannel(key);
// metrics
MetricGroup metrics = getRuntimeContext().getMetricGroup();
SimpleCounter produced = metrics.counter("produced", new SimpleCounter());
metrics.meter("producedRate", new MeterView(produced, 60));
this.totalProduced = produced;
}
@Override
public void prepareSnapshotPreBarrier(long checkpointId) throws Exception {
super.prepareSnapshotPreBarrier(checkpointId);
V sentinel = barrierSentinelSupplier.apply(checkpointId);
channel.put(sentinel);
}
@Override
public void close() throws Exception {
IOUtils.closeQuietly(channel);
super.close();
}
}
| 6,197 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/feedback/Checkpoints.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.flink.core.feedback;
import java.io.OutputStream;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Supplier;
import org.apache.flink.statefun.flink.core.logger.FeedbackLogger;
import org.apache.flink.util.IOUtils;
final class Checkpoints<T> implements AutoCloseable {
private final Supplier<? extends FeedbackLogger<T>> feedbackLoggerFactory;
private final TreeMap<Long, FeedbackLogger<T>> uncompletedCheckpoints = new TreeMap<>();
Checkpoints(Supplier<? extends FeedbackLogger<T>> feedbackLoggerFactory) {
this.feedbackLoggerFactory = Objects.requireNonNull(feedbackLoggerFactory);
}
public void startLogging(long checkpointId, OutputStream outputStream) {
FeedbackLogger<T> logger = feedbackLoggerFactory.get();
logger.startLogging(outputStream);
uncompletedCheckpoints.put(checkpointId, logger);
}
public void append(T element) {
for (FeedbackLogger<T> logger : uncompletedCheckpoints.values()) {
logger.append(element);
}
}
public void commitCheckpointsUntil(long checkpointId) {
SortedMap<Long, FeedbackLogger<T>> completedCheckpoints =
uncompletedCheckpoints.headMap(checkpointId, true);
completedCheckpoints.values().forEach(FeedbackLogger::commit);
completedCheckpoints.clear();
}
@Override
public void close() {
IOUtils.closeAllQuietly(uncompletedCheckpoints.values());
uncompletedCheckpoints.clear();
}
}
| 6,198 |
0 | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core | Create_ds/flink-statefun/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/ManagingResources.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.flink.core.common;
import org.apache.flink.annotation.Internal;
@Internal
public interface ManagingResources {
/**
* This method would be called by the runtime on shutdown, and indicates that this is the time to
* free up any resources managed by this class.
*/
void shutdown();
}
| 6,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.