index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/mantis/mantis-runtime/src/test/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/test/java/io/mantisrx/runtime/executor/ParameterDefinitionTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.executor;
import io.mantisrx.runtime.parameter.Parameter;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import io.mantisrx.runtime.parameter.ParameterUtils;
import io.mantisrx.runtime.parameter.type.EnumCSVParameter;
import io.mantisrx.runtime.parameter.type.EnumParameter;
import io.mantisrx.runtime.parameter.type.StringParameter;
import io.mantisrx.runtime.parameter.validator.Validators;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class ParameterDefinitionTest {
@Test
public void emptyCheck() {
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
Map<String, Parameter> parameters = new HashMap<>();
ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
}
@Test(expected = IllegalArgumentException.class)
public void missingRequiredParameter() {
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("foo", new StringParameter()
.name("foo")
.required()
.validator(Validators.<String>alwaysPass())
.build());
Map<String, Parameter> parameters = new HashMap<>();
ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
}
@Test
public void singleRequiredParameterCheck() {
Map<String, Object> parameterState = new HashMap<>();
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("foo", new StringParameter()
.name("foo")
.required()
.validator(Validators.<String>alwaysPass())
.build());
Map<String, Parameter> parameters = new HashMap<>();
parameters.put("foo", new Parameter("foo", "test"));
parameterState = ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
Assert.assertEquals(1, parameterState.size());
Assert.assertEquals(true, parameterState.containsKey("foo"));
Assert.assertEquals("test", parameterState.get("foo"));
}
@Test
public void singleRequiredSingleNonRequiredParameterCheck() {
Map<String, Object> parameterState = new HashMap<>();
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("required", new StringParameter()
.name("required")
.required()
.validator(Validators.<String>alwaysPass())
.build());
parameterDefinitions.put("nonRequired", new StringParameter()
.name("nonRequired")
.validator(Validators.<String>alwaysPass())
.build());
Map<String, Parameter> parameters = new HashMap<>();
parameters.put("required", new Parameter("required", "test"));
parameterState = ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
Assert.assertEquals(1, parameterState.size());
Assert.assertEquals(true, parameterState.containsKey("required"));
Assert.assertEquals("test", parameterState.get("required"));
}
@Test
public void testEnumParameter() {
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("foo", new EnumParameter<>(TestEnum.class)
.name("foo")
.required()
.validator(Validators.alwaysPass())
.build());
Map<String, Parameter> parameters = new HashMap<>();
parameters.put("foo", new Parameter("foo", "A"));
Map<String, Object> parameterState = ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
Assert.assertEquals(TestEnum.A, parameterState.get("foo"));
}
;
@Test
public void testEnumCSVParameter() {
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("foo", new EnumCSVParameter<>(TestEnum.class)
.name("foo")
.required()
.validator(Validators.alwaysPass())
.build());
Map<String, Parameter> parameters = new HashMap<>();
parameters.put("foo", new Parameter("foo", " A , C "));
Map<String, Object> parameterState = ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
EnumSet<TestEnum> foo = (EnumSet<TestEnum>) parameterState.get("foo");
Assert.assertTrue(foo.contains(TestEnum.A));
Assert.assertTrue(foo.contains(TestEnum.C));
Assert.assertFalse(foo.contains(TestEnum.B));
}
@Test(expected = IllegalArgumentException.class)
public void emptyEnumCSVListValidation() {
Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
parameterDefinitions.put("foo", new EnumCSVParameter<>(TestEnum.class)
.name("foo")
.required()
.validator(Validators.notNullOrEmptyEnumCSV())
.build());
Map<String, Parameter> parameters = new HashMap<>();
parameters.put("foo", new Parameter("foo", " "));
ParameterUtils.checkThenCreateState(parameterDefinitions, parameters);
}
enum TestEnum {A, B, C}
}
| 8,600 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/SourceHolder.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.computation.ToGroupComputation;
import io.mantisrx.runtime.computation.ToKeyComputation;
import io.mantisrx.runtime.source.SelfDocumentingSource;
import io.mantisrx.runtime.source.Source;
public class SourceHolder<T> {
private Metadata metadata;
private final Source<T> sourceFunction;
// There is no need for input codec
// for a source, if called
// throw exception to detect error
private final Codec<T> failCodec = new Codec<T>() {
@Override
public byte[] encode(T value) {
throw new RuntimeException("Attempting to encode source data");
}
@Override
public T decode(byte[] bytes) {
throw new RuntimeException("Attempting to decode source data");
}
};
SourceHolder(Source<T> sourceFunction) {
this.sourceFunction = sourceFunction;
}
SourceHolder(SelfDocumentingSource<T> sourceFunction) {
this.metadata = sourceFunction.metadata();
this.sourceFunction = sourceFunction;
}
public Source<T> getSourceFunction() {
return sourceFunction;
}
public Metadata getMetadata() {
return metadata;
}
public <K, R> KeyedStages<K, R> stage(ToKeyComputation<T, K, R> computation,
ScalarToKey.Config<T, K, R> config) {
return new KeyedStages<>(this, new ScalarToKey<>(computation, config, failCodec), config.getKeyCodec(), config.getCodec());
}
/**
* Use instead of ToKeyComputation for high cardinality, high throughput use cases
*
* @param computation The computation that transforms a scalar to a group
* @param config stage config
*
* @return KeyedStages
*/
public <K, R> KeyedStages<K, R> stage(ToGroupComputation<T, K, R> computation,
ScalarToGroup.Config<T, K, R> config) {
return new KeyedStages<>(this, new ScalarToGroup<>(computation, config, failCodec), config.getKeyCodec(), config.getCodec());
}
public <R> ScalarStages<R> stage(ScalarComputation<T, R> computation,
ScalarToScalar.Config<T, R> config) {
return new ScalarStages<>(this, new ScalarToScalar<>(computation, config, failCodec), config.getCodec());
}
}
| 8,601 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/WorkerMap.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Wrapper object that contains worker information organized by stage number
*/
public class WorkerMap {
private final Map<Integer, List<WorkerInfo>> workerRegistryMap;
public WorkerMap(Map<Integer, List<WorkerInfo>> workerRegistryMap) {
Objects.nonNull(workerRegistryMap);
this.workerRegistryMap = workerRegistryMap;
}
public List<WorkerInfo> getWorkersForStage(int stageNum) {
return workerRegistryMap.get(stageNum);
}
public boolean isEmpty() {
return workerRegistryMap.isEmpty();
}
@Override
public String toString() {
return "WorkerMap{" +
"workerRegistryMap=" + workerRegistryMap +
'}';
}
}
| 8,602 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/SinkHolder.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.runtime.sink.SelfDocumentingSink;
import io.mantisrx.runtime.sink.Sink;
public class SinkHolder<T> {
private Metadata metadata;
private final Sink<T> sinkAction;
public SinkHolder(final SelfDocumentingSink<T> sinkAction) {
this.metadata = sinkAction.metadata();
this.sinkAction = sinkAction;
}
public SinkHolder(final Sink<T> sinkAction) {
this.sinkAction = sinkAction;
}
public Metadata getMetadata() {
return metadata;
}
public Sink<T> getSinkAction() {
return sinkAction;
}
public boolean isPortRequested() {
return true;
}
}
| 8,603 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/MantisJob.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.runtime.source.Source;
public class MantisJob<T> {
public static <T> SourceHolder<T> source(Source<T> source) {
return new SourceHolder<T>(source);
}
}
| 8,604 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/KeyToScalar.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.computation.ToScalarComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class KeyToScalar<K, T, R> extends StageConfig<T, R> {
private final ToScalarComputation<K, T, R> computation;
private final long keyExpireTimeSeconds;
/**
* @deprecated As of release 0.603, use {@link #KeyToScalar(ToScalarComputation, Config, Codec)} instead
*/
KeyToScalar(ToScalarComputation<K, T, R> computation,
Config<K, T, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
KeyToScalar(ToScalarComputation<K, T, R> computation,
Config<K, T, R> config, final Codec<T> inputCodec) {
this(computation, config, (Codec<K>) Codecs.string(), inputCodec);
}
KeyToScalar(ToScalarComputation<K, T, R> computation,
Config<K, T, R> config, Codec<K> inputKeyCodec, Codec<T> inputCodec) {
super(config.description, inputKeyCodec, inputCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public ToScalarComputation<K, T, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<K, T, R> {
private Codec<R> codec;
private String description;
private long keyExpireTimeSeconds = TimeUnit.HOURS.toSeconds(1); // 1 hour default
// default input type is serial for
// 'stateful group calculation' use case
// do not allow config override
private final INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.SERIAL;
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is netty reactive x
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<K, T, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<K, T, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<K, T, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<K, T, R> description(String description) {
this.description = description;
return this;
}
public Codec<R> getCodec() {
return codec;
}
public String getDescription() {
return description;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public Config<K, T, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,605 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/KeyToKey.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.computation.KeyComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Use to perform another shuffle on the data with a different key
* It transforms an item of type <K1, T> to <K2,R>
* @param <K1> Input key type
* @param <T> Input value type
* @param <K2> Output key type
* @param <R> Output value type
*/
public class KeyToKey<K1, T, K2, R> extends KeyValueStageConfig<T, K2, R> {
private final KeyComputation<K1, T, K2, R> computation;
private final long keyExpireTimeSeconds;
/**
* @deprecated As of release 0.603, use {@link #KeyToKey(KeyComputation, Config, Codec)} instead
*/
KeyToKey(KeyComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
KeyToKey(KeyComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, Codec<T> inputCodec) {
this(computation, config, (Codec<K1>) Codecs.string(), inputCodec);
}
KeyToKey(KeyComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, Codec<K1> inputKeyCodec, Codec<T> inputCodec) {
super(config.description, inputKeyCodec, inputCodec, config.keyCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public KeyComputation<K1, T, K2, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<K1, T, K2, R> {
private Codec<R> codec;
private Codec<K2> keyCodec;
private String description;
private long keyExpireTimeSeconds = TimeUnit.HOURS.toSeconds(1); // 1 hour default
// input type for keyToKey is serial
// always assume a stateful calculation is being made
// do not allow config to override
private final INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.SERIAL;
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is a netty reactivex codec
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<K1, T, K2, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<K1, T, K2, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<K1, T, K2, R> keyCodec(Codec<K2> keyCodec) {
this.keyCodec = keyCodec;
return this;
}
public Config<K1, T, K2, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<K1, T, K2, R> description(String description) {
this.description = description;
return this;
}
public Codec<K2> getKeyCodec() {
return keyCodec;
}
public Codec<R> getCodec() {
return codec;
}
public String getDescription() {
return description;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public Config<K1, T, K2, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,606 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Groups.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.MantisGroup;
import io.reactivx.mantis.operators.GroupedObservableUtils;
import rx.Observable;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
public class Groups {
private Groups() {}
public static <K, T> Observable<GroupedObservable<K, T>> flatten(
Observable<Observable<GroupedObservable<K, T>>> groups) {
Observable<GroupedObservable<K, T>> flattenedGroups = Observable.merge(groups);
return flattenedGroups
// // re-group by key
.groupBy(GroupedObservable::getKey)
// flatten, with merged group
.flatMap(new Func1<GroupedObservable<K, GroupedObservable<K, T>>, Observable<GroupedObservable<K, T>>>() {
@Override
public Observable<GroupedObservable<K, T>> call(
GroupedObservable<K, GroupedObservable<K, T>> groups) {
return Observable.just(GroupedObservableUtils.createGroupedObservable(groups.getKey(),
Observable.merge(groups)));
}
});
}
/**
* Convert O O MantisGroup to O GroupedObservable
*
* @param <K> MantisGroup<K, T> groups keyValue
*
* @param <T> MantisGroup<K, T>> groups value
*
* @return Observable
*/
public static <K, T> Observable<GroupedObservable<K, T>> flattenMantisGroupsToGroupedObservables(
Observable<Observable<MantisGroup<K, T>>> groups) {
Observable<MantisGroup<K, T>> flattenedGroups = Observable.merge(groups);
return flattenedGroups.groupBy(MantisGroup::getKeyValue, MantisGroup::getValue);
}
}
| 8,607 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/KeyValueStageConfig.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.List;
/** An intermediate abstract class that holds the keyCodec for the output key
* for mantis events
*
* @param <T> Input datatype
* @param <K> Output keytype
* @param <R> Output value datatype
*/
public abstract class KeyValueStageConfig<T, K, R> extends StageConfig<T, R> {
private final Codec<K> keyCodec;
public KeyValueStageConfig(String description, Codec<?> inputKeyCodec, Codec<T> inputCodec, Codec<K> outputKeyCodec, Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, List<ParameterDefinition<?>> params) {
super(description, inputKeyCodec, inputCodec, outputCodec, inputStrategy, params);
this.keyCodec = outputKeyCodec;
}
public Codec<K> getOutputKeyCodec() {
if (this.keyCodec == null) {
return (Codec<K>) Codecs.string();
}
return this.keyCodec;
}
}
| 8,608 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Context.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.runtime.lifecycle.LifecycleNoOp;
import io.mantisrx.runtime.lifecycle.ServiceLocator;
import io.mantisrx.runtime.parameter.Parameters;
import javax.annotation.Nullable;
import rx.Observable;
import rx.functions.Action0;
import rx.subjects.BehaviorSubject;
/**
* <p>
* An instance of this class is made available to the user job during the <code>init()</code> and <code>call</code> methods
* of a stage. This object provides information related to the current job
* <p>
* </p>
*/
public class Context {
// Callback invoked during job shutdown
private final Action0 completeAndExitAction;
private MetricsRegistry metricsRegistry;
// Parameters associated with this job
private Parameters parameters = new Parameters();
// Service Locator allows the user to access guice modules loaded with this job
private ServiceLocator serviceLocator = new LifecycleNoOp().getServiceLocator();
// Information related to the current worker
private WorkerInfo workerInfo;
// No longer used.
private Observable<Boolean> prevStageCompletedObservable = BehaviorSubject.create(false);
// An Observable providing details of all workers of the current job
private Observable<WorkerMap> workerMapObservable = Observable.empty();
// Custom class loader
@Nullable
private final ClassLoader classLoader;
/**
* For testing only
*/
public Context() {
this.classLoader = null;
completeAndExitAction = () -> {
// no-op
};
}
public Context(Parameters parameters, ServiceLocator serviceLocator, WorkerInfo workerInfo,
MetricsRegistry metricsRegistry, Action0 completeAndExitAction) {
this(parameters, serviceLocator, workerInfo, metricsRegistry, completeAndExitAction, Observable.empty(), null);
}
public Context(Parameters parameters, ServiceLocator serviceLocator, WorkerInfo workerInfo,
MetricsRegistry metricsRegistry, Action0 completeAndExitAction, Observable<WorkerMap> workerMapObservable, @Nullable ClassLoader classLoader) {
this.parameters = parameters;
this.serviceLocator = serviceLocator;
this.workerInfo = workerInfo;
this.metricsRegistry = metricsRegistry;
if (completeAndExitAction == null)
throw new IllegalArgumentException("Null complete action provided in Context contructor");
this.completeAndExitAction = completeAndExitAction;
this.workerMapObservable = workerMapObservable;
this.classLoader = classLoader;
}
public MetricsRegistry getMetricsRegistry() {
return metricsRegistry;
}
/**
* Returns the Job Parameters associated with the current job
*
* @return Parameters
*/
public Parameters getParameters() {
return parameters;
}
public ServiceLocator getServiceLocator() {
return serviceLocator;
}
/**
* Returns the JobId of the current job.
*
* @return String
*/
public String getJobId() {
return workerInfo.getJobId();
}
/**
* Returns information related to the current worker
*
* @return WorkerInfo
*/
public WorkerInfo getWorkerInfo() {
return workerInfo;
}
/**
* <P> Note: This method is deprecated as it is not expected for workers of a stage to complete. If the task
* of the Job is complete the workers should invoke <code>context.completeAndExit()</code> api.
* <p>
* Get a boolean observable that will emit the state of whether or not all workers in the previous
* stage have completed. Workers in the previous stage that have failed and are going to be replaced by new
* workers will not trigger this event.
* <p>
* The observable will be backed by an rx.subjects.BehaviorSubject so you can expect to
* always get the latest state upon subscription. They are may be multiple emissions of <code>false</code> before
* an emission of <code>true</code> when the previous stage completes all of its workers.
* <p>
* In workers for first stage of the job, this observable will never emit a value of <code>true</code>.
* <p>
* Generally, this is useful only for batch style jobs (those with their sla of job duration type set to
* {@link MantisJobDurationType#Transient}).
*
* @return A boolean observable to indicate whether or not the previous stage has completed all of its workers.
*/
@Deprecated
public Observable<Boolean> getPrevStageCompletedObservable() {
return prevStageCompletedObservable;
}
@Deprecated
public void setPrevStageCompletedObservable(Observable<Boolean> prevStageCompletedObservable) {
this.prevStageCompletedObservable = prevStageCompletedObservable;
}
/**
* Used to convey to the Mantis Master that the job has finished its work and wishes to be shutdown.
*/
public void completeAndExit() {
completeAndExitAction.call();
}
/**
* Returns an Observable of WorkerMap for the current Job. The user can use this Observable
* to track the location information of all the workers of the current job.
*
* @return Observable
*/
public Observable<WorkerMap> getWorkerMapObservable() {
return this.workerMapObservable;
}
@Nullable
public ClassLoader getClassLoader() { return this.classLoader; }
}
| 8,609 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Job.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.runtime.lifecycle.Lifecycle;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.List;
import java.util.Map;
public class Job<T> {
private final Metadata metadata;
private final SourceHolder<?> source;
private final List<StageConfig<?, ?>> stages;
private final SinkHolder<T> sink;
private final Lifecycle lifecycle;
private final Map<String, ParameterDefinition<?>> parameterDefinitions;
Job(SourceHolder<?> source, List<StageConfig<?, ?>> stages, SinkHolder<T> sink,
Lifecycle lifecycle, Metadata metadata,
Map<String, ParameterDefinition<?>> parameterDefinitions) {
this.source = source;
this.stages = stages;
this.sink = sink;
this.lifecycle = lifecycle;
this.metadata = metadata;
this.parameterDefinitions = parameterDefinitions;
}
public Map<String, ParameterDefinition<?>> getParameterDefinitions() {
return parameterDefinitions;
}
public Lifecycle getLifecycle() {
return lifecycle;
}
public SourceHolder<?> getSource() {
return source;
}
public List<StageConfig<?, ?>> getStages() {
return stages;
}
public SinkHolder<T> getSink() {
return sink;
}
public Metadata getMetadata() {
return metadata;
}
}
| 8,610 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/KeyedStages.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.GroupComputation;
import io.mantisrx.runtime.computation.GroupToScalarComputation;
import io.mantisrx.runtime.computation.KeyComputation;
import io.mantisrx.runtime.computation.ToScalarComputation;
public class KeyedStages<K1, T> extends Stages<T> {
KeyedStages(SourceHolder<?> source, StageConfig<?, ?> stage, Codec<?> inputKeyCodec, Codec<T> inputCodec) {
super(source, stage, inputKeyCodec, inputCodec);
}
KeyedStages(Stages<?> self, StageConfig<?, ?> stage, Codec<?> inputKeyCodec, Codec<T> inputCodec) {
super(self.getSource(), self.getStages(), stage, inputKeyCodec, inputCodec);
}
public <K2, R> KeyedStages<K2, R> stage(KeyComputation<K1, T, K2, R> computation,
KeyToKey.Config<K1, T, K2, R> config) {
return new KeyedStages<>(this, new KeyToKey<>(computation, config, (Codec<K1>) inputKeyCodec, inputCodec), config.getKeyCodec(), config.getCodec());
}
public <K2, R> KeyedStages<K2, R> stage(GroupComputation<K1, T, K2, R> computation,
GroupToGroup.Config<K1, T, K2, R> config) {
return new KeyedStages<>(this, new GroupToGroup<>(computation, config, (Codec<K1>) inputKeyCodec, inputCodec), config.getKeyCodec(), config.getCodec());
}
public <K, R> ScalarStages<R> stage(ToScalarComputation<K, T, R> computation,
KeyToScalar.Config<K, T, R> config) {
return new ScalarStages<>(this, new KeyToScalar<>(computation, config, (Codec<K>) inputKeyCodec, inputCodec), config.getCodec());
}
public <K, R> ScalarStages<R> stage(GroupToScalarComputation<K, T, R> computation,
GroupToScalar.Config<K, T, R> config) {
return new ScalarStages<>(this, new GroupToScalar<>(computation, config, (Codec<K>) inputKeyCodec, inputCodec), config.getCodec());
}
}
| 8,611 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalarToScalar.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
public class ScalarToScalar<T, R> extends StageConfig<T, R> {
private final INPUT_STRATEGY inputStrategy;
private final ScalarComputation<T, R> computation;
private List<ParameterDefinition<?>> parameters;
/**
* @deprecated As of release 0.603, use {@link #ScalarToScalar(ScalarComputation, Config, Codec)} instead
*/
ScalarToScalar(ScalarComputation<T, R> computation,
Config<T, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
super(config.description, NettyCodec.fromNetty(inputCodec), config.codec, config.inputStrategy, config.parameters, config.concurrency);
this.computation = computation;
this.inputStrategy = config.inputStrategy;
}
public ScalarToScalar(ScalarComputation<T, R> computation,
Config<T, R> config, Codec<T> inputCodec) {
super(config.description, inputCodec, config.codec, config.inputStrategy, config.parameters, config.concurrency);
this.computation = computation;
this.inputStrategy = config.inputStrategy;
this.parameters = config.parameters;
}
public ScalarComputation<T, R> getComputation() {
return computation;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
@Override
public List<ParameterDefinition<?>> getParameters() {
return parameters;
}
public static class Config<T, R> {
private Codec<R> codec;
private String description;
// default input type is serial for 'collecting' use case
private INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.SERIAL;
private volatile int concurrency = StageConfig.DEFAULT_STAGE_CONCURRENCY;
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is Codec of netty reactivex
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<T, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<T, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<T, R> serialInput() {
this.inputStrategy = INPUT_STRATEGY.SERIAL;
return this;
}
public Config<T, R> concurrentInput() {
this.inputStrategy = INPUT_STRATEGY.CONCURRENT;
return this;
}
public Config<T, R> concurrentInput(final int concurrency) {
this.inputStrategy = INPUT_STRATEGY.CONCURRENT;
this.concurrency = concurrency;
return this;
}
public Config<T, R> description(String description) {
this.description = description;
return this;
}
public Codec<R> getCodec() {
return codec;
}
public Config<T, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
public String getDescription() {
return description;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public int getConcurrency() {
return concurrency;
}
}
}
| 8,612 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Stages.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import java.util.LinkedList;
import java.util.List;
public class Stages<T> {
final Codec<?> inputKeyCodec;
final Codec<T> inputCodec;
private final SourceHolder<?> source;
private final List<StageConfig<?, ?>> stages;
Stages(SourceHolder<?> source, StageConfig<?, ?> stage, Codec<T> inputCodec) {
this(source, stage, null, inputCodec);
}
Stages(SourceHolder<?> source, StageConfig<?, ?> stage, Codec<?> inputKeyCodec, Codec<T> inputCodec) {
this(source, new LinkedList<>(), stage, inputKeyCodec, inputCodec);
}
Stages(SourceHolder<?> source, List<StageConfig<?, ?>> stages,
StageConfig<?, ?> stage, Codec<T> inputCodec) {
this(source, stages, stage, null, inputCodec);
}
Stages(SourceHolder<?> source, List<StageConfig<?, ?>> stages,
StageConfig<?, ?> stage, Codec<?> inputKeyCodec, Codec<T> inputCodec) {
this.source = source;
this.stages = stages;
this.stages.add(stage);
this.inputCodec = inputCodec;
this.inputKeyCodec = inputKeyCodec;
}
public List<StageConfig<?, ?>> getStages() {
return stages;
}
public SourceHolder<?> getSource() {
return source;
}
}
| 8,613 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/GroupToGroup.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.computation.GroupComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Use to perform another shuffle on the data with a different key
* It transforms an item of type MantisGroup<K1, T> to MantisGroup<K2,R>
* @param <K1> Input key type
* @param <T> Input value type
* @param <K2> Output key type
* @param <R> Output value type
*/
public class GroupToGroup<K1, T, K2, R> extends KeyValueStageConfig<T, K2, R> {
private final GroupComputation<K1, T, K2, R> computation;
private final long keyExpireTimeSeconds;
/**
* @deprecated As of release 0.603, use {@link #GroupToGroup(GroupComputation, Config, Codec)} instead
*/
GroupToGroup(GroupComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
GroupToGroup(GroupComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, Codec<T> inputCodec) {
this(computation, config, (Codec<K1>) Codecs.string(), inputCodec);
}
GroupToGroup(GroupComputation<K1, T, K2, R> computation,
Config<K1, T, K2, R> config, Codec<K1> inputKeyCodec, Codec<T> inputCodec) {
super(config.description, inputKeyCodec, inputCodec, config.keyCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public GroupComputation<K1, T, K2, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<K1, T, K2, R> {
private Codec<R> codec;
private Codec<K2> keyCodec;
private String description;
private long keyExpireTimeSeconds = TimeUnit.HOURS.toSeconds(1); // 1 hour default
// input type for keyToKey is serial
// always assume a stateful calculation is being made
// do not allow config to override
private final INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.SERIAL;
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<K1, T, K2, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<K1, T, K2, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<K1, T, K2, R> keyCodec(Codec<K2> keyCodec) {
this.keyCodec = keyCodec;
return this;
}
public Config<K1, T, K2, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<K1, T, K2, R> description(String description) {
this.description = description;
return this;
}
public Codec<K2> getKeyCodec() {
return keyCodec;
}
public Codec<R> getCodec() {
return codec;
}
public String getDescription() {
return description;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public Config<K1, T, K2, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,614 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/GroupToScalar.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.computation.GroupToScalarComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Alternative to ToScalar which expects GroupedObservables as input.
* This computation should be used instead of ToScalar for high cardinality, high volume
* data.
*
* @param <K> Type of the key
* @param <T> Type of the value
* @param <R> The transformed value
*
* @author njoshi
*/
public class GroupToScalar<K, T, R> extends StageConfig<T, R> {
private final GroupToScalarComputation<K, T, R> computation;
private final long keyExpireTimeSeconds;
/**
* @deprecated As of release 0.603, use {@link #GroupToScalar(GroupToScalarComputation, Config, Codec)} instead
*/
GroupToScalar(GroupToScalarComputation<K, T, R> computation,
Config<K, T, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
GroupToScalar(GroupToScalarComputation<K, T, R> computation,
Config<K, T, R> config, Codec<T> inputCodec) {
this(computation, config, (Codec<K>) Codecs.string(), inputCodec);
}
GroupToScalar(GroupToScalarComputation<K, T, R> computation,
Config<K, T, R> config, Codec<K> inputKeyCodec, Codec<T> inputCodec) {
super(config.description, inputKeyCodec, inputCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public GroupToScalarComputation<K, T, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<K, T, R> {
private Codec<R> codec;
private String description;
private long keyExpireTimeSeconds = TimeUnit.HOURS.toSeconds(1); // 1 hour default
// default input type is serial for
// 'stateful group calculation' use case
// do not allow config override
private INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.SERIAL;
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is netty reactivex Codec
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(io.mantisrx.common.codec.Codec)} instead
*/
public Config<K, T, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<K, T, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
/**
* Not used. As we are not generating GroupedObservables
*
* @param seconds is a long
*
* @return Config
*/
public Config<K, T, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<K, T, R> description(String description) {
this.description = description;
return this;
}
public Config<K, T, R> concurrentInput() {
this.inputStrategy = INPUT_STRATEGY.CONCURRENT;
return this;
}
public Codec<R> getCodec() {
return codec;
}
public String getDescription() {
return description;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public Config<K, T, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,615 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalingPolicies.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public class ScalingPolicies {
public static ScalingPolicy singleMachine(MachineDefinition machineResourceRequirements) {
return new ScalingPolicy(1, machineResourceRequirements);
}
public static ScalingPolicy fixedSizedCluster(int clusterSize, MachineDefinition machineResourceRequirements) {
return new ScalingPolicy(clusterSize, machineResourceRequirements);
}
}
| 8,616 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/NettyCodec.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
public class NettyCodec<T> implements Codec<T> {
private final io.reactivex.netty.codec.Codec<T> codec;
private NettyCodec(io.reactivex.netty.codec.Codec<T> codec) {
this.codec = codec;
}
@Override
public T decode(byte[] bytes) {
return codec.decode(bytes);
}
@Override
public byte[] encode(T value) {
return codec.encode(value);
}
static <T> Codec<T> fromNetty(io.reactivex.netty.codec.Codec<T> codec) {
return new NettyCodec<>(codec);
}
}
| 8,617 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/StageConfig.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
public abstract class StageConfig<T, R> {
// Note: the default of -1 implies the concurrency is not explicitly configured. This defaults to
// the behaviour of relying on the number of inner observables for concurrency in the system
public static final int DEFAULT_STAGE_CONCURRENCY = -1;
private final String description;
// holds the codec for the key datatype if there is one in the stage
private final Codec<?> inputKeyCodec;
private final Codec<T> inputCodec;
private final Codec<R> outputCodec;
private final INPUT_STRATEGY inputStrategy;
private final List<ParameterDefinition<?>> parameters;
// this number determines the number of New Threads created for concurrent Stage processing irrespective of the
// number of inner observables processed
private int concurrency = DEFAULT_STAGE_CONCURRENCY;
public StageConfig(String description, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy) {
this(description, inputCodec, outputCodec, inputStrategy, Collections.emptyList(), DEFAULT_STAGE_CONCURRENCY);
}
public StageConfig(String description, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, List<ParameterDefinition<?>> params) {
this(description, inputCodec, outputCodec, inputStrategy, params, DEFAULT_STAGE_CONCURRENCY);
}
public <K> StageConfig(String description, Codec<K> inputKeyCodec, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, List<ParameterDefinition<?>> params) {
this(description, inputKeyCodec, inputCodec, outputCodec, inputStrategy, params, DEFAULT_STAGE_CONCURRENCY);
}
public StageConfig(String description, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, int concurrency) {
this(description, inputCodec, outputCodec, inputStrategy, Collections.emptyList(), concurrency);
}
public StageConfig(String description, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, List<ParameterDefinition<?>> params,
int concurrency) {
this(description, null, inputCodec, outputCodec, inputStrategy, params, concurrency);
}
public <K> StageConfig(String description, Codec<K> inputKeyCodec, Codec<T> inputCodec,
Codec<R> outputCodec, INPUT_STRATEGY inputStrategy, List<ParameterDefinition<?>> params,
int concurrency) {
this.description = description;
this.inputKeyCodec = inputKeyCodec;
this.inputCodec = inputCodec;
this.outputCodec = outputCodec;
this.inputStrategy = inputStrategy;
this.parameters = params;
this.concurrency = concurrency;
}
public String getDescription() {
return description;
}
public <K> Codec<K> getInputKeyCodec() {
if (inputKeyCodec == null) {
return (Codec<K>) Codecs.string();
}
return (Codec<K>) inputKeyCodec;
}
public Codec<T> getInputCodec() {
return inputCodec;
}
public Codec<R> getOutputCodec() {
return outputCodec;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public List<ParameterDefinition<?>> getParameters() {
return parameters;
}
public int getConcurrency() {
return concurrency;
}
public enum INPUT_STRATEGY {NONE_SPECIFIED, SERIAL, CONCURRENT}
}
| 8,618 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/PortRequest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public class PortRequest {
private int port = -1;
public PortRequest(int port) {
this.port = port;
}
public int getPort() {
return port;
}
}
| 8,619 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/DefaultLifecycleFactory.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.runtime.lifecycle.Lifecycle;
import io.mantisrx.runtime.lifecycle.LifecycleNoOp;
public class DefaultLifecycleFactory {
private static Lifecycle instance;
public static Lifecycle getInstance() {
if (instance == null) {
return new LifecycleNoOp();
}
return instance;
}
public static void setInstance(final Lifecycle lifecycle) {
instance = lifecycle;
}
}
| 8,620 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalarToKey.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.ToKeyComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
/** A deprecated class to shuffle mantis events based on a key.
* Prefer using {@code ScalarToGroup} instead
*
* @param <T> Input datatype
* @param <K> Output keytype
* @param <R> Output value datatype
*/
public class ScalarToKey<T, K, R> extends KeyValueStageConfig<T, K, R> {
private final ToKeyComputation<T, K, R> computation;
private final long keyExpireTimeSeconds;
/**
* @param computation is a ToGroupComputation
* @param config is a ScalartoGroup config
* @param inputCodec is codec of mantisx runtime codec
*
* @deprecated As of release 0.603, use {@link #ScalarToKey(ToKeyComputation, Config, Codec)} (ToGroupComputation, Config, Codec)} instead
*/
ScalarToKey(ToKeyComputation<T, K, R> computation,
Config<T, K, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
ScalarToKey(ToKeyComputation<T, K, R> computation,
Config<T, K, R> config, Codec<T> inputCodec) {
super(config.description, null, inputCodec, config.keyCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public ToKeyComputation<T, K, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<T, K, R> {
private Codec<R> codec;
private Codec<K> keyCodec;
private String description;
// default input type is concurrent for 'grouping' use case
private INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.CONCURRENT;
private long keyExpireTimeSeconds = Long.MAX_VALUE; // never expire by default
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is Codec of netty reactivex
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<T, K, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<T, K, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<T, K, R> keyCodec(Codec<K> keyCodec) {
this.keyCodec = keyCodec;
return this;
}
public Config<T, K, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<T, K, R> serialInput() {
this.inputStrategy = INPUT_STRATEGY.SERIAL;
return this;
}
public Config<T, K, R> concurrentInput() {
this.inputStrategy = INPUT_STRATEGY.CONCURRENT;
return this;
}
public Config<T, K, R> description(String description) {
this.description = description;
return this;
}
public Codec<K> getKeyCodec() {
return keyCodec;
}
public Codec<R> getCodec() {
return codec;
}
public String getDescription() {
return description;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public Config<T, K, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,621 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Metadata.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public class Metadata {
private String name;
private String description;
Metadata() {}
Metadata(Builder builder) {
this.name = builder.name;
this.description = builder.description;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public static class Builder {
private String name;
private String description;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Metadata build() {
return new Metadata(this);
}
}
}
| 8,622 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalarToGroup.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.ToGroupComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.Collections;
import java.util.List;
/**
* This should be used as an alternative to ScalarToKey for high cardinality, high volume data.
* It transforms a T to MantisGroup K,R
*
* @param <T> Input data type
* @param <K> Key type
* @param <R> Output data type
*
* @author njoshi
*/
public class ScalarToGroup<T, K, R> extends KeyValueStageConfig<T, K, R> {
private final ToGroupComputation<T, K, R> computation;
private final long keyExpireTimeSeconds;
/**
* @param computation is a ToGroupComputation
* @param config is a ScalartoGroup config
* @param inputCodec is codec of mantisx runtime codec
*
* @deprecated As of release 0.603, use {@link #ScalarToGroup(ToGroupComputation, Config, Codec)} instead
*/
ScalarToGroup(ToGroupComputation<T, K, R> computation,
Config<T, K, R> config, final io.reactivex.netty.codec.Codec<T> inputCodec) {
this(computation, config, NettyCodec.fromNetty(inputCodec));
}
public ScalarToGroup(ToGroupComputation<T, K, R> computation,
Config<T, K, R> config, Codec<T> inputCodec) {
super(config.description, null, inputCodec, config.keyCodec, config.codec, config.inputStrategy, config.parameters);
this.computation = computation;
this.keyExpireTimeSeconds = config.keyExpireTimeSeconds;
}
public ToGroupComputation<T, K, R> getComputation() {
return computation;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public static class Config<T, K, R> {
private Codec<R> codec;
private Codec<K> keyCodec;
private String description;
// default input type is concurrent for 'grouping' use case
private INPUT_STRATEGY inputStrategy = INPUT_STRATEGY.CONCURRENT;
private long keyExpireTimeSeconds = Long.MAX_VALUE; // never expire by default
private List<ParameterDefinition<?>> parameters = Collections.emptyList();
/**
* @param codec is Codec of netty reactivex
*
* @return Config
*
* @deprecated As of release 0.603, use {@link #codec(Codec)} instead
*/
public Config<T, K, R> codec(final io.reactivex.netty.codec.Codec<R> codec) {
this.codec = NettyCodec.fromNetty(codec);
return this;
}
public Config<T, K, R> codec(Codec<R> codec) {
this.codec = codec;
return this;
}
public Config<T, K, R> keyCodec(Codec<K> keyCodec) {
this.keyCodec = keyCodec;
return this;
}
public Config<T, K, R> keyExpireTimeSeconds(long seconds) {
this.keyExpireTimeSeconds = seconds;
return this;
}
public Config<T, K, R> serialInput() {
this.inputStrategy = INPUT_STRATEGY.SERIAL;
return this;
}
public Config<T, K, R> concurrentInput() {
this.inputStrategy = INPUT_STRATEGY.CONCURRENT;
return this;
}
public Config<T, K, R> description(String description) {
this.description = description;
return this;
}
public Codec<R> getCodec() {
return codec;
}
public Codec<K> getKeyCodec() {
return keyCodec;
}
public String getDescription() {
return description;
}
public INPUT_STRATEGY getInputStrategy() {
return inputStrategy;
}
public long getKeyExpireTimeSeconds() {
return keyExpireTimeSeconds;
}
public Config<T, K, R> withParameters(List<ParameterDefinition<?>> params) {
this.parameters = params;
return this;
}
}
}
| 8,623 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/MantisJobProvider.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public abstract class MantisJobProvider<T> {
public abstract Job<T> getJobInstance();
}
| 8,624 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalarStages.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.computation.ToGroupComputation;
import io.mantisrx.runtime.computation.ToKeyComputation;
import io.mantisrx.runtime.sink.SelfDocumentingSink;
import io.mantisrx.runtime.sink.Sink;
public class ScalarStages<T> extends Stages<T> {
ScalarStages(SourceHolder<?> source, StageConfig<?, ?> stage, Codec<T> inputCodec) {
super(source, stage, inputCodec);
}
ScalarStages(Stages<?> self, StageConfig<?, ?> stage, Codec<T> inputCodec) {
super(self.getSource(), self.getStages(), stage, inputCodec);
}
public <K, R> KeyedStages<K, R> stage(ToKeyComputation<T, K, R> computation,
ScalarToKey.Config<T, K, R> config) {
return new KeyedStages<>(this,
new ScalarToKey<>(computation, config, inputCodec), config.getKeyCodec(), config.getCodec());
}
/**
* Use instead of ToKeyComputation for high cardinality, high throughput use cases
*
* @param computation The computation that transforms a scalar to a group
* @param config stage config
*
* @return KeyedStages
*/
public <K, R> KeyedStages<K, R> stage(ToGroupComputation<T, K, R> computation,
ScalarToGroup.Config<T, K, R> config) {
return new KeyedStages<>(this, new ScalarToGroup<>(computation, config, inputCodec), config.getKeyCodec(), config.getCodec());
}
public <R> ScalarStages<R> stage(ScalarComputation<T, R> computation,
ScalarToScalar.Config<T, R> config) {
return new ScalarStages<>(this,
new ScalarToScalar<>(computation, config, inputCodec), config.getCodec());
}
public Config<T> sink(Sink<T> sink) {
return new Config<>(this, new SinkHolder<>(sink));
}
public Config<T> sink(SelfDocumentingSink<T> sink) {
return new Config<>(this, new SinkHolder<>(sink));
}
}
| 8,625 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/WorkerInfo.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.common.WorkerPorts;
public class WorkerInfo {
private final String jobName;
private final String jobId;
private final int stageNumber;
private final int workerIndex;
private final int workerNumber;
private final String host;
private final WorkerPorts workerPorts;
private final MantisJobDurationType durationType;
public WorkerInfo(String jobName, String jobId, int stageNumber, int workerIndex, int workerNumber, MantisJobDurationType durationType, String host, WorkerPorts workerPorts) {
this.jobName = jobName;
this.jobId = jobId;
this.stageNumber = stageNumber;
this.workerIndex = workerIndex;
this.workerNumber = workerNumber;
this.durationType = durationType;
this.host = host;
this.workerPorts = workerPorts;
}
/**
* @return String
*
* @deprecated use {@link #getJobClusterName()} instead
*/
@Deprecated
public String getJobName() {
return jobName;
}
public String getJobClusterName() {
return jobName;
}
public String getJobId() {
return jobId;
}
public int getStageNumber() {
return stageNumber;
}
public int getWorkerIndex() {
return workerIndex;
}
public int getWorkerNumber() {
return workerNumber;
}
public MantisJobDurationType getDurationType() {
return durationType;
}
public String getHost() {
return host;
}
public WorkerPorts getWorkerPorts() {
return workerPorts;
}
@Override
public String toString() {
return "WorkerInfo{" +
"jobName='" + jobName + '\'' +
", jobId='" + jobId + '\'' +
", stageNumber=" + stageNumber +
", workerIndex=" + workerIndex +
", workerNumber=" + workerNumber +
", host='" + host + '\'' +
", workerPorts=" + workerPorts +
", durationType=" + durationType +
'}';
}
}
| 8,626 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/ScalingPolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public class ScalingPolicy {
private final int numInstances;
private final MachineDefinition machineDefinition;
ScalingPolicy(int numInstances,
MachineDefinition machineDefinition) {
this.numInstances = numInstances;
this.machineDefinition = machineDefinition;
}
public int getNumInstances() {
return numInstances;
}
public MachineDefinition getMachineDefinition() {
return machineDefinition;
}
}
| 8,627 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/Config.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
import io.mantisrx.runtime.lifecycle.Lifecycle;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Config<T> {
private Metadata metadata = new Metadata();
private final SourceHolder<?> source;
private final List<StageConfig<?, ?>> stages;
private final SinkHolder<T> sink;
private Lifecycle lifecycle = DefaultLifecycleFactory.getInstance();
private final Map<String, ParameterDefinition<?>> parameterDefinitions = new HashMap<>();
Config(Stages<?> stages, SinkHolder<T> observable) {
this.source = stages.getSource();
this.stages = stages.getStages();
this.sink = observable;
initParams();
}
private void putParameterOnce(ParameterDefinition<?> definition) {
final String name = definition.getName();
if (parameterDefinitions.containsKey(name)) {
throw new IllegalArgumentException("cannot have two parameters with same name " + name);
}
parameterDefinitions.put(name, definition);
}
private void initParams() {
// add parameters from Source, Stage and Sink and ensure we don't have naming conflicts between params defined by Source, Stage and Sink
source.getSourceFunction().getParameters().forEach(this::putParameterOnce);
for (StageConfig<?, ?> stage : stages) {
stage.getParameters().forEach(this::putParameterOnce);
}
sink.getSinkAction().getParameters().forEach(this::putParameterOnce);
}
public Config<T> lifecycle(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
return this;
}
public Config<T> metadata(Metadata metadata) {
this.metadata = metadata;
return this;
}
/**
* define a parameter definition at the Job level, this allows overriding defaults
* for parameters that might be already defined by a Source, Stage or Sink
*
* @param definition Parameter definition
*
* @return Config object
*/
public Config<T> parameterDefinition(ParameterDefinition<?> definition) {
parameterDefinitions.put(definition.getName(), definition);
return this;
}
public Job<T> create() {
return new Job<>(source, stages, sink, lifecycle,
metadata, parameterDefinitions);
}
}
| 8,628 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/MachineDefinitions.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime;
public class MachineDefinitions {
public static MachineDefinition micro() {
return new MachineDefinition(2f, 2014, 128.0, 1024, 1); // 2 cores, 2GB RAM, 500MB disk
}
public static MachineDefinition fromValues(double cpuCores, double memory, double disk) {
return new MachineDefinition(cpuCores, memory, 128.0, disk, 1);
}
public static MachineDefinition fromValues(double cpuCores, double memory, double network, double disk) {
return new MachineDefinition(cpuCores, memory, network, disk, 1);
}
}
| 8,629 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/MantisStreamImpl.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.runtime.Config;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.computation.Computation;
import io.mantisrx.runtime.computation.ToGroupComputation;
import io.mantisrx.runtime.core.functions.FilterFunction;
import io.mantisrx.runtime.core.functions.FlatMapFunction;
import io.mantisrx.runtime.core.functions.FunctionCombinator;
import io.mantisrx.runtime.core.functions.KeyByFunction;
import io.mantisrx.runtime.core.functions.MantisFunction;
import io.mantisrx.runtime.core.functions.MapFunction;
import io.mantisrx.runtime.core.functions.WindowFunction;
import io.mantisrx.runtime.core.sinks.ObservableSinkImpl;
import io.mantisrx.runtime.core.sinks.SinkFunction;
import io.mantisrx.runtime.core.sources.ObservableSourceImpl;
import io.mantisrx.runtime.core.sources.SourceFunction;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import io.mantisrx.shaded.com.google.common.collect.ImmutableList;
import io.mantisrx.shaded.com.google.common.graph.ImmutableValueGraph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
@Slf4j
public class MantisStreamImpl<T> implements MantisStream<T> {
final OperandNode<T> currNode;
final MantisGraph graph;
final Iterable<ParameterDefinition<?>> params;
MantisStreamImpl(OperandNode<T> newNode, MantisGraph graph) {
this(newNode, graph, ImmutableList.of());
}
MantisStreamImpl(OperandNode<T> node, MantisGraph graph, Iterable<ParameterDefinition<?>> params) {
this.currNode = node;
this.graph = graph;
this.params = params;
}
public static <T> MantisStream<T> init() {
OperandNode<T> node = new OperandNode<>(0, "init");
return new MantisStreamImpl<>(node, new MantisGraph().addNode(node));
}
public <OUT> MantisStream<OUT> source(SourceFunction<OUT> source) {
return updateGraph(source);
}
@Override
public Config<T> sink(SinkFunction<T> sink) {
MantisStreamImpl<Void> mantisStream = updateGraph(sink);
ImmutableValueGraph<OperandNode<?>, MantisFunction> graphDag = mantisStream.graph.immutable();
Iterable<OperandNode<?>> operandNodes = topSortTraversal(graphDag);
MantisJobBuilder jobBuilder = makeMantisJob(graphDag, operandNodes);
return (Config<T>) jobBuilder.buildJobConfig();
}
<OUT> MantisStreamImpl<OUT> updateGraph(MantisFunction mantisFn) {
OperandNode<OUT> node = OperandNode.create(graph, mantisFn.getClass().getName() + "OUT");
graph.putEdge(currNode, node, mantisFn);
return new MantisStreamImpl<>(node, graph);
}
@Override
public MantisStream<T> filter(FilterFunction<T> filterFn) {
return updateGraph(filterFn);
}
@Override
public <OUT> MantisStream<OUT> map(MapFunction<T, OUT> mapFn) {
return updateGraph(mapFn);
}
@Override
public <OUT> MantisStream<OUT> flatMap(FlatMapFunction<T, OUT> flatMapFn) {
return updateGraph(flatMapFn);
}
@Override
public MantisStream<T> materialize() {
return materializeInternal();
}
private MantisStreamImpl<T> materializeInternal() {
graph.putEdge(currNode, currNode, MantisFunction.empty());
return new MantisStreamImpl<>(currNode, graph);
}
private <K> KeyedMantisStreamImpl<K, T> keyByInternal(KeyByFunction<K, T> keyFn) {
OperandNode<T> node = OperandNode.create(graph, "keyByOut");
graph.putEdge(currNode, node, keyFn);
return new KeyedMantisStreamImpl<>(node, graph);
}
@Override
public <K> KeyedMantisStream<K, T> keyBy(KeyByFunction<K, T> keyFn) {
return this.materializeInternal()
.keyByInternal(keyFn);
}
private MantisJobBuilder makeMantisJob(ImmutableValueGraph<OperandNode<?>, MantisFunction> graphDag, Iterable<OperandNode<?>> operandNodes) {
MantisJobBuilder jobBuilder = new MantisJobBuilder();
final AtomicReference<FunctionCombinator<?, ?>> composite = new AtomicReference<>(new FunctionCombinator<>(false));
for (OperandNode<?> n : operandNodes) {
Set<OperandNode<?>> successorsNodes = graphDag.successors(n);
if (successorsNodes.size() == 0) {
continue;
}
// remove self-loop
Optional<MantisFunction> selfEdge = graphDag.edgeValue(n, n);
Integer numSelfEdges = selfEdge.map(x -> 1).orElse(0);
selfEdge.ifPresent(mantisFn -> {
if (MantisFunction.empty().equals(mantisFn)) {
jobBuilder.addStage(composite.get().makeStage(), n.getCodec(), n.getKeyCodec());
composite.set(new FunctionCombinator<>(false));
} else if (mantisFn instanceof WindowFunction) {
composite.set(composite.get().add(mantisFn));
}
// No other types of self-edges are possible
});
if (successorsNodes.size() - numSelfEdges > 1) {
log.warn("Found multi-output node {} with nbrs {}. Not supported yet!", n, successorsNodes);
}
for (OperandNode<?> successorsNode : successorsNodes) {
if (successorsNode == n) {
continue;
}
graphDag.edgeValue(n, successorsNode).ifPresent(mantisFn -> {
if (mantisFn instanceof SourceFunction) {
if (mantisFn instanceof ObservableSourceImpl) {
jobBuilder.addStage(((ObservableSourceImpl) mantisFn).getSource());
}
} else if (mantisFn instanceof KeyByFunction) {
// ensure that the existing composite is empty here
if (composite.get().size() > 0) {
log.warn("Unempty composite found for KeyByFunction {}", composite.get());
}
jobBuilder.addStage(makeGroupComputation((KeyByFunction) mantisFn), n.getCodec(), n.getKeyCodec());
composite.set(new FunctionCombinator<>(true));
} else if (mantisFn instanceof SinkFunction) {
// materialize all composite functions into a scalar stage
// it can't be a keyed stage because we didn't encounter a reduce function!
jobBuilder.addStage(composite.get().makeStage(), n.getCodec());
if (mantisFn instanceof ObservableSinkImpl) {
jobBuilder.addStage(((ObservableSinkImpl) mantisFn).getSink());
}
} else {
composite.set(composite.get().add(mantisFn));
}
});
}
}
return jobBuilder;
}
private <A, K> Computation makeGroupComputation(KeyByFunction<K, A> keyFn) {
return new ToGroupComputation<A, K, A>() {
@Override
public void init(Context ctx) {
keyFn.init();
}
@Override
public Observable<MantisGroup<K, A>> call(Context ctx, Observable<A> obs) {
return obs.map(e -> new MantisGroup<>(keyFn.getKey(e), e));
}
};
}
static <V, E> Iterable<V> topSortTraversal(ImmutableValueGraph<V, E> graphDag) {
Set<V> nodes = graphDag.nodes();
Map<V, AtomicInteger> inDegreeMap = nodes.stream()
.collect(Collectors.toMap(x -> x, x ->
new AtomicInteger(graphDag.inDegree(x) - (graphDag.hasEdgeConnecting(x, x) ? 1 : 0))));
List<V> nodeOrder = new ArrayList<>();
final Set<V> visited = new HashSet<>();
List<V> starts = inDegreeMap.keySet().stream()
.filter(x -> inDegreeMap.get(x).get() == 0)
.collect(Collectors.toList());
while (!starts.isEmpty()) {
starts.forEach(x -> graphDag.successors(x).forEach(nbr -> {
if (nbr != x) inDegreeMap.get(nbr).decrementAndGet();
}));
visited.addAll(starts);
nodeOrder.addAll(starts);
starts = starts.stream().flatMap(x -> graphDag.successors(x).stream())
.filter(x -> !visited.contains(x) && inDegreeMap.get(x).get() == 0)
.collect(Collectors.toList());
}
return nodeOrder;
}
}
| 8,630 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/MantisStream.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.runtime.Config;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.core.functions.FilterFunction;
import io.mantisrx.runtime.core.functions.FlatMapFunction;
import io.mantisrx.runtime.core.functions.KeyByFunction;
import io.mantisrx.runtime.core.functions.MapFunction;
import io.mantisrx.runtime.core.sinks.SinkFunction;
import io.mantisrx.runtime.core.sources.SourceFunction;
public interface MantisStream<T> {
static <OUT> MantisStream<OUT> create(Context context) {
return MantisStreamImpl.init();
}
/**
*
* Defines a source operation that generates elements for the stream using
* the provided {@link SourceFunction}.
*
* This method defines a source operation that generates elements for the
* stream using the provided {@link SourceFunction}. A source operation is a
* starting operation that produces the initial set of elements in the stream.
* The provided {@link SourceFunction} defines the logic to generate the
* elements.
*
* The method returns a new {@link MantisStream} that starts with the elements
* generated by the provided {@link SourceFunction}. The resulting stream can be
* used to apply further operations on the generated elements, such as
* filtering, mapping, or aggregation.
*
* @param sourceFunction the function that generates the elements for the
* @param <OUT> the type of the elements in the stream.
* @return a new {@link MantisStream} that starts with the elements generated
*/
<OUT> MantisStream<OUT> source(SourceFunction<OUT> sourceFunction);
/**
* Defines a sink operation that writes the elements in the stream to an
* external system, using the provided {@link SinkFunction}.
*
* This method defines a sink operation that writes the elements in the stream
* to an external system, using the provided {@link SinkFunction}. A sink
* operation is a terminal operation that does not produce a new stream, but
* instead writes the elements in the stream to an external system. The
* provided {@link SinkFunction} defines the logic to write the elements.
*
* @param sinkFunction a sink operator usually an SSE sink
* @return a {@link Config} object that captures the essence of {@link MantisJob}
*/
Config<T> sink(SinkFunction<T> sinkFunction);
/**
* Applies the provided {@link FilterFunction} to each element in the stream
* and returns all elements that match {@code filterFn.apply()}. The function is
* applied independently to each element in the stream.
*
* @param filterFn the function to apply on each element in the stream. Returns boolean
* @return a new {@link MantisStream}
*/
MantisStream<T> filter(FilterFunction<T> filterFn);
/**
* Applies the provided {@link MapFunction} to each element in the stream
* and returns a new stream consisting of result elements. The function is
* applied independently to each element in the stream.
*
* @param mapFn the function to apply to each element in the stream.
* @param <OUT> the type of the output elements in the resulting stream.
* @return a new {@link MantisStream}
*/
<OUT> MantisStream<OUT> map(MapFunction<T, OUT> mapFn);
/**
* Applies the provided {@link FlatMapFunction} to each element in the stream
* and returns a new stream consisting of result elements. The function is
* applied independently to each element in the stream. Compared to
* {@link MapFunction}, each element might produce zero, one, or more elements.
*
* @param flatMapFn the function to apply to each element in the stream.
* @param <OUT> the type of the output elements in the resulting stream.
* @return a new {@link MantisStream}
*/
<OUT> MantisStream<OUT> flatMap(FlatMapFunction<T, OUT> flatMapFn);
/**
* Operators are chained by default meaning processed in the same stage
* (worker-thread). Materialize breaks this chaining and all the pending
* operators are combined into a single scalar stage.
* Any subsequent operators will go into a new scalar stage [with chaining]
*
* @return a new {@link MantisStream} instance
*/
MantisStream<T> materialize();
/**
* Partitions the elements of the stream based on the key extracted by
* {@link KeyByFunction}. Elements with the same key are assigned to the same partition.
* This keyBy is distributed and each key is handled on a single worker possibly
* handling many key groups.
*
* @param keyFn the function to extract the key from each element in the stream.
* @param <K> the type of the key.
* @return a new {@link KeyedMantisStream} with elements partitioned based on the keys.
*/
<K> KeyedMantisStream<K, T> keyBy(KeyByFunction<K, T> keyFn);
}
| 8,631 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/OperandNode.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.common.codec.Codecs;
import java.io.Serializable;
import lombok.Getter;
@Getter
class OperandNode<T> {
private final int nodeIdx;
private final String description;
private final Codec<Serializable> codec;
public OperandNode(int i, String description) {
this.nodeIdx = i;
this.description = description;
this.codec = Codecs.javaSerializer();
}
public static <T> OperandNode<T> create(MantisGraph graph, String description) {
return new OperandNode<>(graph.nodes().size(), description);
}
@Override
public String toString() {
return String.format("%d (%s)", nodeIdx, description);
}
public <K extends Serializable> Codec<K> getKeyCodec() {
return Codecs.javaSerializer();
}
}
| 8,632 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/MantisJobBuilder.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.common.codec.Codec;
import io.mantisrx.runtime.Config;
import io.mantisrx.runtime.GroupToGroup;
import io.mantisrx.runtime.GroupToScalar;
import io.mantisrx.runtime.KeyToKey;
import io.mantisrx.runtime.KeyToScalar;
import io.mantisrx.runtime.KeyedStages;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.ScalarStages;
import io.mantisrx.runtime.ScalarToGroup;
import io.mantisrx.runtime.ScalarToKey;
import io.mantisrx.runtime.ScalarToScalar;
import io.mantisrx.runtime.SourceHolder;
import io.mantisrx.runtime.Stages;
import io.mantisrx.runtime.computation.Computation;
import io.mantisrx.runtime.computation.GroupComputation;
import io.mantisrx.runtime.computation.GroupToScalarComputation;
import io.mantisrx.runtime.computation.KeyComputation;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.computation.ToGroupComputation;
import io.mantisrx.runtime.computation.ToKeyComputation;
import io.mantisrx.runtime.computation.ToScalarComputation;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import io.mantisrx.runtime.sink.SelfDocumentingSink;
import io.mantisrx.runtime.sink.Sink;
import io.mantisrx.runtime.source.Source;
import io.mantisrx.shaded.com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MantisJobBuilder {
private SourceHolder<?> sourceHolder;
private Stages<?> currentStage;
private Config<?> jobConfig;
MantisJobBuilder() {}
public Config<?> buildJobConfig() {
Preconditions.checkNotNull(jobConfig, "Need to configure a sink for the stream to build MantisJob. `jobConfig` is null!");
return jobConfig;
}
public MantisJobBuilder addStage(Source<?> source) {
this.sourceHolder = MantisJob.source(source);
return this;
}
public MantisJobBuilder addStage(Computation compFn, Codec<?> codec) {
if (compFn == null) {
return null;
}
return this.addStage(compFn, codec, null);
}
public MantisJobBuilder addStage(Computation compFn, Codec<?> codec, Codec<?> keyCodec) {
if (compFn == null) {
return this;
}
if (this.sourceHolder == null) {
throw new IllegalArgumentException(
"SourceHolder not currently set. Uninitialized MantisJob configuration");
}
if (currentStage == null) {
this.currentStage = addInitStage(compFn, codec, keyCodec);
} else {
this.currentStage = addMoreStages(compFn, codec, keyCodec);
}
return this;
}
public MantisJobBuilder addStage(Sink<?> sink) {
ScalarStages scalarStages = (ScalarStages) this.currentStage;
this.jobConfig = scalarStages.sink(sink);
return this;
}
public MantisJobBuilder addStage(SelfDocumentingSink<?> sink) {
ScalarStages scalarStages = (ScalarStages) this.currentStage;
this.jobConfig = scalarStages.sink(sink);
return this;
}
private Stages<?> addInitStage(Computation compFn, Codec<?> codec, Codec<?> keyCodec) {
if (compFn instanceof ScalarComputation) {
return this.sourceHolder.stage((ScalarComputation) compFn, new ScalarToScalar.Config().codec(codec));
} else if (compFn instanceof ToGroupComputation) {
return this.sourceHolder.stage((ToGroupComputation) compFn, new ScalarToGroup.Config().codec(codec).keyCodec(keyCodec));
}
return this.sourceHolder.stage((ToKeyComputation) compFn, new ScalarToKey.Config().codec(codec).keyCodec(keyCodec));
}
private Stages<?> addMoreStages(Computation compFn, Codec<?> codec, Codec<?> keyCodec) {
if (this.currentStage instanceof ScalarStages) {
ScalarStages scalarStages = (ScalarStages) this.currentStage;
if (compFn instanceof ScalarComputation) {
return scalarStages.stage((ScalarComputation) compFn, new ScalarToScalar.Config().codec(codec));
} else if (compFn instanceof ToKeyComputation) {
return scalarStages.stage((ToKeyComputation) compFn, new ScalarToKey.Config().codec(codec).keyCodec(keyCodec));
}
return scalarStages.stage((ToGroupComputation) compFn, new ScalarToGroup.Config().codec(codec).keyCodec(keyCodec));
}
KeyedStages keyedStages = (KeyedStages) this.currentStage;
if (compFn instanceof ToScalarComputation) {
return keyedStages.stage((ToScalarComputation) compFn, new KeyToScalar.Config().codec(codec));
} else if (compFn instanceof GroupToScalarComputation) {
return keyedStages.stage((GroupToScalarComputation) compFn, new GroupToScalar.Config().codec(codec));
} else if (compFn instanceof KeyComputation) {
return keyedStages.stage((KeyComputation) compFn, new KeyToKey.Config().codec(codec).keyCodec(keyCodec));
}
return keyedStages.stage((GroupComputation) compFn, new GroupToGroup.Config().codec(codec).keyCodec(keyCodec));
}
public MantisJobBuilder addParameters(Iterable<ParameterDefinition<?>> params) {
params.forEach(p -> this.jobConfig = this.jobConfig.parameterDefinition(p));
return this;
}
}
| 8,633 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/KeyedMantisStream.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.runtime.core.functions.FilterFunction;
import io.mantisrx.runtime.core.functions.FlatMapFunction;
import io.mantisrx.runtime.core.functions.MapFunction;
import io.mantisrx.runtime.core.functions.ReduceFunction;
public interface KeyedMantisStream<K, IN> {
/**
* Applies the provided {@link MapFunction} to each element in the stream
* and returns a new keyed stream consisting of result elements partitioned
* with existing keys.
*
* @param mapFn the function to apply to each element in the stream.
* @param <OUT> the type of the output elements in the resulting stream.
* @return a new {@link KeyedMantisStream}
*/
<OUT> KeyedMantisStream<K, OUT> map(MapFunction<IN, OUT> mapFn);
/**
* Applies the provided {@link FlatMapFunction} to each element in the stream
* and returns a new keyed stream consisting of result elements partitioned
* with existing keys.
* Compared to {@link MapFunction}, each element might produce zero, one,
* or more elements.
*
* @param flatMapFn the function to apply to each element in the stream.
* @param <OUT> the type of the output elements in the resulting stream.
* @return a new {@link KeyedMantisStream}
*/
<OUT> KeyedMantisStream<K, OUT> flatMap(FlatMapFunction<IN, OUT> flatMapFn);
/**
* Applies the provided {@link FilterFunction} to each element in the stream
* and returns all elements that match {@code filterFn.apply()}. The function is
* applied independently to each element in the stream.
*
* @param filterFn the function to apply on each element in the stream. Returns boolean
* @return a new {@link KeyedMantisStream}
*/
KeyedMantisStream<K, IN> filter(FilterFunction<IN> filterFn);
/**
*
* Defines a windowing operation that partitions the stream into windows of
* elements, based on the provided {@link WindowSpec}.
*
* This method defines a windowing operation that partitions the stream into
* windows of elements, based on the provided {@link WindowSpec}. The
* {@link WindowSpec} defines the criteria for creating windows, such as the
* window size, the sliding interval, or the type of trigger to use.
* Mantis primarily deals with operational metrics and so usually involves
* processing times only.
* This method can only be applied to a {@link KeyedMantisStream}, as the
* windowing operation requires partitioning the stream by key.
* Also, the current implementation requires a window function in
* {@link KeyedMantisStream} that is immediately followed by a
* {@link KeyedMantisStream#reduce(ReduceFunction)}
*
* @param spec the specification of the windows to create.
* @return a {@link KeyedMantisStream} that applies the windowing operation*
*/
KeyedMantisStream<K, IN> window(WindowSpec spec);
/**
* Defines a reduction operation that aggregates elements in the stream using
* the provided {@link ReduceFunction}.
*
* This method defines a reduction operation that aggregates elements in the
* stream using the provided {@link ReduceFunction}. The {@link ReduceFunction}
* defines the logic to combine multiple elements into a single, aggregated
* result.
*
* The method returns a new {@link MantisStream} that contains the results of
* the reduction operation. The resulting stream contains only the output
* elements generated by the {@link ReduceFunction}, and not the intermediate
* values produced during the aggregation.
*
* The type of the output elements in the resulting stream is determined by the
* type parameter of the {@link ReduceFunction}.
*
* Note: This function must immediately follow {@link KeyedMantisStream#window(WindowSpec)}
* because of current implementation assumptions.
*
* @param reduceFn the function that aggregates elements in the stream.
* @param <OUT> the type of the elements in the output stream.
* @return a new {@link MantisStream} with result of reduction operation.
*/
<OUT> MantisStream<OUT> reduce(ReduceFunction<IN, OUT> reduceFn);
}
| 8,634 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/Collector.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Collector<OUT> {
ConcurrentLinkedQueue<Optional<OUT>> queue = new ConcurrentLinkedQueue<>();
void add(OUT element) {
queue.add(Optional.ofNullable(element));
}
Iterable<Optional<OUT>> iterable() {
return queue;
}
}
| 8,635 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/KeyedMantisStreamImpl.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.runtime.core.functions.FilterFunction;
import io.mantisrx.runtime.core.functions.FlatMapFunction;
import io.mantisrx.runtime.core.functions.MantisFunction;
import io.mantisrx.runtime.core.functions.MapFunction;
import io.mantisrx.runtime.core.functions.ReduceFunction;
import io.mantisrx.runtime.core.functions.WindowFunction;
class KeyedMantisStreamImpl<K, T> implements KeyedMantisStream<K, T> {
final OperandNode<T> currNode;
final MantisGraph graph;
public KeyedMantisStreamImpl(OperandNode<T> node, MantisGraph graph) {
this.currNode = node;
this.graph = graph;
}
<OUT> KeyedMantisStream<K, OUT> updateGraph(MantisFunction mantisFn) {
OperandNode<OUT> node = OperandNode.create(graph, mantisFn.getClass().getName() + "OUT");
graph.putEdge(currNode, node, mantisFn);
return new KeyedMantisStreamImpl<>(node, graph);
}
@Override
public <OUT> KeyedMantisStream<K, OUT> map(MapFunction<T, OUT> mapFn) {
//todo(hmittal): figure out a way to make the key available inside these functions
return updateGraph(mapFn);
}
@Override
public <OUT> KeyedMantisStream<K, OUT> flatMap(FlatMapFunction<T, OUT> flatMapFn) {
return updateGraph(flatMapFn);
}
@Override
public KeyedMantisStream<K, T> filter(FilterFunction<T> filterFn) {
return updateGraph(filterFn);
}
public KeyedMantisStream<K, T> window(WindowSpec spec) {
this.graph.putEdge(currNode, currNode, new WindowFunction<>(spec));
return new KeyedMantisStreamImpl<>(currNode, graph);
}
@Override
public <OUT> MantisStream<OUT> reduce(ReduceFunction<T, OUT> reduceFn) {
OperandNode<OUT> node = OperandNode.create(graph, "reduceFunctionOut");
this.graph.putEdge(currNode, node, reduceFn);
this.graph.putEdge(node, node, MantisFunction.empty());
return new MantisStreamImpl<>(node, graph);
}
}
| 8,636 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/MantisGraph.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import io.mantisrx.runtime.core.functions.MantisFunction;
import io.mantisrx.shaded.com.google.common.graph.ImmutableValueGraph;
import io.mantisrx.shaded.com.google.common.graph.MutableValueGraph;
import io.mantisrx.shaded.com.google.common.graph.ValueGraphBuilder;
import java.util.Set;
class MantisGraph {
private final MutableValueGraph<OperandNode<?>, MantisFunction> graph;
MantisGraph() {
this(ValueGraphBuilder.directed().allowsSelfLoops(true).build());
}
MantisGraph(MutableValueGraph<OperandNode<?>, MantisFunction> graph) {
this.graph = graph;
}
Set<OperandNode<?>> nodes() {
return this.graph.nodes();
}
MantisGraph addNode(OperandNode<?> node) {
this.graph.addNode(node);
return this;
}
MantisGraph putEdge(OperandNode<?> from, OperandNode<?> to, MantisFunction edge) {
this.graph.addNode(from);
this.graph.addNode(to);
this.graph.putEdgeValue(from, to, edge);
return this;
}
public ImmutableValueGraph<OperandNode<?>, MantisFunction> immutable() {
return ImmutableValueGraph.copyOf(this.graph);
}
}
| 8,637 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/WindowSpec.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core;
import java.time.Duration;
import lombok.Getter;
@Getter
public
class WindowSpec {
private final WindowType type;
private int numElements;
private int elementOffset;
private Duration windowLength;
private Duration windowOffset;
WindowSpec(WindowType type, Duration windowLength, Duration windowOffset) {
this.type = type;
this.windowLength = windowLength;
this.windowOffset = windowOffset;
}
WindowSpec(WindowType type, int numElements, int elementOffset) {
this.type = type;
this.numElements = numElements;
this.elementOffset = elementOffset;
}
/**
*
* Creates a time-based window specification for windows of the specified
* length. The window type is {@link WindowType#TUMBLING}, which means that
* non-overlapping windows are created.
*
* @param windowLength the length of the windows
* @return the time-based window specification
*/
public static WindowSpec timed(Duration windowLength) {
return new WindowSpec(WindowType.TUMBLING, windowLength, windowLength);
}
/**
*
* Creates a time-based window specification for sliding windows of the specified
* length and offset. The window type is {@link WindowType#SLIDING}, which means
* that overlapping windows are created.
*
* @param windowLength the length of the windows
* @param windowOffset the offset between the start of adjacent windows
* @return the time-based window specification
*/
public static WindowSpec timed(Duration windowLength, Duration windowOffset) {
return new WindowSpec(WindowType.SLIDING, windowLength, windowOffset);
}
/**
*
* Creates an element-based window specification for windows of the specified
* number of elements. The window type is {@link WindowType#ELEMENT}, which
* means that non-overlapping windows are created.
*
* @param numElements the number of elements per window
* @return the element-based window specification
*/
public static WindowSpec count(int numElements) {
return new WindowSpec(WindowType.ELEMENT, numElements, numElements);
}
/**
*
* Creates an element-based window specification for sliding windows of the
* specified number of elements and offset. The window type is
* {@link WindowType#ELEMENT_SLIDING}, which means that overlapping windows
* are created.
*
* @param numElements the number of elements per window
* @param elementOffset the offset between the start of adjacent windows
* @return the element-based window specification
*/
public static WindowSpec count(int numElements, int elementOffset) {
return new WindowSpec(WindowType.ELEMENT_SLIDING, numElements, elementOffset);
}
public enum WindowType {
TUMBLING,
SLIDING,
ELEMENT,
ELEMENT_SLIDING
}
}
| 8,638 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/sinks/SinkFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.sinks;
import io.mantisrx.runtime.core.functions.MantisFunction;
public class SinkFunction<IN> implements MantisFunction {
}
| 8,639 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/sinks/ObservableSinkImpl.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.sinks;
import io.mantisrx.runtime.sink.SelfDocumentingSink;
import io.mantisrx.runtime.sink.Sink;
import lombok.Getter;
public class ObservableSinkImpl<T> extends SinkFunction<T> {
@Getter
private final Sink<T> sink;
public ObservableSinkImpl(SelfDocumentingSink<T> sink) {
this.sink = sink;
}
public ObservableSinkImpl(Sink<T> sink) {
this.sink = sink;
}
}
| 8,640 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/sources/SourceFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.sources;
import io.mantisrx.runtime.core.functions.MantisFunction;
public interface SourceFunction<OUT> extends MantisFunction {
OUT next();
}
| 8,641 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/sources/ObservableSourceImpl.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.sources;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.source.Index;
import io.mantisrx.runtime.source.Source;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import lombok.Getter;
import rx.Subscription;
public class ObservableSourceImpl<R> implements SourceFunction<R> {
@Getter
private final Source<R> source;
private final AtomicReference<R> elemContainer = new AtomicReference<>();
private Subscription subscription;
public ObservableSourceImpl(Source<R> source) {
this.source = source;
}
@Override
public void init() {
Context context = new Context();
Index index = new Index(0, 0);
this.source.init(context, index);
subscription = this.source
.call(context, index)
.flatMap(x -> x)
// single element buffer as a POC!
.subscribe(elemContainer::set);
}
@Override
public void close() throws IOException {
if (subscription != null) {
subscription.unsubscribe();
}
}
@Override
public R next() {
return elemContainer.get();
}
}
| 8,642 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/FunctionCombinator.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.computation.Computation;
import io.mantisrx.runtime.computation.GroupToScalarComputation;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.core.WindowSpec;
import io.mantisrx.shaded.com.google.common.annotations.VisibleForTesting;
import io.mantisrx.shaded.com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import rx.Observable;
public class FunctionCombinator<T, R> {
@Getter
private final boolean isKeyed;
private final List<MantisFunction> functions;
public FunctionCombinator(boolean isKeyed) {
this(isKeyed, ImmutableList.of());
}
public FunctionCombinator(boolean isKeyed, List<MantisFunction> functions) {
this.isKeyed = isKeyed;
this.functions = functions;
}
public <IN, OUT> FunctionCombinator<T, OUT> add(MantisFunction fn) {
ImmutableList<MantisFunction> functions = ImmutableList.<MantisFunction>builder().addAll(this.functions).add(fn).build();
return new FunctionCombinator<>(this.isKeyed, functions);
}
public int size() {
return functions.size();
}
@VisibleForTesting
<U, V> ScalarComputation<U, V> makeScalarStage() {
return new ScalarComputation<U, V>() {
@Override
public void init(Context context) {
functions.forEach(MantisFunction::init);
}
@Override
public Observable<V> call(Context context, Observable<U> uObservable) {
Observable<?> current = uObservable;
for (MantisFunction fn : functions) {
if (fn instanceof FilterFunction) {
current = current.filter(((FilterFunction) fn)::apply);
} else if (fn instanceof MapFunction) {
current = current.map(e -> ((MapFunction) fn).apply(e));
} else if (fn instanceof FlatMapFunction) {
current = current.flatMap(e -> Observable.from(((FlatMapFunction) fn).apply(e)));
}
}
return (Observable<V>) current;
}
};
}
@VisibleForTesting
<K, U, V> GroupToScalarComputation<K, U, V> makeGroupToScalarStage() {
return new GroupToScalarComputation<K, U, V>() {
@Override
public void init(Context context) {
functions.forEach(MantisFunction::init);
}
@Override
public Observable<V> call(Context context, Observable<MantisGroup<K, U>> gobs) {
Observable<?> observable = gobs.groupBy(MantisGroup::getKeyValue).flatMap(gob -> {
Observable<?> current = gob.map(MantisGroup::getValue);
K key = gob.getKey();
for (MantisFunction fn : functions) {
if (fn instanceof FilterFunction) {
current = current.filter(((FilterFunction) fn)::apply);
} else if (fn instanceof MapFunction) {
current = current.map(x -> ((MapFunction) fn).apply(x));
} else if (fn instanceof FlatMapFunction) {
current = current.flatMap(x -> Observable.from(((FlatMapFunction) fn).apply(x)));
} else if (fn instanceof WindowFunction) {
current = handleWindows(current, (WindowFunction) fn);
} else if (fn instanceof ReduceFunction) {
ReduceFunction reduceFn = (ReduceFunction) fn;
current = ((Observable<Observable<?>>) current)
.map(obs -> obs.reduce(reduceFn.initialValue(), (acc, e) -> reduceFn.reduce(acc, e)))
.flatMap(x -> x)
.filter(x -> x != SimpleReduceFunction.EMPTY);
}
}
return current;
});
return (Observable<V>) observable;
}
};
}
private Observable<? extends Observable<?>> handleWindows(Observable<?> obs, WindowFunction<?> windowFn) {
WindowSpec spec = windowFn.getSpec();
switch (spec.getType()) {
case ELEMENT:
case ELEMENT_SLIDING:
return obs.window(spec.getNumElements(), spec.getElementOffset());
case TUMBLING:
case SLIDING:
return obs.window(spec.getWindowLength().toMillis(), spec.getWindowOffset().toMillis(), TimeUnit.MILLISECONDS);
}
throw new UnsupportedOperationException("Unknown WindowSpec must be one of " + Arrays.toString(WindowSpec.WindowType.values()));
}
public Computation makeStage() {
if (size() == 0) {
return null;
}
if (isKeyed) {
return makeGroupToScalarStage();
}
return makeScalarStage();
}
}
| 8,643 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/FlatMapFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
* Functional interface for mapping an input value of type {@code IN}
* to an iterable of output values of type {@code OUT}.
* There could be zero, one, or more output elements.
* {@code FunctionalInterface} allows java-8 lambda
*/
@FunctionalInterface
public interface FlatMapFunction<IN, OUT> extends MantisFunction {
/**
* Applies the flat map function to the given input value.
@param in the input value
@return an iterable of output values
*/
Iterable<OUT> apply(IN in);
}
| 8,644 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/FilterFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
*
* A functional interface that defines a filter operation on a stream of
* input elements of type {@code IN}.
* @param <IN> the type of the input elements.
*/
@FunctionalInterface
public interface FilterFunction<IN> extends MantisFunction {
/**
*
* Tests whether an input element should be included in the output stream.
* @param in the input element.
* @return {@code true} if the input element should be included in the
* output stream, {@code false} otherwise.
*/
boolean apply(IN in);
}
| 8,645 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/MantisFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
public interface MantisFunction extends AutoCloseable {
MantisFunction EMPTY = new MantisFunction() {};
static MantisFunction empty() {
return EMPTY;
}
default void init() {
}
@Override
default void close() throws Exception {
}
}
| 8,646 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/ReduceFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
* Functional interface for reducing a collection of input values of type
* {@code IN} to a single output value of type {@code OUT}.
*/
public interface ReduceFunction<IN, OUT> extends MantisFunction {
/**
* Returns the initial value for the reduce operation.
* @return the initial value
*/
OUT initialValue();
/**
*
* Reduces the given input value using the accumulator.
* @param acc the accumulator
* @param in the input value to reduce
* @return the reduced output value
*/
OUT reduce(OUT acc, IN in);
}
| 8,647 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/SimpleReduceFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
* Functional interface for reducing a collection of input values of type {@code IN}
* to a single output value of type {@code IN}.
*
* This implementation extends the {@link ReduceFunction} interface and provides a
* single method for reducing the given input value using the accumulator.
*/
@FunctionalInterface
public interface SimpleReduceFunction<IN> extends ReduceFunction<IN, IN> {
Object EMPTY = new Object();
/**
* Applies the reduce operation to the given accumulator and input value.
*
* If no values are to be returned, returns {@link SimpleReduceFunction#EMPTY}
* instead. This means {@link SimpleReduceFunction#apply(IN, IN)} isn't
* called for the first item which is returned as-is. For subsequent items,
* apply is called normally.
*
* @param acc current accumulator value
* @param item the input value to reduce
* @return the reduced output value
*/
IN apply(IN acc, IN item);
@Override
default IN initialValue() {
return (IN) EMPTY;
}
@Override
default IN reduce(IN acc, IN item) {
if (acc == EMPTY) {
return item;
} else {
return apply(acc, item);
}
}
}
| 8,648 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/MapFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
* Functional interface for mapping an input value of type {@code IN}
* to an output value of type {@code OUT}.
*/
@FunctionalInterface
public interface MapFunction<IN, OUT> extends MantisFunction {
/**
* Applies the map function to the given input value.
* @param in the input value
* @return the output value
*/
OUT apply(IN in);
}
| 8,649 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/WindowFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
import io.mantisrx.runtime.core.WindowSpec;
import lombok.Getter;
/**
* A function that defines a window for grouping and processing elements of type
* {@code IN}. The window is defined by a {@link WindowSpec} object.
*/
public class WindowFunction<IN> implements MantisFunction {
/**
* The window specification defining window boundaries and triggers.
*/
@Getter
private final WindowSpec spec;
/**
*
* Constructs a new window function with the given window specification.
* @param spec the window specification
*/
public WindowFunction(WindowSpec spec) {
this.spec = spec;
}
}
| 8,650 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/core/functions/KeyByFunction.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.core.functions;
/**
* Functional interface for extracting a key of type {@code K} from an input value
* of type {@code IN}.
*/
@FunctionalInterface
public interface KeyByFunction<K, IN> extends MantisFunction {
/**
* Extracts a key from the given input value.
*
* @param in the input value
* @return the extracted key
*/
K getKey(IN in);
}
| 8,651 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/markers/StageIn.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.markers;
import rx.Observable.Operator;
import rx.Subscriber;
public class StageIn<T> implements Operator<T, T> {
@Override
public Subscriber<? super T> call(final Subscriber<? super T> o) {
return new Subscriber<T>(o) {
@Override
public void onCompleted() {
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(T t) {
o.onNext(t);
}
};
}
}
| 8,652 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/markers/StageOut.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.markers;
import rx.Observable.Operator;
import rx.Subscriber;
public class StageOut<T> implements Operator<T, T> {
@Override
public Subscriber<? super T> call(final Subscriber<? super T> o) {
return new Subscriber<T>(o) {
@Override
public void onCompleted() {
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(T t) {
o.onNext(t);
}
};
}
}
| 8,653 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/markers/MantisMarker.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.markers;
import rx.Observable;
public class MantisMarker {
public static <T> Observable<T> sourceOut(Observable<T> source) {
return source.lift(new SourceOut<T>());
}
public static <T> Observable<T> stageIn(Observable<T> source) {
return source.lift(new StageIn<T>());
}
public static <T> Observable<T> stageOut(Observable<T> source) {
return source.lift(new StageOut<T>());
}
public static <T> Observable<T> networkMerge(Observable<T> source) {
return source.lift(new NetworkMerge<T>());
}
}
| 8,654 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/markers/NetworkMerge.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.markers;
import rx.Observable.Operator;
import rx.Subscriber;
public class NetworkMerge<T> implements Operator<T, T> {
@Override
public Subscriber<? super T> call(final Subscriber<? super T> o) {
return new Subscriber<T>(o) {
@Override
public void onCompleted() {
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(T t) {
o.onNext(t);
}
};
}
}
| 8,655 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/markers/SourceOut.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.markers;
import rx.Observable.Operator;
import rx.Subscriber;
public class SourceOut<T> implements Operator<T, T> {
@Override
public Subscriber<? super T> call(final Subscriber<? super T> o) {
return new Subscriber<T>(o) {
@Override
public void onCompleted() {
o.onCompleted();
}
@Override
public void onError(Throwable e) {
o.onError(e);
}
@Override
public void onNext(T t) {
o.onNext(t);
}
};
}
}
| 8,656 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/Index.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source;
import rx.Observable;
import rx.subjects.BehaviorSubject;
public class Index {
private final int workerIndex;
private final Observable<Integer> totalNumWorkersObservable;
public Index(int offset, int total) {
this.workerIndex = offset;
this.totalNumWorkersObservable = BehaviorSubject.create(total);
}
public Index(int offset, final Observable<Integer> totalWorkerAtStageObservable) {
this.workerIndex = offset;
this.totalNumWorkersObservable = totalWorkerAtStageObservable;
}
public int getWorkerIndex() {
return workerIndex;
}
public int getTotalNumWorkers() {
return totalNumWorkersObservable.take(1).toBlocking().first();
}
public Observable<Integer> getTotalNumWorkersObservable() {
return totalNumWorkersObservable;
}
@Override
public String toString() {
return "InputQuota [offset=" + workerIndex + ", total=" + getTotalNumWorkers() + "]";
}
}
| 8,657 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/SelfDocumentingSource.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source;
import io.mantisrx.runtime.Metadata;
public interface SelfDocumentingSource<T> extends Source<T> {
public Metadata metadata();
}
| 8,658 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/Source.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.functions.Func2;
public interface Source<T> extends Func2<Context, Index, Observable<Observable<T>>>, Closeable {
default List<ParameterDefinition<?>> getParameters() {
return Collections.emptyList();
}
default void init(Context context, Index index) {
}
@Override
default void close() throws IOException {
}
}
| 8,659 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/Sources.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source;
import io.mantisrx.runtime.Context;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Func1;
public class Sources {
private Sources() {}
public static <T> Source<T> observable(final Observable<T> o) {
return new Source<T>() {
@Override
public Observable<Observable<T>> call(Context context, Index t1) {
return Observable.just(o);
}
@Override
public void close() throws IOException {
}
};
}
public static <T> Source<T> observables(final Observable<Observable<T>> o) {
return new Source<T>() {
@Override
public Observable<Observable<T>> call(Context context, Index t1) {
return o;
}
@Override
public void close() throws IOException {
}
};
}
public static Source<Integer> integerPerSecond() {
return integers(0, 1);
}
public static Source<Integer> integerPerSecond(int initialDelay) {
return integers(initialDelay, 1);
}
public static Source<Integer> integers(final int initialDelay, final long periodInSec) {
return new Source<Integer>() {
@Override
public Observable<Observable<Integer>> call(Context t1, Index t2) {
return Observable.just(Observable.interval(initialDelay, periodInSec, TimeUnit.SECONDS)
.map(new Func1<Long, Integer>() {
@Override
public Integer call(Long t1) {
return (int) (long) t1;
}
}));
}
@Override
public void close() throws IOException {
}
};
}
}
| 8,660 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/ContextualHttpSource.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.source.Index;
import io.mantisrx.runtime.source.Source;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent;
import io.mantisrx.runtime.source.http.impl.ServerContext;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import rx.Observable;
import rx.Observer;
public class ContextualHttpSource<E> implements Source<ServerContext<E>> {
private final HttpSourceImpl<ByteBuf, E, ServerContext<E>> impl;
private ContextualHttpSource(HttpSourceImpl<ByteBuf, E, ServerContext<E>> impl) {
this.impl = impl;
}
public static <E> Builder<E> builder(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory) {
HttpSourceImpl.Builder<ByteBuf, E, ServerContext<E>> builderImpl = HttpSourceImpl
.builder(
clientFactory,
requestFactory,
HttpSourceImpl.<E>contextWrapper());
return new Builder<>(builderImpl);
}
public static <E> Builder<E> builder(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory, ClientResumePolicy<ByteBuf, E> policy) {
HttpSourceImpl.Builder<ByteBuf, E, ServerContext<E>> builderImpl = HttpSourceImpl
.builder(
clientFactory,
requestFactory,
HttpSourceImpl.<E>contextWrapper(),
policy);
return new Builder<>(builderImpl);
}
@Override
public Observable<Observable<ServerContext<E>>> call(Context context, Index t2) {
return impl.call(context, t2);
}
@Override
public void close() throws IOException {
impl.close();
}
public static class Builder<E> {
private final HttpSourceImpl.Builder<ByteBuf, E, ServerContext<E>> builderImpl;
private Builder(HttpSourceImpl.Builder<ByteBuf, E, ServerContext<E>> builderImpl) {
this.builderImpl = builderImpl;
}
public Builder<E> withServerProvider(HttpServerProvider serverProvider) {
builderImpl.withServerProvider(serverProvider);
return this;
}
public Builder<E> withActivityObserver(Observer<HttpSourceEvent> observer) {
builderImpl.withActivityObserver(observer);
return this;
}
public Builder<E> resumeWith(ClientResumePolicy<ByteBuf, E> policy) {
builderImpl.resumeWith(policy);
return this;
}
public ContextualHttpSource<E> build() {
return new ContextualHttpSource<>(builderImpl.build());
}
}
} | 8,661 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/HttpClientFactory.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import mantis.io.reactivex.netty.protocol.http.client.HttpClient;
/**
* A factory that creates new {@link mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest} for a given server, which is uniquely identified
* by its host name and a given port.
*
* @param <R> The request entity's type
* @param <E> The response entity's type
*/
public interface HttpClientFactory<R, E> {
HttpClient<R, E> createClient(ServerInfo server);
}
| 8,662 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/HttpServerProvider.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import rx.Observable;
public interface HttpServerProvider {
Observable<ServerInfo> getServersToAdd();
Observable<ServerInfo> getServersToRemove();
}
| 8,663 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/ServerPoller.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import java.util.Set;
import mantis.io.reactivex.netty.client.RxClient;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import rx.Observable;
public interface ServerPoller {
Observable<Set<RxClient.ServerInfo>> servers();
public Set<ServerInfo> getServers();
}
| 8,664 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/HttpSource.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.source.Index;
import io.mantisrx.runtime.source.Source;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import rx.Observable;
import rx.Observer;
public class HttpSource<E, T> implements Source<T> {
private final HttpSourceImpl<ByteBuf, E, T> impl;
private HttpSource(HttpSourceImpl<ByteBuf, E, T> impl) {
this.impl = impl;
}
public static <E, T> Builder<E, T> builder(HttpSourceImpl.Builder<ByteBuf, E, T> builderImpl) {
return new Builder<>(builderImpl);
}
public static <E> Builder<E, E> builder(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory) {
HttpSourceImpl.Builder<ByteBuf, E, E> builderImpl = HttpSourceImpl
.builder(
clientFactory,
requestFactory,
HttpSourceImpl.<E>identityConverter());
return new Builder<>(builderImpl);
}
public static <E> Builder<E, E> builder(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory, ClientResumePolicy<ByteBuf, E> policy) {
HttpSourceImpl.Builder<ByteBuf, E, E> builderImpl = HttpSourceImpl
.builder(
clientFactory,
requestFactory,
HttpSourceImpl.<E>identityConverter(),
policy);
return new Builder<>(builderImpl);
}
@Override
public Observable<Observable<T>> call(Context context, Index index) {
return impl.call(context, index);
}
@Override
public void close() throws IOException {
impl.close();
}
public static class Builder<E, T> {
private final HttpSourceImpl.Builder<ByteBuf, E, T> builderImpl;
private Builder(HttpSourceImpl.Builder<ByteBuf, E, T> builderImpl) {
this.builderImpl = builderImpl;
}
public Builder<E, T> withServerProvider(HttpServerProvider serverProvider) {
builderImpl.withServerProvider(serverProvider);
return this;
}
public Builder<E, T> withActivityObserver(Observer<HttpSourceEvent> observer) {
builderImpl.withActivityObserver(observer);
return this;
}
public Builder<E, T> resumeWith(ClientResumePolicy<ByteBuf, E> policy) {
builderImpl.resumeWith(policy);
return this;
}
public HttpSource<E, T> build() {
return new HttpSource<>(builderImpl.build());
}
}
} | 8,665 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/ClientResumePolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import io.mantisrx.runtime.source.http.impl.ServerClientContext;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
public interface ClientResumePolicy<R, E> {
/**
* Returns a new observable when the subscriber's onError() method is called. Return null should resumption will
* not be run.
*
* @param clientContext The client context that offers access to the subscribed server and the logic of creating the
* original stream
* @param attempts The number of resumptions so far
* @param error The error the resulted in the onError() event
*/
Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error);
/**
* Returns a new observable when the subscribed stream is completed. Return null should resumption will
* not be run.
*
* @param clientContext The client context that offers access to the subscribed server and the logic of creating the
* original stream
* @param attempts The number of resumptions so far
*/
Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts);
}
| 8,666 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/HttpRequestFactory.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest;
public interface HttpRequestFactory<T> {
public HttpClientRequest<T> create();
}
| 8,667 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/HttpSources.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import io.mantisrx.runtime.source.http.HttpSource.Builder;
import io.mantisrx.runtime.source.http.impl.HttpClientFactories;
import io.mantisrx.runtime.source.http.impl.HttpRequestFactories;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl;
import io.mantisrx.runtime.source.http.impl.ServerClientContext;
import io.mantisrx.runtime.source.http.impl.ServerContext;
import io.netty.buffer.ByteBuf;
import java.nio.charset.Charset;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
import rx.functions.Func2;
public class HttpSources {
public static <E> Builder<E, E> source(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory) {
return HttpSource.builder(clientFactory, requestFactory);
}
public static <E> Builder<E, E> sourceWithResume(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory, ClientResumePolicy<ByteBuf, E> policy) {
return HttpSource.builder(clientFactory, requestFactory, policy);
}
public static <E> ContextualHttpSource.Builder<E> contextualSource(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory) {
return ContextualHttpSource.builder(clientFactory, requestFactory);
}
public static <E> ContextualHttpSource.Builder<E> contextualSourceWithResume(HttpClientFactory<ByteBuf, E> clientFactory, HttpRequestFactory<ByteBuf> requestFactory, ClientResumePolicy<ByteBuf, E> policy) {
return ContextualHttpSource.builder(clientFactory, requestFactory, policy);
}
/**
* Create a {@code HttpSource} that infinitely polls the give server with the given URL
*
* @param host The host name of the server to be queried
* @param port The port used for query
* @param uri The URI used for query. The URI should be relative to http://host:port/
*
* @return A builder that will return an implementation that polls the give server infinitely
*/
public static Builder<ByteBuf, String> pollingSource(final String host, final int port, String uri) {
HttpClientFactory<ByteBuf, ByteBuf> clientFactory = HttpClientFactories.defaultFactory();
HttpSourceImpl.Builder<ByteBuf, ByteBuf, String> builderImpl = HttpSourceImpl
.builder(
clientFactory,
HttpRequestFactories.createGetFactory(uri),
new Func2<ServerContext<HttpClientResponse<ByteBuf>>, ByteBuf, String>() {
@Override
public String call(ServerContext<HttpClientResponse<ByteBuf>> context, ByteBuf content) {
return content.toString(Charset.defaultCharset());
}
})
.withServerProvider(new HttpServerProvider() {
@Override
public Observable<ServerInfo> getServersToAdd() {
return Observable.just(new ServerInfo(host, port));
}
@Override
public Observable<ServerInfo> getServersToRemove() {
return Observable.empty();
}
})
.resumeWith(new ClientResumePolicy<ByteBuf, ByteBuf>() {
@Override
public Observable<HttpClientResponse<ByteBuf>> onError(ServerClientContext<ByteBuf, ByteBuf> clientContext, int attempts, Throwable error) {
return clientContext.newResponse();
}
@Override
public Observable<HttpClientResponse<ByteBuf>> onCompleted(ServerClientContext<ByteBuf, ByteBuf> clientContext, int attempts) {
return clientContext.newResponse();
}
});
return HttpSource.builder(builderImpl);
}
}
| 8,668 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/ClientResumePolicies.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http;
import io.mantisrx.runtime.source.http.impl.ServerClientContext;
import java.util.concurrent.TimeUnit;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
import rx.functions.Func0;
/**
* Convenient methods to create or combine {@link io.mantisrx.runtime.source.http.ClientResumePolicy}s. All the methods
* follow the following conventions for generic types:
* <ul>
* <li>R: The type of a request payload </li>
* <li>E: The type of the response payload </li>
* </ul>
*/
public class ClientResumePolicies {
/**
* Creates a policy that repeats the given number of times
*
* @param maxRepeat The number of times to resume
* @param <R> The type of request payload
* @param <E> The type of response payload
*/
public static <R, E> ClientResumePolicy<R, E> maxRepeat(final int maxRepeat) {
return new ClientResumePolicy<R, E>() {
@Override
public Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error) {
return getNewResponse(clientContext, attempts);
}
@Override
public Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts) {
return getNewResponse(clientContext, attempts);
}
private Observable<HttpClientResponse<E>> getNewResponse(ServerClientContext<R, E> clientContext, int attempts) {
if (attempts <= maxRepeat) {
return clientContext.newResponse();
}
return null;
}
};
}
public static <R, E> ClientResumePolicy<R, E> noRepeat() {
return new ClientResumePolicy<R, E>() {
@Override
public Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error) {
return null;
}
@Override
public Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts) {
return null;
}
};
}
/**
* Creates a policy that resumes after given delay.
*
* @param delayFunc A function that returns a delay value. The function will be called every time the resume policy is called.
* @param unit The unit of the delay value
* @param <R> The type of request payload
* @param <E> The type of response payload
*/
public static <R, E> ClientResumePolicy<R, E> delayed(final Func0<Long> delayFunc, final TimeUnit unit) {
return new ClientResumePolicy<R, E>() {
@Override
public Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error) {
return createDelayedResponse(clientContext);
}
@Override
public Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts) {
return createDelayedResponse(clientContext);
}
private Observable<HttpClientResponse<E>> createDelayedResponse(ServerClientContext<R, E> clientContext) {
return clientContext.newResponse()
.delaySubscription(delayFunc.call(), unit);
}
};
}
/**
* Returns a new policy that repeats a given policy for the specified times
*
* @param policy The policy to be repeated
* @param maxRepeat The maximum number of repeats
* @param <R> The type of request payload
* @param <E> The type of response payload
*/
public static <R, E> ClientResumePolicy<R, E> maxRepeat(final ClientResumePolicy<R, E> policy, final int maxRepeat) {
return new ClientResumePolicy<R, E>() {
@Override
public Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error) {
if (attempts <= maxRepeat) {
return policy.onError(clientContext, attempts, error);
}
return null;
}
@Override
public Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts) {
if (attempts <= maxRepeat) {
return policy.onCompleted(clientContext, attempts);
}
return null;
}
};
}
}
| 8,669 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/OperatorResumeOnError.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import rx.Observable;
import rx.Observable.Operator;
import rx.Scheduler;
import rx.Scheduler.Worker;
import rx.Subscriber;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import rx.subscriptions.SerialSubscription;
public class OperatorResumeOnError<T> implements Operator<T, T> {
private static final Scheduler scheduler = Schedulers.trampoline();
private final ResumeOnErrorPolicy<T> resumePolicy;
private final int currentAttempts;
private OperatorResumeOnError(int currentAttempts, ResumeOnErrorPolicy<T> resumePolicy) {
this.currentAttempts = currentAttempts;
this.resumePolicy = resumePolicy;
}
public OperatorResumeOnError(ResumeOnErrorPolicy<T> resumePolicy) {
this(0, resumePolicy);
}
@Override
public Subscriber<? super T> call(final Subscriber<? super T> child) {
final SerialSubscription serialSubscription = new SerialSubscription();
child.add(serialSubscription);
return new Subscriber<T>(child) {
private final Worker worker = scheduler.createWorker();
@Override
public void onCompleted() {
child.onCompleted();
}
@Override
public void onError(final Throwable e) {
worker.schedule(new Action0() {
@Override
public void call() {
try {
int newAttempts = currentAttempts + 1;
Observable<? extends T> resume = resumePolicy.call(newAttempts, e);
if (resume == null) {
child.onError(e);
} else {
resume = resume.lift(new OperatorResumeOnError<>(
newAttempts,
resumePolicy
));
serialSubscription.set(resume.unsafeSubscribe(child));
}
} catch (Throwable e2) {
child.onError(e2);
}
}
});
}
@Override
public void onNext(T t) {
child.onNext(t);
}
};
}
}
| 8,670 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/HttpClientFactories.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import io.mantisrx.runtime.source.http.HttpClientFactory;
import io.netty.buffer.ByteBuf;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurators;
import mantis.io.reactivex.netty.protocol.http.client.HttpClient;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientBuilder;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
public class HttpClientFactories {
public static HttpClientFactory<ByteBuf, ByteBuf> defaultFactory() {
return new DefaultHttpClientFactory();
}
public static HttpClientFactory<ByteBuf, ByteBuf> defaultFactory(
boolean enableConnectionPooling,
boolean enableIdleConnectionCleanup) {
return new DefaultHttpClientFactory(enableConnectionPooling, enableIdleConnectionCleanup);
}
public static HttpClientFactory<ByteBuf, ServerSentEvent> sseClientFactory() {
return new SSEClientFactory();
}
/**
* [Deprecated] read timeouts is not longer supported in SSE client factory.
* @param readTimeout
*/
@Deprecated
public static HttpClientFactory<ByteBuf, ServerSentEvent> sseClientFactory(int readTimeout) {
return new SSEClientFactory(readTimeout);
}
public static HttpClientFactory<ByteBuf, ServerSentEvent> sseClientFactory(
boolean enableConnectionPooling,
boolean enableIdleConnectionCleanup) {
return new SSEClientFactory(enableConnectionPooling, enableIdleConnectionCleanup);
}
private static class DefaultHttpClientFactory implements HttpClientFactory<ByteBuf, ByteBuf> {
private final HttpClient.ClientConfig clientConfig;
private final boolean enableConnectionPooling;
private final boolean enableIdleConnectionCleanup;
public DefaultHttpClientFactory() { this(false, false); }
public DefaultHttpClientFactory(boolean enableConnectionPooling, boolean enableIdleConnectionCleanup) {
this.enableConnectionPooling = enableConnectionPooling;
this.enableIdleConnectionCleanup = enableIdleConnectionCleanup;
clientConfig = new HttpClient.HttpClientConfig.Builder()
.setFollowRedirect(true)
.userAgent("Netflix Mantis HTTP Source")
.build();
}
@Override
public HttpClient<ByteBuf, ByteBuf> createClient(ServerInfo server) {
HttpClientBuilder<ByteBuf, ByteBuf> builder =
new HttpClientBuilder<ByteBuf, ByteBuf>(server.getHost(), server.getPort())
.config(clientConfig);
if (!this.enableConnectionPooling) {
builder.withNoConnectionPooling();
}
else {
if (!this.enableIdleConnectionCleanup) {
builder.withNoIdleConnectionCleanup();
}
}
return builder.build();
}
}
private static class SSEClientFactory implements HttpClientFactory<ByteBuf, ServerSentEvent> {
private final boolean enableConnectionPooling;
private final boolean enableIdleConnectionCleanup;
public SSEClientFactory(boolean enableConnectionPooling, boolean enableIdleConnectionCleanup) {
this.enableConnectionPooling = enableConnectionPooling;
this.enableIdleConnectionCleanup = enableIdleConnectionCleanup;
}
public SSEClientFactory(int readTimeout) {
this();
}
public SSEClientFactory() {
this(false, false);
}
@Override
public HttpClient<ByteBuf, ServerSentEvent> createClient(ServerInfo server) {
// ClientConfig clientConfig = new HttpClient.HttpClientConfig.Builder()
// .readTimeout(this.readTimeout, TimeUnit.SECONDS)
// .userAgent("Netflix Mantis HTTP Source")
// .build();
// Forking from original RxNetty.createHttpClient to disable ConnectionPooling or IdleConnectionCleanup
// tasks.
// RxNetty.createHttpClient(
// server.getHost(),
// server.getPort(),
// //PipelineConfigurators.createClientConfigurator(new SseClientPipelineConfigurator<ByteBuf>(), clientConfig));
// PipelineConfigurators.<ByteBuf>clientSseConfigurator());
HttpClientBuilder<ByteBuf, ServerSentEvent> builder =
RxNetty.<ByteBuf, ServerSentEvent>newHttpClientBuilder(server.getHost(), server.getPort())
.pipelineConfigurator(PipelineConfigurators.<ByteBuf>clientSseConfigurator());
if (!this.enableConnectionPooling) {
builder.withNoConnectionPooling();
}
else {
if (!this.enableIdleConnectionCleanup) {
builder.withNoIdleConnectionCleanup();
}
}
return builder.build();
}
}
}
| 8,671 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/StaticServerPoller.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import io.mantisrx.runtime.source.http.ServerPoller;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Scheduler;
import rx.Scheduler.Worker;
import rx.Subscriber;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
public class StaticServerPoller implements ServerPoller {
private final Set<ServerInfo> servers;
private final int periodSeconds;
private final Scheduler scheduler;
public StaticServerPoller(Set<ServerInfo> servers, int periodSeconds, Scheduler scheduler) {
this.servers = Collections.unmodifiableSet(servers);
this.periodSeconds = periodSeconds;
this.scheduler = scheduler;
}
public StaticServerPoller(Set<ServerInfo> servers, int periodSeconds) {
this(servers, periodSeconds, Schedulers.computation());
}
private Worker schedulePolling(final Subscriber<? super Set<ServerInfo>> subscriber) {
final Worker worker = this.scheduler.createWorker();
worker.schedulePeriodically(
new Action0() {
@Override
public void call() {
if (subscriber.isUnsubscribed()) {
worker.unsubscribe();
} else {
subscriber.onNext(servers);
}
}
},
0,
this.periodSeconds,
TimeUnit.SECONDS
);
return worker;
}
@Override
public Observable<Set<ServerInfo>> servers() {
return Observable.create((OnSubscribe<Set<ServerInfo>>) this::schedulePolling);
}
@Override
public Set<ServerInfo> getServers() {
return servers;
}
}
| 8,672 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/DefaultHttpServerProvider.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.runtime.source.http.HttpServerProvider;
import io.mantisrx.runtime.source.http.ServerPoller;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.Subscription;
public class DefaultHttpServerProvider implements HttpServerProvider {
private final ServerPoller serverPoller;
private final Gauge discoveryActiveGauge;
private final Gauge newServersGauge;
private final Gauge removedServersGauge;
protected DefaultHttpServerProvider(ServerPoller serverPoller) {
this.serverPoller = serverPoller;
Metrics m = new Metrics.Builder()
.name("DefaultHttpServerProvider")
.addGauge("discoveryActiveGauge")
.addGauge("newServersGauge")
.addGauge("removedServersGauge")
.build();
m = MetricsRegistry.getInstance().registerAndGet(m);
discoveryActiveGauge = m.getGauge("discoveryActiveGauge");
newServersGauge = m.getGauge("newServersGauge");
removedServersGauge = m.getGauge("removedServersGauge");
}
private static Set<ServerInfo> diff(Set<ServerInfo> left, Set<ServerInfo> right) {
Set<ServerInfo> result = new HashSet<>(left);
result.removeAll(right);
return result;
}
public Set<ServerInfo> getServers() {
return serverPoller.getServers();
}
@Override
public final Observable<ServerInfo> getServersToAdd() {
// We use an Observable.create instead of a simple serverPoller.servers().flatMap(...)
// because we want to create an activeServers object for each subscription
return Observable.create(new OnSubscribe<ServerInfo>() {
@Override
public void call(final Subscriber<? super ServerInfo> subscriber) {
// Single out the assignment to make type inference happy
Set<ServerInfo> empty = Collections.emptySet();
final AtomicReference<Set<ServerInfo>> activeServers = new AtomicReference<>(empty);
Subscription subs = serverPoller.servers()
.subscribe(new Subscriber<Set<ServerInfo>>() {
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(Set<ServerInfo> servers) {
discoveryActiveGauge.set(servers.size());
Set<ServerInfo> currentServers = activeServers.getAndSet(servers);
Set<ServerInfo> newServers = diff(servers, currentServers);
newServersGauge.set(newServers.size());
// for (ServerInfo server : newServers) {
// subscriber.onNext(server);
// }
// always send down all active server list, let the client figure out if it is already connected
for (ServerInfo server : servers) {
subscriber.onNext(server);
}
}
});
// We need to make sure if a subscriber unsubscribes, the server poller
// should stop sending data to the subscriber
subscriber.add(subs);
}
});
}
@Override
public Observable<ServerInfo> getServersToRemove() {
return Observable.create(new OnSubscribe<ServerInfo>() {
@Override
public void call(final Subscriber<? super ServerInfo> subscriber) {
// Single out the assignment to make type inference happy
Set<ServerInfo> empty = Collections.emptySet();
final AtomicReference<Set<ServerInfo>> activeServers = new AtomicReference<>(empty);
Subscription subs = serverPoller.servers()
.subscribe(new Subscriber<Set<ServerInfo>>() {
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(Set<ServerInfo> servers) {
Set<ServerInfo> currentServers = activeServers.getAndSet(servers);
Set<ServerInfo> serversToRemove = diff(currentServers, servers);
removedServersGauge.set(serversToRemove.size());
for (ServerInfo server : serversToRemove) {
subscriber.onNext(server);
}
}
});
// We need to make sure if a subscriber unsubscribes, the server poller
// should stop sending data to the subscriber
subscriber.add(subs);
}
});
}
}
| 8,673 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/ResumeOnErrorPolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import rx.Observable;
import rx.functions.Func2;
/**
* An implementation of this functional interface defines how to resume an {@link rx.Observable} when the
* {@link rx.Observable}'s runs into an error. This is used by an {@link io.mantisrx.runtime.source.http.impl.OperatorResumeOnCompleted} instance.
*
* @param <T> The type of items in the returned new {@link rx.Observable}
*
* @see io.mantisrx.runtime.source.http.impl.OperatorResumeOnCompleted
*/
public interface ResumeOnErrorPolicy<T> extends Func2<Integer, Throwable, Observable<T>> {
/**
* Called when an {@link rx.Observable} needs to be to resumed upon error.
*
* @param attempts The number of the current attempt.
* @param error The error of the {@link rx.Observable} to be resumed.
*
* @return An {@link rx.Observable} that will be used to replaced the old completed one.
* Return {@code null} if there should be no more attempt on resuming the old {@link rx.Observable}.
*/
@Override
Observable<T> call(Integer attempts, Throwable error);
}
| 8,674 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/HttpRequestFactories.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import io.mantisrx.runtime.source.http.HttpRequestFactory;
import io.netty.buffer.ByteBuf;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest;
/**
* A collection of commonly used {@link io.mantisrx.runtime.source.http.HttpRequestFactory}
*/
public class HttpRequestFactories {
/**
* Creates a simple GET request factory that takes a URI and creates GET requests using the URI
*
* @param uri The URI used by the created request
*
* @return An {@link io.mantisrx.runtime.source.http.HttpRequestFactory} instance used for GET request.
*/
public static HttpRequestFactory<ByteBuf> createGetFactory(String uri) {
return new GetRequestFactory(uri);
}
/**
* Creates a factory that produces simple HTTP request that posts to the given URI. The POST request
* does not take any payload.
*
* @param uri The URI to post to
*
* @return An {@link io.mantisrx.runtime.source.http.HttpRequestFactory} instance used for creating the POST requests
*/
public static HttpRequestFactory<ByteBuf> createPostFactory(String uri) {
return new SimplePostRequestFactory(uri);
}
/**
* Creates a factory that produces HTTP request that posts to a given URI. The POST request
* will include the given payload. It's the caller's responsibility to serialize content object
* into byte array. The byte array will not be copied, so the caller should not reuse the byte array
* after passing it to this method.
*
* @param uri The URI that a request will posts to
* @param entity The content of a POST request
*
* @return A {@link io.mantisrx.runtime.source.http.HttpRequestFactory} instance that creates the specified POST requests.
*/
public static HttpRequestFactory<ByteBuf> createPostFactory(String uri, byte[] entity) {
return new PostRequestWithContentFactory(uri, entity);
}
private static class GetRequestFactory implements HttpRequestFactory<ByteBuf> {
private final String uri;
private GetRequestFactory(String uri) {
this.uri = uri;
}
@Override
public HttpClientRequest<ByteBuf> create() {
return HttpClientRequest.createGet(uri);
}
}
private static class SimplePostRequestFactory implements HttpRequestFactory<ByteBuf> {
private final String uri;
private SimplePostRequestFactory(String uri) {
this.uri = uri;
}
@Override
public HttpClientRequest<ByteBuf> create() {
return HttpClientRequest.createPost(uri);
}
}
private static class PostRequestWithContentFactory implements HttpRequestFactory<ByteBuf> {
private final String uri;
private final byte[] content;
private PostRequestWithContentFactory(String uri, byte[] content) {
this.uri = uri;
this.content = content;
}
@Override
public HttpClientRequest<ByteBuf> create() {
return HttpClientRequest.createPost(uri).withContent(content);
}
}
}
| 8,675 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/HttpSourceImpl.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import static com.mantisrx.common.utils.MantisMetricStringConstants.DROP_OPERATOR_INCOMING_METRIC_GROUP;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.CONNECTION_ESTABLISHED;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.CONNECTION_UNSUBSCRIBED;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.SERVER_FOUND;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.SOURCE_COMPLETED;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.SUBSCRIPTION_ENDED;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.SUBSCRIPTION_ESTABLISHED;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.SUBSCRIPTION_FAILED;
import com.mantisrx.common.utils.NettyUtils;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.source.Index;
import io.mantisrx.runtime.source.Source;
import io.mantisrx.runtime.source.http.ClientResumePolicy;
import io.mantisrx.runtime.source.http.HttpClientFactory;
import io.mantisrx.runtime.source.http.HttpRequestFactory;
import io.mantisrx.runtime.source.http.HttpServerProvider;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType;
import io.mantisrx.server.core.ServiceRegistry;
import io.netty.util.ReferenceCountUtil;
import io.reactivx.mantis.operators.DropOperator;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import lombok.Value;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import mantis.io.reactivex.netty.protocol.http.client.HttpClient;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subjects.PublishSubject;
import rx.subscriptions.Subscriptions;
/**
* An HTTP source that connects to multiple servers, and streams responses from the servers with a single merged
* stream.
*
* @param <R> The entity type of the request
* @param <E> The entity type of the response
*/
public class HttpSourceImpl<R, E, T> implements Source<T> {
private static final String DEFAULT_BUFFER_SIZE = "0";
private static Logger logger = LoggerFactory.getLogger(HttpSourceImpl.class);
static {
NettyUtils.setNettyThreads();
}
private final HttpRequestFactory<R> requestFactory;
private final HttpServerProvider serverProvider;
// Note the HTTP source needs a client factory instead of using RxNetty's HttpClientBuilder directory
// because we need to create a new HttpClientBuilder for each server to connect to. Therefore,
// HttpSource can't take a single HttpClientBuilder.
private final HttpClientFactory<R, E> clientFactory;
private final Observer<HttpSourceEvent> observer;
private final Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor;
private final ClientResumePolicy<R, E> resumePolicy;
private final PublishSubject<ServerInfo> serversToRemove;
private final Gauge connectionGauge;
private final Gauge retryListGauge;
private final Gauge connectionAttemptedGauge;
private final Counter connectionEstablishedCounter;
private final Counter connectionUnsubscribedCounter;
private final Counter sourceCompletedCounter;
private final Counter subscriptionEndedCounter;
private final Counter subscriptionEstablishedCounter;
private final Counter subscriptionFailedCounter;
private final Counter serverFoundCounter;
private final Counter subscriptionCancelledCounter;
private final Counter dropped;
//aggregated metrics for all connections to source servers
private final Metrics incomingDataMetrics;
private final ConnectionManager<E> connectionManager = new ConnectionManager<>();
private final int bufferSize;
private final Subscription serversToRemoveSubscription;
/**
* Constructs an {@code HttpSource} instance that is ready to connects to one or more servers provided by the given
* {@link io.mantisrx.runtime.source.http.HttpServerProvider} instance.
*
* @param requestFactory A factory that creates a new request for the source to submit
* @param serverProvider The provider that specifies with servers to connect to and which servers to disconnect
* from
* @param clientFactory The factory that creates HTTP client for the source to make connections to each server
* @param observer The observer that gets notified for internal events of the source
* @param resumePolicy The policy of resuming client response when a response terminates
*/
HttpSourceImpl(
HttpRequestFactory<R> requestFactory,
HttpServerProvider serverProvider,
HttpClientFactory<R, E> clientFactory,
Observer<HttpSourceEvent> observer,
Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor,
ClientResumePolicy<R, E> resumePolicy) {
this.requestFactory = requestFactory;
this.serverProvider = serverProvider;
this.clientFactory = clientFactory;
this.observer = observer;
this.postProcessor = postProcessor;
this.resumePolicy = resumePolicy;
Metrics m = new Metrics.Builder()
.name(HttpSourceImpl.class.getCanonicalName())
.addGauge("connectionGauge")
.addGauge("retryListGauge")
.addGauge("connectionAttemptedGauge")
.addCounter("connectionEstablishedCounter")
.addCounter("connectionUnsubscribedCounter")
.addCounter("sourceCompletedCounter")
.addCounter("subscriptionEndedCounter")
.addCounter("subscriptionEstablishedCounter")
.addCounter("subscriptionFailedCounter")
.addCounter("serverFoundCounter")
.addCounter("subscriptionCancelledCounter")
.build();
m = MetricsRegistry.getInstance().registerAndGet(m);
connectionGauge = m.getGauge("connectionGauge");
retryListGauge = m.getGauge("retryListGauge");
connectionAttemptedGauge = m.getGauge("connectionAttemptedGauge");
connectionEstablishedCounter = m.getCounter("connectionEstablishedCounter");
connectionUnsubscribedCounter = m.getCounter("connectionUnsubscribedCounter");
sourceCompletedCounter = m.getCounter("sourceCompletedCounter");
subscriptionEndedCounter = m.getCounter("subscriptionEndedCounter");
subscriptionEstablishedCounter = m.getCounter("subscriptionEstablishedCounter");
subscriptionFailedCounter = m.getCounter("subscriptionFailedCounter");
serverFoundCounter = m.getCounter("serverFoundCounter");
subscriptionCancelledCounter = m.getCounter("subscriptionCancelledCounter");
incomingDataMetrics = new Metrics.Builder()
.name(DROP_OPERATOR_INCOMING_METRIC_GROUP + "_HttpSourceImpl")
.addCounter("onNext")
.addCounter("onError")
.addCounter("onComplete")
.addGauge("subscribe")
.addCounter("dropped")
.addGauge("requested")
.addGauge("bufferedGauge")
.build();
MetricsRegistry.getInstance().registerAndGet(incomingDataMetrics);
dropped = incomingDataMetrics.getCounter("dropped");
String bufferSizeStr = ServiceRegistry.INSTANCE.getPropertiesService()
.getStringValue("httpSource.buffer.size", DEFAULT_BUFFER_SIZE);
bufferSize = Integer.parseInt(bufferSizeStr);
// We use a subject here instead of directly using the observable of
// servers to be removed because we do not want to complete the observable, or
// the source will be completed.
this.serversToRemove = PublishSubject.create();
serversToRemoveSubscription =
serverProvider
.getServersToRemove()
.subscribe(serversToRemove::onNext);
}
public static <R, E, T> Builder<R, E, T> builder(
HttpClientFactory<R, E> clientFactory,
HttpRequestFactory<R> requestFactory,
Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor) {
return new Builder<>(clientFactory, requestFactory, postProcessor);
}
public static <R, E, T> Builder<R, E, T> builder(
HttpClientFactory<R, E> clientFactory,
HttpRequestFactory<R> requestFactory,
Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor,
ClientResumePolicy<R, E> resumePolicy) {
return new Builder<>(clientFactory, requestFactory, postProcessor, resumePolicy);
}
public static <E> Func2<ServerContext<HttpClientResponse<E>>, E, ServerContext<E>> contextWrapper() {
return new Func2<ServerContext<HttpClientResponse<E>>, E, ServerContext<E>>() {
@Override
public ServerContext<E> call(ServerContext<HttpClientResponse<E>> context, E e) {
return new ServerContext<>(context.getServer(), e);
}
};
}
public static <E> Func2<ServerContext<HttpClientResponse<E>>, E, E> identityConverter() {
return new Func2<ServerContext<HttpClientResponse<E>>, E, E>() {
@Override
public E call(ServerContext<HttpClientResponse<E>> httpClientResponseServerContext, E e) {
return e;
}
};
}
@Override
public Observable<Observable<T>> call(Context context, Index index) {
return serverProvider
.getServersToAdd()
.filter((ServerInfo serverInfo) -> !connectionManager.alreadyConnected(serverInfo) && !connectionManager
.connectionAlreadyAttempted(serverInfo))
.flatMap((ServerInfo serverInfo) -> {
return streamServers(Observable.just(serverInfo));
})
.doOnError((Throwable error) -> {
logger.error(String.format("The source encountered an error " + error.getMessage(), error));
observer.onError(error);
})
.doAfterTerminate(() -> {
observer.onCompleted();
connectionManager.reset();
})
.lift(new Operator<Observable<T>, Observable<T>>() {
@Override
public Subscriber<? super Observable<T>> call(Subscriber<? super Observable<T>> subscriber) {
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
// When there is no subscriber left, we should clean up everything
// so the next incoming request can be handled properly. The most
// important thing is cached connections. Without them being removed,
// this HttpSource will not accept new request. See filter(disconnectedServer())
// above.
connectionManager.reset();
}
}));
return subscriber;
}
});
// We must ref count this stream because we'd like to ensure that the stream cleans up
// its internal states only if all subscribers are gone, and the stream is unsubscribed
// only once instead of per un-subscription.
// Should not have to share as we are doing it at the stage level.
// .share()
// .lift(new DropOperator<Observable<T>>("http_source_impl_share"));
}
@Override
public void close() throws IOException {
serversToRemoveSubscription.unsubscribe();
connectionManager.reset();
}
private Observable<Observable<T>> streamServers(Observable<ServerInfo> servers) {
return servers.map((ServerInfo server) -> {
SERVER_FOUND.newEvent(observer, server);
serverFoundCounter.increment();
return new ServerClientContext<>(server, clientFactory.createClient(server), requestFactory, observer);
})
.flatMap((final ServerClientContext<R, E> clientContext) -> {
final Observable<HttpClientResponse<E>> response =
streamResponseUntilServerIsRemoved(clientContext);
return response
.map(response1 -> {
// We delay the event until it here because we need to make sure
// the response observable is not completed for any reason
CONNECTION_ESTABLISHED.newEvent(observer, clientContext.getServer());
connectionEstablishedCounter.increment();
return new ServerContext<>(clientContext.getServer(), new ClientWithResponse<>(clientContext.getClient(), response1));
})
.lift((Operator<ServerContext<ClientWithResponse<R, E>>, ServerContext<ClientWithResponse<R, E>>>) subscriber -> {
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
// Note a connection is not equivalent to a subscription. A subscriber subscribes to
// to valid connection, while a connection may return server errors.
connectionUnsubscribedCounter.increment();
CONNECTION_UNSUBSCRIBED.newEvent(observer, clientContext.getServer());
}
}));
return subscriber;
});
})
.map(new Func1<ServerContext<ClientWithResponse<R, E>>, Observable<T>>() {
@Override
public Observable<T> call(
final
ServerContext<ClientWithResponse<R, E>> context) {
final HttpClientResponse<E> response = context.getValue().getResponse();
final ServerInfo server = context.getServer();
SUBSCRIPTION_ESTABLISHED.newEvent(observer, server);
subscriptionEstablishedCounter.increment();
connectionManager.serverConnected(server, context.getValue());
connectionGauge.set(getConnectedServers().size());
return streamResponseContent(server, response)
.map(new Func1<E, T>() {
@Override
public T call(E e) {
ReferenceCountUtil.retain(e);
return postProcessor.call(context.map(c -> c.getResponse()), e);
}
})
.lift(new DropOperator<T>(incomingDataMetrics))
.lift(new Operator<T, T>() {
@Override
public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
SUBSCRIPTION_ENDED.newEvent(observer, context.getServer());
subscriptionEndedCounter.increment();
}
}));
return subscriber;
}
});
}
});
}
// private Func1<ServerInfo, Boolean> disconnectedServer() {
// return new Func1<ServerInfo, Boolean>() {
// @Override
// public Boolean call(ServerInfo serverInfo) {
// return !connectionManager.alreadyConnected(serverInfo);
// }
// };
// }
private void checkResponseIsSuccessful(HttpClientResponse<E> response) {
int status = response.getStatus().code();
if (status != 200) {
throw new RuntimeException(String.format(
"Expected 200 but got status %d and reason: %s",
status,
response.getStatus().reasonPhrase()));
}
}
private Observable<E> streamResponseContent(final ServerInfo server, HttpClientResponse<E> response) {
// Note we must unsubscribe from the content stream or the stream will continue receiving from server even if
// the stream's response observable is unsubscribed.
return response.getContent()
.takeUntil(
serversToRemove.filter((ServerInfo toRemove) -> toRemove != null && toRemove.equals(server)))
.doOnError((Throwable throwable) -> {
SUBSCRIPTION_FAILED.newEvent(observer, server);
subscriptionFailedCounter.increment();
retryListGauge.set(getRetryServers().size());
logger.info("server disconnected onError1: " + server);
connectionManager.serverDisconnected(server);
connectionGauge.set(getConnectedServers().size());
})
// Upon error, simply completes the observable for this particular server. The error should not be
// propagated to the entire http source
.onErrorResumeNext(Observable.empty())
.doOnCompleted(() -> {
SOURCE_COMPLETED.newEvent(observer, server);
sourceCompletedCounter.increment();
logger.info("server disconnected onComplete1: " + server);
connectionManager.serverDisconnected(server);
retryListGauge.set(getRetryServers().size());
connectionGauge.set(getConnectedServers().size());
});
}
private Observable<HttpClientResponse<E>> streamResponseUntilServerIsRemoved(final ServerClientContext<R, E> clientContext) {
return clientContext
.newResponse((ServerInfo t) -> {
connectionAttemptedGauge.set(getConnectionAttemptedServers().size());
connectionManager.serverConnectionAttempted(t);
})
.lift(new OperatorResumeOnError<>(new ResumeOnErrorPolicy<HttpClientResponse<E>>() {
@Override
public Observable<HttpClientResponse<E>> call(Integer attempts, Throwable error) {
return resumePolicy.onError(clientContext, attempts, error);
}
}))
.lift(new OperatorResumeOnCompleted<>(new ResumeOnCompletedPolicy<HttpClientResponse<E>>() {
@Override
public Observable<HttpClientResponse<E>> call(Integer attempts) {
return resumePolicy.onCompleted(clientContext, attempts);
}
}))
.takeUntil(
serversToRemove.filter((ServerInfo toRemove) -> {
boolean shouldUnsubscribe = toRemove != null && toRemove.equals(clientContext.getServer());
if (shouldUnsubscribe) {
subscriptionCancelledCounter.increment();
EventType.SUBSCRIPTION_CANCELED.newEvent(observer, toRemove);
}
return shouldUnsubscribe;
}).doOnNext((ServerInfo server) -> {
logger.info("server removed: " + server);
connectionManager.serverRemoved(server);
connectionGauge.set(getConnectedServers().size());
})
)
.doOnNext((HttpClientResponse<E> response) -> checkResponseIsSuccessful(response))
.doOnError((Throwable error) -> {
logger.error(
"Connecting to server {} failed: {}",
clientContext.getServer(),
error.getMessage(),
error);
SUBSCRIPTION_FAILED.newEvent(observer, clientContext.getServer());
subscriptionFailedCounter.increment();
logger.info("server disconnected onError2: " + clientContext.getServer());
connectionManager.serverDisconnected(clientContext.getServer());
retryListGauge.set(getRetryServers().size());
connectionGauge.set(connectionManager.getConnectedServers().size());
})
.doOnCompleted(() -> {
// the response header obs completes here no op
// connectionManager.serverDisconnected(clientContext.getServer());
// logger.info("server disconnected onComplete2: " + clientContext.getServer());
// connectionGauge.set(getConnectedServers().size());
})
// Upon error, simply completes the observable for this particular server. The error should not be
// propagated to the entire http source
.onErrorResumeNext(Observable.empty());
}
Set<ServerInfo> getConnectedServers() {
return connectionManager.getConnectedServers();
}
Set<ServerInfo> getRetryServers() {
return connectionManager.getRetryServers();
}
Set<ServerInfo> getConnectionAttemptedServers() {
return connectionManager.getConnectionAttemptedServers();
}
public static class Builder<R, E, T> {
public static final HttpServerProvider EMPTY_HTTP_SERVER_PROVIDER = new HttpServerProvider() {
@Override
public Observable<ServerInfo> getServersToAdd() {
return Observable.empty();
}
@Override
public Observable<ServerInfo> getServersToRemove() {
return Observable.empty();
}
};
private HttpRequestFactory<R> requestFactory;
private HttpServerProvider serverProvider;
private HttpClientFactory<R, E> httpClientFactory;
private Observer<HttpSourceEvent> observer;
private Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor;
private ClientResumePolicy<R, E> clientResumePolicy;
public Builder(
HttpClientFactory<R, E> clientFactory,
HttpRequestFactory<R> requestFactory,
Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor
) {
this.requestFactory = requestFactory;
this.httpClientFactory = clientFactory;
this.serverProvider = EMPTY_HTTP_SERVER_PROVIDER;
this.postProcessor = postProcessor;
// Do not resume by default
this.clientResumePolicy = new ClientResumePolicy<R, E>() {
@Override
public Observable<HttpClientResponse<E>> onError(
ServerClientContext<R, E> clientContext,
int attempts,
Throwable error) {
return null;
}
@Override
public Observable<HttpClientResponse<E>> onCompleted(
ServerClientContext<R, E> clientContext,
int attempts) {
return null;
}
};
// this.clientResumePolicy = ClientResumePolicies.maxRepeat(9);
observer = PublishSubject.create();
}
public Builder(
HttpClientFactory<R, E> clientFactory,
HttpRequestFactory<R> requestFactory,
Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor,
ClientResumePolicy<R, E> resumePolicy
) {
this.requestFactory = requestFactory;
this.httpClientFactory = clientFactory;
this.serverProvider = EMPTY_HTTP_SERVER_PROVIDER;
this.postProcessor = postProcessor;
this.clientResumePolicy = resumePolicy;
observer = PublishSubject.create();
}
public Builder<R, E, T> withServerProvider(HttpServerProvider serverProvider) {
this.serverProvider = serverProvider;
return this;
}
public Builder<R, E, T> withActivityObserver(Observer<HttpSourceEvent> observer) {
this.observer = observer;
return this;
}
public Builder<R, E, T> resumeWith(ClientResumePolicy<R, E> policy) {
this.clientResumePolicy = policy;
return this;
}
public HttpSourceImpl<R, E, T> build() {
return new HttpSourceImpl<>(
requestFactory,
serverProvider,
httpClientFactory,
observer,
postProcessor,
clientResumePolicy);
}
}
public static class HttpSourceEvent {
private final ServerInfo server;
private final EventType eventType;
private HttpSourceEvent(ServerInfo server, EventType eventType) {
this.server = server;
this.eventType = eventType;
}
public ServerInfo getServer() {
return server;
}
public EventType getEventType() {
return eventType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HttpSourceEvent that = (HttpSourceEvent) o;
if (eventType != that.eventType) {
return false;
}
if (server != null ? !server.equals(that.server) : that.server != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = server != null ? server.hashCode() : 0;
result = 31 * result + (eventType != null ? eventType.hashCode() : 0);
return result;
}
public static enum EventType {
SERVER_FOUND,
CONNECTION_ATTEMPTED,
CONNECTION_ESTABLISHED,
CONNECTION_UNSUBSCRIBED,
SOURCE_COMPLETED,
SUBSCRIPTION_ESTABLISHED,
SUBSCRIPTION_FAILED,
SUBSCRIPTION_CANCELED,
SUBSCRIPTION_ENDED;
public HttpSourceEvent newEvent(Observer<HttpSourceEvent> observer, ServerInfo server) {
HttpSourceEvent event = new HttpSourceEvent(server, this);
observer.onNext(event);
return event;
}
}
}
private static class ConnectionManager<E> {
private final ConcurrentMap<ServerInfo, ClientWithResponse<?, E>> connectedServers = new ConcurrentHashMap<>();
private final Set<ServerInfo> retryServers = new CopyOnWriteArraySet<>();
private final Set<ServerInfo> connectionAttempted = new CopyOnWriteArraySet<>();
//private final Set<ServerInfo> connectedServers = new CopyOnWriteArraySet<>();
public void serverConnected(ServerInfo server, ClientWithResponse<?, E> response) {
connectedServers.put(server, response);
retryServers.remove(server);
connectionAttempted.remove(server);
logger.info("CM: Server connected: " + server + " count " + connectedServers.size());
}
public void serverConnectionAttempted(ServerInfo server) {
connectionAttempted.add(server);
}
public boolean alreadyConnected(ServerInfo server) {
//logger.info("CM: is connected? " + server);
return connectedServers.containsKey(server);
}
public boolean connectionAlreadyAttempted(ServerInfo server) {
//logger.info("CM: is connected? " + server);
return connectionAttempted.contains(server);
}
public void serverDisconnected(ServerInfo server) {
removeConnectedServer(server);
connectionAttempted.remove(server);
retryServers.add(server);
logger.info("CM: Server disconnected: " + server + " count " + connectedServers.size());
}
public void serverRemoved(ServerInfo server) {
removeConnectedServer(server);
connectionAttempted.remove(server);
retryServers.remove(server);
logger.info("CM: Server removed: " + server + " count " + connectedServers.size());
}
private void removeConnectedServer(ServerInfo serverInfo) {
ClientWithResponse<?, E> stored = connectedServers.remove(serverInfo);
if (stored != null) {
try {
stored.getClient().shutdown();
} catch (Exception e) {
logger.error("Failed to shut the client for {} successfully", serverInfo, e);
}
}
}
public Set<ServerInfo> getConnectedServers() {
return Collections.unmodifiableSet(connectedServers.keySet());
}
public Set<ServerInfo> getRetryServers() {
return Collections.unmodifiableSet(retryServers);
}
public Set<ServerInfo> getConnectionAttemptedServers() {
return Collections.unmodifiableSet(connectionAttempted);
}
public void reset() {
Set<ServerInfo> connectedServerInfos = new HashSet<>(connectedServers.keySet());
for (ServerInfo serverInfo: connectedServerInfos) {
removeConnectedServer(serverInfo);
}
connectionAttempted.clear();
retryServers.clear();
logger.info("CM: reset");
}
}
@Value
static class ClientWithResponse<R, E> {
HttpClient<R, E> client;
HttpClientResponse<E> response;
}
}
| 8,676 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/ResumeOnCompletedPolicy.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import rx.Observable;
import rx.functions.Func1;
/**
* An implementation of this functional interface defines how to resume an {@link rx.Observable}. This is
* used by an {@link io.mantisrx.runtime.source.http.impl.OperatorResumeOnCompleted} instance. Return null
* to indicate that an {@link rx.Observable} should be not resumed.
*
* @param <T> The type of items in the returned new {@link rx.Observable}
*
* @see io.mantisrx.runtime.source.http.impl.OperatorResumeOnCompleted
*/
public interface ResumeOnCompletedPolicy<T> extends Func1<Integer, Observable<T>> {
/**
* Called when an {@link rx.Observable} needs to be to resumed upon completion.
*
* @param attempts The number of the current attempt.
*
* @return An {@link rx.Observable} that will be used to replaced the old completed one.
* Return {@code null} if there should be no more attempt on resuming the old {@link rx.Observable}.
*/
@Override
Observable<T> call(Integer attempts);
}
| 8,677 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/ServerContext.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import java.util.function.Function;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
/**
* The context that provides contextual information for a value. In particular, the information
* about a server
*
* @param <T> The type of the value associated with the context
*/
public class ServerContext<T> {
private final ServerInfo server;
private final T value;
public ServerContext(ServerInfo server, T value) {
this.server = server;
this.value = value;
}
public ServerInfo getServer() {
return server;
}
public T getValue() {
return value;
}
public <R> ServerContext<R> map(Function<? super T, ? extends R> mapper) {
return new ServerContext<>(server, mapper.apply(value));
}
}
| 8,678 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/ServerClientContext.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import static io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent.EventType.CONNECTION_ATTEMPTED;
import io.mantisrx.runtime.source.http.HttpRequestFactory;
import io.mantisrx.runtime.source.http.impl.HttpSourceImpl.HttpSourceEvent;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import mantis.io.reactivex.netty.protocol.http.client.HttpClient;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
import rx.Observer;
import rx.functions.Action1;
public class ServerClientContext<R, E> extends ServerContext<HttpClient<R, E>> {
private final HttpRequestFactory<R> requestFactory;
private final Observer<HttpSourceEvent> sourceObserver;
private final Action1<ServerInfo> noOpAction = new Action1<ServerInfo>() {
@Override
public void call(ServerInfo t) {}
};
public ServerClientContext(ServerInfo server, HttpClient<R, E> client, HttpRequestFactory<R> requestFactory, Observer<HttpSourceEvent> sourceObserver) {
super(server, client);
this.requestFactory = requestFactory;
this.sourceObserver = sourceObserver;
}
public HttpClient<R, E> getClient() {
return getValue();
}
public Observable<HttpClientResponse<E>> newResponse(Action1<ServerInfo> connectionAttemptedCallback) {
CONNECTION_ATTEMPTED.newEvent(sourceObserver, getServer());
connectionAttemptedCallback.call(getServer());
return getClient().submit(requestFactory.create());
}
public Observable<HttpClientResponse<E>> newResponse() {
return newResponse(noOpAction);
}
}
| 8,679 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/source/http/impl/OperatorResumeOnCompleted.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.source.http.impl;
import rx.Observable;
import rx.Observable.Operator;
import rx.Scheduler;
import rx.Scheduler.Worker;
import rx.Subscriber;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import rx.subscriptions.SerialSubscription;
public class OperatorResumeOnCompleted<T> implements Operator<T, T> {
private static final Scheduler scheduler = Schedulers.trampoline();
private final ResumeOnCompletedPolicy<T> resumePolicy;
private final int currentAttempts;
private OperatorResumeOnCompleted(int currentAttempts, ResumeOnCompletedPolicy<T> resumePolicy) {
this.currentAttempts = currentAttempts;
this.resumePolicy = resumePolicy;
}
public OperatorResumeOnCompleted(ResumeOnCompletedPolicy<T> resumePolicy) {
this(0, resumePolicy);
}
@Override
public Subscriber<? super T> call(final Subscriber<? super T> child) {
final SerialSubscription serialSubscription = new SerialSubscription();
child.add(serialSubscription);
return new Subscriber<T>(child) {
private final Worker worker = scheduler.createWorker();
@Override
public void onCompleted() {
worker.schedule(new Action0() {
@Override
public void call() {
try {
int newAttempts = currentAttempts + 1;
Observable<? extends T> resume = resumePolicy.call(newAttempts);
if (resume == null) {
child.onCompleted();
} else {
resume = resume.lift(new OperatorResumeOnCompleted<>(
newAttempts,
resumePolicy
));
serialSubscription.set(resume.unsafeSubscribe(child));
}
} catch (Throwable e2) {
child.onError(e2);
}
}
});
}
@Override
public void onError(final Throwable e) {
child.onError(e);
}
@Override
public void onNext(T t) {
child.onNext(t);
}
};
}
}
| 8,680 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/ServiceLocator.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public interface ServiceLocator {
public <T> T service(Class<T> key);
}
| 8,681 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/LifecycleNoOp.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public class LifecycleNoOp extends Lifecycle {
@Override
public void startup() throws StartupError {}
@Override
public void shutdown() throws ShutdownError {}
@Override
public ServiceLocator getServiceLocator() {
return new ServiceLocator() {
@Override
public <T> T service(Class<T> key) {
throw new UnsupportedOperationException("NoOp lifecycle does not support service lookup");
}
};
}
}
| 8,682 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/Lifecycle.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public abstract class Lifecycle implements Startup, Shutdown {
public abstract ServiceLocator getServiceLocator();
}
| 8,683 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/Shutdown.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public interface Shutdown {
public void shutdown() throws ShutdownError;
}
| 8,684 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/ShutdownError.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public class ShutdownError extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| 8,685 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/Startup.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public interface Startup {
public void startup() throws StartupError;
}
| 8,686 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/lifecycle/StartupError.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.lifecycle;
public class StartupError extends RuntimeException {
private static final long serialVersionUID = 1L;
public StartupError(Throwable cause) {
super(cause);
}
public StartupError(String string) {
super(string);
}
}
| 8,687 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/scheduler/MantisRxSingleThreadScheduler.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.scheduler;
import static java.util.concurrent.Executors.newFixedThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import rx.Scheduler;
import rx.schedulers.Schedulers;
/**
* Schedules work on the same fixed thread pool executor with 1 thread that is constructed once as part of creating
* this Scheduler.
*/
public final class MantisRxSingleThreadScheduler extends Scheduler {
private final Scheduler scheduler;
public MantisRxSingleThreadScheduler(ThreadFactory threadFactory) {
ExecutorService executorService = newFixedThreadPool(1, threadFactory);
this.scheduler = Schedulers.from(executorService);
}
@Override
public Worker createWorker() {
return this.scheduler.createWorker();
}
}
| 8,688 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/ServerSentEventRequestHandler.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink;
import com.mantisrx.common.utils.MantisSSEConstants;
import com.netflix.spectator.api.BasicTag;
import com.netflix.spectator.api.Tag;
import io.mantisrx.common.compression.CompressionUtils;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.network.Endpoint;
import io.mantisrx.common.network.HashFunctions;
import io.mantisrx.common.network.ServerSlotManager;
import io.mantisrx.common.network.ServerSlotManager.SlotAssignmentManager;
import io.mantisrx.common.network.WritableEndpoint;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.sink.predicate.Predicate;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivx.mantis.operators.DisableBackPressureOperator;
import io.reactivx.mantis.operators.DropOperator;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import mantis.io.reactivex.netty.protocol.http.server.HttpServerRequest;
import mantis.io.reactivex.netty.protocol.http.server.HttpServerResponse;
import mantis.io.reactivex.netty.protocol.http.server.RequestHandler;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
public class ServerSentEventRequestHandler<T> implements
RequestHandler<ByteBuf, ServerSentEvent> {
protected static final Object BINARY_FORMAT = "binary";
private static final String TWO_NEWLINES = "\n\n";
private static final String SSE_DATA_PREFIX = "data: ";
private static final Logger LOG = LoggerFactory.getLogger(ServerSentEventRequestHandler.class);
private static final String ENABLE_PINGS_PARAM = "enablePings";
private static final String SAMPLE_PARAM = "sample";
private static final String SAMPLE_PARAM_MSEC = "sampleMSec";
private static final String CLIENT_ID_PARAM = "clientId";
private static final int PING_INTERVAL = 2000;
private static final String TEXT_FORMAT = "text";
private static final String DEFAULT_FORMAT = TEXT_FORMAT;
private static final String FORMAT_PARAM = "format";
private static final byte[] EVENT_PREFIX_BYTES = "event: ".getBytes();
private static final byte[] NEW_LINE_AS_BYTES = TWO_NEWLINES.getBytes();
private static final byte[] ID_PREFIX_AS_BYTES = "id: ".getBytes();
private static final byte[] DATA_PREFIX_AS_BYTES = SSE_DATA_PREFIX.getBytes();
private static final String PING = "\ndata: ping\n\n";
final ServerSlotManager<String> ssm = new ServerSlotManager<>(HashFunctions.ketama());
private final Observable<T> observableToServe;
private final Func1<T, String> encoder;
private final Func1<Throwable, String> errorEncoder;
private final Predicate<T> predicate;
private final Func2<Map<String, List<String>>, Context, Void> requestPreprocessor;
private final Func2<Map<String, List<String>>, Context, Void> requestPostprocessor;
private final Context context;
private boolean pingsEnabled = true;
private int flushIntervalMillis = 250;
private String format = DEFAULT_FORMAT;
public ServerSentEventRequestHandler(Observable<T> observableToServe,
Func1<T, String> encoder,
Func1<Throwable, String> errorEncoder,
Predicate<T> predicate,
Func2<Map<String, List<String>>, Context, Void> requestPreprocessor,
Func2<Map<String, List<String>>, Context, Void> requestPostprocessor,
Context context,
int batchInterval) {
this.observableToServe = observableToServe;
this.encoder = encoder;
this.errorEncoder = errorEncoder;
this.predicate = predicate;
this.requestPreprocessor = requestPreprocessor;
this.requestPostprocessor = requestPostprocessor;
this.context = context;
this.flushIntervalMillis = batchInterval;
}
@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> request,
final HttpServerResponse<ServerSentEvent> response) {
InetSocketAddress socketAddress = (InetSocketAddress) response.getChannel().remoteAddress();
LOG.info("HTTP SSE connection received from " + socketAddress.getAddress() + ":" + socketAddress.getPort() + " queryParams: " + request.getQueryParameters());
final String socketAddrStr = socketAddress.getAddress().toString();
final WritableEndpoint<String> sn = new WritableEndpoint<>(socketAddress.getHostString(),
socketAddress.getPort(), Endpoint.uniqueHost(socketAddress.getHostString(), socketAddress.getPort(), null));
final Map<String, List<String>> queryParameters = request.getQueryParameters();
final SlotAssignmentManager<String> slotMgr = ssm.registerServer(sn, queryParameters);
final AtomicLong lastResponseFlush = new AtomicLong();
lastResponseFlush.set(-1);
final AtomicLong lastResponseSent = new AtomicLong(-1);
// copy reference, then apply request specific filters, sampling
Observable<T> requestObservable = observableToServe;
// decouple the observable on a separate thread and add backpressure handling
String decoupleSSE = "false";//ServiceRegistry.INSTANCE.getPropertiesService().getStringValue("sse.decouple", "false");
//TODO Below condition would be always false during if condition.
// Since decoupleSSE would be false and matching with true as string
// would always ignore code inside if block
if ("true".equals(decoupleSSE)) {
final BasicTag sockAddrTag = new BasicTag("sockAddr", Optional.ofNullable(socketAddrStr).orElse("none"));
requestObservable = requestObservable
.lift(new DropOperator<>("outgoing_ServerSentEventRequestHandler", sockAddrTag))
.observeOn(Schedulers.io());
}
response.getHeaders().set("Access-Control-Allow-Origin", "*");
response.getHeaders().set("content-type", "text/event-stream");
response.getHeaders().set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.getHeaders().set("Pragma", "no-cache");
response.flush();
String uniqueClientId = socketAddrStr;
Tag[] tags = new Tag[2];
final String clientId = Optional.ofNullable(uniqueClientId).orElse("none");
final String sockAddr = Optional.ofNullable(socketAddrStr).orElse("none");
tags[0] = new BasicTag("clientId", clientId);
tags[1] = new BasicTag("sockAddr", sockAddr);
Metrics sseSinkMetrics = new Metrics.Builder()
.id("ServerSentEventRequestHandler", tags)
.addCounter("processedCounter")
.addCounter("pingCounter")
.addCounter("errorCounter")
.addCounter("droppedCounter")
.addCounter("flushCounter")
.addCounter("sourceJobNameMismatchRejection")
.build();
final Counter msgProcessedCounter = sseSinkMetrics.getCounter("processedCounter");
final Counter pingCounter = sseSinkMetrics.getCounter("pingCounter");
final Counter errorCounter = sseSinkMetrics.getCounter("errorCounter");
final Counter droppedWrites = sseSinkMetrics.getCounter("droppedCounter");
final Counter flushCounter = sseSinkMetrics.getCounter("flushCounter");
final Counter sourceJobNameMismatchRejectionCounter = sseSinkMetrics.getCounter("sourceJobNameMismatchRejection");
if (queryParameters != null && queryParameters.containsKey(MantisSSEConstants.TARGET_JOB)) {
String targetJob = queryParameters.get(MantisSSEConstants.TARGET_JOB).get(0);
String currentJob = this.context.getWorkerInfo().getJobClusterName();
if (!currentJob.equalsIgnoreCase(targetJob)) {
LOG.info("Rejecting connection from {}. Client is targeting job {} but this is job {}.", uniqueClientId, targetJob, currentJob);
sourceJobNameMismatchRejectionCounter.increment();
response.setStatus(HttpResponseStatus.BAD_REQUEST);
response.writeStringAndFlush("data: " + MantisSSEConstants.TARGET_JOB + " is " + targetJob + " but this is " + currentJob + "." + TWO_NEWLINES);
return response.close();
}
}
if (queryParameters != null && queryParameters.containsKey(CLIENT_ID_PARAM)) {
// enablePings
uniqueClientId = queryParameters.get(CLIENT_ID_PARAM).get(0);
}
if (queryParameters != null && queryParameters.containsKey(FORMAT_PARAM)) {
format = queryParameters.get(FORMAT_PARAM).get(0);
}
if (queryParameters != null && requestPreprocessor != null) {
requestPreprocessor.call(queryParameters, context);
}
// apply sampling, milli, then seconds
if (queryParameters != null && queryParameters.containsKey(SAMPLE_PARAM_MSEC)) {
// apply sampling rate
int samplingRate = Integer.parseInt(queryParameters.get(SAMPLE_PARAM_MSEC).get(0));
requestObservable = requestObservable.sample(samplingRate, TimeUnit.MILLISECONDS);
}
if (queryParameters != null && queryParameters.containsKey(SAMPLE_PARAM)) {
// apply sampling rate
int samplingRate = Integer.parseInt(queryParameters.get(SAMPLE_PARAM).get(0));
requestObservable = requestObservable.sample(samplingRate, TimeUnit.SECONDS);
}
if (queryParameters != null && queryParameters.containsKey(ENABLE_PINGS_PARAM)) {
// enablePings
String enablePings = queryParameters.get(ENABLE_PINGS_PARAM).get(0);
//TODO Note: Code logic can be improved here.
// since if condition check returns same true or false which can equated to pingsEnabled value.
if ("true".equalsIgnoreCase(enablePings)) {
pingsEnabled = true;
} else {
pingsEnabled = false;
}
}
if (queryParameters != null && queryParameters.containsKey("delay")) {
// apply flush
try {
int flushInterval = Integer.parseInt(queryParameters.get("delay").get(0));
if (flushInterval >= 50) {
flushIntervalMillis = flushInterval;
} else {
LOG.warn("delay parameter too small " + flushInterval + " min. is 100");
}
} catch (Exception e) {
e.printStackTrace();
}
}
final byte[] delimiter = queryParameters != null
&& queryParameters.containsKey(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER)
&& queryParameters.get(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER).get(0) != null
? queryParameters.get(MantisSSEConstants.MANTIS_COMPRESSION_DELIMITER).get(0).getBytes()
: null;
// get predicate, defaults to return true for all T
Func1<T, Boolean> filterFunction = new Func1<T, Boolean>() {
@Override
public Boolean call(T t1) {
return true;
}
};
if (queryParameters != null && predicate != null) {
filterFunction = predicate.getPredicate().call(queryParameters);
}
final Subscription timerSubscription = Observable.interval(1, TimeUnit.SECONDS).doOnNext(new Action1<Long>() {
@Override
public void call(Long t1) {
long currentTime = System.currentTimeMillis();
if (pingsEnabled && (lastResponseSent.get() == -1 || currentTime > lastResponseSent.get() + PING_INTERVAL)) {
pingCounter.increment();
response.writeStringAndFlush(PING);
lastResponseSent.set(currentTime);
}
}
}).subscribe();
return requestObservable
.filter(filterFunction)
.map(encoder)
.lift(new DisableBackPressureOperator<>())
.buffer(flushIntervalMillis, TimeUnit.MILLISECONDS)
.flatMap(new Func1<List<String>, Observable<Void>>() {
@Override
public Observable<Void> call(List<String> valueList) {
if (response.isCloseIssued() || !response.getChannel().isActive()) {
LOG.info("Client closed detected, throwing closed channel exception");
return Observable.error(new ClosedChannelException());
}
List<String> filteredList = valueList.stream().filter(e -> {
return slotMgr.filter(sn, e.getBytes());
}).collect(Collectors.toList());
if (response.getChannel().isWritable()) {
flushCounter.increment();
if (format.equals(BINARY_FORMAT)) {
boolean useSnappy = true;
try {
String compressedList = delimiter == null
? CompressionUtils.compressAndBase64Encode(filteredList, useSnappy)
: CompressionUtils.compressAndBase64Encode(filteredList, useSnappy, delimiter);
StringBuilder sb = new StringBuilder(3);
sb.append(SSE_DATA_PREFIX);
sb.append(compressedList);
sb.append(TWO_NEWLINES);
msgProcessedCounter.increment(valueList.size());
lastResponseSent.set(System.currentTimeMillis());
return response.writeStringAndFlush(sb.toString());
} catch (Exception e) {
LOG.warn("Could not compress data" + e.getMessage());
droppedWrites.increment(valueList.size());
return Observable.empty();
}
} else {
int noOfMsgs = 0;
StringBuilder sb = new StringBuilder(valueList.size() * 3);
for (String s : filteredList) {
sb.append(SSE_DATA_PREFIX);
sb.append(s);
sb.append(TWO_NEWLINES);
noOfMsgs++;
}
msgProcessedCounter.increment(noOfMsgs);
lastResponseSent.set(System.currentTimeMillis());
return response.writeStringAndFlush(sb.toString());
}
} else {
//
droppedWrites.increment(filteredList.size());
}
return Observable.empty();
}
})
.onErrorResumeNext(new Func1<Throwable, Observable<? extends Void>>() {
@Override
public Observable<? extends Void> call(Throwable throwable) {
Throwable cause = throwable.getCause();
// ignore closed channel exceptions, this is
// when the connection was closed on the client
// side without informing the server
errorCounter.increment();
if (cause != null && !(cause instanceof ClosedChannelException)) {
LOG.warn("Error detected in SSE sink", cause);
if (errorEncoder != null) {
// write error out on connection
//response.writeAndFlush(errorEncoder.call(throwable));
ByteBuf errType = response.getAllocator().buffer().writeBytes("error: ".getBytes());
ByteBuf errRes = response.getAllocator().buffer().writeBytes((errorEncoder.call(throwable)).getBytes());
response.writeAndFlush(ServerSentEvent.withEventType(errType, errRes));
}
throwable.printStackTrace();
}
if (requestPostprocessor != null && queryParameters != null) {
requestPostprocessor.call(queryParameters, context);
}
ssm.deregisterServer(sn, queryParameters);
timerSubscription.unsubscribe();
return Observable.error(throwable);
}
});
}
}
| 8,689 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/ServerSentEventsSink.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink;
import io.mantisrx.common.properties.MantisPropertiesLoader;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.PortRequest;
import io.mantisrx.runtime.sink.predicate.Predicate;
import io.mantisrx.server.core.ServiceRegistry;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelOption;
import io.netty.channel.WriteBufferWaterMark;
import io.reactivex.mantis.network.push.PushServerSse;
import io.reactivex.mantis.network.push.PushServers;
import io.reactivex.mantis.network.push.Routers;
import io.reactivex.mantis.network.push.ServerConfig;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurators;
import mantis.io.reactivex.netty.protocol.http.server.HttpServer;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subjects.BehaviorSubject;
public class ServerSentEventsSink<T> implements SelfDocumentingSink<T> {
private static final Logger LOG = LoggerFactory.getLogger(ServerSentEventsSink.class);
private final Func2<Map<String, List<String>>, Context, Void> subscribeProcessor;
private final BehaviorSubject<Integer> portObservable = BehaviorSubject.create();
private final Func1<T, String> encoder;
private final Func1<Throwable, String> errorEncoder;
private final Predicate<T> predicate;
private Func2<Map<String, List<String>>, Context, Void> requestPreprocessor;
private Func2<Map<String, List<String>>, Context, Void> requestPostprocessor;
private int port = -1;
private final MantisPropertiesLoader propService;
private PushServerSse<T, Context> pushServerSse;
private HttpServer<ByteBuf, ServerSentEvent> httpServer;
public ServerSentEventsSink(Func1<T, String> encoder) {
this(encoder, null, null);
}
ServerSentEventsSink(Func1<T, String> encoder,
Func1<Throwable, String> errorEncoder,
Predicate<T> predicate) {
if (errorEncoder == null) {
// default
errorEncoder = Throwable::getMessage;
}
this.encoder = encoder;
this.errorEncoder = errorEncoder;
this.predicate = predicate;
this.propService = ServiceRegistry.INSTANCE.getPropertiesService();
this.subscribeProcessor = null;
}
ServerSentEventsSink(Builder<T> builder) {
this.encoder = builder.encoder;
this.errorEncoder = builder.errorEncoder;
this.predicate = builder.predicate;
this.requestPreprocessor = builder.requestPreprocessor;
this.requestPostprocessor = builder.requestPostprocessor;
this.subscribeProcessor = builder.subscribeProcessor;
this.propService = ServiceRegistry.INSTANCE.getPropertiesService();
}
@Override
public Metadata metadata() {
StringBuilder description = new StringBuilder();
description.append("HTTP server streaming results using Server-sent events. The sink"
+ " supports optional subscription (GET) parameters to change the events emitted"
+ " by the stream. A sampling interval can be applied to the stream using"
+ " the GET parameter sample=numSeconds. This will limit the stream rate to"
+ " events-per-numSeconds.");
if (predicate != null && predicate.getDescription() != null) {
description.append(" Predicate description: ").append(predicate.getDescription());
}
return new Metadata.Builder()
.name("Server Sent Event Sink")
.description(description.toString())
.build();
}
private boolean runNewSseServerImpl(String jobName) {
String legacyServerString = propService.getStringValue("mantis.sse.newServerImpl", "true");
String legacyServerStringPerJob = propService.getStringValue(jobName + ".mantis.sse.newServerImpl", "false");
return Boolean.parseBoolean(legacyServerString) || Boolean.parseBoolean(legacyServerStringPerJob);
}
private int numConsumerThreads() {
String consumerThreadsString = propService.getStringValue("mantis.sse.numConsumerThreads", "1");
return Integer.parseInt(consumerThreadsString);
}
private int maxChunkSize() {
String maxChunkSize = propService.getStringValue("mantis.sse.maxChunkSize", "1000");
return Integer.parseInt(maxChunkSize);
}
private int maxReadTime() {
String maxChunkSize = propService.getStringValue("mantis.sse.maxReadTimeMSec", "250");
return Integer.parseInt(maxChunkSize);
}
private int maxNotWritableTimeSec() {
String maxNotWritableTimeSec = propService.getStringValue("mantis.sse.maxNotWritableTimeSec", "-1");
return Integer.parseInt(maxNotWritableTimeSec);
}
private int bufferCapacity() {
String bufferCapacityString = propService.getStringValue("mantis.sse.bufferCapacity", "25000");
return Integer.parseInt(bufferCapacityString);
}
private boolean useSpsc() {
String useSpsc = propService.getStringValue("mantis.sse.spsc", "false");
return Boolean.parseBoolean(useSpsc);
}
@Override
public void call(Context context, PortRequest portRequest, final Observable<T> observable) {
port = portRequest.getPort();
if (runNewSseServerImpl(context.getWorkerInfo().getJobClusterName())) {
LOG.info("Serving modern HTTP SSE server sink on port: " + port);
String serverName = "SseSink";
ServerConfig.Builder<T> config = new ServerConfig.Builder<T>()
.name(serverName)
.groupRouter(Routers.roundRobinSse(serverName, encoder))
.port(port)
.metricsRegistry(context.getMetricsRegistry())
.maxChunkTimeMSec(maxReadTime())
.maxChunkSize(maxChunkSize())
.bufferCapacity(bufferCapacity())
.numQueueConsumers(numConsumerThreads())
.useSpscQueue(useSpsc())
.maxChunkTimeMSec(getBatchInterval())
.maxNotWritableTimeSec(maxNotWritableTimeSec());
if (predicate != null) {
config.predicate(predicate.getPredicate());
}
pushServerSse = PushServers.infiniteStreamSse(config.build(), observable,
requestPreprocessor, requestPostprocessor,
subscribeProcessor, context, true);
pushServerSse.start();
} else {
LOG.info("Serving legacy HTTP SSE server sink on port: " + port);
int batchInterval = getBatchInterval();
httpServer = RxNetty.newHttpServerBuilder(
port,
new ServerSentEventRequestHandler<>(
observable,
encoder,
errorEncoder,
predicate,
requestPreprocessor,
requestPostprocessor,
context,
batchInterval))
.pipelineConfigurator(PipelineConfigurators.<ByteBuf>serveSseConfigurator())
.channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024))
.build();
httpServer.start();
}
portObservable.onNext(port);
}
@Override
public void close() throws IOException {
if (pushServerSse != null) {
pushServerSse.shutdown();
} else if (httpServer != null) {
try {
httpServer.shutdown();
} catch (InterruptedException e) {
throw new IOException(String.format("Failed to shut down the http server %s", httpServer), e);
}
}
}
private int getBatchInterval() {
//default flush interval
String flushIntervalMillisStr =
ServiceRegistry.INSTANCE.getPropertiesService()
.getStringValue("mantis.sse.batchInterval", "100");
LOG.info("Read fast property mantis.sse.batchInterval" + flushIntervalMillisStr);
return Integer.parseInt(flushIntervalMillisStr);
}
private int getHighWaterMark() {
String jobName = propService.getStringValue("JOB_NAME", "default");
int highWaterMark = 5 * 1024 * 1024;
String highWaterMarkStr = propService.getStringValue(
jobName + ".sse.highwater.mark",
Integer.toString(5 * 1024 * 1024));
LOG.info("Read fast property:" + jobName + ".sse.highwater.mark ->" + highWaterMarkStr);
try {
highWaterMark = Integer.parseInt(highWaterMarkStr);
} catch (Exception e) {
LOG.error("Error parsing string " + highWaterMarkStr + " exception " + e.getMessage());
}
return highWaterMark;
}
public int getServerPort() {
return port;
}
/**
* Notifies you when the mantis job is available to listen to, for use when you want to
* write unit or regressions tests with the local runner that verify the output.
*/
public Observable<Integer> portConnections() {
return portObservable;
}
public static class Builder<T> {
private Func1<T, String> encoder;
private Func2<Map<String, List<String>>, Context, Void> requestPreprocessor;
private Func2<Map<String, List<String>>, Context, Void> requestPostprocessor;
private Func1<Throwable, String> errorEncoder = Throwable::getMessage;
private Predicate<T> predicate;
private Func2<Map<String, List<String>>, Context, Void> subscribeProcessor;
public Builder<T> withEncoder(Func1<T, String> encoder) {
this.encoder = encoder;
return this;
}
public Builder<T> withErrorEncoder(Func1<Throwable, String> errorEncoder) {
this.errorEncoder = errorEncoder;
return this;
}
public Builder<T> withPredicate(Predicate<T> predicate) {
this.predicate = predicate;
return this;
}
public Builder<T> withRequestPreprocessor(Func2<Map<String, List<String>>, Context, Void> preProcessor) {
this.requestPreprocessor = preProcessor;
return this;
}
public Builder<T> withSubscribePreprocessor(
Func2<Map<String, List<String>>, Context, Void> subscribeProcessor) {
this.subscribeProcessor = subscribeProcessor;
return this;
}
public Builder<T> withRequestPostprocessor(Func2<Map<String, List<String>>, Context, Void> postProcessor) {
this.requestPostprocessor = postProcessor;
return this;
}
public ServerSentEventsSink<T> build() {
return new ServerSentEventsSink<>(this);
}
}
}
| 8,690 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/Sink.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.PortRequest;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.functions.Action3;
public interface Sink<T> extends Action3<Context, PortRequest, Observable<T>>, Closeable {
default void init(Context context) {
}
default List<ParameterDefinition<?>> getParameters() {
return Collections.emptyList();
}
@Override
default void close() throws IOException {
}
}
| 8,691 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/SelfDocumentingSink.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink;
import io.mantisrx.runtime.Metadata;
public interface SelfDocumentingSink<T> extends Sink<T> {
public Metadata metadata();
}
| 8,692 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/Sinks.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink;
import com.mantisrx.common.utils.Closeables;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.PortRequest;
import io.mantisrx.runtime.parameter.ParameterDefinition;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Func1;
public class Sinks {
@SuppressWarnings("unused")
public static <T> Sink<T> eagerSubscribe(final Sink<T> sink) {
return new Sink<T>() {
private Subscription subscription;
@Override
public List<ParameterDefinition<?>> getParameters() {
return sink.getParameters();
}
@Override
public void call(Context c, PortRequest p, Observable<T> o) {
subscription = o.subscribe();
sink.call(c, p, o);
}
@Override
public void init(Context t) {
sink.init(t);
}
@Override
public void close() throws IOException {
try {
sink.close();
} finally {
subscription.unsubscribe();
}
}
};
}
public static <T> SelfDocumentingSink<T> eagerSubscribe(final SelfDocumentingSink<T> sink) {
return new SelfDocumentingSink<T>() {
private Subscription subscription;
@Override
public List<ParameterDefinition<?>> getParameters() {
return sink.getParameters();
}
@Override
public void call(Context c, PortRequest p, Observable<T> o) {
subscription = o.subscribe();
sink.call(c, p, o);
}
@Override
public Metadata metadata() {
return sink.metadata();
}
@Override
public void init(Context t) {
sink.init(t);
}
@Override
public void close() throws IOException {
try {
sink.close();
} finally {
subscription.unsubscribe();
}
}
};
}
@SafeVarargs
public static <T> Sink<T> toMany(final Sink<T>... many) {
return new Sink<T>() {
@Override
public List<ParameterDefinition<?>> getParameters() {
List<ParameterDefinition<?>> parameterDefinitions = new ArrayList<>();
for (Sink<T> sink : many) {
parameterDefinitions.addAll(sink.getParameters());
}
return parameterDefinitions;
}
@Override
public void call(Context t1, PortRequest t2, Observable<T> t3) {
for (Sink<T> sink : many) {
sink.call(t1, t2, t3);
}
}
@Override
public void init(Context t) {
for(Sink<T> sink : many) {
sink.init(t);
}
}
@Override
public void close() throws IOException {
Closeables.combine(many).close();
}
};
}
public static <T> ServerSentEventsSink<T> sse(Func1<T, String> encoder) {
return new ServerSentEventsSink<>(encoder);
}
public static <T> Sink<T> sysout() {
return new Sink<T>() {
private Subscription subscription;
@Override
public void call(Context t1, PortRequest p, Observable<T> t2) {
subscription = t2.subscribe(new Observer<T>() {
@Override
public void onCompleted() {
System.out.println("completed");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(T t) {
System.out.println(t);
}
});
}
@Override
public void close() {
subscription.unsubscribe();
}
};
}
}
| 8,693 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/sink/predicate/Predicate.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.sink.predicate;
import java.util.List;
import java.util.Map;
import rx.functions.Func1;
public class Predicate<T> {
private final String description;
private final Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate;
public Predicate(String description,
Func1<Map<String, List<String>>, Func1<T, Boolean>> predicate) {
this.description = description;
this.predicate = predicate;
}
public String getDescription() {
return description;
}
public Func1<Map<String, List<String>>, Func1<T, Boolean>> getPredicate() {
return predicate;
}
}
| 8,694 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/GroupComputation.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.computation;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.runtime.Context;
import rx.Observable;
import rx.functions.Func2;
public interface GroupComputation<K1, T, K2, R> extends Computation, Func2<Context, Observable<MantisGroup<K1, T>>, Observable<MantisGroup<K2, R>>> {
}
| 8,695 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/ScalarComputations.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.computation;
import io.mantisrx.runtime.Context;
import rx.Observable;
public class ScalarComputations {
private ScalarComputations() {}
public static <T> ScalarComputation<T, T> identity() {
return new ScalarComputation<T, T>() {
@Override
public Observable<T> call(Context context, Observable<T> t1) {
return t1;
}
};
}
}
| 8,696 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/KeyComputation.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.computation;
import io.mantisrx.runtime.Context;
import rx.Observable;
import rx.functions.Func2;
import rx.observables.GroupedObservable;
public interface KeyComputation<K1, T, K2, R> extends Computation, Func2<Context, GroupedObservable<K1, T>, Observable<GroupedObservable<K2, R>>> {
}
| 8,697 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/ToScalarComputation.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.computation;
import io.mantisrx.runtime.Context;
import rx.Observable;
import rx.functions.Func2;
import rx.observables.GroupedObservable;
public interface ToScalarComputation<K, T, R> extends Computation, Func2<Context, GroupedObservable<K, T>, Observable<R>> {
}
| 8,698 |
0 | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime | Create_ds/mantis/mantis-runtime/src/main/java/io/mantisrx/runtime/computation/GroupToScalarComputation.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.runtime.computation;
import io.mantisrx.common.MantisGroup;
import io.mantisrx.runtime.Context;
import rx.Observable;
import rx.functions.Func2;
public interface GroupToScalarComputation<K, T, R> extends Computation, Func2<Context, Observable<MantisGroup<K, T>>, Observable<R>> {
}
| 8,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.