mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(bedrockagentcore): emulate the AgentCore control plane and InvokeAgentRuntime stub (#2316)
* docs(bedrockagentcore): add AgentCore emulation design + upgrade path
* feat(bedrockagentcore): add agent runtime CRUD control plane
Implements the bedrock-agentcore-control runtime registry (Phase 1):
Create/Get/List/Update/Delete AgentRuntime plus ListAgentRuntimeVersions,
with immutable version snapshots, cursor pagination, and ISO-8601 timestamps.
- REST-JSON controller + service + reflection-safe models
- ServiceRegistry descriptor + EmulatorConfig toggle
- Unit + RestAssured integration tests
- AWS SDK v2 compatibility test (sdk-test-java)
- Service docs page
Refs lex00/floci#2
* feat(bedrockagentcore): add agent runtime endpoints
Phase 2: Create/Get/Update/Delete/List AgentRuntimeEndpoint under
/runtimes/{id}/runtime-endpoints/, with a DEFAULT endpoint auto-created per
runtime and agentEndpoint/<uuid> ARNs. RestAssured + SDK v2 compat tests.
Refs lex00/floci#3
* feat(bedrockagentcore): add InvokeAgentRuntime data-plane stub
Phase 3: POST /runtimes/{agentRuntimeArn}/invocations returns a fixed,
configurable canned response ({"output":"yes"}) and echoes the runtime
session id. Opaque payload is never parsed; streaming is not emulated.
Separate stateless bedrock-agentcore service. RestAssured + SDK v2 compat tests.
Refs lex00/floci#4
* feat(bedrockagentcore): add tagging and workload identity
Phase 4:
- TagResource/UntagResource/ListTagsForResource for runtime ARNs via a
TagHandler on the shared /tags/{arn} route
- Workload identity RPC CRUD (POST /identities/<Op>); each runtime auto-creates
a resolvable workload identity
- Workload-identity timestamps are epoch-seconds (unixTimestamp), distinct from
the runtime ISO-8601 timestamps
RestAssured + SDK v2 compat tests.
Refs lex00/floci#5
* feat(bedrockagentcore): add gateway and memory primitives
Phase 5 (optional): metadata-only CRUD registries.
- Gateways (POST /gateways/) + gateway targets, standard REST
- Memory (POST /memories/create, GET /memories/{id}/details, ...), action-suffix
- Gateway timestamps are ISO-8601; memory timestamps are epoch seconds
RestAssured + SDK v2 compat tests.
Refs lex00/floci#6
* fix(bedrockagentcore): correctness fixes from adversarial audit
- Fix ListAgentRuntimeVersions pagination cycling for >=10 versions: sort by
the pagination cursor and zero-pad the version cursor (closes #7)
- Capture authorizerConfiguration/protocolConfiguration in version snapshots so
GetAgentRuntime?version returns the requested version's config (closes #8)
- Support tagging AgentCore gateways (AWS-taggable): add tags to Gateway,
dispatch the TagHandler by ARN resource type, store tags on CreateGateway;
non-taggable AgentCore ARNs now 400 (closes #9)
- Validate maxResults range (1..N) across all list operations (closes #12)
Adds regression tests: version-pagination multi-page, version-config snapshot,
gateway tag round-trip (REST + SDK), unsupported-ARN 400, maxResults + malformed
nextToken validation, and an HTTP-level multi-page pagination test.
Refs lex00/floci#14
* feat(bedrockagentcore): clientToken idempotency, invoke existence flag, config docs
- clientToken idempotency for Runtime/Endpoint/Memory create+delete (lenient:
same token returns the existing resource; completed-delete tokens tracked
in-memory so a replayed delete returns 202 not 404) (closes #10)
- InvokeAgentRuntime existence check behind floci.services.bedrock-agent-core
.validate-runtime-exists (default false, preserving permissive behavior);
when on, unknown runtime ARNs return ResourceNotFoundException (closes #11)
- Document that YAML config keys are hyphenated (bedrock-agent-core-control),
distinct from the reported service name (closes #13)
Adds unit tests (create/delete idempotency), a TestProfile integration test for
the existence flag, and an SDK v2 idempotency compat test.
Refs lex00/floci#10 lex00/floci#11 lex00/floci#13
* ci: trigger fork pipeline dry-run
* test(bedrockagentcore): add persistence, region-isolation, concurrency and boundary coverage
Closes the structural test gaps from the audit (issue #14):
- Persistence-across-restart: full AgentRuntime (JsonNode config, Instants,
version snapshots, endpoints, tags, env vars) round-trips through
PersistentStorage to disk and reloads intact
- Region isolation: a runtime is invisible/ungettable from another region
- Concurrency: concurrent creates all persist (no dropped inserts)
- Endpoint version retargeting, gateway + target update, duplicate-name 409,
and memory eventExpiryDuration boundaries (2/3/365/366)
Refs lex00/floci#14
* fix(bedrockagentcore): validate endpoint versions and the identity in a tagging ARN
createEndpoint and updateEndpoint stored agentRuntimeVersion without resolving
it against the runtime, so a version that was never published produced a READY
endpoint whose generated runtime ARN resolves to nothing. Both now reject one
the runtime has not published.
Tag operations resolved a resource from the ARN's id suffix alone, so an ARN
naming another account or region but a local id reached the local runtime or
gateway and could read or change its tags. The shared tag dispatch now checks
both fields against the request, which covers runtimes and gateways in one
place, and reports not found rather than a validation error so the response
does not confirm what sits behind the foreign identity.
This commit is contained in:
1 parent
6b14999974
commit
4e6e6df06d
43 files changed
+5405
No files matched your search
@@ -292,6 +292,16 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>pipes</artifactId>
|
||||
</dependency>
|
||||
<!-- Bedrock AgentCore control-plane client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bedrockagentcorecontrol</artifactId>
|
||||
</dependency>
|
||||
<!-- Bedrock AgentCore data-plane client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bedrockagentcore</artifactId>
|
||||
</dependency>
|
||||
<!-- AWS IoT client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
|
||||
@@ -56,6 +56,8 @@ import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient;
|
||||
import software.amazon.awssdk.services.acm.AcmClient;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ecr.EcrClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcore.BedrockAgentCoreClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.pipes.PipesClient;
|
||||
import software.amazon.awssdk.services.codebuild.CodeBuildClient;
|
||||
import software.amazon.awssdk.services.codedeploy.CodeDeployClient;
|
||||
@@ -836,6 +838,22 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BedrockAgentCoreControlClient bedrockAgentCoreControlClient() {
|
||||
return BedrockAgentCoreControlClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BedrockAgentCoreClient bedrockAgentCoreClient() {
|
||||
return BedrockAgentCoreClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static IotClient iotClient() {
|
||||
return IotClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore Control")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class BedrockAgentCoreControlTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/agent-runtime";
|
||||
|
||||
private static BedrockAgentCoreControlClient client;
|
||||
private static String runtimeName;
|
||||
private static String runtimeId;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
// AgentCore names must match [a-zA-Z][a-zA-Z0-9_]{0,47} — no hyphens.
|
||||
runtimeName = "itAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
try {
|
||||
client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static AgentRuntimeArtifact artifact(String uri) {
|
||||
return AgentRuntimeArtifact.builder()
|
||||
.containerConfiguration(ContainerConfiguration.builder().containerUri(uri).build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static NetworkConfiguration network() {
|
||||
return NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createAgentRuntime() {
|
||||
CreateAgentRuntimeResponse response = client.createAgentRuntime(CreateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeName(runtimeName)
|
||||
.agentRuntimeArtifact(artifact("public.ecr.aws/x/agent:latest"))
|
||||
.networkConfiguration(network())
|
||||
.roleArn(ROLE_ARN)
|
||||
.description("v1")
|
||||
.build());
|
||||
|
||||
runtimeId = response.agentRuntimeId();
|
||||
assertThat(runtimeId).startsWith(runtimeName + "-");
|
||||
assertThat(response.agentRuntimeVersion()).isEqualTo("1");
|
||||
assertThat(response.statusAsString()).isEqualTo("READY");
|
||||
assertThat(response.agentRuntimeArn()).contains(":bedrock-agentcore:").contains(":agent/");
|
||||
assertThat(response.workloadIdentityDetails().workloadIdentityArn()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAgentRuntime() {
|
||||
GetAgentRuntimeResponse response = client.getAgentRuntime(GetAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId).build());
|
||||
|
||||
assertThat(response.agentRuntimeName()).isEqualTo(runtimeName);
|
||||
assertThat(response.agentRuntimeVersion()).isEqualTo("1");
|
||||
assertThat(response.description()).isEqualTo("v1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void listAgentRuntimes() {
|
||||
ListAgentRuntimesResponse response = client.listAgentRuntimes(ListAgentRuntimesRequest.builder().build());
|
||||
assertThat(response.agentRuntimes())
|
||||
.anyMatch(r -> runtimeId.equals(r.agentRuntimeId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateAgentRuntimeBumpsVersion() {
|
||||
UpdateAgentRuntimeResponse response = client.updateAgentRuntime(UpdateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId)
|
||||
.agentRuntimeArtifact(artifact("public.ecr.aws/x/agent:v2"))
|
||||
.networkConfiguration(network())
|
||||
.roleArn(ROLE_ARN)
|
||||
.description("v2")
|
||||
.build());
|
||||
|
||||
assertThat(response.agentRuntimeVersion()).isEqualTo("2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void getSpecificVersionReturnsSnapshot() {
|
||||
GetAgentRuntimeResponse response = client.getAgentRuntime(GetAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId)
|
||||
.agentRuntimeVersion("1")
|
||||
.build());
|
||||
|
||||
assertThat(response.agentRuntimeVersion()).isEqualTo("1");
|
||||
assertThat(response.description()).isEqualTo("v1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void deleteAgentRuntime() {
|
||||
DeleteAgentRuntimeResponse response = client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId).build());
|
||||
assertThat(response.statusAsString()).isEqualTo("DELETING");
|
||||
|
||||
assertThatThrownBy(() -> client.getAgentRuntime(GetAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId).build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void createWithInvalidNameThrowsValidation() {
|
||||
assertThatThrownBy(() -> client.createAgentRuntime(CreateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeName("1-invalid-name")
|
||||
.agentRuntimeArtifact(artifact("x:latest"))
|
||||
.networkConfiguration(network())
|
||||
.roleArn(ROLE_ARN)
|
||||
.build()))
|
||||
.isInstanceOf(ValidationException.class);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore Runtime Endpoints")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class BedrockAgentCoreEndpointTest {
|
||||
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime";
|
||||
|
||||
private static BedrockAgentCoreControlClient client;
|
||||
private static String runtimeId;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
String name = "epAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
runtimeId = client.createAgentRuntime(CreateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeName(name)
|
||||
.agentRuntimeArtifact(AgentRuntimeArtifact.builder()
|
||||
.containerConfiguration(ContainerConfiguration.builder()
|
||||
.containerUri("public.ecr.aws/x/agent:latest").build())
|
||||
.build())
|
||||
.networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build())
|
||||
.roleArn(ROLE_ARN)
|
||||
.build()).agentRuntimeId();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
try {
|
||||
client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(runtimeId).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void defaultEndpointExists() {
|
||||
ListAgentRuntimeEndpointsResponse response = client.listAgentRuntimeEndpoints(
|
||||
ListAgentRuntimeEndpointsRequest.builder().agentRuntimeId(runtimeId).build());
|
||||
assertThat(response.runtimeEndpoints())
|
||||
.anyMatch(e -> "DEFAULT".equals(e.name()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void createEndpoint() {
|
||||
CreateAgentRuntimeEndpointResponse response = client.createAgentRuntimeEndpoint(
|
||||
CreateAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId)
|
||||
.name("prod")
|
||||
.agentRuntimeVersion("1")
|
||||
.description("prod endpoint")
|
||||
.build());
|
||||
assertThat(response.endpointName()).isEqualTo("prod");
|
||||
assertThat(response.targetVersion()).isEqualTo("1");
|
||||
assertThat(response.statusAsString()).isEqualTo("READY");
|
||||
assertThat(response.agentRuntimeEndpointArn()).contains(":agentEndpoint/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void getEndpoint() {
|
||||
GetAgentRuntimeEndpointResponse response = client.getAgentRuntimeEndpoint(
|
||||
GetAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId).endpointName("prod").build());
|
||||
assertThat(response.name()).isEqualTo("prod");
|
||||
assertThat(response.targetVersion()).isEqualTo("1");
|
||||
assertThat(response.description()).isEqualTo("prod endpoint");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void listEndpoints() {
|
||||
ListAgentRuntimeEndpointsResponse response = client.listAgentRuntimeEndpoints(
|
||||
ListAgentRuntimeEndpointsRequest.builder().agentRuntimeId(runtimeId).build());
|
||||
assertThat(response.runtimeEndpoints()).extracting(AgentRuntimeEndpoint::name)
|
||||
.contains("DEFAULT", "prod");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void updateEndpoint() {
|
||||
client.updateAgentRuntimeEndpoint(UpdateAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId).endpointName("prod").description("prod v2").build());
|
||||
|
||||
GetAgentRuntimeEndpointResponse response = client.getAgentRuntimeEndpoint(
|
||||
GetAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId).endpointName("prod").build());
|
||||
assertThat(response.description()).isEqualTo("prod v2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void deleteEndpoint() {
|
||||
DeleteAgentRuntimeEndpointResponse response = client.deleteAgentRuntimeEndpoint(
|
||||
DeleteAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId).endpointName("prod").build());
|
||||
assertThat(response.statusAsString()).isEqualTo("DELETING");
|
||||
|
||||
assertThatThrownBy(() -> client.getAgentRuntimeEndpoint(GetAgentRuntimeEndpointRequest.builder()
|
||||
.agentRuntimeId(runtimeId).endpointName("prod").build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore Gateway")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class BedrockAgentCoreGatewayTest {
|
||||
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/gw";
|
||||
|
||||
private static BedrockAgentCoreControlClient client;
|
||||
private static String gatewayName;
|
||||
private static String gatewayId;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
gatewayName = "gw" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
try {
|
||||
client.deleteGateway(DeleteGatewayRequest.builder().gatewayIdentifier(gatewayId).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createGateway() {
|
||||
CreateGatewayResponse response = client.createGateway(CreateGatewayRequest.builder()
|
||||
.name(gatewayName)
|
||||
.protocolType(GatewayProtocolType.MCP)
|
||||
.authorizerType(AuthorizerType.AWS_IAM)
|
||||
.roleArn(ROLE_ARN)
|
||||
.build());
|
||||
gatewayId = response.gatewayId();
|
||||
assertThat(gatewayId).isNotBlank();
|
||||
assertThat(response.gatewayArn()).contains(":gateway/");
|
||||
assertThat(response.gatewayUrl()).contains(gatewayId);
|
||||
assertThat(response.statusAsString()).isEqualTo("READY");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getGateway() {
|
||||
GetGatewayResponse response = client.getGateway(GetGatewayRequest.builder()
|
||||
.gatewayIdentifier(gatewayId).build());
|
||||
assertThat(response.name()).isEqualTo(gatewayName);
|
||||
assertThat(response.protocolTypeAsString()).isEqualTo("MCP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void listGateways() {
|
||||
ListGatewaysResponse response = client.listGateways(ListGatewaysRequest.builder().build());
|
||||
assertThat(response.items()).extracting(GatewaySummary::gatewayId).contains(gatewayId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void deleteGateway() {
|
||||
DeleteGatewayResponse response = client.deleteGateway(DeleteGatewayRequest.builder()
|
||||
.gatewayIdentifier(gatewayId).build());
|
||||
assertThat(response.statusAsString()).isEqualTo("DELETING");
|
||||
|
||||
assertThatThrownBy(() -> client.getGateway(GetGatewayRequest.builder()
|
||||
.gatewayIdentifier(gatewayId).build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore clientToken idempotency")
|
||||
class BedrockAgentCoreIdempotencyTest {
|
||||
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime";
|
||||
|
||||
private static CreateAgentRuntimeRequest req(String name, String token) {
|
||||
return CreateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeName(name)
|
||||
.agentRuntimeArtifact(AgentRuntimeArtifact.builder()
|
||||
.containerConfiguration(ContainerConfiguration.builder()
|
||||
.containerUri("public.ecr.aws/x/agent:latest").build())
|
||||
.build())
|
||||
.networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build())
|
||||
.roleArn(ROLE_ARN)
|
||||
.clientToken(token)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRuntimeWithSameClientTokenReturnsSameRuntime() {
|
||||
BedrockAgentCoreControlClient client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
String name = "idem" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
// clientToken must be >= 33 chars of the allowed alphabet.
|
||||
String token = "idemtoken" + UUID.randomUUID().toString().replace("-", "");
|
||||
String id1 = null;
|
||||
try {
|
||||
id1 = client.createAgentRuntime(req(name, token)).agentRuntimeId();
|
||||
String id2 = client.createAgentRuntime(req(name, token)).agentRuntimeId();
|
||||
assertThat(id2).isEqualTo(id1);
|
||||
} finally {
|
||||
if (id1 != null) {
|
||||
try {
|
||||
client.deleteAgentRuntime(DeleteAgentRuntimeRequest.builder()
|
||||
.agentRuntimeId(id1).clientToken(token).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.core.ResponseBytes;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.bedrockagentcore.BedrockAgentCoreClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcore.model.InvokeAgentRuntimeRequest;
|
||||
import software.amazon.awssdk.services.bedrockagentcore.model.InvokeAgentRuntimeResponse;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore InvokeAgentRuntime (data plane)")
|
||||
class BedrockAgentCoreInvokeTest {
|
||||
|
||||
private static final String ARN =
|
||||
"arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/abcdef12-3456-7890-abcd-ef1234567890:1";
|
||||
private static final String SESSION_ID = "session-0000000000000000000000000000abc";
|
||||
|
||||
@Test
|
||||
void invokeReturnsCannedBodyAndEchoesSession() {
|
||||
try (BedrockAgentCoreClient client = TestFixtures.bedrockAgentCoreClient()) {
|
||||
ResponseBytes<InvokeAgentRuntimeResponse> response = client.invokeAgentRuntimeAsBytes(
|
||||
InvokeAgentRuntimeRequest.builder()
|
||||
.agentRuntimeArn(ARN)
|
||||
.runtimeSessionId(SESSION_ID)
|
||||
.contentType("application/json")
|
||||
.payload(SdkBytes.fromUtf8String("{\"prompt\":\"anything\"}"))
|
||||
.build());
|
||||
|
||||
assertThat(response.asUtf8String()).contains("yes");
|
||||
assertThat(response.response().runtimeSessionId()).isEqualTo(SESSION_ID);
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore Memory")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class BedrockAgentCoreMemoryTest {
|
||||
|
||||
private static BedrockAgentCoreControlClient client;
|
||||
private static String memoryName;
|
||||
private static String memoryId;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
memoryName = "mem" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
try {
|
||||
client.deleteMemory(DeleteMemoryRequest.builder().memoryId(memoryId).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createMemory() {
|
||||
CreateMemoryResponse response = client.createMemory(CreateMemoryRequest.builder()
|
||||
.name(memoryName)
|
||||
.eventExpiryDuration(30)
|
||||
.description("v1")
|
||||
.build());
|
||||
memoryId = response.memory().id();
|
||||
assertThat(memoryId).isNotBlank();
|
||||
assertThat(response.memory().name()).isEqualTo(memoryName);
|
||||
assertThat(response.memory().arn()).contains(":memory/");
|
||||
assertThat(response.memory().statusAsString()).isEqualTo("ACTIVE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getMemory() {
|
||||
GetMemoryResponse response = client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build());
|
||||
assertThat(response.memory().name()).isEqualTo(memoryName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void listMemories() {
|
||||
ListMemoriesResponse response = client.listMemories(ListMemoriesRequest.builder().build());
|
||||
assertThat(response.memories()).extracting(MemorySummary::id).contains(memoryId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateMemory() {
|
||||
UpdateMemoryResponse response = client.updateMemory(UpdateMemoryRequest.builder()
|
||||
.memoryId(memoryId).description("v2").build());
|
||||
assertThat(response.memory().id()).isEqualTo(memoryId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteMemory() {
|
||||
DeleteMemoryResponse response = client.deleteMemory(DeleteMemoryRequest.builder()
|
||||
.memoryId(memoryId).build());
|
||||
assertThat(response.statusAsString()).isEqualTo("DELETING");
|
||||
|
||||
assertThatThrownBy(() -> client.getMemory(GetMemoryRequest.builder().memoryId(memoryId).build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
|
||||
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("Bedrock AgentCore Tagging + Workload Identity")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class BedrockAgentCoreTagIdentityTest {
|
||||
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent-runtime";
|
||||
|
||||
private static BedrockAgentCoreControlClient client;
|
||||
private static String runtimeArn;
|
||||
private static String identityName;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.bedrockAgentCoreControlClient();
|
||||
String name = "tagAgent" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
runtimeArn = client.createAgentRuntime(CreateAgentRuntimeRequest.builder()
|
||||
.agentRuntimeName(name)
|
||||
.agentRuntimeArtifact(AgentRuntimeArtifact.builder()
|
||||
.containerConfiguration(ContainerConfiguration.builder()
|
||||
.containerUri("public.ecr.aws/x/agent:latest").build())
|
||||
.build())
|
||||
.networkConfiguration(NetworkConfiguration.builder().networkMode(NetworkMode.PUBLIC).build())
|
||||
.roleArn(ROLE_ARN)
|
||||
.build()).agentRuntimeArn();
|
||||
identityName = "wid" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void tagRoundTrip() {
|
||||
client.tagResource(TagResourceRequest.builder()
|
||||
.resourceArn(runtimeArn).tags(Map.of("env", "prod", "team", "core")).build());
|
||||
|
||||
Map<String, String> tags = client.listTagsForResource(ListTagsForResourceRequest.builder()
|
||||
.resourceArn(runtimeArn).build()).tags();
|
||||
assertThat(tags).containsEntry("env", "prod").containsEntry("team", "core");
|
||||
|
||||
client.untagResource(UntagResourceRequest.builder()
|
||||
.resourceArn(runtimeArn).tagKeys(List.of("env")).build());
|
||||
|
||||
Map<String, String> after = client.listTagsForResource(ListTagsForResourceRequest.builder()
|
||||
.resourceArn(runtimeArn).build()).tags();
|
||||
assertThat(after).doesNotContainKey("env").containsEntry("team", "core");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void gatewayTagRoundTripViaSdk() {
|
||||
String gwName = "gwtag" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
String gatewayArn = client.createGateway(CreateGatewayRequest.builder()
|
||||
.name(gwName)
|
||||
.protocolType(GatewayProtocolType.MCP)
|
||||
.authorizerType(AuthorizerType.AWS_IAM)
|
||||
.roleArn("arn:aws:iam::000000000000:role/gw")
|
||||
.build()).gatewayArn();
|
||||
try {
|
||||
client.tagResource(TagResourceRequest.builder()
|
||||
.resourceArn(gatewayArn).tags(Map.of("env", "prod")).build());
|
||||
assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder()
|
||||
.resourceArn(gatewayArn).build()).tags()).containsEntry("env", "prod");
|
||||
client.untagResource(UntagResourceRequest.builder()
|
||||
.resourceArn(gatewayArn).tagKeys(List.of("env")).build());
|
||||
assertThat(client.listTagsForResource(ListTagsForResourceRequest.builder()
|
||||
.resourceArn(gatewayArn).build()).tags()).doesNotContainKey("env");
|
||||
} finally {
|
||||
// gatewayIdentifier is the id form; derive it from the ARN's last segment.
|
||||
String gatewayId = gatewayArn.substring(gatewayArn.lastIndexOf('/') + 1);
|
||||
try {
|
||||
client.deleteGateway(DeleteGatewayRequest.builder().gatewayIdentifier(gatewayId).build());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void workloadIdentityCrud() {
|
||||
CreateWorkloadIdentityResponse created = client.createWorkloadIdentity(
|
||||
CreateWorkloadIdentityRequest.builder().name(identityName).build());
|
||||
assertThat(created.name()).isEqualTo(identityName);
|
||||
assertThat(created.workloadIdentityArn()).contains(":bedrock-agentcore:");
|
||||
|
||||
GetWorkloadIdentityResponse got = client.getWorkloadIdentity(
|
||||
GetWorkloadIdentityRequest.builder().name(identityName).build());
|
||||
assertThat(got.name()).isEqualTo(identityName);
|
||||
|
||||
ListWorkloadIdentitiesResponse listed = client.listWorkloadIdentities(
|
||||
ListWorkloadIdentitiesRequest.builder().build());
|
||||
assertThat(listed.workloadIdentities()).extracting(WorkloadIdentityType::name)
|
||||
.contains(identityName);
|
||||
|
||||
client.deleteWorkloadIdentity(DeleteWorkloadIdentityRequest.builder().name(identityName).build());
|
||||
assertThatThrownBy(() -> client.getWorkloadIdentity(
|
||||
GetWorkloadIdentityRequest.builder().name(identityName).build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
# Design: Amazon Bedrock AgentCore emulation
|
||||
|
||||
Status: proposed. Tracked by the AgentCore epic and phase issues on this fork.
|
||||
|
||||
## Goal
|
||||
|
||||
Emulate Amazon Bedrock AgentCore well enough that AWS SDK/CLI clients can create,
|
||||
read, update, delete, list, and invoke agent runtimes against Floci on port 4566.
|
||||
No real agent execution: the control plane maintains a stateful registry, the data
|
||||
plane returns a canned response.
|
||||
|
||||
Designed clean-room from the AWS public API reference only.
|
||||
|
||||
Two AWS services are involved:
|
||||
|
||||
| Service | API version | SigV4 signing name | Protocol | Role |
|
||||
|---|---|---|---|---|
|
||||
| `bedrock-agentcore-control` | 2023-06-05 | `bedrock-agentcore` | REST JSON (restJson1) | stateful CRUD registry |
|
||||
| `bedrock-agentcore` | 2024-02-28 | `bedrock-agentcore` | REST JSON (binary payload) | `InvokeAgentRuntime` canned-response stub |
|
||||
|
||||
## Scope (MVP)
|
||||
|
||||
- Phase 1 — Agent Runtime CRUD (`bedrock-agentcore-control`)
|
||||
- Phase 2 — Agent Runtime Endpoints
|
||||
- Phase 3 — `InvokeAgentRuntime` data-plane stub (`bedrock-agentcore`)
|
||||
- Phase 4 — Tagging + Workload Identity
|
||||
- Phase 5 (optional) — Gateway + Memory primitives
|
||||
|
||||
Out of scope for the MVP: real inference, streaming invoke semantics, gateway
|
||||
rules, policy engine, registry, payment, browser, code interpreter, dataset,
|
||||
evaluator, harness, token vault, credential providers, IAM enforcement. All are
|
||||
reachable via the upgrade path below.
|
||||
|
||||
## Floci integration conventions
|
||||
|
||||
Follows `AGENTS.md` + `CONTRIBUTING.md`. Verified against the current codebase.
|
||||
|
||||
1. **Packages** — `services/bedrockagentcorecontrol/` and `services/bedrockagentcore/`:
|
||||
`*Controller.java` (thin JAX-RS), `*Service.java` (`@ApplicationScoped`), `model/` POJOs.
|
||||
2. **Controller** — class `@Path("/")`, `@Produces/@Consumes(APPLICATION_JSON)`; full path
|
||||
per method. Inject `Service`, `RegionResolver`, `ObjectMapper`. Take the raw body as a
|
||||
`String` and parse with `ObjectMapper.readTree`. First line: `regionResolver.resolveRegion(headers)`.
|
||||
3. **Service registration** — one `descriptor(...)` line in `core/common/ResolvedServiceCatalog.java`
|
||||
(+ import the controller). Template: the `bedrockruntime`/`pipes` entries. For a REST-JSON service:
|
||||
`defaultProtocol`/`supportedProtocols` = `ServiceProtocol.REST_JSON`; `targetPrefixes = Set.of()`;
|
||||
`credentialScopes = Set.of("bedrock-agentcore")` (SigV4 signing name — verify against the SDK model);
|
||||
`resourceClasses = Set.of(<Controller>.class)` (required for enable/disable);
|
||||
`storageKey = "bedrockagentcore"` (control plane) / `null` (stateless data plane).
|
||||
4. **Config** — `config/EmulatorConfig.java`: add a `ServicesConfig` accessor + nested interface
|
||||
(`@WithDefault("true") boolean enabled();`). Env: `FLOCI_SERVICES_BEDROCK_AGENT_CORE_CONTROL_ENABLED`
|
||||
and `FLOCI_SERVICES_BEDROCK_AGENT_CORE_ENABLED`.
|
||||
5. **Storage** — `StorageFactory.create("bedrockagentcore", "<file>.json", new TypeReference<Map<String,V>>(){})`.
|
||||
Account partitioning is automatic (`AccountAwareStorageBackend`). Two-constructor DI (public `@Inject`
|
||||
builds the store; package-private takes the store for unit tests). Keys: `"<entity>:<region>:<id>"`.
|
||||
Not-found → `store.get(k).orElseThrow(() -> new AwsException("ResourceNotFoundException", msg, 404))`.
|
||||
6. **ARNs** — only via `regionResolver.buildArn("bedrock-agentcore", region, resource)`; account via
|
||||
`regionResolver.getAccountId()`.
|
||||
7. **Errors** — throw `AwsException(code, message, status)`. The global `AwsExceptionMapper` builds the
|
||||
JSON body but does NOT set `X-Amzn-Errortype`, which SDK v2 restJson1 needs. Follow the
|
||||
`services/rdsdata/RdsDataController` / `services/batch/BatchController` pattern: return
|
||||
`Response.status(s).header("X-Amzn-Errortype", code).entity(new AwsErrorResponse(code, message)).build()`.
|
||||
Codes: `ValidationException` (400), `ResourceNotFoundException` (404), `ConflictException` (409).
|
||||
8. **Reflection** — `@io.quarkus.runtime.annotations.RegisterForReflection` on every model/DTO.
|
||||
9. **Pagination** — copy the `services/acm/AcmService` cursor pattern (sort by ARN, Base64(JSON)
|
||||
`nextToken` carrying the last ARN, `skip`/`limit`; bad token → `ValidationException`).
|
||||
10. **clientToken** — accept-and-ignore (scheduler pattern); key uniqueness yields `ConflictException`.
|
||||
11. **Tests** — unit `*ServiceTest.java`; integration `*IntegrationTest.java` as `@QuarkusTest` +
|
||||
RestAssured hitting routes directly (NOT an SDK client — that goes in `compatibility-tests/`).
|
||||
`@TestMethodOrder(OrderAnnotation.class)` for lifecycles. No `Authorization` header → region
|
||||
`us-east-1`, account `000000000000`.
|
||||
12. **Docs** — `docs/services/bedrock-agentcore.md`, register in `tools/docs/services.yaml`,
|
||||
run `make docs-sync` (CI runs `make docs-check`). Add to `mkdocs.yml` nav.
|
||||
|
||||
### Routing
|
||||
No existing service claims `/runtimes` (verified). Control-plane and data-plane controllers both
|
||||
live under `/runtimes` on distinct method paths/verbs — safe under Floci's path-based JAX-RS dispatch.
|
||||
|
||||
## Pinned wire contracts
|
||||
|
||||
All verified against the AWS API reference. **Note verbs and trailing slashes.**
|
||||
|
||||
### Agent Runtime (control plane)
|
||||
|
||||
| Operation | Method + Path | Success | Notes |
|
||||
|---|---|---|---|
|
||||
| CreateAgentRuntime | `PUT /runtimes/` | 202 | required: `agentRuntimeArtifact`, `agentRuntimeName` (`[a-zA-Z][a-zA-Z0-9_]{0,47}`), `networkConfiguration`, `roleArn` |
|
||||
| GetAgentRuntime | `GET /runtimes/{agentRuntimeId}/?version={v}` | 200 | full runtime shape |
|
||||
| ListAgentRuntimes | `POST /runtimes/?maxResults={n}&nextToken={t}` | 200 | **POST**, no body; `agentRuntimes[]` + `nextToken` |
|
||||
| UpdateAgentRuntime | `PUT /runtimes/{agentRuntimeId}/` | 202 | required: `agentRuntimeArtifact`, `networkConfiguration`, `roleArn`; bumps version |
|
||||
| ListAgentRuntimeVersions | `POST /runtimes/{agentRuntimeId}/versions/?maxResults=&nextToken=` | 200 | **POST**, no body |
|
||||
| DeleteAgentRuntime | `DELETE /runtimes/{agentRuntimeId}/?clientToken={t}` | 202 | body `{agentRuntimeId, status: DELETING}` |
|
||||
|
||||
Identity: `agentRuntimeId` = `<name>-<10 [a-zA-Z0-9]>` (`[a-zA-Z][a-zA-Z0-9_]{0,99}-[a-zA-Z0-9]{10}`).
|
||||
ARN embeds a fresh UUID + version: `arn:aws:bedrock-agentcore:<region>:<account>:agent/<uuid>:<version>`.
|
||||
`agentRuntimeVersion` is a string int starting `"1"`, incremented on Update. `status` = `READY`.
|
||||
|
||||
### Agent Runtime Endpoint (control plane)
|
||||
|
||||
| Operation | Method + Path | Success |
|
||||
|---|---|---|
|
||||
| CreateAgentRuntimeEndpoint | `PUT /runtimes/{agentRuntimeId}/runtime-endpoints/` | 202 |
|
||||
| GetAgentRuntimeEndpoint | `GET /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/` | 200 |
|
||||
| UpdateAgentRuntimeEndpoint | `PUT /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/` | 202 |
|
||||
| DeleteAgentRuntimeEndpoint | `DELETE /runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/?clientToken={t}` | 202 |
|
||||
| ListAgentRuntimeEndpoints | `POST /runtimes/{agentRuntimeId}/runtime-endpoints/?maxResults=&nextToken=` | 200 |
|
||||
|
||||
Endpoint ARN `arn:aws:bedrock-agentcore:<region>:<account>:agentEndpoint/<uuid>` (no version).
|
||||
Create body: `name` (required), `agentRuntimeVersion`/`description`/`clientToken`/`tags` (optional).
|
||||
Fields: `liveVersion` (serving) vs `targetVersion` (requested). A `DEFAULT` endpoint is auto-created
|
||||
on runtime create so an unqualified invoke resolves.
|
||||
|
||||
### InvokeAgentRuntime (data plane)
|
||||
|
||||
`POST /runtimes/{agentRuntimeArn}/invocations?accountId={id}&qualifier={q}` → 200.
|
||||
Payload is opaque binary (≤100 MB) — take `byte[]`, do not parse (mirror `BedrockRuntimeController.invokeModel`,
|
||||
`@Consumes(WILDCARD)`). Echo `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id`; return canned JSON,
|
||||
default `{"output":"yes"}`. The ARN in the path is URL-encoded — use `@Path("/runtimes/{agentRuntimeArn:.+}/invocations")`
|
||||
and test with an SDK-encoded ARN. Streaming is out of scope; the stub returns a single non-streaming 200.
|
||||
|
||||
### Tagging (control plane) — matches Floci's shared `/tags/` route
|
||||
|
||||
| Operation | Method + Path | Success |
|
||||
|---|---|---|
|
||||
| TagResource | `POST /tags/{resourceArn}` | 204 |
|
||||
| UntagResource | `DELETE /tags/{resourceArn}?tagKeys={k1}&tagKeys={k2}` | 204 |
|
||||
| ListTagsForResource | `GET /tags/{resourceArn}` | 200 |
|
||||
|
||||
Implement a `TagHandler` (not a controller): `serviceKey()="bedrock-agentcore"`, `tagsBodyKey()="tags"`,
|
||||
`tagsBodyIsList()=false`, `tagKeysQueryName()="tagKeys"`. Body `{"tags":{"k":"v"}}`. Template:
|
||||
`services/scheduler/SchedulerTagHandler.java`.
|
||||
|
||||
### Workload Identity (control plane) — RPC-in-path
|
||||
|
||||
`POST /identities/<Operation>` with all input in the body:
|
||||
`CreateWorkloadIdentity` (201), `GetWorkloadIdentity` (200), `UpdateWorkloadIdentity` (200),
|
||||
`DeleteWorkloadIdentity` (204), `ListWorkloadIdentities` (200, `maxResults` 1–20). Required body: `name`
|
||||
(`[A-Za-z0-9_.-]+`, 3–255). `workloadIdentityArn` has no published regex (≤1024) — synthesize
|
||||
`arn:aws:bedrock-agentcore:<region>:<account>:workload-identity-directory/default/workload-identity/<name>-<suffix>`.
|
||||
`CreateAgentRuntime` auto-creates one and sets the runtime's `workloadIdentityArn`.
|
||||
|
||||
### Gateway + Gateway Target (control plane)
|
||||
|
||||
Standard REST, trailing slashes; identifier is `gatewayId` (not ARN):
|
||||
`POST /gateways/` (202), `GET|PUT|DELETE /gateways/{gatewayIdentifier}/`, `GET /gateways/?maxResults=&nextToken=`.
|
||||
Targets nested: `POST /gateways/{gatewayIdentifier}/targets/`, `GET|PUT|DELETE /gateways/{gatewayIdentifier}/targets/{targetId}/`,
|
||||
`GET /gateways/{gatewayIdentifier}/targets/?...`. Gateway ARN
|
||||
`arn:aws...:bedrock-agentcore:<region>:<account>:gateway/([0-9a-z][-]?){1,48}-[a-z0-9]{10}`; `gatewayId`
|
||||
`([0-9a-z][-]?){1,100}-[0-9a-z]{10}`; `targetId` `[0-9a-zA-Z]{10}` (targets have no own ARN — return the
|
||||
parent `gatewayArn`). Mutations return 202. `protocolType`: gateway `MCP`, target `MCP|HTTP`.
|
||||
|
||||
### Memory (control plane) — action-suffix REST
|
||||
|
||||
`POST /memories/create` (202, required `name` + `eventExpiryDuration` int 3–365),
|
||||
`GET /memories/{memoryId}/details?view={view}` (200), `PUT /memories/{memoryId}/update` (202),
|
||||
`DELETE /memories/{memoryId}/delete?clientToken={t}` (202), `POST /memories/?maxResults=&nextToken=` (200 list).
|
||||
`memoryId` `[a-zA-Z][a-zA-Z0-9-_]{0,99}-[a-zA-Z0-9]{10}`; ARN unpublished — synthesize
|
||||
`arn:aws:bedrock-agentcore:<region>:<account>:memory/<memoryId>`. status `CREATING|ACTIVE|FAILED|DELETING|UPDATING`
|
||||
→ return `ACTIVE`. `clientToken` is a body field on Create/Update but a query param on Delete.
|
||||
|
||||
## Upgrade path — extending beyond the MVP
|
||||
|
||||
`bedrock-agentcore-control` has ~140 operations; the MVP covers the runtime-centric subset. The rest
|
||||
add incrementally without rework, because every operation reduces to the same Floci recipe.
|
||||
|
||||
### Three wire-protocol styles coexist in this one service
|
||||
Classify each new operation before writing the controller:
|
||||
|
||||
| Style | Shape | Examples | JAX-RS handling |
|
||||
|---|---|---|---|
|
||||
| A. Standard REST | resource in path, verb = HTTP method | Runtimes, Endpoints, Gateways, Targets | `@GET/@PUT/@POST/@DELETE` on the path. Several *list* ops are `POST`, not `GET`. |
|
||||
| B. RPC-in-path | operation name is a path segment; input in body | Workload Identity (`/identities/<Op>`), Credential Providers, Token Vault | one `@POST` per `/identities/<Op>` |
|
||||
| C. Action-suffix REST | resource path + literal action suffix | Memory (`/memories/create`, `/{id}/details`, `/update`, `/delete`) | REST verb + exact suffix in `@Path` |
|
||||
|
||||
Always confirm the exact `Method + Path` on each operation's `API_<Op>.html` page — never assume plain REST.
|
||||
|
||||
### Repeatable recipe (every future op)
|
||||
1. Fetch the API page; record method, path (trailing slashes), success code, required fields, response
|
||||
shape, ID/ARN patterns.
|
||||
2. Add the handler method to the matching controller (or a new `services/<family>/` package), classified A/B/C.
|
||||
3. New resource → add a `StorageFactory` store, a `@RegisterForReflection` model, and (if taggable)
|
||||
extend the `bedrock-agentcore` `TagHandler`. A new *operation* on an existing service needs no new
|
||||
`descriptor(...)` — only a new *service* does.
|
||||
4. Add unit + RestAssured integration tests; run `make docs-sync`.
|
||||
|
||||
### Full operation catalog & status
|
||||
"Planned" = MVP issue set; "Future" = same recipe, not yet scheduled.
|
||||
|
||||
| Resource family | Operations | Style | Status |
|
||||
|---|---|---|---|
|
||||
| Agent Runtime | Create/Get/Update/Delete/List + ListVersions | A | Planned |
|
||||
| Agent Runtime Endpoint | Create/Get/Update/Delete/List | A | Planned |
|
||||
| InvokeAgentRuntime (data plane) | Invoke | A (binary) | Planned |
|
||||
| Tagging | Tag/Untag/ListTagsForResource | A (`/tags/{arn}`) | Planned |
|
||||
| Workload Identity | Create/Get/Update/Delete/List | B | Planned |
|
||||
| Gateway + Gateway Target | Create/Get/Update/Delete/List (×2) | A | Planned |
|
||||
| Memory | Create/Get/Update/Delete/List | C | Planned |
|
||||
| Gateway Rule | Create/Get/Update/Delete/List | A | Future |
|
||||
| Credential Providers (ApiKey/OAuth2/Payment) | Create/Get/Update/Delete/List | B | Future |
|
||||
| Browser / Browser Profile / Code Interpreter | Create/Get/Delete/List | A | Future |
|
||||
| Policy / Policy Engine / Policy Generation | Create/Get/Update/Delete/List + Start/Summary | mixed | Future |
|
||||
| Registry / Registry Record | Create/Get/Update/Delete/List + Submit | mixed | Future |
|
||||
| Dataset / Dataset Version / Examples | Create/Get/Update/Delete/List + Add/Delete examples | mixed | Future |
|
||||
| Evaluator / Online Evaluation Config | Create/Get/Update/Delete/List | A | Future |
|
||||
| Harness / Harness Endpoint | Create/Get/Update/Delete/List | A | Future |
|
||||
| Configuration Bundle | Create/Get/Update/Delete/List (+ versions) | A | Future |
|
||||
| Payment Manager / Connector | Create/Get/Update/Delete/List | mixed | Future |
|
||||
| Token Vault / Resource Policy | Get/Put/Delete/SetCMK | B | Future |
|
||||
|
||||
A future contributor picks any "Future" row, applies the recipe, and files a follow-up referencing the epic.
|
||||
@@ -0,0 +1,93 @@
|
||||
# Bedrock AgentCore
|
||||
|
||||
**Protocol:** REST-JSON
|
||||
**Endpoint:** `http://localhost:4566/runtimes/...`
|
||||
|
||||
Emulates the Amazon Bedrock AgentCore **control plane** (`bedrock-agentcore-control`)
|
||||
as a stateful runtime registry. No real agent execution — runtimes reach `READY`
|
||||
immediately and hold metadata only. See
|
||||
[the design note](../design/bedrock-agentcore.md) for scope and the roadmap covering
|
||||
endpoints, the `InvokeAgentRuntime` data-plane stub, tagging, workload identity, and
|
||||
gateway/memory primitives.
|
||||
|
||||
## Supported Actions
|
||||
|
||||
| Action | Description |
|
||||
|---|---|
|
||||
| `CreateAgentRuntime` | Register an agent runtime; returns an id, versioned ARN, and workload identity |
|
||||
| `GetAgentRuntime` | Get a runtime, optionally a specific `version` |
|
||||
| `ListAgentRuntimes` | List runtimes (paginated) |
|
||||
| `UpdateAgentRuntime` | Update a runtime; appends a new immutable version |
|
||||
| `ListAgentRuntimeVersions` | List a runtime's versions (paginated) |
|
||||
| `DeleteAgentRuntime` | Delete a runtime |
|
||||
| `CreateAgentRuntimeEndpoint` | Create a named endpoint (qualifier) targeting a version |
|
||||
| `GetAgentRuntimeEndpoint` | Get an endpoint |
|
||||
| `UpdateAgentRuntimeEndpoint` | Retarget an endpoint's version / update its description |
|
||||
| `ListAgentRuntimeEndpoints` | List a runtime's endpoints (paginated) |
|
||||
| `DeleteAgentRuntimeEndpoint` | Delete an endpoint |
|
||||
| `InvokeAgentRuntime` *(data plane)* | Invoke a runtime; returns a fixed canned response |
|
||||
| `TagResource` / `UntagResource` / `ListTagsForResource` | Tag runtimes via the shared `/tags/{arn}` route |
|
||||
| `CreateWorkloadIdentity` / `GetWorkloadIdentity` / `UpdateWorkloadIdentity` / `DeleteWorkloadIdentity` / `ListWorkloadIdentities` | Manage workload identities (`POST /identities/<Op>`) |
|
||||
| `CreateGateway` / `GetGateway` / `UpdateGateway` / `DeleteGateway` / `ListGateways` | Manage gateways (metadata only) |
|
||||
| `CreateGatewayTarget` / `GetGatewayTarget` / `UpdateGatewayTarget` / `DeleteGatewayTarget` / `ListGatewayTargets` | Manage gateway targets |
|
||||
| `CreateMemory` / `GetMemory` / `UpdateMemory` / `DeleteMemory` / `ListMemories` | Manage memory resources (metadata only) |
|
||||
|
||||
A `DEFAULT` endpoint is created automatically with each runtime, and each runtime
|
||||
is associated with an auto-created, resolvable workload identity.
|
||||
|
||||
## Data plane — `InvokeAgentRuntime`
|
||||
|
||||
`POST /runtimes/{agentRuntimeArn}/invocations` returns a fixed, configurable JSON
|
||||
body (default `{"output":"yes"}`) and echoes the
|
||||
`X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header. The request payload (opaque
|
||||
binary, up to 100 MB) is never parsed. Streaming responses are not emulated — a
|
||||
single non-streaming `200` is returned.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_CONTROL_ENABLED` | `true` | Enable/disable the control plane |
|
||||
| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_ENABLED` | `true` | Enable/disable the data plane (invoke) |
|
||||
| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_INVOKE_RESPONSE` | `{"output":"yes"}` | Canned `InvokeAgentRuntime` response body |
|
||||
| `FLOCI_SERVICES_BEDROCK_AGENT_CORE_VALIDATE_RUNTIME_EXISTS` | `false` | When `true`, `InvokeAgentRuntime` returns `ResourceNotFoundException` for an unknown runtime ARN instead of the canned response |
|
||||
|
||||
> **Note on YAML config keys.** The status endpoint reports these services as
|
||||
> `bedrock-agentcore-control` and `bedrock-agentcore`, but the YAML property paths
|
||||
> use hyphenated words: `floci.services.bedrock-agent-core-control.enabled` and
|
||||
> `floci.services.bedrock-agent-core.enabled` (and `…bedrock-agent-core.invoke-response`,
|
||||
> `…bedrock-agent-core.validate-runtime-exists`). The `FLOCI_*` environment variables
|
||||
> above map to these paths directly and are the recommended way to configure the service.
|
||||
|
||||
## Behavior notes
|
||||
|
||||
- `agentRuntimeId` is `<name>-<10 alphanumerics>`; the ARN embeds a UUID and the
|
||||
version: `arn:aws:bedrock-agentcore:<region>:<account>:agent/<uuid>:<version>`.
|
||||
- `agentRuntimeName` must match `[a-zA-Z][a-zA-Z0-9_]{0,47}` (no hyphens); invalid
|
||||
names return `ValidationException`.
|
||||
- Each `UpdateAgentRuntime` increments the version and preserves prior versions for
|
||||
`GetAgentRuntime?version=` and `ListAgentRuntimeVersions`.
|
||||
- Timestamps (`createdAt`, `lastUpdatedAt`) are ISO-8601 strings.
|
||||
- Config blobs (`agentRuntimeArtifact`, `networkConfiguration`, …) are stored opaquely
|
||||
and echoed back; they are not deeply validated.
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
|
||||
# Create an agent runtime
|
||||
aws bedrock-agentcore-control create-agent-runtime \
|
||||
--agent-runtime-name myAgent \
|
||||
--agent-runtime-artifact '{"containerConfiguration":{"containerUri":"public.ecr.aws/x/agent:latest"}}' \
|
||||
--network-configuration '{"networkMode":"PUBLIC"}' \
|
||||
--role-arn "arn:aws:iam::000000000000:role/agent-runtime" \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
|
||||
# Get / list
|
||||
aws bedrock-agentcore-control get-agent-runtime --agent-runtime-id <id> --endpoint-url $AWS_ENDPOINT_URL
|
||||
aws bedrock-agentcore-control list-agent-runtimes --endpoint-url $AWS_ENDPOINT_URL
|
||||
|
||||
# Delete
|
||||
aws bedrock-agentcore-control delete-agent-runtime --agent-runtime-id <id> --endpoint-url $AWS_ENDPOINT_URL
|
||||
```
|
||||
@@ -120,6 +120,7 @@ nav:
|
||||
- Lightsail: services/lightsail.md
|
||||
- AppConfig: services/appconfig.md
|
||||
- Bedrock Runtime: services/bedrock-runtime.md
|
||||
- Bedrock AgentCore: services/bedrock-agentcore.md
|
||||
- ELB v2: services/elb.md
|
||||
- Auto Scaling: services/autoscaling.md
|
||||
- Elastic Beanstalk: services/elastic-beanstalk.md
|
||||
|
||||
@@ -575,6 +575,8 @@ public interface EmulatorConfig {
|
||||
EksServiceConfig eks();
|
||||
MwaaServiceConfig mwaa();
|
||||
PipesServiceConfig pipes();
|
||||
BedrockAgentCoreControlServiceConfig bedrockAgentCoreControl();
|
||||
BedrockAgentCoreServiceConfig bedrockAgentCore();
|
||||
ElbV2ServiceConfig elbv2();
|
||||
CodeBuildServiceConfig codebuild();
|
||||
CodeDeployServiceConfig codedeploy();
|
||||
@@ -1603,6 +1605,22 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface BedrockAgentCoreControlServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface BedrockAgentCoreServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("{\"output\":\"yes\"}")
|
||||
String invokeResponse();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean validateRuntimeExists();
|
||||
}
|
||||
|
||||
interface ElbV2ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -12,6 +12,11 @@ import io.github.hectorvent.floci.services.eks.EksController;
|
||||
import io.github.hectorvent.floci.services.mwaa.MwaaController;
|
||||
import io.github.hectorvent.floci.services.iot.IotController;
|
||||
import io.github.hectorvent.floci.services.iot.IotDataController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreGatewayController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreIdentityController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryController;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesController;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaController;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController;
|
||||
@@ -296,6 +301,19 @@ public class ResolvedServiceCatalog {
|
||||
"pipes", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("pipes"), Set.of(), Set.of(PipesController.class)),
|
||||
descriptor("bedrock-agentcore-control", "bedrock-agentcore-control",
|
||||
config.services().bedrockAgentCoreControl().enabled(), true,
|
||||
"bedrockagentcore", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("bedrock-agentcore"), Set.of(),
|
||||
Set.of(BedrockAgentCoreControlController.class, BedrockAgentCoreIdentityController.class,
|
||||
BedrockAgentCoreGatewayController.class, BedrockAgentCoreMemoryController.class)),
|
||||
descriptor("bedrock-agentcore", "bedrock-agentcore",
|
||||
config.services().bedrockAgentCore().enabled(), true,
|
||||
null, null, 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of(), Set.of(),
|
||||
Set.of(BedrockAgentCoreController.class)),
|
||||
descriptor("elasticloadbalancing", "elbv2", config.services().elbv2().enabled(), true,
|
||||
"elbv2", config.storage().mode(), 5000L, AwsNamespaces.ELB_V2, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Amazon Bedrock AgentCore data-plane stub ({@code InvokeAgentRuntime}).
|
||||
*
|
||||
* <p>Real endpoint: {@code POST /runtimes/{agentRuntimeArn}/invocations}. The ARN is
|
||||
* URL-encoded in the path, so the template regex captures the remaining path segments.
|
||||
* The payload (opaque binary, up to 100MB) is never parsed. Returns a fixed canned
|
||||
* body and echoes the runtime session id. Streaming is not emulated.
|
||||
*
|
||||
* <p>By default any ARN is accepted (permissive). When
|
||||
* {@code floci.services.bedrock-agent-core.validate-runtime-exists=true}, an unknown
|
||||
* runtime ARN returns {@code ResourceNotFoundException} (404).
|
||||
*/
|
||||
@Path("/")
|
||||
public class BedrockAgentCoreController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreController.class);
|
||||
private static final String SESSION_HEADER = "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id";
|
||||
|
||||
private final BedrockAgentCoreService service;
|
||||
private final BedrockAgentCoreControlService controlService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final boolean validateRuntimeExists;
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreController(BedrockAgentCoreService service,
|
||||
BedrockAgentCoreControlService controlService,
|
||||
RegionResolver regionResolver,
|
||||
EmulatorConfig config) {
|
||||
this.service = service;
|
||||
this.controlService = controlService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.validateRuntimeExists = config.services().bedrockAgentCore().validateRuntimeExists();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/runtimes/{agentRuntimeArn:.+}/invocations")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response invokeAgentRuntime(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeArn") String agentRuntimeArn,
|
||||
@QueryParam("qualifier") String qualifier,
|
||||
@QueryParam("accountId") String accountId,
|
||||
byte[] payload) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
if (validateRuntimeExists && !controlService.runtimeArnExists(region, agentRuntimeArn)) {
|
||||
return Response.status(404)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("X-Amzn-Errortype", "ResourceNotFoundException")
|
||||
.entity(new AwsErrorResponse("ResourceNotFoundException",
|
||||
"AgentCore runtime not found: " + agentRuntimeArn))
|
||||
.build();
|
||||
}
|
||||
|
||||
String sessionId = headers.getHeaderString(SESSION_HEADER);
|
||||
LOG.debugv("InvokeAgentRuntime: arn={0}, qualifier={1}, bytes={2}",
|
||||
agentRuntimeArn, qualifier, payload == null ? 0 : payload.length);
|
||||
|
||||
Response.ResponseBuilder builder = Response.ok(service.invoke(), MediaType.APPLICATION_JSON);
|
||||
if (sessionId != null) {
|
||||
builder.header(SESSION_HEADER, sessionId);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcore;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Data-plane stub for Amazon Bedrock AgentCore ({@code InvokeAgentRuntime}).
|
||||
*
|
||||
* <p>No real agent execution: returns a fixed, configurable response body for every
|
||||
* invocation. The payload is never parsed.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class BedrockAgentCoreService {
|
||||
|
||||
private final byte[] cannedResponse;
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreService(EmulatorConfig config) {
|
||||
this.cannedResponse = config.services().bedrockAgentCore().invokeResponse()
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public byte[] invoke() {
|
||||
return cannedResponse;
|
||||
}
|
||||
}
|
||||
+442
@@ -0,0 +1,442 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
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.services.bedrockagentcorecontrol.model.AgentRuntimeVersion;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Amazon Bedrock AgentCore control-plane REST-JSON endpoints (runtime registry).
|
||||
*
|
||||
* <p>Real AgentCore control plane uses {@code PUT /runtimes/}, {@code POST /runtimes/}
|
||||
* (list), {@code GET|PUT|DELETE /runtimes/{id}/}, and {@code POST /runtimes/{id}/versions/}.
|
||||
* Mutations return HTTP 202; reads/lists return 200. No real agent execution.
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class BedrockAgentCoreControlController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreControlController.class);
|
||||
|
||||
private final BedrockAgentCoreControlService service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreControlController(BedrockAgentCoreControlService service,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/runtimes/")
|
||||
public Response createAgentRuntime(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
|
||||
AgentRuntime runtime = service.createAgentRuntime(
|
||||
text(req, "agentRuntimeName"),
|
||||
obj(req, "agentRuntimeArtifact"),
|
||||
obj(req, "networkConfiguration"),
|
||||
text(req, "roleArn"),
|
||||
text(req, "description"),
|
||||
stringMap(req.get("environmentVariables")),
|
||||
obj(req, "authorizerConfiguration"),
|
||||
obj(req, "protocolConfiguration"),
|
||||
text(req, "clientToken"),
|
||||
region);
|
||||
Map<String, String> tags = stringMap(req.get("tags"));
|
||||
if (tags != null) {
|
||||
runtime.getTags().putAll(tags);
|
||||
}
|
||||
String version = String.valueOf(runtime.getLatestVersion());
|
||||
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("agentRuntimeArn", service.arn(runtime, version, region));
|
||||
out.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
out.put("agentRuntimeVersion", version);
|
||||
putInstant(out, "createdAt", runtime.getCreatedAt());
|
||||
out.put("status", runtime.getStatus());
|
||||
workloadIdentity(out, runtime);
|
||||
return Response.status(202).entity(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "creating runtime");
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/runtimes/")
|
||||
public Response listAgentRuntimes(@Context HttpHeaders headers,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
ListResult<AgentRuntime> result =
|
||||
service.listAgentRuntimes(maxResults != null ? maxResults : 0, nextToken, region);
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
ArrayNode arr = out.putArray("agentRuntimes");
|
||||
for (AgentRuntime runtime : result.items()) {
|
||||
arr.add(summary(runtime, String.valueOf(runtime.getLatestVersion()), region));
|
||||
}
|
||||
if (result.nextToken() != null) {
|
||||
out.put("nextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "listing runtimes");
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/runtimes/{agentRuntimeId}/")
|
||||
public Response getAgentRuntime(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@QueryParam("version") String version) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
AgentRuntimeVersion snap = service.resolveVersion(runtime, version);
|
||||
String v = snap.getVersion();
|
||||
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("agentRuntimeArn", service.arn(runtime, v, region));
|
||||
out.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
out.put("agentRuntimeName", runtime.getAgentRuntimeName());
|
||||
out.put("agentRuntimeVersion", v);
|
||||
if (snap.getAgentRuntimeArtifact() != null) {
|
||||
out.set("agentRuntimeArtifact", snap.getAgentRuntimeArtifact());
|
||||
}
|
||||
if (snap.getNetworkConfiguration() != null) {
|
||||
out.set("networkConfiguration", snap.getNetworkConfiguration());
|
||||
}
|
||||
if (snap.getAuthorizerConfiguration() != null) {
|
||||
out.set("authorizerConfiguration", snap.getAuthorizerConfiguration());
|
||||
}
|
||||
if (snap.getProtocolConfiguration() != null) {
|
||||
out.set("protocolConfiguration", snap.getProtocolConfiguration());
|
||||
}
|
||||
if (snap.getRoleArn() != null) {
|
||||
out.put("roleArn", snap.getRoleArn());
|
||||
}
|
||||
if (snap.getDescription() != null) {
|
||||
out.put("description", snap.getDescription());
|
||||
}
|
||||
if (snap.getEnvironmentVariables() != null && !snap.getEnvironmentVariables().isEmpty()) {
|
||||
out.set("environmentVariables", objectMapper.valueToTree(snap.getEnvironmentVariables()));
|
||||
}
|
||||
putInstant(out, "createdAt", runtime.getCreatedAt());
|
||||
putInstant(out, "lastUpdatedAt", runtime.getLastUpdatedAt());
|
||||
out.put("status", runtime.getStatus());
|
||||
workloadIdentity(out, runtime);
|
||||
return Response.ok(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "getting runtime");
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/runtimes/{agentRuntimeId}/")
|
||||
public Response updateAgentRuntime(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
|
||||
AgentRuntime runtime = service.updateAgentRuntime(
|
||||
id,
|
||||
obj(req, "agentRuntimeArtifact"),
|
||||
obj(req, "networkConfiguration"),
|
||||
text(req, "roleArn"),
|
||||
text(req, "description"),
|
||||
stringMap(req.get("environmentVariables")),
|
||||
obj(req, "authorizerConfiguration"),
|
||||
obj(req, "protocolConfiguration"),
|
||||
region);
|
||||
String version = String.valueOf(runtime.getLatestVersion());
|
||||
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("agentRuntimeArn", service.arn(runtime, version, region));
|
||||
out.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
out.put("agentRuntimeVersion", version);
|
||||
putInstant(out, "createdAt", runtime.getCreatedAt());
|
||||
putInstant(out, "lastUpdatedAt", runtime.getLastUpdatedAt());
|
||||
out.put("status", runtime.getStatus());
|
||||
workloadIdentity(out, runtime);
|
||||
return Response.status(202).entity(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "updating runtime");
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/runtimes/{agentRuntimeId}/versions/")
|
||||
public Response listAgentRuntimeVersions(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
ListResult<AgentRuntimeVersion> result =
|
||||
service.listAgentRuntimeVersions(id, maxResults != null ? maxResults : 0, nextToken, region);
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
ArrayNode arr = out.putArray("agentRuntimes");
|
||||
for (AgentRuntimeVersion snap : result.items()) {
|
||||
arr.add(versionSummary(runtime, snap, region));
|
||||
}
|
||||
if (result.nextToken() != null) {
|
||||
out.put("nextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "listing runtime versions");
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/runtimes/{agentRuntimeId}/")
|
||||
public Response deleteAgentRuntime(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@QueryParam("clientToken") String clientToken) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntime runtime = service.deleteAgentRuntime(id, clientToken, region);
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
out.put("status", runtime.getStatus());
|
||||
return Response.status(202).entity(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "deleting runtime");
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Endpoints (Phase 2) ────────────────────────────
|
||||
|
||||
@PUT
|
||||
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/")
|
||||
public Response createEndpoint(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
|
||||
AgentRuntimeEndpoint endpoint = service.createEndpoint(id, text(req, "name"),
|
||||
text(req, "agentRuntimeVersion"), text(req, "description"), text(req, "clientToken"), region);
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
return Response.status(202).entity(endpointResponse(runtime, endpoint, region, false)).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "creating endpoint");
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/")
|
||||
public Response getEndpoint(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@PathParam("endpointName") String name) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
AgentRuntimeEndpoint endpoint = service.getEndpoint(id, name, region);
|
||||
return Response.ok(endpointResponse(runtime, endpoint, region, true)).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "getting endpoint");
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/")
|
||||
public Response updateEndpoint(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@PathParam("endpointName") String name,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
|
||||
AgentRuntimeEndpoint endpoint = service.updateEndpoint(id, name,
|
||||
text(req, "agentRuntimeVersion"), text(req, "description"), region);
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
return Response.status(202).entity(endpointResponse(runtime, endpoint, region, true)).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "updating endpoint");
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/{endpointName}/")
|
||||
public Response deleteEndpoint(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@PathParam("endpointName") String name,
|
||||
@QueryParam("clientToken") String clientToken) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntimeEndpoint endpoint = service.deleteEndpoint(id, name, clientToken, region);
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
out.put("agentRuntimeId", id);
|
||||
out.put("endpointName", endpoint.getName());
|
||||
out.put("status", endpoint.getStatus());
|
||||
return Response.status(202).entity(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "deleting endpoint");
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/")
|
||||
public Response listEndpoints(@Context HttpHeaders headers,
|
||||
@PathParam("agentRuntimeId") String id,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
AgentRuntime runtime = service.getAgentRuntime(id, region);
|
||||
ListResult<AgentRuntimeEndpoint> result =
|
||||
service.listEndpoints(id, maxResults != null ? maxResults : 0, nextToken, region);
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
ArrayNode arr = out.putArray("runtimeEndpoints");
|
||||
for (AgentRuntimeEndpoint endpoint : result.items()) {
|
||||
arr.add(endpointResponse(runtime, endpoint, region, true));
|
||||
}
|
||||
if (result.nextToken() != null) {
|
||||
out.put("nextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(out).build();
|
||||
} catch (Exception e) {
|
||||
return error(e, "listing endpoints");
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode endpointResponse(AgentRuntime runtime, AgentRuntimeEndpoint endpoint,
|
||||
String region, boolean full) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("agentRuntimeArn", service.arn(runtime, endpoint.getTargetVersion(), region));
|
||||
node.put("agentRuntimeEndpointArn", service.endpointArn(endpoint, region));
|
||||
node.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
node.put("endpointName", endpoint.getName());
|
||||
node.put("status", endpoint.getStatus());
|
||||
node.put("targetVersion", endpoint.getTargetVersion());
|
||||
putInstant(node, "createdAt", endpoint.getCreatedAt());
|
||||
if (full) {
|
||||
node.put("id", endpoint.getUuid());
|
||||
node.put("name", endpoint.getName());
|
||||
if (endpoint.getLiveVersion() != null) {
|
||||
node.put("liveVersion", endpoint.getLiveVersion());
|
||||
}
|
||||
if (endpoint.getDescription() != null) {
|
||||
node.put("description", endpoint.getDescription());
|
||||
}
|
||||
putInstant(node, "lastUpdatedAt", endpoint.getLastUpdatedAt());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private ObjectNode summary(AgentRuntime runtime, String version, String region) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("agentRuntimeArn", service.arn(runtime, version, region));
|
||||
node.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
node.put("agentRuntimeName", runtime.getAgentRuntimeName());
|
||||
node.put("agentRuntimeVersion", version);
|
||||
if (runtime.getDescription() != null) {
|
||||
node.put("description", runtime.getDescription());
|
||||
}
|
||||
putInstant(node, "lastUpdatedAt", runtime.getLastUpdatedAt());
|
||||
node.put("status", runtime.getStatus());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode versionSummary(AgentRuntime runtime, AgentRuntimeVersion snap, String region) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("agentRuntimeArn", service.arn(runtime, snap.getVersion(), region));
|
||||
node.put("agentRuntimeId", runtime.getAgentRuntimeId());
|
||||
node.put("agentRuntimeName", runtime.getAgentRuntimeName());
|
||||
node.put("agentRuntimeVersion", snap.getVersion());
|
||||
if (snap.getDescription() != null) {
|
||||
node.put("description", snap.getDescription());
|
||||
}
|
||||
putInstant(node, "lastUpdatedAt", snap.getCreatedAt());
|
||||
node.put("status", runtime.getStatus());
|
||||
return node;
|
||||
}
|
||||
|
||||
private void workloadIdentity(ObjectNode out, AgentRuntime runtime) {
|
||||
if (runtime.getWorkloadIdentityArn() != null) {
|
||||
ObjectNode wi = out.putObject("workloadIdentityDetails");
|
||||
wi.put("workloadIdentityArn", runtime.getWorkloadIdentityArn());
|
||||
}
|
||||
}
|
||||
|
||||
private static void putInstant(ObjectNode node, String field, Instant instant) {
|
||||
if (instant != null) {
|
||||
// AgentCore models these as ISO-8601 strings; second precision stays within
|
||||
// AWS's 20-char timestamp limit.
|
||||
node.put(field, instant.truncatedTo(java.time.temporal.ChronoUnit.SECONDS).toString());
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return (v == null || v.isNull()) ? null : v.asText();
|
||||
}
|
||||
|
||||
private static JsonNode obj(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return (v == null || v.isNull() || v.isMissingNode()) ? null : v;
|
||||
}
|
||||
|
||||
private static Map<String, String> stringMap(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> map = new HashMap<>();
|
||||
node.fields().forEachRemaining(e -> map.put(e.getKey(), e.getValue().asText()));
|
||||
return map;
|
||||
}
|
||||
|
||||
private Response error(Exception e, String action) {
|
||||
if (e instanceof AwsException aws) {
|
||||
return Response.status(aws.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("X-Amzn-Errortype", aws.jsonType())
|
||||
.entity(new AwsErrorResponse(aws.jsonType(), aws.getMessage()))
|
||||
.build();
|
||||
}
|
||||
LOG.errorv(e, "Error {0}", action);
|
||||
return Response.status(400)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.header("X-Amzn-Errortype", "ValidationException")
|
||||
.entity(new AwsErrorResponse("ValidationException", e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Business logic for the Amazon Bedrock AgentCore control plane (runtime registry).
|
||||
*
|
||||
* <p>Stateful CRUD only: no real agent execution. Runtimes reach {@code READY}
|
||||
* immediately. Each {@code UpdateAgentRuntime} appends an immutable version snapshot.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class BedrockAgentCoreControlService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreControlService.class);
|
||||
|
||||
static final String STATUS_READY = "READY";
|
||||
static final String STATUS_DELETING = "DELETING";
|
||||
private static final String ARN_SERVICE = "bedrock-agentcore";
|
||||
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}");
|
||||
private static final String ID_ALPHABET =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final int MAX_PAGE = 100;
|
||||
private static final int DEFAULT_PAGE = 100;
|
||||
|
||||
private final StorageBackend<String, AgentRuntime> storage;
|
||||
private final RegionResolver regionResolver;
|
||||
private final BedrockAgentCoreIdentityService identityService;
|
||||
// clientToken idempotency: tokens of completed deletes, so a replayed delete succeeds
|
||||
// instead of 404ing. In-memory only (reset on restart) — sufficient for an emulator.
|
||||
private final Set<String> deletedRuntimeTokens = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> deletedEndpointTokens = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public BedrockAgentCoreControlService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
BedrockAgentCoreIdentityService identityService) {
|
||||
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-runtimes.json",
|
||||
new TypeReference<Map<String, AgentRuntime>>() {}), regionResolver, identityService);
|
||||
}
|
||||
|
||||
BedrockAgentCoreControlService(StorageBackend<String, AgentRuntime> storage, RegionResolver regionResolver) {
|
||||
this(storage, regionResolver, null);
|
||||
}
|
||||
|
||||
BedrockAgentCoreControlService(StorageBackend<String, AgentRuntime> storage, RegionResolver regionResolver,
|
||||
BedrockAgentCoreIdentityService identityService) {
|
||||
this.storage = storage;
|
||||
this.regionResolver = regionResolver;
|
||||
this.identityService = identityService;
|
||||
}
|
||||
|
||||
public AgentRuntime createAgentRuntime(String name, JsonNode artifact, JsonNode networkConfiguration,
|
||||
String roleArn, String description, Map<String, String> environmentVariables,
|
||||
JsonNode authorizerConfiguration, JsonNode protocolConfiguration,
|
||||
String clientToken, String region) {
|
||||
if (clientToken != null) {
|
||||
Optional<AgentRuntime> replay = storage.scan(k -> k.startsWith(keyPrefix(region))).stream()
|
||||
.filter(r -> clientToken.equals(r.getClientToken()))
|
||||
.findFirst();
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
}
|
||||
if (name == null || !NAME_PATTERN.matcher(name).matches()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"agentRuntimeName must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
String id = name + "-" + randomId();
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
|
||||
AgentRuntime runtime = new AgentRuntime();
|
||||
runtime.setAgentRuntimeId(id);
|
||||
runtime.setAgentRuntimeName(name);
|
||||
runtime.setUuid(uuid);
|
||||
runtime.setRoleArn(roleArn);
|
||||
runtime.setDescription(description);
|
||||
runtime.setStatus(STATUS_READY);
|
||||
runtime.setLatestVersion(1);
|
||||
runtime.setCreatedAt(now);
|
||||
runtime.setLastUpdatedAt(now);
|
||||
runtime.setAccountId(regionResolver.getAccountId());
|
||||
runtime.setAgentRuntimeArtifact(artifact);
|
||||
runtime.setNetworkConfiguration(networkConfiguration);
|
||||
runtime.setAuthorizerConfiguration(authorizerConfiguration);
|
||||
runtime.setProtocolConfiguration(protocolConfiguration);
|
||||
runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>());
|
||||
runtime.setClientToken(clientToken);
|
||||
String workloadName = name + "-" + randomId();
|
||||
if (identityService != null) {
|
||||
runtime.setWorkloadIdentityArn(
|
||||
identityService.createForRuntime(workloadName, region).getWorkloadIdentityArn());
|
||||
} else {
|
||||
runtime.setWorkloadIdentityArn(regionResolver.buildArn(ARN_SERVICE, region,
|
||||
"workload-identity-directory/default/workload-identity/" + workloadName));
|
||||
}
|
||||
runtime.getVersions().add(snapshot(runtime, "1", now));
|
||||
runtime.getEndpoints().add(newEndpoint("DEFAULT", "1", null, now));
|
||||
|
||||
storage.put(key(region, id), runtime);
|
||||
LOG.infov("Created AgentCore runtime {0} (id={1})", name, id);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
public AgentRuntime getAgentRuntime(String id, String region) {
|
||||
return storage.get(key(region, id))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"AgentCore runtime not found: " + id, 404));
|
||||
}
|
||||
|
||||
/** Returns the snapshot matching {@code version}, or the latest when {@code version} is null. */
|
||||
public AgentRuntimeVersion resolveVersion(AgentRuntime runtime, String version) {
|
||||
String wanted = version != null ? version : String.valueOf(runtime.getLatestVersion());
|
||||
return runtime.getVersions().stream()
|
||||
.filter(v -> wanted.equals(v.getVersion()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"AgentCore runtime version not found: " + wanted, 404));
|
||||
}
|
||||
|
||||
public AgentRuntime updateAgentRuntime(String id, JsonNode artifact, JsonNode networkConfiguration,
|
||||
String roleArn, String description, Map<String, String> 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);
|
||||
}
|
||||
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);
|
||||
if (authorizerConfiguration != null) {
|
||||
runtime.setAuthorizerConfiguration(authorizerConfiguration);
|
||||
}
|
||||
if (protocolConfiguration != null) {
|
||||
runtime.setProtocolConfiguration(protocolConfiguration);
|
||||
}
|
||||
if (environmentVariables != null) {
|
||||
runtime.setEnvironmentVariables(new HashMap<>(environmentVariables));
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) {
|
||||
Optional<AgentRuntime> 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);
|
||||
}
|
||||
AgentRuntime runtime = found.get();
|
||||
storage.delete(key(region, id));
|
||||
if (clientToken != null) {
|
||||
deletedRuntimeTokens.add(tokenKey(region, clientToken));
|
||||
}
|
||||
runtime.setStatus(STATUS_DELETING);
|
||||
LOG.infov("Deleted AgentCore runtime {0}", id);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private static String tokenKey(String region, String clientToken) {
|
||||
return region + " | ||||