fix(cloudformation): provision Bedrock application inference profiles (#8772)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-17 21:08:02 -04:00
1 parent 261fcac13a
commit 6bde4e6bb3
20 files changed
+1778 -57

No files matched your search

@@ -8,6 +8,7 @@ import io.floci.aws.core.common.JsonErrorResponseUtils;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile;
import io.floci.aws.services.bedrock.model.Guardrail;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -179,13 +180,13 @@ public class BedrockController {
@QueryParam("nextToken") String nextToken,
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
PaginatedResult<BedrockModelCatalog.InferenceProfile> page = bedrockService.listInferenceProfiles(typeEquals,
PaginatedResult<BedrockService.InferenceProfileView> page = bedrockService.listInferenceProfiles(typeEquals,
Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode summaries = response.putArray("inferenceProfileSummaries");
for (BedrockModelCatalog.InferenceProfile profile : page.items()) {
summaries.add(inferenceProfileNode(profile, region));
for (BedrockService.InferenceProfileView profile : page.items()) {
summaries.add(inferenceProfileNode(profile));
}
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
@@ -199,7 +200,31 @@ public class BedrockController {
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
return Response.ok(inferenceProfileNode(
bedrockService.getInferenceProfile(inferenceProfileIdentifier, region), region)).build();
bedrockService.getInferenceProfile(inferenceProfileIdentifier, region))).build();
}
@POST
@Path("/inference-profiles")
public Response createInferenceProfile(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
ApplicationInferenceProfile profile = bedrockService.createApplicationInferenceProfile(
textOrNull(request, "inferenceProfileName"), textOrNull(request, "description"),
textOrNull(request.path("modelSource"), "copyFrom"),
applicationProfileTags(request.get("tags")),
textOrNull(request, "clientRequestToken"), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("inferenceProfileArn", profile.getInferenceProfileArn());
response.put("status", "ACTIVE");
return Response.status(201).entity(response).build();
}
@DELETE
@Path("/inference-profiles/{inferenceProfileIdentifier: .+}")
public Response deleteInferenceProfile(@PathParam("inferenceProfileIdentifier") String identifier,
@Context HttpHeaders headers) {
bedrockService.deleteApplicationInferenceProfile(identifier, regionResolver.resolveRegion(headers));
return Response.ok(objectMapper.createObjectNode()).build();
}
// Resource policies
@@ -246,7 +271,7 @@ public class BedrockController {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
bedrockService.tagResource(textOrNull(request, "resourceARN"),
BedrockService.parseTagList(request.get("tags")), region);
bedrockTagResourceTags(request.get("tags")), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -312,7 +337,7 @@ public class BedrockController {
private ObjectNode foundationModelNode(BedrockModelCatalog.FoundationModel model, String region) {
ObjectNode node = objectMapper.createObjectNode();
node.put("modelArn", foundationModelArn(model.modelId(), region));
node.put("modelArn", bedrockService.foundationModelArn(model.modelId(), region));
node.put("modelId", model.modelId());
node.put("modelName", model.modelName());
node.put("providerName", model.providerName());
@@ -328,27 +353,25 @@ public class BedrockController {
return node;
}
private ObjectNode inferenceProfileNode(BedrockModelCatalog.InferenceProfile profile, String region) {
private ObjectNode inferenceProfileNode(BedrockService.InferenceProfileView profile) {
ObjectNode node = objectMapper.createObjectNode();
node.put("inferenceProfileName", profile.inferenceProfileName());
node.put("inferenceProfileArn", regionResolver.buildArn("bedrock", region,
"inference-profile/" + profile.inferenceProfileId()));
node.put("inferenceProfileArn", profile.inferenceProfileArn());
node.put("inferenceProfileId", profile.inferenceProfileId());
if (profile.description() != null) {
node.put("description", profile.description());
}
node.put("createdAt", iso8601(profile.createdAt()));
node.put("updatedAt", iso8601(profile.createdAt()));
node.put("updatedAt", iso8601(profile.updatedAt()));
ArrayNode models = node.putArray("models");
for (String destination : profile.routes().get(region)) {
models.addObject().put("modelArn", foundationModelArn(profile.modelId(), destination));
for (String modelArn : profile.models()) {
models.addObject().put("modelArn", modelArn);
}
node.put("status", "ACTIVE");
node.put("type", "SYSTEM_DEFINED");
node.put("type", profile.type());
return node;
}
private String foundationModelArn(String modelId, String region) {
return regionResolver.buildArn("bedrock", region, "", "foundation-model/" + modelId);
}
private ObjectNode guardrailSummaryNode(Guardrail guardrail) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", guardrail.getGuardrailId());
@@ -390,4 +413,14 @@ public class BedrockController {
}
return value.asText();
}
private static Map<String, String> applicationProfileTags(JsonNode tags) {
BedrockTagValidator.validate(tags, "key", "value", "ValidationException", "tags");
return BedrockService.parseTagList(tags);
}
private static Map<String, String> bedrockTagResourceTags(JsonNode tags) {
BedrockTagValidator.validateRequired(tags, "key", "value", "ValidationException", "tags");
return BedrockService.parseTagList(tags);
}
}
@@ -17,6 +17,7 @@ import io.floci.aws.core.resource.ResourceProvider;
import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile;
import io.floci.aws.services.bedrock.model.Guardrail;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
@@ -74,7 +75,14 @@ public class BedrockService implements ResourceProvider {
private static final List<String> CUSTOMIZATION_TYPES = List.of("FINE_TUNING", "CONTINUED_PRE_TRAINING", "DISTILLATION");
private static final String FOUNDATION_MODEL_PREFIX = "foundation-model/";
private static final String INFERENCE_PROFILE_PREFIX = "inference-profile/";
private static final String APPLICATION_INFERENCE_PROFILE_PREFIX = "application-inference-profile/";
private static final List<String> INFERENCE_PROFILE_TYPES = List.of("SYSTEM_DEFINED", "APPLICATION");
private static final Pattern APPLICATION_PROFILE_NAME_PATTERN =
Pattern.compile("([0-9a-zA-Z][ _-]?)+");
private static final Pattern APPLICATION_PROFILE_DESCRIPTION_PATTERN =
Pattern.compile("([0-9a-zA-Z:.][ _-]?)+");
private static final Pattern IDEMPOTENCY_TOKEN_PATTERN =
Pattern.compile("[a-zA-Z0-9]([-a-zA-Z0-9]{0,254}[a-zA-Z0-9])?");
/** {@code TagList} from the AWS model: at most 200 items on one request. */
private static final int TAG_LIST_MAX = 200;
@@ -130,6 +138,7 @@ public class BedrockService implements ResourceProvider {
* Region that received {@code PutResourcePolicy}, so one ARN can hold a different policy per Region.
*/
private final StorageBackend<String, String> guardrailProfilePolicies;
private final StorageBackend<String, ApplicationInferenceProfile> applicationInferenceProfiles;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final KmsService kmsService;
@@ -141,14 +150,19 @@ public class BedrockService implements ResourceProvider {
new TypeReference<Map<String, Guardrail>>() {}),
storageFactory.create("bedrock", "bedrock-guardrail-profile-policies.json",
new TypeReference<Map<String, String>>() {}),
storageFactory.create("bedrock", "bedrock-application-inference-profiles.json",
new TypeReference<Map<String, ApplicationInferenceProfile>>() {}),
regionResolver, objectMapper, kmsService);
}
BedrockService(StorageBackend<String, Guardrail> guardrails,
StorageBackend<String, String> guardrailProfilePolicies, RegionResolver regionResolver,
StorageBackend<String, String> guardrailProfilePolicies,
StorageBackend<String, ApplicationInferenceProfile> applicationInferenceProfiles,
RegionResolver regionResolver,
ObjectMapper objectMapper, KmsService kmsService) {
this.guardrails = guardrails;
this.guardrailProfilePolicies = guardrailProfilePolicies;
this.applicationInferenceProfiles = applicationInferenceProfiles;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.kmsService = kmsService;
@@ -308,25 +322,194 @@ public class BedrockService implements ResourceProvider {
throw invalidModelIdentifier();
}
public PaginatedResult<BedrockModelCatalog.InferenceProfile> listInferenceProfiles(String typeEquals,
Integer maxResults,
String nextToken, String region) {
requireOneOf("typeEquals", typeEquals, INFERENCE_PROFILE_TYPES);
// Only system-defined profiles exist: application inference profiles cannot be created yet.
List<BedrockModelCatalog.InferenceProfile> profiles = "APPLICATION".equals(typeEquals)
? List.of()
: BedrockModelCatalog.profilesFrom(region);
return Pagination.paginate(profiles, BedrockModelCatalog.InferenceProfile::inferenceProfileId,
maxResults, nextToken, MAX_PAGE, "ValidationException");
public record InferenceProfileView(String inferenceProfileId, String inferenceProfileArn,
String inferenceProfileName, String description, List<String> models,
Instant createdAt, Instant updatedAt, String type) {
}
public BedrockModelCatalog.InferenceProfile getInferenceProfile(String inferenceProfileIdentifier, String region) {
public synchronized ApplicationInferenceProfile createApplicationInferenceProfile(
String name, String description, String copyFrom, Map<String, String> tags, String region) {
return createApplicationInferenceProfile(name, description, copyFrom, tags, null, region);
}
public synchronized ApplicationInferenceProfile createApplicationInferenceProfile(
String name, String description, String copyFrom, Map<String, String> tags,
String clientRequestToken, String region) {
if (clientRequestToken != null) {
if (clientRequestToken.length() > 256 || !IDEMPOTENCY_TOKEN_PATTERN.matcher(clientRequestToken).matches()) {
throw new AwsException("ValidationException", "clientRequestToken is invalid.", 400);
}
Optional<ApplicationInferenceProfile> previous = applicationsIn(region).stream()
.filter(profile -> clientRequestToken.equals(profile.getClientRequestToken()))
.findFirst();
if (previous.isPresent()) {
return previous.get();
}
}
if (name == null || name.length() > 64 || !APPLICATION_PROFILE_NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException", "inferenceProfileName is invalid.", 400);
}
if (description != null && (description.length() > 200
|| !APPLICATION_PROFILE_DESCRIPTION_PATTERN.matcher(description).matches())) {
throw new AwsException("ValidationException", "description is invalid.", 400);
}
List<String> models = modelsFromSource(copyFrom, region);
if (applicationsIn(region).stream().anyMatch(profile -> name.equals(profile.getInferenceProfileName()))) {
throw new AwsException("ConflictException", "Inference profile " + name + " already exists.", 400);
}
String id = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
String arn = regionResolver.buildArn("bedrock", region, APPLICATION_INFERENCE_PROFILE_PREFIX + id);
Map<String, String> initialTags = tags == null ? Map.of() : Map.copyOf(tags);
if (initialTags.size() > TAGS_PER_RESOURCE_MAX) {
throw tooManyTags(arn, initialTags.size());
}
Instant now = Instant.now();
ApplicationInferenceProfile profile = new ApplicationInferenceProfile();
profile.setInferenceProfileId(id);
profile.setInferenceProfileArn(arn);
profile.setInferenceProfileName(name);
profile.setDescription(description);
profile.setModels(models);
profile.setCreatedAt(now);
profile.setUpdatedAt(now);
profile.setTags(initialTags);
profile.setAccountId(regionResolver.getAccountId());
profile.setRegion(region);
profile.setClientRequestToken(clientRequestToken);
applicationInferenceProfiles.put(applicationProfileKey(region, id), profile);
LOG.infov("Created Bedrock application inference profile: {0}", id);
return profile;
}
public ApplicationInferenceProfile getApplicationInferenceProfile(String identifier, String region) {
String id = applicationProfileIdOf(identifier, region);
return applicationInferenceProfiles.get(applicationProfileKey(region, id))
.orElseThrow(() -> profileNotFound(identifier));
}
public synchronized void deleteApplicationInferenceProfile(String identifier, String region) {
ApplicationInferenceProfile profile = getApplicationInferenceProfile(identifier, region);
applicationInferenceProfiles.delete(applicationProfileKey(region, profile.getInferenceProfileId()));
LOG.infov("Deleted Bedrock application inference profile: {0}", profile.getInferenceProfileId());
}
public PaginatedResult<InferenceProfileView> listInferenceProfiles(String typeEquals,
Integer maxResults,
String nextToken, String region) {
requireOneOf("typeEquals", typeEquals, INFERENCE_PROFILE_TYPES);
List<InferenceProfileView> profiles = new ArrayList<>();
if (!"APPLICATION".equals(typeEquals)) {
BedrockModelCatalog.profilesFrom(region).stream()
.map(profile -> systemProfileView(profile, region)).forEach(profiles::add);
}
if (!"SYSTEM_DEFINED".equals(typeEquals)) {
applicationsIn(region).stream().map(BedrockService::applicationProfileView).forEach(profiles::add);
}
String scope = "bedrock-inference-profiles:" + regionResolver.getAccountId() + ":" + region + ":"
+ (typeEquals == null ? "ALL" : typeEquals);
return Pagination.paginate(profiles, InferenceProfileView::inferenceProfileId,
maxResults, nextToken, MAX_PAGE, MAX_PAGE, 2048, "ValidationException", scope, true);
}
public InferenceProfileView getInferenceProfile(String inferenceProfileIdentifier, String region) {
AwsArnUtils.Arn arn = arnOf(inferenceProfileIdentifier);
if (arn != null && arn.resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX)) {
return applicationProfileView(getApplicationInferenceProfile(inferenceProfileIdentifier, region));
}
if (arn == null) {
Optional<ApplicationInferenceProfile> application = applicationInferenceProfiles.get(
applicationProfileKey(region, inferenceProfileIdentifier));
if (application.isPresent()) {
return applicationProfileView(application.get());
}
}
String profileId = inferenceProfileIdOf(inferenceProfileIdentifier, region);
return BedrockModelCatalog.profilesFrom(region).stream()
.filter(profile -> profile.inferenceProfileId().equals(profileId))
.map(profile -> systemProfileView(profile, region))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The inference profile " + inferenceProfileIdentifier + " was not found.", 404));
.orElseThrow(() -> profileNotFound(inferenceProfileIdentifier));
}
private List<String> modelsFromSource(String copyFrom, String region) {
AwsArnUtils.Arn arn = arnOf(copyFrom);
if (arn == null || !isBedrockArnIn(arn, region)) {
throw new AwsException("ValidationException", "modelSource.copyFrom must be a Bedrock ARN in this Region.", 400);
}
if (arn.resource().startsWith(FOUNDATION_MODEL_PREFIX) && arn.accountId().isEmpty()) {
String modelId = arn.resource().substring(FOUNDATION_MODEL_PREFIX.length());
getFoundationModel(copyFrom, region);
if (BedrockModelCatalog.MODELS.stream().noneMatch(model -> model.modelId().equals(modelId)
&& model.servedInRegion(region))) {
throw new AwsException("ValidationException", "The foundation model is not served in this Region.", 400);
}
return List.of(copyFrom);
}
if (arn.resource().startsWith(INFERENCE_PROFILE_PREFIX)
&& arn.accountId().equals(regionResolver.getAccountId())) {
String profileId = arn.resource().substring(INFERENCE_PROFILE_PREFIX.length());
BedrockModelCatalog.InferenceProfile profile = BedrockModelCatalog.profilesFrom(region).stream()
.filter(candidate -> candidate.inferenceProfileId().equals(profileId))
.findFirst().orElseThrow(() -> profileNotFound(copyFrom));
return systemProfileModelArns(profile, region);
}
throw new AwsException("ValidationException", "modelSource.copyFrom must name a foundation model "
+ "or system-defined inference profile.", 400);
}
private InferenceProfileView systemProfileView(BedrockModelCatalog.InferenceProfile profile, String region) {
return new InferenceProfileView(profile.inferenceProfileId(), regionResolver.buildArn("bedrock", region,
INFERENCE_PROFILE_PREFIX + profile.inferenceProfileId()), profile.inferenceProfileName(),
null, systemProfileModelArns(profile, region), profile.createdAt(), profile.createdAt(),
"SYSTEM_DEFINED");
}
private List<String> systemProfileModelArns(BedrockModelCatalog.InferenceProfile profile, String region) {
return profile.routes().get(region).stream()
.map(destination -> foundationModelArn(profile.modelId(), destination)).toList();
}
public String foundationModelArn(String modelId, String region) {
return regionResolver.buildArn("bedrock", region, "", FOUNDATION_MODEL_PREFIX + modelId);
}
private static InferenceProfileView applicationProfileView(ApplicationInferenceProfile profile) {
return new InferenceProfileView(profile.getInferenceProfileId(), profile.getInferenceProfileArn(),
profile.getInferenceProfileName(), profile.getDescription(), profile.getModels(),
profile.getCreatedAt(), profile.getUpdatedAt(), "APPLICATION");
}
private List<ApplicationInferenceProfile> applicationsIn(String region) {
String prefix = regionResolver.getAccountId() + "::" + region + "::";
return applicationInferenceProfiles.scan(key -> key.startsWith(prefix));
}
private String applicationProfileKey(String region, String id) {
return regionResolver.getAccountId() + "::" + region + "::" + id;
}
private String applicationProfileIdOf(String identifier, String region) {
AwsArnUtils.Arn arn = arnOf(identifier);
if (arn == null) {
return identifier;
}
if (!"bedrock".equals(arn.service()) || arn.accountId().isEmpty()) {
throw new AwsException("ValidationException", "The provided inference profile identifier is invalid.", 400);
}
if (!arn.accountId().equals(regionResolver.getAccountId())) {
throw new AwsException("AccessDeniedException",
"You don't have access to the inference profile " + identifier + ".", 403);
}
if (!isBedrockArnIn(arn, region) || !arn.resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX)) {
throw profileNotFound(identifier);
}
return arn.resource().substring(APPLICATION_INFERENCE_PROFILE_PREFIX.length());
}
private static AwsException profileNotFound(String identifier) {
return new AwsException("ResourceNotFoundException",
"The inference profile " + identifier + " was not found.", 404);
}
/**
@@ -466,6 +649,10 @@ public class BedrockService implements ResourceProvider {
// Tags
public Map<String, String> listTags(String resourceArn, String region) {
if (isApplicationProfileResource(resourceArn, region)) {
ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region);
return profile.getTags() != null ? Map.copyOf(profile.getTags()) : Map.of();
}
Guardrail guardrail = findByArn(resourceArn, region);
return guardrail.getTags() != null ? guardrail.getTags() : Map.of();
}
@@ -476,6 +663,17 @@ public class BedrockService implements ResourceProvider {
* the value of a key already present does not add to that total.
*/
public synchronized void tagResource(String resourceArn, Map<String, String> tags, String region) {
if (isApplicationProfileResource(resourceArn, region)) {
ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region);
Map<String, String> merged = new HashMap<>(profile.getTags() != null ? profile.getTags() : Map.of());
merged.putAll(tags);
if (merged.size() > TAGS_PER_RESOURCE_MAX) {
throw tooManyTags(profile.getInferenceProfileArn(), merged.size());
}
applicationInferenceProfiles.put(applicationProfileKey(region, profile.getInferenceProfileId()),
applicationProfileWithTags(profile, merged));
return;
}
Guardrail guardrail = findByArn(resourceArn, region);
Map<String, String> merged = guardrail.getTags() == null
? new HashMap<>()
@@ -489,6 +687,16 @@ public class BedrockService implements ResourceProvider {
}
public synchronized void untagResource(String resourceArn, List<String> tagKeys, String region) {
if (isApplicationProfileResource(resourceArn, region)) {
ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region);
Map<String, String> remaining = new HashMap<>(profile.getTags() != null ? profile.getTags() : Map.of());
if (tagKeys != null) {
tagKeys.forEach(remaining::remove);
}
applicationInferenceProfiles.put(applicationProfileKey(region, profile.getInferenceProfileId()),
applicationProfileWithTags(profile, remaining));
return;
}
Guardrail guardrail = findByArn(resourceArn, region);
if (guardrail.getTags() != null && tagKeys != null) {
tagKeys.forEach(guardrail.getTags()::remove);
@@ -512,12 +720,50 @@ public class BedrockService implements ResourceProvider {
guardrail.getCreatedAt() != null ? guardrail.getCreatedAt() : Instant.now(),
guardrail.getTags() != null ? guardrail.getTags() : Map.of())));
}
for (String key : applicationInferenceProfiles.keys()) {
applicationInferenceProfiles.get(key).ifPresent(profile -> resources.add(new ExplorerResource(
profile.getInferenceProfileArn(), "bedrock:application-inference-profile", "bedrock",
profile.getRegion(), profile.getAccountId(), profile.getCreatedAt(),
profile.getTags() != null ? profile.getTags() : Map.of())));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("bedrock:guardrail", "bedrock", true));
return Set.of(new SupportedResourceType("bedrock:guardrail", "bedrock", true),
new SupportedResourceType("bedrock:application-inference-profile", "bedrock", true));
}
private boolean isApplicationProfileResource(String identifier, String region) {
if (identifier == null) {
return false;
}
if (!AwsArnUtils.looksLikeArn(identifier)) {
return applicationInferenceProfiles.get(applicationProfileKey(region, identifier)).isPresent();
}
try {
return AwsArnUtils.parse(identifier).resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX);
} catch (IllegalArgumentException e) {
return false;
}
}
private static ApplicationInferenceProfile applicationProfileWithTags(ApplicationInferenceProfile source,
Map<String, String> tags) {
ApplicationInferenceProfile updated = new ApplicationInferenceProfile();
updated.setInferenceProfileId(source.getInferenceProfileId());
updated.setInferenceProfileArn(source.getInferenceProfileArn());
updated.setInferenceProfileName(source.getInferenceProfileName());
updated.setDescription(source.getDescription());
updated.setModels(source.getModels());
updated.setCreatedAt(source.getCreatedAt());
updated.setUpdatedAt(source.getUpdatedAt());
updated.setTags(Map.copyOf(tags));
updated.setAccountId(source.getAccountId());
updated.setRegion(source.getRegion());
updated.setClientRequestToken(source.getClientRequestToken());
return updated;
}
// Helpers
@@ -0,0 +1,61 @@
package io.floci.aws.services.bedrock;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import java.util.regex.Pattern;
/** Validates the Bedrock TagList shape. */
public final class BedrockTagValidator {
private static final int TAG_LIST_MAX = 200;
private static final int TAG_KEY_MIN = 1;
private static final int TAG_KEY_MAX = 128;
private static final int TAG_VALUE_MAX = 256;
private static final Pattern TAG_PATTERN = Pattern.compile("[a-zA-Z0-9\\s._:/=+@-]*");
private BedrockTagValidator() {
}
public static void validateRequired(JsonNode tags, String keyProperty, String valueProperty,
String errorCode, String propertyName) {
if (tags == null || tags.isNull()) {
throw invalid(errorCode, propertyName + " is required.");
}
validate(tags, keyProperty, valueProperty, errorCode, propertyName);
}
public static void validate(JsonNode tags, String keyProperty, String valueProperty,
String errorCode, String propertyName) {
if (tags == null || tags.isNull()) {
return;
}
if (!tags.isArray()) {
throw invalid(errorCode, propertyName + " must be an array.");
}
if (tags.size() > TAG_LIST_MAX) {
throw invalid(errorCode, propertyName + " must have at most " + TAG_LIST_MAX + " items.");
}
for (JsonNode tag : tags) {
JsonNode key = tag.path(keyProperty);
JsonNode value = tag.path(valueProperty);
if (!tag.isObject() || !key.isTextual() || !value.isTextual()) {
throw invalid(errorCode, propertyName + " items require string "
+ keyProperty + " and " + valueProperty + ".");
}
String keyText = key.textValue();
String valueText = value.textValue();
if (keyText.length() < TAG_KEY_MIN || keyText.length() > TAG_KEY_MAX
|| !TAG_PATTERN.matcher(keyText).matches()) {
throw invalid(errorCode, propertyName + " item " + keyProperty + " is invalid.");
}
if (valueText.length() > TAG_VALUE_MAX || !TAG_PATTERN.matcher(valueText).matches()) {
throw invalid(errorCode, propertyName + " item " + valueProperty + " is invalid.");
}
}
}
private static AwsException invalid(String errorCode, String message) {
return new AwsException(errorCode, message, 400);
}
}
@@ -0,0 +1,111 @@
package io.floci.aws.services.bedrock.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public class ApplicationInferenceProfile {
private String inferenceProfileId;
private String inferenceProfileArn;
private String inferenceProfileName;
private String description;
private List<String> models;
private Instant createdAt;
private Instant updatedAt;
private Map<String, String> tags;
private String accountId;
private String region;
private String clientRequestToken;
public String getInferenceProfileId() {
return inferenceProfileId;
}
public void setInferenceProfileId(String inferenceProfileId) {
this.inferenceProfileId = inferenceProfileId;
}
public String getInferenceProfileArn() {
return inferenceProfileArn;
}
public void setInferenceProfileArn(String inferenceProfileArn) {
this.inferenceProfileArn = inferenceProfileArn;
}
public String getInferenceProfileName() {
return inferenceProfileName;
}
public void setInferenceProfileName(String inferenceProfileName) {
this.inferenceProfileName = inferenceProfileName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getModels() {
return models;
}
public void setModels(List<String> models) {
this.models = models;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Instant updatedAt) {
this.updatedAt = updatedAt;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getClientRequestToken() {
return clientRequestToken;
}
public void setClientRequestToken(String clientRequestToken) {
this.clientRequestToken = clientRequestToken;
}
}
@@ -0,0 +1,261 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
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.floci.aws.core.common.AwsException;
import io.floci.aws.services.bedrock.BedrockService;
import io.floci.aws.services.bedrock.BedrockTagValidator;
import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile;
import io.floci.aws.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/** Provisions an application inference profile through the Bedrock control plane. */
@ApplicationScoped
public class BedrockCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::Bedrock::ApplicationInferenceProfile";
private static final String NOT_FOUND = "ResourceNotFoundException";
private static final String PRIOR_TAGS = "__FlociBedrockProfilePriorTags";
private static final String MANAGED_TAG_KEYS = "__FlociBedrockProfileManagedTagKeys";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final BedrockService bedrockService;
@Inject
public BedrockCfnProvisioner(BedrockService bedrockService) {
this.bedrockService = bedrockService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public Map<String, Set<String>> jsonAttributes() {
return Map.of(TYPE, Set.of("Models"));
}
@Override
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
Map<String, String> attributesBefore = Map.copyOf(resource.getAttributes());
String name = required(ctx.resolveOptional(properties, "InferenceProfileName"), "InferenceProfileName");
String description = ctx.resolveOptional(properties, "Description");
String source = modelSource(properties, ctx);
Map<String, String> tags = tags(properties, ctx);
Set<String> previouslyManagedTagKeys = managedTagKeys(attributesBefore);
ApplicationInferenceProfile existing = ctx.isUpdate()
&& !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore)
? bedrockService.getApplicationInferenceProfile(ctx.priorPhysicalId(), ctx.region()) : null;
if (existing != null && !ctx.changes(TYPE, properties).requiresReplacement()) {
resource.getAttributes().remove(PRIOR_TAGS);
Map<String, String> existingTags = existing.getTags() == null ? Map.of() : existing.getTags();
if (tagStateChanged(existingTags, previouslyManagedTagKeys, tags)) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", ctx.region());
snapshot.put("managedTagKeys", attributesBefore.get(MANAGED_TAG_KEYS));
Set<String> touchedKeys = new HashSet<>(previouslyManagedTagKeys);
touchedKeys.addAll(tags.keySet());
CfnRollback.putTagSnapshot(snapshot, touchedKeys, existingTags);
resource.getAttributes().put(PRIOR_TAGS, snapshot.toString());
CfnRollback.guarded(resource, ctx, false, () -> { }, () -> restoreTags(resource), () -> {
reconcileTags(existing.getInferenceProfileArn(), previouslyManagedTagKeys, tags, ctx.region());
publish(resource, bedrockService.getApplicationInferenceProfile(
existing.getInferenceProfileId(), ctx.region()));
});
} else {
publish(resource, bedrockService.getApplicationInferenceProfile(existing.getInferenceProfileId(),
ctx.region()));
}
} else {
ApplicationInferenceProfile created = bedrockService.createApplicationInferenceProfile(name,
description, source, tags, ctx.region());
publish(resource, created);
}
recordManagedTagKeys(resource, tags.keySet());
ReplacementCleanup.record(resource, ctx, attributesBefore);
}
private static String modelSource(JsonNode properties, ProvisionContext ctx) {
JsonNode source = properties == null ? null : properties.get("ModelSource");
String copyFrom = source == null ? null : ctx.engine().resolve(source.path("CopyFrom"));
return required(copyFrom, "ModelSource.CopyFrom");
}
private static Map<String, String> tags(JsonNode properties, ProvisionContext ctx) {
if (properties == null || !properties.has("Tags")) {
return Map.of();
}
JsonNode resolved = ctx.engine().resolveNode(properties.get("Tags"));
if (resolved == null || !resolved.isArray()) {
throw new AwsException("ValidationError", TYPE + " Tags must be an array.", 400);
}
BedrockTagValidator.validate(resolved, "Key", "Value", "ValidationError",
TYPE + " Tags");
Map<String, String> tags = new LinkedHashMap<>();
for (JsonNode tag : resolved) {
tags.put(tag.path("Key").textValue(), tag.path("Value").textValue());
}
return tags;
}
private static String required(String value, String property) {
if (value == null || value.isBlank()) {
throw new AwsException("ValidationError", TYPE + " requires " + property, 400);
}
return value;
}
private static void publish(StackResource resource, ApplicationInferenceProfile profile) {
String id = profile.getInferenceProfileId();
resource.setPhysicalId(id);
resource.getAttributes().put("InferenceProfileId", id);
resource.getAttributes().put("InferenceProfileArn", profile.getInferenceProfileArn());
resource.getAttributes().put("InferenceProfileIdentifier", id);
resource.getAttributes().put("Status", "ACTIVE");
resource.getAttributes().put("Type", "APPLICATION");
resource.getAttributes().put("CreatedAt", profile.getCreatedAt().toString());
resource.getAttributes().put("UpdatedAt", profile.getUpdatedAt().toString());
ArrayNode models = MAPPER.createArrayNode();
for (String modelArn : profile.getModels()) {
models.addObject().put("ModelArn", modelArn);
}
resource.getAttributes().put("Models", models.toString());
}
private static boolean tagStateChanged(Map<String, String> current, Set<String> previouslyManaged,
Map<String, String> desired) {
return !previouslyManaged.equals(desired.keySet()) || previouslyManaged.stream()
.anyMatch(key -> !Objects.equals(current.get(key), desired.get(key)));
}
private void reconcileTags(String arn, Set<String> managedKeys, Map<String, String> desired, String region) {
CfnRollback.reconcileTags(managedKeys, desired,
keys -> bedrockService.untagResource(arn, keys, region),
tags -> bedrockService.tagResource(arn, tags, region));
}
private void restoreTags(StackResource resource) {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, PRIOR_TAGS);
if (snapshot == null) {
return;
}
String region = CfnRollback.snapshotText(snapshot, "region");
List<String> managedKeys = CfnRollback.snapshotTagKeys(snapshot);
Map<String, String> tags = CfnRollback.snapshotTags(snapshot);
ApplicationInferenceProfile profile = bedrockService.getApplicationInferenceProfile(
resource.getPhysicalId(), region);
CfnRollback.reconcileTags(managedKeys, tags,
keys -> bedrockService.untagResource(profile.getInferenceProfileArn(), keys, region),
desired -> bedrockService.tagResource(profile.getInferenceProfileArn(), desired, region));
restoreManagedTagKeys(resource, CfnRollback.snapshotText(snapshot, "managedTagKeys"));
resource.getAttributes().remove(PRIOR_TAGS);
}
private static Set<String> managedTagKeys(Map<String, String> attributes) {
String raw = attributes.get(MANAGED_TAG_KEYS);
if (raw == null) {
return Set.of();
}
try {
JsonNode keys = MAPPER.readTree(raw);
if (keys == null || !keys.isArray()) {
throw new IllegalArgumentException("managed tag keys are not an array");
}
Set<String> result = new HashSet<>();
for (JsonNode key : keys) {
if (!key.isTextual()) {
throw new IllegalArgumentException("managed tag key is not a string");
}
result.add(key.textValue());
}
return result;
} catch (JsonProcessingException | IllegalArgumentException e) {
throw new AwsException("InternalFailure", "Invalid Bedrock profile managed-tag metadata: "
+ e.getMessage(), 500);
}
}
private static void recordManagedTagKeys(StackResource resource, Set<String> keys) {
if (keys.isEmpty()) {
resource.getAttributes().remove(MANAGED_TAG_KEYS);
return;
}
try {
resource.getAttributes().put(MANAGED_TAG_KEYS, MAPPER.writeValueAsString(new TreeSet<>(keys)));
} catch (JsonProcessingException e) {
throw new AwsException("InternalFailure", "Failed to store Bedrock profile managed-tag metadata: "
+ e.getMessage(), 500);
}
}
private static void restoreManagedTagKeys(StackResource resource, String keys) {
if (keys == null) {
resource.getAttributes().remove(MANAGED_TAG_KEYS);
} else {
resource.getAttributes().put(MANAGED_TAG_KEYS, keys);
}
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
resource.getAttributes().remove(PRIOR_TAGS);
return true;
}
restoreTags(resource);
return true;
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
String priorTags = attempted.getAttributes().get(PRIOR_TAGS);
if (priorTags != null) {
previous.getAttributes().put(PRIOR_TAGS, priorTags);
}
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(PRIOR_TAGS);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(PRIOR_TAGS);
ReplacementCleanup.clear(resource);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (physicalId == null || physicalId.isBlank()) {
return;
}
CfnDeletes.safeDelete("Bedrock application inference profile", physicalId,
() -> bedrockService.deleteApplicationInferenceProfile(physicalId, region), NOT_FOUND);
}
}