mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift-serverless): add usage limit actions (#5378)
* feat(redshift-serverless): add usage limit actions Add CreateUsageLimit, GetUsageLimit, ListUsageLimits, UpdateUsageLimit and DeleteUsageLimit, following the botocore redshift-serverless model. Usage limits are stored and echoed, not enforced: Floci does not meter RPU consumption, so breachAction never fires. A limit belongs to a workgroup, at most one per usageType, and disappears with it. The service checks the workgroup on read instead of hooking deleteWorkgroup, so deletes through CloudFormation are covered too. * fix(redshift-serverless): reject malformed usage limit members and purge stale limits on read - Usage limit string members of another JSON type (a numeric period, breachAction, resourceArn, usageType, usageLimitId or nextToken) were read as absent, so a create took the defaults, an update ignored the action and a list dropped its filter. They are now a ValidationException. - maxResults accepted fractional and out-of-range numbers and truncated them. It must be an integer that fits an int. - GetUsageLimit and the other id lookups answered 404 for a limit whose workgroup was gone but left the record in storage; they now delete it. - Listing checked every limit with a full workgroup scan. It now takes one snapshot of the Region's workgroup ARNs per scan. - Add a paging test that deletes the limit behind the nextToken. * fix(redshift-serverless): permit multiple usage limits per type and return 400 on missing resources - Remove the one-limit-per-usageType check on CreateUsageLimit so a workgroup can have multiple limits for the same usage type with different periods (e.g. daily and monthly serverless-compute). - Align ResourceNotFoundException on usage limit actions with the AWS Redshift Serverless API specification by returning HTTP 400 instead of 404. - Update documentation and test assertions accordingly.
This commit is contained in:
1 parent
e4278a800c
commit
141fd747ee
10 files changed
+922
-7
No files matched your search
+92
-2
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParame
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.PricePerformanceTarget;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.UsageLimit;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Workgroup;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -52,13 +53,16 @@ public class RedshiftServerlessJsonHandler {
|
||||
private final RedshiftServerlessService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RedshiftIamDbUserResolver iamDbUserResolver;
|
||||
private final RedshiftServerlessUsageLimitService usageLimits;
|
||||
|
||||
@Inject
|
||||
public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper,
|
||||
RedshiftIamDbUserResolver iamDbUserResolver) {
|
||||
RedshiftIamDbUserResolver iamDbUserResolver,
|
||||
RedshiftServerlessUsageLimitService usageLimits) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamDbUserResolver = iamDbUserResolver;
|
||||
this.usageLimits = usageLimits;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
@@ -84,6 +88,11 @@ public class RedshiftServerlessJsonHandler {
|
||||
case "ListSnapshots" -> handleListSnapshots(request, region);
|
||||
case "DeleteSnapshot" -> handleDeleteSnapshot(request, region);
|
||||
case "RestoreFromSnapshot" -> handleRestoreFromSnapshot(request, region);
|
||||
case "CreateUsageLimit" -> handleCreateUsageLimit(request, region);
|
||||
case "GetUsageLimit" -> handleGetUsageLimit(request, region);
|
||||
case "ListUsageLimits" -> handleListUsageLimits(request, region);
|
||||
case "UpdateUsageLimit" -> handleUpdateUsageLimit(request, region);
|
||||
case "DeleteUsageLimit" -> handleDeleteUsageLimit(request, region);
|
||||
case "GetCredentials" -> handleGetCredentials(request, region, authorizationHeader);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(request, region);
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
@@ -260,6 +269,64 @@ public class RedshiftServerlessJsonHandler {
|
||||
return snapshotArn == null ? snapshotName : service.snapshotNameFromArn(snapshotArn, region);
|
||||
}
|
||||
|
||||
private Response handleCreateUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.createUsageLimit(
|
||||
optionalText(request, "resourceArn"),
|
||||
optionalText(request, "usageType"),
|
||||
parseLong(request, "amount"),
|
||||
optionalText(request, "period"),
|
||||
optionalText(request, "breachAction"),
|
||||
region));
|
||||
}
|
||||
|
||||
private Response handleGetUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.getUsageLimit(optionalText(request, "usageLimitId"), region));
|
||||
}
|
||||
|
||||
private Response handleListUsageLimits(JsonNode request, String region) {
|
||||
PaginatedResult<UsageLimit> page = usageLimits.listUsageLimits(
|
||||
optionalText(request, "resourceArn"), optionalText(request, "usageType"), region,
|
||||
parseMaxResults(request), optionalText(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("usageLimits");
|
||||
page.items().forEach(limit -> items.add(usageLimitNode(limit)));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.updateUsageLimit(
|
||||
optionalText(request, "usageLimitId"),
|
||||
parseLong(request, "amount"),
|
||||
optionalText(request, "breachAction"),
|
||||
region));
|
||||
}
|
||||
|
||||
private Response handleDeleteUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.deleteUsageLimit(optionalText(request, "usageLimitId"), region));
|
||||
}
|
||||
|
||||
private Response usageLimitResponse(UsageLimit limit) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("usageLimit", usageLimitNode(limit));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/** {@code UsageLimit} has no timestamp member, so the creation date the store keeps is not emitted. */
|
||||
private ObjectNode usageLimitNode(UsageLimit limit) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("usageLimitId", limit.getUsageLimitId());
|
||||
node.put("usageLimitArn", limit.getUsageLimitArn());
|
||||
node.put("resourceArn", limit.getResourceArn());
|
||||
node.put("usageType", limit.getUsageType());
|
||||
node.put("amount", limit.getAmount());
|
||||
node.put("period", limit.getPeriod());
|
||||
node.put("breachAction", limit.getBreachAction());
|
||||
return node;
|
||||
}
|
||||
|
||||
private Response handleListTagsForResource(JsonNode request, String region) {
|
||||
Map<String, String> tags = service.listTagsForResource(text(request, "resourceArn"), region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
@@ -489,12 +556,35 @@ public class RedshiftServerlessJsonHandler {
|
||||
return Instant.ofEpochMilli(Math.round(node.asDouble() * 1000));
|
||||
}
|
||||
|
||||
/** A string member: null when missing or null, a validation error when present with any other type. */
|
||||
private String optionalText(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isTextual()) {
|
||||
throw validation(field + " must be a string.");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
private Long parseLong(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToLong()) {
|
||||
throw validation(field + " must be an integer.");
|
||||
}
|
||||
return node.asLong();
|
||||
}
|
||||
|
||||
private Integer parseMaxResults(JsonNode request) {
|
||||
JsonNode node = request.path("maxResults");
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isNumber()) {
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
|
||||
throw validation("maxResults must be an integer.");
|
||||
}
|
||||
return node.asInt();
|
||||
|
||||
+12
@@ -38,6 +38,7 @@ import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftServerlessService implements Resettable {
|
||||
@@ -615,6 +616,17 @@ public class RedshiftServerlessService implements Resettable {
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public Optional<Workgroup> findWorkgroupByArn(String resourceArn, String region) {
|
||||
return workgroupByArn(resourceArn, region);
|
||||
}
|
||||
|
||||
/** ARNs of every workgroup in the Region, for callers that test many resources against them at once. */
|
||||
public Set<String> workgroupArns(String region) {
|
||||
return workgroups.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.map(Workgroup::getWorkgroupArn)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private Optional<Workgroup> workgroupByArn(String resourceArn, String region) {
|
||||
return workgroups.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(workgroup -> resourceArn.equals(workgroup.getWorkgroupArn()))
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.UsageLimit;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Redshift Serverless usage limits. They are stored and echoed, not enforced: Floci does not meter
|
||||
* RPU consumption, so no {@code breachAction} ever fires.
|
||||
*
|
||||
* <p>A limit belongs to a workgroup but is kept in its own store, so deleting a workgroup, from the
|
||||
* API or from CloudFormation, needs no hook here. Each read instead checks that the workgroup still
|
||||
* exists and drops the limit otherwise. A workgroup ARN carries a generated id, so a workgroup
|
||||
* recreated under the same name has a new ARN and never matches a limit left by its predecessor.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftServerlessUsageLimitService implements Resettable {
|
||||
|
||||
private static final Set<String> USAGE_TYPES = Set.of("serverless-compute", "cross-region-datasharing");
|
||||
private static final Set<String> PERIODS = Set.of("daily", "weekly", "monthly");
|
||||
private static final Set<String> BREACH_ACTIONS = Set.of("log", "emit-metric", "deactivate");
|
||||
private static final String DEFAULT_PERIOD = "monthly";
|
||||
private static final String DEFAULT_BREACH_ACTION = "log";
|
||||
private static final int PAGE_SIZE = 100;
|
||||
|
||||
private final AccountAwareStorageBackend<UsageLimit> usageLimits;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RedshiftServerlessService serverless;
|
||||
|
||||
@Inject
|
||||
public RedshiftServerlessUsageLimitService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
RedshiftServerlessService serverless) {
|
||||
this.usageLimits = storageFactory.create("redshiftserverless", "redshiftserverless-usagelimits.json",
|
||||
new TypeReference<Map<String, UsageLimit>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
this.serverless = serverless;
|
||||
}
|
||||
|
||||
public synchronized UsageLimit createUsageLimit(String resourceArn, String usageType, Long amount,
|
||||
String period, String breachAction, String region) {
|
||||
requireText(resourceArn, "resourceArn");
|
||||
requireText(usageType, "usageType");
|
||||
requireOneOf(usageType, USAGE_TYPES, "usageType");
|
||||
if (amount == null) {
|
||||
throw validation("amount is required.");
|
||||
}
|
||||
requirePositive(amount);
|
||||
String resolvedPeriod = period == null ? DEFAULT_PERIOD : requireOneOf(period, PERIODS, "period");
|
||||
String resolvedAction = breachAction == null
|
||||
? DEFAULT_BREACH_ACTION : requireOneOf(breachAction, BREACH_ACTIONS, "breachAction");
|
||||
serverless.findWorkgroupByArn(resourceArn, region)
|
||||
.orElseThrow(() -> notFound("The resource " + resourceArn + " was not found."));
|
||||
|
||||
UsageLimit limit = new UsageLimit();
|
||||
limit.setUsageLimitId(UUID.randomUUID().toString());
|
||||
limit.setUsageLimitArn(regionResolver.buildArn("redshift-serverless", region,
|
||||
"usagelimit/" + limit.getUsageLimitId()));
|
||||
limit.setResourceArn(resourceArn);
|
||||
limit.setUsageType(usageType);
|
||||
limit.setAmount(amount);
|
||||
limit.setPeriod(resolvedPeriod);
|
||||
limit.setBreachAction(resolvedAction);
|
||||
usageLimits.put(storageKey(region, limit.getUsageLimitId()), limit);
|
||||
return new UsageLimit(limit);
|
||||
}
|
||||
|
||||
public synchronized UsageLimit getUsageLimit(String usageLimitId, String region) {
|
||||
return new UsageLimit(require(usageLimitId, region));
|
||||
}
|
||||
|
||||
public synchronized PaginatedResult<UsageLimit> listUsageLimits(String resourceArn, String usageType,
|
||||
String region, Integer maxResults,
|
||||
String nextToken) {
|
||||
if (usageType != null) {
|
||||
requireOneOf(usageType, USAGE_TYPES, "usageType");
|
||||
}
|
||||
List<UsageLimit> matching = live(region).stream()
|
||||
.filter(limit -> resourceArn == null || resourceArn.equals(limit.getResourceArn()))
|
||||
.filter(limit -> usageType == null || usageType.equals(limit.getUsageType()))
|
||||
.sorted(Comparator.comparing(UsageLimit::getUsageLimitId))
|
||||
.map(UsageLimit::new)
|
||||
.toList();
|
||||
return Pagination.paginate(matching, UsageLimit::getUsageLimitId, maxResults, nextToken,
|
||||
PAGE_SIZE, PAGE_SIZE, "InvalidPaginationException");
|
||||
}
|
||||
|
||||
public synchronized UsageLimit updateUsageLimit(String usageLimitId, Long amount, String breachAction,
|
||||
String region) {
|
||||
UsageLimit current = require(usageLimitId, region);
|
||||
if (amount != null) {
|
||||
requirePositive(amount);
|
||||
}
|
||||
if (breachAction != null) {
|
||||
requireOneOf(breachAction, BREACH_ACTIONS, "breachAction");
|
||||
}
|
||||
UsageLimit updated = new UsageLimit(current);
|
||||
if (amount != null) {
|
||||
updated.setAmount(amount);
|
||||
}
|
||||
if (breachAction != null) {
|
||||
updated.setBreachAction(breachAction);
|
||||
}
|
||||
usageLimits.put(storageKey(region, usageLimitId), updated);
|
||||
return new UsageLimit(updated);
|
||||
}
|
||||
|
||||
public synchronized UsageLimit deleteUsageLimit(String usageLimitId, String region) {
|
||||
UsageLimit existing = require(usageLimitId, region);
|
||||
usageLimits.delete(storageKey(region, usageLimitId));
|
||||
return new UsageLimit(existing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
usageLimits.clear();
|
||||
}
|
||||
|
||||
private UsageLimit require(String usageLimitId, String region) {
|
||||
requireText(usageLimitId, "usageLimitId");
|
||||
UsageLimit limit = usageLimits.get(storageKey(region, usageLimitId)).orElse(null);
|
||||
if (limit != null && !isLive(limit, region)) {
|
||||
usageLimits.delete(storageKey(region, usageLimitId));
|
||||
limit = null;
|
||||
}
|
||||
if (limit == null) {
|
||||
throw notFound("The usage limit " + usageLimitId + " was not found.");
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
/** The region's limits whose workgroup is still there; any other is deleted as it is found. */
|
||||
private List<UsageLimit> live(String region) {
|
||||
Set<String> workgroupArns = serverless.workgroupArns(region);
|
||||
return usageLimits.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(limit -> {
|
||||
if (workgroupArns.contains(limit.getResourceArn())) {
|
||||
return true;
|
||||
}
|
||||
usageLimits.delete(storageKey(region, limit.getUsageLimitId()));
|
||||
return false;
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean isLive(UsageLimit limit, String region) {
|
||||
return serverless.findWorkgroupByArn(limit.getResourceArn(), region).isPresent();
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String usageLimitId) {
|
||||
return region + "::" + usageLimitId;
|
||||
}
|
||||
|
||||
private static void requireText(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw validation(field + " is required.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireOneOf(String value, Set<String> allowed, String field) {
|
||||
if (!allowed.contains(value)) {
|
||||
throw validation(field + " must be one of " + allowed.stream().sorted().toList() + ".");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void requirePositive(long amount) {
|
||||
if (amount < 1) {
|
||||
throw validation("amount must be a positive number.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException notFound(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* A Redshift Serverless usage limit. Floci stores and echoes it but does not meter usage, so
|
||||
* {@code breachAction} never fires.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class UsageLimit {
|
||||
|
||||
private String usageLimitId;
|
||||
private String usageLimitArn;
|
||||
private String resourceArn;
|
||||
private String usageType;
|
||||
private long amount;
|
||||
private String period;
|
||||
private String breachAction;
|
||||
|
||||
public UsageLimit() {
|
||||
}
|
||||
|
||||
public UsageLimit(UsageLimit other) {
|
||||
this.usageLimitId = other.usageLimitId;
|
||||
this.usageLimitArn = other.usageLimitArn;
|
||||
this.resourceArn = other.resourceArn;
|
||||
this.usageType = other.usageType;
|
||||
this.amount = other.amount;
|
||||
this.period = other.period;
|
||||
this.breachAction = other.breachAction;
|
||||
}
|
||||
|
||||
public String getUsageLimitId() {
|
||||
return usageLimitId;
|
||||
}
|
||||
|
||||
public void setUsageLimitId(String usageLimitId) {
|
||||
this.usageLimitId = usageLimitId;
|
||||
}
|
||||
|
||||
public String getUsageLimitArn() {
|
||||
return usageLimitArn;
|
||||
}
|
||||
|
||||
public void setUsageLimitArn(String usageLimitArn) {
|
||||
this.usageLimitArn = usageLimitArn;
|
||||
}
|
||||
|
||||
public String getResourceArn() {
|
||||
return resourceArn;
|
||||
}
|
||||
|
||||
public void setResourceArn(String resourceArn) {
|
||||
this.resourceArn = resourceArn;
|
||||
}
|
||||
|
||||
public String getUsageType() {
|
||||
return usageType;
|
||||
}
|
||||
|
||||
public void setUsageType(String usageType) {
|
||||
this.usageType = usageType;
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getPeriod() {
|
||||
return period;
|
||||
}
|
||||
|
||||
public void setPeriod(String period) {
|
||||
this.period = period;
|
||||
}
|
||||
|
||||
public String getBreachAction() {
|
||||
return breachAction;
|
||||
}
|
||||
|
||||
public void setBreachAction(String breachAction) {
|
||||
this.breachAction = breachAction;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user