All Downloads are FREE. Search and download functionalities are using the official Maven repository.

software.amazon.awssdk.services.redshift.waiters.DefaultRedshiftAsyncWaiter Maven / Gradle / Ivy

Go to download

The AWS Java SDK for Amazon Redshift module holds the client classes that are used for communicating with Amazon Redshift Service

There is a newer version: 2.29.15
Show newest version
/*
 * Copyright 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.awssdk.services.redshift.waiters;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.internal.waiters.WaiterAttribute;
import software.amazon.awssdk.core.retry.backoff.BackoffStrategy;
import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy;
import software.amazon.awssdk.core.waiters.AsyncWaiter;
import software.amazon.awssdk.core.waiters.WaiterAcceptor;
import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.redshift.RedshiftAsyncClient;
import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsRequest;
import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsResponse;
import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest;
import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse;
import software.amazon.awssdk.services.redshift.model.RedshiftRequest;
import software.amazon.awssdk.services.redshift.waiters.internal.WaitersRuntime;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;

@Generated("software.amazon.awssdk:codegen")
@SdkInternalApi
@ThreadSafe
final class DefaultRedshiftAsyncWaiter implements RedshiftAsyncWaiter {
    private static final WaiterAttribute CLIENT_ATTRIBUTE = new WaiterAttribute<>(SdkAutoCloseable.class);

    private static final WaiterAttribute SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE = new WaiterAttribute<>(
            ScheduledExecutorService.class);

    private final RedshiftAsyncClient client;

    private final AttributeMap managedResources;

    private final AsyncWaiter clusterAvailableWaiter;

    private final AsyncWaiter clusterDeletedWaiter;

    private final AsyncWaiter clusterRestoredWaiter;

    private final AsyncWaiter snapshotAvailableWaiter;

    private final ScheduledExecutorService executorService;

    private DefaultRedshiftAsyncWaiter(DefaultBuilder builder) {
        AttributeMap.Builder attributeMapBuilder = AttributeMap.builder();
        if (builder.client == null) {
            this.client = RedshiftAsyncClient.builder().build();
            attributeMapBuilder.put(CLIENT_ATTRIBUTE, this.client);
        } else {
            this.client = builder.client;
        }
        if (builder.executorService == null) {
            this.executorService = Executors.newScheduledThreadPool(1,
                    new ThreadFactoryBuilder().threadNamePrefix("waiters-ScheduledExecutor").build());
            attributeMapBuilder.put(SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE, this.executorService);
        } else {
            this.executorService = builder.executorService;
        }
        managedResources = attributeMapBuilder.build();
        this.clusterAvailableWaiter = AsyncWaiter.builder(DescribeClustersResponse.class)
                .acceptors(clusterAvailableWaiterAcceptors())
                .overrideConfiguration(clusterAvailableWaiterConfig(builder.overrideConfiguration))
                .scheduledExecutorService(executorService).build();
        this.clusterDeletedWaiter = AsyncWaiter.builder(DescribeClustersResponse.class)
                .acceptors(clusterDeletedWaiterAcceptors())
                .overrideConfiguration(clusterDeletedWaiterConfig(builder.overrideConfiguration))
                .scheduledExecutorService(executorService).build();
        this.clusterRestoredWaiter = AsyncWaiter.builder(DescribeClustersResponse.class)
                .acceptors(clusterRestoredWaiterAcceptors())
                .overrideConfiguration(clusterRestoredWaiterConfig(builder.overrideConfiguration))
                .scheduledExecutorService(executorService).build();
        this.snapshotAvailableWaiter = AsyncWaiter.builder(DescribeClusterSnapshotsResponse.class)
                .acceptors(snapshotAvailableWaiterAcceptors())
                .overrideConfiguration(snapshotAvailableWaiterConfig(builder.overrideConfiguration))
                .scheduledExecutorService(executorService).build();
    }

    private static String errorCode(Throwable error) {
        if (error instanceof AwsServiceException) {
            return ((AwsServiceException) error).awsErrorDetails().errorCode();
        }
        return null;
    }

    @Override
    public CompletableFuture> waitUntilClusterAvailable(
            DescribeClustersRequest describeClustersRequest) {
        return clusterAvailableWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)));
    }

    @Override
    public CompletableFuture> waitUntilClusterAvailable(
            DescribeClustersRequest describeClustersRequest, WaiterOverrideConfiguration overrideConfig) {
        return clusterAvailableWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)),
                clusterAvailableWaiterConfig(overrideConfig));
    }

    @Override
    public CompletableFuture> waitUntilClusterDeleted(
            DescribeClustersRequest describeClustersRequest) {
        return clusterDeletedWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)));
    }

    @Override
    public CompletableFuture> waitUntilClusterDeleted(
            DescribeClustersRequest describeClustersRequest, WaiterOverrideConfiguration overrideConfig) {
        return clusterDeletedWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)),
                clusterDeletedWaiterConfig(overrideConfig));
    }

    @Override
    public CompletableFuture> waitUntilClusterRestored(
            DescribeClustersRequest describeClustersRequest) {
        return clusterRestoredWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)));
    }

    @Override
    public CompletableFuture> waitUntilClusterRestored(
            DescribeClustersRequest describeClustersRequest, WaiterOverrideConfiguration overrideConfig) {
        return clusterRestoredWaiter.runAsync(() -> client.describeClusters(applyWaitersUserAgent(describeClustersRequest)),
                clusterRestoredWaiterConfig(overrideConfig));
    }

    @Override
    public CompletableFuture> waitUntilSnapshotAvailable(
            DescribeClusterSnapshotsRequest describeClusterSnapshotsRequest) {
        return snapshotAvailableWaiter.runAsync(() -> client
                .describeClusterSnapshots(applyWaitersUserAgent(describeClusterSnapshotsRequest)));
    }

    @Override
    public CompletableFuture> waitUntilSnapshotAvailable(
            DescribeClusterSnapshotsRequest describeClusterSnapshotsRequest, WaiterOverrideConfiguration overrideConfig) {
        return snapshotAvailableWaiter.runAsync(
                () -> client.describeClusterSnapshots(applyWaitersUserAgent(describeClusterSnapshotsRequest)),
                snapshotAvailableWaiterConfig(overrideConfig));
    }

    private static List> clusterAvailableWaiterAcceptors() {
        List> result = new ArrayList<>();
        result.add(WaiterAcceptor.successOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("ClusterStatus").values();
            return !resultValues.isEmpty() && resultValues.stream().allMatch(v -> Objects.equals(v, "available"));
        }));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("ClusterStatus").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "deleting"));
        }));
        result.add(WaiterAcceptor.retryOnExceptionAcceptor(error -> Objects.equals(errorCode(error), "ClusterNotFound")));
        result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS);
        return result;
    }

    private static List> clusterDeletedWaiterAcceptors() {
        List> result = new ArrayList<>();
        result.add(WaiterAcceptor.successOnExceptionAcceptor(error -> Objects.equals(errorCode(error), "ClusterNotFound")));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("ClusterStatus").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "creating"));
        }));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("ClusterStatus").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "modifying"));
        }));
        result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS);
        return result;
    }

    private static List> clusterRestoredWaiterAcceptors() {
        List> result = new ArrayList<>();
        result.add(WaiterAcceptor.successOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("RestoreStatus").field("Status").values();
            return !resultValues.isEmpty() && resultValues.stream().allMatch(v -> Objects.equals(v, "completed"));
        }));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Clusters").flatten().field("ClusterStatus").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "deleting"));
        }));
        result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS);
        return result;
    }

    private static List> snapshotAvailableWaiterAcceptors() {
        List> result = new ArrayList<>();
        result.add(WaiterAcceptor.successOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Snapshots").flatten().field("Status").values();
            return !resultValues.isEmpty() && resultValues.stream().allMatch(v -> Objects.equals(v, "available"));
        }));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Snapshots").flatten().field("Status").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "failed"));
        }));
        result.add(WaiterAcceptor.errorOnResponseAcceptor(response -> {
            WaitersRuntime.Value input = new WaitersRuntime.Value(response);
            List resultValues = input.field("Snapshots").flatten().field("Status").values();
            return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "deleted"));
        }));
        result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS);
        return result;
    }

    private static WaiterOverrideConfiguration clusterAvailableWaiterConfig(WaiterOverrideConfiguration overrideConfig) {
        Optional optionalOverrideConfig = Optional.ofNullable(overrideConfig);
        int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(30);
        BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse(
                FixedDelayBackoffStrategy.create(Duration.ofSeconds(60)));
        Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null);
        return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy)
                .waitTimeout(waitTimeout).build();
    }

    private static WaiterOverrideConfiguration clusterDeletedWaiterConfig(WaiterOverrideConfiguration overrideConfig) {
        Optional optionalOverrideConfig = Optional.ofNullable(overrideConfig);
        int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(30);
        BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse(
                FixedDelayBackoffStrategy.create(Duration.ofSeconds(60)));
        Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null);
        return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy)
                .waitTimeout(waitTimeout).build();
    }

    private static WaiterOverrideConfiguration clusterRestoredWaiterConfig(WaiterOverrideConfiguration overrideConfig) {
        Optional optionalOverrideConfig = Optional.ofNullable(overrideConfig);
        int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(30);
        BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse(
                FixedDelayBackoffStrategy.create(Duration.ofSeconds(60)));
        Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null);
        return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy)
                .waitTimeout(waitTimeout).build();
    }

    private static WaiterOverrideConfiguration snapshotAvailableWaiterConfig(WaiterOverrideConfiguration overrideConfig) {
        Optional optionalOverrideConfig = Optional.ofNullable(overrideConfig);
        int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(20);
        BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse(
                FixedDelayBackoffStrategy.create(Duration.ofSeconds(15)));
        Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null);
        return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy)
                .waitTimeout(waitTimeout).build();
    }

    @Override
    public void close() {
        managedResources.close();
    }

    public static RedshiftAsyncWaiter.Builder builder() {
        return new DefaultBuilder();
    }

    private  T applyWaitersUserAgent(T request) {
        Consumer userAgentApplier = b -> b.addApiName(ApiName.builder()
                .version("waiter").name("hll").build());
        AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration()
                .map(c -> c.toBuilder().applyMutation(userAgentApplier).build())
                .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build()));
        return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build();
    }

    public static final class DefaultBuilder implements RedshiftAsyncWaiter.Builder {
        private RedshiftAsyncClient client;

        private WaiterOverrideConfiguration overrideConfiguration;

        private ScheduledExecutorService executorService;

        private DefaultBuilder() {
        }

        @Override
        public RedshiftAsyncWaiter.Builder scheduledExecutorService(ScheduledExecutorService executorService) {
            this.executorService = executorService;
            return this;
        }

        @Override
        public RedshiftAsyncWaiter.Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration) {
            this.overrideConfiguration = overrideConfiguration;
            return this;
        }

        @Override
        public RedshiftAsyncWaiter.Builder client(RedshiftAsyncClient client) {
            this.client = client;
            return this;
        }

        public RedshiftAsyncWaiter build() {
            return new DefaultRedshiftAsyncWaiter(this);
        }
    }
}