Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions buildSrc/src/main/kotlin/CodegenExtension.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ fun Project.addGenerateSrcsTask(
}
val dirs = resourceDirs
tasks.register(mergeTaskName) {
// Without inputs the task stays up to date and misses newly generated resources.
inputs.files(project.provider { dirs.map { File(it) } }).withPropertyName("generatedResources")
outputs.dir(mergedDir)
doLast {
val outputDir = mergedDir.get().asFile
Expand Down
4 changes: 4 additions & 0 deletions client/client-waiters/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ dependencies {
implementation(project(":jmespath"))
implementation(project(":logging"))
implementation(project(":client:client-core"))

testImplementation(project(":client:dynamic-client"))
testImplementation(project(":aws:client:aws-client-restjson"))
testImplementation(project(":client:client-mock-plugin"))
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import software.amazon.smithy.java.client.waiters.backoff.BackoffStrategy;
import software.amazon.smithy.java.client.waiters.matching.Matcher;
import software.amazon.smithy.java.core.error.ModeledException;
import software.amazon.smithy.java.core.schema.ApiOperation;
import software.amazon.smithy.java.core.schema.SerializableStruct;
import software.amazon.smithy.utils.SmithyInternalApi;

/**
* Waiters are used to poll a resource until a desired state is reached, or until it is determined that the resource
Expand Down Expand Up @@ -185,6 +187,84 @@ O extends SerializableStruct> Builder<I, O> builder(Waitable<I, O> pollingFuncti
return new Builder<>(pollingFunction);
}

/**
* Create a waiter from a waiter modeled with the {@code smithy.waiters#waitable} trait on an operation.
*
* <p>The operation's schema must carry the {@code waitable} trait. Schemas created from a model, such as those
* used by dynamic clients, include it.
*
* <p>Example usage with a dynamic client<pre>{@code
* var operation = client.getOperation("GetFoo");
* Waiter<StructDocument, StructDocument> waiter = Waiter.fromModel(
* (input, override) -> (StructDocument) client.call("GetFoo", input, override),
* operation,
* "FooExists");
* var input = (StructDocument) client.createStruct(
* operation.inputSchema().id(),
* Document.ofObject(Map.of("id", "my-id")));
* waiter.wait(input, Duration.ofMinutes(5));
* }</pre>
*
* @param pollingFunction Client call that will be used to poll for the resource state.
* @param operation Operation that defines the waiter.
* @param waiterName Name of the waiter, as modeled in the {@code waitable} trait.
* @return the waiter.
* @param <I> Input shape type
* @param <O> Output shape type
* @throws IllegalArgumentException if the operation does not define the waiter.
*/
public static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromModel(
Waitable<I, O> pollingFunction,
ApiOperation<I, O> operation,
String waiterName
) {
return WaiterDefinitions.fromModel(pollingFunction, operation, waiterName);
}

/**
* Create a waiter from a modeled Smithy waiter definition.
*
* <p>Acceptors are evaluated in their modeled order, and the modeled minimum and maximum delays configure the
* default backoff strategy.
*
* @param pollingFunction Client call that will be used to poll for the resource state.
* @param definition Modeled waiter definition.
* @return the waiter.
* @param <I> Input shape type
* @param <O> Output shape type
*/
public static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromDefinition(
Waitable<I, O> pollingFunction,
software.amazon.smithy.waiters.Waiter definition
) {
return WaiterDefinitions.fromDefinition(pollingFunction, definition);
}

/**
* Create a waiter from definitions bundled as a resource next to a class.
*
* <p>The resource is named {@code <SimpleName>.waiters.json}, lives in the same package as {@code owner}, and
* contains a JSON object that maps waiter names to modeled waiter definitions. It is read once per class, the
* first time one of its waiters is requested. Generated waiter containers use this method.
*
* @param pollingFunction Client call that will be used to poll for the resource state.
* @param owner Class the definitions are bundled with.
* @param waiterName Name of the waiter.
* @return the waiter.
* @param <I> Input shape type
* @param <O> Output shape type
* @throws IllegalArgumentException if no waiter with the given name is bundled with the class.
* @throws IllegalStateException if the resource is missing.
*/
@SmithyInternalApi
public static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromResource(
Waitable<I, O> pollingFunction,
Class<?> owner,
String waiterName
) {
return WaiterDefinitions.fromResource(pollingFunction, owner, waiterName);
}

/**
* Static builder for {@link Waiter}.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package software.amazon.smithy.java.client.waiters;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.smithy.java.client.waiters.backoff.BackoffStrategy;
import software.amazon.smithy.java.client.waiters.jmespath.Comparator;
import software.amazon.smithy.java.client.waiters.jmespath.JMESPathBiPredicate;
import software.amazon.smithy.java.client.waiters.jmespath.JMESPathPredicate;
import software.amazon.smithy.java.client.waiters.matching.Matcher;
import software.amazon.smithy.java.core.schema.ApiOperation;
import software.amazon.smithy.java.core.schema.SerializableStruct;
import software.amazon.smithy.java.core.schema.TraitKey;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.waiters.Matcher.ErrorTypeMember;
import software.amazon.smithy.waiters.Matcher.InputOutputMember;
import software.amazon.smithy.waiters.Matcher.OutputMember;
import software.amazon.smithy.waiters.Matcher.SuccessMember;
import software.amazon.smithy.waiters.PathMatcher;
import software.amazon.smithy.waiters.WaitableTrait;

/**
* Converts modeled Smithy waiter definitions into runtime {@link Waiter}s.
*/
final class WaiterDefinitions {

private static final String RESOURCE_SUFFIX = ".waiters.json";
private static final TraitKey<WaitableTrait> WAITABLE_TRAIT = TraitKey.get(WaitableTrait.class);

// Definitions bundled next to a class, loaded the first time one of its waiters is requested.
private static final ClassValue<Map<String, software.amazon.smithy.waiters.Waiter>> BUNDLED = new ClassValue<>() {
@Override
protected Map<String, software.amazon.smithy.waiters.Waiter> computeValue(Class<?> owner) {
return loadBundled(owner);
}
};

private WaiterDefinitions() {}

static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromDefinition(
Waiter.Waitable<I, O> pollingFunction,
software.amazon.smithy.waiters.Waiter definition
) {
// Min and max delay are always modeled in seconds.
var builder = Waiter.builder(pollingFunction)
.backoffStrategy(BackoffStrategy.getDefault(
definition.getMinDelay() * 1000L,
definition.getMaxDelay() * 1000L));
// Acceptors are evaluated in modeled order.
for (var acceptor : definition.getAcceptors()) {
Matcher<I, O> matcher = convertMatcher(acceptor.getMatcher());
switch (acceptor.getState()) {
case SUCCESS -> builder.success(matcher);
case FAILURE -> builder.failure(matcher);
case RETRY -> builder.retry(matcher);
}
}
return builder.build();
}

static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromModel(
Waiter.Waitable<I, O> pollingFunction,
ApiOperation<I, O> operation,
String waiterName
) {
var operationId = operation.schema().id();
var trait = operation.schema().getTrait(WAITABLE_TRAIT);
if (trait == null) {
throw new IllegalArgumentException("Operation " + operationId
+ " has no waiters. Its schema must have the " + WaitableTrait.ID + " trait.");
}
var definition = trait.getWaiters().get(waiterName);
if (definition == null) {
throw new IllegalArgumentException("Operation " + operationId + " has no waiter named '"
+ waiterName + "'. Available waiters: " + trait.getWaiters().keySet());
}
return fromDefinition(pollingFunction, definition);
}

static <I extends SerializableStruct, O extends SerializableStruct> Waiter<I, O> fromResource(
Waiter.Waitable<I, O> pollingFunction,
Class<?> owner,
String waiterName
) {
var definitions = BUNDLED.get(owner);
var definition = definitions.get(waiterName);
if (definition == null) {
throw new IllegalArgumentException("No waiter named '" + waiterName + "' is bundled with "
+ owner.getName() + ". Available waiters: " + definitions.keySet());
}
return fromDefinition(pollingFunction, definition);
}

private static Map<String, software.amazon.smithy.waiters.Waiter> loadBundled(Class<?> owner) {
var resource = owner.getSimpleName() + RESOURCE_SUFFIX;
try (var stream = owner.getResourceAsStream(resource)) {
if (stream == null) {
throw new IllegalStateException("Missing waiter definitions resource " + resource
+ " for " + owner.getName());
}
var node = Node.parse(new String(stream.readAllBytes(), StandardCharsets.UTF_8));
Map<String, software.amazon.smithy.waiters.Waiter> result = new HashMap<>();
for (var entry : node.expectObjectNode().getStringMap().entrySet()) {
result.put(entry.getKey(), software.amazon.smithy.waiters.Waiter.fromNode(entry.getValue()));
}
return Collections.unmodifiableMap(result);
} catch (IOException e) {
throw new UncheckedIOException("Unable to read waiter definitions resource " + resource, e);
}
}

private static <I extends SerializableStruct, O extends SerializableStruct> Matcher<I, O> convertMatcher(
software.amazon.smithy.waiters.Matcher<?> matcher
) {
return switch (matcher) {
case OutputMember m -> Matcher.output(new JMESPathPredicate<>(
m.getValue().getPath(),
m.getValue().getExpected(),
comparator(m.getValue())));
case InputOutputMember m -> Matcher.inputOutput(new JMESPathBiPredicate<>(
m.getValue().getPath(),
m.getValue().getExpected(),
comparator(m.getValue())));
case SuccessMember m -> Matcher.success(m.getValue());
case ErrorTypeMember m -> Matcher.errorType(m.getValue());
default -> throw new IllegalArgumentException("Unsupported waiter matcher: " + matcher.getMemberName());
};
}

private static Comparator comparator(PathMatcher pathMatcher) {
// The runtime comparator constants share names with the modeled comparators.
return Comparator.valueOf(pathMatcher.getComparator().name());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ final class DefaultBackoffStrategy implements BackoffStrategy {

@Override
public long computeNextDelayInMills(int attempt, long remainingTime) {
// Per the Smithy waiter spec: delay = minDelay * 2^(attempt - 1), capped at maxDelay once attempt exceeds
// log2(maxDelay / minDelay) + 1, then a random delay between minDelay and that value.
var attemptCeiling = (Math.log((double) maxDelayMillis / minDelayMillis) / Math.log(2)) + 1;
long delay = maxDelayMillis;
if (((double) attempt) < attemptCeiling) {
delay = Math.min(maxDelayMillis, (long) Math.pow(minDelayMillis * 2, attempt));
if (attempt <= attemptCeiling) {
delay = Math.min(maxDelayMillis, (long) (minDelayMillis * Math.pow(2, Math.max(0, attempt - 1))));
}
// Math.pow can return a delay <= minDelayMillis on early attempts (e.g. attempt=0
// gives 1 when minDelayMillis=2). Random.nextLong(origin, bound) requires bound > origin,
// so floor the upper bound at minDelayMillis + 1.
long upper = Math.max(minDelayMillis + 1, delay);
// Random.nextLong(origin, bound) excludes bound, so add one to make delay inclusive.
long upper = Math.max(minDelayMillis, delay) + 1;
delay = rng.nextLong(minDelayMillis, upper);
if (remainingTime - delay <= minDelayMillis) {
delay = remainingTime;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public boolean compare(Document value, String expected) {
}

for (var document : documentList) {
if (Comparator.STRING_EQUALS.compare(document, expected)) {
if (!Comparator.STRING_EQUALS.compare(document, expected)) {
return false;
}
}
Expand Down
Loading
Loading