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/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/CumulativeCollapserEventCounterStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.metric.HystrixCollapserEvent;
import com.netflix.hystrix.metric.HystrixCollapserEventStream;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of event counters for a given Command.
* There is no rolling window abstraction on this stream - every event since the start of the JVM is kept track of.
* The event counters object is calculated on the same schedule as the rolling abstract {@link RollingCommandEventCounterStream},
* so bucket rolls correspond to new data in this stream, though data never goes out of window in this stream.
*
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link com.netflix.hystrix.HystrixCollapserProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link com.netflix.hystrix.HystrixCollapserProperties#metricsRollingStatisticalWindowBuckets()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class. This value (the latest observed value) may be queried using {@link #getLatest(HystrixEventType.Collapser)}.
*/
public class CumulativeCollapserEventCounterStream extends BucketedCumulativeCounterStream<HystrixCollapserEvent, long[], long[]> {
private static final ConcurrentMap<String, CumulativeCollapserEventCounterStream> streams = new ConcurrentHashMap<String, CumulativeCollapserEventCounterStream>();
private static final int NUM_EVENT_TYPES = HystrixEventType.Collapser.values().length;
public static CumulativeCollapserEventCounterStream getInstance(HystrixCollapserKey collapserKey, HystrixCollapserProperties properties) {
final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get();
final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get();
final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets;
return getInstance(collapserKey, numCounterBuckets, counterBucketSizeInMs);
}
public static CumulativeCollapserEventCounterStream getInstance(HystrixCollapserKey collapserKey, int numBuckets, int bucketSizeInMs) {
CumulativeCollapserEventCounterStream initialStream = streams.get(collapserKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (CumulativeCollapserEventCounterStream.class) {
CumulativeCollapserEventCounterStream existingStream = streams.get(collapserKey.name());
if (existingStream == null) {
CumulativeCollapserEventCounterStream newStream = new CumulativeCollapserEventCounterStream(collapserKey, numBuckets, bucketSizeInMs, HystrixCollapserMetrics.appendEventToBucket, HystrixCollapserMetrics.bucketAggregator);
streams.putIfAbsent(collapserKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private CumulativeCollapserEventCounterStream(HystrixCollapserKey collapserKey, int numCounterBuckets, int counterBucketSizeInMs,
Func2<long[], HystrixCollapserEvent, long[]> appendEventToBucket,
Func2<long[], long[], long[]> reduceBucket) {
super(HystrixCollapserEventStream.getInstance(collapserKey), numCounterBuckets, counterBucketSizeInMs, appendEventToBucket, reduceBucket);
}
@Override
long[] getEmptyBucketSummary() {
return new long[NUM_EVENT_TYPES];
}
@Override
long[] getEmptyOutputValue() {
return new long[NUM_EVENT_TYPES];
}
public long getLatest(HystrixEventType.Collapser eventType) {
return getLatest()[eventType.ordinal()];
}
}
| 4,700 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/BucketedCounterStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.metric.HystrixEvent;
import com.netflix.hystrix.metric.HystrixEventStream;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subjects.BehaviorSubject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Abstract class that imposes a bucketing structure and provides streams of buckets
*
* @param <Event> type of raw data that needs to get summarized into a bucket
* @param <Bucket> type of data contained in each bucket
* @param <Output> type of data emitted to stream subscribers (often is the same as A but does not have to be)
*/
public abstract class BucketedCounterStream<Event extends HystrixEvent, Bucket, Output> {
protected final int numBuckets;
protected final Observable<Bucket> bucketedStream;
protected final AtomicReference<Subscription> subscription = new AtomicReference<Subscription>(null);
private final Func1<Observable<Event>, Observable<Bucket>> reduceBucketToSummary;
private final BehaviorSubject<Output> counterSubject = BehaviorSubject.create(getEmptyOutputValue());
protected BucketedCounterStream(final HystrixEventStream<Event> inputEventStream, final int numBuckets, final int bucketSizeInMs,
final Func2<Bucket, Event, Bucket> appendRawEventToBucket) {
this.numBuckets = numBuckets;
this.reduceBucketToSummary = new Func1<Observable<Event>, Observable<Bucket>>() {
@Override
public Observable<Bucket> call(Observable<Event> eventBucket) {
return eventBucket.reduce(getEmptyBucketSummary(), appendRawEventToBucket);
}
};
final List<Bucket> emptyEventCountsToStart = new ArrayList<Bucket>();
for (int i = 0; i < numBuckets; i++) {
emptyEventCountsToStart.add(getEmptyBucketSummary());
}
this.bucketedStream = Observable.defer(new Func0<Observable<Bucket>>() {
@Override
public Observable<Bucket> call() {
return inputEventStream
.observe()
.window(bucketSizeInMs, TimeUnit.MILLISECONDS) //bucket it by the counter window so we can emit to the next operator in time chunks, not on every OnNext
.flatMap(reduceBucketToSummary) //for a given bucket, turn it into a long array containing counts of event types
.startWith(emptyEventCountsToStart); //start it with empty arrays to make consumer logic as generic as possible (windows are always full)
}
});
}
abstract Bucket getEmptyBucketSummary();
abstract Output getEmptyOutputValue();
/**
* Return the stream of buckets
* @return stream of buckets
*/
public abstract Observable<Output> observe();
public void startCachingStreamValuesIfUnstarted() {
if (subscription.get() == null) {
//the stream is not yet started
Subscription candidateSubscription = observe().subscribe(counterSubject);
if (subscription.compareAndSet(null, candidateSubscription)) {
//won the race to set the subscription
} else {
//lost the race to set the subscription, so we need to cancel this one
candidateSubscription.unsubscribe();
}
}
}
/**
* Synchronous call to retrieve the last calculated bucket without waiting for any emissions
* @return last calculated bucket
*/
public Output getLatest() {
startCachingStreamValuesIfUnstarted();
if (counterSubject.hasValue()) {
return counterSubject.getValue();
} else {
return getEmptyOutputValue();
}
}
public void unsubscribe() {
Subscription s = subscription.get();
if (s != null) {
s.unsubscribe();
subscription.compareAndSet(s, null);
}
}
}
| 4,701 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCollapserBatchSizeDistributionStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.metric.HystrixCollapserEvent;
import com.netflix.hystrix.metric.HystrixCollapserEventStream;
import org.HdrHistogram.Histogram;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of batch size distributions for a given Command.
* There is a rolling window abstraction on this stream.
* The latency distribution object is calculated over a window of t1 milliseconds. This window has b buckets.
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixCollapserProperties#metricsRollingPercentileWindowInMilliseconds()}
* b = {@link HystrixCollapserProperties#metricsRollingPercentileBucketSize()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class, as soon as this stream is queried for the first time.
*/
public class RollingCollapserBatchSizeDistributionStream extends RollingDistributionStream<HystrixCollapserEvent> {
private static final ConcurrentMap<String, RollingCollapserBatchSizeDistributionStream> streams = new ConcurrentHashMap<String, RollingCollapserBatchSizeDistributionStream>();
private static final Func2<Histogram, HystrixCollapserEvent, Histogram> addValuesToBucket = new Func2<Histogram, HystrixCollapserEvent, Histogram>() {
@Override
public Histogram call(Histogram initialDistribution, HystrixCollapserEvent event) {
switch (event.getEventType()) {
case ADDED_TO_BATCH:
if (event.getCount() > -1) {
initialDistribution.recordValue(event.getCount());
}
break;
default:
//do nothing
break;
}
return initialDistribution;
}
};
public static RollingCollapserBatchSizeDistributionStream getInstance(HystrixCollapserKey collapserKey, HystrixCollapserProperties properties) {
final int percentileMetricWindow = properties.metricsRollingPercentileWindowInMilliseconds().get();
final int numPercentileBuckets = properties.metricsRollingPercentileWindowBuckets().get();
final int percentileBucketSizeInMs = percentileMetricWindow / numPercentileBuckets;
return getInstance(collapserKey, numPercentileBuckets, percentileBucketSizeInMs);
}
public static RollingCollapserBatchSizeDistributionStream getInstance(HystrixCollapserKey collapserKey, int numBuckets, int bucketSizeInMs) {
RollingCollapserBatchSizeDistributionStream initialStream = streams.get(collapserKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (RollingCollapserBatchSizeDistributionStream.class) {
RollingCollapserBatchSizeDistributionStream existingStream = streams.get(collapserKey.name());
if (existingStream == null) {
RollingCollapserBatchSizeDistributionStream newStream = new RollingCollapserBatchSizeDistributionStream(collapserKey, numBuckets, bucketSizeInMs);
streams.putIfAbsent(collapserKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private RollingCollapserBatchSizeDistributionStream(HystrixCollapserKey collapserKey, int numPercentileBuckets, int percentileBucketSizeInMs) {
super(HystrixCollapserEventStream.getInstance(collapserKey), numPercentileBuckets, percentileBucketSizeInMs, addValuesToBucket);
}
}
| 4,702 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingThreadPoolMaxConcurrencyStream.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.metric.HystrixThreadPoolStartStream;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of max-concurrency
*
* This gets calculated using a rolling window of t1 milliseconds. This window has b buckets.
* Therefore, a new rolling-max is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowBuckets()}
*
* This value gets cached in this class. It may be queried using {@link #getLatestRollingMax()}
*
* This is a stable value - there's no peeking into a bucket until it is emitted
*/
public class RollingThreadPoolMaxConcurrencyStream extends RollingConcurrencyStream {
private static final ConcurrentMap<String, RollingThreadPoolMaxConcurrencyStream> streams = new ConcurrentHashMap<String, RollingThreadPoolMaxConcurrencyStream>();
public static RollingThreadPoolMaxConcurrencyStream getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties properties) {
final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get();
final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get();
final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets;
return getInstance(threadPoolKey, numCounterBuckets, counterBucketSizeInMs);
}
public static RollingThreadPoolMaxConcurrencyStream getInstance(HystrixThreadPoolKey threadPoolKey, int numBuckets, int bucketSizeInMs) {
RollingThreadPoolMaxConcurrencyStream initialStream = streams.get(threadPoolKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (RollingThreadPoolMaxConcurrencyStream.class) {
RollingThreadPoolMaxConcurrencyStream existingStream = streams.get(threadPoolKey.name());
if (existingStream == null) {
RollingThreadPoolMaxConcurrencyStream newStream =
new RollingThreadPoolMaxConcurrencyStream(threadPoolKey, numBuckets, bucketSizeInMs);
streams.putIfAbsent(threadPoolKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
public RollingThreadPoolMaxConcurrencyStream(final HystrixThreadPoolKey threadPoolKey, final int numBuckets, final int bucketSizeInMs) {
super(HystrixThreadPoolStartStream.getInstance(threadPoolKey), numBuckets, bucketSizeInMs);
}
}
| 4,703 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingConcurrencyStream.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.metric.HystrixCommandExecutionStarted;
import com.netflix.hystrix.metric.HystrixEventStream;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.subjects.BehaviorSubject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Maintains a stream of max-concurrency
*
* This gets calculated using a rolling window of t1 milliseconds. This window has b buckets.
* Therefore, a new rolling-max is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link HystrixCommandProperties#metricsRollingStatisticalWindowBuckets()}
*
* This value gets cached in this class. It may be queried using {@link #getLatestRollingMax()}
*
* This is a stable value - there's no peeking into a bucket until it is emitted
*/
public abstract class RollingConcurrencyStream {
private AtomicReference<Subscription> rollingMaxSubscription = new AtomicReference<Subscription>(null);
private final BehaviorSubject<Integer> rollingMax = BehaviorSubject.create(0);
private final Observable<Integer> rollingMaxStream;
private static final Func2<Integer, Integer, Integer> reduceToMax = new Func2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer a, Integer b) {
return Math.max(a, b);
}
};
private static final Func1<Observable<Integer>, Observable<Integer>> reduceStreamToMax = new Func1<Observable<Integer>, Observable<Integer>>() {
@Override
public Observable<Integer> call(Observable<Integer> observedConcurrency) {
return observedConcurrency.reduce(0, reduceToMax);
}
};
private static final Func1<HystrixCommandExecutionStarted, Integer> getConcurrencyCountFromEvent = new Func1<HystrixCommandExecutionStarted, Integer>() {
@Override
public Integer call(HystrixCommandExecutionStarted event) {
return event.getCurrentConcurrency();
}
};
protected RollingConcurrencyStream(final HystrixEventStream<HystrixCommandExecutionStarted> inputEventStream, final int numBuckets, final int bucketSizeInMs) {
final List<Integer> emptyRollingMaxBuckets = new ArrayList<Integer>();
for (int i = 0; i < numBuckets; i++) {
emptyRollingMaxBuckets.add(0);
}
rollingMaxStream = inputEventStream
.observe()
.map(getConcurrencyCountFromEvent)
.window(bucketSizeInMs, TimeUnit.MILLISECONDS)
.flatMap(reduceStreamToMax)
.startWith(emptyRollingMaxBuckets)
.window(numBuckets, 1)
.flatMap(reduceStreamToMax)
.share()
.onBackpressureDrop();
}
public void startCachingStreamValuesIfUnstarted() {
if (rollingMaxSubscription.get() == null) {
//the stream is not yet started
Subscription candidateSubscription = observe().subscribe(rollingMax);
if (rollingMaxSubscription.compareAndSet(null, candidateSubscription)) {
//won the race to set the subscription
} else {
//lost the race to set the subscription, so we need to cancel this one
candidateSubscription.unsubscribe();
}
}
}
public long getLatestRollingMax() {
startCachingStreamValuesIfUnstarted();
if (rollingMax.hasValue()) {
return rollingMax.getValue();
} else {
return 0L;
}
}
public Observable<Integer> observe() {
return rollingMaxStream;
}
public void unsubscribe() {
Subscription s = rollingMaxSubscription.get();
if (s != null) {
s.unsubscribe();
rollingMaxSubscription.compareAndSet(s, null);
}
}
}
| 4,704 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/HealthCountsStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.metric.HystrixCommandCompletion;
import com.netflix.hystrix.metric.HystrixCommandCompletionStream;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of rolling health counts for a given Command.
* There is a rolling window abstraction on this stream.
* The HealthCounts object is calculated over a window of t1 milliseconds. This window has b buckets.
* Therefore, a new HealthCounts object is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixCommandProperties#metricsHealthSnapshotIntervalInMilliseconds()}
* b = {@link HystrixCommandProperties#metricsRollingStatisticalWindowBuckets()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class. This value (the latest observed value) may be queried using {@link #getLatest()}.
*/
public class HealthCountsStream extends BucketedRollingCounterStream<HystrixCommandCompletion, long[], HystrixCommandMetrics.HealthCounts> {
private static final ConcurrentMap<String, HealthCountsStream> streams = new ConcurrentHashMap<String, HealthCountsStream>();
private static final int NUM_EVENT_TYPES = HystrixEventType.values().length;
private static final Func2<HystrixCommandMetrics.HealthCounts, long[], HystrixCommandMetrics.HealthCounts> healthCheckAccumulator = new Func2<HystrixCommandMetrics.HealthCounts, long[], HystrixCommandMetrics.HealthCounts>() {
@Override
public HystrixCommandMetrics.HealthCounts call(HystrixCommandMetrics.HealthCounts healthCounts, long[] bucketEventCounts) {
return healthCounts.plus(bucketEventCounts);
}
};
public static HealthCountsStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) {
final int healthCountBucketSizeInMs = properties.metricsHealthSnapshotIntervalInMilliseconds().get();
if (healthCountBucketSizeInMs == 0) {
throw new RuntimeException("You have set the bucket size to 0ms. Please set a positive number, so that the metric stream can be properly consumed");
}
final int numHealthCountBuckets = properties.metricsRollingStatisticalWindowInMilliseconds().get() / healthCountBucketSizeInMs;
return getInstance(commandKey, numHealthCountBuckets, healthCountBucketSizeInMs);
}
public static HealthCountsStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) {
HealthCountsStream initialStream = streams.get(commandKey.name());
if (initialStream != null) {
return initialStream;
} else {
final HealthCountsStream healthStream;
synchronized (HealthCountsStream.class) {
HealthCountsStream existingStream = streams.get(commandKey.name());
if (existingStream == null) {
HealthCountsStream newStream = new HealthCountsStream(commandKey, numBuckets, bucketSizeInMs,
HystrixCommandMetrics.appendEventToBucket);
streams.putIfAbsent(commandKey.name(), newStream);
healthStream = newStream;
} else {
healthStream = existingStream;
}
}
healthStream.startCachingStreamValuesIfUnstarted();
return healthStream;
}
}
public static void reset() {
streams.clear();
}
public static void removeByKey(HystrixCommandKey key) {
streams.remove(key.name());
}
private HealthCountsStream(final HystrixCommandKey commandKey, final int numBuckets, final int bucketSizeInMs,
Func2<long[], HystrixCommandCompletion, long[]> reduceCommandCompletion) {
super(HystrixCommandCompletionStream.getInstance(commandKey), numBuckets, bucketSizeInMs, reduceCommandCompletion, healthCheckAccumulator);
}
@Override
long[] getEmptyBucketSummary() {
return new long[NUM_EVENT_TYPES];
}
@Override
HystrixCommandMetrics.HealthCounts getEmptyOutputValue() {
return HystrixCommandMetrics.HealthCounts.empty();
}
}
| 4,705 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/CumulativeCommandEventCounterStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.metric.HystrixCommandCompletion;
import com.netflix.hystrix.metric.HystrixCommandCompletionStream;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of event counters for a given Command.
* There is no rolling window abstraction on this stream - every event since the start of the JVM is kept track of.
* The event counters object is calculated on the same schedule as the rolling abstract {@link RollingCommandEventCounterStream},
* so bucket rolls correspond to new data in this stream, though data never goes out of window in this stream.
*
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link HystrixCommandProperties#metricsRollingStatisticalWindowBuckets()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class. This value (the latest observed value) may be queried using {@link #getLatest(HystrixEventType)}.
*/
public class CumulativeCommandEventCounterStream extends BucketedCumulativeCounterStream<HystrixCommandCompletion, long[], long[]> {
private static final ConcurrentMap<String, CumulativeCommandEventCounterStream> streams = new ConcurrentHashMap<String, CumulativeCommandEventCounterStream>();
private static final int NUM_EVENT_TYPES = HystrixEventType.values().length;
public static CumulativeCommandEventCounterStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) {
final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get();
final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get();
final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets;
return getInstance(commandKey, numCounterBuckets, counterBucketSizeInMs);
}
public static CumulativeCommandEventCounterStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) {
CumulativeCommandEventCounterStream initialStream = streams.get(commandKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (CumulativeCommandEventCounterStream.class) {
CumulativeCommandEventCounterStream existingStream = streams.get(commandKey.name());
if (existingStream == null) {
CumulativeCommandEventCounterStream newStream = new CumulativeCommandEventCounterStream(commandKey, numBuckets, bucketSizeInMs,
HystrixCommandMetrics.appendEventToBucket, HystrixCommandMetrics.bucketAggregator);
streams.putIfAbsent(commandKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private CumulativeCommandEventCounterStream(HystrixCommandKey commandKey, int numCounterBuckets, int counterBucketSizeInMs,
Func2<long[], HystrixCommandCompletion, long[]> reduceCommandCompletion,
Func2<long[], long[], long[]> reduceBucket) {
super(HystrixCommandCompletionStream.getInstance(commandKey), numCounterBuckets, counterBucketSizeInMs, reduceCommandCompletion, reduceBucket);
}
@Override
long[] getEmptyBucketSummary() {
return new long[NUM_EVENT_TYPES];
}
@Override
long[] getEmptyOutputValue() {
return new long[NUM_EVENT_TYPES];
}
public long getLatest(HystrixEventType eventType) {
return getLatest()[eventType.ordinal()];
}
}
| 4,706 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingThreadPoolEventCounterStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.metric.HystrixCommandCompletion;
import com.netflix.hystrix.metric.HystrixThreadPoolCompletionStream;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of event counters for a given ThreadPool.
* There is a rolling window abstraction on this stream.
* The event counters object is calculated over a window of t1 milliseconds. This window has b buckets.
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowBuckets()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class.
* You may query to find the latest rolling count of 2 events (executed/rejected) via {@link #getLatestCount(com.netflix.hystrix.HystrixEventType.ThreadPool)}.
*/
public class RollingThreadPoolEventCounterStream extends BucketedRollingCounterStream<HystrixCommandCompletion, long[], long[]> {
private static final ConcurrentMap<String, RollingThreadPoolEventCounterStream> streams = new ConcurrentHashMap<String, RollingThreadPoolEventCounterStream>();
private static final int ALL_EVENT_TYPES_SIZE = HystrixEventType.ThreadPool.values().length;
public static RollingThreadPoolEventCounterStream getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties properties) {
final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get();
final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get();
final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets;
return getInstance(threadPoolKey, numCounterBuckets, counterBucketSizeInMs);
}
public static RollingThreadPoolEventCounterStream getInstance(HystrixThreadPoolKey threadPoolKey, int numBuckets, int bucketSizeInMs) {
RollingThreadPoolEventCounterStream initialStream = streams.get(threadPoolKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (RollingThreadPoolEventCounterStream.class) {
RollingThreadPoolEventCounterStream existingStream = streams.get(threadPoolKey.name());
if (existingStream == null) {
RollingThreadPoolEventCounterStream newStream =
new RollingThreadPoolEventCounterStream(threadPoolKey, numBuckets, bucketSizeInMs,
HystrixThreadPoolMetrics.appendEventToBucket, HystrixThreadPoolMetrics.counterAggregator);
streams.putIfAbsent(threadPoolKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private RollingThreadPoolEventCounterStream(HystrixThreadPoolKey threadPoolKey, int numCounterBuckets, int counterBucketSizeInMs,
Func2<long[], HystrixCommandCompletion, long[]> reduceCommandCompletion,
Func2<long[], long[], long[]> reduceBucket) {
super(HystrixThreadPoolCompletionStream.getInstance(threadPoolKey), numCounterBuckets, counterBucketSizeInMs, reduceCommandCompletion, reduceBucket);
}
@Override
public long[] getEmptyBucketSummary() {
return new long[ALL_EVENT_TYPES_SIZE];
}
@Override
public long[] getEmptyOutputValue() {
return new long[ALL_EVENT_TYPES_SIZE];
}
public long getLatestCount(HystrixEventType.ThreadPool eventType) {
return getLatest()[eventType.ordinal()];
}
}
| 4,707 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCommandLatencyDistributionStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.metric.HystrixCommandCompletion;
import com.netflix.hystrix.metric.HystrixCommandCompletionStream;
import com.netflix.hystrix.metric.HystrixCommandEvent;
import org.HdrHistogram.Histogram;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of latency distributions for a given Command.
* There is a rolling window abstraction on this stream.
* The latency distribution object is calculated over a window of t1 milliseconds. This window has b buckets.
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixCommandProperties#metricsRollingPercentileWindowInMilliseconds()}
* b = {@link HystrixCommandProperties#metricsRollingPercentileBucketSize()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* The only latencies which get included in the distribution are for those commands which started execution.
* This relies on {@link HystrixCommandEvent#didCommandExecute()}
*
* These values get produced and cached in this class.
* The distributions can be queried on 2 dimensions:
* * Execution time or total time
* ** Execution time is the time spent executing the user-provided execution method.
* ** Total time is the time spent from the perspecitve of the consumer, and includes all Hystrix bookkeeping.
*/
public class RollingCommandLatencyDistributionStream extends RollingDistributionStream<HystrixCommandCompletion> {
private static final ConcurrentMap<String, RollingCommandLatencyDistributionStream> streams = new ConcurrentHashMap<String, RollingCommandLatencyDistributionStream>();
private static final Func2<Histogram, HystrixCommandCompletion, Histogram> addValuesToBucket = new Func2<Histogram, HystrixCommandCompletion, Histogram>() {
@Override
public Histogram call(Histogram initialDistribution, HystrixCommandCompletion event) {
if (event.didCommandExecute() && event.getExecutionLatency() > -1) {
initialDistribution.recordValue(event.getExecutionLatency());
}
return initialDistribution;
}
};
public static RollingCommandLatencyDistributionStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) {
final int percentileMetricWindow = properties.metricsRollingPercentileWindowInMilliseconds().get();
final int numPercentileBuckets = properties.metricsRollingPercentileWindowBuckets().get();
final int percentileBucketSizeInMs = percentileMetricWindow / numPercentileBuckets;
return getInstance(commandKey, numPercentileBuckets, percentileBucketSizeInMs);
}
public static RollingCommandLatencyDistributionStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) {
RollingCommandLatencyDistributionStream initialStream = streams.get(commandKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (RollingCommandLatencyDistributionStream.class) {
RollingCommandLatencyDistributionStream existingStream = streams.get(commandKey.name());
if (existingStream == null) {
RollingCommandLatencyDistributionStream newStream = new RollingCommandLatencyDistributionStream(commandKey, numBuckets, bucketSizeInMs);
streams.putIfAbsent(commandKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private RollingCommandLatencyDistributionStream(HystrixCommandKey commandKey, int numPercentileBuckets, int percentileBucketSizeInMs) {
super(HystrixCommandCompletionStream.getInstance(commandKey), numPercentileBuckets, percentileBucketSizeInMs, addValuesToBucket);
}
}
| 4,708 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/CumulativeThreadPoolEventCounterStream.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.metric.HystrixCommandCompletion;
import com.netflix.hystrix.metric.HystrixThreadPoolCompletionStream;
import rx.functions.Func2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Maintains a stream of event counters for a given ThreadPool.
* There is a rolling window abstraction on this stream.
* The event counters object is calculated over a window of t1 milliseconds. This window has b buckets.
* Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds
* t1 = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}
* b = {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowBuckets()}
*
* These values are stable - there's no peeking into a bucket until it is emitted
*
* These values get produced and cached in this class.
* You may query to find the latest rolling count of 2 events (executed/rejected) via {@link #getLatestCount(com.netflix.hystrix.HystrixEventType.ThreadPool)}.
*/
public class CumulativeThreadPoolEventCounterStream extends BucketedCumulativeCounterStream<HystrixCommandCompletion, long[], long[]> {
private static final ConcurrentMap<String, CumulativeThreadPoolEventCounterStream> streams = new ConcurrentHashMap<String, CumulativeThreadPoolEventCounterStream>();
private static final int ALL_EVENT_TYPES_SIZE = HystrixEventType.ThreadPool.values().length;
public static CumulativeThreadPoolEventCounterStream getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties properties) {
final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get();
final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get();
final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets;
return getInstance(threadPoolKey, numCounterBuckets, counterBucketSizeInMs);
}
public static CumulativeThreadPoolEventCounterStream getInstance(HystrixThreadPoolKey threadPoolKey, int numBuckets, int bucketSizeInMs) {
CumulativeThreadPoolEventCounterStream initialStream = streams.get(threadPoolKey.name());
if (initialStream != null) {
return initialStream;
} else {
synchronized (CumulativeThreadPoolEventCounterStream.class) {
CumulativeThreadPoolEventCounterStream existingStream = streams.get(threadPoolKey.name());
if (existingStream == null) {
CumulativeThreadPoolEventCounterStream newStream =
new CumulativeThreadPoolEventCounterStream(threadPoolKey, numBuckets, bucketSizeInMs,
HystrixThreadPoolMetrics.appendEventToBucket, HystrixThreadPoolMetrics.counterAggregator);
streams.putIfAbsent(threadPoolKey.name(), newStream);
return newStream;
} else {
return existingStream;
}
}
}
}
public static void reset() {
streams.clear();
}
private CumulativeThreadPoolEventCounterStream(HystrixThreadPoolKey threadPoolKey, int numCounterBuckets, int counterBucketSizeInMs,
Func2<long[], HystrixCommandCompletion, long[]> reduceCommandCompletion,
Func2<long[], long[], long[]> reduceBucket) {
super(HystrixThreadPoolCompletionStream.getInstance(threadPoolKey), numCounterBuckets, counterBucketSizeInMs, reduceCommandCompletion, reduceBucket);
}
@Override
public long[] getEmptyBucketSummary() {
return new long[ALL_EVENT_TYPES_SIZE];
}
@Override
public long[] getEmptyOutputValue() {
return new long[ALL_EVENT_TYPES_SIZE];
}
public long getLatestCount(HystrixEventType.ThreadPool eventType) {
return getLatest()[eventType.ordinal()];
}
}
| 4,709 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/exception/HystrixTimeoutException.java | /**
* Copyright 2015 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 com.netflix.hystrix.exception;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixObservableCommand;
/**
* An exception representing an error where the provided execution method took longer than the Hystrix timeout.
* <p>
* Hystrix will trigger an exception of this type if it times out an execution. This class is public, so
* user-defined execution methods ({@link HystrixCommand#run()} / {@link HystrixObservableCommand#construct()) may also
* throw this error. If you want some types of failures to be counted as timeouts, you may wrap those failures in
* a HystrixTimeoutException. See https://github.com/Netflix/Hystrix/issues/920 for more discussion.
*/
public class HystrixTimeoutException extends Exception {
private static final long serialVersionUID = -5085623652043595962L;
}
| 4,710 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/exception/HystrixBadRequestException.java | /**
* Copyright 2012 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 com.netflix.hystrix.exception;
import com.netflix.hystrix.HystrixCommand;
/**
* An exception representing an error with provided arguments or state rather than an execution failure.
* <p>
* Unlike all other exceptions thrown by a {@link HystrixCommand} this will not trigger fallback, not count against failure metrics and thus not trigger the circuit breaker.
* <p>
* NOTE: This should <b>only</b> be used when an error is due to user input such as {@link IllegalArgumentException} otherwise it defeats the purpose of fault-tolerance and fallback behavior.
*/
public class HystrixBadRequestException extends RuntimeException {
private static final long serialVersionUID = -8341452103561805856L;
public HystrixBadRequestException(String message) {
super(message);
}
public HystrixBadRequestException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,711 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/exception/HystrixRuntimeException.java | /**
* Copyright 2012 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 com.netflix.hystrix.exception;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.util.ExceptionThreadingUtility;
/**
* RuntimeException that is thrown when a {@link HystrixCommand} fails and does not have a fallback.
*/
@SuppressWarnings("rawtypes")
public class HystrixRuntimeException extends RuntimeException {
private static final long serialVersionUID = 5219160375476046229L;
private final Class<? extends HystrixInvokable> commandClass;
private final Throwable fallbackException;
private final FailureType failureCause;
public static enum FailureType {
BAD_REQUEST_EXCEPTION, COMMAND_EXCEPTION, TIMEOUT, SHORTCIRCUIT, REJECTED_THREAD_EXECUTION, REJECTED_SEMAPHORE_EXECUTION, REJECTED_SEMAPHORE_FALLBACK
}
public HystrixRuntimeException(FailureType failureCause, Class<? extends HystrixInvokable> commandClass, String message, Exception cause, Throwable fallbackException) {
super(message, cause);
this.failureCause = failureCause;
this.commandClass = commandClass;
this.fallbackException = fallbackException;
}
public HystrixRuntimeException(FailureType failureCause, Class<? extends HystrixInvokable> commandClass, String message, Throwable cause, Throwable fallbackException) {
super(message, cause);
this.failureCause = failureCause;
this.commandClass = commandClass;
this.fallbackException = fallbackException;
}
/**
* The type of failure that caused this exception to be thrown.
*
* @return {@link FailureType}
*/
public FailureType getFailureType() {
return failureCause;
}
/**
* The implementing class of the {@link HystrixCommand}.
*
* @return {@code Class<? extends HystrixCommand> }
*/
public Class<? extends HystrixInvokable> getImplementingClass() {
return commandClass;
}
/**
* The {@link Throwable} that was thrown when trying to retrieve a fallback.
*
* @return {@link Throwable}
*/
public Throwable getFallbackException() {
return fallbackException;
}
}
| 4,712 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/exception/ExceptionNotWrappedByHystrix.java | package com.netflix.hystrix.exception;
/**
* Exceptions can implement this interface to prevent Hystrix from wrapping detected exceptions in a HystrixRuntimeException
*/
public interface ExceptionNotWrappedByHystrix {
}
| 4,713 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/exception/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Custom exception implementations.
*
* @since 1.0.0
*/
package com.netflix.hystrix.exception; | 4,714 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/HystrixPlugins.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifierDefault;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHookDefault;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherDefault;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory;
import com.netflix.hystrix.strategy.properties.HystrixDynamicProperties;
import com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesSystemProperties;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategyDefault;
/**
* Registry for plugin implementations that allows global override and handles the retrieval of correct implementation based on order of precedence:
* <ol>
* <li>plugin registered globally via <code>register</code> methods in this class</li>
* <li>plugin registered and retrieved using the resolved {@link HystrixDynamicProperties} (usually Archaius, see get methods for property names)</li>
* <li>plugin registered and retrieved using the JDK {@link ServiceLoader}</li>
* <li>default implementation</li>
* </ol>
*
* The exception to the above order is the {@link HystrixDynamicProperties} implementation
* which is only loaded through <code>System.properties</code> or the ServiceLoader (see the {@link HystrixPlugins#getDynamicProperties() getter} for more details).
* <p>
* See the Hystrix GitHub Wiki for more information: <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
*/
public class HystrixPlugins {
//We should not load unless we are requested to. This avoids accidental initialization. @agentgt
//See https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
private static class LazyHolder { private static final HystrixPlugins INSTANCE = HystrixPlugins.create(); }
private final ClassLoader classLoader;
/* package */ final AtomicReference<HystrixEventNotifier> notifier = new AtomicReference<HystrixEventNotifier>();
/* package */ final AtomicReference<HystrixConcurrencyStrategy> concurrencyStrategy = new AtomicReference<HystrixConcurrencyStrategy>();
/* package */ final AtomicReference<HystrixMetricsPublisher> metricsPublisher = new AtomicReference<HystrixMetricsPublisher>();
/* package */ final AtomicReference<HystrixPropertiesStrategy> propertiesFactory = new AtomicReference<HystrixPropertiesStrategy>();
/* package */ final AtomicReference<HystrixCommandExecutionHook> commandExecutionHook = new AtomicReference<HystrixCommandExecutionHook>();
private final HystrixDynamicProperties dynamicProperties;
private HystrixPlugins(ClassLoader classLoader, LoggerSupplier logSupplier) {
//This will load Archaius if its in the classpath.
this.classLoader = classLoader;
//N.B. Do not use a logger before this is loaded as it will most likely load the configuration system.
//The configuration system may need to do something prior to loading logging. @agentgt
dynamicProperties = resolveDynamicProperties(classLoader, logSupplier);
}
/**
* For unit test purposes.
* @ExcludeFromJavadoc
*/
/* private */ static HystrixPlugins create(ClassLoader classLoader, LoggerSupplier logSupplier) {
return new HystrixPlugins(classLoader, logSupplier);
}
/**
* For unit test purposes.
* @ExcludeFromJavadoc
*/
/* private */ static HystrixPlugins create(ClassLoader classLoader) {
return new HystrixPlugins(classLoader, new LoggerSupplier() {
@Override
public Logger getLogger() {
return LoggerFactory.getLogger(HystrixPlugins.class);
}
});
}
/**
* @ExcludeFromJavadoc
*/
/* private */ static HystrixPlugins create() {
return create(HystrixPlugins.class.getClassLoader());
}
public static HystrixPlugins getInstance() {
return LazyHolder.INSTANCE;
}
/**
* Reset all of the HystrixPlugins to null. You may invoke this directly, or it also gets invoked via <code>Hystrix.reset()</code>
*/
public static void reset() {
getInstance().notifier.set(null);
getInstance().concurrencyStrategy.set(null);
getInstance().metricsPublisher.set(null);
getInstance().propertiesFactory.set(null);
getInstance().commandExecutionHook.set(null);
HystrixMetricsPublisherFactory.reset();
}
/**
* Retrieve instance of {@link HystrixEventNotifier} to use based on order of precedence as defined in {@link HystrixPlugins} class header.
* <p>
* Override default by using {@link #registerEventNotifier(HystrixEventNotifier)} or setting property (via Archaius): <code>hystrix.plugin.HystrixEventNotifier.implementation</code> with the full classname to
* load.
*
* @return {@link HystrixEventNotifier} implementation to use
*/
public HystrixEventNotifier getEventNotifier() {
if (notifier.get() == null) {
// check for an implementation from Archaius first
Object impl = getPluginImplementation(HystrixEventNotifier.class);
if (impl == null) {
// nothing set via Archaius so initialize with default
notifier.compareAndSet(null, HystrixEventNotifierDefault.getInstance());
// we don't return from here but call get() again in case of thread-race so the winner will always get returned
} else {
// we received an implementation from Archaius so use it
notifier.compareAndSet(null, (HystrixEventNotifier) impl);
}
}
return notifier.get();
}
/**
* Register a {@link HystrixEventNotifier} implementation as a global override of any injected or default implementations.
*
* @param impl
* {@link HystrixEventNotifier} implementation
* @throws IllegalStateException
* if called more than once or after the default was initialized (if usage occurs before trying to register)
*/
public void registerEventNotifier(HystrixEventNotifier impl) {
if (!notifier.compareAndSet(null, impl)) {
throw new IllegalStateException("Another strategy was already registered.");
}
}
/**
* Retrieve instance of {@link HystrixConcurrencyStrategy} to use based on order of precedence as defined in {@link HystrixPlugins} class header.
* <p>
* Override default by using {@link #registerConcurrencyStrategy(HystrixConcurrencyStrategy)} or setting property (via Archaius): <code>hystrix.plugin.HystrixConcurrencyStrategy.implementation</code> with the
* full classname to load.
*
* @return {@link HystrixConcurrencyStrategy} implementation to use
*/
public HystrixConcurrencyStrategy getConcurrencyStrategy() {
if (concurrencyStrategy.get() == null) {
// check for an implementation from Archaius first
Object impl = getPluginImplementation(HystrixConcurrencyStrategy.class);
if (impl == null) {
// nothing set via Archaius so initialize with default
concurrencyStrategy.compareAndSet(null, HystrixConcurrencyStrategyDefault.getInstance());
// we don't return from here but call get() again in case of thread-race so the winner will always get returned
} else {
// we received an implementation from Archaius so use it
concurrencyStrategy.compareAndSet(null, (HystrixConcurrencyStrategy) impl);
}
}
return concurrencyStrategy.get();
}
/**
* Register a {@link HystrixConcurrencyStrategy} implementation as a global override of any injected or default implementations.
*
* @param impl
* {@link HystrixConcurrencyStrategy} implementation
* @throws IllegalStateException
* if called more than once or after the default was initialized (if usage occurs before trying to register)
*/
public void registerConcurrencyStrategy(HystrixConcurrencyStrategy impl) {
if (!concurrencyStrategy.compareAndSet(null, impl)) {
throw new IllegalStateException("Another strategy was already registered.");
}
}
/**
* Retrieve instance of {@link HystrixMetricsPublisher} to use based on order of precedence as defined in {@link HystrixPlugins} class header.
* <p>
* Override default by using {@link #registerMetricsPublisher(HystrixMetricsPublisher)} or setting property (via Archaius): <code>hystrix.plugin.HystrixMetricsPublisher.implementation</code> with the full
* classname to load.
*
* @return {@link HystrixMetricsPublisher} implementation to use
*/
public HystrixMetricsPublisher getMetricsPublisher() {
if (metricsPublisher.get() == null) {
// check for an implementation from Archaius first
Object impl = getPluginImplementation(HystrixMetricsPublisher.class);
if (impl == null) {
// nothing set via Archaius so initialize with default
metricsPublisher.compareAndSet(null, HystrixMetricsPublisherDefault.getInstance());
// we don't return from here but call get() again in case of thread-race so the winner will always get returned
} else {
// we received an implementation from Archaius so use it
metricsPublisher.compareAndSet(null, (HystrixMetricsPublisher) impl);
}
}
return metricsPublisher.get();
}
/**
* Register a {@link HystrixMetricsPublisher} implementation as a global override of any injected or default implementations.
*
* @param impl
* {@link HystrixMetricsPublisher} implementation
* @throws IllegalStateException
* if called more than once or after the default was initialized (if usage occurs before trying to register)
*/
public void registerMetricsPublisher(HystrixMetricsPublisher impl) {
if (!metricsPublisher.compareAndSet(null, impl)) {
throw new IllegalStateException("Another strategy was already registered.");
}
}
/**
* Retrieve instance of {@link HystrixPropertiesStrategy} to use based on order of precedence as defined in {@link HystrixPlugins} class header.
* <p>
* Override default by using {@link #registerPropertiesStrategy(HystrixPropertiesStrategy)} or setting property (via Archaius): <code>hystrix.plugin.HystrixPropertiesStrategy.implementation</code> with the full
* classname to load.
*
* @return {@link HystrixPropertiesStrategy} implementation to use
*/
public HystrixPropertiesStrategy getPropertiesStrategy() {
if (propertiesFactory.get() == null) {
// check for an implementation from Archaius first
Object impl = getPluginImplementation(HystrixPropertiesStrategy.class);
if (impl == null) {
// nothing set via Archaius so initialize with default
propertiesFactory.compareAndSet(null, HystrixPropertiesStrategyDefault.getInstance());
// we don't return from here but call get() again in case of thread-race so the winner will always get returned
} else {
// we received an implementation from Archaius so use it
propertiesFactory.compareAndSet(null, (HystrixPropertiesStrategy) impl);
}
}
return propertiesFactory.get();
}
/**
* Retrieves the instance of {@link HystrixDynamicProperties} to use.
* <p>
* Unlike the other plugins this plugin cannot be re-registered and is only loaded at creation
* of the {@link HystrixPlugins} singleton.
* <p>
* The order of precedence for loading implementations is:
* <ol>
* <li>System property of key: <code>hystrix.plugin.HystrixDynamicProperties.implementation</code> with the class as a value.</li>
* <li>The {@link ServiceLoader}.</li>
* <li>An implementation based on Archaius if it is found in the classpath is used.</li>
* <li>A fallback implementation based on the {@link System#getProperties()}</li>
* </ol>
* @return never <code>null</code>
*/
public HystrixDynamicProperties getDynamicProperties() {
return dynamicProperties;
}
/**
* Register a {@link HystrixPropertiesStrategy} implementation as a global override of any injected or default implementations.
*
* @param impl
* {@link HystrixPropertiesStrategy} implementation
* @throws IllegalStateException
* if called more than once or after the default was initialized (if usage occurs before trying to register)
*/
public void registerPropertiesStrategy(HystrixPropertiesStrategy impl) {
if (!propertiesFactory.compareAndSet(null, impl)) {
throw new IllegalStateException("Another strategy was already registered.");
}
}
/**
* Retrieve instance of {@link HystrixCommandExecutionHook} to use based on order of precedence as defined in {@link HystrixPlugins} class header.
* <p>
* Override default by using {@link #registerCommandExecutionHook(HystrixCommandExecutionHook)} or setting property (via Archaius): <code>hystrix.plugin.HystrixCommandExecutionHook.implementation</code> with the
* full classname to
* load.
*
* @return {@link HystrixCommandExecutionHook} implementation to use
*
* @since 1.2
*/
public HystrixCommandExecutionHook getCommandExecutionHook() {
if (commandExecutionHook.get() == null) {
// check for an implementation from Archaius first
Object impl = getPluginImplementation(HystrixCommandExecutionHook.class);
if (impl == null) {
// nothing set via Archaius so initialize with default
commandExecutionHook.compareAndSet(null, HystrixCommandExecutionHookDefault.getInstance());
// we don't return from here but call get() again in case of thread-race so the winner will always get returned
} else {
// we received an implementation from Archaius so use it
commandExecutionHook.compareAndSet(null, (HystrixCommandExecutionHook) impl);
}
}
return commandExecutionHook.get();
}
/**
* Register a {@link HystrixCommandExecutionHook} implementation as a global override of any injected or default implementations.
*
* @param impl
* {@link HystrixCommandExecutionHook} implementation
* @throws IllegalStateException
* if called more than once or after the default was initialized (if usage occurs before trying to register)
*
* @since 1.2
*/
public void registerCommandExecutionHook(HystrixCommandExecutionHook impl) {
if (!commandExecutionHook.compareAndSet(null, impl)) {
throw new IllegalStateException("Another strategy was already registered.");
}
}
private <T> T getPluginImplementation(Class<T> pluginClass) {
T p = getPluginImplementationViaProperties(pluginClass, dynamicProperties);
if (p != null) return p;
return findService(pluginClass, classLoader);
}
@SuppressWarnings("unchecked")
private static <T> T getPluginImplementationViaProperties(Class<T> pluginClass, HystrixDynamicProperties dynamicProperties) {
String classSimpleName = pluginClass.getSimpleName();
// Check Archaius for plugin class.
String propertyName = "hystrix.plugin." + classSimpleName + ".implementation";
String implementingClass = dynamicProperties.getString(propertyName, null).get();
if (implementingClass != null) {
try {
Class<?> cls = Class.forName(implementingClass);
// narrow the scope (cast) to the type we're expecting
cls = cls.asSubclass(pluginClass);
return (T) cls.newInstance();
} catch (ClassCastException e) {
throw new RuntimeException(classSimpleName + " implementation is not an instance of " + classSimpleName + ": " + implementingClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(classSimpleName + " implementation class not found: " + implementingClass, e);
} catch (InstantiationException e) {
throw new RuntimeException(classSimpleName + " implementation not able to be instantiated: " + implementingClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException(classSimpleName + " implementation not able to be accessed: " + implementingClass, e);
}
} else {
return null;
}
}
private static HystrixDynamicProperties resolveDynamicProperties(ClassLoader classLoader, LoggerSupplier logSupplier) {
HystrixDynamicProperties hp = getPluginImplementationViaProperties(HystrixDynamicProperties.class,
HystrixDynamicPropertiesSystemProperties.getInstance());
if (hp != null) {
logSupplier.getLogger().debug(
"Created HystrixDynamicProperties instance from System property named "
+ "\"hystrix.plugin.HystrixDynamicProperties.implementation\". Using class: {}",
hp.getClass().getCanonicalName());
return hp;
}
hp = findService(HystrixDynamicProperties.class, classLoader);
if (hp != null) {
logSupplier.getLogger()
.debug("Created HystrixDynamicProperties instance by loading from ServiceLoader. Using class: {}",
hp.getClass().getCanonicalName());
return hp;
}
hp = HystrixArchaiusHelper.createArchaiusDynamicProperties();
if (hp != null) {
logSupplier.getLogger().debug("Created HystrixDynamicProperties. Using class : {}",
hp.getClass().getCanonicalName());
return hp;
}
hp = HystrixDynamicPropertiesSystemProperties.getInstance();
logSupplier.getLogger().info("Using System Properties for HystrixDynamicProperties! Using class: {}",
hp.getClass().getCanonicalName());
return hp;
}
private static <T> T findService(
Class<T> spi,
ClassLoader classLoader) throws ServiceConfigurationError {
ServiceLoader<T> sl = ServiceLoader.load(spi,
classLoader);
for (T s : sl) {
if (s != null)
return s;
}
return null;
}
interface LoggerSupplier {
Logger getLogger();
}
}
| 4,715 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/HystrixArchaiusHelper.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.strategy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.netflix.hystrix.strategy.properties.HystrixDynamicProperties;
/**
* @ExcludeFromJavadoc
* @author agentgt
*/
class HystrixArchaiusHelper {
/**
* To keep class loading minimal for those that have archaius in the classpath but choose not to use it.
* @ExcludeFromJavadoc
* @author agent
*/
private static class LazyHolder {
private final static Method loadCascadedPropertiesFromResources;
private final static String CONFIG_MANAGER_CLASS = "com.netflix.config.ConfigurationManager";
static {
Method load = null;
try {
Class<?> configManager = Class.forName(CONFIG_MANAGER_CLASS);
load = configManager.getMethod("loadCascadedPropertiesFromResources", String.class);
} catch (Exception e) {
}
loadCascadedPropertiesFromResources = load;
}
}
/**
* @ExcludeFromJavadoc
*/
static boolean isArchaiusV1Available() {
return LazyHolder.loadCascadedPropertiesFromResources != null;
}
static void loadCascadedPropertiesFromResources(String name) {
if (isArchaiusV1Available()) {
try {
LazyHolder.loadCascadedPropertiesFromResources.invoke(null, name);
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
}
}
/**
* @ExcludeFromJavadoc
*/
static HystrixDynamicProperties createArchaiusDynamicProperties() {
if (isArchaiusV1Available()) {
loadCascadedPropertiesFromResources("hystrix-plugins");
try {
Class<?> defaultProperties = Class.forName(
"com.netflix.hystrix.strategy.properties.archaius" + ".HystrixDynamicPropertiesArchaius");
return (HystrixDynamicProperties) defaultProperties.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
// Fallback to System properties.
return null;
}
}
| 4,716 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Parent package of strategies and plugin management.
*
* @since 1.0.0
*/
package com.netflix.hystrix.strategy; | 4,717 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherCommandDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
/**
* Default implementation of {@link HystrixMetricsPublisherCommand} that does nothing.
* <p>
* See <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">Wiki docs</a> about plugins for more information.
*
* @ExcludeFromJavadoc
*/
public class HystrixMetricsPublisherCommandDefault implements HystrixMetricsPublisherCommand {
public HystrixMetricsPublisherCommandDefault(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
// do nothing by default
}
@Override
public void initialize() {
// do nothing by default
}
}
| 4,718 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisher.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Abstract class with default implementations of Factory methods for creating "Metrics Publisher" instances for getting metrics and other related data
* exposed, published or otherwise retrievable by external systems such as Servo (https://github.com/Netflix/servo)
* for monitoring and statistical purposes.
* <p>
* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
* href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
*/
public abstract class HystrixMetricsPublisher {
// TODO should this have cacheKey functionality like HystrixProperties does?
// I think we do otherwise dynamically provided owner and properties won't work
// a custom override would need the caching strategy for properties/publisher/owner etc to be in sync
/**
* Construct an implementation of {@link HystrixMetricsPublisherCommand} for {@link HystrixCommand} instances having key {@link HystrixCommandKey}.
* <p>
* This will be invoked once per {@link HystrixCommandKey} instance.
* <p>
* <b>Default Implementation</b>
* <p>
* Return instance of {@link HystrixMetricsPublisherCommandDefault}
*
* @param commandKey
* {@link HystrixCommandKey} representing the name or type of {@link HystrixCommand}
* @param commandGroupKey
* {@link HystrixCommandGroupKey} of {@link HystrixCommand}
* @param metrics
* {@link HystrixCommandMetrics} instance tracking metrics for {@link HystrixCommand} instances having the key as defined by {@link HystrixCommandKey}
* @param circuitBreaker
* {@link HystrixCircuitBreaker} instance for {@link HystrixCommand} instances having the key as defined by {@link HystrixCommandKey}
* @param properties
* {@link HystrixCommandProperties} instance for {@link HystrixCommand} instances having the key as defined by {@link HystrixCommandKey}
* @return instance of {@link HystrixMetricsPublisherCommand} that will have its <code>initialize</code> method invoked once.
*/
public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
return new HystrixMetricsPublisherCommandDefault(commandKey, commandGroupKey, metrics, circuitBreaker, properties);
}
/**
* Construct an implementation of {@link HystrixMetricsPublisherThreadPool} for {@link HystrixThreadPool} instances having key {@link HystrixThreadPoolKey}.
* <p>
* This will be invoked once per {@link HystrixThreadPoolKey} instance.
* <p>
* <b>Default Implementation</b>
* <p>
* Return instance of {@link HystrixMetricsPublisherThreadPoolDefault}
*
* @param threadPoolKey
* {@link HystrixThreadPoolKey} representing the name or type of {@link HystrixThreadPool}
* @param metrics
* {@link HystrixThreadPoolMetrics} instance tracking metrics for the {@link HystrixThreadPool} instance having the key as defined by {@link HystrixThreadPoolKey}
* @param properties
* {@link HystrixThreadPoolProperties} instance for the {@link HystrixThreadPool} instance having the key as defined by {@link HystrixThreadPoolKey}
* @return instance of {@link HystrixMetricsPublisherThreadPool} that will have its <code>initialize</code> method invoked once.
*/
public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
return new HystrixMetricsPublisherThreadPoolDefault(threadPoolKey, metrics, properties);
}
/**
* Construct an implementation of {@link HystrixMetricsPublisherCollapser} for {@link HystrixCollapser} instances having key {@link HystrixCollapserKey}.
* <p>
* This will be invoked once per {@link HystrixCollapserKey} instance.
* <p>
* <b>Default Implementation</b>
* <p>
* Return instance of {@link HystrixMetricsPublisherCollapserDefault}
*
* @param collapserKey
* {@link HystrixCollapserKey} representing the name or type of {@link HystrixCollapser}
* @param metrics
* {@link HystrixCollapserMetrics} instance tracking metrics for the {@link HystrixCollapser} instance having the key as defined by {@link HystrixCollapserKey}
* @param properties
* {@link HystrixCollapserProperties} instance for the {@link HystrixCollapser} instance having the key as defined by {@link HystrixCollapserKey}
* @return instance of {@link HystrixMetricsPublisherCollapser} that will have its <code>initialize</code> method invoked once.
*/
public HystrixMetricsPublisherCollapser getMetricsPublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
return new HystrixMetricsPublisherCollapserDefault(collapserKey, metrics, properties);
}
}
| 4,719 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherCollapser.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixCollapser;
/**
* Metrics publisher for a {@link HystrixCollapser} that will be constructed by an implementation of {@link HystrixMetricsPublisher}.
* <p>
* Instantiation of implementations of this interface should NOT allocate resources that require shutdown, register listeners or other such global state changes.
* <p>
* The <code>initialize()</code> method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
* <p>
* Doing this logic in the constructor could result in memory leaks, double-publishing and other such behavior because this can be optimistically constructed more than once and "extras" discarded with
* only one actually having <code>initialize()</code> called on it.
*/
public interface HystrixMetricsPublisherCollapser {
// TODO should the arguments be given via initialize rather than constructor so people can't accidentally do it wrong?
public void initialize();
}
| 4,720 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherCollapserDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
/**
* Default implementation of {@link HystrixMetricsPublisherCollapser} that does nothing.
* <p>
* See <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">Wiki docs</a> about plugins for more information.
*
* @ExcludeFromJavadoc
*/
public class HystrixMetricsPublisherCollapserDefault implements HystrixMetricsPublisherCollapser {
public HystrixMetricsPublisherCollapserDefault(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
// do nothing by default
}
@Override
public void initialize() {
// do nothing by default
}
}
| 4,721 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherThreadPool.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixThreadPool;
/**
* Metrics publisher for a {@link HystrixThreadPool} that will be constructed by an implementation of {@link HystrixMetricsPublisher}.
* <p>
* Instantiation of implementations of this interface should NOT allocate resources that require shutdown, register listeners or other such global state changes.
* <p>
* The <code>initialize()</code> method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
* <p>
* Doing this logic in the constructor could result in memory leaks, double-publishing and other such behavior because this can be optimistically constructed more than once and "extras" discarded with
* only one actually having <code>initialize()</code> called on it.
*/
public interface HystrixMetricsPublisherThreadPool {
// TODO should the arguments be given via initialize rather than constructor so people can't accidentally do it wrong?
public void initialize();
}
| 4,722 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
/**
* Default implementation of {@link HystrixMetricsPublisher}.
* <p>
* See <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">Wiki docs</a> about plugins for more information.
*
* @ExcludeFromJavadoc
*/
public class HystrixMetricsPublisherDefault extends HystrixMetricsPublisher {
private static HystrixMetricsPublisherDefault INSTANCE = new HystrixMetricsPublisherDefault();
public static HystrixMetricsPublisher getInstance() {
return INSTANCE;
}
private HystrixMetricsPublisherDefault() {
}
}
| 4,723 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherCommand.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixCommand;
/**
* Metrics publisher for a {@link HystrixCommand} that will be constructed by an implementation of {@link HystrixMetricsPublisher}.
* <p>
* Instantiation of implementations of this interface should NOT allocate resources that require shutdown, register listeners or other such global state changes.
* <p>
* The <code>initialize()</code> method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
* <p>
* Doing this logic in the constructor could result in memory leaks, double-publishing and other such behavior because this can be optimistically constructed more than once and "extras" discarded with
* only one actually having <code>initialize()</code> called on it.
*/
public interface HystrixMetricsPublisherCommand {
// TODO should the arguments be given via initialize rather than constructor so they can't accidentally do it wrong?
public void initialize();
}
| 4,724 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Strategy definition for publishing metrics and default implementation.
*
* @since 1.0.0
*/
package com.netflix.hystrix.strategy.metrics; | 4,725 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherThreadPoolDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
/**
* Default implementation of {@link HystrixMetricsPublisherThreadPool} that does nothing.
* <p>
* See <a href="https://github.com/Netflix/Hystrix/wiki/Plugins">Wiki docs</a> about plugins for more information.
*
* @ExcludeFromJavadoc
*/
public class HystrixMetricsPublisherThreadPoolDefault implements HystrixMetricsPublisherThreadPool {
public HystrixMetricsPublisherThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
// do nothing by default
}
@Override
public void initialize() {
// do nothing by default
}
}
| 4,726 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactory.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.metrics;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Factory for retrieving metrics publisher implementations.
* <p>
* This uses given {@link HystrixMetricsPublisher} implementations to construct publisher instances and caches each instance according to the cache key provided.
*
* @ExcludeFromJavadoc
*/
public class HystrixMetricsPublisherFactory {
/**
* The SINGLETON instance for real use.
* <p>
* Unit tests will create instance methods for testing and injecting different publishers.
*/
private static HystrixMetricsPublisherFactory SINGLETON = new HystrixMetricsPublisherFactory();
/**
* Get an instance of {@link HystrixMetricsPublisherThreadPool} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixThreadPool} instance.
*
* @param threadPoolKey
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation
* @param metrics
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation
* @param properties
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation
* @return {@link HystrixMetricsPublisherThreadPool} instance
*/
public static HystrixMetricsPublisherThreadPool createOrRetrievePublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
return SINGLETON.getPublisherForThreadPool(threadPoolKey, metrics, properties);
}
/**
* Get an instance of {@link HystrixMetricsPublisherCommand} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixCommand} instance.
*
* @param commandKey
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCommand} implementation
* @param commandOwner
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCommand} implementation
* @param metrics
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCommand} implementation
* @param circuitBreaker
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCommand} implementation
* @param properties
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCommand} implementation
* @return {@link HystrixMetricsPublisherCommand} instance
*/
public static HystrixMetricsPublisherCommand createOrRetrievePublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandOwner, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
return SINGLETON.getPublisherForCommand(commandKey, commandOwner, metrics, circuitBreaker, properties);
}
/**
* Resets the SINGLETON object.
* Clears all state from publishers. If new requests come in instances will be recreated.
*
*/
public static void reset() {
SINGLETON = new HystrixMetricsPublisherFactory();
SINGLETON.commandPublishers.clear();
SINGLETON.threadPoolPublishers.clear();
SINGLETON.collapserPublishers.clear();
}
/* package */ HystrixMetricsPublisherFactory() {}
// String is CommandKey.name() (we can't use CommandKey directly as we can't guarantee it implements hashcode/equals correctly)
private final ConcurrentHashMap<String, HystrixMetricsPublisherCommand> commandPublishers = new ConcurrentHashMap<String, HystrixMetricsPublisherCommand>();
/* package */ HystrixMetricsPublisherCommand getPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandOwner, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
// attempt to retrieve from cache first
HystrixMetricsPublisherCommand publisher = commandPublishers.get(commandKey.name());
if (publisher != null) {
return publisher;
} else {
synchronized (this) {
HystrixMetricsPublisherCommand existingPublisher = commandPublishers.get(commandKey.name());
if (existingPublisher != null) {
return existingPublisher;
} else {
HystrixMetricsPublisherCommand newPublisher = HystrixPlugins.getInstance().getMetricsPublisher().getMetricsPublisherForCommand(commandKey, commandOwner, metrics, circuitBreaker, properties);
commandPublishers.putIfAbsent(commandKey.name(), newPublisher);
newPublisher.initialize();
return newPublisher;
}
}
}
}
// String is ThreadPoolKey.name() (we can't use ThreadPoolKey directly as we can't guarantee it implements hashcode/equals correctly)
private final ConcurrentHashMap<String, HystrixMetricsPublisherThreadPool> threadPoolPublishers = new ConcurrentHashMap<String, HystrixMetricsPublisherThreadPool>();
/* package */ HystrixMetricsPublisherThreadPool getPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
// attempt to retrieve from cache first
HystrixMetricsPublisherThreadPool publisher = threadPoolPublishers.get(threadPoolKey.name());
if (publisher != null) {
return publisher;
}
// it doesn't exist so we need to create it
publisher = HystrixPlugins.getInstance().getMetricsPublisher().getMetricsPublisherForThreadPool(threadPoolKey, metrics, properties);
// attempt to store it (race other threads)
HystrixMetricsPublisherThreadPool existing = threadPoolPublishers.putIfAbsent(threadPoolKey.name(), publisher);
if (existing == null) {
// we won the thread-race to store the instance we created so initialize it
publisher.initialize();
// done registering, return instance that got cached
return publisher;
} else {
// we lost so return 'existing' and let the one we created be garbage collected
// without calling initialize() on it
return existing;
}
}
/**
* Get an instance of {@link HystrixMetricsPublisherCollapser} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixCollapser} instance.
*
* @param collapserKey
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation
* @param metrics
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation
* @param properties
* Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForCollapser} implementation
* @return {@link HystrixMetricsPublisherCollapser} instance
*/
public static HystrixMetricsPublisherCollapser createOrRetrievePublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
return SINGLETON.getPublisherForCollapser(collapserKey, metrics, properties);
}
// String is CollapserKey.name() (we can't use CollapserKey directly as we can't guarantee it implements hashcode/equals correctly)
private final ConcurrentHashMap<String, HystrixMetricsPublisherCollapser> collapserPublishers = new ConcurrentHashMap<String, HystrixMetricsPublisherCollapser>();
/* package */ HystrixMetricsPublisherCollapser getPublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
// attempt to retrieve from cache first
HystrixMetricsPublisherCollapser publisher = collapserPublishers.get(collapserKey.name());
if (publisher != null) {
return publisher;
}
// it doesn't exist so we need to create it
publisher = HystrixPlugins.getInstance().getMetricsPublisher().getMetricsPublisherForCollapser(collapserKey, metrics, properties);
// attempt to store it (race other threads)
HystrixMetricsPublisherCollapser existing = collapserPublishers.putIfAbsent(collapserKey.name(), publisher);
if (existing == null) {
// we won the thread-race to store the instance we created so initialize it
publisher.initialize();
// done registering, return instance that got cached
return publisher;
} else {
// we lost so return 'existing' and let the one we created be garbage collected
// without calling initialize() on it
return existing;
}
}
}
| 4,727 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariable.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Interface for a variable similar to {@link ThreadLocal} but scoped at the user request level.
* <p>
* Default implementation is {@link HystrixRequestVariableDefault} managed by {@link HystrixRequestContext}.
* <p>
* Custom implementations can be injected using {@link HystrixPlugins} and {@link HystrixConcurrencyStrategy#getRequestVariable}.
* <p>
* See JavaDoc of {@link HystrixRequestContext} for more information about functionality this enables and how to use the default implementation.
*
* @param <T>
* Type to be stored on the HystrixRequestVariable
*/
public interface HystrixRequestVariable<T> extends HystrixRequestVariableLifecycle<T> {
/**
* Retrieve current value or initialize and then return value for this variable for the current request scope.
*
* @return T value of variable for current request scope.
*/
public T get();
}
| 4,728 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixConcurrencyStrategyDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
/**
* Default implementation of {@link HystrixConcurrencyStrategy} using standard java.util.concurrent.* implementations.
*
* @ExcludeFromJavadoc
*/
public class HystrixConcurrencyStrategyDefault extends HystrixConcurrencyStrategy {
private static HystrixConcurrencyStrategyDefault INSTANCE = new HystrixConcurrencyStrategyDefault();
public static HystrixConcurrencyStrategy getInstance() {
return INSTANCE;
}
private HystrixConcurrencyStrategyDefault() {
}
}
| 4,729 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixContextRunnable.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.Callable;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Wrapper around {@link Runnable} that manages the {@link HystrixRequestContext} initialization and cleanup for the execution of the {@link Runnable}
*
* @ExcludeFromJavadoc
*/
public class HystrixContextRunnable implements Runnable {
private final Callable<Void> actual;
private final HystrixRequestContext parentThreadState;
public HystrixContextRunnable(Runnable actual) {
this(HystrixPlugins.getInstance().getConcurrencyStrategy(), actual);
}
public HystrixContextRunnable(HystrixConcurrencyStrategy concurrencyStrategy, final Runnable actual) {
this(concurrencyStrategy, HystrixRequestContext.getContextForCurrentThread(), actual);
}
public HystrixContextRunnable(final HystrixConcurrencyStrategy concurrencyStrategy, final HystrixRequestContext hystrixRequestContext, final Runnable actual) {
this.actual = concurrencyStrategy.wrapCallable(new Callable<Void>() {
@Override
public Void call() throws Exception {
actual.run();
return null;
}
});
this.parentThreadState = hystrixRequestContext;
}
@Override
public void run() {
HystrixRequestContext existingState = HystrixRequestContext.getContextForCurrentThread();
try {
// set the state of this thread to that of its parent
HystrixRequestContext.setContextOnCurrentThread(parentThreadState);
// execute actual Callable with the state of the parent
try {
actual.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
} finally {
// restore this thread back to its original state
HystrixRequestContext.setContextOnCurrentThread(existingState);
}
}
}
| 4,730 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariableDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of {@link HystrixRequestVariable}. Similar to {@link ThreadLocal} but scoped at the user request level. Context is managed via {@link HystrixRequestContext}.
* <p>
* All statements below assume that child threads are spawned and initialized with the use of {@link HystrixContextCallable} or {@link HystrixContextRunnable} which capture state from a parent thread
* and propagate to the child thread.
* <p>
* Characteristics that differ from ThreadLocal:
* <ul>
* <li>HystrixRequestVariable context must be initialized at the beginning of every request by {@link HystrixRequestContext#initializeContext}</li>
* <li>HystrixRequestVariables attached to a thread will be cleared at the end of every user request by {@link HystrixRequestContext#shutdown} which execute {@link #remove} for each
* HystrixRequestVariable</li>
* <li>HystrixRequestVariables have a {@link #shutdown} lifecycle method that gets called at the end of every user request (invoked when {@link HystrixRequestContext#shutdown} is called) to allow for
* resource cleanup.</li>
* <li>HystrixRequestVariables are copied (by reference) to child threads via the {@link HystrixRequestContext#getContextForCurrentThread} and {@link HystrixRequestContext#setContextOnCurrentThread}
* functionality.</li>
* <li>HystrixRequestVariables created on a child thread are available on sibling and parent threads.</li>
* <li>HystrixRequestVariables created on a child thread will be cleaned up by the parent thread via the {@link #shutdown} method.</li>
* </ul>
*
* <p>
* Note on thread-safety: By design a HystrixRequestVariables is intended to be accessed by all threads in a user request, thus anything stored in a HystrixRequestVariables must be thread-safe and
* plan on being accessed/mutated concurrently.
* <p>
* For example, a HashMap would likely not be a good choice for a RequestVariable value, but ConcurrentHashMap would.
*
* @param <T>
* Type to be stored on the HystrixRequestVariable
* <p>
* Example 1: {@code HystrixRequestVariable<ConcurrentHashMap<String, DataObject>>} <p>
* Example 2: {@code HystrixRequestVariable<PojoThatIsThreadSafe>}
*
* @ExcludeFromJavadoc
* @ThreadSafe
*/
public class HystrixRequestVariableDefault<T> implements HystrixRequestVariable<T> {
static final Logger logger = LoggerFactory.getLogger(HystrixRequestVariableDefault.class);
/**
* Creates a new HystrixRequestVariable that will exist across all threads
* within a {@link HystrixRequestContext}
*/
public HystrixRequestVariableDefault() {
}
/**
* Get the current value for this variable for the current request context.
*
* @return the value of the variable for the current request,
* or null if no value has been set and there is no initial value
*/
@SuppressWarnings("unchecked")
public T get() {
if (HystrixRequestContext.getContextForCurrentThread() == null) {
throw new IllegalStateException(HystrixRequestContext.class.getSimpleName() + ".initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.");
}
ConcurrentHashMap<HystrixRequestVariableDefault<?>, LazyInitializer<?>> variableMap = HystrixRequestContext.getContextForCurrentThread().state;
// short-circuit the synchronized path below if we already have the value in the ConcurrentHashMap
LazyInitializer<?> v = variableMap.get(this);
if (v != null) {
return (T) v.get();
}
/*
* Optimistically create a LazyInitializer to put into the ConcurrentHashMap.
*
* The LazyInitializer will not invoke initialValue() unless the get() method is invoked
* so we can optimistically instantiate LazyInitializer and then discard for garbage collection
* if the putIfAbsent fails.
*
* Whichever instance of LazyInitializer succeeds will then have get() invoked which will call
* the initialValue() method once-and-only-once.
*/
LazyInitializer<T> l = new LazyInitializer<T>(this);
LazyInitializer<?> existing = variableMap.putIfAbsent(this, l);
if (existing == null) {
/*
* We won the thread-race so can use 'l' that we just created.
*/
return l.get();
} else {
/*
* We lost the thread-race so let 'l' be garbage collected and instead return 'existing'
*/
return (T) existing.get();
}
}
/**
* Computes the initial value of the HystrixRequestVariable in a request.
* <p>
* This is called the first time the value of the HystrixRequestVariable is fetched in a request. Override this to provide an initial value for a HystrixRequestVariable on each request on which it
* is used.
*
* The default implementation returns null.
*
* @return initial value of the HystrixRequestVariable to use for the instance being constructed
*/
public T initialValue() {
return null;
}
/**
* Sets the value of the HystrixRequestVariable for the current request context.
* <p>
* Note, if a value already exists, the set will result in overwriting that value. It is up to the caller to ensure the existing value is cleaned up. The {@link #shutdown} method will not be
* called
*
* @param value
* the value to set
*/
public void set(T value) {
HystrixRequestContext.getContextForCurrentThread().state.put(this, new LazyInitializer<T>(this, value));
}
/**
* Removes the value of the HystrixRequestVariable from the current request.
* <p>
* This will invoke {@link #shutdown} if implemented.
* <p>
* If the value is subsequently fetched in the thread, the {@link #initialValue} method will be called again.
*/
public void remove() {
if (HystrixRequestContext.getContextForCurrentThread() != null) {
remove(HystrixRequestContext.getContextForCurrentThread(), this);
}
}
@SuppressWarnings("unchecked")
/* package */static <T> void remove(HystrixRequestContext context, HystrixRequestVariableDefault<T> v) {
// remove first so no other threads get it
LazyInitializer<?> o = context.state.remove(v);
if (o != null) {
// this thread removed it so let's execute shutdown
v.shutdown((T) o.get());
}
}
/**
* Provide life-cycle hook for a HystrixRequestVariable implementation to perform cleanup
* before the HystrixRequestVariable is removed from the current thread.
* <p>
* This is executed at the end of each user request when {@link HystrixRequestContext#shutdown} is called or whenever {@link #remove} is invoked.
* <p>
* By default does nothing.
* <p>
* NOTE: Do not call <code>get()</code> from within this method or <code>initialValue()</code> will be invoked again. The current value is passed in as an argument.
*
* @param value
* the value of the HystrixRequestVariable being removed
*/
public void shutdown(T value) {
// do nothing by default
}
/**
* Holder for a value that can be derived from the {@link HystrixRequestVariableDefault#initialValue} method that needs
* to be executed once-and-only-once.
* <p>
* This class can be instantiated and garbage collected without calling initialValue() as long as the get() method is not invoked and can thus be used with compareAndSet in
* ConcurrentHashMap.putIfAbsent and allow "losers" in a thread-race to be discarded.
*
* @param <T>
*/
/* package */static final class LazyInitializer<T> {
// @GuardedBy("synchronization on get() or construction")
private T value;
/*
* Boolean to ensure only-once initialValue() execution instead of using
* a null check in case initialValue() returns null
*/
// @GuardedBy("synchronization on get() or construction")
private boolean initialized = false;
private final HystrixRequestVariableDefault<T> rv;
private LazyInitializer(HystrixRequestVariableDefault<T> rv) {
this.rv = rv;
}
private LazyInitializer(HystrixRequestVariableDefault<T> rv, T value) {
this.rv = rv;
this.value = value;
this.initialized = true;
}
public synchronized T get() {
if (!initialized) {
value = rv.initialValue();
initialized = true;
}
return value;
}
}
}
| 4,731 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariableLifecycle.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
/**
* Interface for lifecycle methods that are then executed by an implementation of {@link HystrixRequestVariable}.
*
* @param <T>
*/
public interface HystrixRequestVariableLifecycle<T> {
/**
* Invoked when {@link HystrixRequestVariable#get()} is first called.
* <p>
* When using the default implementation this is invoked when {@link HystrixRequestVariableDefault#get()} is called.
*
* @return T with initial value or null if none.
*/
public T initialValue();
/**
* Invoked when request scope is shutdown to allow for cleanup.
* <p>
* When using the default implementation this is invoked when {@link HystrixRequestContext#shutdown()} is called.
* <p>
* The {@link HystrixRequestVariable#get()} method should not be called from within this method as it will result in {@link #initialValue()} being called again.
*
* @param value
* of request variable to allow cleanup activity.
* <p>
* If nothing needs to be cleaned up then nothing needs to be done in this method.
*/
public void shutdown(T value);
}
| 4,732 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixLifecycleForwardingRequestVariable.java | /**
* Copyright 2015 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 com.netflix.hystrix.strategy.concurrency;
/**
* Implementation of {@link HystrixRequestVariable} which forwards to the wrapped
* {@link HystrixRequestVariableLifecycle}.
* <p>
* This implementation also returns null when {@link #get()} is called while the {@link HystrixRequestContext} has not
* been initialized rather than throwing an exception, allowing for use in a {@link HystrixConcurrencyStrategy} which
* does not depend on an a HystrixRequestContext
*/
public class HystrixLifecycleForwardingRequestVariable<T> extends HystrixRequestVariableDefault<T> {
private final HystrixRequestVariableLifecycle<T> lifecycle;
/**
* Creates a HystrixRequestVariable which will return data as provided by the {@link HystrixRequestVariableLifecycle}
* @param lifecycle lifecycle used to provide values. Must have the same type parameter as the constructed instance.
*/
public HystrixLifecycleForwardingRequestVariable(HystrixRequestVariableLifecycle<T> lifecycle) {
this.lifecycle = lifecycle;
}
/**
* Delegates to the wrapped {@link HystrixRequestVariableLifecycle}
* @return T with initial value or null if none.
*/
@Override
public T initialValue() {
return lifecycle.initialValue();
}
/**
* Delegates to the wrapped {@link HystrixRequestVariableLifecycle}
* @param value
* of request variable to allow cleanup activity.
* <p>
* If nothing needs to be cleaned up then nothing needs to be done in this method.
*/
@Override
public void shutdown(T value) {
lifecycle.shutdown(value);
}
/**
* Return null if the {@link HystrixRequestContext} has not been initialized for the current thread.
* <p>
* If {@link HystrixRequestContext} has been initialized then call method in superclass:
* {@link HystrixRequestVariableDefault#get()}
*/
@Override
public T get() {
if (!HystrixRequestContext.isCurrentThreadInitialized()) {
return null;
}
return super.get();
}
}
| 4,733 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestVariableHolder.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Factory that encompasses functionality of {@link HystrixRequestVariable} for internal Hystrix code.
* <p>
* This is used as a layer between the actual {@link HystrixRequestVariable} and calling code to allow injected implementations of {@link HystrixConcurrencyStrategy}.
* <p>
* Typically a {@link HystrixRequestVariable} would be statically referenced (similar to a ThreadLocal) but to allow dynamic injection we instead statically reference this class which can then
* dynamically fetch the correct implementation and statically retain an instance across threads within a context (such as {@link HystrixRequestContext}.
*
* @param <T>
*
* @ExcludeFromJavadoc
*/
public class HystrixRequestVariableHolder<T> {
static final Logger logger = LoggerFactory.getLogger(HystrixRequestVariableHolder.class);
private static ConcurrentHashMap<RVCacheKey, HystrixRequestVariable<?>> requestVariableInstance = new ConcurrentHashMap<RVCacheKey, HystrixRequestVariable<?>>();
private final HystrixRequestVariableLifecycle<T> lifeCycleMethods;
public HystrixRequestVariableHolder(HystrixRequestVariableLifecycle<T> lifeCycleMethods) {
this.lifeCycleMethods = lifeCycleMethods;
}
@SuppressWarnings("unchecked")
public T get(HystrixConcurrencyStrategy concurrencyStrategy) {
/*
* 1) Fetch RequestVariable implementation from cache.
* 2) If no implementation is found in cache then construct from factory.
* 3) Cache implementation from factory as each object instance needs to be statically cached to be relevant across threads.
*/
RVCacheKey key = new RVCacheKey(this, concurrencyStrategy);
HystrixRequestVariable<?> rvInstance = requestVariableInstance.get(key);
if (rvInstance == null) {
requestVariableInstance.putIfAbsent(key, concurrencyStrategy.getRequestVariable(lifeCycleMethods));
/*
* A safety check to help debug problems if someone starts injecting dynamically created HystrixConcurrencyStrategy instances - which should not be done and has no good reason to be done.
*
* The 100 value is arbitrary ... just a number far higher than we should see.
*/
if (requestVariableInstance.size() > 100) {
logger.warn("Over 100 instances of HystrixRequestVariable are being stored. This is likely the sign of a memory leak caused by using unique instances of HystrixConcurrencyStrategy instead of a single instance.");
}
}
return (T) requestVariableInstance.get(key).get();
}
private static class RVCacheKey {
private final HystrixRequestVariableHolder<?> rvHolder;
private final HystrixConcurrencyStrategy concurrencyStrategy;
private RVCacheKey(HystrixRequestVariableHolder<?> rvHolder, HystrixConcurrencyStrategy concurrencyStrategy) {
this.rvHolder = rvHolder;
this.concurrencyStrategy = concurrencyStrategy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((concurrencyStrategy == null) ? 0 : concurrencyStrategy.hashCode());
result = prime * result + ((rvHolder == null) ? 0 : rvHolder.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RVCacheKey other = (RVCacheKey) obj;
if (concurrencyStrategy == null) {
if (other.concurrencyStrategy != null)
return false;
} else if (!concurrencyStrategy.equals(other.concurrencyStrategy))
return false;
if (rvHolder == null) {
if (other.rvHolder != null)
return false;
} else if (!rvHolder.equals(other.rvHolder))
return false;
return true;
}
}
}
| 4,734 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixContextCallable.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.Callable;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Wrapper around {@link Callable} that manages the {@link HystrixRequestContext} initialization and cleanup for the execution of the {@link Callable}
*
* @param <K>
* Return type of {@link Callable}
*
* @ExcludeFromJavadoc
*/
public class HystrixContextCallable<K> implements Callable<K> {
private final Callable<K> actual;
private final HystrixRequestContext parentThreadState;
public HystrixContextCallable(Callable<K> actual) {
this(HystrixPlugins.getInstance().getConcurrencyStrategy(), actual);
}
public HystrixContextCallable(HystrixConcurrencyStrategy concurrencyStrategy, Callable<K> actual) {
this.actual = concurrencyStrategy.wrapCallable(actual);
this.parentThreadState = HystrixRequestContext.getContextForCurrentThread();
}
@Override
public K call() throws Exception {
HystrixRequestContext existingState = HystrixRequestContext.getContextForCurrentThread();
try {
// set the state of this thread to that of its parent
HystrixRequestContext.setContextOnCurrentThread(parentThreadState);
// execute actual Callable with the state of the parent
return actual.call();
} finally {
// restore this thread back to its original state
HystrixRequestContext.setContextOnCurrentThread(existingState);
}
}
}
| 4,735 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixContextScheduler.java | /**
* Copyright 2013 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.*;
import rx.*;
import rx.functions.Action0;
import rx.functions.Func0;
import rx.internal.schedulers.ScheduledAction;
import rx.subscriptions.*;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Wrap a {@link Scheduler} so that scheduled actions are wrapped with {@link HystrixContextSchedulerAction} so that
* the {@link HystrixRequestContext} is properly copied across threads (if they are used by the {@link Scheduler}).
*/
public class HystrixContextScheduler extends Scheduler {
private final HystrixConcurrencyStrategy concurrencyStrategy;
private final Scheduler actualScheduler;
private final HystrixThreadPool threadPool;
public HystrixContextScheduler(Scheduler scheduler) {
this.actualScheduler = scheduler;
this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
this.threadPool = null;
}
public HystrixContextScheduler(HystrixConcurrencyStrategy concurrencyStrategy, Scheduler scheduler) {
this.actualScheduler = scheduler;
this.concurrencyStrategy = concurrencyStrategy;
this.threadPool = null;
}
public HystrixContextScheduler(HystrixConcurrencyStrategy concurrencyStrategy, HystrixThreadPool threadPool) {
this(concurrencyStrategy, threadPool, new Func0<Boolean>() {
@Override
public Boolean call() {
return true;
}
});
}
public HystrixContextScheduler(HystrixConcurrencyStrategy concurrencyStrategy, HystrixThreadPool threadPool, Func0<Boolean> shouldInterruptThread) {
this.concurrencyStrategy = concurrencyStrategy;
this.threadPool = threadPool;
this.actualScheduler = new ThreadPoolScheduler(threadPool, shouldInterruptThread);
}
@Override
public Worker createWorker() {
return new HystrixContextSchedulerWorker(actualScheduler.createWorker());
}
private class HystrixContextSchedulerWorker extends Worker {
private final Worker worker;
private HystrixContextSchedulerWorker(Worker actualWorker) {
this.worker = actualWorker;
}
@Override
public void unsubscribe() {
worker.unsubscribe();
}
@Override
public boolean isUnsubscribed() {
return worker.isUnsubscribed();
}
@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
if (threadPool != null) {
if (!threadPool.isQueueSpaceAvailable()) {
throw new RejectedExecutionException("Rejected command because thread-pool queueSize is at rejection threshold.");
}
}
return worker.schedule(new HystrixContextSchedulerAction(concurrencyStrategy, action), delayTime, unit);
}
@Override
public Subscription schedule(Action0 action) {
if (threadPool != null) {
if (!threadPool.isQueueSpaceAvailable()) {
throw new RejectedExecutionException("Rejected command because thread-pool queueSize is at rejection threshold.");
}
}
return worker.schedule(new HystrixContextSchedulerAction(concurrencyStrategy, action));
}
}
private static class ThreadPoolScheduler extends Scheduler {
private final HystrixThreadPool threadPool;
private final Func0<Boolean> shouldInterruptThread;
public ThreadPoolScheduler(HystrixThreadPool threadPool, Func0<Boolean> shouldInterruptThread) {
this.threadPool = threadPool;
this.shouldInterruptThread = shouldInterruptThread;
}
@Override
public Worker createWorker() {
return new ThreadPoolWorker(threadPool, shouldInterruptThread);
}
}
/**
* Purely for scheduling work on a thread-pool.
* <p>
* This is not natively supported by RxJava as of 0.18.0 because thread-pools
* are contrary to sequential execution.
* <p>
* For the Hystrix case, each Command invocation has a single action so the concurrency
* issue is not a problem.
*/
private static class ThreadPoolWorker extends Worker {
private final HystrixThreadPool threadPool;
private final CompositeSubscription subscription = new CompositeSubscription();
private final Func0<Boolean> shouldInterruptThread;
public ThreadPoolWorker(HystrixThreadPool threadPool, Func0<Boolean> shouldInterruptThread) {
this.threadPool = threadPool;
this.shouldInterruptThread = shouldInterruptThread;
}
@Override
public void unsubscribe() {
subscription.unsubscribe();
}
@Override
public boolean isUnsubscribed() {
return subscription.isUnsubscribed();
}
@Override
public Subscription schedule(final Action0 action) {
if (subscription.isUnsubscribed()) {
// don't schedule, we are unsubscribed
return Subscriptions.unsubscribed();
}
// This is internal RxJava API but it is too useful.
ScheduledAction sa = new ScheduledAction(action);
subscription.add(sa);
sa.addParent(subscription);
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor();
FutureTask<?> f = (FutureTask<?>) executor.submit(sa);
sa.add(new FutureCompleterWithConfigurableInterrupt(f, shouldInterruptThread, executor));
return sa;
}
@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
throw new IllegalStateException("Hystrix does not support delayed scheduling");
}
}
/**
* Very similar to rx.internal.schedulers.ScheduledAction.FutureCompleter, but with configurable interrupt behavior
*/
private static class FutureCompleterWithConfigurableInterrupt implements Subscription {
private final FutureTask<?> f;
private final Func0<Boolean> shouldInterruptThread;
private final ThreadPoolExecutor executor;
private FutureCompleterWithConfigurableInterrupt(FutureTask<?> f, Func0<Boolean> shouldInterruptThread, ThreadPoolExecutor executor) {
this.f = f;
this.shouldInterruptThread = shouldInterruptThread;
this.executor = executor;
}
@Override
public void unsubscribe() {
executor.remove(f);
if (shouldInterruptThread.call()) {
f.cancel(true);
} else {
f.cancel(false);
}
}
@Override
public boolean isUnsubscribed() {
return f.isCancelled();
}
}
}
| 4,736 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixConcurrencyStrategy.java | /**
* Copyright 2013 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 com.netflix.hystrix.strategy.concurrency;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import com.netflix.hystrix.util.PlatformSpecific;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Abstract class for defining different behavior or implementations for concurrency related aspects of the system with default implementations.
* <p>
* For example, every {@link Callable} executed by {@link HystrixCommand} will call {@link #wrapCallable(Callable)} to give a chance for custom implementations to decorate the {@link Callable} with
* additional behavior.
* <p>
* When you implement a concrete {@link HystrixConcurrencyStrategy}, you should make the strategy idempotent w.r.t ThreadLocals.
* Since the usage of threads by Hystrix is internal, Hystrix does not attempt to apply the strategy in an idempotent way.
* Instead, you should write your strategy to work idempotently. See https://github.com/Netflix/Hystrix/issues/351 for a more detailed discussion.
* <p>
* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
* href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
*/
public abstract class HystrixConcurrencyStrategy {
private final static Logger logger = LoggerFactory.getLogger(HystrixConcurrencyStrategy.class);
/**
* Factory method to provide {@link ThreadPoolExecutor} instances as desired.
* <p>
* Note that the corePoolSize, maximumPoolSize and keepAliveTime values will be dynamically set during runtime if their values change using the {@link ThreadPoolExecutor#setCorePoolSize},
* {@link ThreadPoolExecutor#setMaximumPoolSize} and {@link ThreadPoolExecutor#setKeepAliveTime} methods.
* <p>
* <b>Default Implementation</b>
* <p>
* Implementation using standard java.util.concurrent.ThreadPoolExecutor
*
* @param threadPoolKey
* {@link HystrixThreadPoolKey} representing the {@link HystrixThreadPool} that this {@link ThreadPoolExecutor} will be used for.
* @param corePoolSize
* Core number of threads requested via properties (or system default if no properties set).
* @param maximumPoolSize
* Max number of threads requested via properties (or system default if no properties set).
* @param keepAliveTime
* Keep-alive time for threads requested via properties (or system default if no properties set).
* @param unit
* {@link TimeUnit} corresponding with keepAliveTime
* @param workQueue
* {@code BlockingQueue<Runnable>} as provided by {@link #getBlockingQueue(int)}
* @return instance of {@link ThreadPoolExecutor}
*/
public ThreadPoolExecutor getThreadPool(final HystrixThreadPoolKey threadPoolKey, HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize, HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
final ThreadFactory threadFactory = getThreadFactory(threadPoolKey);
final int dynamicCoreSize = corePoolSize.get();
final int dynamicMaximumSize = maximumPoolSize.get();
if (dynamicCoreSize > dynamicMaximumSize) {
logger.error("Hystrix ThreadPool configuration at startup for : " + threadPoolKey.name() + " is trying to set coreSize = " +
dynamicCoreSize + " and maximumSize = " + dynamicMaximumSize + ". Maximum size will be set to " +
dynamicCoreSize + ", the coreSize value, since it must be equal to or greater than the coreSize value");
return new ThreadPoolExecutor(dynamicCoreSize, dynamicCoreSize, keepAliveTime.get(), unit, workQueue, threadFactory);
} else {
return new ThreadPoolExecutor(dynamicCoreSize, dynamicMaximumSize, keepAliveTime.get(), unit, workQueue, threadFactory);
}
}
public ThreadPoolExecutor getThreadPool(final HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) {
final ThreadFactory threadFactory = getThreadFactory(threadPoolKey);
final boolean allowMaximumSizeToDivergeFromCoreSize = threadPoolProperties.getAllowMaximumSizeToDivergeFromCoreSize().get();
final int dynamicCoreSize = threadPoolProperties.coreSize().get();
final int keepAliveTime = threadPoolProperties.keepAliveTimeMinutes().get();
final int maxQueueSize = threadPoolProperties.maxQueueSize().get();
final BlockingQueue<Runnable> workQueue = getBlockingQueue(maxQueueSize);
if (allowMaximumSizeToDivergeFromCoreSize) {
final int dynamicMaximumSize = threadPoolProperties.maximumSize().get();
if (dynamicCoreSize > dynamicMaximumSize) {
logger.error("Hystrix ThreadPool configuration at startup for : " + threadPoolKey.name() + " is trying to set coreSize = " +
dynamicCoreSize + " and maximumSize = " + dynamicMaximumSize + ". Maximum size will be set to " +
dynamicCoreSize + ", the coreSize value, since it must be equal to or greater than the coreSize value");
return new ThreadPoolExecutor(dynamicCoreSize, dynamicCoreSize, keepAliveTime, TimeUnit.MINUTES, workQueue, threadFactory);
} else {
return new ThreadPoolExecutor(dynamicCoreSize, dynamicMaximumSize, keepAliveTime, TimeUnit.MINUTES, workQueue, threadFactory);
}
} else {
return new ThreadPoolExecutor(dynamicCoreSize, dynamicCoreSize, keepAliveTime, TimeUnit.MINUTES, workQueue, threadFactory);
}
}
private static ThreadFactory getThreadFactory(final HystrixThreadPoolKey threadPoolKey) {
if (!PlatformSpecific.isAppEngineStandardEnvironment()) {
return new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "hystrix-" + threadPoolKey.name() + "-" + threadNumber.incrementAndGet());
thread.setDaemon(true);
return thread;
}
};
} else {
return PlatformSpecific.getAppEngineThreadFactory();
}
}
/**
* Factory method to provide instance of {@code BlockingQueue<Runnable>} used for each {@link ThreadPoolExecutor} as constructed in {@link #getThreadPool}.
* <p>
* Note: The maxQueueSize value is provided so any type of queue can be used but typically an implementation such as {@link SynchronousQueue} without a queue (just a handoff) is preferred as
* queueing is an anti-pattern to be purposefully avoided for latency tolerance reasons.
* <p>
* <b>Default Implementation</b>
* <p>
* Implementation returns {@link SynchronousQueue} when maxQueueSize <= 0 or {@link LinkedBlockingQueue} when maxQueueSize > 0.
*
* @param maxQueueSize
* The max size of the queue requested via properties (or system default if no properties set).
* @return instance of {@code BlockingQueue<Runnable>}
*/
public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
/*
* We are using SynchronousQueue if maxQueueSize <= 0 (meaning a queue is not wanted).
* <p>
* SynchronousQueue will do a handoff from calling thread to worker thread and not allow queuing which is what we want.
* <p>
* Queuing results in added latency and would only occur when the thread-pool is full at which point there are latency issues
* and rejecting is the preferred solution.
*/
if (maxQueueSize <= 0) {
return new SynchronousQueue<Runnable>();
} else {
return new LinkedBlockingQueue<Runnable>(maxQueueSize);
}
}
/**
* Provides an opportunity to wrap/decorate a {@code Callable<T>} before execution.
* <p>
* This can be used to inject additional behavior such as copying of thread state (such as {@link ThreadLocal}).
* <p>
* <b>Default Implementation</b>
* <p>
* Pass-thru that does no wrapping.
*
* @param callable
* {@code Callable<T>} to be executed via a {@link ThreadPoolExecutor}
* @return {@code Callable<T>} either as a pass-thru or wrapping the one given
*/
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return callable;
}
/**
* Factory method to return an implementation of {@link HystrixRequestVariable} that behaves like a {@link ThreadLocal} except that it
* is scoped to a request instead of a thread.
* <p>
* For example, if a request starts with an HTTP request and ends with the HTTP response, then {@link HystrixRequestVariable} should
* be initialized at the beginning, available on any and all threads spawned during the request and then cleaned up once the HTTP request is completed.
* <p>
* If this method is implemented it is generally necessary to also implemented {@link #wrapCallable(Callable)} in order to copy state
* from parent to child thread.
*
* @param rv
* {@link HystrixRequestVariableLifecycle} with lifecycle implementations from Hystrix
* @return {@code HystrixRequestVariable<T>}
*/
public <T> HystrixRequestVariable<T> getRequestVariable(final HystrixRequestVariableLifecycle<T> rv) {
return new HystrixLifecycleForwardingRequestVariable<T>(rv);
}
}
| 4,737 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixRequestContext.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.io.Closeable;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.HystrixRequestLog;
/**
* Contains the state and manages the lifecycle of {@link HystrixRequestVariableDefault} objects that provide request scoped (rather than only thread scoped) variables so that multiple threads within
* a
* single request can share state:
* <ul>
* <li>request scoped caching as in {@link HystrixRequestCache} for de-duping {@link HystrixCommand} executions</li>
* <li>request scoped log of all events as in {@link HystrixRequestLog}</li>
* <li>automated batching of {@link HystrixCommand} executions within the scope of a request as in {@link HystrixCollapser}</li>
* </ul>
* <p>
* If those features are not used then this does not need to be used. If those features are used then this must be initialized or a custom implementation of {@link HystrixRequestVariable} must be
* returned from {@link HystrixConcurrencyStrategy#getRequestVariable}.
* <p>
* If {@link HystrixRequestVariableDefault} is used (directly or indirectly by above-mentioned features) and this context has not been initialized then an {@link IllegalStateException} will be thrown
* with a
* message such as: <blockquote> HystrixRequestContext.initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used. </blockquote>
* <p>
* Example ServletFilter for initializing {@link HystrixRequestContext} at the beginning of an HTTP request and shutting down at the end:
*
* <blockquote>
*
* <pre>
* public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
* HystrixRequestContext context = HystrixRequestContext.initializeContext();
* try {
* chain.doFilter(request, response);
* } finally {
* context.shutdown();
* }
* }
* </pre>
*
* </blockquote>
* <p>
* You can find an implementation at <a target="_top" href="https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-request-servlet">hystrix-contrib/hystrix-request-servlet</a> on GitHub.
* <p>
* <b>NOTE:</b> If <code>initializeContext()</code> is called then <code>shutdown()</code> must also be called or a memory leak will occur.
*/
public class HystrixRequestContext implements Closeable {
/*
* ThreadLocal on each thread will hold the HystrixRequestVariableState.
*
* Shutdown will clear the state inside HystrixRequestContext but not nullify the ThreadLocal on all
* child threads as these threads will not be known by the parent when cleanupAfterRequest() is called.
*
* However, the only thing held by those child threads until they are re-used and re-initialized is an empty
* HystrixRequestContext object with the ConcurrentHashMap within it nulled out since once it is nullified
* from the parent thread it is shared across all child threads.
*/
private static ThreadLocal<HystrixRequestContext> requestVariables = new ThreadLocal<HystrixRequestContext>();
public static boolean isCurrentThreadInitialized() {
HystrixRequestContext context = requestVariables.get();
return context != null && context.state != null;
}
public static HystrixRequestContext getContextForCurrentThread() {
HystrixRequestContext context = requestVariables.get();
if (context != null && context.state != null) {
// context.state can be null when context is not null
// if a thread is being re-used and held a context previously, the context was shut down
// but the thread was not cleared
return context;
} else {
return null;
}
}
public static void setContextOnCurrentThread(HystrixRequestContext state) {
requestVariables.set(state);
}
/**
* Call this at the beginning of each request (from parent thread)
* to initialize the underlying context so that {@link HystrixRequestVariableDefault} can be used on any children threads and be accessible from
* the parent thread.
* <p>
* <b>NOTE: If this method is called then <code>shutdown()</code> must also be called or a memory leak will occur.</b>
* <p>
* See class header JavaDoc for example Servlet Filter implementation that initializes and shuts down the context.
*/
public static HystrixRequestContext initializeContext() {
HystrixRequestContext state = new HystrixRequestContext();
requestVariables.set(state);
return state;
}
/*
* This ConcurrentHashMap should not be made publicly accessible. It is the state of RequestVariables for a given RequestContext.
*
* Only HystrixRequestVariable has a reason to be accessing this field.
*/
/* package */ConcurrentHashMap<HystrixRequestVariableDefault<?>, HystrixRequestVariableDefault.LazyInitializer<?>> state = new ConcurrentHashMap<HystrixRequestVariableDefault<?>, HystrixRequestVariableDefault.LazyInitializer<?>>();
// instantiation should occur via static factory methods.
private HystrixRequestContext() {
}
/**
* Shutdown {@link HystrixRequestVariableDefault} objects in this context.
* <p>
* <b>NOTE: This must be called if <code>initializeContext()</code> was called or a memory leak will occur.</b>
*/
public void shutdown() {
if (state != null) {
for (HystrixRequestVariableDefault<?> v : state.keySet()) {
// for each RequestVariable we call 'remove' which performs the shutdown logic
try {
HystrixRequestVariableDefault.remove(this, v);
} catch (Throwable t) {
HystrixRequestVariableDefault.logger.error("Error in shutdown, will continue with shutdown of other variables", t);
}
}
// null out so it can be garbage collected even if the containing object is still
// being held in ThreadLocals on threads that weren't cleaned up
state = null;
}
}
/**
* Shutdown {@link HystrixRequestVariableDefault} objects in this context.
* <p>
* <b>NOTE: This must be called if <code>initializeContext()</code> was called or a memory leak will occur.</b>
*
* This method invokes <code>shutdown()</code>
*/
public void close() {
shutdown();
}
}
| 4,738 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/HystrixContextSchedulerAction.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.concurrency;
import java.util.concurrent.Callable;
import rx.functions.Action0;
import rx.functions.Func2;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Wrapper around {@link Func2} that manages the {@link HystrixRequestContext} initialization and cleanup for the execution of the {@link Func2}
*
* @param <T>
* Return type of {@link Func2}
*
* @ExcludeFromJavadoc
*/
public class HystrixContextSchedulerAction implements Action0 {
private final Action0 actual;
private final HystrixRequestContext parentThreadState;
private final Callable<Void> c;
public HystrixContextSchedulerAction(Action0 action) {
this(HystrixPlugins.getInstance().getConcurrencyStrategy(), action);
}
public HystrixContextSchedulerAction(final HystrixConcurrencyStrategy concurrencyStrategy, Action0 action) {
this.actual = action;
this.parentThreadState = HystrixRequestContext.getContextForCurrentThread();
this.c = concurrencyStrategy.wrapCallable(new Callable<Void>() {
@Override
public Void call() throws Exception {
HystrixRequestContext existingState = HystrixRequestContext.getContextForCurrentThread();
try {
// set the state of this thread to that of its parent
HystrixRequestContext.setContextOnCurrentThread(parentThreadState);
// execute actual Action0 with the state of the parent
actual.call();
return null;
} finally {
// restore this thread back to its original state
HystrixRequestContext.setContextOnCurrentThread(existingState);
}
}
});
}
@Override
public void call() {
try {
c.call();
} catch (Exception e) {
throw new RuntimeException("Failed executing wrapped Action0", e);
}
}
}
| 4,739 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/concurrency/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Strategy definition for concurrency related behavior and default implementation.
*
* @since 1.0.0
*/
package com.netflix.hystrix.strategy.concurrency; | 4,740 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesChainedProperty.java | /**
* Copyright 2016 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 com.netflix.hystrix.strategy.properties;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Chained property allowing a chain of defaults properties which is uses the properties plugin.
* <p>
* Instead of just a single dynamic property with a default this allows a sequence of properties that fallback to the farthest down the chain with a value.
*
* TODO This should be replaced by a version in the Archaius library once available.
*
* @ExcludeFromJavadoc
*/
public abstract class HystrixPropertiesChainedProperty {
private static final Logger logger = LoggerFactory.getLogger(HystrixPropertiesChainedProperty.class);
/**
* @ExcludeFromJavadoc
*/
private static abstract class ChainLink<T> {
private final AtomicReference<ChainLink<T>> pReference;
private final ChainLink<T> next;
private final List<Runnable> callbacks;
/**
* @return String
*/
public abstract String getName();
/**
* @return T
*/
protected abstract T getValue();
/**
* @return Boolean
*/
public abstract boolean isValueAcceptable();
/**
* No arg constructor - used for end node
*/
public ChainLink() {
next = null;
pReference = new AtomicReference<ChainLink<T>>(this);
callbacks = new ArrayList<Runnable>();
}
/**
* @param nextProperty next property in the chain
*/
public ChainLink(ChainLink<T> nextProperty) {
next = nextProperty;
pReference = new AtomicReference<ChainLink<T>>(next);
callbacks = new ArrayList<Runnable>();
}
protected void checkAndFlip() {
// in case this is the end node
if (next == null) {
pReference.set(this);
return;
}
if (this.isValueAcceptable()) {
logger.debug("Flipping property: {} to use its current value: {}", getName(), getValue());
pReference.set(this);
} else {
logger.debug("Flipping property: {} to use NEXT property: {}", getName(), next);
pReference.set(next);
}
for (Runnable r : callbacks) {
r.run();
}
}
/**
* @return T
*/
public T get() {
if (pReference.get() == this) {
return this.getValue();
} else {
return pReference.get().get();
}
}
/**
* @param r callback to execut
*/
public void addCallback(Runnable r) {
callbacks.add(r);
}
/**
* @return String
*/
public String toString() {
return getName() + " = " + get();
}
}
public static abstract class ChainBuilder<T> {
private ChainBuilder() {
super();
}
private List<HystrixDynamicProperty<T>> properties =
new ArrayList<HystrixDynamicProperty<T>>();
public ChainBuilder<T> add(HystrixDynamicProperty<T> property) {
properties.add(property);
return this;
}
public ChainBuilder<T> add(String name, T defaultValue) {
properties.add(getDynamicProperty(name, defaultValue, getType()));
return this;
}
public HystrixDynamicProperty<T> build() {
if (properties.size() < 1) throw new IllegalArgumentException();
if (properties.size() == 1) return properties.get(0);
List<HystrixDynamicProperty<T>> reversed =
new ArrayList<HystrixDynamicProperty<T>>(properties);
Collections.reverse(reversed);
ChainProperty<T> current = null;
for (HystrixDynamicProperty<T> p : reversed) {
if (current == null) {
current = new ChainProperty<T>(p);
}
else {
current = new ChainProperty<T>(p, current);
}
}
return new ChainHystrixProperty<T>(current);
}
protected abstract Class<T> getType();
}
private static <T> ChainBuilder<T> forType(final Class<T> type) {
return new ChainBuilder<T>() {
@Override
protected Class<T> getType() {
return type;
}
};
}
public static ChainBuilder<String> forString() {
return forType(String.class);
}
public static ChainBuilder<Integer> forInteger() {
return forType(Integer.class);
}
public static ChainBuilder<Boolean> forBoolean() {
return forType(Boolean.class);
}
public static ChainBuilder<Long> forLong() {
return forType(Long.class);
}
private static class ChainHystrixProperty<T> implements HystrixDynamicProperty<T> {
private final ChainProperty<T> property;
public ChainHystrixProperty(ChainProperty<T> property) {
super();
this.property = property;
}
@Override
public String getName() {
return property.getName();
}
@Override
public T get() {
return property.get();
}
@Override
public void addCallback(Runnable callback) {
property.addCallback(callback);
}
}
private static class ChainProperty<T> extends ChainLink<T> {
private final HystrixDynamicProperty<T> sProp;
public ChainProperty(HystrixDynamicProperty<T> sProperty) {
super();
sProp = sProperty;
}
public ChainProperty(HystrixDynamicProperty<T> sProperty, ChainProperty<T> next) {
super(next); // setup next pointer
sProp = sProperty;
sProp.addCallback(new Runnable() {
@Override
public void run() {
logger.debug("Property changed: '{} = {}'", getName(), getValue());
checkAndFlip();
}
});
checkAndFlip();
}
@Override
public boolean isValueAcceptable() {
return (sProp.get() != null);
}
@Override
protected T getValue() {
return sProp.get();
}
@Override
public String getName() {
return sProp.getName();
}
}
private static <T> HystrixDynamicProperty<T>
getDynamicProperty(String propName, T defaultValue, Class<T> type) {
HystrixDynamicProperties properties = HystrixPlugins.getInstance().getDynamicProperties();
HystrixDynamicProperty<T> p =
HystrixDynamicProperties.Util.getProperty(properties, propName, defaultValue, type);
return p;
}
}
| 4,741 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesCommandDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
/**
* Default implementation of {@link HystrixCommandProperties} using Archaius (https://github.com/Netflix/archaius)
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesCommandDefault extends HystrixCommandProperties {
public HystrixPropertiesCommandDefault(HystrixCommandKey key, Setter builder) {
super(key, builder);
}
}
| 4,742 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesFactory.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Factory for retrieving properties implementations.
* <p>
* This uses given {@link HystrixPropertiesStrategy} implementations to construct Properties instances and caches each instance according to the cache key provided.
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesFactory {
/**
* Clears all the defaults in the static property cache. This makes it possible for property defaults to not persist for
* an entire JVM lifetime. May be invoked directly, and also gets invoked by <code>Hystrix.reset()</code>
*/
public static void reset() {
commandProperties.clear();
threadPoolProperties.clear();
collapserProperties.clear();
}
// String is CommandKey.name() (we can't use CommandKey directly as we can't guarantee it implements hashcode/equals correctly)
private static final ConcurrentHashMap<String, HystrixCommandProperties> commandProperties = new ConcurrentHashMap<String, HystrixCommandProperties>();
/**
* Get an instance of {@link HystrixCommandProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixCommand} instance.
*
* @param key
* Pass-thru to {@link HystrixPropertiesStrategy#getCommandProperties} implementation.
* @param builder
* Pass-thru to {@link HystrixPropertiesStrategy#getCommandProperties} implementation.
* @return {@link HystrixCommandProperties} instance
*/
public static HystrixCommandProperties getCommandProperties(HystrixCommandKey key, HystrixCommandProperties.Setter builder) {
HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
String cacheKey = hystrixPropertiesStrategy.getCommandPropertiesCacheKey(key, builder);
if (cacheKey != null) {
HystrixCommandProperties properties = commandProperties.get(cacheKey);
if (properties != null) {
return properties;
} else {
if (builder == null) {
builder = HystrixCommandProperties.Setter();
}
// create new instance
properties = hystrixPropertiesStrategy.getCommandProperties(key, builder);
// cache and return
HystrixCommandProperties existing = commandProperties.putIfAbsent(cacheKey, properties);
if (existing == null) {
return properties;
} else {
return existing;
}
}
} else {
// no cacheKey so we generate it with caching
return hystrixPropertiesStrategy.getCommandProperties(key, builder);
}
}
// String is ThreadPoolKey.name() (we can't use ThreadPoolKey directly as we can't guarantee it implements hashcode/equals correctly)
private static final ConcurrentHashMap<String, HystrixThreadPoolProperties> threadPoolProperties = new ConcurrentHashMap<String, HystrixThreadPoolProperties>();
/**
* Get an instance of {@link HystrixThreadPoolProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixThreadPool} instance.
*
* @param key
* Pass-thru to {@link HystrixPropertiesStrategy#getThreadPoolProperties} implementation.
* @param builder
* Pass-thru to {@link HystrixPropertiesStrategy#getThreadPoolProperties} implementation.
* @return {@link HystrixThreadPoolProperties} instance
*/
public static HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey key, HystrixThreadPoolProperties.Setter builder) {
HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
String cacheKey = hystrixPropertiesStrategy.getThreadPoolPropertiesCacheKey(key, builder);
if (cacheKey != null) {
HystrixThreadPoolProperties properties = threadPoolProperties.get(cacheKey);
if (properties != null) {
return properties;
} else {
if (builder == null) {
builder = HystrixThreadPoolProperties.Setter();
}
// create new instance
properties = hystrixPropertiesStrategy.getThreadPoolProperties(key, builder);
// cache and return
HystrixThreadPoolProperties existing = threadPoolProperties.putIfAbsent(cacheKey, properties);
if (existing == null) {
return properties;
} else {
return existing;
}
}
} else {
// no cacheKey so we generate it with caching
return hystrixPropertiesStrategy.getThreadPoolProperties(key, builder);
}
}
// String is CollapserKey.name() (we can't use CollapserKey directly as we can't guarantee it implements hashcode/equals correctly)
private static final ConcurrentHashMap<String, HystrixCollapserProperties> collapserProperties = new ConcurrentHashMap<String, HystrixCollapserProperties>();
/**
* Get an instance of {@link HystrixCollapserProperties} with the given factory {@link HystrixPropertiesStrategy} implementation for each {@link HystrixCollapserKey} instance.
*
* @param key
* Pass-thru to {@link HystrixPropertiesStrategy#getCollapserProperties} implementation.
* @param builder
* Pass-thru to {@link HystrixPropertiesStrategy#getCollapserProperties} implementation.
* @return {@link HystrixCollapserProperties} instance
*/
public static HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey key, HystrixCollapserProperties.Setter builder) {
HystrixPropertiesStrategy hystrixPropertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
String cacheKey = hystrixPropertiesStrategy.getCollapserPropertiesCacheKey(key, builder);
if (cacheKey != null) {
HystrixCollapserProperties properties = collapserProperties.get(cacheKey);
if (properties != null) {
return properties;
} else {
if (builder == null) {
builder = HystrixCollapserProperties.Setter();
}
// create new instance
properties = hystrixPropertiesStrategy.getCollapserProperties(key, builder);
// cache and return
HystrixCollapserProperties existing = collapserProperties.putIfAbsent(cacheKey, properties);
if (existing == null) {
return properties;
} else {
return existing;
}
}
} else {
// no cacheKey so we generate it with caching
return hystrixPropertiesStrategy.getCollapserProperties(key, builder);
}
}
}
| 4,743 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesThreadPoolDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
/**
* Default implementation of {@link HystrixThreadPoolProperties} using Archaius (https://github.com/Netflix/archaius)
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesThreadPoolDefault extends HystrixThreadPoolProperties {
protected HystrixPropertiesThreadPoolDefault(HystrixThreadPoolKey key, Setter builder) {
super(key, builder);
}
}
| 4,744 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesStrategy.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.HystrixTimerThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Abstract class with default implementations of factory methods for properties used by various components of Hystrix.
* <p>
* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
* href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
*/
public abstract class HystrixPropertiesStrategy {
/**
* Construct an implementation of {@link HystrixCommandProperties} for {@link HystrixCommand} instances with {@link HystrixCommandKey}.
* <p>
* <b>Default Implementation</b>
* <p>
* Constructs instance of {@link HystrixPropertiesCommandDefault}.
*
* @param commandKey
* {@link HystrixCommandKey} representing the name or type of {@link HystrixCommand}
* @param builder
* {@link com.netflix.hystrix.HystrixCommandProperties.Setter} with default overrides as injected from the {@link HystrixCommand} implementation.
* <p>
* The builder will return NULL for each value if no override was provided.
* @return Implementation of {@link HystrixCommandProperties}
*/
public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) {
return new HystrixPropertiesCommandDefault(commandKey, builder);
}
/**
* Cache key used for caching the retrieval of {@link HystrixCommandProperties} implementations.
* <p>
* Typically this would return <code>HystrixCommandKey.name()</code> but can be done differently if required.
* <p>
* For example, null can be returned which would cause it to not cache and invoke {@link #getCommandProperties} for each {@link HystrixCommand} instantiation (not recommended).
* <p>
* <b>Default Implementation</b>
* <p>
* Returns {@link HystrixCommandKey#name()}
*
* @param commandKey command key used in determining command's cache key
* @param builder builder for {@link HystrixCommandProperties} used in determining command's cache key
* @return String value to be used as the cache key of a {@link HystrixCommandProperties} implementation.
*/
public String getCommandPropertiesCacheKey(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) {
return commandKey.name();
}
/**
* Construct an implementation of {@link HystrixThreadPoolProperties} for {@link HystrixThreadPool} instances with {@link HystrixThreadPoolKey}.
* <p>
* <b>Default Implementation</b>
* <p>
* Constructs instance of {@link HystrixPropertiesThreadPoolDefault}.
*
* @param threadPoolKey
* {@link HystrixThreadPoolKey} representing the name or type of {@link HystrixThreadPool}
* @param builder
* {@link com.netflix.hystrix.HystrixThreadPoolProperties.Setter} with default overrides as injected via {@link HystrixCommand} to the {@link HystrixThreadPool} implementation.
* <p>
* The builder will return NULL for each value if no override was provided.
*
* @return Implementation of {@link HystrixThreadPoolProperties}
*/
public HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter builder) {
return new HystrixPropertiesThreadPoolDefault(threadPoolKey, builder);
}
/**
* Cache key used for caching the retrieval of {@link HystrixThreadPoolProperties} implementations.
* <p>
* Typically this would return <code>HystrixThreadPoolKey.name()</code> but can be done differently if required.
* <p>
* For example, null can be returned which would cause it to not cache and invoke {@link #getThreadPoolProperties} for each {@link HystrixThreadPool} instantiation (not recommended).
* <p>
* <b>Default Implementation</b>
* <p>
* Returns {@link HystrixThreadPoolKey#name()}
*
* @param threadPoolKey thread pool key used in determining thread pool's cache key
* @param builder builder for {@link HystrixThreadPoolProperties} used in determining thread pool's cache key
* @return String value to be used as the cache key of a {@link HystrixThreadPoolProperties} implementation.
*/
public String getThreadPoolPropertiesCacheKey(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter builder) {
return threadPoolKey.name();
}
/**
* Construct an implementation of {@link HystrixCollapserProperties} for {@link HystrixCollapser} instances with {@link HystrixCollapserKey}.
* <p>
* <b>Default Implementation</b>
* <p>
* Constructs instance of {@link HystrixPropertiesCollapserDefault}.
*
* @param collapserKey
* {@link HystrixCollapserKey} representing the name or type of {@link HystrixCollapser}
* @param builder
* {@link com.netflix.hystrix.HystrixCollapserProperties.Setter} with default overrides as injected to the {@link HystrixCollapser} implementation.
* <p>
* The builder will return NULL for each value if no override was provided.
*
* @return Implementation of {@link HystrixCollapserProperties}
*/
public HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey collapserKey, HystrixCollapserProperties.Setter builder) {
return new HystrixPropertiesCollapserDefault(collapserKey, builder);
}
/**
* Cache key used for caching the retrieval of {@link HystrixCollapserProperties} implementations.
* <p>
* Typically this would return <code>HystrixCollapserKey.name()</code> but can be done differently if required.
* <p>
* For example, null can be returned which would cause it to not cache and invoke {@link #getCollapserProperties} for each {@link HystrixCollapser} instantiation (not recommended).
* <p>
* <b>Default Implementation</b>
* <p>
* Returns {@link HystrixCollapserKey#name()}
*
* @param collapserKey collapser key used in determining collapser's cache key
* @param builder builder for {@link HystrixCollapserProperties} used in determining collapser's cache key
* @return String value to be used as the cache key of a {@link HystrixCollapserProperties} implementation.
*/
public String getCollapserPropertiesCacheKey(HystrixCollapserKey collapserKey, HystrixCollapserProperties.Setter builder) {
return collapserKey.name();
}
/**
* Construct an implementation of {@link com.netflix.hystrix.HystrixTimerThreadPoolProperties} for configuration of the timer thread pool
* that handles timeouts and collapser logic.
* <p>
* Constructs instance of {@link HystrixPropertiesTimerThreadPoolDefault}.
*
*
* @return Implementation of {@link com.netflix.hystrix.HystrixTimerThreadPoolProperties}
*/
public HystrixTimerThreadPoolProperties getTimerThreadPoolProperties() {
return new HystrixPropertiesTimerThreadPoolDefault();
}
}
| 4,745 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixDynamicProperty.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.strategy.properties;
/**
* Generic interface to represent a <b>dynamic</b> property value so Hystrix can consume
* properties without being tied to any particular backing implementation.
*
* @author agentgt
*
* @param <T>
* Type of property value.
* @see HystrixProperty
* @see HystrixDynamicProperties
*/
public interface HystrixDynamicProperty<T> extends HystrixProperty<T>{
public String getName();
/**
* Register a callback to be run if the property is updated.
* Backing implementations may choose to do nothing.
* @param callback callback.
*/
public void addCallback(Runnable callback);
} | 4,746 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesChainedArchaiusProperty.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.config.PropertyWrapper;
/**
* Chained property allowing a chain of defaults using Archaius (https://github.com/Netflix/archaius) properties which is used by the default properties implementations.
* <p>
* Instead of just a single dynamic property with a default this allows a sequence of properties that fallback to the farthest down the chain with a value.
*
* TODO This should be replaced by a version in the Archaius library once available.
*
* @ExcludeFromJavadoc
*/
public abstract class HystrixPropertiesChainedArchaiusProperty {
private static final Logger logger = LoggerFactory.getLogger(HystrixPropertiesChainedArchaiusProperty.class);
/**
* @ExcludeFromJavadoc
*/
public static abstract class ChainLink<T> {
private final AtomicReference<ChainLink<T>> pReference;
private final ChainLink<T> next;
private final List<Runnable> callbacks;
/**
* @return String
*/
public abstract String getName();
/**
* @return T
*/
protected abstract T getValue();
/**
* @return Boolean
*/
public abstract boolean isValueAcceptable();
/**
* No arg constructor - used for end node
*/
public ChainLink() {
next = null;
pReference = new AtomicReference<ChainLink<T>>(this);
callbacks = new ArrayList<Runnable>();
}
/**
* @param nextProperty next property in the chain
*/
public ChainLink(ChainLink<T> nextProperty) {
next = nextProperty;
pReference = new AtomicReference<ChainLink<T>>(next);
callbacks = new ArrayList<Runnable>();
}
protected void checkAndFlip() {
// in case this is the end node
if (next == null) {
pReference.set(this);
return;
}
if (this.isValueAcceptable()) {
logger.debug("Flipping property: {} to use its current value: {}", getName(), getValue());
pReference.set(this);
} else {
logger.debug("Flipping property: {} to use NEXT property: {}", getName(), next);
pReference.set(next);
}
for (Runnable r : callbacks) {
r.run();
}
}
/**
* @return T
*/
public T get() {
if (pReference.get() == this) {
return this.getValue();
} else {
return pReference.get().get();
}
}
/**
* @param r callback to execut
*/
public void addCallback(Runnable r) {
callbacks.add(r);
}
/**
* @return String
*/
public String toString() {
return getName() + " = " + get();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class StringProperty extends ChainLink<String> {
private final DynamicStringProperty sProp;
public StringProperty(DynamicStringProperty sProperty) {
super();
sProp = sProperty;
}
public StringProperty(String name, DynamicStringProperty sProperty) {
this(name, new StringProperty(sProperty));
}
public StringProperty(String name, StringProperty next) {
this(new DynamicStringProperty(name, null), next);
}
public StringProperty(DynamicStringProperty sProperty, DynamicStringProperty next) {
this(sProperty, new StringProperty(next));
}
public StringProperty(DynamicStringProperty sProperty, StringProperty next) {
super(next); // setup next pointer
sProp = sProperty;
sProp.addCallback(new Runnable() {
@Override
public void run() {
logger.debug("Property changed: '{} = {}'", getName(), getValue());
checkAndFlip();
}
});
checkAndFlip();
}
@Override
public boolean isValueAcceptable() {
return (sProp.get() != null);
}
@Override
protected String getValue() {
return sProp.get();
}
@Override
public String getName() {
return sProp.getName();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class IntegerProperty extends ChainLink<Integer> {
private final DynamicIntegerProperty sProp;
public IntegerProperty(DynamicIntegerProperty sProperty) {
super();
sProp = sProperty;
}
public IntegerProperty(String name, DynamicIntegerProperty sProperty) {
this(name, new IntegerProperty(sProperty));
}
public IntegerProperty(String name, IntegerProperty next) {
this(new DynamicIntegerProperty(name, null), next);
}
public IntegerProperty(DynamicIntegerProperty sProperty, DynamicIntegerProperty next) {
this(sProperty, new IntegerProperty(next));
}
public IntegerProperty(DynamicIntegerProperty sProperty, IntegerProperty next) {
super(next); // setup next pointer
sProp = sProperty;
sProp.addCallback(new Runnable() {
@Override
public void run() {
logger.debug("Property changed: '{} = {}'", getName(), getValue());
checkAndFlip();
}
});
checkAndFlip();
}
@Override
public boolean isValueAcceptable() {
return (sProp.get() != null);
}
@Override
public Integer getValue() {
return sProp.get();
}
@Override
public String getName() {
return sProp.getName();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class BooleanProperty extends ChainLink<Boolean> {
private final DynamicBooleanProperty sProp;
public BooleanProperty(DynamicBooleanProperty sProperty) {
super();
sProp = sProperty;
}
public BooleanProperty(String name, DynamicBooleanProperty sProperty) {
this(name, new BooleanProperty(sProperty));
}
public BooleanProperty(String name, BooleanProperty next) {
this(new DynamicBooleanProperty(name, null), next);
}
public BooleanProperty(DynamicBooleanProperty sProperty, DynamicBooleanProperty next) {
this(sProperty, new BooleanProperty(next));
}
public BooleanProperty(DynamicBooleanProperty sProperty, BooleanProperty next) {
super(next); // setup next pointer
sProp = sProperty;
sProp.addCallback(new Runnable() {
@Override
public void run() {
logger.debug("Property changed: '{} = {}'", getName(), getValue());
checkAndFlip();
}
});
checkAndFlip();
}
@Override
public boolean isValueAcceptable() {
return (sProp.getValue() != null);
}
@Override
public Boolean getValue() {
return sProp.get();
}
@Override
public String getName() {
return sProp.getName();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class DynamicBooleanProperty extends PropertyWrapper<Boolean> {
public DynamicBooleanProperty(String propName, Boolean defaultValue) {
super(propName, defaultValue);
}
/**
* Get the current value from the underlying DynamicProperty
*/
public Boolean get() {
return prop.getBoolean(defaultValue);
}
@Override
public Boolean getValue() {
return get();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class DynamicIntegerProperty extends PropertyWrapper<Integer> {
public DynamicIntegerProperty(String propName, Integer defaultValue) {
super(propName, defaultValue);
}
/**
* Get the current value from the underlying DynamicProperty
*/
public Integer get() {
return prop.getInteger(defaultValue);
}
@Override
public Integer getValue() {
return get();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class DynamicLongProperty extends PropertyWrapper<Long> {
public DynamicLongProperty(String propName, Long defaultValue) {
super(propName, defaultValue);
}
/**
* Get the current value from the underlying DynamicProperty
*/
public Long get() {
return prop.getLong(defaultValue);
}
@Override
public Long getValue() {
return get();
}
}
/**
* @ExcludeFromJavadoc
*/
public static class DynamicStringProperty extends PropertyWrapper<String> {
public DynamicStringProperty(String propName, String defaultValue) {
super(propName, defaultValue);
}
/**
* Get the current value from the underlying DynamicProperty
*/
public String get() {
return prop.getString(defaultValue);
}
@Override
public String getValue() {
return get();
}
}
}
| 4,747 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesCollapserDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
/**
* Default implementation of {@link HystrixCollapserProperties} using Archaius (https://github.com/Netflix/archaius)
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesCollapserDefault extends HystrixCollapserProperties {
public HystrixPropertiesCollapserDefault(HystrixCollapserKey collapserKey, Setter builder) {
super(collapserKey, builder);
}
}
| 4,748 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesStrategyDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
/**
* Default implementation of {@link HystrixPropertiesStrategy}.
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesStrategyDefault extends HystrixPropertiesStrategy {
private final static HystrixPropertiesStrategyDefault INSTANCE = new HystrixPropertiesStrategyDefault();
private HystrixPropertiesStrategyDefault() {
}
public static HystrixPropertiesStrategy getInstance() {
return INSTANCE;
}
}
| 4,749 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesTimerThreadPoolDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.HystrixTimerThreadPoolProperties;
/**
* Default implementation of {@link HystrixTimerThreadPoolProperties} using Archaius (https://github.com/Netflix/archaius)
*
* @ExcludeFromJavadoc
*/
public class HystrixPropertiesTimerThreadPoolDefault extends HystrixTimerThreadPoolProperties {
}
| 4,750 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixDynamicPropertiesSystemProperties.java | package com.netflix.hystrix.strategy.properties;
/**
* @ExcludeFromJavadoc
* @author agent
*/
public final class HystrixDynamicPropertiesSystemProperties implements HystrixDynamicProperties {
/**
* Only public for unit test purposes.
*/
public HystrixDynamicPropertiesSystemProperties() {}
private static class LazyHolder {
private static final HystrixDynamicPropertiesSystemProperties INSTANCE = new HystrixDynamicPropertiesSystemProperties();
}
public static HystrixDynamicProperties getInstance() {
return LazyHolder.INSTANCE;
}
//TODO probably should not be anonymous classes for GC reasons and possible jit method eliding.
@Override
public HystrixDynamicProperty<Integer> getInteger(final String name, final Integer fallback) {
return new HystrixDynamicProperty<Integer>() {
@Override
public String getName() {
return name;
}
@Override
public Integer get() {
return Integer.getInteger(name, fallback);
}
@Override
public void addCallback(Runnable callback) {
}
};
}
@Override
public HystrixDynamicProperty<String> getString(final String name, final String fallback) {
return new HystrixDynamicProperty<String>() {
@Override
public String getName() {
return name;
}
@Override
public String get() {
return System.getProperty(name, fallback);
}
@Override
public void addCallback(Runnable callback) {
}
};
}
@Override
public HystrixDynamicProperty<Long> getLong(final String name, final Long fallback) {
return new HystrixDynamicProperty<Long>() {
@Override
public String getName() {
return name;
}
@Override
public Long get() {
return Long.getLong(name, fallback);
}
@Override
public void addCallback(Runnable callback) {
}
};
}
@Override
public HystrixDynamicProperty<Boolean> getBoolean(final String name, final Boolean fallback) {
return new HystrixDynamicProperty<Boolean>() {
@Override
public String getName() {
return name;
}
@Override
public Boolean get() {
if (System.getProperty(name) == null) {
return fallback;
}
return Boolean.getBoolean(name);
}
@Override
public void addCallback(Runnable callback) {
}
};
}
} | 4,751 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Strategy definition for properties and configuration and default implementation.
*
* @since 1.0.0
*/
package com.netflix.hystrix.strategy.properties; | 4,752 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixDynamicProperties.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.strategy.properties;
import java.util.ServiceLoader;
/**
* A hystrix plugin (SPI) for resolving dynamic configuration properties. This
* SPI allows for varying configuration sources.
*
* The HystrixPlugin singleton will load only one implementation of this SPI
* throught the {@link ServiceLoader} mechanism.
*
* @author agentgt
*
*/
public interface HystrixDynamicProperties {
/**
* Requests a property that may or may not actually exist.
* @param name property name, never <code>null</code>
* @param fallback default value, maybe <code>null</code>
* @return never <code>null</code>
*/
public HystrixDynamicProperty<String> getString(String name, String fallback);
/**
* Requests a property that may or may not actually exist.
* @param name property name, never <code>null</code>
* @param fallback default value, maybe <code>null</code>
* @return never <code>null</code>
*/
public HystrixDynamicProperty<Integer> getInteger(String name, Integer fallback);
/**
* Requests a property that may or may not actually exist.
* @param name property name, never <code>null</code>
* @param fallback default value, maybe <code>null</code>
* @return never <code>null</code>
*/
public HystrixDynamicProperty<Long> getLong(String name, Long fallback);
/**
* Requests a property that may or may not actually exist.
* @param name property name
* @param fallback default value
* @return never <code>null</code>
*/
public HystrixDynamicProperty<Boolean> getBoolean(String name, Boolean fallback);
/**
* @ExcludeFromJavadoc
*/
public static class Util {
/**
* A convenience method to get a property by type (Class).
* @param properties never <code>null</code>
* @param name never <code>null</code>
* @param fallback maybe <code>null</code>
* @param type never <code>null</code>
* @return a dynamic property with type T.
*/
@SuppressWarnings("unchecked")
public static <T> HystrixDynamicProperty<T> getProperty(
HystrixDynamicProperties properties, String name, T fallback, Class<T> type) {
return (HystrixDynamicProperty<T>) doProperty(properties, name, fallback, type);
}
private static HystrixDynamicProperty<?> doProperty(
HystrixDynamicProperties delegate,
String name, Object fallback, Class<?> type) {
if(type == String.class) {
return delegate.getString(name, (String) fallback);
}
else if (type == Integer.class) {
return delegate.getInteger(name, (Integer) fallback);
}
else if (type == Long.class) {
return delegate.getLong(name, (Long) fallback);
}
else if (type == Boolean.class) {
return delegate.getBoolean(name, (Boolean) fallback);
}
throw new IllegalStateException();
}
}
} | 4,753 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixProperty.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.properties;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicBooleanProperty;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicIntegerProperty;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicLongProperty;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicStringProperty;
/**
* Generic interface to represent a property value so Hystrix can consume properties without being tied to any particular backing implementation.
*
* @param <T>
* Type of property value
*/
public interface HystrixProperty<T> {
public T get();
/**
* Helper methods for wrapping static values and dynamic Archaius (https://github.com/Netflix/archaius) properties in the {@link HystrixProperty} interface.
*/
public static class Factory {
public static <T> HystrixProperty<T> asProperty(final T value) {
return new HystrixProperty<T>() {
@Override
public T get() {
return value;
}
};
}
/**
* @ExcludeFromJavadoc
*/
public static HystrixProperty<Integer> asProperty(final DynamicIntegerProperty value) {
return new HystrixProperty<Integer>() {
@Override
public Integer get() {
return value.get();
}
};
}
/**
* @ExcludeFromJavadoc
*/
public static HystrixProperty<Long> asProperty(final DynamicLongProperty value) {
return new HystrixProperty<Long>() {
@Override
public Long get() {
return value.get();
}
};
}
/**
* @ExcludeFromJavadoc
*/
public static HystrixProperty<String> asProperty(final DynamicStringProperty value) {
return new HystrixProperty<String>() {
@Override
public String get() {
return value.get();
}
};
}
/**
* @ExcludeFromJavadoc
*/
public static HystrixProperty<Boolean> asProperty(final DynamicBooleanProperty value) {
return new HystrixProperty<Boolean>() {
@Override
public Boolean get() {
return value.get();
}
};
}
/**
* When retrieved this will return the value from the given {@link HystrixProperty} or if that returns null then return the <code>defaultValue</code>.
*
* @param value
* {@link HystrixProperty} of property value that can return null (meaning no value)
* @param defaultValue
* value to be returned if value returns null
* @return value or defaultValue if value returns null
*/
public static <T> HystrixProperty<T> asProperty(final HystrixProperty<T> value, final T defaultValue) {
return new HystrixProperty<T>() {
@Override
public T get() {
T v = value.get();
if (v == null) {
return defaultValue;
} else {
return v;
}
}
};
}
/**
* When retrieved this will iterate over the contained {@link HystrixProperty} instances until a non-null value is found and return that.
*
* @param values properties to iterate over
* @return first non-null value or null if none found
*/
public static <T> HystrixProperty<T> asProperty(final HystrixProperty<T>... values) {
return new HystrixProperty<T>() {
@Override
public T get() {
for (HystrixProperty<T> v : values) {
// return the first one that doesn't return null
if (v.get() != null) {
return v.get();
}
}
return null;
}
};
}
/**
* @ExcludeFromJavadoc
*/
public static <T> HystrixProperty<T> asProperty(final HystrixPropertiesChainedArchaiusProperty.ChainLink<T> chainedProperty) {
return new HystrixProperty<T>() {
@Override
public T get() {
return chainedProperty.get();
}
};
}
public static <T> HystrixProperty<T> nullProperty() {
return new HystrixProperty<T>() {
@Override
public T get() {
return null;
}
};
}
}
}
| 4,754 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/archaius/HystrixDynamicPropertiesArchaius.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.strategy.properties.archaius;
import com.netflix.config.PropertyWrapper;
import com.netflix.hystrix.strategy.properties.HystrixDynamicProperties;
import com.netflix.hystrix.strategy.properties.HystrixDynamicProperty;
/**
* This class should not be imported from any class in core or else Archaius will be loaded.
* @author agentgt
* @ExcludeFromJavadoc
*/
/* package */ public class HystrixDynamicPropertiesArchaius implements HystrixDynamicProperties {
/**
* @ExcludeFromJavadoc
*/
@Override
public HystrixDynamicProperty<String> getString(String name, String fallback) {
return new StringDynamicProperty(name, fallback);
}
/**
* @ExcludeFromJavadoc
*/
@Override
public HystrixDynamicProperty<Integer> getInteger(String name, Integer fallback) {
return new IntegerDynamicProperty(name, fallback);
}
/**
* @ExcludeFromJavadoc
*/
@Override
public HystrixDynamicProperty<Long> getLong(String name, Long fallback) {
return new LongDynamicProperty(name, fallback);
}
/**
* @ExcludeFromJavadoc
*/
@Override
public HystrixDynamicProperty<Boolean> getBoolean(String name, Boolean fallback) {
return new BooleanDynamicProperty(name, fallback);
}
private abstract static class ArchaiusDynamicProperty<T>
extends PropertyWrapper<T> implements HystrixDynamicProperty<T> {
protected ArchaiusDynamicProperty(String propName, T defaultValue) {
super(propName, defaultValue);
}
@Override
public T get() {
return getValue();
}
}
private static class StringDynamicProperty extends ArchaiusDynamicProperty<String> {
protected StringDynamicProperty(String propName, String defaultValue) {
super(propName, defaultValue);
}
@Override
public String getValue() {
return prop.getString(defaultValue);
}
}
private static class IntegerDynamicProperty extends ArchaiusDynamicProperty<Integer> {
protected IntegerDynamicProperty(String propName, Integer defaultValue) {
super(propName, defaultValue);
}
@Override
public Integer getValue() {
return prop.getInteger(defaultValue);
}
}
private static class LongDynamicProperty extends ArchaiusDynamicProperty<Long> {
protected LongDynamicProperty(String propName, Long defaultValue) {
super(propName, defaultValue);
}
@Override
public Long getValue() {
return prop.getLong(defaultValue);
}
}
private static class BooleanDynamicProperty extends ArchaiusDynamicProperty<Boolean> {
protected BooleanDynamicProperty(String propName, Boolean defaultValue) {
super(propName, defaultValue);
}
@Override
public Boolean getValue() {
return prop.getBoolean(defaultValue);
}
}
}
| 4,755 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHookDefault.java | /**
* Copyright 2013 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 com.netflix.hystrix.strategy.executionhook;
/**
* Default implementations of {@link HystrixCommandExecutionHook} that does nothing.
*
* @ExcludeFromJavadoc
*/
public class HystrixCommandExecutionHookDefault extends HystrixCommandExecutionHook {
private static HystrixCommandExecutionHookDefault INSTANCE = new HystrixCommandExecutionHookDefault();
private HystrixCommandExecutionHookDefault() {
}
public static HystrixCommandExecutionHook getInstance() {
return INSTANCE;
}
}
| 4,756 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java | /**
* Copyright 2013 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 com.netflix.hystrix.strategy.executionhook;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Abstract ExecutionHook with invocations at different lifecycle points of {@link HystrixCommand}
* and {@link HystrixObservableCommand} execution with default no-op implementations.
* <p>
* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
* href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
* <p>
* <b>Note on thread-safety and performance</b>
* <p>
* A single implementation of this class will be used globally so methods on this class will be invoked concurrently from multiple threads so all functionality must be thread-safe.
* <p>
* Methods are also invoked synchronously and will add to execution time of the commands so all behavior should be fast. If anything time-consuming is to be done it should be spawned asynchronously
* onto separate worker threads.
*
* @since 1.2
* */
public abstract class HystrixCommandExecutionHook {
/**
* Invoked before {@link HystrixInvokable} begins executing.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.2
*/
public <T> void onStart(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked when {@link HystrixInvokable} emits a value.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param value value emitted
*
* @since 1.4
*/
public <T> T onEmit(HystrixInvokable<T> commandInstance, T value) {
return value; //by default, just pass through
}
/**
* Invoked when {@link HystrixInvokable} fails with an Exception.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param failureType {@link FailureType} enum representing which type of error
* @param e exception object
*
* @since 1.2
*/
public <T> Exception onError(HystrixInvokable<T> commandInstance, FailureType failureType, Exception e) {
return e; //by default, just pass through
}
/**
* Invoked when {@link HystrixInvokable} finishes a successful execution.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.4
*/
public <T> void onSuccess(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked at start of thread execution when {@link HystrixCommand} is executed using {@link ExecutionIsolationStrategy#THREAD}.
*
* @param commandInstance The executing HystrixCommand instance.
*
* @since 1.2
*/
public <T> void onThreadStart(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked at completion of thread execution when {@link HystrixCommand} is executed using {@link ExecutionIsolationStrategy#THREAD}.
* This will get invoked whenever the Hystrix thread is done executing, regardless of whether the thread finished
* naturally, or was unsubscribed externally
*
* @param commandInstance The executing HystrixCommand instance.
*
* @since 1.2
*/
public <T> void onThreadComplete(HystrixInvokable<T> commandInstance) {
// do nothing by default
}
/**
* Invoked when the user-defined execution method in {@link HystrixInvokable} starts.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.4
*/
public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked when the user-defined execution method in {@link HystrixInvokable} emits a value.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param value value emitted
*
* @since 1.4
*/
public <T> T onExecutionEmit(HystrixInvokable<T> commandInstance, T value) {
return value; //by default, just pass through
}
/**
* Invoked when the user-defined execution method in {@link HystrixInvokable} fails with an Exception.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param e exception object
*
* @since 1.4
*/
public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception e) {
return e; //by default, just pass through
}
/**
* Invoked when the user-defined execution method in {@link HystrixInvokable} completes successfully.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.4
*/
public <T> void onExecutionSuccess(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked when the fallback method in {@link HystrixInvokable} starts.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.2
*/
public <T> void onFallbackStart(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked when the fallback method in {@link HystrixInvokable} emits a value.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param value value emitted
*
* @since 1.4
*/
public <T> T onFallbackEmit(HystrixInvokable<T> commandInstance, T value) {
return value; //by default, just pass through
}
/**
* Invoked when the fallback method in {@link HystrixInvokable} fails with an Exception.
*
* @param commandInstance The executing HystrixInvokable instance.
* @param e exception object
*
* @since 1.2
*/
public <T> Exception onFallbackError(HystrixInvokable<T> commandInstance, Exception e) {
//by default, just pass through
return e;
}
/**
* Invoked when the user-defined execution method in {@link HystrixInvokable} completes successfully.
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.4
*/
public <T> void onFallbackSuccess(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked when the command response is found in the {@link com.netflix.hystrix.HystrixRequestCache}.
*
* @param commandInstance The executing HystrixCommand
*
* @since 1.4
*/
public <T> void onCacheHit(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* Invoked with the command is unsubscribed before a terminal state
*
* @param commandInstance The executing HystrixInvokable instance.
*
* @since 1.5.9
*/
public <T> void onUnsubscribe(HystrixInvokable<T> commandInstance) {
//do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionStart}.
*
* Invoked before {@link HystrixCommand#run()} is about to be executed.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onRunStart(HystrixCommand<T> commandInstance) {
// do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionStart}.
*
* Invoked before {@link HystrixCommand#run()} is about to be executed.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onRunStart(HystrixInvokable<T> commandInstance) {
// do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionEmit} if you want to add a hook for each value emitted by the command
* or to {@link #onExecutionSuccess} if you want to add a hook when the command successfully executes
*
* Invoked after successful execution of {@link HystrixCommand#run()} with response value.
* In a {@link HystrixCommand} using {@link ExecutionIsolationStrategy#THREAD}, this will get invoked if the Hystrix thread
* successfully runs, regardless of whether the calling thread encountered a timeout.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param response
* from {@link HystrixCommand#run()}
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) {
// pass-thru by default
return response;
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionEmit} if you want to add a hook for each value emitted by the command
* or to {@link #onExecutionSuccess} if you want to add a hook when the command successfully executes
*
* Invoked after successful execution of {@link HystrixCommand#run()} with response value.
* In a {@link HystrixCommand} using {@link ExecutionIsolationStrategy#THREAD}, this will get invoked if the Hystrix thread
* successfully runs, regardless of whether the calling thread encountered a timeout.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param response
* from {@link HystrixCommand#run()}
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onRunSuccess(HystrixInvokable<T> commandInstance, T response) {
// pass-thru by default
return response;
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionError}
*
* Invoked after failed execution of {@link HystrixCommand#run()} with thrown Exception.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param e
* Exception thrown by {@link HystrixCommand#run()}
* @return Exception that can be decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
}
/**
* DEPRECATED: Change usages of this to {@link #onExecutionError}
*
* Invoked after failed execution of {@link HystrixCommand#run()} with thrown Exception.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param e
* Exception thrown by {@link HystrixCommand#run()}
* @return Exception that can be decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> Exception onRunError(HystrixInvokable<T> commandInstance, Exception e) {
// pass-thru by default
return e;
}
/**
* DEPRECATED: Change usages of this to {@link #onFallbackStart}
*
* Invoked before {@link HystrixCommand#getFallback()} is about to be executed.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onFallbackStart(HystrixCommand<T> commandInstance) {
// do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onFallbackEmit} if you want to write a hook that handles each emitted fallback value
* or to {@link #onFallbackSuccess} if you want to write a hook that handles success of the fallback method
*
* Invoked after successful execution of {@link HystrixCommand#getFallback()} with response value.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param fallbackResponse
* from {@link HystrixCommand#getFallback()}
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onFallbackSuccess(HystrixCommand<T> commandInstance, T fallbackResponse) {
// pass-thru by default
return fallbackResponse;
}
/**
* DEPRECATED: Change usages of this to {@link #onFallbackEmit} if you want to write a hook that handles each emitted fallback value
* or to {@link #onFallbackSuccess} if you want to write a hook that handles success of the fallback method
*
* Invoked after successful execution of {@link HystrixCommand#getFallback()} with response value.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param fallbackResponse
* from {@link HystrixCommand#getFallback()}
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onFallbackSuccess(HystrixInvokable<T> commandInstance, T fallbackResponse) {
// pass-thru by default
return fallbackResponse;
}
/**
* DEPRECATED: Change usages of this to {@link #onFallbackError}.
*
* Invoked after failed execution of {@link HystrixCommand#getFallback()} with thrown exception.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param e
* Exception thrown by {@link HystrixCommand#getFallback()}
* @return Exception that can be decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) {
// pass-thru by default
return e;
}
/**
* DEPRECATED: Change usages of this to {@link #onStart}.
*
* Invoked before {@link HystrixCommand} executes.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onStart(HystrixCommand<T> commandInstance) {
// do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onEmit} if you want to write a hook that handles each emitted command value
* or to {@link #onSuccess} if you want to write a hook that handles success of the command
*
* Invoked after completion of {@link HystrixCommand} execution that results in a response.
* <p>
* The response can come either from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param response
* from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onComplete(HystrixCommand<T> commandInstance, T response) {
// pass-thru by default
return response;
}
/**
* DEPRECATED: Change usages of this to {@link #onEmit} if you want to write a hook that handles each emitted command value
* or to {@link #onSuccess} if you want to write a hook that handles success of the command
*
* Invoked after completion of {@link HystrixCommand} execution that results in a response.
* <p>
* The response can come either from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param response
* from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
* @return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> T onComplete(HystrixInvokable<T> commandInstance, T response) {
// pass-thru by default
return response;
}
/**
* DEPRECATED: Change usages of this to {@link #onError}.
*
* Invoked after failed completion of {@link HystrixCommand} execution.
*
* @param commandInstance
* The executing HystrixCommand instance.
* @param failureType
* {@link FailureType} representing the type of failure that occurred.
* <p>
* See {@link HystrixRuntimeException} for more information.
* @param e
* Exception thrown by {@link HystrixCommand}
* @return Exception that can be decorated, replaced or just returned as a pass-thru.
*
* @since 1.2
*/
@Deprecated
public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) {
// pass-thru by default
return e;
}
/**
* DEPRECATED: Change usages of this to {@link #onThreadStart}.
*
* Invoked at start of thread execution when {@link HystrixCommand} is executed using {@link ExecutionIsolationStrategy#THREAD}.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onThreadStart(HystrixCommand<T> commandInstance) {
// do nothing by default
}
/**
* DEPRECATED: Change usages of this to {@link #onThreadComplete}.
*
* Invoked at completion of thread execution when {@link HystrixCommand} is executed using {@link ExecutionIsolationStrategy#THREAD}.
* This will get invoked if the Hystrix thread successfully executes, regardless of whether the calling thread
* encountered a timeout.
*
* @param commandInstance
* The executing HystrixCommand instance.
*
* @since 1.2
*/
@Deprecated
public <T> void onThreadComplete(HystrixCommand<T> commandInstance) {
// do nothing by default
}
}
| 4,757 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/package-info.java | /**
* Copyright 2013 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.
*/
/**
* Strategy definition for execution hook.
*
* @since 1.2.0
*/
package com.netflix.hystrix.strategy.executionhook; | 4,758 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/eventnotifier/HystrixEventNotifierDefault.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.eventnotifier;
/**
* Default implementations of {@link HystrixEventNotifier} that does nothing.
*
* @ExcludeFromJavadoc
*/
public class HystrixEventNotifierDefault extends HystrixEventNotifier {
private static HystrixEventNotifierDefault INSTANCE = new HystrixEventNotifierDefault();
private HystrixEventNotifierDefault() {
}
public static HystrixEventNotifier getInstance() {
return INSTANCE;
}
}
| 4,759 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/eventnotifier/HystrixEventNotifier.java | /**
* Copyright 2012 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 com.netflix.hystrix.strategy.eventnotifier;
import java.util.List;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.strategy.HystrixPlugins;
/**
* Abstract EventNotifier that allows receiving notifications for different events with default implementations.
* <p>
* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
* href="https://github.com/Netflix/Hystrix/wiki/Plugins">https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
* <p>
* <b>Note on thread-safety and performance</b>
* <p>
* A single implementation of this class will be used globally so methods on this class will be invoked concurrently from multiple threads so all functionality must be thread-safe.
* <p>
* Methods are also invoked synchronously and will add to execution time of the commands so all behavior should be fast. If anything time-consuming is to be done it should be spawned asynchronously
* onto separate worker threads.
*/
public abstract class HystrixEventNotifier {
/**
* Called for every event fired.
* <p>
* <b>Default Implementation: </b> Does nothing
*
* @param eventType event type
* @param key event key
*/
public void markEvent(HystrixEventType eventType, HystrixCommandKey key) {
// do nothing
}
/**
* Called after a command is executed using thread isolation.
* <p>
* Will not get called if a command is rejected, short-circuited etc.
* <p>
* <b>Default Implementation: </b> Does nothing
*
* @param key
* {@link HystrixCommandKey} of command instance.
* @param isolationStrategy
* {@link ExecutionIsolationStrategy} the isolation strategy used by the command when executed
* @param duration
* time in milliseconds of executing <code>run()</code> method
* @param eventsDuringExecution
* {@code List<HystrixEventType>} of events occurred during execution.
*/
public void markCommandExecution(HystrixCommandKey key, ExecutionIsolationStrategy isolationStrategy, int duration, List<HystrixEventType> eventsDuringExecution) {
// do nothing
}
}
| 4,760 |
0 | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy | Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/strategy/eventnotifier/package-info.java | /**
* Copyright 2012 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.
*/
/**
* Strategy definition for event notification.
*
* @since 1.0.0
*/
package com.netflix.hystrix.strategy.eventnotifier; | 4,761 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CommandExecutionPerfTest.java | /**
* Copyright 2014 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.perf;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.infra.Blackhole;
import rx.Observable;
import rx.functions.Func0;
import rx.schedulers.Schedulers;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Note that the hystrixExecute test must be run on a forked JVM. Otherwise, the initial properties that get
* set for the command apply to all runs. This would leave the command as THREAD-isolated in all test, for example.
*/
public class CommandExecutionPerfTest {
private static HystrixCommandProperties.Setter threadIsolatedCommandDefaults = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerForceOpen(false);
private static HystrixCommandProperties.Setter threadIsolatedFailFastCommandDefaults = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerForceOpen(true);
private static HystrixCommandProperties.Setter semaphoreIsolatedCommandDefaults = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerForceOpen(false);
private static HystrixCommandProperties.Setter semaphoreIsolatedFailFastCommandDefaults = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerForceOpen(true);
private static HystrixThreadPoolProperties.Setter threadPoolDefaults = HystrixThreadPoolProperties.Setter()
.withCoreSize(100);
private static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("PERF");
private static HystrixCommandProperties.Setter getCommandSetter(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy, boolean forceOpen) {
switch (isolationStrategy) {
case THREAD:
if (forceOpen) {
return threadIsolatedFailFastCommandDefaults;
} else {
return threadIsolatedCommandDefaults;
}
default:
if (forceOpen) {
return semaphoreIsolatedFailFastCommandDefaults;
} else {
return semaphoreIsolatedCommandDefaults;
}
}
}
@State(Scope.Thread)
public static class BlackholeState {
//amount of "work" to give to CPU
@Param({"1", "100", "10000"})
public int blackholeConsumption;
}
@State(Scope.Thread)
public static class CommandState {
HystrixCommand<Integer> command;
HystrixRequestContext requestContext;
@Param({"true", "false"})
public boolean forceOpen;
@Param({"true", "false"})
public boolean setUpRequestContext;
@Param({"THREAD", "SEMAPHORE"})
public HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy;
//amount of "work" to give to CPU
@Param({"1", "100", "10000"})
public int blackholeConsumption;
@Setup(Level.Invocation)
public void setUp() {
if (setUpRequestContext) {
requestContext = HystrixRequestContext.initializeContext();
}
command = new HystrixCommand<Integer>(
HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("PERF"))
.andCommandPropertiesDefaults(getCommandSetter(isolationStrategy, forceOpen))
.andThreadPoolPropertiesDefaults(threadPoolDefaults)
) {
@Override
protected Integer run() throws Exception {
Blackhole.consumeCPU(blackholeConsumption);
return 1;
}
@Override
protected Integer getFallback() {
return 2;
}
};
}
@TearDown(Level.Invocation)
public void tearDown() {
if (setUpRequestContext) {
requestContext.shutdown();
}
}
}
@State(Scope.Thread)
public static class ObservableCommandState {
HystrixObservableCommand<Integer> command;
HystrixRequestContext requestContext;
@Param({"true", "false"})
public boolean forceOpen;
@Param({"true", "false"})
public boolean setUpRequestContext;
//amount of "work" to give to CPU
@Param({"1", "100", "10000"})
public int blackholeConsumption;
@Setup(Level.Invocation)
public void setUp() {
if (setUpRequestContext) {
requestContext = HystrixRequestContext.initializeContext();
}
command = new HystrixObservableCommand<Integer>(
HystrixObservableCommand.Setter.withGroupKey(groupKey)
.andCommandPropertiesDefaults(getCommandSetter(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE, forceOpen))
) {
@Override
protected Observable<Integer> construct() {
return Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
Blackhole.consumeCPU(blackholeConsumption);
return Observable.just(1);
}
}).subscribeOn(Schedulers.computation());
}
};
}
@TearDown(Level.Invocation)
public void tearDown() {
if (setUpRequestContext) {
requestContext.shutdown();
}
}
}
@State(Scope.Benchmark)
public static class ExecutorState {
ExecutorService executorService;
@Setup
public void setUp() {
executorService = Executors.newFixedThreadPool(100);
}
@TearDown
public void tearDown() {
List<Runnable> runnables = executorService.shutdownNow();
}
}
@State(Scope.Benchmark)
public static class ThreadPoolState {
HystrixThreadPool hystrixThreadPool;
@Setup
public void setUp() {
hystrixThreadPool = new HystrixThreadPool.HystrixThreadPoolDefault(
HystrixThreadPoolKey.Factory.asKey("PERF")
, HystrixThreadPoolProperties.Setter().withCoreSize(100));
}
@TearDown
public void tearDown() {
hystrixThreadPool.getExecutor().shutdownNow();
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer baselineExecute(BlackholeState bhState) {
Blackhole.consumeCPU(bhState.blackholeConsumption);
return 1;
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer baselineQueue(ExecutorState state, final BlackholeState bhState) throws InterruptedException, ExecutionException {
try {
return state.executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Blackhole.consumeCPU(bhState.blackholeConsumption);
return 1;
}
}).get();
} catch (Throwable t) {
return 2;
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer baselineSyncObserve(final BlackholeState bhState) throws InterruptedException {
Observable<Integer> syncObservable = Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
Blackhole.consumeCPU(bhState.blackholeConsumption);
return Observable.just(1);
}
});
try {
return syncObservable.toBlocking().first();
} catch (Throwable t) {
return 2;
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer baselineAsyncComputationObserve(final BlackholeState bhState) throws InterruptedException {
Observable<Integer> asyncObservable = Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
Blackhole.consumeCPU(bhState.blackholeConsumption);
return Observable.just(1);
}
}).subscribeOn(Schedulers.computation());
try {
return asyncObservable.toBlocking().first();
} catch (Throwable t) {
return 2;
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer baselineAsyncCustomThreadPoolObserve(ThreadPoolState state, final BlackholeState bhState) {
Observable<Integer> asyncObservable = Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
Blackhole.consumeCPU(bhState.blackholeConsumption);
return Observable.just(1);
}
}).subscribeOn(state.hystrixThreadPool.getScheduler());
try {
return asyncObservable.toBlocking().first();
} catch (Throwable t) {
return 2;
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer hystrixExecute(CommandState state) {
return state.command.execute();
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer hystrixObserve(ObservableCommandState state) {
return state.command.observe().toBlocking().first();
}
}
| 4,762 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/RollingNumberPerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.util.HystrixRollingNumber;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class RollingNumberPerfTest {
@State(Scope.Thread)
public static class CounterState {
HystrixRollingNumber counter;
@Setup(Level.Iteration)
public void setUp() {
counter = new HystrixRollingNumber(100, 10);
}
}
@State(Scope.Thread)
public static class ValueState {
final Random r = new Random();
int value;
HystrixRollingNumberEvent type;
@Setup(Level.Invocation)
public void setUp() {
value = r.nextInt(100);
int typeInt = r.nextInt(3);
switch(typeInt) {
case 0:
type = HystrixRollingNumberEvent.SUCCESS;
break;
case 1:
type = HystrixRollingNumberEvent.FAILURE;
break;
case 2:
type = HystrixRollingNumberEvent.TIMEOUT;
break;
default: throw new RuntimeException("Unexpected : " + typeInt);
}
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber writeOnly(CounterState counterState, ValueState valueState) {
counterState.counter.add(valueState.type, valueState.value);
return counterState.counter;
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long readOnly(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getCumulativeSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getCumulativeSum(HystrixRollingNumberEvent.FAILURE) +
counter.getCumulativeSum(HystrixRollingNumberEvent.TIMEOUT) +
counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getRollingSum(HystrixRollingNumberEvent.FAILURE) +
counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT);
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber writeHeavyCounterAdd(CounterState counterState, ValueState valueState) {
counterState.counter.add(valueState.type, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long writeHeavyReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getCumulativeSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getCumulativeSum(HystrixRollingNumberEvent.FAILURE) +
counter.getCumulativeSum(HystrixRollingNumberEvent.TIMEOUT) +
counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getRollingSum(HystrixRollingNumberEvent.FAILURE) +
counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT);
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber evenSplitCounterAdd(CounterState counterState, ValueState valueState) {
counterState.counter.add(valueState.type, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long evenSplitReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getCumulativeSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getCumulativeSum(HystrixRollingNumberEvent.FAILURE) +
counter.getCumulativeSum(HystrixRollingNumberEvent.TIMEOUT) +
counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getRollingSum(HystrixRollingNumberEvent.FAILURE) +
counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT);
}
@Benchmark
@Group("readHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber readHeavyCounterAdd(CounterState counterState, ValueState valueState) {
counterState.counter.add(valueState.type, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("readHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long readHeavyReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getCumulativeSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getCumulativeSum(HystrixRollingNumberEvent.FAILURE) +
counter.getCumulativeSum(HystrixRollingNumberEvent.TIMEOUT) +
counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS) +
counter.getRollingSum(HystrixRollingNumberEvent.FAILURE) +
counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT);
}
}
| 4,763 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/ObservableCollapserPerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCollapser;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesCollapserDefault;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.infra.Blackhole;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ObservableCollapserPerfTest {
@State(Scope.Thread)
public static class CollapserState {
@Param({"1", "10", "100", "1000"})
int numToCollapse;
@Param({"1", "10", "100"})
int numResponsesPerArg;
@Param({"1", "1000", "1000000"})
int blackholeConsumption;
HystrixRequestContext reqContext;
Observable<String> executionHandle;
@Setup(Level.Invocation)
public void setUp() {
reqContext = HystrixRequestContext.initializeContext();
List<Observable<String>> os = new ArrayList<Observable<String>>();
for (int i = 0; i < numToCollapse; i++) {
TestCollapserWithMultipleResponses collapser = new TestCollapserWithMultipleResponses(i, numResponsesPerArg, blackholeConsumption);
os.add(collapser.observe());
}
executionHandle = Observable.merge(os);
}
@TearDown(Level.Invocation)
public void tearDown() {
reqContext.shutdown();
}
}
//TODO wire in synthetic timer
private static class TestCollapserWithMultipleResponses extends HystrixObservableCollapser<String, String, String, String> {
private final String arg;
private final static Map<String, Integer> emitsPerArg;
private final int blackholeConsumption;
private final boolean commandConstructionFails;
private final Func1<String, String> keyMapper;
private final Action1<HystrixCollapser.CollapsedRequest<String, String>> onMissingResponseHandler;
static {
emitsPerArg = new HashMap<String, Integer>();
}
public TestCollapserWithMultipleResponses(int arg, int numResponsePerArg, int blackholeConsumption) {
super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("COLLAPSER")).andScope(Scope.REQUEST).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withMaxRequestsInBatch(1000).withTimerDelayInMilliseconds(1)));
this.arg = arg + "";
emitsPerArg.put(this.arg, numResponsePerArg);
this.blackholeConsumption = blackholeConsumption;
commandConstructionFails = false;
keyMapper = new Func1<String, String>() {
@Override
public String call(String s) {
return s.substring(0, s.indexOf(":"));
}
};
onMissingResponseHandler = new Action1<HystrixCollapser.CollapsedRequest<String, String>>() {
@Override
public void call(HystrixCollapser.CollapsedRequest<String, String> collapsedReq) {
collapsedReq.setResponse("missing:missing");
}
};
}
@Override
public String getRequestArgument() {
return arg;
}
@Override
protected HystrixObservableCommand<String> createCommand(Collection<HystrixCollapser.CollapsedRequest<String, String>> collapsedRequests) {
if (commandConstructionFails) {
throw new RuntimeException("Exception thrown in command construction");
} else {
List<Integer> args = new ArrayList<Integer>();
for (HystrixCollapser.CollapsedRequest<String, String> collapsedRequest : collapsedRequests) {
String stringArg = collapsedRequest.getArgument();
int intArg = Integer.parseInt(stringArg);
args.add(intArg);
}
return new TestCollapserCommandWithMultipleResponsePerArgument(args, emitsPerArg, blackholeConsumption);
}
}
//Data comes back in the form: 1:1, 1:2, 1:3, 2:2, 2:4, 2:6.
//This method should use the first half of that string as the request arg
@Override
protected Func1<String, String> getBatchReturnTypeKeySelector() {
return keyMapper;
}
@Override
protected Func1<String, String> getRequestArgumentKeySelector() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected void onMissingResponse(HystrixCollapser.CollapsedRequest<String, String> r) {
onMissingResponseHandler.call(r);
}
@Override
protected Func1<String, String> getBatchReturnTypeToResponseTypeMapper() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
}
private static class TestCollapserCommandWithMultipleResponsePerArgument extends HystrixObservableCommand<String> {
private final List<Integer> args;
private final Map<String, Integer> emitsPerArg;
private final int blackholeConsumption;
TestCollapserCommandWithMultipleResponsePerArgument(List<Integer> args, Map<String, Integer> emitsPerArg, int blackholeConsumption) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("COLLAPSER_MULTI")).andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)));
this.args = args;
this.emitsPerArg = emitsPerArg;
this.blackholeConsumption = blackholeConsumption;
}
@Override
protected Observable<String> construct() {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
Blackhole.consumeCPU(blackholeConsumption);
for (Integer arg: args) {
int numEmits = emitsPerArg.get(arg.toString());
for (int j = 1; j < numEmits + 1; j++) {
subscriber.onNext(arg + ":" + (arg * j));
}
}
} catch (Throwable ex) {
subscriber.onError(ex);
}
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.computation());
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.SECONDS)
public List<String> observeCollapsedAndWait(CollapserState collapserState) {
return collapserState.executionHandle.toList().toBlocking().single();
}
}
| 4,764 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CommandConstructionPerfTest.java | /**
* Copyright 2014 Netflix, Inc.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.perf;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
public class CommandConstructionPerfTest {
static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Group");
@Benchmark
@BenchmarkMode({Mode.SingleShotTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public HystrixCommand constructHystrixCommandByGroupKeyOnly() {
return new HystrixCommand<Integer>(groupKey) {
@Override
protected Integer run() throws Exception {
return 1;
}
};
}
}
| 4,765 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/RollingPercentilePerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import com.netflix.hystrix.util.HystrixRollingPercentile;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class RollingPercentilePerfTest {
@State(Scope.Thread)
public static class PercentileState {
HystrixRollingPercentile percentile;
@Param({"true", "false"})
public boolean percentileEnabled;
@Setup(Level.Iteration)
public void setUp() {
percentile = new HystrixRollingPercentile(100, 10, 1000, HystrixProperty.Factory.asProperty(percentileEnabled));
}
}
@State(Scope.Thread)
public static class LatencyState {
final Random r = new Random();
int latency;
@Setup(Level.Invocation)
public void setUp() {
latency = r.nextInt(100);
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingPercentile writeOnly(PercentileState percentileState, LatencyState latencyState) {
percentileState.percentile.addValue(latencyState.latency);
return percentileState.percentile;
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public int readOnly(PercentileState percentileState) {
HystrixRollingPercentile percentile = percentileState.percentile;
return percentile.getMean() +
percentile.getPercentile(10) +
percentile.getPercentile(25) +
percentile.getPercentile(50) +
percentile.getPercentile(75) +
percentile.getPercentile(90) +
percentile.getPercentile(95) +
percentile.getPercentile(99) +
percentile.getPercentile(99.5);
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingPercentile writeHeavyLatencyAdd(PercentileState percentileState, LatencyState latencyState) {
percentileState.percentile.addValue(latencyState.latency);
return percentileState.percentile;
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public int writeHeavyReadMetrics(PercentileState percentileState) {
HystrixRollingPercentile percentile = percentileState.percentile;
return percentile.getMean() +
percentile.getPercentile(10) +
percentile.getPercentile(25) +
percentile.getPercentile(50) +
percentile.getPercentile(75) +
percentile.getPercentile(90) +
percentile.getPercentile(95) +
percentile.getPercentile(99) +
percentile.getPercentile(99.5);
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingPercentile evenSplitLatencyAdd(PercentileState percentileState, LatencyState latencyState) {
percentileState.percentile.addValue(latencyState.latency);
return percentileState.percentile;
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public int evenSplitReadMetrics(PercentileState percentileState) {
HystrixRollingPercentile percentile = percentileState.percentile;
return percentile.getMean() +
percentile.getPercentile(10) +
percentile.getPercentile(25) +
percentile.getPercentile(50) +
percentile.getPercentile(75) +
percentile.getPercentile(90) +
percentile.getPercentile(95) +
percentile.getPercentile(99) +
percentile.getPercentile(99.5);
}
@Benchmark
@Group("readHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingPercentile readHeavyLatencyAdd(PercentileState percentileState, LatencyState latencyState) {
percentileState.percentile.addValue(latencyState.latency);
return percentileState.percentile;
}
@Benchmark
@Group("readHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public int readHeavyReadMetrics(PercentileState percentileState) {
HystrixRollingPercentile percentile = percentileState.percentile;
return percentile.getMean() +
percentile.getPercentile(10) +
percentile.getPercentile(25) +
percentile.getPercentile(50) +
percentile.getPercentile(75) +
percentile.getPercentile(90) +
percentile.getPercentile(95) +
percentile.getPercentile(99) +
percentile.getPercentile(99.5);
}
}
| 4,766 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CommandExecutionAndConcurrentMetricsReadPerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
public class CommandExecutionAndConcurrentMetricsReadPerfTest {
@State(Scope.Thread)
public static class CommandState {
HystrixCommand<Integer> command;
@Param({"THREAD", "SEMAPHORE"})
public HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy;
@Setup(Level.Invocation)
public void setUp() {
command = new HystrixCommand<Integer>(
HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("PERF"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(isolationStrategy)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerForceOpen(false)
)
.andThreadPoolPropertiesDefaults(
HystrixThreadPoolProperties.Setter()
.withCoreSize(100)
)
) {
@Override
protected Integer run() throws Exception {
return 1;
}
@Override
protected Integer getFallback() {
return 2;
}
};
}
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer writeHeavyCommandExecution(CommandState state) {
return state.command.observe().toBlocking().first();
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long writeHeavyReadMetrics(CommandState state) {
HystrixCommandMetrics metrics = state.command.getMetrics();
return metrics.getExecutionTimeMean()
+ metrics.getExecutionTimePercentile(50)
+ metrics.getExecutionTimePercentile(75)
+ metrics.getExecutionTimePercentile(99)
+ metrics.getCumulativeCount(HystrixEventType.SUCCESS)
+ metrics.getRollingCount(HystrixEventType.FAILURE)
+ metrics.getRollingMaxConcurrentExecutions();
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer evenSplitOfWritesAndReadsCommandExecution(CommandState state) {
return state.command.observe().toBlocking().first();
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long evenSplitOfWritesAndReadsReadMetrics(CommandState state) {
HystrixCommandMetrics metrics = state.command.getMetrics();
return metrics.getExecutionTimeMean()
+ metrics.getExecutionTimePercentile(50)
+ metrics.getExecutionTimePercentile(75)
+ metrics.getExecutionTimePercentile(99)
+ metrics.getCumulativeCount(HystrixEventType.SUCCESS)
+ metrics.getRollingCount(HystrixEventType.FAILURE)
+ metrics.getRollingMaxConcurrentExecutions();
}
@Benchmark
@Group("readHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Integer readHeavyCommandExecution(CommandState state) {
return state.command.observe().toBlocking().first();
}
@Benchmark
@Group("readHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public Long readHeavyReadMetrics(CommandState state) {
HystrixCommandMetrics metrics = state.command.getMetrics();
return metrics.getExecutionTimeMean()
+ metrics.getExecutionTimePercentile(50)
+ metrics.getExecutionTimePercentile(75)
+ metrics.getExecutionTimePercentile(99)
+ metrics.getCumulativeCount(HystrixEventType.SUCCESS)
+ metrics.getRollingCount(HystrixEventType.FAILURE)
+ metrics.getRollingMaxConcurrentExecutions();
}
}
| 4,767 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CollapserPerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixThreadPool;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.infra.Blackhole;
import rx.Observable;
import rx.Subscription;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class CollapserPerfTest {
@State(Scope.Benchmark)
public static class ThreadPoolState {
HystrixThreadPool hystrixThreadPool;
@Setup
public void setUp() {
hystrixThreadPool = new HystrixThreadPool.HystrixThreadPoolDefault(
HystrixThreadPoolKey.Factory.asKey("PERF")
, HystrixThreadPoolProperties.Setter().withCoreSize(100));
}
@TearDown
public void tearDown() {
hystrixThreadPool.getExecutor().shutdownNow();
}
}
@State(Scope.Thread)
public static class CollapserState {
@Param({"1", "10", "100", "1000"})
int numToCollapse;
@Param({"1", "1000", "1000000"})
int blackholeConsumption;
HystrixRequestContext reqContext;
Observable<String> executionHandle;
@Setup(Level.Invocation)
public void setUp() {
reqContext = HystrixRequestContext.initializeContext();
List<Observable<String>> os = new ArrayList<Observable<String>>();
for (int i = 0; i < numToCollapse; i++) {
IdentityCollapser collapser = new IdentityCollapser(i, blackholeConsumption);
os.add(collapser.observe());
}
executionHandle = Observable.merge(os);
}
@TearDown(Level.Invocation)
public void tearDown() {
reqContext.shutdown();
}
}
private static class IdentityCollapser extends HystrixCollapser<List<String>, String, String> {
private final int arg;
private final int blackholeConsumption;
IdentityCollapser(int arg, int blackholeConsumption) {
super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("COLLAPSER")).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withMaxRequestsInBatch(1000).withTimerDelayInMilliseconds(1)));
this.arg = arg;
this.blackholeConsumption = blackholeConsumption;
}
@Override
public String getRequestArgument() {
return arg + "";
}
@Override
protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> collapsedRequests) {
List<String> args = new ArrayList<String>();
for (CollapsedRequest<String, String> collapsedReq: collapsedRequests) {
args.add(collapsedReq.getArgument());
}
return new BatchCommand(args, blackholeConsumption);
}
@Override
protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, String>> collapsedRequests) {
for (CollapsedRequest<String, String> collapsedReq: collapsedRequests) {
String requestArg = collapsedReq.getArgument();
String response = "<not found>";
for (String responsePiece: batchResponse) {
if (responsePiece.startsWith(requestArg + ":")) {
response = responsePiece;
break;
}
}
collapsedReq.setResponse(response);
}
}
}
private static class BatchCommand extends HystrixCommand<List<String>> {
private final List<String> inputArgs;
private final int blackholeConsumption;
BatchCommand(List<String> inputArgs, int blackholeConsumption) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("PERF")).andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PERF")));
this.inputArgs = inputArgs;
this.blackholeConsumption = blackholeConsumption;
}
@Override
protected List<String> run() throws Exception {
Blackhole.consumeCPU(blackholeConsumption);
List<String> toReturn = new ArrayList<String>();
for (String inputArg: inputArgs) {
toReturn.add(inputArg + ":1");
}
return toReturn;
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.SECONDS)
public List<String> observeCollapsedAndWait(CollapserState collapserState, ThreadPoolState threadPoolState) {
return collapserState.executionHandle.toList().toBlocking().single();
}
}
| 4,768 |
0 | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/jmh/java/com/netflix/hystrix/perf/RollingMaxPerfTest.java | /**
* Copyright 2015 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 com.netflix.hystrix.perf;
import com.netflix.hystrix.util.HystrixRollingNumber;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class RollingMaxPerfTest {
@State(Scope.Thread)
public static class CounterState {
HystrixRollingNumber counter;
@Setup(Level.Iteration)
public void setUp() {
counter = new HystrixRollingNumber(100, 10);
}
}
@State(Scope.Thread)
public static class ValueState {
final Random r = new Random();
int value;
@Setup(Level.Invocation)
public void setUp() {
value = r.nextInt(100);
}
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber writeOnly(CounterState counterState, ValueState valueState) {
counterState.counter.updateRollingMax(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE, valueState.value);
return counterState.counter;
}
@Benchmark
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long readOnly(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getRollingMaxValue(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE);
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber writeHeavyUpdateMax(CounterState counterState, ValueState valueState) {
counterState.counter.updateRollingMax(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("writeHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long writeHeavyReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getRollingMaxValue(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE);
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber evenSplitUpdateMax(CounterState counterState, ValueState valueState) {
counterState.counter.updateRollingMax(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("evenSplit")
@GroupThreads(4)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long evenSplitReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getRollingMaxValue(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE);
}
@Benchmark
@Group("readHeavy")
@GroupThreads(1)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public HystrixRollingNumber readHeavyUpdateMax(CounterState counterState, ValueState valueState) {
counterState.counter.updateRollingMax(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE, valueState.value);
return counterState.counter;
}
@Benchmark
@Group("readHeavy")
@GroupThreads(7)
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public long readHeavyReadMetrics(CounterState counterState) {
HystrixRollingNumber counter = counterState.counter;
return counter.getRollingMaxValue(HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE);
}
}
| 4,769 |
0 | Create_ds/aws-sdk-js-v3/tests/react-native/End2End/android/app/src/main/java/com | Create_ds/aws-sdk-js-v3/tests/react-native/End2End/android/app/src/main/java/com/end2end/MainApplication.java | package com.end2end;
import android.app.Application;
import android.util.Log;
import com.facebook.react.PackageList;
import com.facebook.hermes.reactexecutor.HermesExecutorFactory;
import com.facebook.react.bridge.JavaScriptExecutorFactory;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| 4,770 |
0 | Create_ds/aws-sdk-js-v3/tests/react-native/End2End/android/app/src/main/java/com | Create_ds/aws-sdk-js-v3/tests/react-native/End2End/android/app/src/main/java/com/end2end/MainActivity.java | package com.end2end;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "End2End";
}
}
| 4,771 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AddAwsAuthPluginTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
public class AddAwsAuthPluginTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(AwsDependency.CREDENTIAL_PROVIDER_NODE.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("credentialDefaultProvider?"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), not(containsString("signingName")));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(),
containsString("decorateDefaultCredentialProvider"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("Credential is missing"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), not(containsString("signingName:")));
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("resolveAwsAuthConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getAwsAuthPlugin"));
}
@Test
public void sigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExampleSigV4.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExampleSigV4"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(AwsDependency.CREDENTIAL_PROVIDER_NODE.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("credentialDefaultProvider?"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("signingName?"));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(),
containsString("decorateDefaultCredentialProvider"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("Credential is missing"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), containsString("signingName:"));
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("resolveSigV4AuthConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("getSigV4AuthPlugin"));
}
@Test
public void notSigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
not(containsString(AwsDependency.CREDENTIAL_PROVIDER_NODE.packageName)));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("credentialDefaultProvider?")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("signingName?")));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(),
not(containsString("decorateDefaultCredentialProvider")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("Credential is missing")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), not(containsString("signingName:")));
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("resolveSigV4AuthConfig")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("resolveAwsV4AuthConfig")));
}
}
| 4,772 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AddBuiltinPluginsTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
public class AddBuiltinPluginsTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("resolveRegionConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("resolveEndpointsConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("resolveRetryConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getRetryPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getContentLengthPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getHostHeaderPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getLoggerPlugin"));
}
@Test
public void sigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExampleSigV4.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExampleSigV4"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("resolveRegionConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("resolveCustomEndpointsConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("resolveRetryConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("getRetryPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("getContentLengthPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("getHostHeaderPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("getLoggerPlugin"));
}
@Test
public void notSigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("resolveRegionConfig")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("resolveCustomEndpointsConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("resolveRetryConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("getRetryPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("getContentLengthPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("getHostHeaderPlugin"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), containsString("getLoggerPlugin"));
}
}
| 4,773 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AwsEndpointGeneratorIntegrationTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
import software.amazon.smithy.typescript.codegen.TypeScriptServerCodegenPlugin;
public class AwsEndpointGeneratorIntegrationTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
assertTrue(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/endpoints.ts").isPresent());
}
@Test
public void genericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NonAwsService.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#ExampleService"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
assertFalse(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/endpoints.ts").isPresent());
}
@Test
public void serverSdk() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.withMember("disableDefaultValidation", Node.from(true))
.build())
.build();
new TypeScriptServerCodegenPlugin().execute(context);
assertFalse(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/endpoints.ts").isPresent());
}
}
| 4,774 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AwsServiceIdIntegrationTest.java | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
public class AwsServiceIdIntegrationTest {
@Test
public void testSomeLibraryMethod() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
Shape service = model.expectShape((ShapeId.from("smithy.example#OriginalName")));
AwsServiceIdIntegration integration = new AwsServiceIdIntegration();
TypeScriptSettings settings = new TypeScriptSettings();
settings.setService(ShapeId.from("smithy.example#OriginalName"));
SymbolProvider provider = TypeScriptSettings.ArtifactType.CLIENT.createSymbolProvider(model, settings);
SymbolProvider decorated = integration.decorateSymbolProvider(model, settings, provider);
Symbol symbol = decorated.toSymbol(service);
assertThat(symbol.getName(), equalTo("NotSameClient"));
assertThat(symbol.getNamespace(), equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/NotSameClient"));
assertThat(symbol.getDefinitionFile(), equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts"));
}
@Test
public void testFirstNotCapitalizedServiceId() {
Model model = Model.assembler()
.addImport(getClass().getResource("firstNotCapitalized.smithy"))
.discoverModels()
.assemble()
.unwrap();
Shape service = model.expectShape((ShapeId.from("smithy.example#OriginalName")));
AwsServiceIdIntegration integration = new AwsServiceIdIntegration();
TypeScriptSettings settings = new TypeScriptSettings();
SymbolProvider provider = TypeScriptSettings.ArtifactType.CLIENT.createSymbolProvider(model, settings);
SymbolProvider decorated = integration.decorateSymbolProvider(model, settings, provider);
Symbol symbol = decorated.toSymbol(service);
assertThat(symbol.getName(), equalTo("FirstNotCapitalizedClient"));
assertThat(symbol.getNamespace(), equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/FirstNotCapitalizedClient"));
assertThat(symbol.getDefinitionFile(),
equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/FirstNotCapitalizedClient.ts"));
}
@Test
public void testRestNotCapitalizedServiceId() {
Model model = Model.assembler()
.addImport(getClass().getResource("Restnotcapitalized.smithy"))
.discoverModels()
.assemble()
.unwrap();
Shape service = model.expectShape((ShapeId.from("smithy.example#OriginalName")));
AwsServiceIdIntegration integration = new AwsServiceIdIntegration();
TypeScriptSettings settings = new TypeScriptSettings();
SymbolProvider provider = TypeScriptSettings.ArtifactType.CLIENT.createSymbolProvider(model, settings);
SymbolProvider decorated = integration.decorateSymbolProvider(model, settings, provider);
Symbol symbol = decorated.toSymbol(service);
assertThat(symbol.getName(), equalTo("RestNotCapitalizedClient"));
assertThat(symbol.getNamespace(), equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/RestNotCapitalizedClient"));
assertThat(symbol.getDefinitionFile(),
equalTo("./" + CodegenUtils.SOURCE_FOLDER + "/RestNotCapitalizedClient.ts"));
}
}
| 4,775 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AddUserAgentDependencyTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
public class AddUserAgentDependencyTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(AwsDependency.AWS_SDK_UTIL_USER_AGENT_NODE.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("defaultUserAgentProvider?"));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("defaultUserAgent"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("packageInfo.version"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("clientSharedValues.serviceId"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("defaultUserAgent"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("packageInfo.version"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("clientSharedValues.serviceId"));
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("resolveUserAgentConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("getUserAgentPlugin"));
}
@Test
public void genericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NonAwsService.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#ExampleService"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(AwsDependency.AWS_SDK_UTIL_USER_AGENT_NODE.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/ExampleServiceClient.ts").get(), containsString("defaultUserAgentProvider?"));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("defaultUserAgent"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("packageInfo.version"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("ClientSharedValues.serviceId")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("defaultUserAgent"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("packageInfo.version"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("ClientSharedValues.serviceId")));
// Check the config resolution and middleware plugin
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/ExampleServiceClient.ts").get(), containsString("resolveUserAgentConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/ExampleServiceClient.ts").get(), containsString("getUserAgentPlugin"));
}
}
| 4,776 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AddAwsRuntimeConfigTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
public class AddAwsRuntimeConfigTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.NODE_CONFIG_PROVIDER.packageName));
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.CONFIG_RESOLVER.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("serviceId?:"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("region?:"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("useDualstackEndpoint?:"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/NotSameClient.ts").get(), containsString("useFipsEndpoint?:"));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), containsString("serviceId: config?.serviceId ?? \"Not Same\""));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("region: config?.region ?? invalidProvider"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("region: config?.region ?? loadNodeConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString(
"useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT))"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString(
"useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS)"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString(
"useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString(
"useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS),"));
}
@Test
public void sigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExampleSigV4.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExampleSigV4"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.NODE_CONFIG_PROVIDER.packageName));
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.CONFIG_RESOLVER.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), not(containsString("serviceId?:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), containsString("region?:"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), not(containsString("useDualstackEndpoint?:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleSigV4Client.ts").get(), not(containsString("useFipsEndpoint?:")));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), not(containsString("serviceId:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), containsString("region: config?.region ?? invalidProvider"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), containsString("region: config?.region ?? loadNodeConfig"));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("useDualstackEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("useDualstackEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("useFipsEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("useFipsEndpoint:")));
}
@Test
public void notSigV4GenericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.pluginClassLoader(getClass().getClassLoader())
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
// Check dependencies
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.NODE_CONFIG_PROVIDER.packageName));
assertThat(manifest.getFileString("package.json").get(),
containsString(TypeScriptDependency.CONFIG_RESOLVER.packageName));
// Check config interface fields
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("serviceId?:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("region?:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("useDualstackEndpoint?:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/SsdkExampleClient.ts").get(), not(containsString("useFipsEndpoint?:")));
// Check config files
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.shared.ts").get(), not(containsString("serviceId:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("region:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("region:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("useDualstackEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("useDualstackEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.browser.ts").get(), not(containsString("useFipsEndpoint:")));
assertThat(manifest.getFileString(CodegenUtils.SOURCE_FOLDER + "/runtimeConfig.ts").get(), not(containsString("useFipsEndpoint:")));
}
}
| 4,777 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/AwsPackageFixturesGeneratorIntegrationTest.java | package software.amazon.smithy.aws.typescript.codegen;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import software.amazon.smithy.build.MockManifest;
import software.amazon.smithy.build.PluginContext;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenPlugin;
import software.amazon.smithy.typescript.codegen.TypeScriptServerCodegenPlugin;
public class AwsPackageFixturesGeneratorIntegrationTest {
@Test
public void awsClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("NotSame.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#OriginalName"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
assertTrue(manifest.hasFile("LICENSE"));
assertTrue(manifest.hasFile("README.md"));
String readme = manifest.getFileString("README.md").get();
assertThat(readme, containsString("AWS SDK for JavaScript NotSame Client")); // Description
assertThat(readme, containsString("`NotSameClient`")); // Modular Client name
assertThat(readme, containsString("`GetFooCommand`")); // Command name
assertThat(readme, containsString("AWS.NotSame")); // v2 compatible client name
assertThat(readme, containsString("client.getFoo")); // v2 compatible operation name
}
@Test
public void genericClient() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.build())
.build();
new TypeScriptCodegenPlugin().execute(context);
assertTrue(manifest.hasFile("LICENSE"));
assertTrue(manifest.hasFile(".gitignore"));
assertFalse(manifest.hasFile("README.md"));
}
@Test
public void serverSdk() {
Model model = Model.assembler()
.addImport(getClass().getResource("SsdkExample.smithy"))
.discoverModels()
.assemble()
.unwrap();
MockManifest manifest = new MockManifest();
PluginContext context = PluginContext.builder()
.model(model)
.fileManifest(manifest)
.settings(Node.objectNodeBuilder()
.withMember("service", Node.from("smithy.example#SsdkExample"))
.withMember("package", Node.from("example"))
.withMember("packageVersion", Node.from("1.0.0"))
.withMember("disableDefaultValidation", Node.from(true))
.build())
.build();
new TypeScriptServerCodegenPlugin().execute(context);
assertTrue(manifest.hasFile("LICENSE"));
assertTrue(manifest.hasFile(".gitignore"));
assertFalse(manifest.hasFile("README.md"));
}
}
| 4,778 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/propertyaccess/PropertyAccessorTest.java | package software.amazon.smithy.aws.typescript.codegen.propertyaccess;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PropertyAccessorTest {
@Test
void getFrom() {
assertEquals("output.fileSystemId", PropertyAccessor.getFrom("output", "fileSystemId"));
assertEquals("output.__fileSystemId", PropertyAccessor.getFrom("output", "__fileSystemId"));
}
@Test
void getFromQuoted() {
assertEquals("output[\"0fileSystemId\"]", PropertyAccessor.getFrom("output", "0fileSystemId"));
assertEquals("output[\"file-system-id\"]", PropertyAccessor.getFrom("output", "file-system-id"));
}
@Test
void getFromExtraQuoted() {
assertEquals("output[`file\"system\"id`]", PropertyAccessor.getFrom("output", "file\"system\"id"));
}
} | 4,779 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/test/java/software/amazon/smithy/aws/typescript/codegen/validation/UnaryFunctionCallTest.java | package software.amazon.smithy.aws.typescript.codegen.validation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class UnaryFunctionCallTest {
@Test
void check() {
assertEquals(false, UnaryFunctionCall.check(""));
assertEquals(false, UnaryFunctionCall.check("5"));
assertEquals(false, UnaryFunctionCall.check("(param)"));
assertEquals(false, UnaryFunctionCall.check("x[5]"));
assertEquals(false, UnaryFunctionCall.check("new Date(timestamp)"));
assertEquals(false, UnaryFunctionCall.check("x(y(_))"));
assertEquals(false, UnaryFunctionCall.check("call(param).prop"));
assertEquals(false, UnaryFunctionCall.check("call(param, param2)"));
assertEquals(true, UnaryFunctionCall.check("_"));
assertEquals(true, UnaryFunctionCall.check("x()"));
assertEquals(true, UnaryFunctionCall.check("x(_)"));
assertEquals(true, UnaryFunctionCall.check("long_function_name(long_parameter_name)"));
assertEquals(true, UnaryFunctionCall.check("container.function(param)"));
assertEquals(true, UnaryFunctionCall.check("factory(param)(param2)"));
}
@Test
void toRef() {
assertEquals("_", UnaryFunctionCall.toRef("_"));
assertEquals("x", UnaryFunctionCall.toRef("x()"));
assertEquals("x", UnaryFunctionCall.toRef("x(_)"));
assertEquals("long_function_name", UnaryFunctionCall.toRef("long_function_name(long_parameter_name)"));
assertEquals("container.function", UnaryFunctionCall.toRef("container.function(param)"));
assertEquals("factory(param)", UnaryFunctionCall.toRef("factory(param)(param2)"));
}
} | 4,780 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/JsonRpcProtocolGenerator.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.Set;
import software.amazon.smithy.aws.traits.protocols.AwsQueryCompatibleTrait;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.HttpRpcProtocolGenerator;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles general components across the AWS JSON protocols that have do not have
* HTTP bindings. It handles reading and writing from document bodies, including
* generating any functions needed for performing serde.
*
* This builds on the foundations of the {@link HttpRpcProtocolGenerator} to handle
* standard components of the HTTP requests and responses.
*
* @see JsonShapeSerVisitor
* @see JsonShapeDeserVisitor
* @see JsonMemberSerVisitor
* @see JsonMemberDeserVisitor
* @see AwsProtocolUtils
*/
@SmithyInternalApi
abstract class JsonRpcProtocolGenerator extends HttpRpcProtocolGenerator {
/**
* Creates a AWS JSON RPC protocol generator.
*/
JsonRpcProtocolGenerator() {
// AWS JSON RPC protocols will attempt to parse error codes from response bodies.
super(true);
}
@Override
protected String getOperationPath(GenerationContext context, OperationShape operationShape) {
return "/";
}
protected Format getDocumentTimestampFormat() {
return Format.EPOCH_SECONDS;
}
@Override
protected void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes) {
boolean isAwsQueryCompat = context.getService().hasTrait(AwsQueryCompatibleTrait.class);
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes,
// AWS JSON does not support jsonName
new JsonShapeSerVisitor(
context,
(shape, name) -> name,
!isAwsQueryCompat && enableSerdeElision()
)
);
}
@Override
protected void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes,
// AWS JSON does not support jsonName
new JsonShapeDeserVisitor(
context,
(shape, name) -> name,
enableSerdeElision()
)
);
}
@Override
public void generateSharedComponents(GenerationContext context) {
super.generateSharedComponents(context);
AwsProtocolUtils.generateJsonParseBody(context);
AwsProtocolUtils.generateJsonParseErrorBody(context);
AwsProtocolUtils.addItempotencyAutofillImport(context);
TypeScriptWriter writer = context.getWriter();
writer.addUseImports(getApplicationProtocol().getResponseType());
writer.write(IoUtils.readUtf8Resource(getClass(), "load-json-error-code-stub.ts"));
if (context.getService().hasTrait(AwsQueryCompatibleTrait.class)) {
AwsProtocolUtils.generateJsonParseBodyWithQueryHeader(context);
}
}
@Override
protected void writeRequestHeaders(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
ServiceShape serviceShape = context.getService();
String operationName = operation.getId().getName(serviceShape);
if (AwsProtocolUtils.includeUnsignedPayloadSigV4Header(operation)) {
writer.openBlock("const headers: __HeaderBag = { ", " }", () -> {
AwsProtocolUtils.generateUnsignedPayloadSigV4Header(context, operation);
writer.write("...sharedHeaders($S)", operationName);
});
} else {
writer.write("const headers: __HeaderBag = sharedHeaders($S)", operationName);
}
}
@Override
protected void writeSharedRequestHeaders(GenerationContext context) {
ServiceShape serviceShape = context.getService();
TypeScriptWriter writer = context.getWriter();
writer.addImport("HeaderBag", "__HeaderBag", TypeScriptDependency.SMITHY_TYPES);
String targetHeader = serviceShape.getId().getName(serviceShape) + ".${operation}";
writer.openBlock("function sharedHeaders(operation: string): __HeaderBag { return {", "}};",
() -> {
writer.write("'content-type': $S,", getDocumentContentType());
// AWS JSON RPC protocols use a combination of the service and operation shape names,
// separated by a '.' character, for the target header.
writer.write("'x-amz-target': `$L`,", targetHeader);
}
);
}
@Override
protected void serializeInputDocument(
GenerationContext context,
OperationShape operation,
StructureShape inputStructure
) {
TypeScriptWriter writer = context.getWriter();
writer.write("body = JSON.stringify($L);", inputStructure.accept(getMemberSerVisitor(context, "input")));
}
private DocumentMemberSerVisitor getMemberSerVisitor(GenerationContext context, String dataSource) {
return new JsonMemberSerVisitor(context, dataSource, getDocumentTimestampFormat());
}
@Override
protected boolean writeUndefinedInputBody(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
writer.write("const body = '{}';");
return true;
}
@Override
protected void writeErrorCodeParser(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
if (context.getService().hasTrait(AwsQueryCompatibleTrait.class)) {
// Populate parsedOutput.body with 'Code' and 'Type' fields
// "x-amzn-query-error" header is available when AwsQueryCompatibleTrait is applied to a service
// The header value contains query error Code and Type joined by ';'
// E.g. "MalformedInput;Sender" or "InternalFailure;Receiver"
writer.write("populateBodyWithQueryCompatibility(parsedOutput, output.headers);");
}
// Outsource error code parsing since it's complex for this protocol.
writer.write("const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);");
}
@Override
protected void deserializeOutputDocument(
GenerationContext context,
OperationShape operation,
StructureShape outputStructure
) {
TypeScriptWriter writer = context.getWriter();
writer.write("contents = $L;", outputStructure.accept(getMemberDeserVisitor(context, "data")));
}
private DocumentMemberDeserVisitor getMemberDeserVisitor(GenerationContext context, String dataSource) {
return new JsonMemberDeserVisitor(context, dataSource, getDocumentTimestampFormat());
}
@Override
public void generateProtocolTests(GenerationContext context) {
AwsProtocolUtils.generateProtocolTests(this, context);
}
@Override
protected boolean enableSerdeElision() {
return true;
}
}
| 4,781 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DocumentAggregatedClientGenerator.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.nio.file.Paths;
import java.util.Set;
import java.util.TreeSet;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.codegen.core.SymbolReference;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.typescript.codegen.ApplicationProtocol;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.SmithyInternalApi;
import software.amazon.smithy.utils.StringUtils;
@SmithyInternalApi
final class DocumentAggregatedClientGenerator implements Runnable {
static final String CLIENT_CONFIG_SECTION = "client_config";
static final String CLIENT_PROPERTIES_SECTION = "client_properties";
static final String CLIENT_CONSTRUCTOR_SECTION = "client_constructor";
static final String CLIENT_DESTROY_SECTION = "client_destroy";
private final Model model;
private final SymbolProvider symbolProvider;
private final ServiceShape service;
private final TypeScriptWriter writer;
private final Symbol symbol;
private final String serviceName;
DocumentAggregatedClientGenerator(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
this.model = model;
this.symbolProvider = symbolProvider;
this.service = settings.getService(model);
this.writer = writer;
symbol = symbolProvider.toSymbol(service);
serviceName = symbol.getName();
}
@Override
public void run() {
writer.addImport(DocumentClientUtils.CLIENT_NAME,
DocumentClientUtils.CLIENT_NAME, Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString());
writer.writeDocs(DocumentClientUtils.getClientDocs());
writer.openBlock("export class $L extends $L {", "}",
DocumentClientUtils.CLIENT_FULL_NAME, DocumentClientUtils.CLIENT_NAME, () -> {
generateStaticFactoryFrom();
writer.write("");
generateOperations();
});
}
private void generateStaticFactoryFrom() {
String translateConfig = DocumentClientUtils.CLIENT_TRANSLATE_CONFIG_TYPE;
writer.addImport(serviceName, serviceName, "@aws-sdk/client-dynamodb");
writer.addImport(translateConfig, translateConfig, Paths.get(".", DocumentClientUtils.CLIENT_NAME).toString());
writer.openBlock("static from(client: $L, translateConfig?: $L) {", "}",
serviceName, translateConfig, () -> {
writer.write("return new $L(client, translateConfig);", DocumentClientUtils.CLIENT_FULL_NAME);
});
}
private void generateOperations() {
Set<OperationShape> containedOperations =
new TreeSet<>(TopDownIndex.of(model).getContainedOperations(service));
for (OperationShape operation : containedOperations) {
if (DocumentClientUtils.containsAttributeValue(model, symbolProvider, operation)) {
Symbol operationSymbol = symbolProvider.toSymbol(operation);
String name = DocumentClientUtils.getModifiedName(operationSymbol.getName());
String input = DocumentClientUtils.getModifiedName(
operationSymbol.expectProperty("inputType", Symbol.class).getName()
);
String output = DocumentClientUtils.getModifiedName(
operationSymbol.expectProperty("outputType", Symbol.class).getName()
);
SymbolReference options = ApplicationProtocol.createDefaultHttpApplicationProtocol().getOptionsType();
String commandFileLocation = String.format("./%s/%s",
DocumentClientUtils.CLIENT_COMMANDS_FOLDER, name);
writer.addImport(name, name, commandFileLocation);
writer.addImport(input, input, commandFileLocation);
writer.addImport(output, output, commandFileLocation);
String methodName = StringUtils.uncapitalize(
DocumentClientUtils.getModifiedName(operationSymbol.getName().replaceAll("Command$", ""))
);
// Generate a multiple overloaded methods for each command.
writer.writeDocs(DocumentClientUtils.getCommandDocs(operationSymbol.getName()));
writer.write("public $L(\n"
+ " args: $L,\n"
+ " options?: $T,\n"
+ "): Promise<$L>;", methodName, input, options, output);
writer.write("public $L(\n"
+ " args: $L,\n"
+ " cb: (err: any, data?: $L) => void\n"
+ "): void;", methodName, input, output);
writer.write("public $L(\n"
+ " args: $L,\n"
+ " options: $T,\n"
+ " cb: (err: any, data?: $L) => void\n"
+ "): void;", methodName, input, options, output);
writer.openBlock("public $1L(\n"
+ " args: $2L,\n"
+ " optionsOrCb?: $3T | ((err: any, data?: $4L) => void),\n"
+ " cb?: (err: any, data?: $4L) => void\n"
+ "): Promise<$4L> | void { ", "}",
methodName,
input,
options,
output,
() -> {
writer.write("const command = new $L(args);\n"
+ "if (typeof optionsOrCb === \"function\") {\n"
+ " this.send(command, optionsOrCb)\n"
+ "} else if (typeof cb === \"function\") {\n"
+ " if (typeof optionsOrCb !== \"object\")\n"
+ " throw new Error(`Expect http options but get $${typeof optionsOrCb}`)\n"
+ " this.send(command, optionsOrCb || {}, cb)\n"
+ "} else {\n"
+ " return this.send(command, optionsOrCb);\n"
+ "}", name);
});
writer.write("");
}
}
}
}
| 4,782 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddAwsAuthPlugin.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isSigV4Service;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Logger;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.auth.SigV4Trait;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.OptionalAuthTrait;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenContext;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Configure clients with AWS auth configurations and plugin.
*
* This is the existing control behavior for `experimentalIdentityAndAuth`.
*/
@SmithyInternalApi
public final class AddAwsAuthPlugin implements TypeScriptIntegration {
static final String STS_CLIENT_PREFIX = "sts-client-";
static final String ROLE_ASSUMERS_FILE = "defaultRoleAssumers";
static final String ROLE_ASSUMERS_TEST_FILE = "defaultRoleAssumers.spec";
static final String STS_ROLE_ASSUMERS_FILE = "defaultStsRoleAssumers";
private static final Logger LOGGER = Logger.getLogger(AddAwsAuthPlugin.class.getName());
/**
* Integration should only be used if `experimentalIdentityAndAuth` flag is false.
*/
@Override
public boolean matchesSettings(TypeScriptSettings settings) {
return !settings.getExperimentalIdentityAndAuth();
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
ServiceShape service = settings.getService(model);
if (!isSigV4Service(service) && isAwsService(service)) {
ServiceTrait serviceTrait = service.getTrait(ServiceTrait.class).get();
settings.setDefaultSigningName(
serviceTrait.getArnNamespace()
);
return;
}
if (!isSigV4Service(service)) {
return;
}
if (!isAwsService(service)) {
writer.writeDocs("The service name to use as the signing service for AWS Auth\n@internal")
.write("signingName?: string;\n");
}
if (!areAllOptionalAuthOperations(model, service)) {
writer.addImport("Credentials", "__Credentials", TypeScriptDependency.AWS_SDK_TYPES);
writer.writeDocs("Default credentials provider; Not available in browser runtime.\n"
+ "@internal");
writer.write("credentialDefaultProvider?: (input: any) => __Provider<__Credentials>;\n");
}
try {
ServiceTrait serviceTrait = service.getTrait(ServiceTrait.class).get();
settings.setDefaultSigningName(
service.getTrait(SigV4Trait.class).map(SigV4Trait::getName)
.orElse(serviceTrait.getArnNamespace())
);
} catch (Exception e) {
LOGGER.warning("Unable to set service default signing name. A SigV4 or Service trait is needed.");
}
}
// Only one of AwsAuth or SigV4Auth should be used
// AwsAuth - for AWS services
// SigV4Auth - for non AWS services
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "AwsAuth", HAS_CONFIG)
.servicePredicate((m, s) -> isSigV4Service(s)
&& isAwsService(s)
&& !testServiceId(s, "STS")
&& !areAllOptionalAuthOperations(m, s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "SigV4Auth", HAS_CONFIG)
.servicePredicate((m, s) -> isSigV4Service(s)
&& !isAwsService(s)
&& !areAllOptionalAuthOperations(m, s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.STS_MIDDLEWARE.dependency,
"StsAuth", HAS_CONFIG)
.additionalResolveFunctionParamsSupplier((m, s, o) -> new HashMap<String, Object>() {{
put("stsClientCtor", Symbol.builder().name("STSClient").build());
}})
.servicePredicate((m, s) -> testServiceId(s, "STS"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "AwsAuth", HAS_MIDDLEWARE)
// See operationUsesAwsAuth() below for AwsAuth Middleware customizations.
.servicePredicate((m, s) -> isSigV4Service(s)
&& isAwsService(s)
&& !testServiceId(s, "STS")
&& !hasOptionalAuthOperation(m, s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "SigV4Auth", HAS_MIDDLEWARE)
// See operationUsesAwsAuth() below for AwsAuth Middleware customizations.
.servicePredicate((m, s) -> isSigV4Service(s)
&& !isAwsService(s)
&& !hasOptionalAuthOperation(m, s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "AwsAuth", HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> isSigV4Service(s)
&& isAwsService(s)
&& operationUsesAwsAuth(m, s, o))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_SIGNING.dependency, "SigV4Auth", HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> isSigV4Service(s)
&& !isAwsService(s)
&& operationUsesAwsAuth(m, s, o))
.build()
);
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
LanguageTarget target
) {
ServiceShape service = settings.getService(model);
if (!isSigV4Service(service) || areAllOptionalAuthOperations(model, service)) {
return Collections.emptyMap();
}
switch (target) {
case SHARED:
if (isAwsService(service)) {
return Collections.emptyMap();
}
String signingService = service.getTrait(SigV4Trait.class).get().getName();
return MapUtils.of(
"signingName", writer -> {
writer.write("$S", signingService);
}
);
case BROWSER:
return MapUtils.of(
"credentialDefaultProvider", writer -> {
writer.write("((_: unknown) => () => Promise.reject(new Error(\"Credential is missing\")))");
}
);
case NODE:
return MapUtils.of(
"credentialDefaultProvider", writer -> {
if (!testServiceId(service, "STS")) {
writer.addDependency(AwsDependency.STS_CLIENT);
writer.addImport("decorateDefaultCredentialProvider", "decorateDefaultCredentialProvider",
AwsDependency.STS_CLIENT);
} else {
writer.addRelativeImport("decorateDefaultCredentialProvider",
"decorateDefaultCredentialProvider", Paths.get(".", CodegenUtils.SOURCE_FOLDER,
STS_ROLE_ASSUMERS_FILE));
}
writer.addDependency(AwsDependency.CREDENTIAL_PROVIDER_NODE);
writer.addImport("defaultProvider", "credentialDefaultProvider",
AwsDependency.CREDENTIAL_PROVIDER_NODE);
writer.write("decorateDefaultCredentialProvider(credentialDefaultProvider)");
}
);
default:
return Collections.emptyMap();
}
}
@Override
public void customize(TypeScriptCodegenContext codegenContext) {
TypeScriptSettings settings = codegenContext.settings();
Model model = codegenContext.model();
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory = codegenContext.writerDelegator()::useFileWriter;
writeAdditionalFiles(settings, model, writerFactory);
writerFactory.accept(Paths.get(CodegenUtils.SOURCE_FOLDER, "index.ts").toString(), writer -> {
writeAdditionalExports(settings, model, writer);
});
}
private void writeAdditionalFiles(
TypeScriptSettings settings,
Model model,
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory
) {
ServiceShape service = settings.getService(model);
if (!testServiceId(service, "STS")) {
return;
}
String noTouchNoticePrefix = "// Please do not touch this file. It's generated from template in:\n"
+ "// https://github.com/aws/aws-sdk-js-v3/blob/main/codegen/smithy-aws-typescript-codegen/"
+ "src/main/resources/software/amazon/smithy/aws/typescript/codegen/";
writerFactory.accept(Paths.get(CodegenUtils.SOURCE_FOLDER, "defaultRoleAssumers.ts").toString(), writer -> {
String resourceName = String.format("%s%s.ts", STS_CLIENT_PREFIX, ROLE_ASSUMERS_FILE);
String source = IoUtils.readUtf8Resource(getClass(), resourceName);
writer.write("$L$L", noTouchNoticePrefix, resourceName);
writer.write("$L", source);
});
writerFactory.accept(Paths.get(CodegenUtils.SOURCE_FOLDER, "defaultStsRoleAssumers.ts").toString(), writer -> {
String resourceName = String.format("%s%s.ts", STS_CLIENT_PREFIX, STS_ROLE_ASSUMERS_FILE);
String source = IoUtils.readUtf8Resource(getClass(), resourceName);
writer.write("$L$L", noTouchNoticePrefix, resourceName);
writer.write("$L", source);
});
writerFactory.accept("test/defaultRoleAssumers.spec.ts", writer -> {
String resourceName = String.format("%s%s.ts", STS_CLIENT_PREFIX, ROLE_ASSUMERS_TEST_FILE);
String source = IoUtils.readUtf8Resource(getClass(), resourceName);
writer.write("$L$L", noTouchNoticePrefix, resourceName);
writer.write("$L", source);
});
}
private void writeAdditionalExports(
TypeScriptSettings settings,
Model model,
TypeScriptWriter writer
) {
ServiceShape service = settings.getService(model);
if (!testServiceId(service, "STS")) {
return;
}
writer.write("export * from $S", Paths.get(".", ROLE_ASSUMERS_FILE).toString());
}
private static boolean testServiceId(Shape serviceShape, String expectedId) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals(expectedId);
}
private static boolean operationUsesAwsAuth(Model model, ServiceShape service, OperationShape operation) {
// STS doesn't need auth for AssumeRoleWithWebIdentity, AssumeRoleWithSAML.
// Remove when optionalAuth model update is published in 0533102932.
if (testServiceId(service, "STS")) {
Boolean isUnsignedCommand = SetUtils
.of("AssumeRoleWithWebIdentity", "AssumeRoleWithSAML")
.contains(operation.getId().getName(service));
return !isUnsignedCommand;
}
// optionalAuth trait doesn't require authentication.
if (hasOptionalAuthOperation(model, service)) {
return !operation.hasTrait(OptionalAuthTrait.class);
}
return false;
}
private static boolean hasOptionalAuthOperation(Model model, ServiceShape service) {
TopDownIndex topDownIndex = TopDownIndex.of(model);
Set<OperationShape> operations = topDownIndex.getContainedOperations(service);
for (OperationShape operation : operations) {
if (operation.hasTrait(OptionalAuthTrait.class)) {
return true;
}
}
return false;
}
private static boolean areAllOptionalAuthOperations(Model model, ServiceShape service) {
TopDownIndex topDownIndex = TopDownIndex.of(model);
Set<OperationShape> operations = topDownIndex.getContainedOperations(service);
for (OperationShape operation : operations) {
if (!operation.hasTrait(OptionalAuthTrait.class)) {
return false;
}
}
return true;
}
}
| 4,783 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsServiceIdIntegration.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.typescript.codegen.CodegenUtils;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.SmithyInternalApi;
import software.amazon.smithy.utils.StringUtils;
/**
* Uses the {@code aws.api#service$sdkId} trait property to determine the
* name of a service.
*/
@SmithyInternalApi
public final class AwsServiceIdIntegration implements TypeScriptIntegration {
private static final Logger LOGGER = Logger.getLogger(AwsServiceIdIntegration.class.getName());
@Override
public SymbolProvider decorateSymbolProvider(
Model model, TypeScriptSettings settings, SymbolProvider symbolProvider) {
return shape -> {
Symbol symbol = symbolProvider.toSymbol(shape);
if (!shape.isServiceShape() || !settings.generateClient()) {
return symbol;
}
// TODO: Should this WARNING be avoided somehow if client is not for an AWS service?
// If the SDK service ID trait is present, use that, otherwise fall back to
// the default naming strategy for the service.
return shape.getTrait(ServiceTrait.class)
.map(ServiceTrait::getSdkId)
.map(id -> updateServiceSymbol(symbol, id))
.orElseGet(() -> {
LOGGER.warning(String.format("No `%s` trait found on `%s`", ServiceTrait.ID, shape.getId()));
return symbol;
});
};
}
private static Symbol updateServiceSymbol(Symbol symbol, String serviceId) {
String name = Arrays.asList(serviceId.split(" ")).stream()
.map(StringUtils::capitalize)
.collect(Collectors.joining("")) + "Client";
return symbol.toBuilder()
.name(name)
.namespace(Paths.get(".", CodegenUtils.SOURCE_FOLDER, name).toString(), "/")
.definitionFile(Paths.get(".", CodegenUtils.SOURCE_FOLDER, name + ".ts").toString())
.build();
}
}
| 4,784 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/XmlMemberDeserVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.aws.typescript.codegen.visitor.MemberDeserVisitor;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.BigDecimalShape;
import software.amazon.smithy.model.shapes.BigIntegerShape;
import software.amazon.smithy.model.shapes.BooleanShape;
import software.amazon.smithy.model.shapes.ByteShape;
import software.amazon.smithy.model.shapes.DoubleShape;
import software.amazon.smithy.model.shapes.FloatShape;
import software.amazon.smithy.model.shapes.IntegerShape;
import software.amazon.smithy.model.shapes.LongShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShortShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Overrides several of the default implementations to handle XML document
* contents deserializing to strings instead of typed components:
*
* <ul>
* <li>Uses {@code strictParseFloat} on Float and Double shapes.</li>
* <li>Fails on BigDecimal and BigInteger shapes.</li>
* <li>Uses {@code strictParseInt} on other number shapes.</li>
* <li>Compares boolean shapes to the string {@code "true"} to generate a boolean.</li>
* </ul>
*
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
*/
@SmithyInternalApi
final class XmlMemberDeserVisitor extends MemberDeserVisitor {
private final MemberShape memberShape;
XmlMemberDeserVisitor(GenerationContext context, String dataSource, Format defaultTimestampFormat) {
this(context, null, dataSource, defaultTimestampFormat);
}
XmlMemberDeserVisitor(GenerationContext context,
MemberShape memberShape,
String dataSource,
Format defaultTimestampFormat) {
super(context, dataSource, defaultTimestampFormat);
this.memberShape = memberShape;
this.context = context;
}
@Override
public String booleanShape(BooleanShape shape) {
getContext().getWriter().addImport("parseBoolean", "__parseBoolean", TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__parseBoolean(" + getDataSource() + ")";
}
@Override
public String byteShape(ByteShape shape) {
getContext().getWriter().addImport("strictParseByte", "__strictParseByte",
TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__strictParseByte(" + getDataSource() + ") as number";
}
@Override
public String shortShape(ShortShape shape) {
getContext().getWriter().addImport("strictParseShort", "__strictParseShort",
TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__strictParseShort(" + getDataSource() + ") as number";
}
@Override
public String integerShape(IntegerShape shape) {
getContext().getWriter().addImport("strictParseInt32", "__strictParseInt32",
TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__strictParseInt32(" + getDataSource() + ") as number";
}
@Override
public String longShape(LongShape shape) {
getContext().getWriter().addImport("strictParseLong", "__strictParseLong",
TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__strictParseLong(" + getDataSource() + ") as number";
}
@Override
public String floatShape(FloatShape shape) {
return deserializeFloat();
}
@Override
public String doubleShape(DoubleShape shape) {
return deserializeFloat();
}
@Override
public String bigDecimalShape(BigDecimalShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String bigIntegerShape(BigIntegerShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
protected MemberShape getMemberShape() {
return memberShape;
}
private String unsupportedShape(Shape shape) {
throw new CodegenException(String.format("Cannot deserialize shape type %s on protocol, shape: %s.",
shape.getType(), shape.getId()));
}
private String deserializeFloat() {
getContext().getWriter().addImport("strictParseFloat", "__strictParseFloat",
TypeScriptDependency.AWS_SMITHY_CLIENT);
return "__strictParseFloat(" + getDataSource() + ") as number";
}
}
| 4,785 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsProtocolUtils.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.model.knowledge.HttpBinding.Location.DOCUMENT;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import software.amazon.smithy.aws.traits.auth.UnsignedPayloadTrait;
import software.amazon.smithy.model.knowledge.HttpBindingIndex;
import software.amazon.smithy.model.knowledge.NeighborProviderIndex;
import software.amazon.smithy.model.neighbor.Walker;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeVisitor;
import software.amazon.smithy.model.traits.IdempotencyTokenTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlNamespaceTrait;
import software.amazon.smithy.protocoltests.traits.HttpMalformedRequestTestCase;
import software.amazon.smithy.protocoltests.traits.HttpMessageTestCase;
import software.amazon.smithy.typescript.codegen.HttpProtocolTestGenerator;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.HttpProtocolGeneratorUtils;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Utility methods for generating AWS protocols.
*/
@SmithyInternalApi
final class AwsProtocolUtils {
private AwsProtocolUtils() {}
/**
* Writes an {@code 'x-amz-content-sha256' = 'UNSIGNED-PAYLOAD'} header for an
* {@code @aws.api#unsignedPayload} trait that specifies the {@code "aws.v4"} auth scheme.
*
* @see <a href=https://smithy.io/2.0/aws/aws-auth.html#aws-auth-unsignedpayload-trait>@aws.api#unsignedPayload trait</a>
*
* @param context The generation context.
* @param operation The operation being generated.
*/
static void generateUnsignedPayloadSigV4Header(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
if (includeUnsignedPayloadSigV4Header(operation)) {
writer.write("'x-amz-content-sha256': 'UNSIGNED-PAYLOAD',");
}
}
static boolean includeUnsignedPayloadSigV4Header(OperationShape operation) {
return operation.hasTrait(UnsignedPayloadTrait.ID);
}
/**
* Writes a serde function for a set of shapes using the passed visitor.
* This will walk the input set of shapes and invoke the visitor for any
* members of aggregate shapes in the set.
*
* @see software.amazon.smithy.typescript.codegen.integration.DocumentShapeSerVisitor
* @see software.amazon.smithy.typescript.codegen.integration.DocumentShapeDeserVisitor
*
* @param context The generation context.
* @param shapes A list of shapes to generate serde for, including their members.
* @param visitor A ShapeVisitor that generates a serde function for shapes.
*/
static void generateDocumentBodyShapeSerde(
GenerationContext context,
Set<Shape> shapes,
ShapeVisitor<Void> visitor
) {
// Walk all the shapes within those in the document and generate for them as well.
Walker shapeWalker = new Walker(NeighborProviderIndex.of(context.getModel()).getProvider());
Set<Shape> shapesToGenerate = new TreeSet<>(shapes);
shapes.forEach(shape -> shapesToGenerate.addAll(shapeWalker.walkShapes(shape)));
shapesToGenerate.forEach(shape -> shape.accept(visitor));
}
/**
* Writes a response body parser function for JSON protocols. This
* will parse a present body after converting it to utf-8.
*
* @param context The generation context.
*/
static void generateJsonParseBody(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Include a JSON body parser used to deserialize documents from HTTP responses.
writer.addImport("SerdeContext", "__SerdeContext", TypeScriptDependency.SMITHY_TYPES);
writer.openBlock("const parseBody = (streamBody: any, context: __SerdeContext): "
+ "any => collectBodyString(streamBody, context).then(encoded => {", "});", () -> {
writer.openBlock("if (encoded.length) {", "}", () -> {
writer.write("return JSON.parse(encoded);");
});
writer.write("return {};");
});
writer.write("");
}
static void generateJsonParseBodyWithQueryHeader(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
writer.addImport("HeaderBag", "__HeaderBag", TypeScriptDependency.SMITHY_TYPES);
writer.write(IoUtils.readUtf8Resource(
AwsProtocolUtils.class, "populate-body-with-query-compatibility-code-stub.ts"));
}
/**
* Writes a response body parser function for JSON errors. This
* will populate message field in parsed object, if it's not present.
*
* @param context The generation context.
*/
static void generateJsonParseErrorBody(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Include a JSON body parser used to deserialize documents from HTTP responses.
writer.addImport("SerdeContext", "__SerdeContext", TypeScriptDependency.SMITHY_TYPES);
writer.openBlock("const parseErrorBody = async (errorBody: any, context: __SerdeContext) => {",
"}", () -> {
writer.write("const value = await parseBody(errorBody, context);");
writer.write("value.message = value.message ?? value.Message;");
writer.write("return value;");
});
writer.write("");
}
/**
* Writes a response body parser function for XML protocols. This
* will parse a present body after converting it to utf-8.
*
* @param context The generation context.
*/
static void generateXmlParseBody(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Include an XML body parser used to deserialize documents from HTTP responses.
writer.addImport("SerdeContext", "__SerdeContext", TypeScriptDependency.SMITHY_TYPES);
writer.addImport("getValueFromTextNode", "__getValueFromTextNode", TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.addDependency(TypeScriptDependency.XML_PARSER);
writer.addImport("XMLParser", null, TypeScriptDependency.XML_PARSER);
writer.openBlock("const parseBody = (streamBody: any, context: __SerdeContext): "
+ "any => collectBodyString(streamBody, context).then(encoded => {", "});", () -> {
writer.openBlock("if (encoded.length) {", "}", () -> {
// Temporararily creating parser inside the function.
// Parser would be moved to runtime config in https://github.com/aws/aws-sdk-js-v3/issues/3979
writer.write("const parser = new XMLParser({ attributeNamePrefix: '', htmlEntities: true, "
+ "ignoreAttributes: false, ignoreDeclaration: true, parseTagValue: false, "
+ "trimValues: false, tagValueProcessor: (_: any, val: any) => "
+ "(val.trim() === '' && val.includes('\\n')) ? '': undefined });");
writer.write("parser.addEntity('#xD', '\\r');");
writer.write("parser.addEntity('#10', '\\n');");
writer.write("const parsedObj = parser.parse(encoded);");
writer.write("const textNodeName = '#text';");
writer.write("const key = Object.keys(parsedObj)[0];");
writer.write("const parsedObjToReturn = parsedObj[key];");
writer.openBlock("if (parsedObjToReturn[textNodeName]) {", "}", () -> {
writer.write("parsedObjToReturn[key] = parsedObjToReturn[textNodeName];");
writer.write("delete parsedObjToReturn[textNodeName];");
});
writer.write("return __getValueFromTextNode(parsedObjToReturn);");
});
writer.write("return {};");
});
writer.write("");
}
/**
* Writes a response body parser function for XML errors. This
* will populate message field in parsed object, if it's not present.
*
* @param context The generation context.
*/
static void generateXmlParseErrorBody(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Include a JSON body parser used to deserialize documents from HTTP responses.
writer.addImport("SerdeContext", "__SerdeContext", TypeScriptDependency.SMITHY_TYPES);
writer.openBlock("const parseErrorBody = async (errorBody: any, context: __SerdeContext) => {",
"}", () -> {
writer.write("const value = await parseBody(errorBody, context);");
writer.openBlock("if (value.Error) {", "}", () -> {
writer.write("value.Error.message = value.Error.message ?? value.Error.Message;");
});
writer.write("return value;");
});
writer.write("");
}
/**
* Writes a form urlencoded string builder function for query based protocols.
* This will escape the keys and values, combine those with an '=', and combine
* those strings with an '&'.
*
* @param context The generation context.
*/
static void generateBuildFormUrlencodedString(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Write a single function to handle combining a map in to a valid query string.
writer.addImport("extendedEncodeURIComponent", "__extendedEncodeURIComponent",
TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.openBlock("const buildFormUrlencodedString = (formEntries: Record<string, string>): "
+ "string => Object.entries(formEntries).map(", ").join(\"&\");",
() -> writer.write("([key, value]) => __extendedEncodeURIComponent(key) + '=' + "
+ "__extendedEncodeURIComponent(value)"));
writer.write("");
}
/**
* Writes a default body for query-based operations when the operation doesn't
* have an input defined.
*
* @param context The generation context.
* @param operation The operation being generated for.
* @return That a body variable was generated and should be set on the request.
*/
static boolean generateUndefinedQueryInputBody(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
// Set the form encoded string.
writer.openBlock("const body = buildFormUrlencodedString({", "});", () -> {
// Set the protocol required values.
ServiceShape serviceShape = context.getService();
writer.write("Action: $S,", operation.getId().getName(serviceShape));
writer.write("Version: $S,", serviceShape.getVersion());
});
return true;
}
/**
* Writes an attribute containing information about a Shape's optionally specified
* XML namespace configuration to an attribute of the passed node name.
*
* @param context The generation context.
* @param shape The shape to apply the namespace attribute to, if present on it.
* @param nodeName The node to apply the namespace attribute to.
* @return Returns if an XML namespace attribute was written.
*/
static boolean writeXmlNamespace(GenerationContext context, Shape shape, String nodeName) {
Optional<XmlNamespaceTrait> traitOptional = shape.getTrait(XmlNamespaceTrait.class);
if (!traitOptional.isPresent()) {
return false;
}
XmlNamespaceTrait trait = traitOptional.get();
TypeScriptWriter writer = context.getWriter();
String xmlns = "xmlns";
Optional<String> prefix = trait.getPrefix();
if (prefix.isPresent()) {
xmlns += ":" + prefix.get();
}
writer.write("$L.addAttribute($S, $S);", nodeName, xmlns, trait.getUri());
return true;
}
/**
* Imports a UUID v4 generating function used for auto-filling idempotency tokens.
*
* @param context The generation context.
*/
static void addItempotencyAutofillImport(GenerationContext context) {
// servers do not autogenerate idempotency tokens during deserialization
if (!context.getSettings().generateClient()) {
return;
}
context.getModel().shapes(MemberShape.class)
.filter(memberShape -> memberShape.hasTrait(IdempotencyTokenTrait.class))
.findFirst()
.ifPresent(memberShape -> {
TypeScriptWriter writer = context.getWriter();
// Include the uuid package and import the v4 function as our more clearly named alias.
writer.addDependency(TypeScriptDependency.UUID);
writer.addDependency(AwsDependency.UUID_GENERATOR_TYPES);
writer.addImport("v4", "generateIdempotencyToken", TypeScriptDependency.UUID);
});
}
/**
* Writes a statement that auto-fills the value of a member that is an idempotency
* token if it is undefined at the time of serialization.
*
* @param context The generation context.
* @param memberShape The member that may be an idempotency token.
* @param inputLocation The location of input data for the member.
*/
static void writeIdempotencyAutofill(GenerationContext context, MemberShape memberShape, String inputLocation) {
if (memberShape.hasTrait(IdempotencyTokenTrait.class)) {
TypeScriptWriter writer = context.getWriter();
writer.openBlock("if ($L === undefined) {", "}", inputLocation, () ->
writer.write("$L = generateIdempotencyToken();", inputLocation));
}
}
/**
* Gets a value provider for the timestamp member handling proper serialization
* formatting.
*
* @param context The generation context.
* @param memberShape The member that needs timestamp serialization.
* @param defaultFormat The timestamp format to default to.
* @param inputLocation The location of input data for the member.
* @return A string representing the proper value provider for this timestamp.
*/
static String getInputTimestampValueProvider(
GenerationContext context,
MemberShape memberShape,
Format defaultFormat,
String inputLocation
) {
HttpBindingIndex httpIndex = HttpBindingIndex.of(context.getModel());
TimestampFormatTrait.Format format = httpIndex.determineTimestampFormat(memberShape, DOCUMENT, defaultFormat);
return HttpProtocolGeneratorUtils.getTimestampInputParam(context, inputLocation, memberShape, format);
}
static void generateProtocolTests(ProtocolGenerator generator, GenerationContext context) {
new HttpProtocolTestGenerator(context,
generator,
AwsProtocolUtils::filterProtocolTests,
AwsProtocolUtils::filterMalformedRequestTests).run();
}
private static boolean filterProtocolTests(
ServiceShape service,
OperationShape operation,
HttpMessageTestCase testCase,
TypeScriptSettings settings
) {
// TODO: Remove when requestCompression has been implemented.
if (testCase.getId().startsWith("SDKAppliedContentEncoding_")
|| testCase.getId().startsWith("SDKAppendsGzipAndIgnoresHttpProvidedEncoding_")
|| testCase.getId().startsWith("SDKAppendedGzipAfterProvidedEncoding_")) {
return true;
}
// TODO: remove when there's a decision on separator to use
// https://github.com/awslabs/smithy/issues/1014
if (testCase.getId().equals("RestJsonInputAndOutputWithQuotedStringHeaders")) {
return true;
}
// TODO: implementation change pending.
List<String> extraUnionKey = Arrays.asList(
"RestXmlHttpPayloadWithUnsetUnion",
"RestJsonHttpPayloadWithUnsetUnion"
);
if (extraUnionKey.contains(testCase.getId())) {
return true;
}
return false;
}
private static boolean filterMalformedRequestTests(
ServiceShape service,
OperationShape operation,
HttpMalformedRequestTestCase testCase,
TypeScriptSettings settings
) {
// Handling overflow/underflow of longs in JS is extraordinarily tricky.
// Numbers are actually all 62-bit floats, and so any integral number is
// limited to 53 bits. In typical JS fashion, a value outside of this
// range just kinda silently bumbles on in some third state between valid
// and invalid. Infuriatingly, there doesn't seem to be a consistent way
// to detect this. We could *try* to do bounds checking, but the constants
// we use wouldn't necessarily work, so it could work in some environments
// but not others.
if (operation.getId().getName().equals("MalformedLong") && testCase.hasTag("underflow/overflow")) {
return true;
}
//TODO: we don't validate map values
if (testCase.getId().equals("RestJsonBodyMalformedMapNullValue")) {
return true;
}
//TODO: reenable when the SSDK uses RE2 and not built-in regex for pattern constraints
if (testCase.getId().equals("RestJsonMalformedPatternReDOSString")) {
return true;
}
// skipped to allow unambiguous type conversions to unblock minor type inconsistencies
List<String> typeCoercionCases = Arrays.asList(
"RestJsonBodyTimestampDefaultRejectsStringifiedEpochSeconds_case1",
"RestJsonBodyTimestampDefaultRejectsStringifiedEpochSeconds_case0",
"RestJsonBodyTimestampDefaultRejectsDateTime_case2",
"RestJsonBodyTimestampDefaultRejectsDateTime_case1",
"RestJsonBodyTimestampDefaultRejectsDateTime_case0",
"RestJsonBodyBooleanBadLiteral_case18",
"RestJsonBodyBooleanBadLiteral_case7",
"RestJsonBodyBooleanStringCoercion_case14",
"RestJsonBodyBooleanStringCoercion_case13",
"RestJsonBodyBooleanStringCoercion_case12",
"RestJsonBodyBooleanStringCoercion_case2",
"RestJsonBodyBooleanStringCoercion_case1",
"RestJsonBodyBooleanStringCoercion_case0"
);
if (typeCoercionCases.contains(testCase.getId())) {
return true;
}
return false;
}
}
| 4,786 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsRestXml.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.propertyaccess.PropertyAccessor.getFrom;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.aws.traits.protocols.RestXmlTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.codegen.core.SymbolReference;
import software.amazon.smithy.model.knowledge.HttpBinding;
import software.amazon.smithy.model.knowledge.HttpBinding.Location;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.StreamingTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.HttpBindingProtocolGenerator;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.rest-xml protocol for services. It handles reading and
* writing from document bodies, including generating any functions needed for
* performing serde.
*
* This builds on the foundations of the {@link HttpBindingProtocolGenerator} to handle
* components of binding to HTTP requests and responses.
*
* A service-specific customization exists for Amazon S3, which doesn't wrap the Error
* object in the response.
*
* TODO: Build an XmlIndex to handle pre-computing resolved values for names, namespaces, and more.
*
* @see XmlShapeSerVisitor
* @see XmlShapeDeserVisitor
* @see XmlMemberSerVisitor
* @see XmlMemberDeserVisitor
* @see AwsProtocolUtils
* @see <a href="https://smithy.io/2.0/spec/http-bindings.html">Smithy HTTP protocol bindings.</a>
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
*/
@SmithyInternalApi
final class AwsRestXml extends HttpBindingProtocolGenerator {
AwsRestXml() {
super(true);
}
@Override
protected String getDocumentContentType() {
return "application/xml";
}
@Override
protected Format getDocumentTimestampFormat() {
return Format.DATE_TIME;
}
@Override
public ShapeId getProtocol() {
return RestXmlTrait.ID;
}
@Override
public String getName() {
return "aws.rest-xml";
}
@Override
protected void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new XmlShapeSerVisitor(context));
}
@Override
protected void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new XmlShapeDeserVisitor(context));
}
@Override
public void generateSharedComponents(GenerationContext context) {
super.generateSharedComponents(context);
AwsProtocolUtils.generateXmlParseBody(context);
AwsProtocolUtils.generateXmlParseErrorBody(context);
AwsProtocolUtils.addItempotencyAutofillImport(context);
TypeScriptWriter writer = context.getWriter();
writer.addDependency(AwsDependency.XML_BUILDER);
// Generate a function that handles the complex rules around deserializing
// an error code from a rest-xml error.
SymbolReference responseType = getApplicationProtocol().getResponseType();
writer.openBlock("const loadRestXmlErrorCode = (\n"
+ " output: $T,\n"
+ " data: any\n"
+ "): string | undefined => {", "};", responseType, () -> {
// Attempt to fetch the error code from the specific location.
String errorCodeCheckLocation = getErrorBodyLocation(context, "data") + "?.Code";
String errorCodeAccessLocation = getErrorBodyLocation(context, "data") + ".Code";
writer.openBlock("if ($L !== undefined) {", "}", errorCodeCheckLocation, () -> {
writer.write("return $L;", errorCodeAccessLocation);
});
// Default a 404 status code to the NotFound code.
writer.openBlock("if (output.statusCode == 404) {", "}", () -> writer.write("return 'NotFound';"));
});
writer.write("");
}
@Override
protected String getErrorBodyLocation(GenerationContext context, String outputLocation) {
// Some services, S3 for example, don't wrap the Error object in the response.
if (usesWrappedErrorResponse(context)) {
return outputLocation + ".Error";
}
return outputLocation;
}
private boolean usesWrappedErrorResponse(GenerationContext context) {
return !context.getService().expectTrait(RestXmlTrait.class).isNoErrorWrapping();
}
@Override
protected void writeDefaultInputHeaders(GenerationContext context, OperationShape operation) {
AwsProtocolUtils.generateUnsignedPayloadSigV4Header(context, operation);
}
@Override
protected void serializeInputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
serializeDocumentBody(context, documentBindings);
}
@Override
protected void serializeInputEventDocumentPayload(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
writer.write("body = context.utf8Decoder(body.toString());");
}
@Override
protected void serializeOutputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
serializeDocumentBody(context, documentBindings);
}
@Override
protected void serializeErrorDocumentBody(
GenerationContext context,
StructureShape error,
List<HttpBinding> documentBindings
) {
serializeDocumentBody(context, documentBindings);
}
private void serializeDocumentBody(
GenerationContext context,
List<HttpBinding> documentBindings
) {
// Short circuit when we have no bindings.
TypeScriptWriter writer = context.getWriter();
if (documentBindings.isEmpty()) {
writer.write("body = \"\";");
return;
}
ServiceShape serviceShape = context.getService();
SymbolProvider symbolProvider = context.getSymbolProvider();
ShapeId inputShapeId = documentBindings.get(0).getMember().getContainer();
// Start with the XML declaration.
writer.write("body = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\";");
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
// Handle the @xmlName trait for the input shape.
StructureShape inputShape = context.getModel().expectShape(inputShapeId, StructureShape.class);
String nodeName = inputShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(inputShapeId.getName(serviceShape));
writer.write("const bodyNode = new __XmlNode($S);", nodeName);
// Add @xmlNamespace value of the service to the root node,
// fall back to one from the input shape.
boolean serviceXmlns = AwsProtocolUtils.writeXmlNamespace(context, serviceShape, "bodyNode");
if (!serviceXmlns) {
AwsProtocolUtils.writeXmlNamespace(context, inputShape, "bodyNode");
}
XmlShapeSerVisitor shapeSerVisitor = new XmlShapeSerVisitor(context);
for (HttpBinding binding : documentBindings) {
MemberShape memberShape = binding.getMember();
// The name of the member to get from the input shape.
String memberName = symbolProvider.toMemberName(memberShape);
String inputLocation = "input." + memberName;
// Handle if the member is an idempotency token that should be auto-filled.
AwsProtocolUtils.writeIdempotencyAutofill(context, memberShape, inputLocation);
writer.openBlock("if ($L !== undefined) {", "}", inputLocation, () -> {
shapeSerVisitor.serializeNamedMember(context, memberName, memberShape, () -> inputLocation);
});
}
// Append the generated XML to the body.
writer.write("body += bodyNode.toString();");
}
@Override
protected void serializeInputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
super.serializeInputPayload(context, operation, payloadBinding);
serializePayload(context, payloadBinding);
}
@Override
protected void serializeOutputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
super.serializeOutputPayload(context, operation, payloadBinding);
serializePayload(context, payloadBinding);
}
@Override
protected void serializeErrorPayload(
GenerationContext context,
StructureShape error,
HttpBinding payloadBinding
) {
super.serializeErrorPayload(context, error, payloadBinding);
serializePayload(context, payloadBinding);
}
private void serializePayload(
GenerationContext context,
HttpBinding payloadBinding
) {
SymbolProvider symbolProvider = context.getSymbolProvider();
TypeScriptWriter writer = context.getWriter();
MemberShape member = payloadBinding.getMember();
String memberName = symbolProvider.toMemberName(member);
writer.write("let contents: any;");
// Generate an if statement to set the body node if the member is set.
writer.openBlock("if ($L !== undefined) {", "}", getFrom("input", memberName), () -> {
Shape target = context.getModel().expectShape(member.getTarget());
writer.write("contents = $L;",
getInputValue(context, Location.PAYLOAD, getFrom("input", memberName), member, target));
String targetName = target.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(target.getId().getName());
if (
member.hasTrait(XmlNameTrait.class)
&& !member.getTrait(XmlNameTrait.class).get().getValue().equals(targetName)
) {
writer.write("contents = contents.withName($S);", member.getTrait(XmlNameTrait.class).get().getValue());
}
// XmlNode will serialize Structure and non-streaming Union payloads as XML documents.
if (target instanceof StructureShape
|| (target instanceof UnionShape && !target.hasTrait(StreamingTrait.class))
) {
// Start with the XML declaration.
writer.write("body = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\";");
// Add @xmlNamespace value of the service to the root node,
// fall back to one from the payload target.
boolean serviceXmlns = AwsProtocolUtils.writeXmlNamespace(context, context.getService(), "contents");
if (!serviceXmlns) {
AwsProtocolUtils.writeXmlNamespace(context, target, "contents");
}
// Append the generated XML to the body.
writer.write("body += contents.toString();");
} else {
// Strings and blobs (streaming or not) will not need any modification.
writer.write("body = contents;");
}
});
}
@Override
protected void writeErrorCodeParser(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Outsource error code parsing since it's complex for this protocol.
writer.write("const errorCode = loadRestXmlErrorCode(output, parsedOutput.body);");
}
@Override
protected void deserializeInputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
@Override
protected void deserializeOutputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
@Override
protected void deserializeErrorDocumentBody(
GenerationContext context,
StructureShape error,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
private void deserializeDocumentBody(
GenerationContext context,
List<HttpBinding> documentBindings
) {
SymbolProvider symbolProvider = context.getSymbolProvider();
XmlShapeDeserVisitor shapeVisitor = new XmlShapeDeserVisitor(context);
for (HttpBinding binding : documentBindings) {
MemberShape memberShape = binding.getMember();
// Grab the target shape so we can use a member deserializer on it.
Shape target = context.getModel().expectShape(memberShape.getTarget());
// The name of the member to get from the output shape.
String memberName = symbolProvider.toMemberName(memberShape);
shapeVisitor.deserializeNamedMember(context, memberName, memberShape, "data", (dataSource, visitor) -> {
TypeScriptWriter writer = context.getWriter();
writer.write("contents.$L = $L;", memberName, target.accept(visitor));
});
}
}
@Override
public void generateRequestSerializers(GenerationContext context) {
String serviceId = context.getService()
.getTrait(ServiceTrait.class)
.map(ServiceTrait::getSdkId)
.orElse("");
if (serviceId.equals("S3")) {
setContextParamDeduplicationParamControlSet(Collections.singleton("Bucket"));
} else {
setContextParamDeduplicationParamControlSet(Collections.emptySet());
}
super.generateRequestSerializers(context);
}
@Override
public void generateProtocolTests(GenerationContext context) {
AwsProtocolUtils.generateProtocolTests(this, context);
}
@Override
protected boolean requiresNumericEpochSecondsInPayload() {
return false;
}
}
| 4,787 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddDocumentClientPlugin.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.PaginatedTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenContext;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Generates Client and Commands for DynamoDB Document Client.
*/
@SmithyInternalApi
public class AddDocumentClientPlugin implements TypeScriptIntegration {
@Override
public void customize(TypeScriptCodegenContext codegenContext) {
TypeScriptSettings settings = codegenContext.settings();
Model model = codegenContext.model();
SymbolProvider symbolProvider = codegenContext.symbolProvider();
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory = codegenContext.writerDelegator()::useFileWriter;
writeAdditionalFiles(settings, model, symbolProvider, writerFactory);
}
private void writeAdditionalFiles(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory
) {
ServiceShape service = settings.getService(model);
if (testServiceId(service, "DynamoDB")) {
Set<OperationShape> containedOperations =
new TreeSet<>(TopDownIndex.of(model).getContainedOperations(service));
List<OperationShape> overridenOperationsList = new ArrayList<>();
for (OperationShape operation : containedOperations) {
String operationName = symbolProvider.toSymbol(operation).getName();
String commandFileName = String.format("%s%s/%s.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientUtils.CLIENT_COMMANDS_FOLDER, DocumentClientUtils.getModifiedName(operationName));
if (DocumentClientUtils.containsAttributeValue(model, symbolProvider, operation)) {
overridenOperationsList.add(operation);
writerFactory.accept(commandFileName,
writer -> new DocumentClientCommandGenerator(
settings, model, operation, symbolProvider, writer).run()
);
if (operation.hasTrait(PaginatedTrait.ID)) {
String paginationFileName = DocumentClientPaginationGenerator.getOutputFilelocation(operation);
writerFactory.accept(paginationFileName, paginationWriter ->
new DocumentClientPaginationGenerator(model, service, operation, symbolProvider,
paginationWriter).run());
}
}
}
writerFactory.accept(String.format("%s%s.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientUtils.CLIENT_NAME),
writer -> new DocumentBareBonesClientGenerator(settings, model, symbolProvider, writer).run());
writerFactory.accept(String.format("%s%s.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientUtils.CLIENT_FULL_NAME),
writer -> new DocumentAggregatedClientGenerator(settings, model, symbolProvider, writer).run());
writerFactory.accept(String.format("%s%s/index.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientUtils.CLIENT_COMMANDS_FOLDER), writer -> {
for (OperationShape operation : overridenOperationsList) {
String operationFileName = DocumentClientUtils.getModifiedName(
symbolProvider.toSymbol(operation).getName()
);
writer.write("export * from './$L';", operationFileName);
}
});
writerFactory.accept(String.format("%s%s/index.ts", DocumentClientUtils.DOC_CLIENT_PREFIX,
DocumentClientPaginationGenerator.PAGINATION_FOLDER), writer -> {
writer.write("export * from './Interfaces';");
for (OperationShape operation : overridenOperationsList) {
if (operation.hasTrait(PaginatedTrait.ID)) {
String paginationFileName =
DocumentClientUtils.getModifiedName(operation.getId().getName()) + "Paginator";
writer.write("export * from './$L';", paginationFileName);
}
}
});
String paginationInterfaceFileName = DocumentClientPaginationGenerator.getInterfaceFilelocation();
writerFactory.accept(paginationInterfaceFileName, paginationWriter ->
DocumentClientPaginationGenerator.generateServicePaginationInterfaces(paginationWriter));
writerFactory.accept(String.format("%sindex.ts", DocumentClientUtils.DOC_CLIENT_PREFIX), writer -> {
writer.write("export * from './commands';");
writer.write("export * from './pagination';");
writer.write("export * from './$L';", DocumentClientUtils.CLIENT_NAME);
writer.write("export * from './$L';", DocumentClientUtils.CLIENT_FULL_NAME);
writer.write("export { NumberValueImpl as NumberValue } from \"@aws-sdk/util-dynamodb\";");
});
}
}
private boolean testServiceId(Shape serviceShape, String expectedId) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals(expectedId);
}
}
| 4,788 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsPackageFixturesGeneratorIntegration.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isAwsService;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.TopDownIndex;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.DocumentationTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenContext;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
import software.amazon.smithy.utils.StringUtils;
@SmithyInternalApi
public final class AwsPackageFixturesGeneratorIntegration implements TypeScriptIntegration {
@Override
public void customize(TypeScriptCodegenContext codegenContext) {
TypeScriptSettings settings = codegenContext.settings();
Model model = codegenContext.model();
SymbolProvider symbolProvider = codegenContext.symbolProvider();
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory = codegenContext.writerDelegator()::useFileWriter;
writeAdditionalFiles(settings, model, symbolProvider, writerFactory);
}
private void writeAdditionalFiles(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
BiConsumer<String, Consumer<TypeScriptWriter>> writerFactory
) {
writerFactory.accept(".gitignore", writer -> {
String resource = IoUtils.readUtf8Resource(getClass(), "gitignore");
writer.write(resource);
});
writerFactory.accept("api-extractor.json", writer -> {
String resource = IoUtils.readUtf8Resource(getClass(), "api-extractor.json");
writer.write(resource);
});
writerFactory.accept("LICENSE", writer -> {
String resource = IoUtils.readUtf8Resource(getClass(), "LICENSE.template");
resource = resource.replace("${year}", Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));
writer.write(resource);
});
// TODO: May need to generate a different/modified README.md for these cases
if (!settings.generateClient() || !isAwsService(settings, model)) {
return;
}
writerFactory.accept("README.md", writer -> {
ServiceShape service = settings.getService(model);
String resource = IoUtils.readUtf8Resource(getClass(), "README.md.template");
resource = resource.replaceAll(Pattern.quote("${packageName}"), settings.getPackageName());
String sdkId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse(null);
String clientName = Arrays.asList(sdkId.split(" ")).stream()
.map(StringUtils::capitalize)
.collect(Collectors.joining(""));
resource = resource.replaceAll(Pattern.quote("${serviceId}"), clientName);
String rawDocumentation = service.getTrait(DocumentationTrait.class)
.map(DocumentationTrait::getValue)
.orElse("");
String documentation = Arrays.asList(rawDocumentation.split("\n")).stream()
.map(StringUtils::trim)
.collect(Collectors.joining("\n"));
resource = resource.replaceAll(Pattern.quote("${documentation}"), Matcher.quoteReplacement(documentation));
TopDownIndex topDownIndex = TopDownIndex.of(model);
OperationShape sampleOperation =
getPreferredExampleOperation(topDownIndex.getContainedOperations(service), model);
String operationName = sampleOperation.getId().getName(service);
resource = resource.replaceAll(Pattern.quote("${commandName}"), operationName);
resource = resource.replaceAll(Pattern.quote("${operationName}"),
operationName.substring(0, 1).toLowerCase() + operationName.substring(1));
writer.write(resource.replaceAll(Pattern.quote("$"), Matcher.quoteReplacement("$$")));
writeOperationList(writer, model, settings);
});
}
/**
* Tries to find an operation with a read-like name prefix "get", "describe", "list" etc.
* And has few or no required input parameters.
*/
private OperationShape getPreferredExampleOperation(Collection<OperationShape> operations, Model model) {
// Heuristic score used to rank the candidate operations.
long candidateOperationScore = Long.MIN_VALUE;
OperationShape candidateOperation = null;
for (OperationShape operation : operations) {
long heuristicScore = 0;
String name = operation.getId().getName().toLowerCase();
heuristicScore -= name.length() / 6;
if (name.startsWith("list")) {
heuristicScore += 20;
} else if (
name.startsWith("get")
|| name.startsWith("describe")
|| name.startsWith("retrieve")
|| name.startsWith("fetch")
) {
heuristicScore += 10;
} else if (
name.startsWith("delete")
|| name.startsWith("remove")
|| name.startsWith("stop")
|| name.startsWith("abort")
|| name.startsWith("terminate")
|| name.startsWith("deactivate")
|| name.startsWith("toggle")
) {
heuristicScore -= 20;
}
Optional<Shape> input = model.getShape(operation.getInputShape());
if (input.isPresent()) {
long inputFields = input.get().getAllMembers().values().stream()
.filter(member -> member.isRequired())
.count();
heuristicScore -= inputFields;
}
if (heuristicScore > candidateOperationScore) {
candidateOperation = operation;
candidateOperationScore = heuristicScore;
}
}
return candidateOperation;
}
private void writeOperationList(TypeScriptWriter writer, Model model, TypeScriptSettings settings) {
writer.write("## Client Commands (Operations List)");
writer.write("");
Set<OperationShape> operationShapesSet = model.getOperationShapes();
List<OperationShape> operationShapes = operationShapesSet.stream()
.sorted(Comparator.comparing(Shape::getId)).toList();
for (OperationShape operationShape : operationShapes) {
writer.write("<details>");
writer.write("<summary>");
writer.write("$L", operationShape.getId().getName());
writer.write("</summary>");
writer.write("");
// sample URL for command
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/classes/abortmultipartuploadcommand.html
String commandNameLowercase = operationShape.getId().getName().toLowerCase();
String serviceId = settings.getService(model).getTrait(ServiceTrait.class)
.orElseThrow(() -> new RuntimeException("Missing Service Trait during README doc generation."))
.getSdkId().toLowerCase().replaceAll(" ", "-");
String commandUrl = "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-"
+ serviceId + "/classes/" + commandNameLowercase + "command.html";
// sample URL for command input and outputs
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/abortmultipartuploadcommandinput.html
String commandInputUrl = "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-"
+ serviceId + "/interfaces/" + commandNameLowercase + "commandinput.html";
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/abortmultipartuploadcommandoutput.html
String commandOutputUrl = "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-"
+ serviceId + "/interfaces/" + commandNameLowercase + "commandoutput.html";
writer.write(
"[Command API Reference]($L) / [Input]($L) / [Output]($L)",
commandUrl,
commandInputUrl,
commandOutputUrl
);
writer.write("</details>");
}
}
}
| 4,789 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsQuery.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import software.amazon.smithy.aws.traits.protocols.AwsQueryErrorTrait;
import software.amazon.smithy.aws.traits.protocols.AwsQueryTrait;
import software.amazon.smithy.codegen.core.SymbolReference;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.HttpRpcProtocolGenerator;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles generating the aws.query protocol for services. It handles reading and
* writing from document bodies, including generating any functions needed for
* performing serde.
*
* This builds on the foundations of the {@link HttpRpcProtocolGenerator} to handle
* standard components of the HTTP requests and responses.
*
* @see QueryShapeSerVisitor
* @see XmlShapeDeserVisitor
* @see QueryMemberSerVisitor
* @see XmlMemberDeserVisitor
* @see AwsProtocolUtils
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
*/
@SmithyInternalApi
final class AwsQuery extends HttpRpcProtocolGenerator {
AwsQuery() {
// AWS Query protocols will attempt to parse error codes from response bodies.
super(true);
}
@Override
protected String getOperationPath(GenerationContext context, OperationShape operationShape) {
return "/";
}
@Override
public ShapeId getProtocol() {
return AwsQueryTrait.ID;
}
@Override
public String getName() {
return "aws.query";
}
@Override
protected String getDocumentContentType() {
return "application/x-www-form-urlencoded";
}
@Override
protected void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new QueryShapeSerVisitor(context));
}
@Override
protected void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new XmlShapeDeserVisitor(context));
}
@Override
public void generateSharedComponents(GenerationContext context) {
super.generateSharedComponents(context);
AwsProtocolUtils.generateXmlParseBody(context);
AwsProtocolUtils.generateXmlParseErrorBody(context);
AwsProtocolUtils.generateBuildFormUrlencodedString(context);
AwsProtocolUtils.addItempotencyAutofillImport(context);
TypeScriptWriter writer = context.getWriter();
// Generate a function that handles the complex rules around deserializing
// an error code from an xml error body.
SymbolReference responseType = getApplicationProtocol().getResponseType();
writer.openBlock("const loadQueryErrorCode = (\n"
+ " output: $T,\n"
+ " data: any\n"
+ "): string | undefined => {", "};", responseType, () -> {
// Attempt to fetch the error code from the specific location.
String errorCodeCheckLocation = getErrorBodyLocation(context, "data") + "?.Code";
String errorCodeAccessLocation = getErrorBodyLocation(context, "data") + ".Code";
writer.openBlock("if ($L !== undefined) {", "}", errorCodeCheckLocation, () -> {
writer.write("return $L;", errorCodeAccessLocation);
});
// Default a 404 status code to the NotFound code.
writer.openBlock("if (output.statusCode == 404) {", "}", () -> writer.write("return 'NotFound';"));
});
writer.write("");
}
@Override
protected String getErrorBodyLocation(GenerationContext context, String outputLocation) {
return outputLocation + ".Error";
}
@Override
protected void writeRequestHeaders(GenerationContext context, OperationShape operation) {
TypeScriptWriter writer = context.getWriter();
if (AwsProtocolUtils.includeUnsignedPayloadSigV4Header(operation)) {
writer.openBlock("const headers: __HeaderBag = { ", " }", () -> {
AwsProtocolUtils.generateUnsignedPayloadSigV4Header(context, operation);
writer.write("...SHARED_HEADERS");
});
} else {
writer.write("const headers: __HeaderBag = SHARED_HEADERS;");
}
}
@Override
protected void serializeInputDocument(
GenerationContext context,
OperationShape operation,
StructureShape inputStructure
) {
TypeScriptWriter writer = context.getWriter();
// Set the form encoded string.
writer.openBlock("body = buildFormUrlencodedString({", "});", () -> {
// Gather all the explicit input entries.
writer.write("...$L,",
inputStructure.accept(new QueryMemberSerVisitor(context, "input", Format.DATE_TIME)));
// Set the protocol required values.
ServiceShape serviceShape = context.getService();
writer.write("Action: $S,", operation.getId().getName(serviceShape));
writer.write("Version: $S,", serviceShape.getVersion());
});
}
@Override
protected boolean writeUndefinedInputBody(GenerationContext context, OperationShape operation) {
return AwsProtocolUtils.generateUndefinedQueryInputBody(context, operation);
}
@Override
protected void writeErrorCodeParser(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Outsource error code parsing since it's complex for this protocol.
writer.write("const errorCode = loadQueryErrorCode(output, parsedOutput.body);");
}
@Override
protected void deserializeOutputDocument(
GenerationContext context,
OperationShape operation,
StructureShape outputStructure
) {
TypeScriptWriter writer = context.getWriter();
String dataSource = "data." + operation.getId().getName(context.getService()) + "Result";
writer.write("contents = $L;",
outputStructure.accept(new XmlMemberDeserVisitor(context, dataSource, Format.DATE_TIME)));
}
@Override
public void generateProtocolTests(GenerationContext context) {
AwsProtocolUtils.generateProtocolTests(this, context);
}
@Override
public Map<String, ShapeId> getOperationErrors(GenerationContext context, OperationShape operation) {
Map<String, ShapeId> errors = new TreeMap<>();
operation.getErrors().forEach(shapeId -> {
Shape errorShape = context.getModel().expectShape(shapeId);
String errorName = shapeId.getName(context.getService());
Optional<AwsQueryErrorTrait> errorShapeTrait = errorShape.getTrait(AwsQueryErrorTrait.class);
if (errorShapeTrait.isPresent()) {
errors.put(errorShapeTrait.get().getCode(), shapeId);
} else {
errors.put(errorName, shapeId);
}
});
return errors;
}
}
| 4,790 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddS3ControlDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.traits.RequiredTrait;
import software.amazon.smithy.model.transform.ModelTransformer;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Add S3Control customization.
*/
@SmithyInternalApi
public class AddS3ControlDependency implements TypeScriptIntegration {
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_CONTROL_MIDDLEWARE.dependency, "S3Control", HAS_CONFIG)
.servicePredicate((m, s) -> isS3Control(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_CONTROL_MIDDLEWARE.dependency,
"HostPrefixDeduplication", HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isS3Control(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(
AwsDependency.S3_CONTROL_MIDDLEWARE.dependency,
"ProcessArnables",
HAS_MIDDLEWARE
)
.operationPredicate((m, s, o) -> isS3Control(s) && isArnableOperation(o, s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(
AwsDependency.S3_CONTROL_MIDDLEWARE.dependency,
"RedirectFromPostId",
HAS_MIDDLEWARE
)
.operationPredicate((m, s, o) -> isS3Control(s) && !isArnableOperation(o, s))
.build());
}
@Override
public Model preprocessModel(Model model, TypeScriptSettings settings) {
if (!isS3Control(settings.getService(model))) {
return model;
}
ServiceShape serviceShape = model.expectShape(settings.getService(), ServiceShape.class);
return ModelTransformer.create().mapShapes(model, shape -> {
Optional<MemberShape> modified = shape.asMemberShape()
.filter(memberShape -> memberShape.getTarget().getName(serviceShape).equals("AccountId"))
.filter(memberShape -> model.expectShape(memberShape.getTarget()).isStringShape())
.filter(memberShape -> memberShape.isRequired())
.map(memberShape -> Shape.shapeToBuilder(memberShape).removeTrait(RequiredTrait.ID).build());
return modified.isPresent() ? modified.get() : shape;
});
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings, Model model,
SymbolProvider symbolProvider, LanguageTarget target
) {
if (!isS3Control(settings.getService(model))) {
return Collections.emptyMap();
}
if (settings.getExperimentalIdentityAndAuth()) {
return Collections.emptyMap();
}
// feat(experimentalIdentityAndAuth): control branch for S3 Control signingEscapePath
switch (target) {
case SHARED:
return MapUtils.of("signingEscapePath", writer -> {
writer.write("false");
});
case NODE:
default:
return Collections.emptyMap();
}
}
private static boolean isS3Control(ServiceShape service) {
String serviceId = service.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("");
return serviceId.equals("S3 Control");
}
private static boolean isArnableOperation(OperationShape operation, ServiceShape serviceShape) {
String operationName = operation.getId().getName(serviceShape);
return !operationName.equals("CreateBucket") && !operationName.equals("ListRegionalBuckets");
}
}
| 4,791 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/XmlMemberSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.BigDecimalShape;
import software.amazon.smithy.model.shapes.BigIntegerShape;
import software.amazon.smithy.model.shapes.BlobShape;
import software.amazon.smithy.model.shapes.BooleanShape;
import software.amazon.smithy.model.shapes.ByteShape;
import software.amazon.smithy.model.shapes.DoubleShape;
import software.amazon.smithy.model.shapes.FloatShape;
import software.amazon.smithy.model.shapes.IntegerShape;
import software.amazon.smithy.model.shapes.LongShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShortShape;
import software.amazon.smithy.model.shapes.StringShape;
import software.amazon.smithy.model.shapes.TimestampShape;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Overrides several of the default implementations to handle XML document
* contents serializing as XmlText entities instead of typed components:
*
* <ul>
* <li>All scalar types are set as contents of an XmlText inside an XmlNode.</li>
* <li>Fails on BigDecimal and BigInteger shapes.</li>
* </ul>
*
* TODO: Work out support for BigDecimal and BigInteger, natively or through a library.
*
* @see <a href="https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings">Smithy XML traits.</a>
*/
@SmithyInternalApi
final class XmlMemberSerVisitor extends DocumentMemberSerVisitor {
private final GenerationContext context;
XmlMemberSerVisitor(GenerationContext context, String dataSource, Format defaultTimestampFormat) {
super(context, dataSource, defaultTimestampFormat);
this.context = context;
}
@Override
public String stringShape(StringShape shape) {
return getAsXmlText(shape, super.stringShape(shape));
}
@Override
public String blobShape(BlobShape shape) {
return getAsXmlText(shape, super.blobShape(shape));
}
@Override
public String timestampShape(TimestampShape shape) {
return getAsXmlText(shape, super.timestampShape(shape));
}
@Override
public String booleanShape(BooleanShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String byteShape(ByteShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String shortShape(ShortShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String integerShape(IntegerShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String longShape(LongShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String floatShape(FloatShape shape) {
return serializeSimpleScalar(shape);
}
@Override
public String doubleShape(DoubleShape shape) {
return serializeSimpleScalar(shape);
}
private String serializeSimpleScalar(Shape shape) {
return getAsXmlText(shape, "String(" + getDataSource() + ")");
}
String getAsXmlText(Shape shape, String dataSource) {
// Handle the @xmlName trait for the shape itself.
String nodeName = shape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.orElse(shape.getId().getName(context.getService()));
TypeScriptWriter writer = getContext().getWriter();
writer.addImport("XmlNode", "__XmlNode", "@aws-sdk/xml-builder");
writer.addImport("XmlText", "__XmlText", "@aws-sdk/xml-builder");
return "__XmlNode.of(\"" + nodeName + "\", " + dataSource + ")";
}
@Override
public String bigDecimalShape(BigDecimalShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
@Override
public String bigIntegerShape(BigIntegerShape shape) {
// Fail instead of losing precision through Number.
return unsupportedShape(shape);
}
private String unsupportedShape(Shape shape) {
throw new CodegenException(String.format("Cannot serialize shape type %s on protocol, shape: %s.",
shape.getType(), shape.getId()));
}
}
| 4,792 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddS3Config.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isEndpointsV2Service;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Logger;
import software.amazon.smithy.aws.traits.ServiceTrait;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.knowledge.OperationIndex;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.ServiceShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.DocumentationTrait;
import software.amazon.smithy.typescript.codegen.LanguageTarget;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SetUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* AWS S3 client configuration.
*/
@SmithyInternalApi
public final class AddS3Config implements TypeScriptIntegration {
private static final Logger LOGGER = Logger.getLogger(AddS3Config.class.getName());
private static final Set<String> SSEC_INPUT_KEYS = SetUtils.of("SSECustomerKey", "CopySourceSSECustomerKey");
private static final Set<String> BUCKET_ENDPOINT_INPUT_KEYS = SetUtils.of("Bucket");
private static final Set<String> NON_BUCKET_ENDPOINT_OPERATIONS = SetUtils.of(
"CreateBucket",
"DeleteBucket",
"ListBuckets"
);
private static final Set<String> EXCEPTIONS_OF_200_OPERATIONS = SetUtils.of(
"CopyObject",
"UploadPartCopy",
"CompleteMultipartUpload"
);
private static final String CRT_NOTIFICATION = "<p>Note: To supply the Multi-region Access Point (MRAP) to Bucket,"
+ " you need to install the \"@aws-sdk/signature-v4-crt\" package to your project dependencies. \n"
+ "For more information, please go to https://github.com/aws/aws-sdk-js-v3#known-issues</p>";
@Override
public Model preprocessModel(Model model, TypeScriptSettings settings) {
ServiceShape serviceShape = settings.getService(model);
if (!isS3(serviceShape)) {
return model;
}
Model.Builder modelBuilder = model.toBuilder();
Set<StructureShape> inputShapes = new HashSet<>();
for (ShapeId operationId : serviceShape.getAllOperations()) {
OperationShape operationShape = model.expectShape(operationId, OperationShape.class);
if (NON_BUCKET_ENDPOINT_OPERATIONS.contains(operationShape.getId().getName(serviceShape))) {
continue;
}
operationShape.getInput().ifPresent(inputShapeId -> {
StructureShape inputShape = model.expectShape(inputShapeId, StructureShape.class);
inputShape.getMember("Bucket").ifPresent(bucketMember -> {
bucketMember.getTrait(DocumentationTrait.class).ifPresent(documentationTrait -> {
StructureShape.Builder inputShapeBuilder = inputShape.toBuilder();
MemberShape.Builder builder = MemberShape.shapeToBuilder(bucketMember);
String newDocString = documentationTrait.getValue() + "\n" + CRT_NOTIFICATION;
MemberShape newMemberShape = builder.addTrait(new DocumentationTrait(newDocString)).build();
inputShapeBuilder.addMember(newMemberShape);
inputShapes.add(inputShapeBuilder.build());
});
});
});
}
LOGGER.info("Patching " + inputShapes.size() + " input shapes with CRT notification");
return modelBuilder.addShapes(inputShapes).build();
}
@Override
public void addConfigInterfaceFields(
TypeScriptSettings settings,
Model model,
SymbolProvider symbolProvider,
TypeScriptWriter writer
) {
ServiceShape service = settings.getService(model);
if (!isS3(service)) {
return;
}
if (settings.getExperimentalIdentityAndAuth()) {
return;
}
// feat(experimentalIdentityAndAuth): control branch for S3 Config interface fields
writer.writeDocs("Whether to escape request path when signing the request.")
.write("signingEscapePath?: boolean;\n");
writer.writeDocs(
"Whether to override the request region with the region inferred from requested resource's ARN."
+ " Defaults to false.")
.addImport("Provider", "Provider", TypeScriptDependency.SMITHY_TYPES)
.write("useArnRegion?: boolean | Provider<boolean>;");
}
@Override
public Map<String, Consumer<TypeScriptWriter>> getRuntimeConfigWriters(
TypeScriptSettings settings, Model model,
SymbolProvider symbolProvider, LanguageTarget target
) {
if (!isS3(settings.getService(model))) {
return Collections.emptyMap();
}
if (settings.getExperimentalIdentityAndAuth()) {
return Collections.emptyMap();
}
// feat(experimentalIdentityAndAuth): control branch for S3 Config runtime config
switch (target) {
case SHARED:
return MapUtils.of("signingEscapePath", writer -> {
writer.write("false");
}, "useArnRegion", writer -> {
writer.write("false");
}, "signerConstructor", writer -> {
writer.addDependency(AwsDependency.SIGNATURE_V4_MULTIREGION)
.addImport("SignatureV4MultiRegion", "SignatureV4MultiRegion",
AwsDependency.SIGNATURE_V4_MULTIREGION.packageName)
.write("SignatureV4MultiRegion");
});
case NODE:
return MapUtils.of("useArnRegion", writer -> {
writer.addDependency(TypeScriptDependency.NODE_CONFIG_PROVIDER)
.addImport("loadConfig", "loadNodeConfig",
TypeScriptDependency.NODE_CONFIG_PROVIDER.packageName)
.addDependency(AwsDependency.BUCKET_ENDPOINT_MIDDLEWARE)
.addImport("NODE_USE_ARN_REGION_CONFIG_OPTIONS", "NODE_USE_ARN_REGION_CONFIG_OPTIONS",
AwsDependency.BUCKET_ENDPOINT_MIDDLEWARE.packageName)
.write("loadNodeConfig(NODE_USE_ARN_REGION_CONFIG_OPTIONS)");
});
default:
return Collections.emptyMap();
}
}
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_MIDDLEWARE.dependency, "ValidateBucketName",
HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isS3(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_MIDDLEWARE.dependency, "CheckContentLengthHeader",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> isS3(s) && o.getId().getName(s).equals("PutObject"))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_MIDDLEWARE.dependency, "throw200Exceptions",
HAS_MIDDLEWARE)
.operationPredicate(
(m, s, o) -> EXCEPTIONS_OF_200_OPERATIONS.contains(o.getId().getName(s))
&& isS3(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.ADD_EXPECT_CONTINUE.dependency, "AddExpectContinue",
HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isS3(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.SSEC_MIDDLEWARE.dependency, "Ssec", HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> containsInputMembers(m, o, SSEC_INPUT_KEYS)
&& isS3(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.LOCATION_CONSTRAINT.dependency, "LocationConstraint",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> o.getId().getName(s).equals("CreateBucket")
&& isS3(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_MIDDLEWARE.dependency, "S3",
HAS_CONFIG)
.servicePredicate((m, s) -> isS3(s) && isEndpointsV2Service(s))
.build(),
/*
* BUCKET_ENDPOINT_MIDDLEWARE needs two separate plugins. The first resolves the config in the client.
* The second applies the middleware to bucket endpoint operations.
*/
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.BUCKET_ENDPOINT_MIDDLEWARE.dependency, "BucketEndpoint",
HAS_CONFIG)
.servicePredicate((m, s) -> isS3(s) && !isEndpointsV2Service(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.BUCKET_ENDPOINT_MIDDLEWARE.dependency, "BucketEndpoint",
HAS_MIDDLEWARE)
.operationPredicate((m, s, o) -> !NON_BUCKET_ENDPOINT_OPERATIONS.contains(o.getId().getName(s))
&& isS3(s)
&& !isEndpointsV2Service(s)
&& containsInputMembers(m, o, BUCKET_ENDPOINT_INPUT_KEYS))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.S3_MIDDLEWARE.dependency, "RegionRedirectMiddleware",
HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isS3(s))
.build()
);
}
private static boolean containsInputMembers(
Model model,
OperationShape operationShape,
Set<String> expectedMemberNames
) {
OperationIndex operationIndex = OperationIndex.of(model);
return operationIndex.getInput(operationShape)
.filter(input -> input.getMemberNames().stream().anyMatch(expectedMemberNames::contains))
.isPresent();
}
private static boolean isS3(Shape serviceShape) {
return serviceShape.getTrait(ServiceTrait.class).map(ServiceTrait::getSdkId).orElse("").equals("S3");
}
}
| 4,793 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/RestJsonProtocolGenerator.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.List;
import java.util.Set;
import software.amazon.smithy.aws.traits.protocols.AwsQueryCompatibleTrait;
import software.amazon.smithy.aws.typescript.codegen.validation.UnaryFunctionCall;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.knowledge.HttpBinding;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.IdempotencyTokenTrait;
import software.amazon.smithy.model.traits.JsonNameTrait;
import software.amazon.smithy.model.traits.StreamingTrait;
import software.amazon.smithy.model.traits.TimestampFormatTrait;
import software.amazon.smithy.typescript.codegen.TypeScriptDependency;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberDeserVisitor;
import software.amazon.smithy.typescript.codegen.integration.DocumentMemberSerVisitor;
import software.amazon.smithy.typescript.codegen.integration.HttpBindingProtocolGenerator;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Handles general components across the AWS JSON protocols that have HTTP bindings.
* It handles reading and writing from document bodies, including generating any
* functions needed for performing serde.
*
* This builds on the foundations of the {@link HttpBindingProtocolGenerator} to handle
* components of binding to HTTP requests and responses.
*
* @see JsonShapeSerVisitor
* @see JsonShapeDeserVisitor
* @see JsonMemberSerVisitor
* @see JsonMemberDeserVisitor
* @see AwsProtocolUtils
* @see <a href="https://smithy.io/2.0/spec/http-bindings.html">Smithy HTTP protocol bindings.</a>
*/
@SmithyInternalApi
abstract class RestJsonProtocolGenerator extends HttpBindingProtocolGenerator {
/**
* Creates a AWS JSON RPC protocol generator.
*/
RestJsonProtocolGenerator() {
super(true);
}
@Override
protected TimestampFormatTrait.Format getDocumentTimestampFormat() {
return TimestampFormatTrait.Format.EPOCH_SECONDS;
}
@Override
protected void generateDocumentBodyShapeSerializers(GenerationContext context, Set<Shape> shapes) {
boolean isAwsQueryCompat = context.getService().hasTrait(AwsQueryCompatibleTrait.class);
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new JsonShapeSerVisitor(context,
(!context.getSettings().generateServerSdk() && !isAwsQueryCompat && enableSerdeElision())));
}
@Override
protected void generateDocumentBodyShapeDeserializers(GenerationContext context, Set<Shape> shapes) {
AwsProtocolUtils.generateDocumentBodyShapeSerde(context, shapes, new JsonShapeDeserVisitor(context,
(!context.getSettings().generateServerSdk() && enableSerdeElision())));
}
@Override
public void generateSharedComponents(GenerationContext context) {
super.generateSharedComponents(context);
AwsProtocolUtils.generateJsonParseBody(context);
AwsProtocolUtils.generateJsonParseErrorBody(context);
AwsProtocolUtils.addItempotencyAutofillImport(context);
TypeScriptWriter writer = context.getWriter();
writer.addUseImports(getApplicationProtocol().getResponseType());
writer.addImport("take", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.write(IoUtils.readUtf8Resource(getClass(), "load-json-error-code-stub.ts"));
}
@Override
protected void importUnionDeserializer(TypeScriptWriter writer) {
writer.addDependency(AwsDependency.AWS_SDK_CORE);
writer.addImport("awsExpectUnion", "__expectUnion", AwsDependency.AWS_SDK_CORE);
}
@Override
protected void writeDefaultInputHeaders(GenerationContext context, OperationShape operation) {
AwsProtocolUtils.generateUnsignedPayloadSigV4Header(context, operation);
}
@Override
protected void writeDefaultErrorHeaders(GenerationContext context, StructureShape error) {
context.getWriter().write("'x-amzn-errortype': $S,", error.getId().getName());
}
@Override
protected void serializeInputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
// Short circuit when we have no bindings.
TypeScriptWriter writer = context.getWriter();
if (documentBindings.isEmpty()) {
writer.write("body = \"\";");
return;
}
serializeDocumentBody(context, documentBindings);
}
@Override
protected void serializeOutputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
// Short circuit when we have no bindings.
TypeScriptWriter writer = context.getWriter();
if (documentBindings.isEmpty()) {
writer.write("body = \"{}\";");
return;
}
serializeDocumentBody(context, documentBindings);
}
@Override
protected void serializeErrorDocumentBody(
GenerationContext context,
StructureShape error,
List<HttpBinding> documentBindings
) {
// Short circuit when we have no bindings.
TypeScriptWriter writer = context.getWriter();
if (documentBindings.isEmpty()) {
writer.write("body = \"{}\";");
return;
}
serializeDocumentBody(context, documentBindings);
}
private void serializeDocumentBody(GenerationContext context, List<HttpBinding> documentBindings) {
TypeScriptWriter writer = context.getWriter();
SymbolProvider symbolProvider = context.getSymbolProvider();
writer.addImport("take", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.openBlock("body = JSON.stringify(take(input, {", "}));", () -> {
for (HttpBinding binding : documentBindings) {
MemberShape memberShape = binding.getMember();
// The name of the member to get from the input shape.
String memberName = symbolProvider.toMemberName(memberShape);
String inputLocation = "input." + memberName;
// Use the jsonName trait value if present, otherwise use the member name.
String wireName = memberShape.getTrait(JsonNameTrait.class)
.map(JsonNameTrait::getValue)
.orElseGet(binding::getLocationName);
boolean hasJsonName = memberShape.hasTrait(JsonNameTrait.class);
Shape target = context.getModel().expectShape(memberShape.getTarget());
// Handle @timestampFormat on members not just the targeted shape.
String valueProvider = "_ => " + (memberShape.hasTrait(TimestampFormatTrait.class)
? AwsProtocolUtils.getInputTimestampValueProvider(context, memberShape,
getDocumentTimestampFormat(), "_")
: target.accept(getMemberSerVisitor(context, "_")));
if (hasJsonName) {
if (memberShape.hasTrait(IdempotencyTokenTrait.class)) {
writer.write("'$L': [true,_ => _ ?? generateIdempotencyToken(),`$L`],",
wireName, memberName);
} else {
if (valueProvider.equals("_ => _")) {
writer.write("'$L': [,,`$L`],", wireName, memberName);
} else {
writer.write("'$1L': [, $2L, `$3L`],", wireName, valueProvider, memberName);
}
}
} else {
if (memberShape.hasTrait(IdempotencyTokenTrait.class)) {
writer.write("'$L': [true, _ => _ ?? generateIdempotencyToken()],", wireName);
} else {
if (valueProvider.equals("_ => _")) {
writer.write("'$1L': [],", wireName);
} else {
writer.write("'$1L': $2L,", wireName, valueProvider);
}
}
}
}
});
}
@Override
protected void serializeInputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
super.serializeInputPayload(context, operation, payloadBinding);
serializePayload(context, payloadBinding);
}
@Override
protected void serializeInputEventDocumentPayload(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
writer.write("body = context.utf8Decoder(JSON.stringify(body));");
}
@Override
protected void serializeOutputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
super.serializeOutputPayload(context, operation, payloadBinding);
serializePayload(context, payloadBinding);
}
@Override
protected void serializeErrorPayload(
GenerationContext context,
StructureShape error,
HttpBinding payloadBinding
) {
super.serializeErrorPayload(context, error, payloadBinding);
serializePayload(context, payloadBinding);
}
private void serializePayload(
GenerationContext context,
HttpBinding payloadBinding
) {
TypeScriptWriter writer = context.getWriter();
MemberShape payloadMember = payloadBinding.getMember();
Shape target = context.getModel().expectShape(payloadMember.getTarget());
// When payload target is a structure or union but payload is not a stream, default
// to an empty JSON body instead of an undefined body and make sure any structure or union
// content ends up as a JSON string.
if (target instanceof StructureShape
|| (target instanceof UnionShape && !target.hasTrait(StreamingTrait.class))
) {
writer.openBlock("if (body === undefined) {", "}", () -> writer.write("body = {};"));
writer.write("body = JSON.stringify(body);");
} else if (target instanceof DocumentShape) {
// Contents of documents need to be JSON encoded as well.
writer.write("body = JSON.stringify(body);");
}
}
private DocumentMemberSerVisitor getMemberSerVisitor(GenerationContext context, String dataSource) {
return new JsonMemberSerVisitor(context, dataSource, getDocumentTimestampFormat());
}
protected boolean shouldWriteDefaultOutputBody(GenerationContext context, OperationShape operation) {
// Operations that have any defined output shape should always send a default body.
return operation.getOutput().isPresent();
}
@Override
protected void writeErrorCodeParser(GenerationContext context) {
TypeScriptWriter writer = context.getWriter();
// Outsource error code parsing since it's complex for this protocol.
writer.write("const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);");
}
@Override
protected void deserializeInputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
@Override
protected void deserializeOutputDocumentBody(
GenerationContext context,
OperationShape operation,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
@Override
protected void deserializeErrorDocumentBody(
GenerationContext context,
StructureShape error,
List<HttpBinding> documentBindings
) {
deserializeDocumentBody(context, documentBindings);
}
private void deserializeDocumentBody(
GenerationContext context,
List<HttpBinding> documentBindings
) {
TypeScriptWriter writer = context.getWriter();
SymbolProvider symbolProvider = context.getSymbolProvider();
writer.addImport("take", null, TypeScriptDependency.AWS_SMITHY_CLIENT);
writer.openBlock("const doc = take(data, {", "});", () -> {
for (HttpBinding binding : documentBindings) {
Shape target = context.getModel().expectShape(binding.getMember().getTarget());
// The name of the member to get from the input shape.
String memberName = symbolProvider.toMemberName(binding.getMember());
// Use the jsonName trait value if present, otherwise use the member name.
String wireName = binding.getMember().getTrait(JsonNameTrait.class)
.map(JsonNameTrait::getValue)
.orElseGet(binding::getLocationName);
boolean hasJsonName = binding.getMember().hasTrait(JsonNameTrait.class);
String valueExpression = target.accept(
getMemberDeserVisitor(context, binding.getMember(), "_"));
boolean isUnaryCall = UnaryFunctionCall.check(valueExpression);
if (hasJsonName) {
if (isUnaryCall) {
writer.write("'$L': [, $L, `$L`],",
memberName, UnaryFunctionCall.toRef(valueExpression), wireName);
} else {
writer.write("'$L': [, _ => $L, `$L`],", memberName, valueExpression, wireName);
}
} else {
if (isUnaryCall) {
writer.write("'$L': $L,", wireName, UnaryFunctionCall.toRef(valueExpression));
} else {
writer.write("'$L': _ => $L,", wireName, valueExpression);
}
}
}
});
writer.write("Object.assign(contents, doc);");
}
@Override
protected HttpBinding deserializeInputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
HttpBinding returnedBinding = super.deserializeInputPayload(context, operation, payloadBinding);
readPayload(context, payloadBinding);
return returnedBinding;
}
@Override
protected HttpBinding deserializeOutputPayload(
GenerationContext context,
OperationShape operation,
HttpBinding payloadBinding
) {
HttpBinding returnedBinding = super.deserializeOutputPayload(context, operation, payloadBinding);
readPayload(context, payloadBinding);
return returnedBinding;
}
@Override
protected HttpBinding deserializeErrorPayload(
GenerationContext context,
StructureShape error,
HttpBinding payloadBinding
) {
HttpBinding returnedBinding = super.deserializeErrorPayload(context, error, payloadBinding);
readPayload(context, payloadBinding);
return returnedBinding;
}
protected void readPayload(
GenerationContext context,
HttpBinding payloadBinding
) {
TypeScriptWriter writer = context.getWriter();
Shape target = context.getModel().expectShape(payloadBinding.getMember().getTarget());
// Decode the body from a JSON string.
if (target instanceof DocumentShape) {
writer.write("contents.$L = JSON.parse(data);", payloadBinding.getMemberName());
}
}
private DocumentMemberDeserVisitor getMemberDeserVisitor(GenerationContext context,
MemberShape memberShape,
String dataSource) {
return new JsonMemberDeserVisitor(context, memberShape, dataSource, getDocumentTimestampFormat());
}
@Override
public void generateProtocolTests(GenerationContext context) {
AwsProtocolUtils.generateProtocolTests(this, context);
}
@Override
protected boolean requiresNumericEpochSecondsInPayload() {
return true;
}
@Override
protected boolean enableSerdeElision() {
return true;
}
}
| 4,794 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/Ec2ShapeSerVisitor.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.Optional;
import software.amazon.smithy.aws.traits.protocols.Ec2QueryNameTrait;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.shapes.DocumentShape;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.ShapeType;
import software.amazon.smithy.model.traits.TimestampFormatTrait.Format;
import software.amazon.smithy.model.traits.XmlNameTrait;
import software.amazon.smithy.typescript.codegen.integration.ProtocolGenerator.GenerationContext;
import software.amazon.smithy.utils.SmithyInternalApi;
import software.amazon.smithy.utils.StringUtils;
/**
* Visitor to generate serialization functions for shapes in form-urlencoded
* based document bodies specific to aws.ec2.
*
* This class uses the implementations provided by {@code QueryShapeSerVisitor} but with
* the following protocol specific customizations for aws.ec2:
*
* <ul>
* <li>aws.ec2 flattens all lists, sets, and maps regardless of the {@code @xmlFlattened} trait.</li>
* <li>aws.ec2 respects the {@code @ec2QueryName} trait, then the {@code xmlName}
* trait value with the first letter capitalized.</li>
* </ul>
*
* Timestamps are serialized to {@link Format}.DATE_TIME by default.
*
* @see AwsEc2
* @see QueryShapeSerVisitor
* @see <a href="https://smithy.io/2.0/aws/protocols/aws-ec2-query-protocol.html#aws-protocols-ec2queryname-trait">Smithy EC2 Query Name trait.</a>
*/
@SmithyInternalApi
final class Ec2ShapeSerVisitor extends QueryShapeSerVisitor {
Ec2ShapeSerVisitor(GenerationContext context) {
super(context);
}
@Override
protected void serializeDocument(GenerationContext context, DocumentShape shape) {
throw new CodegenException(String.format(
"Cannot serialize Document types in the aws.ec2 protocol, shape: %s.", shape.getId()));
}
@Override
protected String getMemberSerializedLocationName(MemberShape memberShape, String defaultValue) {
// The serialization for aws.ec2 prioritizes the @ec2QueryName trait for serialization.
Optional<Ec2QueryNameTrait> trait = memberShape.getTrait(Ec2QueryNameTrait.class);
if (trait.isPresent()) {
return trait.get().getValue();
}
// Fall back to the capitalized @xmlName trait if present on the member,
// otherwise use the capitalized default value.
return memberShape.getTrait(XmlNameTrait.class)
.map(XmlNameTrait::getValue)
.map(StringUtils::capitalize)
.orElseGet(() -> StringUtils.capitalize(defaultValue));
}
@Override
protected boolean isFlattenedMember(GenerationContext context, MemberShape memberShape) {
// All lists, sets, and maps are flattened in aws.ec2.
ShapeType targetType = context.getModel().expectShape(memberShape.getTarget()).getType();
return targetType == ShapeType.LIST || targetType == ShapeType.SET || targetType == ShapeType.MAP;
}
}
| 4,795 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/DefaultsModeConfigGenerator.java | /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.smithy.codegen.core.CodegenException;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.node.NumberNode;
import software.amazon.smithy.model.node.ObjectNode;
import software.amazon.smithy.model.node.StringNode;
import software.amazon.smithy.typescript.codegen.TypeScriptWriter;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Generate the default configs provider based the default mode config supplied by user.
*/
@SmithyInternalApi
final class DefaultsModeConfigGenerator {
static final String DEFAULTS_MODE_DOC_INTRODUCTION = "Option determining how certain default configuration options "
+ "are resolved in the SDK. It can be one of the value listed below:\n";
static final String INTERNAL_INTERFACES_BLOCK = ""
+ "/**\n"
+ " * @internal\n"
+ " */\n"
+ "export type ResolvedDefaultsMode = Exclude<DefaultsMode, \"auto\">;\n"
+ "\n"
+ "/**\n"
+ " * @internal\n"
+ " */\n"
+ "export interface DefaultsModeConfigs {\n"
+ " retryMode?: string;\n"
+ " connectionTimeout?: number;\n"
+ " requestTimeout?: number;\n"
+ "}\n";
private DefaultsModeConfigGenerator() {}
public static void main(String[] args) throws IOException {
// file has been moved to smithy-typescript
if (true) {
return;
}
Path outputPath = Paths.get(args[0]);
TypeScriptWriter writer = new TypeScriptWriter(outputPath.toString());
String defaultsConfigJson = IoUtils.readUtf8Resource(DefaultsModeConfigGenerator.class,
"sdk-default-configuration.json");
ObjectNode defaultsConfigData = Node.parse(defaultsConfigJson).expectObjectNode();
ObjectNode baseNode = defaultsConfigData.expectObjectMember("base");
ObjectNode modesNode = defaultsConfigData.expectObjectMember("modes");
writer.writeDocs("@internal");
writer.openBlock(
"export const loadConfigsForDefaultMode = (mode: ResolvedDefaultsMode): DefaultsModeConfigs => {", "}\n",
() -> {
writer.openBlock("switch (mode) {", "}", () -> {
modesNode.getMembers().forEach((name, mode) -> {
writer.write("case $S:", name.getValue());
DefaultsMode defaultsMode = new DefaultsMode(baseNode, mode.expectObjectNode());
writer.indent();
defaultsMode.useWriter(writer);
writer.dedent();
});
writer.write("default:");
writer.indent().write("return {};").dedent();
});
});
ObjectNode docNode = defaultsConfigData.expectObjectMember("documentation").expectObjectMember("modes");
List<String> defaultsModes = new LinkedList<String>();
StringBuilder defaultsModeDoc = new StringBuilder(DEFAULTS_MODE_DOC_INTRODUCTION);
for (Entry<StringNode, Node> map : docNode.getMembers().entrySet()) {
String modeName = map.getKey().getValue();
String doc = map.getValue().expectStringNode().getValue();
defaultsModes.add(modeName);
defaultsModeDoc.append(String.format("* `\"%s\"`: %s%n", modeName, doc));
}
defaultsModeDoc.append("\n@default \"legacy\"");
writer.writeDocs(defaultsModeDoc.toString());
writer.write("export type DefaultsMode = $L;\n",
String.join(" | ", defaultsModes.stream().map((mod) -> {
return "\"" + mod + "\""; }).collect(Collectors.toList())));
writer.write(INTERNAL_INTERFACES_BLOCK);
boolean exists = outputPath.toFile().createNewFile();
if (exists) {
// PASS
}
Files.write(outputPath, writer.toString().getBytes(StandardCharsets.UTF_8));
}
enum Modifier {
MULTIPLY("multiply"),
ADD("add"),
OVERRIDE("override");
private final String label;
Modifier(String label) {
this.label = label;
}
}
private static final class DefaultsMode {
private Optional<String> retryMode;
private Optional<Number> connectTimeoutInMillis;
private Optional<Number> httpRequestTimeoutInMillis;
private DefaultsMode(ObjectNode base) {
retryMode = base.getStringMember("retryMode").map(StringNode::getValue);
connectTimeoutInMillis = base.getNumberMember("connectTimeoutInMillis").map(NumberNode::getValue);
httpRequestTimeoutInMillis = base.getNumberMember("httpRequestTimeoutInMillis").map(NumberNode::getValue);
}
private DefaultsMode(ObjectNode base, ObjectNode mode) {
this(base);
mode.getObjectMember("retryMode").ifPresent((overrideNode) -> {
overrideNode.getMembers().forEach((modifier, value) -> {
String modifierName = modifier.getValue().toUpperCase();
this.modifyRetryMode(Modifier.valueOf(modifierName), value.expectStringNode().getValue());
});
});
mode.getObjectMember("connectTimeoutInMillis").ifPresent((overrideNode) -> {
overrideNode.getMembers().forEach((modifier, value) -> {
String modifierName = modifier.getValue().toUpperCase();
this.modifyConnectTimeoutInMillis(Modifier.valueOf(modifierName),
value.expectNumberNode().getValue());
});
});
mode.getObjectMember("httpRequestTimeoutInMillis").ifPresent((overrideNode) -> {
overrideNode.getMembers().forEach((modifier, value) -> {
String modifierName = modifier.getValue().toUpperCase();
this.modifyHttpRequestTimeoutInMillis(Modifier.valueOf(modifierName),
value.expectNumberNode().getValue());
});
});
}
private void modifyRetryMode(Modifier modifier, String val) {
if (modifier == Modifier.OVERRIDE) {
this.retryMode = Optional.of(val);
} else {
throw new CodegenException(
String.format("Unexpected modifier to retryMode, expect \"override\", got %s", modifier.label));
}
}
private Number modifyNumber(Number left, Modifier modifier, Number right) {
switch (modifier) {
case OVERRIDE:
return right;
case ADD:
return (int) left + (int) right;
case MULTIPLY:
return (int) ((int) left * (float) right);
default:
throw new CodegenException("Unexpected modifier");
}
}
private void modifyConnectTimeoutInMillis(Modifier modifier, Number val) {
this.connectTimeoutInMillis = Optional.of(
this.modifyNumber(this.connectTimeoutInMillis.orElse(null), modifier, val));
}
private void modifyHttpRequestTimeoutInMillis(Modifier modifier, Number val) {
this.httpRequestTimeoutInMillis = Optional.of(
this.modifyNumber(this.httpRequestTimeoutInMillis.orElse(null), modifier, val));
}
public void useWriter(TypeScriptWriter writer) {
writer.openBlock("return {", "};", () -> {
this.retryMode.ifPresent((retryMode) -> {
writer.write("retryMode: $S,", this.retryMode);
});
this.connectTimeoutInMillis.ifPresent((connectTimeoutInMillis) -> {
writer.write("connectionTimeout: $L,", connectTimeoutInMillis);
});
this.httpRequestTimeoutInMillis.ifPresent((httpRequestTimeoutInMillis) -> {
writer.write("requestTimeout: $L,", httpRequestTimeoutInMillis);
});
});
}
}
}
| 4,796 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddEndpointsV2ParameterNameMap.java | /*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import java.util.Map;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.typescript.codegen.TypeScriptCodegenContext;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.endpointsV2.EndpointsParamNameMap;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.MapUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
@SmithyInternalApi
public class AddEndpointsV2ParameterNameMap implements TypeScriptIntegration {
public static final Map<String, String> NAME_MAP = MapUtils.of(
"Region", "region",
"UseFIPS", "useFipsEndpoint",
"UseDualStack", "useDualstackEndpoint",
"ForcePathStyle", "forcePathStyle",
"Accelerate", "useAccelerateEndpoint",
"DisableMRAP", "disableMultiregionAccessPoints",
"DisableMultiRegionAccessPoints", "disableMultiregionAccessPoints",
"UseArnRegion", "useArnRegion",
"Endpoint", "endpoint",
"UseGlobalEndpoint", "useGlobalEndpoint"
);
public AddEndpointsV2ParameterNameMap() {
setParameterNameMapForAws();
}
@Override
public Model preprocessModel(Model model, TypeScriptSettings settings) {
setParameterNameMapForAws();
return TypeScriptIntegration.super.preprocessModel(model, settings);
}
@Override
public void customize(TypeScriptCodegenContext codegenContext) {
setParameterNameMapForAws();
}
private static void setParameterNameMapForAws() {
EndpointsParamNameMap.addNameMapping(NAME_MAP);
}
}
| 4,797 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AddTokenAuthPlugin.java | /*
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.aws.typescript.codegen.AwsTraitsUtils.isHttpBearerAuthService;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_CONFIG;
import static software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin.Convention.HAS_MIDDLEWARE;
import java.util.List;
import software.amazon.smithy.typescript.codegen.TypeScriptSettings;
import software.amazon.smithy.typescript.codegen.integration.RuntimeClientPlugin;
import software.amazon.smithy.typescript.codegen.integration.TypeScriptIntegration;
import software.amazon.smithy.utils.ListUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* Configure clients with Token auth configurations and plugin.
*
* This is the existing control behavior for `experimentalIdentityAndAuth`.
*/
@SmithyInternalApi
public final class AddTokenAuthPlugin implements TypeScriptIntegration {
/**
* Integration should only be used if `experimentalIdentityAndAuth` flag is false.
*/
@Override
public boolean matchesSettings(TypeScriptSettings settings) {
return !settings.getExperimentalIdentityAndAuth();
}
@Override
public List<RuntimeClientPlugin> getClientPlugins() {
return ListUtils.of(
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_TOKEN.dependency, "Token", HAS_CONFIG)
.servicePredicate((m, s) -> isHttpBearerAuthService(s))
.build(),
RuntimeClientPlugin.builder()
.withConventions(AwsDependency.MIDDLEWARE_TOKEN.dependency, "Token", HAS_MIDDLEWARE)
.servicePredicate((m, s) -> isHttpBearerAuthService(s))
.build()
);
}
}
| 4,798 |
0 | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript | Create_ds/aws-sdk-js-v3/codegen/smithy-aws-typescript-codegen/src/main/java/software/amazon/smithy/aws/typescript/codegen/AwsDependency.java | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.aws.typescript.codegen;
import static software.amazon.smithy.typescript.codegen.TypeScriptDependency.DEV_DEPENDENCY;
import static software.amazon.smithy.typescript.codegen.TypeScriptDependency.NORMAL_DEPENDENCY;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import software.amazon.smithy.codegen.core.SymbolDependency;
import software.amazon.smithy.typescript.codegen.Dependency;
import software.amazon.smithy.utils.IoUtils;
import software.amazon.smithy.utils.SmithyInternalApi;
/**
* This enum should define all TypeScript dependencies that are introduced by
* this package.
*/
@SmithyInternalApi
public enum AwsDependency implements Dependency {
AWS_SDK_CORE(NORMAL_DEPENDENCY, "@aws-sdk/core"),
MIDDLEWARE_SIGNING(NORMAL_DEPENDENCY, "@aws-sdk/middleware-signing"),
MIDDLEWARE_TOKEN(NORMAL_DEPENDENCY, "@aws-sdk/middleware-token"),
CREDENTIAL_PROVIDER_NODE(NORMAL_DEPENDENCY, "@aws-sdk/credential-provider-node"),
ACCEPT_HEADER(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-api-gateway"),
S3_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-s3"),
ADD_EXPECT_CONTINUE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-expect-continue"),
GLACIER_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-glacier"),
MACHINELEARNING_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-machinelearning"),
S3_CONTROL_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-s3-control"),
SSEC_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-ssec"),
RDS_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-rds"),
LOCATION_CONSTRAINT(NORMAL_DEPENDENCY, "@aws-sdk/middleware-location-constraint"),
ROUTE53_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-route53"),
EC2_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-ec2"),
BUCKET_ENDPOINT_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-bucket-endpoint"),
MIDDLEWARE_HOST_HEADER(NORMAL_DEPENDENCY, "@aws-sdk/middleware-host-header"),
SQS_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-sqs"),
BODY_CHECKSUM_GENERATOR_BROWSER(NORMAL_DEPENDENCY, "@aws-sdk/body-checksum-browser"),
BODY_CHECKSUM_GENERATOR_NODE(NORMAL_DEPENDENCY, "@aws-sdk/body-checksum-node"),
XML_BUILDER(NORMAL_DEPENDENCY, "@aws-sdk/xml-builder"),
XML_PARSER(NORMAL_DEPENDENCY, "fast-xml-parser", "4.2.5"),
UUID_GENERATOR(NORMAL_DEPENDENCY, "uuid", "^8.3.2"),
UUID_GENERATOR_TYPES(DEV_DEPENDENCY, "@types/uuid", "^8.3.0"),
MIDDLEWARE_EVENTSTREAM(NORMAL_DEPENDENCY, "@aws-sdk/middleware-eventstream"),
AWS_SDK_EVENTSTREAM_HANDLER_NODE(NORMAL_DEPENDENCY, "@aws-sdk/eventstream-handler-node"),
TRANSCRIBE_STREAMING_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-transcribe-streaming"),
STS_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-sdk-sts"),
STS_CLIENT(NORMAL_DEPENDENCY, "@aws-sdk/client-sts"),
MIDDLEWARE_LOGGER(NORMAL_DEPENDENCY, "@aws-sdk/middleware-logger"),
MIDDLEWARE_USER_AGENT("dependencies", "@aws-sdk/middleware-user-agent"),
AWS_SDK_UTIL_USER_AGENT_BROWSER(NORMAL_DEPENDENCY, "@aws-sdk/util-user-agent-browser"),
AWS_SDK_UTIL_USER_AGENT_NODE(NORMAL_DEPENDENCY, "@aws-sdk/util-user-agent-node"),
MIDDLEWARE_ENDPOINT_DISCOVERY(NORMAL_DEPENDENCY, "@aws-sdk/middleware-endpoint-discovery"),
AWS_CRYPTO_SHA1_BROWSER(NORMAL_DEPENDENCY, "@aws-crypto/sha1-browser", "3.0.0"),
SIGNATURE_V4_MULTIREGION(NORMAL_DEPENDENCY, "@aws-sdk/signature-v4-multi-region"),
RECURSION_DETECTION_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-recursion-detection"),
MIDDLEWARE_WEBSOCKET(NORMAL_DEPENDENCY, "@aws-sdk/middleware-websocket"),
// Conditionally added when httpChecksum trait is present
@Deprecated MD5_BROWSER(NORMAL_DEPENDENCY, "@aws-sdk/md5-js", "3.374.0"),
@Deprecated STREAM_HASHER_NODE(NORMAL_DEPENDENCY, "@aws-sdk/hash-stream-node", "3.374.0"),
@Deprecated STREAM_HASHER_BROWSER(NORMAL_DEPENDENCY, "@aws-sdk/hash-blob-browser", "3.374.0"),
FLEXIBLE_CHECKSUMS_MIDDLEWARE(NORMAL_DEPENDENCY, "@aws-sdk/middleware-flexible-checksums"),
// Conditionally added when auth trait is present
MIDDLEWARE_API_KEY(NORMAL_DEPENDENCY, "@aws-sdk/middleware-api-key"),
// Conditionally added when EndpointRuleSetTrait is present
UTIL_ENDPOINTS(NORMAL_DEPENDENCY, "@aws-sdk/util-endpoints"),
// feat(experimentalIdentityAndAuth): Conditionally added when @httpBearerAuth is used in an AWS service
TOKEN_PROVIDERS(NORMAL_DEPENDENCY, "@aws-sdk/token-providers"),
TYPES(NORMAL_DEPENDENCY, "@aws-sdk/types"),
REGION_CONFIG_RESOLVER(NORMAL_DEPENDENCY, "@aws-sdk/region-config-resolver");
public final String packageName;
public final String version;
public final SymbolDependency dependency;
AwsDependency(String type, String name) {
this(type, name, SdkVersion.expectVersion(name));
}
AwsDependency(String type, String name, String version) {
this.dependency = SymbolDependency.builder().dependencyType(type).packageName(name).version(version).build();
this.packageName = name;
this.version = version;
}
@Override
public List<SymbolDependency> getDependencies() {
return Collections.singletonList(dependency);
}
@Override
public String getPackageName() {
return this.packageName;
}
private static final class SdkVersion {
private static final Map<String, String> VERSIONS;
static {
String rawProperties =
IoUtils.readUtf8Url(AwsDependency.class.getResource("sdkVersions.properties")).trim();
Properties p = new Properties();
try {
p.load(new StringReader(rawProperties));
} catch (IOException e) {
throw new IllegalArgumentException("Could not read sdkVersions.properties");
}
final Map<String, String> versions = new HashMap<>(p.size());
p.forEach((k, v) -> {
if (versions.put(k.toString(), v.toString()) != null) {
throw new IllegalArgumentException("Multiple versions defined for " + k.toString());
}
});
VERSIONS = Collections.unmodifiableMap(versions);
}
private static String expectVersion(String packageName) {
if (!VERSIONS.containsKey(packageName)) {
throw new IllegalArgumentException("No version for " + packageName);
}
return VERSIONS.get(packageName);
}
}
}
| 4,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.