diff --git a/src/main/java/io/github/hectorvent/floci/core/common/StripedLocks.java b/src/main/java/io/github/hectorvent/floci/core/common/StripedLocks.java new file mode 100644 index 0000000000..900d4e1b86 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/StripedLocks.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.core.common; + +/** A bounded set of monitors for callers to synchronize operations sharing a key. */ +public final class StripedLocks { + + private final Object[] locks; + + public StripedLocks(int stripeCount) { + if (stripeCount <= 0) { + throw new IllegalArgumentException("stripeCount must be positive"); + } + locks = new Object[stripeCount]; + for (int i = 0; i < locks.length; i++) { + locks[i] = new Object(); + } + } + + public Object lockFor(Object key) { + return locks[Math.floorMod(key.hashCode(), locks.length)]; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java index b37d18c272..9bbb5a0d22 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.SmithyValidationErrors; +import io.github.hectorvent.floci.core.common.StripedLocks; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime; @@ -46,9 +47,11 @@ public class BedrockAgentCoreControlService { private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final int MAX_PAGE = 100; + private static final int RUNTIME_LOCK_STRIPES = 256; private final StorageBackend storage; private final RegionResolver regionResolver; + private final StripedLocks runtimeLocks = new StripedLocks(RUNTIME_LOCK_STRIPES); private final BedrockAgentCoreIdentityService identityService; // clientToken idempotency: tokens of completed deletes, so a replayed delete succeeds // instead of 404ing. In-memory only (reset on restart), and each entry expires after @@ -181,34 +184,36 @@ public class BedrockAgentCoreControlService { String roleArn, String description, Map environmentVariables, JsonNode authorizerConfiguration, JsonNode protocolConfiguration, String region) { - if (artifact == null || artifact.isNull()) { - throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400); - } - if (networkConfiguration == null || networkConfiguration.isNull()) { - throw new AwsException("ValidationException", "networkConfiguration is required", 400); - } - if (roleArn == null || roleArn.isBlank()) { - throw new AwsException("ValidationException", "roleArn is required", 400); - } - validateConfiguration(networkConfiguration, protocolConfiguration); - AgentRuntime runtime = getAgentRuntime(id, region); - Instant now = Instant.now(); + synchronized (runtimeLock(region, id)) { + if (artifact == null || artifact.isNull()) { + throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400); + } + if (networkConfiguration == null || networkConfiguration.isNull()) { + throw new AwsException("ValidationException", "networkConfiguration is required", 400); + } + if (roleArn == null || roleArn.isBlank()) { + throw new AwsException("ValidationException", "roleArn is required", 400); + } + validateConfiguration(networkConfiguration, protocolConfiguration); + AgentRuntime runtime = getAgentRuntime(id, region); + Instant now = Instant.now(); - int newVersion = runtime.getLatestVersion() + 1; - runtime.setLatestVersion(newVersion); - runtime.setRoleArn(roleArn); - runtime.setDescription(description); - runtime.setAgentRuntimeArtifact(artifact); - runtime.setNetworkConfiguration(networkConfiguration); - runtime.setAuthorizerConfiguration(authorizerConfiguration); - runtime.setProtocolConfiguration(protocolConfiguration); - runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>()); - runtime.setLastUpdatedAt(now); - runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now)); + int newVersion = runtime.getLatestVersion() + 1; + runtime.setLatestVersion(newVersion); + runtime.setRoleArn(roleArn); + runtime.setDescription(description); + runtime.setAgentRuntimeArtifact(artifact); + runtime.setNetworkConfiguration(networkConfiguration); + runtime.setAuthorizerConfiguration(authorizerConfiguration); + runtime.setProtocolConfiguration(protocolConfiguration); + runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>()); + runtime.setLastUpdatedAt(now); + runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now)); - storage.put(key(region, id), runtime); - LOG.infov("Updated AgentCore runtime {0} to version {1}", id, newVersion); - return runtime; + storage.put(key(region, id), runtime); + LOG.infov("Updated AgentCore runtime {0} to version {1}", id, newVersion); + return runtime; + } } /** @@ -236,25 +241,27 @@ public class BedrockAgentCoreControlService { } public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) { - Optional found = storage.get(key(region, id)); - if (found.isEmpty()) { - if (clientToken != null && deletedRuntimeTokens.contains(tokenKey(region, clientToken))) { - AgentRuntime marker = new AgentRuntime(); - marker.setAgentRuntimeId(id); - marker.setStatus(STATUS_DELETING); - return marker; + synchronized (runtimeLock(region, id)) { + Optional found = storage.get(key(region, id)); + if (found.isEmpty()) { + if (clientToken != null && deletedRuntimeTokens.contains(tokenKey(region, clientToken))) { + AgentRuntime marker = new AgentRuntime(); + marker.setAgentRuntimeId(id); + marker.setStatus(STATUS_DELETING); + return marker; + } + throw new AwsException("ResourceNotFoundException", + "AgentCore runtime not found: " + id, 404); } - throw new AwsException("ResourceNotFoundException", - "AgentCore runtime not found: " + id, 404); + AgentRuntime runtime = found.get(); + storage.delete(key(region, id)); + if (clientToken != null) { + deletedRuntimeTokens.record(tokenKey(region, clientToken)); + } + runtime.setStatus(STATUS_DELETING); + LOG.infov("Deleted AgentCore runtime {0}", id); + return runtime; } - AgentRuntime runtime = found.get(); - storage.delete(key(region, id)); - if (clientToken != null) { - deletedRuntimeTokens.record(tokenKey(region, clientToken)); - } - runtime.setStatus(STATUS_DELETING); - LOG.infov("Deleted AgentCore runtime {0}", id); - return runtime; } private static String tokenKey(String region, String clientToken) { @@ -347,38 +354,42 @@ public class BedrockAgentCoreControlService { public AgentRuntimeEndpoint createEndpoint(String runtimeId, String name, String agentRuntimeVersion, String description, String clientToken, String region) { - AgentRuntime runtime = getAgentRuntime(runtimeId, region); - if (clientToken != null) { - Optional replay = runtime.getEndpoints().stream() - .filter(e -> clientToken.equals(e.getClientToken())) - .findFirst(); - if (replay.isPresent()) { - return replay.get(); + synchronized (runtimeLock(region, runtimeId)) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + if (clientToken != null) { + Optional replay = runtime.getEndpoints().stream() + .filter(e -> clientToken.equals(e.getClientToken())) + .findFirst(); + if (replay.isPresent()) { + return replay.get(); + } } + if (name == null || !NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", + "endpoint name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400); + } + boolean exists = runtime.getEndpoints().stream().anyMatch(e -> name.equals(e.getName())); + if (exists) { + throw new AwsException("ConflictException", + "AgentCore runtime endpoint already exists: " + name, 409); + } + String version = agentRuntimeVersion != null ? agentRuntimeVersion + : String.valueOf(runtime.getLatestVersion()); + requirePublishedVersion(runtime, version); + AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now()); + endpoint.setClientToken(clientToken); + runtime.getEndpoints().add(endpoint); + storage.put(key(region, runtimeId), runtime); + LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId); + return endpoint; } - if (name == null || !NAME_PATTERN.matcher(name).matches()) { - throw new AwsException("ValidationException", - "endpoint name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400); - } - boolean exists = runtime.getEndpoints().stream().anyMatch(e -> name.equals(e.getName())); - if (exists) { - throw new AwsException("ConflictException", - "AgentCore runtime endpoint already exists: " + name, 409); - } - String version = agentRuntimeVersion != null ? agentRuntimeVersion - : String.valueOf(runtime.getLatestVersion()); - requirePublishedVersion(runtime, version); - AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now()); - endpoint.setClientToken(clientToken); - runtime.getEndpoints().add(endpoint); - storage.put(key(region, runtimeId), runtime); - LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId); - return endpoint; } public AgentRuntimeEndpoint getEndpoint(String runtimeId, String name, String region) { - AgentRuntime runtime = getAgentRuntime(runtimeId, region); - return findEndpoint(runtime, name); + synchronized (runtimeLock(region, runtimeId)) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + return findEndpoint(runtime, name); + } } /** UpdateAgentRuntimeEndpoint on the API: a null version or description is left as it is. */ @@ -395,19 +406,21 @@ public class BedrockAgentCoreControlService { */ public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion, String description, boolean replaceOmitted, String region) { - AgentRuntime runtime = getAgentRuntime(runtimeId, region); - AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name); - if (agentRuntimeVersion != null) { - requirePublishedVersion(runtime, agentRuntimeVersion); - endpoint.setTargetVersion(agentRuntimeVersion); - endpoint.setLiveVersion(agentRuntimeVersion); + synchronized (runtimeLock(region, runtimeId)) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name); + if (agentRuntimeVersion != null) { + requirePublishedVersion(runtime, agentRuntimeVersion); + endpoint.setTargetVersion(agentRuntimeVersion); + endpoint.setLiveVersion(agentRuntimeVersion); + } + if (description != null || replaceOmitted) { + endpoint.setDescription(description); + } + endpoint.setLastUpdatedAt(Instant.now()); + storage.put(key(region, runtimeId), runtime); + return endpoint; } - if (description != null || replaceOmitted) { - endpoint.setDescription(description); - } - endpoint.setLastUpdatedAt(Instant.now()); - storage.put(key(region, runtimeId), runtime); - return endpoint; } /** @@ -424,34 +437,38 @@ public class BedrockAgentCoreControlService { } public AgentRuntimeEndpoint deleteEndpoint(String runtimeId, String name, String clientToken, String region) { - AgentRuntime runtime = getAgentRuntime(runtimeId, region); - Optional found = runtime.getEndpoints().stream() - .filter(e -> e.getName().equals(name)).findFirst(); - if (found.isEmpty()) { - if (clientToken != null && deletedEndpointTokens.contains(tokenKey(region, clientToken))) { - AgentRuntimeEndpoint marker = new AgentRuntimeEndpoint(); - marker.setName(name); - marker.setStatus(STATUS_DELETING); - return marker; + synchronized (runtimeLock(region, runtimeId)) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + Optional found = runtime.getEndpoints().stream() + .filter(e -> e.getName().equals(name)).findFirst(); + if (found.isEmpty()) { + if (clientToken != null && deletedEndpointTokens.contains(tokenKey(region, clientToken))) { + AgentRuntimeEndpoint marker = new AgentRuntimeEndpoint(); + marker.setName(name); + marker.setStatus(STATUS_DELETING); + return marker; + } + throw new AwsException("ResourceNotFoundException", + "AgentCore runtime endpoint not found: " + name, 404); } - throw new AwsException("ResourceNotFoundException", - "AgentCore runtime endpoint not found: " + name, 404); + AgentRuntimeEndpoint endpoint = found.get(); + runtime.getEndpoints().removeIf(e -> name.equals(e.getName())); + if (clientToken != null) { + deletedEndpointTokens.record(tokenKey(region, clientToken)); + } + endpoint.setStatus(STATUS_DELETING); + storage.put(key(region, runtimeId), runtime); + return endpoint; } - AgentRuntimeEndpoint endpoint = found.get(); - runtime.getEndpoints().removeIf(e -> name.equals(e.getName())); - if (clientToken != null) { - deletedEndpointTokens.record(tokenKey(region, clientToken)); - } - endpoint.setStatus(STATUS_DELETING); - storage.put(key(region, runtimeId), runtime); - return endpoint; } public PaginatedResult listEndpoints(String runtimeId, Integer maxResults, String nextToken, String region) { - AgentRuntime runtime = getAgentRuntime(runtimeId, region); - return Pagination.paginate(runtime.getEndpoints(), AgentRuntimeEndpoint::getName, maxResults, nextToken, - MAX_PAGE, "ValidationException"); + synchronized (runtimeLock(region, runtimeId)) { + AgentRuntime runtime = getAgentRuntime(runtimeId, region); + return Pagination.paginate(runtime.getEndpoints(), AgentRuntimeEndpoint::getName, maxResults, nextToken, + MAX_PAGE, "ValidationException"); + } } /** An endpoint together with the runtime that holds it. */ @@ -471,15 +488,26 @@ public class BedrockAgentCoreControlService { String uuid = resource.substring("agentEndpoint/".length()); String prefix = keyPrefix(region); for (AgentRuntime runtime : storage.scan(k -> k.startsWith(prefix))) { - for (AgentRuntimeEndpoint endpoint : runtime.getEndpoints()) { - if (uuid.equals(endpoint.getUuid())) { - return Optional.of(new EndpointLocation(runtime, endpoint)); + synchronized (runtimeLock(region, runtime.getAgentRuntimeId())) { + Optional current = storage.get(key(region, runtime.getAgentRuntimeId())); + if (current.isEmpty()) { + continue; + } + for (AgentRuntimeEndpoint endpoint : current.get().getEndpoints()) { + if (uuid.equals(endpoint.getUuid())) { + return Optional.of(new EndpointLocation(current.get(), endpoint)); + } } } } return Optional.empty(); } + private Object runtimeLock(String region, String runtimeId) { + String lockKey = regionResolver.getAccountId() + ":" + key(region, runtimeId); + return runtimeLocks.lockFor(lockKey); + } + private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) { return runtime.getEndpoints().stream() .filter(e -> e.getName().equals(name)) diff --git a/src/test/java/io/github/hectorvent/floci/core/common/StripedLocksTest.java b/src/test/java/io/github/hectorvent/floci/core/common/StripedLocksTest.java new file mode 100644 index 0000000000..da55812453 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/StripedLocksTest.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class StripedLocksTest { + + @Test + void equalKeysShareAMonitor() { + StripedLocks locks = new StripedLocks(256); + + assertSame(locks.lockFor("runtime"), locks.lockFor(new String("runtime"))); + } + + @Test + void aSingleStripeReusesItsMonitorForEveryKey() { + StripedLocks locks = new StripedLocks(1); + + assertSame(locks.lockFor("first"), locks.lockFor("second")); + } + + @Test + void distinctStripesHaveDifferentMonitors() { + StripedLocks locks = new StripedLocks(4); + + assertNotSame(locks.lockFor(0), locks.lockFor(1)); + } + + @Test + void negativeHashesSelectANonnegativeStripe() { + StripedLocks locks = new StripedLocks(3); + + assertSame(locks.lockFor(Integer.MIN_VALUE), locks.lockFor(1)); + assertSame(locks.lockFor(-1), locks.lockFor(2)); + } + + @Test + void requiresAPositiveStripeCount() { + assertThrows(IllegalArgumentException.class, () -> new StripedLocks(0)); + assertThrows(IllegalArgumentException.class, () -> new StripedLocks(-1)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointConcurrencyTest.java new file mode 100644 index 0000000000..14d8175d3d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreEndpointConcurrencyTest.java @@ -0,0 +1,138 @@ +package io.github.hectorvent.floci.services.bedrockagentcorecontrol; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime; +import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint; +import io.github.hectorvent.floci.testing.ParkingStore; +import io.github.hectorvent.floci.testing.ThreadStates; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BedrockAgentCoreEndpointConcurrencyTest { + + private static final String REGION = "us-east-1"; + + @Test + void concurrentClientTokenReplayWaitsForPublication() throws Exception { + Fixture fixture = new Fixture(); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> fixture.create("token")); + try { + assertTrue(fixture.storage.awaitParked()); + AtomicReference secondThread = new AtomicReference<>(); + Future second = executor.submit(() -> { + secondThread.set(Thread.currentThread()); + return fixture.create("token"); + }); + ThreadStates.awaitBlockedOrDone(secondThread, second); + assertNotNull(secondThread.get(), "the competing worker must start"); + assertEquals(Thread.State.BLOCKED, secondThread.get().getState(), + "the competing worker must overlap the parked publication"); + assertFalse(second.isDone(), "replay must await the original publication"); + fixture.storage.release(); + assertSame(first.get(5, TimeUnit.SECONDS), second.get(5, TimeUnit.SECONDS)); + assertEquals(1, fixture.namedEndpointCount()); + } finally { + fixture.storage.release(); + } + } + } + + @Test + void concurrentSameNameGetsConflictAfterPublication() throws Exception { + Fixture fixture = new Fixture(); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> fixture.create(null)); + try { + assertTrue(fixture.storage.awaitParked()); + AtomicReference secondThread = new AtomicReference<>(); + Future second = executor.submit(() -> { + secondThread.set(Thread.currentThread()); + return assertThrows(AwsException.class, () -> fixture.create(null)); + }); + ThreadStates.awaitBlockedOrDone(secondThread, second); + assertNotNull(secondThread.get(), "the competing worker must start"); + assertEquals(Thread.State.BLOCKED, secondThread.get().getState(), + "the competing worker must overlap the parked publication"); + assertFalse(second.isDone(), "the uniqueness decision must await publication"); + fixture.storage.release(); + first.get(5, TimeUnit.SECONDS); + assertEquals("ConflictException", second.get(5, TimeUnit.SECONDS).getErrorCode()); + assertEquals(1, fixture.namedEndpointCount()); + } finally { + fixture.storage.release(); + } + } + } + + @Test + void deletingRuntimeCannotBeUndoneByEndpointPublication() throws Exception { + Fixture fixture = new Fixture(); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> fixture.create(null)); + try { + assertTrue(fixture.storage.awaitParked()); + AtomicReference deleteThread = new AtomicReference<>(); + Future deletion = executor.submit(() -> { + deleteThread.set(Thread.currentThread()); + return fixture.service.deleteAgentRuntime(fixture.runtimeId, null, REGION); + }); + ThreadStates.awaitBlockedOrDone(deleteThread, deletion); + assertNotNull(deleteThread.get(), "the competing worker must start"); + assertEquals(Thread.State.BLOCKED, deleteThread.get().getState(), + "the competing worker must overlap the parked publication"); + assertFalse(deletion.isDone(), "deletion must wait for the in-flight publication"); + fixture.storage.release(); + first.get(5, TimeUnit.SECONDS); + deletion.get(5, TimeUnit.SECONDS); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> fixture.service.getAgentRuntime(fixture.runtimeId, REGION)).getErrorCode()); + } finally { + fixture.storage.release(); + } + } + } + + private static final class Fixture { + private final ParkingStore storage = new ParkingStore<>(); + private final BedrockAgentCoreControlService service = new BedrockAgentCoreControlService( + storage, new RegionResolver(REGION, "000000000000")); + private final String runtimeId; + + private Fixture() { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode artifact = mapper.createObjectNode(); + artifact.putObject("containerConfiguration").put("containerUri", "example.invalid/probe:1"); + ObjectNode network = mapper.createObjectNode().put("networkMode", "PUBLIC"); + runtimeId = service.createAgentRuntime("probe", artifact, network, + "arn:aws:iam::000000000000:role/probe", null, null, + null, null, null, REGION).getAgentRuntimeId(); + storage.parkNextWrite(); + } + + private AgentRuntimeEndpoint create(String clientToken) { + return service.createEndpoint(runtimeId, "shared", null, null, clientToken, REGION); + } + + private long namedEndpointCount() { + return service.getAgentRuntime(runtimeId, REGION).getEndpoints().stream() + .filter(endpoint -> "shared".equals(endpoint.getName())).count(); + } + } + +}