mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
2684 lines
128 KiB
Java
2684 lines
128 KiB
Java
package io.floci.aws.services.eventbridge;
|
|
|
|
import com.fasterxml.jackson.core.JsonParser;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
|
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.JsonNodeFactory;
|
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
import com.fasterxml.jackson.databind.node.TextNode;
|
|
import io.floci.aws.config.EmulatorConfig;
|
|
import io.floci.aws.core.common.AwsArnShapes;
|
|
import io.floci.aws.core.common.AwsArnUtils;
|
|
import io.floci.aws.core.common.AwsException;
|
|
import io.floci.aws.core.common.AwsPartitions;
|
|
import io.floci.aws.core.common.Digests;
|
|
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.core.common.SmithyValidationErrors;
|
|
import io.floci.aws.core.common.StarWildcard;
|
|
import io.floci.aws.core.common.StoredResourceArns;
|
|
import io.floci.aws.core.resource.ExplorerResource;
|
|
import io.floci.aws.core.resource.ResourceProvider;
|
|
import io.floci.aws.core.resource.SupportedResourceType;
|
|
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
|
import io.floci.aws.core.storage.StorageBackend;
|
|
import io.floci.aws.core.storage.StorageFactory;
|
|
import io.floci.aws.services.eventbridge.model.ApiDestination;
|
|
import io.floci.aws.services.eventbridge.model.ApiDestinationState;
|
|
import io.floci.aws.services.eventbridge.model.Archive;
|
|
import io.floci.aws.services.eventbridge.model.ArchiveState;
|
|
import io.floci.aws.services.eventbridge.model.ArchivedEvent;
|
|
import io.floci.aws.services.eventbridge.model.Connection;
|
|
import io.floci.aws.services.eventbridge.model.ConnectionState;
|
|
import io.floci.aws.services.eventbridge.model.EcsParameters;
|
|
import io.floci.aws.services.eventbridge.model.EventBus;
|
|
import io.floci.aws.services.eventbridge.model.Replay;
|
|
import io.floci.aws.services.eventbridge.model.ReplayState;
|
|
import io.floci.aws.services.eventbridge.model.Rule;
|
|
import io.floci.aws.services.eventbridge.model.RuleState;
|
|
import io.floci.aws.services.eventbridge.model.Target;
|
|
import io.floci.aws.services.pipes.PipesFilterMatcher;
|
|
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
|
import jakarta.annotation.PostConstruct;
|
|
import jakarta.enterprise.context.ApplicationScoped;
|
|
import jakarta.inject.Inject;
|
|
import org.jboss.logging.Logger;
|
|
|
|
import java.io.IOException;
|
|
import java.net.URI;
|
|
import java.net.URISyntaxException;
|
|
import java.time.Instant;
|
|
import java.time.temporal.ChronoUnit;
|
|
import java.util.ArrayList;
|
|
import java.util.Comparator;
|
|
import java.util.HashMap;
|
|
import java.util.Iterator;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Optional;
|
|
import java.util.Set;
|
|
import java.util.UUID;
|
|
import java.util.function.Function;
|
|
import java.util.function.Predicate;
|
|
import java.util.regex.Pattern;
|
|
|
|
import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount;
|
|
import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount;
|
|
import static io.floci.aws.core.storage.AccountAwareStorageBackend.readInAccount;
|
|
|
|
@ApplicationScoped
|
|
public class EventBridgeService implements ResourceProvider, StoredResourceArns {
|
|
|
|
private static final Logger LOG = Logger.getLogger(EventBridgeService.class);
|
|
private static final int MAX_LIST_LIMIT = 100;
|
|
private static final List<String> REQUIRED_ENTRY_FIELDS = List.of("Source", "DetailType", "Detail");
|
|
private static final Set<String> NUMERIC_OPERATORS = Set.of("=", ">", ">=", "<", "<=");
|
|
|
|
private final StorageBackend<String, EventBus> busStore;
|
|
private final StorageBackend<String, Rule> ruleStore;
|
|
private final StorageBackend<String, List<Target>> targetStore;
|
|
private final StorageBackend<String, Archive> archiveStore;
|
|
private final StorageBackend<String, List<ArchivedEvent>> archivedEventStore;
|
|
private final StorageBackend<String, Replay> replayStore;
|
|
private final StorageBackend<String, Connection> connectionStore;
|
|
private final StorageBackend<String, ApiDestination> apiDestinationStore;
|
|
private final RegionResolver regionResolver;
|
|
private final ObjectMapper objectMapper;
|
|
private final RuleScheduler ruleScheduler;
|
|
private final TargetDispatcher dispatcher;
|
|
private final ResourceGroupsTaggingService resourceGroupsTaggingService;
|
|
private final ReplayDispatcher replayDispatcher;
|
|
private final AppSyncTargetValidator appSyncTargetValidator;
|
|
|
|
@Inject
|
|
public EventBridgeService(StorageFactory storageFactory,
|
|
EmulatorConfig config,
|
|
RegionResolver regionResolver,
|
|
ObjectMapper objectMapper,
|
|
RuleScheduler ruleScheduler,
|
|
TargetDispatcher dispatcher,
|
|
ReplayDispatcher replayDispatcher,
|
|
ResourceGroupsTaggingService resourceGroupsTaggingService,
|
|
AppSyncTargetValidator appSyncTargetValidator) {
|
|
this(
|
|
storageFactory.create("eventbridge", "eventbridge-buses.json",
|
|
new TypeReference<Map<String, EventBus>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-rules.json",
|
|
new TypeReference<Map<String, Rule>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-targets.json",
|
|
new TypeReference<Map<String, List<Target>>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-archives.json",
|
|
new TypeReference<Map<String, Archive>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-archived-events.json",
|
|
new TypeReference<Map<String, List<ArchivedEvent>>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-replays.json",
|
|
new TypeReference<Map<String, Replay>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-connections.json",
|
|
new TypeReference<Map<String, Connection>>() {}),
|
|
storageFactory.create("eventbridge", "eventbridge-api-destinations.json",
|
|
new TypeReference<Map<String, ApiDestination>>() {}),
|
|
regionResolver, objectMapper, ruleScheduler, dispatcher, replayDispatcher,
|
|
resourceGroupsTaggingService, appSyncTargetValidator
|
|
);
|
|
}
|
|
|
|
EventBridgeService(StorageBackend<String, EventBus> busStore,
|
|
StorageBackend<String, Rule> ruleStore,
|
|
StorageBackend<String, List<Target>> targetStore,
|
|
StorageBackend<String, Archive> archiveStore,
|
|
StorageBackend<String, List<ArchivedEvent>> archivedEventStore,
|
|
StorageBackend<String, Replay> replayStore,
|
|
StorageBackend<String, Connection> connectionStore,
|
|
StorageBackend<String, ApiDestination> apiDestinationStore,
|
|
RegionResolver regionResolver,
|
|
ObjectMapper objectMapper,
|
|
RuleScheduler ruleScheduler,
|
|
TargetDispatcher dispatcher,
|
|
ReplayDispatcher replayDispatcher,
|
|
ResourceGroupsTaggingService resourceGroupsTaggingService,
|
|
AppSyncTargetValidator appSyncTargetValidator) {
|
|
this.busStore = busStore;
|
|
this.ruleStore = ruleStore;
|
|
this.targetStore = targetStore;
|
|
this.archiveStore = archiveStore;
|
|
this.archivedEventStore = archivedEventStore;
|
|
this.replayStore = replayStore;
|
|
this.connectionStore = connectionStore;
|
|
this.apiDestinationStore = apiDestinationStore;
|
|
this.regionResolver = regionResolver;
|
|
this.objectMapper = objectMapper;
|
|
this.ruleScheduler = ruleScheduler;
|
|
this.dispatcher = dispatcher;
|
|
this.replayDispatcher = replayDispatcher;
|
|
this.resourceGroupsTaggingService = resourceGroupsTaggingService;
|
|
this.appSyncTargetValidator = appSyncTargetValidator;
|
|
}
|
|
|
|
@PostConstruct
|
|
void init() {
|
|
if (ruleScheduler != null) {
|
|
List<Rule> allRules = ruleStore instanceof AccountAwareStorageBackend<Rule> aware
|
|
? aware.scanAllAccounts()
|
|
: ruleStore.scan(k -> true);
|
|
allRules.forEach(this::startSchedulerIfNeeded);
|
|
LOG.infov("EventBridge initialized, {0} scheduler(s) restored", ruleScheduler.getActiveSchedulerCount());
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Event Buses ────────────────────────────
|
|
|
|
public EventBus getOrCreateDefaultBus(String region) {
|
|
String key = busKey(region, "default");
|
|
return busStore.get(key).orElseGet(() -> {
|
|
EventBus bus = new EventBus(
|
|
"default",
|
|
regionResolver.buildArn("events", region, "event-bus/default"),
|
|
null,
|
|
Instant.now()
|
|
);
|
|
busStore.put(key, bus);
|
|
return bus;
|
|
});
|
|
}
|
|
|
|
public EventBus createEventBus(String name, String description,
|
|
Map<String, String> tags, String region) {
|
|
return createEventBus(name, null, description, tags, region);
|
|
}
|
|
|
|
public EventBus createEventBus(String name, String eventSourceName, String description,
|
|
Map<String, String> tags, String region) {
|
|
return createEventBus(name, eventSourceName, description, null, null, null, tags, region);
|
|
}
|
|
|
|
/**
|
|
* Creates a custom bus with the KMS key, dead-letter queue and log configuration the request
|
|
* gives, as {@code CreateEventBus} takes them; a null member leaves the bus without it. The
|
|
* dead-letter and log configurations are stored as their JSON, as {@link #updateEventBus} does.
|
|
* A non-null {@code eventSourceName} makes it a partner bus, which takes the source's name.
|
|
*/
|
|
public EventBus createEventBus(String name, String eventSourceName, String description,
|
|
String kmsKeyIdentifier, String deadLetterConfig, String logConfig,
|
|
Map<String, String> tags, String region) {
|
|
if (eventSourceName == null) {
|
|
validateCustomEventBusName(name);
|
|
} else {
|
|
validatePartnerEventBusName(name, eventSourceName);
|
|
}
|
|
validateEventBusDescription(description);
|
|
String key = busKey(region, name);
|
|
if (busStore.get(key).isPresent()) {
|
|
throw new AwsException("ResourceAlreadyExistsException",
|
|
"EventBus already exists: " + name, 400);
|
|
}
|
|
EventBus bus = new EventBus(
|
|
name,
|
|
regionResolver.buildArn("events", region, "event-bus/" + name),
|
|
description,
|
|
Instant.now()
|
|
);
|
|
if (kmsKeyIdentifier != null && !kmsKeyIdentifier.isBlank()) {
|
|
bus.setKmsKeyIdentifier(kmsKeyIdentifier);
|
|
}
|
|
if (deadLetterConfig != null && !deadLetterConfig.isBlank()) {
|
|
bus.setDeadLetterConfig(deadLetterConfig);
|
|
}
|
|
if (logConfig != null && !logConfig.isBlank()) {
|
|
bus.setLogConfig(logConfig);
|
|
}
|
|
if (tags != null) {
|
|
bus.getTags().putAll(tags);
|
|
resourceGroupsTaggingService.tagResources(List.of(bus.getArn()), tags, region);
|
|
}
|
|
busStore.put(key, bus);
|
|
LOG.infov("Created event bus: {0} in region {1}", name, region);
|
|
return bus;
|
|
}
|
|
|
|
public void deleteEventBus(String name, String region) {
|
|
// Validate input and handle both name and ARN format
|
|
if (name == null || name.isBlank()) {
|
|
throw new AwsException("ValidationException", "EventBus name is required.", 400);
|
|
}
|
|
String effectiveName = resolvedBusName(name);
|
|
validateEventBusNameForMutation(effectiveName);
|
|
if ("default".equals(effectiveName)) {
|
|
throw new AwsException("ValidationException", "Cannot delete the default event bus.", 400);
|
|
}
|
|
String key = busKey(region, effectiveName);
|
|
EventBus bus = busStore.get(key).orElse(null);
|
|
if (bus == null) {
|
|
return;
|
|
}
|
|
String rulePrefix = ruleKeyPrefix(region, effectiveName);
|
|
boolean hasRules = ruleStore.scan(k -> k.startsWith(rulePrefix)).stream()
|
|
.anyMatch(rule -> effectiveName.equals(rule.getEventBusName()));
|
|
if (hasRules) {
|
|
throw new AwsException("ValidationException",
|
|
"Cannot delete event bus with existing rules: " + name, 400);
|
|
}
|
|
busStore.delete(key);
|
|
resourceGroupsTaggingService.deleteResources(List.of(bus.getArn()), region);
|
|
LOG.infov("Deleted event bus: {0}", name);
|
|
}
|
|
|
|
public EventBus describeEventBus(String name, String region) {
|
|
// Handle both name and ARN format
|
|
String effectiveName = (name == null || name.isBlank()) ? "default" : resolvedBusName(name);
|
|
if ("default".equals(effectiveName)) {
|
|
return getOrCreateDefaultBus(region);
|
|
}
|
|
return busStore.get(busKey(region, effectiveName))
|
|
.orElseThrow(() -> eventBusNotFound(name));
|
|
}
|
|
|
|
public EventBus updateEventBus(String name,
|
|
String description,
|
|
String kmsKeyIdentifier,
|
|
String deadLetterConfig,
|
|
String logConfig,
|
|
String region) {
|
|
validateEventBusDescription(description);
|
|
if (name != null) {
|
|
validateEventBusNameForMutation(name);
|
|
}
|
|
// Name identifies the bus; never mutated (AWS does not support rename).
|
|
String effectiveName = name == null ? "default" : name;
|
|
EventBus bus = "default".equals(effectiveName)
|
|
? getOrCreateDefaultBus(region)
|
|
: busStore.get(busKey(region, effectiveName))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"EventBus not found: " + effectiveName, 400));
|
|
|
|
// Description accepts an explicit empty string so callers can clear it. A null value means
|
|
// the field was omitted and must remain unchanged.
|
|
boolean dirty = false;
|
|
if (description != null && !description.equals(bus.getDescription())) {
|
|
bus.setDescription(description);
|
|
dirty = true;
|
|
}
|
|
if (kmsKeyIdentifier != null && !kmsKeyIdentifier.isBlank()
|
|
&& !kmsKeyIdentifier.equals(bus.getKmsKeyIdentifier())) {
|
|
bus.setKmsKeyIdentifier(kmsKeyIdentifier);
|
|
dirty = true;
|
|
}
|
|
if (deadLetterConfig != null && !deadLetterConfig.isBlank()
|
|
&& !deadLetterConfig.equals(bus.getDeadLetterConfig())) {
|
|
bus.setDeadLetterConfig(deadLetterConfig);
|
|
dirty = true;
|
|
}
|
|
if (logConfig != null && !logConfig.isBlank()
|
|
&& !logConfig.equals(bus.getLogConfig())) {
|
|
bus.setLogConfig(logConfig);
|
|
dirty = true;
|
|
}
|
|
|
|
if (dirty) {
|
|
busStore.put(busKey(region, effectiveName), bus);
|
|
LOG.infov("Updated event bus: {0} (arn={1}) in region {2}",
|
|
effectiveName, bus.getArn(), region);
|
|
}
|
|
return bus;
|
|
}
|
|
|
|
private void validateCustomEventBusName(String name) {
|
|
if (name == null || name.isBlank()) {
|
|
throw new AwsException("ValidationException", "EventBus name is required.", 400);
|
|
}
|
|
if (name.length() > 256
|
|
|| !name.matches("[.\\-_A-Za-z0-9]+")
|
|
|| "default".equals(name)) {
|
|
throw new AwsException("ValidationException",
|
|
"Invalid custom event bus name: " + name, 400);
|
|
}
|
|
}
|
|
|
|
public static final Pattern PARTNER_EVENT_SOURCE_NAME =
|
|
Pattern.compile("aws\\.partner(/[\\.\\-_A-Za-z0-9]+){2,}");
|
|
private static final Pattern EVENT_BUS_NAME = Pattern.compile("[/\\.\\-_A-Za-z0-9]+");
|
|
|
|
private void validatePartnerEventBusName(String name, String eventSourceName) {
|
|
List<String> violations = new ArrayList<>(nameViolations("name", name, 256, EVENT_BUS_NAME));
|
|
violations.addAll(nameViolations("eventSourceName", eventSourceName, 256, PARTNER_EVENT_SOURCE_NAME));
|
|
if (!violations.isEmpty()) {
|
|
throw SmithyValidationErrors.validationException(violations);
|
|
}
|
|
if (!eventSourceName.equals(name)) {
|
|
throw new AwsException("ValidationException",
|
|
"Partner event bus name must match its event source name: " + eventSourceName, 400);
|
|
}
|
|
}
|
|
|
|
private void validateEventBusDescription(String description) {
|
|
if (description != null && description.length() > 512) {
|
|
throw new AwsException("ValidationException",
|
|
"EventBus description must not exceed 512 characters.", 400);
|
|
}
|
|
}
|
|
|
|
private void validateEventBusNameForMutation(String name) {
|
|
if (name.isEmpty()
|
|
|| name.length() > 256
|
|
|| !name.matches("[/\\.\\-_A-Za-z0-9]+")) {
|
|
throw new AwsException("ValidationException",
|
|
"Invalid event bus name: " + name, 400);
|
|
}
|
|
}
|
|
|
|
public List<EventBus> listEventBuses(String namePrefix, String region) {
|
|
getOrCreateDefaultBus(region);
|
|
String storagePrefix = "bus:" + region + ":";
|
|
List<EventBus> result = busStore.scan(k -> {
|
|
if (!k.startsWith(storagePrefix)) return false;
|
|
if (namePrefix == null || namePrefix.isBlank()) return true;
|
|
String busName = k.substring(storagePrefix.length());
|
|
return busName.startsWith(namePrefix);
|
|
});
|
|
return result;
|
|
}
|
|
|
|
// ──────────────────────────── Rules ────────────────────────────
|
|
|
|
public Rule putRule(String name, String busName, String eventPattern,
|
|
String scheduleExpression, RuleState state, String description,
|
|
String roleArn, Map<String, String> tags, String region) {
|
|
validateRuleName("name", name);
|
|
if ((eventPattern == null || eventPattern.isBlank())
|
|
&& (scheduleExpression == null || scheduleExpression.isBlank())) {
|
|
throw new AwsException("ValidationException",
|
|
"Parameter(s) EventPattern or ScheduleExpression must be specified.", 400);
|
|
}
|
|
if (eventPattern != null && !eventPattern.isBlank()) {
|
|
validateEventPattern(eventPattern);
|
|
}
|
|
if (scheduleExpression != null && !scheduleExpression.isBlank()) {
|
|
try {
|
|
ScheduleExpressionParser.validate(scheduleExpression);
|
|
} catch (IllegalArgumentException e) {
|
|
throw new AwsException("ValidationException", "Parameter ScheduleExpression is not valid.", 400);
|
|
}
|
|
}
|
|
String effectiveBus = resolvedBusName(busName);
|
|
ensureBusExists(effectiveBus, region);
|
|
|
|
String key = ruleKey(region, effectiveBus, name);
|
|
Optional<Rule> stored = ruleStore.get(key);
|
|
if (stored.isPresent() && !effectiveBus.equals(stored.get().getEventBusName())) {
|
|
throw new AwsException("ValidationException",
|
|
"Rule " + name + " on event bus " + effectiveBus + " conflicts with rule "
|
|
+ stored.get().getName() + " on event bus " + stored.get().getEventBusName()
|
|
+ ". Delete that rule first.", 400);
|
|
}
|
|
Rule rule = stored.orElse(new Rule());
|
|
rule.setAccountId(regionResolver.getAccountId());
|
|
rule.setName(name);
|
|
rule.setArn(buildRuleArn(region, effectiveBus, name));
|
|
rule.setEventBusName(effectiveBus);
|
|
rule.setEventPattern(eventPattern);
|
|
rule.setScheduleExpression(scheduleExpression);
|
|
rule.setState(state != null ? state : RuleState.ENABLED);
|
|
rule.setDescription(description);
|
|
rule.setRoleArn(roleArn);
|
|
if (tags != null) {
|
|
rule.getTags().putAll(tags);
|
|
}
|
|
if (rule.getCreatedAt() == null) {
|
|
rule.setCreatedAt(Instant.now());
|
|
}
|
|
ruleStore.put(key, rule);
|
|
|
|
if (tags != null && !tags.isEmpty()) {
|
|
resourceGroupsTaggingService.tagResources(List.of(rule.getArn()), tags, region);
|
|
}
|
|
|
|
if (ruleScheduler != null) {
|
|
ruleScheduler.stopScheduler(rule.getArn());
|
|
startSchedulerIfNeeded(rule);
|
|
}
|
|
|
|
LOG.infov("Put rule: {0} on bus {1}", name, effectiveBus);
|
|
return rule;
|
|
}
|
|
|
|
private static final Pattern NON_PARTNER_NAME = Pattern.compile("[\\.\\-_A-Za-z0-9]+");
|
|
|
|
private static void validateRuleName(String member, String name) {
|
|
List<String> violations = nameViolations(member, name, 64, NON_PARTNER_NAME);
|
|
if (!violations.isEmpty()) {
|
|
throw SmithyValidationErrors.validationException(violations);
|
|
}
|
|
}
|
|
|
|
private void validateRuleReference(String member, String name, String busName, String region) {
|
|
boolean legacyRuleOfBus = name != null
|
|
&& ruleStore.get(ruleKey(region, busName, name))
|
|
.map(rule -> busName.equals(rule.getEventBusName()))
|
|
.orElse(false);
|
|
if (!legacyRuleOfBus) {
|
|
validateRuleName(member, name);
|
|
}
|
|
}
|
|
|
|
private static List<String> nameViolations(String path, String value, int maxLength, Pattern pattern) {
|
|
if (value == null) {
|
|
return List.of(SmithyValidationErrors.notNull(path));
|
|
}
|
|
List<String> violations = new ArrayList<>();
|
|
String length = SmithyValidationErrors.lengthOutOfRange(path, value, 1, maxLength);
|
|
if (length != null) {
|
|
violations.add(length);
|
|
}
|
|
if (!pattern.matcher(value).matches()) {
|
|
violations.add(SmithyValidationErrors.pattern(path, value, pattern.pattern()));
|
|
}
|
|
return violations;
|
|
}
|
|
|
|
public void deleteRule(String name, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("name", name, effectiveBus, region);
|
|
ensureBusExists(effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, name);
|
|
Rule rule = ruleOfBus(key, effectiveBus).orElse(null);
|
|
if (rule == null) {
|
|
return;
|
|
}
|
|
List<Target> targets = targetStore.get(key).orElse(List.of());
|
|
if (!targets.isEmpty()) {
|
|
throw new AwsException("ValidationException",
|
|
"Rule still has targets. Remove targets before deleting the rule.", 400);
|
|
}
|
|
|
|
if (ruleScheduler != null) {
|
|
ruleScheduler.stopScheduler(rule.getArn());
|
|
}
|
|
|
|
ruleStore.delete(key);
|
|
resourceGroupsTaggingService.deleteResources(List.of(rule.getArn()), region);
|
|
LOG.infov("Deleted rule: {0}", name);
|
|
}
|
|
|
|
/**
|
|
* Whether a rule is stored under this exact name on the bus, without validating the name, so a
|
|
* caller can tell a rule persisted before name validation from one that is already gone.
|
|
*/
|
|
public boolean ruleExists(String name, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
return name != null && ruleOfBus(ruleKey(region, effectiveBus, name), effectiveBus).isPresent();
|
|
}
|
|
|
|
public Rule describeRule(String name, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("name", name, effectiveBus, region);
|
|
return ruleOfBus(ruleKey(region, effectiveBus, name), effectiveBus)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Rule not found: " + name, 400));
|
|
}
|
|
|
|
public List<Rule> listRules(String busName, String namePrefix, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
String prefix = ruleKeyPrefix(region, effectiveBus);
|
|
String account = regionResolver.getAccountId();
|
|
Set<String> keys = ruleStore instanceof AccountAwareStorageBackend<Rule> aware
|
|
? aware.keysIncludingLegacyForAccount(account, key -> key.startsWith(prefix))
|
|
: ruleStore.keys();
|
|
List<Rule> rules = new ArrayList<>();
|
|
for (String key : keys) {
|
|
if (!key.startsWith(prefix)) {
|
|
continue;
|
|
}
|
|
String name = key.substring(prefix.length());
|
|
if (namePrefix != null && !namePrefix.isBlank() && !name.startsWith(namePrefix)) {
|
|
continue;
|
|
}
|
|
readInAccount(ruleStore, account, key)
|
|
.filter(rule -> name.equals(rule.getName()) && effectiveBus.equals(rule.getEventBusName()))
|
|
.ifPresent(rules::add);
|
|
}
|
|
return rules;
|
|
}
|
|
|
|
/**
|
|
* One page of a bus's rules in name order. {@code limit} defaults to 100, the documented
|
|
* per-page maximum, and the token is the shared opaque cursor, so a page stays resumable
|
|
* when rules are added or removed between requests.
|
|
*/
|
|
public PaginatedResult<Rule> listRules(String busName, String namePrefix, Integer limit,
|
|
String nextToken, String region) {
|
|
return paginate(listRules(busName, namePrefix, region), Rule::getName, limit, nextToken, "rule");
|
|
}
|
|
|
|
private static <T> PaginatedResult<T> paginate(List<T> items, Function<T, String> cursorOf, Integer limit,
|
|
String nextToken, String scope) {
|
|
if (limit != null && (limit < 1 || limit > MAX_LIST_LIMIT)) {
|
|
throw limitOutOfRange(limit.toString(), limit < 1);
|
|
}
|
|
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > 2048)) {
|
|
throw new AwsException("ValidationException", "NextToken must contain 1 to 2048 characters.", 400);
|
|
}
|
|
return Pagination.paginate(items, cursorOf, limit == null ? MAX_LIST_LIMIT : limit, nextToken, scope,
|
|
token -> new AwsException("InvalidToken", "Invalid NextToken.", 400));
|
|
}
|
|
|
|
static AwsException limitOutOfRange(String value, boolean belowMinimum) {
|
|
String constraint = belowMinimum
|
|
? "Member must have value greater than or equal to 1"
|
|
: "Member must have value less than or equal to " + MAX_LIST_LIMIT;
|
|
return SmithyValidationErrors.validationException(
|
|
"Value '" + value + "' at 'limit' failed to satisfy constraint: " + constraint);
|
|
}
|
|
|
|
public void enableRule(String name, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("name", name, effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, name);
|
|
Rule rule = ruleOfBus(key, effectiveBus)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Rule not found: " + name, 400));
|
|
rule.setState(RuleState.ENABLED);
|
|
ruleStore.put(key, rule);
|
|
startSchedulerIfNeeded(rule);
|
|
}
|
|
|
|
public void disableRule(String name, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("name", name, effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, name);
|
|
Rule rule = ruleOfBus(key, effectiveBus)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Rule not found: " + name, 400));
|
|
rule.setState(RuleState.DISABLED);
|
|
ruleStore.put(key, rule);
|
|
|
|
if (ruleScheduler != null) {
|
|
ruleScheduler.stopScheduler(rule.getArn());
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Targets ────────────────────────────
|
|
|
|
public int putTargets(String ruleName, String busName, List<Target> newTargets, String region) {
|
|
validateTargetSettings(newTargets);
|
|
newTargets.forEach(appSyncTargetValidator::validate);
|
|
return upsertTargets(ruleName, busName, newTargets, region);
|
|
}
|
|
|
|
/**
|
|
* Internal rollback path for previously accepted targets. Local shape checks still apply,
|
|
* but restoring a snapshot must not depend on the GraphQL sidecar being available.
|
|
*/
|
|
public int restoreAcceptedTargets(String ruleName, String busName, List<Target> targets, String region) {
|
|
validateTargetSettings(targets);
|
|
return upsertTargets(ruleName, busName, targets, region);
|
|
}
|
|
|
|
private int upsertTargets(String ruleName, String busName, List<Target> newTargets, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("rule", ruleName, effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, ruleName);
|
|
Rule rule = ruleOfBus(key, effectiveBus)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Rule not found: " + ruleName, 400));
|
|
List<Target> existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>()));
|
|
for (Target newTarget : newTargets) {
|
|
EcsParameters ecs = newTarget.getEcsParameters();
|
|
if (ecs != null) {
|
|
ecs.setTaskCount(ecs.getTaskCount() == null ? 1 : ecs.getTaskCount());
|
|
ecs.setEnableECSManagedTags(ecs.getEnableECSManagedTags() == null ? false : ecs.getEnableECSManagedTags());
|
|
ecs.setEnableExecuteCommand(ecs.getEnableExecuteCommand() == null ? false : ecs.getEnableExecuteCommand());
|
|
}
|
|
if (newTarget.getRoleArn() == null && isCrossAccountEventBus(newTarget.getArn(), rule)) {
|
|
existing.stream()
|
|
.filter(t -> t.getId().equals(newTarget.getId()) && newTarget.getArn().equals(t.getArn()))
|
|
.findFirst()
|
|
.ifPresent(t -> newTarget.setRoleArn(t.getRoleArn()));
|
|
}
|
|
existing.removeIf(t -> t.getId().equals(newTarget.getId()));
|
|
existing.add(newTarget);
|
|
}
|
|
targetStore.put(key, existing);
|
|
LOG.infov("Put {0} targets on rule {1}", newTargets.size(), ruleName);
|
|
return 0;
|
|
}
|
|
|
|
private boolean isCrossAccountEventBus(String targetArn, Rule rule) {
|
|
if (!AwsArnUtils.isArnFor(targetArn, "events")) {
|
|
return false;
|
|
}
|
|
AwsArnUtils.Arn arn = AwsArnUtils.parse(targetArn);
|
|
String accountId = rule.getAccountId() != null ? rule.getAccountId() : regionResolver.getAccountId();
|
|
return arn.resource().startsWith("event-bus/") && AwsArnUtils.isForeignAccount(arn, accountId);
|
|
}
|
|
|
|
private static void validateTargetSettings(List<Target> targets) {
|
|
for (int i = 0; i < targets.size(); i++) {
|
|
Target target = targets.get(i);
|
|
String operation = target.getAppSyncParameters() == null
|
|
? null : target.getAppSyncParameters().graphQLOperation();
|
|
if (operation != null) {
|
|
String violation = SmithyValidationErrors.Violations.WITHOUT_VALUES.lengthOutOfRange(
|
|
"targets." + (i + 1) + ".member.appSyncParameters.graphQLOperation", operation, 1, 1048576);
|
|
if (violation != null) {
|
|
throw SmithyValidationErrors.validationException(violation);
|
|
}
|
|
}
|
|
Target.KinesisParameters kinesisParameters = target.getKinesisParameters();
|
|
if (kinesisParameters != null) {
|
|
String path = kinesisParameters.partitionKeyPath();
|
|
String field = "targets." + (i + 1) + ".member.kinesisParameters.partitionKeyPath";
|
|
String violation = path == null ? SmithyValidationErrors.notNull(field)
|
|
: SmithyValidationErrors.Violations.WITHOUT_VALUES.lengthOutOfRange(field, path, 0, 256);
|
|
if (violation != null) {
|
|
throw SmithyValidationErrors.validationException(violation);
|
|
}
|
|
}
|
|
Integer attempts = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumRetryAttempts() : null;
|
|
Integer age = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumEventAgeInSeconds() : null;
|
|
String arn = target.getDeadLetterConfig() != null ? target.getDeadLetterConfig().arn() : null;
|
|
Integer taskCount = target.getEcsParameters() != null ? target.getEcsParameters().getTaskCount() : null;
|
|
String field = null;
|
|
Object value = null;
|
|
String constraint = null;
|
|
if (taskCount != null && taskCount < 1) {
|
|
field = "ecsParameters.taskCount";
|
|
value = taskCount;
|
|
constraint = "value greater than or equal to 1";
|
|
} else if (attempts != null && (attempts < 0 || attempts > 185)) {
|
|
field = "retryPolicy.maximumRetryAttempts";
|
|
value = attempts;
|
|
constraint = attempts < 0 ? "value greater than or equal to 0" : "value less than or equal to 185";
|
|
} else if (age != null && (age < 60 || age > 86400)) {
|
|
field = "retryPolicy.maximumEventAgeInSeconds";
|
|
value = age;
|
|
constraint = age < 60 ? "value greater than or equal to 60" : "value less than or equal to 86400";
|
|
} else if (arn != null && (arn.isEmpty() || arn.length() > 1600)) {
|
|
field = "deadLetterConfig.arn";
|
|
value = arn;
|
|
constraint = arn.isEmpty() ? "length greater than or equal to 1" : "length less than or equal to 1600";
|
|
} else if (target.getRoleArn() != null
|
|
&& (target.getRoleArn().isEmpty() || target.getRoleArn().length() > 1600)) {
|
|
field = "roleArn";
|
|
value = target.getRoleArn();
|
|
constraint = target.getRoleArn().isEmpty()
|
|
? "length greater than or equal to 1" : "length less than or equal to 1600";
|
|
}
|
|
if (field != null) {
|
|
throw SmithyValidationErrors.validationException("Value '" + value
|
|
+ "' at 'targets." + (i + 1) + ".member." + field
|
|
+ "' failed to satisfy constraint: Member must have " + constraint);
|
|
}
|
|
validateTargetArn(target.getRoleArn(), "iam");
|
|
validateTargetArn(arn, "sqs");
|
|
}
|
|
}
|
|
|
|
private static void validateTargetArn(String arn, String service) {
|
|
if (arn == null) {
|
|
return;
|
|
}
|
|
if (AwsArnUtils.isArnFor(arn, service)) {
|
|
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
|
boolean resourceValid = "iam".equals(service)
|
|
? AwsArnShapes.isIamRole(parsed) && !parsed.resource().endsWith("/")
|
|
: !parsed.region().isBlank() && AwsArnShapes.isSqsQueueName(parsed.resource());
|
|
if (AwsPartitions.find(parsed.partition()).isPresent()
|
|
&& parsed.accountId().matches("[0-9]{12}") && resourceValid) {
|
|
return;
|
|
}
|
|
}
|
|
throw new AwsException("ValidationException",
|
|
"Parameter " + arn + " is not valid. Reason: Provided Arn is not in correct format.", 400);
|
|
}
|
|
|
|
public record RemoveTargetsResult(int successfulCount, int failedCount) {}
|
|
|
|
public RemoveTargetsResult removeTargets(String ruleName, String busName,
|
|
List<String> ids, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("rule", ruleName, effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, ruleName);
|
|
if (ruleStore.get(key).filter(rule -> !effectiveBus.equals(rule.getEventBusName())).isPresent()) {
|
|
return new RemoveTargetsResult(0, ids.size());
|
|
}
|
|
List<Target> existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>()));
|
|
int removed = 0;
|
|
for (String id : ids) {
|
|
if (existing.removeIf(t -> t.getId().equals(id))) {
|
|
removed++;
|
|
}
|
|
}
|
|
targetStore.put(key, existing);
|
|
ruleStore.get(key).ifPresent(rule -> dispatcher.dropPendingRetries(rule.getArn(), ids));
|
|
return new RemoveTargetsResult(removed, ids.size() - removed);
|
|
}
|
|
|
|
public PaginatedResult<String> listRuleNamesByTarget(String targetArn, String busName, Integer limit,
|
|
String nextToken, String region) {
|
|
if (targetArn == null || targetArn.isEmpty() || targetArn.length() > 1600) {
|
|
throw new AwsException("ValidationException", "TargetArn must contain 1 to 1600 characters.", 400);
|
|
}
|
|
if (busName != null && (busName.isBlank() || busName.length() > 1600)) {
|
|
throw new AwsException("ValidationException", "EventBusName must contain 1 to 1600 characters.", 400);
|
|
}
|
|
String effectiveBus = resolvedBusName(busName);
|
|
if (!effectiveBus.matches("[/\\.\\-_A-Za-z0-9]+")) {
|
|
throw new AwsException("ValidationException", "Invalid EventBridge event bus name.", 400);
|
|
}
|
|
requireBusForRead(effectiveBus, region);
|
|
List<String> names = listRules(effectiveBus, null, region).stream()
|
|
.filter(rule -> ruleTargetsArn(rule, effectiveBus, targetArn, region))
|
|
.map(Rule::getName).toList();
|
|
String scope = targetRuleCursorScope(targetArn, busName, effectiveBus, limit, region);
|
|
return paginate(names, Function.identity(), limit, nextToken, scope);
|
|
}
|
|
|
|
private void requireBusForRead(String busName, String region) {
|
|
Optional<EventBus> bus = readInAccount(busStore, regionResolver.getAccountId(), busKey(region, busName));
|
|
if (bus.isEmpty() && !"default".equals(busName)) {
|
|
throw eventBusNotFound(busName);
|
|
}
|
|
}
|
|
|
|
private boolean ruleTargetsArn(Rule rule, String busName, String targetArn, String region) {
|
|
String account = regionResolver.getAccountId();
|
|
if (rule.getAccountId() != null && !account.equals(rule.getAccountId())) {
|
|
return false;
|
|
}
|
|
String expectedArn = buildRuleArn(region, busName, rule.getName());
|
|
if (!expectedArn.equals(rule.getArn())) {
|
|
return false;
|
|
}
|
|
String key = ruleKey(region, busName, rule.getName());
|
|
List<Target> targets = new ArrayList<>(readInAccount(targetStore, account, key).orElse(List.of()));
|
|
return targets.stream().anyMatch(target -> target != null && targetArn.equals(target.getArn()));
|
|
}
|
|
|
|
private String targetRuleCursorScope(String targetArn, String suppliedBus, String effectiveBus,
|
|
Integer limit, String region) {
|
|
StringBuilder scope = new StringBuilder();
|
|
for (String value : List.of(regionResolver.getAccountId(), regionResolver.partitionForRegion(region),
|
|
region, effectiveBus, targetArn, limit == null ? "omitted" : limit.toString(),
|
|
suppliedBus == null ? "" : suppliedBus)) {
|
|
scope.append(value.length()).append(':').append(value);
|
|
}
|
|
return "target-rules:" + Digests.sha256Hex(scope.toString());
|
|
}
|
|
|
|
public List<Target> listTargetsByRule(String ruleName, String busName, String region) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
validateRuleReference("rule", ruleName, effectiveBus, region);
|
|
String key = ruleKey(region, effectiveBus, ruleName);
|
|
ruleOfBus(key, effectiveBus)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Rule not found: " + ruleName, 400));
|
|
return targetStore.get(key).orElse(List.of());
|
|
}
|
|
|
|
// ──────────────────────────── Tags ────────────────────────────
|
|
|
|
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
|
validateTagResourceArn(resourceArn, region);
|
|
String resource = AwsArnUtils.parse(resourceArn).resource();
|
|
if ("event-bus/default".equals(resource)) {
|
|
getOrCreateDefaultBus(region);
|
|
}
|
|
return requireTagResource(resourceArn, region, resource).tags();
|
|
}
|
|
|
|
private record TagResource(String arn, Map<String, String> tags, Runnable save) {}
|
|
|
|
private Optional<TagResource> findTagResource(String accountId, String region, String resource) {
|
|
if (resource.startsWith("event-bus/")) {
|
|
String key = busKey(region, resource.substring("event-bus/".length()));
|
|
return getInAccount(busStore, accountId, key)
|
|
.map(bus -> new TagResource(bus.getArn(), bus.getTags(),
|
|
() -> putInAccount(busStore, accountId, key, bus)));
|
|
}
|
|
if (resource.startsWith("rule/")) {
|
|
RuleRef ref = parseRuleResource(resource);
|
|
String key = ruleKey(region, ref.busName(), ref.ruleName());
|
|
return getInAccount(ruleStore, accountId, key)
|
|
.map(rule -> new TagResource(rule.getArn(), rule.getTags(),
|
|
() -> putInAccount(ruleStore, accountId, key, rule)));
|
|
}
|
|
if (resource.startsWith("archive/")) {
|
|
String key = archiveKey(region, resource.substring("archive/".length()));
|
|
return getInAccount(archiveStore, accountId, key)
|
|
.map(archive -> new TagResource(archive.getArchiveArn(), archive.getTags(),
|
|
() -> putInAccount(archiveStore, accountId, key, archive)));
|
|
}
|
|
return Optional.empty();
|
|
}
|
|
|
|
private TagResource requireTagResource(String resourceArn, String region, String resource) {
|
|
return findTagResource(regionResolver.getAccountId(), region, resource)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Resource not found: " + resourceArn, 400));
|
|
}
|
|
|
|
/** EventBridge tag operations only address resources in the caller's account and Region. */
|
|
private void validateTagResourceArn(String resourceArn, String region) {
|
|
AwsArnUtils.Arn arn;
|
|
try {
|
|
arn = AwsArnUtils.parse(resourceArn);
|
|
} catch (IllegalArgumentException e) {
|
|
throw new AwsException("ResourceNotFoundException",
|
|
"Resource not found: " + resourceArn, 400);
|
|
}
|
|
if (!"events".equals(arn.service())
|
|
|| arn.partition().isBlank()
|
|
|| AwsArnUtils.isForeignPartition(arn, regionResolver.partitionForRegion(region))
|
|
|| !region.equals(arn.region())
|
|
|| arn.accountId().isBlank()
|
|
|| AwsArnUtils.isForeignAccount(arn, regionResolver.getAccountId())) {
|
|
throw new AwsException("ResourceNotFoundException",
|
|
"Resource not found: " + resourceArn, 400);
|
|
}
|
|
}
|
|
|
|
/** Resolves the bus and rule name from a {@code rule/...} ARN resource segment. */
|
|
private record RuleRef(String busName, String ruleName) {}
|
|
|
|
private static RuleRef parseRuleResource(String resource) {
|
|
String afterRule = resource.substring("rule/".length());
|
|
int slashIdx = afterRule.lastIndexOf('/');
|
|
if (slashIdx >= 0) {
|
|
// Custom bus: rule/{busName}/{ruleName}
|
|
return new RuleRef(afterRule.substring(0, slashIdx), afterRule.substring(slashIdx + 1));
|
|
}
|
|
// Default bus: rule/{ruleName}
|
|
return new RuleRef("default", afterRule);
|
|
}
|
|
|
|
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
|
validateTagResourceArn(resourceArn, region);
|
|
String resource = AwsArnUtils.parse(resourceArn).resource();
|
|
TagResource target = requireTagResource(resourceArn, region, resource);
|
|
target.tags().putAll(tags);
|
|
target.save().run();
|
|
resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region);
|
|
}
|
|
|
|
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
|
validateTagResourceArn(resourceArn, region);
|
|
String resource = AwsArnUtils.parse(resourceArn).resource();
|
|
TagResource target = requireTagResource(resourceArn, region, resource);
|
|
tagKeys.forEach(target.tags()::remove);
|
|
target.save().run();
|
|
resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region);
|
|
}
|
|
|
|
// ──────────────────────────── Permissions ────────────────────────────
|
|
|
|
public void putPermission(String busName, String action, String principal,
|
|
String statementId, String conditionJson, String policyJson, String region) {
|
|
String effectiveBus = resolvedNonPartnerBusName(busName);
|
|
if ("default".equals(effectiveBus)) {
|
|
getOrCreateDefaultBus(region);
|
|
}
|
|
String key = busKey(region, effectiveBus);
|
|
EventBus bus = busStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"EventBus not found: " + effectiveBus, 400));
|
|
|
|
try {
|
|
if (policyJson != null && !policyJson.isBlank()) {
|
|
parseClientJson(policyJson, "Policy");
|
|
bus.setPolicy(policyJson);
|
|
} else {
|
|
String currentPolicy = bus.getPolicy();
|
|
ObjectNode policy;
|
|
if (currentPolicy != null && !currentPolicy.isBlank()) {
|
|
policy = (ObjectNode) objectMapper.readTree(currentPolicy);
|
|
} else {
|
|
policy = objectMapper.createObjectNode();
|
|
policy.put("Version", "2012-10-17");
|
|
policy.putArray("Statement");
|
|
}
|
|
|
|
ArrayNode statements = (ArrayNode) policy.get("Statement");
|
|
for (int i = 0; i < statements.size(); i++) {
|
|
if (statementId.equals(statements.get(i).path("Sid").asText(null))) {
|
|
statements.remove(i);
|
|
break;
|
|
}
|
|
}
|
|
|
|
ObjectNode statement = objectMapper.createObjectNode();
|
|
statement.put("Sid", statementId);
|
|
statement.put("Effect", "Allow");
|
|
statement.set("Principal", permissionPrincipal(principal, bus.getArn()));
|
|
statement.put("Action", action != null ? action : "events:PutEvents");
|
|
statement.put("Resource", bus.getArn());
|
|
if (conditionJson != null && !conditionJson.isBlank()) {
|
|
statement.set("Condition", parseClientJson(conditionJson, "Condition"));
|
|
}
|
|
statements.add(statement);
|
|
bus.setPolicy(objectMapper.writeValueAsString(policy));
|
|
}
|
|
} catch (AwsException e) {
|
|
throw e;
|
|
} catch (Exception e) {
|
|
throw new AwsException("InternalException", "Failed to process permission policy: " + e.getMessage(), 500);
|
|
}
|
|
|
|
busStore.put(key, bus);
|
|
LOG.infov("Put permission on bus {0}, statement {1}", effectiveBus, statementId);
|
|
}
|
|
|
|
/**
|
|
* The principal a {@code PutPermission} statement grants: every account for {@code *}, and otherwise the
|
|
* account the request names, as its root in the bus's partition.
|
|
*/
|
|
private static JsonNode permissionPrincipal(String principal, String busArn) {
|
|
if (principal == null || "*".equals(principal)) {
|
|
return TextNode.valueOf("*");
|
|
}
|
|
ObjectNode aws = JsonNodeFactory.instance.objectNode();
|
|
aws.put("AWS", AwsArnUtils.Arn.global(AwsArnUtils.parse(busArn).partition(), "iam", principal, "root")
|
|
.toString());
|
|
return aws;
|
|
}
|
|
|
|
/**
|
|
* Parses client-supplied JSON (PutPermission Policy/Condition). Malformed input is a
|
|
* client error; without this it fell into the catch-all and surfaced as a 500.
|
|
*/
|
|
private JsonNode parseClientJson(String json, String field) {
|
|
try {
|
|
return objectMapper.reader()
|
|
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
|
|
.readTree(json);
|
|
} catch (JsonProcessingException e) {
|
|
throw new AwsException("ValidationException", field + " is not valid JSON.", 400);
|
|
}
|
|
}
|
|
|
|
public void removePermission(String busName, String statementId, boolean removeAll, String region) {
|
|
String effectiveBus = resolvedNonPartnerBusName(busName);
|
|
if ("default".equals(effectiveBus)) {
|
|
getOrCreateDefaultBus(region);
|
|
}
|
|
String key = busKey(region, effectiveBus);
|
|
EventBus bus = busStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"EventBus not found: " + effectiveBus, 400));
|
|
|
|
if (removeAll) {
|
|
bus.setPolicy(null);
|
|
} else {
|
|
if (statementId == null || statementId.isBlank()) {
|
|
throw new AwsException("ValidationException", "StatementId is required.", 400);
|
|
}
|
|
try {
|
|
String currentPolicy = bus.getPolicy();
|
|
if (currentPolicy == null || currentPolicy.isBlank()) {
|
|
throw new AwsException("ResourceNotFoundException",
|
|
"Statement not found: " + statementId, 400);
|
|
}
|
|
ObjectNode policy = (ObjectNode) objectMapper.readTree(currentPolicy);
|
|
ArrayNode statements = (ArrayNode) policy.get("Statement");
|
|
boolean found = false;
|
|
for (int i = 0; i < statements.size(); i++) {
|
|
if (statementId.equals(statements.get(i).path("Sid").asText(null))) {
|
|
statements.remove(i);
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!found) {
|
|
throw new AwsException("ResourceNotFoundException",
|
|
"Statement not found: " + statementId, 400);
|
|
}
|
|
if (statements.isEmpty()) {
|
|
bus.setPolicy(null);
|
|
} else {
|
|
bus.setPolicy(objectMapper.writeValueAsString(policy));
|
|
}
|
|
} catch (AwsException e) {
|
|
throw e;
|
|
} catch (Exception e) {
|
|
throw new AwsException("InternalException", "Failed to process permission policy: " + e.getMessage(), 500);
|
|
}
|
|
}
|
|
|
|
busStore.put(key, bus);
|
|
LOG.infov("Removed permission from bus {0}, statement {1}, removeAll {2}", effectiveBus, statementId, removeAll);
|
|
}
|
|
|
|
// ──────────────────────────── PutEvents ────────────────────────────
|
|
|
|
public record PutEventsResult(int failedCount, List<Map<String, String>> entries) {}
|
|
|
|
/**
|
|
* The entry an AWS service sends on its own behalf, for {@link #putEvents}. {@code Resources} is
|
|
* always present, because rule matching reads it for any rule with a {@code resources} filter,
|
|
* and holds {@code resourceArn} unless that is null or blank. With no {@code EventBusName} the
|
|
* entry goes to the default bus; the map is mutable so a caller can name another.
|
|
*/
|
|
public static Map<String, Object> serviceEventEntry(String source, String detailType, String detail,
|
|
String resourceArn) {
|
|
ArrayNode resources = JsonNodeFactory.instance.arrayNode();
|
|
if (resourceArn != null && !resourceArn.isBlank()) {
|
|
resources.add(resourceArn);
|
|
}
|
|
Map<String, Object> entry = new HashMap<>();
|
|
entry.put("Source", source);
|
|
entry.put("DetailType", detailType);
|
|
entry.put("Detail", detail);
|
|
entry.put("Resources", resources);
|
|
return entry;
|
|
}
|
|
|
|
/**
|
|
* Publishes one event an AWS service sends on its own behalf to {@code region}'s default bus, in the
|
|
* caller's account. Best effort, as the change it reports has already happened and its caller must
|
|
* not see it fail: an entry the bus rejects, or any failure publishing it, is logged and goes no
|
|
* further.
|
|
*/
|
|
public void publishServiceEvent(String source, String detailType, String detail, String resourceArn,
|
|
String region) {
|
|
try {
|
|
PutEventsResult result = putEvents(List.of(serviceEventEntry(source, detailType, detail, resourceArn)),
|
|
region);
|
|
if (result.failedCount() > 0) {
|
|
LOG.warnv("EventBridge rejected the {0} {1} event in {2}: {3}", source, detailType, region,
|
|
result.entries());
|
|
}
|
|
} catch (RuntimeException e) {
|
|
LOG.warnv(e, "EventBridge could not publish the {0} {1} event in {2}", source, detailType, region);
|
|
}
|
|
}
|
|
|
|
public PutEventsResult putEvents(List<Map<String, Object>> entries, String region) {
|
|
return putEvents(entries, region, null);
|
|
}
|
|
|
|
/**
|
|
* Publishes entries to a bus, optionally naming the account the bus lives in.
|
|
*
|
|
* @param accountId account owning the target bus, or {@code null} to resolve against the
|
|
* caller's request context. Only {@code null} carries the un-prefixed
|
|
* legacy-key fallback in {@link AccountAwareStorageBackend#get}, so pass
|
|
* {@code null} whenever the target is in the caller's own account.
|
|
*/
|
|
public PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId) {
|
|
return putEvents(entries, region, accountId, false);
|
|
}
|
|
|
|
/**
|
|
* Publishes the entries of a {@code PutEvents} request. As {@link #putEvents(List, String)}, except that
|
|
* an entry for an event bus that does not exist is answered as published, with an event id and not
|
|
* counted as failed, and goes no further, as the EventBridge User Guide gives it: "If you use PutEvents
|
|
* to publish an event to an event bus that does not exist, EventBridge event matching will not find a
|
|
* corresponding rule and will drop the event. Although EventBridge will send a 200 response, it will not
|
|
* fail the request or include the event in the FailedEntryCount value of the request response." Floci's
|
|
* own deliveries to a bus, for a rule, a pipe or a schedule, go through {@link #putEvents} and still fail
|
|
* such an entry: the guide's sentence is about the action, and no document says how AWS answers them.
|
|
*/
|
|
public PutEventsResult putEventsFromRequest(List<Map<String, Object>> entries, String region) {
|
|
return putEvents(entries, region, null, true);
|
|
}
|
|
|
|
private PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId,
|
|
boolean dropForMissingBus) {
|
|
int failed = 0;
|
|
List<Map<String, String>> resultEntries = new ArrayList<>();
|
|
|
|
for (Map<String, Object> originalEntry : entries) {
|
|
// Defensive copy: callers may pass Map.of(...) (immutable) and we don't want to
|
|
// mutate caller state regardless. Normalize Region / Account from the PutEvents
|
|
// call context up front so matchesPattern, buildEventEnvelope, and the archive
|
|
// capture all see the same values — without this, a pattern's region/account
|
|
// filter would fall back to the resolver default in matchesPattern while the
|
|
// delivered envelope would correctly carry the call's region/account, giving an
|
|
// inconsistent observable.
|
|
Map<String, Object> entry = new HashMap<>(originalEntry);
|
|
|
|
String missingRequiredField = null;
|
|
for(String field : REQUIRED_ENTRY_FIELDS) {
|
|
if(entry.get(field) == null) {
|
|
missingRequiredField = field;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if(missingRequiredField != null) {
|
|
Map<String, String> errorEntry = new HashMap<>();
|
|
errorEntry.put("ErrorCode", "InvalidArgument");
|
|
errorEntry.put("ErrorMessage",
|
|
"Parameter " + missingRequiredField + " is not valid. Reason: " + missingRequiredField + " is a required argument.");
|
|
resultEntries.add(errorEntry);
|
|
failed++;
|
|
continue;
|
|
}
|
|
if (!isValidDetailJson(entry)) {
|
|
Map<String, String> errorEntry = new HashMap<>();
|
|
errorEntry.put("ErrorCode", "MalformedDetail");
|
|
errorEntry.put("ErrorMessage", "The JSON provided is not valid.");
|
|
resultEntries.add(errorEntry);
|
|
failed++;
|
|
|
|
continue;
|
|
}
|
|
if (isBlank(entry.get("Region"))) {
|
|
entry.put("Region", isBlank(region) ? regionResolver.getDefaultRegion() : region);
|
|
}
|
|
if (isBlank(entry.get("Account"))) {
|
|
entry.put("Account", isBlank(accountId) ? regionResolver.getAccountId() : accountId);
|
|
}
|
|
|
|
String eventBusNameRaw = (String) entry.get("EventBusName");
|
|
String effectiveBus = resolvedBusName(eventBusNameRaw);
|
|
String busStoreKey = busKey(region, effectiveBus);
|
|
|
|
if ("default".equals(effectiveBus)) {
|
|
getOrCreateDefaultBus(region);
|
|
} else if (getInAccount(busStore, accountId, busStoreKey).isEmpty()) {
|
|
if (dropForMissingBus) {
|
|
LOG.infov("PutEvents dropped an event for event bus {0}, which does not exist in {1}",
|
|
effectiveBus, region);
|
|
resultEntries.add(Map.of("EventId", UUID.randomUUID().toString()));
|
|
continue;
|
|
}
|
|
failed++;
|
|
Map<String, String> errorEntry = new HashMap<>();
|
|
errorEntry.put("ErrorCode", "InvalidArgument");
|
|
errorEntry.put("ErrorMessage", "EventBus not found: " + effectiveBus);
|
|
resultEntries.add(errorEntry);
|
|
continue;
|
|
}
|
|
|
|
String eventId = UUID.randomUUID().toString();
|
|
String rulePrefix = ruleKeyPrefix(region, effectiveBus);
|
|
List<Rule> candidateRules = accountScan(ruleStore, accountId, k -> isRuleKeyOfBus(k, rulePrefix));
|
|
|
|
for (Rule rule : candidateRules) {
|
|
if (!effectiveBus.equals(rule.getEventBusName()) || rule.getState() != RuleState.ENABLED) {
|
|
continue;
|
|
}
|
|
// A rule without an event pattern is a schedule rule: it never matches put events.
|
|
if (rule.getEventPattern() == null || rule.getEventPattern().isBlank()) {
|
|
continue;
|
|
}
|
|
if (matchesPattern(entry, rule.getEventPattern())) {
|
|
String ruleKey = ruleKey(region, effectiveBus, rule.getName());
|
|
List<Target> targets = getInAccount(targetStore, accountId, ruleKey).orElse(List.of());
|
|
String eventJson = buildEventEnvelope(entry, eventId, region, accountId);
|
|
for (Target target : targets) {
|
|
dispatcher.dispatch(rule.getArn(), target, eventJson, region,
|
|
() -> getInAccount(targetStore, accountId, ruleKey).orElse(List.of()));
|
|
}
|
|
}
|
|
}
|
|
|
|
captureToArchives(entry, busStoreKey, eventId, region, accountId);
|
|
|
|
Map<String, String> successEntry = new HashMap<>();
|
|
successEntry.put("EventId", eventId);
|
|
resultEntries.add(successEntry);
|
|
}
|
|
|
|
return new PutEventsResult(failed, resultEntries);
|
|
}
|
|
|
|
private boolean isValidDetailJson(Map<String, Object> detail) {
|
|
Object raw = detail.get("Detail");
|
|
if (!(raw instanceof String jsonString) || jsonString.trim().isEmpty()) {
|
|
return false;
|
|
}
|
|
|
|
try (JsonParser parser = objectMapper.getFactory().createParser(jsonString)) {
|
|
JsonNode node = objectMapper.readTree(parser);
|
|
if (node == null || !node.isObject()) {
|
|
return false; // empty input or "123" or "[1,2]"
|
|
}
|
|
// check if there is more
|
|
return parser.nextToken() == null;
|
|
} catch (IOException e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Pattern Matching ────────────────────────────
|
|
|
|
/**
|
|
* Tests whether a sample event matches a given event pattern, without firing any
|
|
* targets. Mirrors the AWS {@code TestEventPattern} API: callers pass the full event
|
|
* envelope (lowercase {@code source} / {@code detail-type} / {@code detail} /
|
|
* {@code resources}) as JSON; we adapt it to the internal entry shape and delegate
|
|
* to {@link #matchesPattern(Map, String)}.
|
|
*/
|
|
public boolean testEventPattern(String eventPattern, String eventJson) {
|
|
if (eventPattern == null || eventPattern.isBlank()) {
|
|
throw new AwsException("InvalidEventPatternException", "EventPattern is required.", 400);
|
|
}
|
|
if (eventJson == null || eventJson.isBlank()) {
|
|
throw new AwsException("InvalidEventPatternException", "Event is required.", 400);
|
|
}
|
|
validateEventPattern(eventPattern);
|
|
JsonNode event;
|
|
try {
|
|
event = objectMapper.readTree(eventJson);
|
|
} catch (Exception e) {
|
|
throw new AwsException("InvalidEventPatternException",
|
|
"Event is not valid JSON: " + e.getMessage(), 400);
|
|
}
|
|
if (event == null || !event.isObject()) {
|
|
throw new AwsException("InvalidEventPatternException",
|
|
"Event must be a JSON object.", 400);
|
|
}
|
|
Map<String, Object> entry = new HashMap<>();
|
|
if (event.hasNonNull("source")) {
|
|
entry.put("Source", event.get("source").asText());
|
|
}
|
|
if (event.hasNonNull("detail-type")) {
|
|
entry.put("DetailType", event.get("detail-type").asText());
|
|
}
|
|
if (event.hasNonNull("detail")) {
|
|
JsonNode detail = event.get("detail");
|
|
entry.put("Detail", detail.isTextual() ? detail.asText() : detail.toString());
|
|
}
|
|
if (event.hasNonNull("resources") && event.get("resources").isArray()) {
|
|
entry.put("Resources", event.get("resources"));
|
|
}
|
|
if (event.hasNonNull("account")) {
|
|
entry.put("Account", event.get("account").asText());
|
|
}
|
|
if (event.hasNonNull("region")) {
|
|
entry.put("Region", event.get("region").asText());
|
|
}
|
|
return matchesPattern(entry, eventPattern);
|
|
}
|
|
|
|
private void validateEventPattern(String eventPattern) {
|
|
JsonNode pattern;
|
|
try {
|
|
pattern = objectMapper.readTree(eventPattern);
|
|
} catch (JsonProcessingException e) {
|
|
throw new AwsException("InvalidEventPatternException",
|
|
"Event pattern is not valid JSON: " + e.getMessage(), 400);
|
|
}
|
|
if (pattern == null || !pattern.isObject()) {
|
|
throw new AwsException("InvalidEventPatternException", "Event pattern must be a JSON object.", 400);
|
|
}
|
|
validateNumericPatterns(pattern);
|
|
}
|
|
|
|
private void validateNumericPatterns(JsonNode pattern) {
|
|
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
|
|
while (fields.hasNext()) {
|
|
Map.Entry<String, JsonNode> field = fields.next();
|
|
JsonNode expected = field.getValue();
|
|
if ("$or".equals(field.getKey()) && expected.isArray()) {
|
|
for (JsonNode branch : expected) {
|
|
validateNumericPatterns(branch);
|
|
}
|
|
} else if (expected.isObject()) {
|
|
validateNumericPatterns(expected);
|
|
} else if (expected.isArray()) {
|
|
for (JsonNode filter : expected) {
|
|
if (filter.isObject() && filter.has("numeric") && !isValidNumericFilter(filter.get("numeric"))) {
|
|
throw new AwsException("InvalidEventPatternException",
|
|
"numeric must contain one comparison or a lower bound followed by an upper bound"
|
|
+ " with a strictly greater endpoint.", 400);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
boolean matchesPattern(Map<String, Object> event, String eventPattern) {
|
|
if (eventPattern == null || eventPattern.isBlank()) {
|
|
return true;
|
|
}
|
|
try {
|
|
JsonNode pattern = objectMapper.readTree(eventPattern);
|
|
JsonNode orClauses = pattern.get("$or");
|
|
if (orClauses != null && orClauses.isArray()) {
|
|
boolean anyMatches = false;
|
|
for (JsonNode subPattern : orClauses) {
|
|
if (matchesPattern(event, objectMapper.writeValueAsString(subPattern))) {
|
|
anyMatches = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!anyMatches) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode sourceField = pattern.get("source");
|
|
if (sourceField != null && sourceField.isArray()) {
|
|
String eventSource = (String) event.get("Source");
|
|
if (!matchesArrayField(sourceField, eventSource)) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode detailTypeField = pattern.get("detail-type");
|
|
if (detailTypeField != null && detailTypeField.isArray()) {
|
|
String eventDetailType = (String) event.get("DetailType");
|
|
if (!matchesArrayField(detailTypeField, eventDetailType)) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode accountField = pattern.get("account");
|
|
if (accountField != null && accountField.isArray()) {
|
|
// Prefer the entry's Account (set by TestEventPattern from the
|
|
// supplied event envelope); fall back to the caller's account
|
|
// for PutEvents rule dispatch, where the event always belongs
|
|
// to the caller.
|
|
String eventAccount = (String) event.getOrDefault(
|
|
"Account", regionResolver.getAccountId());
|
|
if (!matchesArrayField(accountField, eventAccount)) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode regionField = pattern.get("region");
|
|
if (regionField != null && regionField.isArray()) {
|
|
String eventRegion = (String) event.getOrDefault(
|
|
"Region", regionResolver.getDefaultRegion());
|
|
if (!matchesArrayField(regionField, eventRegion)) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode detailPattern = pattern.get("detail");
|
|
if (detailPattern != null && detailPattern.isObject()) {
|
|
Object eventDetail = event.get("Detail");
|
|
String detailStr = eventDetail instanceof String s ? s : null;
|
|
if (detailStr == null) {
|
|
return false;
|
|
}
|
|
JsonNode detailNode = objectMapper.readTree(detailStr);
|
|
if (!matchesDetailNode(detailNode, detailPattern)) {
|
|
return false;
|
|
}
|
|
}
|
|
JsonNode resourcesPattern = pattern.get("resources");
|
|
if (resourcesPattern != null && resourcesPattern.isArray()) {
|
|
Iterator<JsonNode> resources = ((ArrayNode) event.get("Resources")).elements();
|
|
while (resources.hasNext()) {
|
|
String resource = resources.next().asText(null);
|
|
if (matchesArrayField(resourcesPattern, resource)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return true;
|
|
} catch (Exception e) {
|
|
LOG.warnv("Failed to parse event pattern: {0}", e.getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private boolean matchesNestedDetail(JsonNode actual, JsonNode pattern) {
|
|
if (actual.isArray()) {
|
|
if (actual.isEmpty()) {
|
|
return matchesDetailNode(JsonNodeFactory.instance.nullNode(), pattern);
|
|
}
|
|
for (JsonNode element : actual) {
|
|
if (matchesDetailNode(element, pattern)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return matchesDetailNode(actual, pattern);
|
|
}
|
|
|
|
private boolean matchesDetailNode(JsonNode actual, JsonNode pattern) {
|
|
if (pattern.isEmpty()) {
|
|
return actual != null && actual.isObject();
|
|
}
|
|
JsonNode orClauses = pattern.get("$or");
|
|
if (orClauses != null && orClauses.isArray()) {
|
|
boolean anyMatches = false;
|
|
for (JsonNode subPattern : orClauses) {
|
|
if (matchesDetailNode(actual, subPattern)) {
|
|
anyMatches = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!anyMatches) {
|
|
return false;
|
|
}
|
|
}
|
|
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
|
|
while (fields.hasNext()) {
|
|
Map.Entry<String, JsonNode> field = fields.next();
|
|
if ("$or".equals(field.getKey())) {
|
|
continue;
|
|
}
|
|
JsonNode expected = field.getValue();
|
|
JsonNode actualField = actual.get(field.getKey());
|
|
if (expected.isArray()) {
|
|
JsonNode leaf = actualField != null && actualField.isArray() && actualField.isEmpty()
|
|
? null : actualField;
|
|
if (!matchesArrayField(expected, leaf)) {
|
|
return false;
|
|
}
|
|
} else if (expected.isObject()) {
|
|
JsonNode nestedActual = actualField == null
|
|
? JsonNodeFactory.instance.nullNode() : actualField;
|
|
if (nestedActual.isTextual()) {
|
|
try {
|
|
nestedActual = objectMapper.readTree(nestedActual.asText());
|
|
} catch (Exception e) {
|
|
nestedActual = JsonNodeFactory.instance.nullNode();
|
|
}
|
|
}
|
|
if (!matchesNestedDetail(nestedActual, expected)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private boolean matchesArrayField(JsonNode arrayNode, String value) {
|
|
JsonNode actual = value != null ? TextNode.valueOf(value) : null;
|
|
return matchesArrayField(arrayNode, actual);
|
|
}
|
|
|
|
private boolean matchesArrayField(JsonNode arrayNode, JsonNode actual) {
|
|
return matchesArrayField(arrayNode, actual, true);
|
|
}
|
|
|
|
private boolean matchesArrayField(JsonNode arrayNode, JsonNode actual, boolean checkExists) {
|
|
if (actual != null && actual.isArray()) {
|
|
if (checkExists) {
|
|
for (JsonNode element : arrayNode) {
|
|
if (element.isObject() && element.has("exists")
|
|
&& matchesSingleElement(element, actual)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
for (JsonNode value : actual) {
|
|
if (matchesArrayField(arrayNode, value, false)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
for (JsonNode element : arrayNode) {
|
|
if (!checkExists && element.isObject() && element.has("exists")) {
|
|
continue;
|
|
}
|
|
if (matchesSingleElement(element, actual)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private boolean matchesSingleElement(JsonNode element, JsonNode actual) {
|
|
// Content filter object
|
|
if (element.isObject()) {
|
|
String value = actual != null && actual.isTextual() ? actual.asText() : null;
|
|
if (element.has("prefix")) {
|
|
return value != null && value.startsWith(element.get("prefix").asText());
|
|
}
|
|
if (element.has("suffix")) {
|
|
return value != null && value.endsWith(element.get("suffix").asText());
|
|
}
|
|
// Amazon EventBridge User Guide, Comparison operators for use in event patterns,
|
|
// Matching using wildcards: each * matches any run of characters in a string value,
|
|
// and \* and \\ stand for a literal * and \.
|
|
if (element.has("wildcard")) {
|
|
JsonNode wildcard = element.get("wildcard");
|
|
return value != null && wildcard.isTextual()
|
|
&& StarWildcard.matchesEscaped(wildcard.asText(), value);
|
|
}
|
|
if (element.has("equals-ignore-case")) {
|
|
return value != null && value.equalsIgnoreCase(element.get("equals-ignore-case").asText());
|
|
}
|
|
if (element.has("numeric")) {
|
|
JsonNode comparisons = element.get("numeric");
|
|
return actual != null && isValidNumericFilter(comparisons)
|
|
&& PipesFilterMatcher.matchesNumeric(comparisons, actual);
|
|
}
|
|
if (element.has("anything-but")) {
|
|
JsonNode anythingBut = element.get("anything-but");
|
|
if (anythingBut.isValueNode()) {
|
|
return actual != null && !actual.isNull() && !matchesExactValue(anythingBut, actual);
|
|
}
|
|
if (anythingBut.isArray()) {
|
|
for (JsonNode v : anythingBut) {
|
|
if (matchesExactValue(v, actual)) {
|
|
return false;
|
|
}
|
|
}
|
|
return actual != null && !actual.isNull();
|
|
}
|
|
if (anythingBut.isObject() && anythingBut.has("prefix")) {
|
|
return value != null && !value.startsWith(anythingBut.get("prefix").asText());
|
|
}
|
|
}
|
|
if (element.has("exists")) {
|
|
boolean shouldExist = element.get("exists").asBoolean();
|
|
boolean present = containsLeafValue(actual);
|
|
return shouldExist == present;
|
|
}
|
|
return false;
|
|
}
|
|
// Exact literal match (string, null, boolean, number)
|
|
return matchesExactValue(element, actual);
|
|
}
|
|
|
|
private boolean containsLeafValue(JsonNode actual) {
|
|
if (actual == null || actual.isObject()) {
|
|
return false;
|
|
}
|
|
if (actual.isArray()) {
|
|
for (JsonNode element : actual) {
|
|
if (containsLeafValue(element)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return actual.isValueNode();
|
|
}
|
|
|
|
private boolean isValidNumericFilter(JsonNode comparisons) {
|
|
if (!comparisons.isArray() || (comparisons.size() != 2 && comparisons.size() != 4)) {
|
|
return false;
|
|
}
|
|
for (int i = 0; i < comparisons.size(); i += 2) {
|
|
JsonNode operator = comparisons.get(i);
|
|
if (!operator.isTextual() || !NUMERIC_OPERATORS.contains(operator.textValue())
|
|
|| !comparisons.get(i + 1).isNumber()) {
|
|
return false;
|
|
}
|
|
}
|
|
if (comparisons.size() == 2) {
|
|
return true;
|
|
}
|
|
String lowerOperator = comparisons.get(0).textValue();
|
|
String upperOperator = comparisons.get(2).textValue();
|
|
return (">".equals(lowerOperator) || ">=".equals(lowerOperator))
|
|
&& ("<".equals(upperOperator) || "<=".equals(upperOperator))
|
|
&& comparisons.get(1).decimalValue().compareTo(comparisons.get(3).decimalValue()) < 0;
|
|
}
|
|
|
|
private boolean matchesExactValue(JsonNode expected, JsonNode actual) {
|
|
if (expected.isNull()) {
|
|
return actual != null && actual.isNull();
|
|
}
|
|
if (actual == null) {
|
|
return false;
|
|
}
|
|
if (expected.isTextual()) {
|
|
return actual.isTextual() && expected.asText().equals(actual.asText());
|
|
}
|
|
if (expected.isBoolean()) {
|
|
return actual.isBoolean() && expected.booleanValue() == actual.booleanValue();
|
|
}
|
|
if (expected.isNumber()) {
|
|
// AWS normalizes numbers before comparing: 300, 300.0 and 3.0e2
|
|
// are all considered equal.
|
|
return actual.isNumber() && expected.decimalValue().compareTo(actual.decimalValue()) == 0;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ──────────────────────────── Target Routing ────────────────────────────
|
|
|
|
|
|
private String buildEventEnvelope(Map<String, Object> entry, String eventId,
|
|
String callRegion, String callAccountId) {
|
|
try {
|
|
String source = (String) entry.getOrDefault("Source", "");
|
|
String detailType = (String) entry.getOrDefault("DetailType", "");
|
|
String detail = (String) entry.getOrDefault("Detail", "{}");
|
|
ArrayNode resources = (ArrayNode) entry.getOrDefault("Resources", objectMapper.createArrayNode());
|
|
// Envelope region/account precedence: entry-supplied "Region"/"Account" (set by
|
|
// archive replay paths and cross-region producers) wins; otherwise stamp the
|
|
// region/account the PutEvents call was made against. Only when neither is
|
|
// available do we fall back to the RegionResolver defaults. This keeps the
|
|
// envelope consistent with matchesPattern() which also reads entry.Region with
|
|
// the same fallback chain.
|
|
String envelopeRegion = (String) entry.get("Region");
|
|
if (isBlank(envelopeRegion)) {
|
|
envelopeRegion = isBlank(callRegion) ? regionResolver.getDefaultRegion() : callRegion;
|
|
}
|
|
String envelopeAccount = (String) entry.get("Account");
|
|
if (isBlank(envelopeAccount)) {
|
|
envelopeAccount = isBlank(callAccountId) ? regionResolver.getAccountId() : callAccountId;
|
|
}
|
|
ObjectNode node = objectMapper.createObjectNode();
|
|
node.put("version", "0");
|
|
node.put("id", eventId);
|
|
node.put("source", source);
|
|
node.put("detail-type", detailType);
|
|
node.put("account", envelopeAccount);
|
|
Instant time = entry.get("Time") instanceof Instant entryTime ? entryTime : Instant.now();
|
|
node.put("time", time.truncatedTo(ChronoUnit.SECONDS).toString());
|
|
node.put("region", envelopeRegion);
|
|
node.putArray("resources").addAll(resources);
|
|
node.set("detail", objectMapper.readTree(detail));
|
|
return objectMapper.writeValueAsString(node);
|
|
} catch (Exception e) {
|
|
return "{}";
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Helpers ────────────────────────────
|
|
|
|
private boolean isRuleEnabled(String ruleStoreKey) {
|
|
return ruleStore.get(ruleStoreKey)
|
|
.map(r -> r.getState() == RuleState.ENABLED)
|
|
.orElse(false);
|
|
}
|
|
|
|
private void ensureBusExists(String busName, String region) {
|
|
if ("default".equals(busName)) {
|
|
getOrCreateDefaultBus(region);
|
|
return;
|
|
}
|
|
busStore.get(busKey(region, busName))
|
|
.orElseThrow(() -> eventBusNotFound(busName));
|
|
}
|
|
|
|
private static AwsException eventBusNotFound(String busName) {
|
|
return new AwsException("ResourceNotFoundException", "EventBus not found: " + busName, 400);
|
|
}
|
|
|
|
private static boolean isBlank(Object value) {
|
|
return !(value instanceof String s) || s.isBlank();
|
|
}
|
|
|
|
/**
|
|
* The ARN of the event bus a {@code PutEvents} entry's {@code EventBusName} reaches: the bus of that
|
|
* name, or of the name its ARN gives, in the {@code account} and {@code region} the call runs in, as
|
|
* {@link #putEventsFromRequest} looks it up whatever account and Region the ARN names. Empty for an
|
|
* ARN that request refuses as malformed.
|
|
*/
|
|
public static Optional<String> eventBusArn(String eventBusName, String partition, String region, String account) {
|
|
try {
|
|
return Optional.of(new AwsArnUtils.Arn(partition, "events", region, account,
|
|
"event-bus/" + resolvedBusName(eventBusName)).toString());
|
|
} catch (AwsException e) {
|
|
LOG.debugv("EventBusName {0} is malformed, so it names no bus: {1}", eventBusName, e.getMessage());
|
|
return Optional.empty();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The resource policy of the event bus {@code busArn} names, in the account and Region of that ARN.
|
|
* Empty when the bus does not exist or has no policy; the default bus has none until one is put on it.
|
|
*/
|
|
public Optional<String> findBusPolicy(String busArn) {
|
|
AwsArnUtils.Arn arn = AwsArnUtils.parse(busArn);
|
|
String name = arn.resource().substring("event-bus/".length());
|
|
return getInAccount(busStore, arn.accountId(), busKey(arn.region(), name))
|
|
.map(EventBus::getPolicy)
|
|
.filter(policy -> !policy.isBlank());
|
|
}
|
|
|
|
/**
|
|
* The bus a permission call addresses. {@code PutPermission} and {@code RemovePermission} model
|
|
* the name as {@code NonPartnerEventBusName}, so a partner bus, whose name holds a slash, is
|
|
* refused there as AWS refuses it rather than given a policy nothing would enforce.
|
|
*/
|
|
private static String resolvedNonPartnerBusName(String busName) {
|
|
String effectiveBus = resolvedBusName(busName);
|
|
if (effectiveBus.indexOf('/') >= 0) {
|
|
throw SmithyValidationErrors.validationException(
|
|
nameViolations("eventBusName", busName, 256, NON_PARTNER_NAME));
|
|
}
|
|
return effectiveBus;
|
|
}
|
|
|
|
private static String resolvedBusName(String busName) {
|
|
if (busName == null || busName.isBlank()) {
|
|
return "default";
|
|
}
|
|
// Handle ARN format: arn:<partition>:events:region:account-id:event-bus/bus-name
|
|
if (EVENT_BUS_ARN_PREFIX.matcher(busName).lookingAt()) {
|
|
try {
|
|
return extractBusNameFromArn(busName);
|
|
} catch (IllegalArgumentException e) {
|
|
throw new AwsException("ValidationException", "Invalid EventBridge event bus ARN: " + busName, 400);
|
|
}
|
|
}
|
|
return busName;
|
|
}
|
|
|
|
/**
|
|
* The partition-tolerant form of {@code startsWith("arn:aws:events:")}: it matches a prefix,
|
|
* not a whole ARN, so a truncated {@code arn:aws:events:} still enters the branch below and is
|
|
* reported as a malformed ARN rather than silently taken as a literal bus name.
|
|
*/
|
|
private static final Pattern EVENT_BUS_ARN_PREFIX =
|
|
Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":events:");
|
|
|
|
private static String extractBusNameFromArn(String arn) {
|
|
// ARN format: arn:aws:events:region:account-id:event-bus/bus-name
|
|
if (arn == null) return null;
|
|
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
|
if (!"events".equals(parsed.service())) {
|
|
throw new IllegalArgumentException("Expected EventBridge ARN but found service: " + parsed.service());
|
|
}
|
|
String prefix = "event-bus/";
|
|
if (parsed.resource() != null && parsed.resource().startsWith(prefix)) {
|
|
return parsed.resource().substring(prefix.length());
|
|
}
|
|
throw new IllegalArgumentException("Expected EventBridge event bus ARN but found resource: " + parsed.resource());
|
|
}
|
|
|
|
private static String busKey(String region, String name) {
|
|
return "bus:" + region + ":" + name;
|
|
}
|
|
|
|
private static String ruleKeyPrefix(String region, String busName) {
|
|
return "rule:" + region + ":" + busName + "/";
|
|
}
|
|
|
|
private Optional<Rule> ruleOfBus(String key, String busName) {
|
|
return ruleStore.get(key).filter(rule -> busName.equals(rule.getEventBusName()));
|
|
}
|
|
|
|
private static boolean isRuleKeyOfBus(String key, String rulePrefix) {
|
|
return key.startsWith(rulePrefix) && key.indexOf('/', rulePrefix.length()) < 0;
|
|
}
|
|
|
|
private static String ruleKey(String region, String busName, String ruleName) {
|
|
return ruleKeyPrefix(region, busName) + ruleName;
|
|
}
|
|
|
|
private String buildRuleArn(String region, String busName, String ruleName) {
|
|
if ("default".equals(busName)) {
|
|
return regionResolver.buildArn("events", region, "rule/" + ruleName);
|
|
}
|
|
return regionResolver.buildArn("events", region, "rule/" + busName + "/" + ruleName);
|
|
}
|
|
|
|
// ──────────────────────────── Archives ────────────────────────────
|
|
|
|
public Archive createArchive(String archiveName, String eventSourceArn, String description,
|
|
String eventPattern, int retentionDays, String region) {
|
|
requireArchiveFields(description, eventPattern, retentionDays);
|
|
if (archiveName == null || archiveName.isBlank()) {
|
|
throw new AwsException("ValidationException", "ArchiveName is required.", 400);
|
|
}
|
|
if (eventSourceArn == null || eventSourceArn.isBlank()) {
|
|
throw new AwsException("ValidationException", "EventSourceArn is required.", 400);
|
|
}
|
|
requireArchiveSource(eventSourceArn, region);
|
|
String key = archiveKey(region, archiveName);
|
|
if (archiveStore.get(key).isPresent()) {
|
|
throw new AwsException("ResourceAlreadyExistsException",
|
|
"Archive already exists: " + archiveName, 400);
|
|
}
|
|
Archive archive = new Archive();
|
|
archive.setArchiveName(archiveName);
|
|
archive.setArchiveArn(regionResolver.buildArn("events", region, "archive/" + archiveName));
|
|
archive.setEventSourceArn(eventSourceArn);
|
|
archive.setDescription(description);
|
|
archive.setEventPattern(eventPattern);
|
|
archive.setRetentionDays(retentionDays);
|
|
archive.setState(ArchiveState.ENABLED);
|
|
archive.setCreationTime(Instant.now());
|
|
archiveStore.put(key, archive);
|
|
LOG.infov("Created archive: {0} for source {1}", archiveName, eventSourceArn);
|
|
return archive;
|
|
}
|
|
|
|
/**
|
|
* The request constraints CreateArchive and UpdateArchive enforce before any other check, all
|
|
* violations reported together in AWS's order. A null argument is absent and not checked.
|
|
*/
|
|
private void requireArchiveFields(String description, String eventPattern, Integer retentionDays) {
|
|
List<String> violations = new ArrayList<>();
|
|
if (retentionDays != null && retentionDays < 0) {
|
|
violations.add("Value '" + retentionDays + "' at 'retentionDays' failed to satisfy constraint: "
|
|
+ "Member must have value greater than or equal to 0");
|
|
}
|
|
String descriptionViolation = description == null ? null
|
|
: SmithyValidationErrors.lengthOutOfRange("description", description, 0, 512);
|
|
if (descriptionViolation != null) {
|
|
violations.add(descriptionViolation);
|
|
}
|
|
String eventPatternViolation = eventPattern == null ? null
|
|
: SmithyValidationErrors.lengthOutOfRange("eventPattern", eventPattern, 0, 4096);
|
|
if (eventPatternViolation != null) {
|
|
violations.add(eventPatternViolation);
|
|
}
|
|
if (!violations.isEmpty()) {
|
|
throw SmithyValidationErrors.validationException(violations);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Checked as AWS does, before the name: the source's account, then its region, then that it is
|
|
* the ARN of an existing bus. Anything else, a malformed ARN included, is reported as a missing
|
|
* bus, since an archive on it could never capture an event.
|
|
*/
|
|
private void requireArchiveSource(String eventSourceArn, String region) {
|
|
String accountId = regionResolver.getAccountId();
|
|
AwsArnUtils.Arn source = AwsArnUtils.isArn(eventSourceArn) ? AwsArnUtils.parse(eventSourceArn) : null;
|
|
if (source != null && !accountId.equals(source.accountId())) {
|
|
throw new AwsException("AccessDeniedException", "Archive event source " + eventSourceArn
|
|
+ " does not belong to account " + accountId + ".", 400);
|
|
}
|
|
if (source != null && !region.equals(source.region())) {
|
|
throw new AwsException("ValidationException",
|
|
"Parameter EventSourceArn is not valid. Reason: Creating cross-region archive is not permitted.",
|
|
400);
|
|
}
|
|
String busName = source != null && source.resource().startsWith("event-bus/")
|
|
? source.resource().substring("event-bus/".length()) : eventSourceArn;
|
|
EventBus bus = "default".equals(busName)
|
|
? getOrCreateDefaultBus(region)
|
|
: busStore.get(busKey(region, busName)).orElse(null);
|
|
if (bus == null || !eventSourceArn.equals(bus.getArn())) {
|
|
throw new AwsException("ResourceNotFoundException", "Event bus " + busName + " does not exist.", 400);
|
|
}
|
|
}
|
|
|
|
public Archive describeArchive(String archiveName, String region) {
|
|
return archiveStore.get(archiveKey(region, archiveName))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Archive not found: " + archiveName, 400));
|
|
}
|
|
|
|
/**
|
|
* A partial update, as on AWS: a null argument leaves the stored value alone, and an empty
|
|
* description or event pattern clears it.
|
|
*/
|
|
public Archive updateArchive(String archiveName, String description,
|
|
String eventPattern, Integer retentionDays, String region) {
|
|
requireArchiveFields(description, eventPattern, retentionDays);
|
|
String key = archiveKey(region, archiveName);
|
|
Archive archive = archiveStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Archive not found: " + archiveName, 400));
|
|
if (description != null) {
|
|
archive.setDescription(description.isEmpty() ? null : description);
|
|
}
|
|
if (eventPattern != null) {
|
|
archive.setEventPattern(eventPattern.isEmpty() ? null : eventPattern);
|
|
}
|
|
if (retentionDays != null) {
|
|
archive.setRetentionDays(retentionDays);
|
|
}
|
|
archiveStore.put(key, archive);
|
|
return archive;
|
|
}
|
|
|
|
public void deleteArchive(String archiveName, String region) {
|
|
String key = archiveKey(region, archiveName);
|
|
Archive archive = archiveStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Archive not found: " + archiveName, 400));
|
|
archiveStore.delete(key);
|
|
archivedEventStore.delete(archivedEventKey(region, archiveName));
|
|
resourceGroupsTaggingService.deleteResources(List.of(archive.getArchiveArn()), region);
|
|
LOG.infov("Deleted archive: {0}", archiveName);
|
|
}
|
|
|
|
public List<Archive> listArchives(String namePrefix, String eventSourceArn,
|
|
ArchiveState state, String region) {
|
|
String prefix = "archive:" + region + ":";
|
|
return archiveStore.scan(k -> {
|
|
if (!k.startsWith(prefix)) return false;
|
|
Archive a = archiveStore.get(k).orElse(null);
|
|
if (a == null) return false;
|
|
if (namePrefix != null && !namePrefix.isBlank()
|
|
&& !a.getArchiveName().startsWith(namePrefix)) {
|
|
return false;
|
|
}
|
|
if (eventSourceArn != null && !eventSourceArn.isBlank()
|
|
&& !eventSourceArn.equals(a.getEventSourceArn())) {
|
|
return false;
|
|
}
|
|
if (state != null && state != a.getState()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
|
|
// ──────────────────────────── Connections ────────────────────────────
|
|
|
|
private static final Pattern CONNECTION_NAME_PATTERN =
|
|
Pattern.compile("[\\.\\-_A-Za-z0-9]+");
|
|
|
|
public Connection createConnection(String name, String description, String authorizationType,
|
|
String authParameters, String invocationConnectivityParameters,
|
|
String kmsKeyIdentifier, String region) {
|
|
validateConnectionName(name);
|
|
validateAuthorizationType(authorizationType);
|
|
if (authParameters == null) {
|
|
throw new AwsException("ValidationException", "AuthParameters is required.", 400);
|
|
}
|
|
String key = connectionKey(region, name);
|
|
if (connectionStore.get(key).isPresent()) {
|
|
throw new AwsException("ResourceAlreadyExistsException",
|
|
"Connection " + name + " already exists.", 400);
|
|
}
|
|
String connectionId = UUID.randomUUID().toString();
|
|
Instant now = Instant.now();
|
|
Connection connection = new Connection();
|
|
connection.setName(name);
|
|
connection.setConnectionArn(regionResolver.buildArn("events", region,
|
|
"connection/" + name + "/" + connectionId));
|
|
connection.setDescription(description);
|
|
connection.setAuthorizationType(authorizationType);
|
|
connection.setAuthParameters(authParameters);
|
|
connection.setInvocationConnectivityParameters(invocationConnectivityParameters);
|
|
connection.setKmsKeyIdentifier(kmsKeyIdentifier);
|
|
connection.setSecretArn(regionResolver.buildArn("secretsmanager", region,
|
|
"secret:events!connection/" + name + "/" + connectionId));
|
|
connection.setConnectionState(ConnectionState.AUTHORIZED);
|
|
connection.setCreationTime(now);
|
|
connection.setLastModifiedTime(now);
|
|
connection.setLastAuthorizedTime(now);
|
|
connectionStore.put(key, connection);
|
|
LOG.infov("Created connection: {0} with authorization type {1}", name, authorizationType);
|
|
return connection;
|
|
}
|
|
|
|
@Override
|
|
public String namespace() {
|
|
return "events";
|
|
}
|
|
|
|
/** The tags of the exact bus or rule ARN, read without changing the stored resource. */
|
|
@Override
|
|
public Map<String, String> storedTags(String resourceArn) {
|
|
if (!AwsArnUtils.isArnFor(resourceArn, "events")) {
|
|
return Map.of();
|
|
}
|
|
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
|
if (!regionResolver.partitionForRegion(arn.region()).equals(arn.partition())) {
|
|
return Map.of();
|
|
}
|
|
if (!arn.resource().startsWith("event-bus/") && !arn.resource().startsWith("rule/")) {
|
|
return Map.of();
|
|
}
|
|
return findTagResource(arn.accountId(), arn.region(), arn.resource())
|
|
.filter(target -> resourceArn.equals(target.arn()))
|
|
.map(TagResource::tags).map(LinkedHashMap::new).orElseGet(LinkedHashMap::new);
|
|
}
|
|
|
|
/** The Region's default event bus, which a request naming no bus acts on. */
|
|
@Override
|
|
public Optional<String> findDefault(String type, String region) {
|
|
return "event-bus".equals(type) ? Optional.of(regionResolver.buildArn("events", region, "event-bus/default"))
|
|
: Optional.empty();
|
|
}
|
|
|
|
/**
|
|
* The ARN of the caller's connection or API destination of the one name in the Region, which follows the name
|
|
* with the id it was minted with, as its handlers look it up.
|
|
*/
|
|
@Override
|
|
public Optional<String> find(String type, List<String> names, String region) {
|
|
if (names.size() != 1) {
|
|
return Optional.empty();
|
|
}
|
|
String name = names.getFirst();
|
|
return switch (type) {
|
|
case "connection" -> connectionStore.get(connectionKey(region, name)).map(Connection::getConnectionArn);
|
|
case "api-destination" -> apiDestinationStore.get(apiDestinationKey(region, name)).map(ApiDestination::getArn);
|
|
default -> Optional.empty();
|
|
};
|
|
}
|
|
|
|
public Connection describeConnection(String name, String region) {
|
|
return connectionStore.get(connectionKey(region, name))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Connection " + name + " does not exist.", 400));
|
|
}
|
|
|
|
public Connection updateConnection(String name, String description, String authorizationType,
|
|
String authParameters, String invocationConnectivityParameters,
|
|
String kmsKeyIdentifier, String region) {
|
|
return updateConnection(name, description, authorizationType, authParameters,
|
|
invocationConnectivityParameters, kmsKeyIdentifier, Set.of(), region);
|
|
}
|
|
|
|
/**
|
|
* As {@link #updateConnection(String, String, String, String, String, String, String)}, and the
|
|
* settings named in {@code cleared} ({@code InvocationConnectivityParameters} or
|
|
* {@code KmsKeyIdentifier}) are removed, as a CloudFormation update that drops them does.
|
|
*/
|
|
public Connection updateConnection(String name, String description, String authorizationType,
|
|
String authParameters, String invocationConnectivityParameters,
|
|
String kmsKeyIdentifier, Set<String> cleared, String region) {
|
|
String key = connectionKey(region, name);
|
|
Connection connection = connectionStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Connection " + name + " does not exist.", 400));
|
|
if (authorizationType != null) {
|
|
validateAuthorizationType(authorizationType);
|
|
if (!authorizationType.equals(connection.getAuthorizationType()) && authParameters == null) {
|
|
throw new AwsException("ValidationException",
|
|
"AuthParameters must be provided when changing AuthorizationType.", 400);
|
|
}
|
|
connection.setAuthorizationType(authorizationType);
|
|
}
|
|
if (description != null) {
|
|
// An empty description clears it, as the stack update that sets one does
|
|
connection.setDescription(description.isEmpty() ? null : description);
|
|
}
|
|
if (authParameters != null) {
|
|
connection.setAuthParameters(authParameters);
|
|
}
|
|
if (invocationConnectivityParameters != null) {
|
|
connection.setInvocationConnectivityParameters(invocationConnectivityParameters);
|
|
}
|
|
if (kmsKeyIdentifier != null) {
|
|
connection.setKmsKeyIdentifier(kmsKeyIdentifier);
|
|
}
|
|
if (cleared.contains("InvocationConnectivityParameters")) {
|
|
connection.setInvocationConnectivityParameters(null);
|
|
}
|
|
if (cleared.contains("KmsKeyIdentifier")) {
|
|
connection.setKmsKeyIdentifier(null);
|
|
}
|
|
Instant now = Instant.now();
|
|
connection.setConnectionState(ConnectionState.AUTHORIZED);
|
|
connection.setLastModifiedTime(now);
|
|
connection.setLastAuthorizedTime(now);
|
|
connectionStore.put(key, connection);
|
|
return connection;
|
|
}
|
|
|
|
/**
|
|
* Puts a connection's mutable settings back to the values {@code previous} carries, exactly:
|
|
* unlike {@link #updateConnection} a null clears the field, and the authorization state and
|
|
* timestamps come back with it. The ARN, secret ARN and creation time are the stored
|
|
* connection's own and stay. Used by a failed CloudFormation update to undo an in-place update.
|
|
*/
|
|
public synchronized Connection restoreConnection(Connection previous, String region) {
|
|
String key = connectionKey(region, previous.getName());
|
|
Connection connection = connectionStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Connection " + previous.getName() + " does not exist.", 400));
|
|
connection.setDescription(previous.getDescription());
|
|
connection.setAuthorizationType(previous.getAuthorizationType());
|
|
connection.setAuthParameters(previous.getAuthParameters());
|
|
connection.setInvocationConnectivityParameters(previous.getInvocationConnectivityParameters());
|
|
connection.setKmsKeyIdentifier(previous.getKmsKeyIdentifier());
|
|
connection.setConnectionState(previous.getConnectionState());
|
|
connection.setStateReason(previous.getStateReason());
|
|
connection.setLastModifiedTime(previous.getLastModifiedTime());
|
|
connection.setLastAuthorizedTime(previous.getLastAuthorizedTime());
|
|
connectionStore.put(key, connection);
|
|
LOG.infov("Restored connection: {0}", previous.getName());
|
|
return connection;
|
|
}
|
|
|
|
public Connection deleteConnection(String name, String region) {
|
|
String key = connectionKey(region, name);
|
|
Connection connection = connectionStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Connection " + name + " does not exist.", 400));
|
|
connectionStore.delete(key);
|
|
LOG.infov("Deleted connection: {0}", name);
|
|
return connection;
|
|
}
|
|
|
|
public List<Connection> listConnections(String namePrefix, ConnectionState state, String region) {
|
|
String prefix = "connection:" + region + ":";
|
|
return connectionStore.scan(k -> {
|
|
if (!k.startsWith(prefix)) return false;
|
|
Connection c = connectionStore.get(k).orElse(null);
|
|
if (c == null) return false;
|
|
if (namePrefix != null && !namePrefix.isBlank()
|
|
&& !c.getName().startsWith(namePrefix)) {
|
|
return false;
|
|
}
|
|
if (state != null && state != c.getConnectionState()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
|
|
public PaginatedResult<Connection> listConnections(String namePrefix, ConnectionState state, Integer limit,
|
|
String nextToken, String region) {
|
|
String effectivePrefix = namePrefix == null || namePrefix.isBlank() ? "" : namePrefix;
|
|
String scope = "events:ListConnections:" + regionResolver.getAccountId() + ":" + region
|
|
+ ":" + effectivePrefix + ":" + (state == null ? "" : state.name());
|
|
return paginate(listConnections(namePrefix, state, region), Connection::getName, limit, nextToken, scope);
|
|
}
|
|
|
|
private static void validateConnectionName(String name) {
|
|
if (name == null || name.isBlank()) {
|
|
throw new AwsException("ValidationException", "Connection name is required.", 400);
|
|
}
|
|
if (name.length() > 64 || !CONNECTION_NAME_PATTERN.matcher(name).matches()) {
|
|
throw new AwsException("ValidationException",
|
|
"Connection name must match [\\.\\-_A-Za-z0-9]+ and be at most 64 characters.", 400);
|
|
}
|
|
}
|
|
|
|
private static void validateAuthorizationType(String authorizationType) {
|
|
if (authorizationType == null || authorizationType.isBlank()) {
|
|
throw new AwsException("ValidationException", "AuthorizationType is required.", 400);
|
|
}
|
|
switch (authorizationType) {
|
|
case "BASIC", "OAUTH_CLIENT_CREDENTIALS", "API_KEY" -> { }
|
|
default -> throw new AwsException("ValidationException",
|
|
"AuthorizationType must be one of BASIC, OAUTH_CLIENT_CREDENTIALS, API_KEY.", 400);
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Api Destinations ────────────────────────────
|
|
|
|
private static final Pattern API_DESTINATION_NAME_PATTERN =
|
|
Pattern.compile("[\\.\\-_A-Za-z0-9]+");
|
|
private static final Set<String> ALLOWED_HTTP_METHODS =
|
|
Set.of("GET", "HEAD", "POST", "OPTIONS", "PUT", "DELETE", "PATCH");
|
|
|
|
public synchronized ApiDestination createApiDestination(String name, String description, String connectionArn,
|
|
String invocationEndpoint, String httpMethod,
|
|
Integer invocationRateLimitPerSecond, String region) {
|
|
validateApiDestinationName(name);
|
|
if (connectionArn == null || connectionArn.isBlank()) {
|
|
throw new AwsException("ValidationException", "ConnectionArn is required.", 400);
|
|
}
|
|
findConnectionByArn(connectionArn, region);
|
|
if (invocationEndpoint == null || invocationEndpoint.isBlank()) {
|
|
throw new AwsException("ValidationException", "InvocationEndpoint is required.", 400);
|
|
}
|
|
validateInvocationEndpoint(invocationEndpoint);
|
|
validateHttpMethod(httpMethod);
|
|
if (invocationRateLimitPerSecond != null && invocationRateLimitPerSecond < 1) {
|
|
throw new AwsException("ValidationException",
|
|
"InvocationRateLimitPerSecond must be at least 1.", 400);
|
|
}
|
|
|
|
String key = apiDestinationKey(region, name);
|
|
if (apiDestinationStore.get(key).isPresent()) {
|
|
throw new AwsException("ResourceAlreadyExistsException",
|
|
"ApiDestination " + name + " already exists.", 400);
|
|
}
|
|
|
|
String destinationId = UUID.randomUUID().toString();
|
|
Instant now = Instant.now();
|
|
ApiDestination destination = new ApiDestination();
|
|
destination.setName(name);
|
|
destination.setArn(regionResolver.buildArn("events", region,
|
|
"api-destination/" + name + "/" + destinationId));
|
|
destination.setDescription(description);
|
|
destination.setConnectionArn(connectionArn);
|
|
destination.setInvocationEndpoint(invocationEndpoint);
|
|
destination.setHttpMethod(httpMethod);
|
|
destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
|
|
destination.setApiDestinationState(ApiDestinationState.ACTIVE);
|
|
destination.setCreationTime(now);
|
|
destination.setLastModifiedTime(now);
|
|
|
|
apiDestinationStore.put(key, destination);
|
|
LOG.infov("Created API Destination: {0} with endpoint {1}", name, invocationEndpoint);
|
|
return destination;
|
|
}
|
|
|
|
public ApiDestination describeApiDestination(String name, String region) {
|
|
return apiDestinationStore.get(apiDestinationKey(region, name))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"ApiDestination " + name + " does not exist.", 400));
|
|
}
|
|
|
|
public synchronized ApiDestination updateApiDestination(String name, String description, String connectionArn,
|
|
String invocationEndpoint, String httpMethod,
|
|
Integer invocationRateLimitPerSecond, String region) {
|
|
String key = apiDestinationKey(region, name);
|
|
ApiDestination destination = apiDestinationStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"ApiDestination " + name + " does not exist.", 400));
|
|
|
|
// Validate everything before assigning: the in-memory store returns the same instance, so a rejected update must not leave partial changes
|
|
if (connectionArn != null) {
|
|
findConnectionByArn(connectionArn, region);
|
|
}
|
|
if (invocationEndpoint != null) {
|
|
validateInvocationEndpoint(invocationEndpoint);
|
|
}
|
|
if (httpMethod != null) {
|
|
validateHttpMethod(httpMethod);
|
|
}
|
|
if (invocationRateLimitPerSecond != null && invocationRateLimitPerSecond < 1) {
|
|
throw new AwsException("ValidationException",
|
|
"InvocationRateLimitPerSecond must be at least 1.", 400);
|
|
}
|
|
|
|
if (connectionArn != null) {
|
|
destination.setConnectionArn(connectionArn);
|
|
}
|
|
if (description != null) {
|
|
destination.setDescription(description);
|
|
}
|
|
if (invocationEndpoint != null) {
|
|
destination.setInvocationEndpoint(invocationEndpoint);
|
|
}
|
|
if (httpMethod != null) {
|
|
destination.setHttpMethod(httpMethod);
|
|
}
|
|
if (invocationRateLimitPerSecond != null) {
|
|
destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
|
|
}
|
|
Instant now = Instant.now();
|
|
destination.setLastModifiedTime(now);
|
|
apiDestinationStore.put(key, destination);
|
|
LOG.infov("Updated API Destination: {0}", name);
|
|
return destination;
|
|
}
|
|
|
|
// Puts back a prior configuration verbatim, including unset fields that updateApiDestination cannot clear
|
|
public synchronized ApiDestination restoreApiDestination(String name, String description, String connectionArn,
|
|
String invocationEndpoint, String httpMethod,
|
|
Integer invocationRateLimitPerSecond, String region) {
|
|
String key = apiDestinationKey(region, name);
|
|
ApiDestination destination = apiDestinationStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"ApiDestination " + name + " does not exist.", 400));
|
|
destination.setDescription(description);
|
|
destination.setConnectionArn(connectionArn);
|
|
destination.setInvocationEndpoint(invocationEndpoint);
|
|
destination.setHttpMethod(httpMethod);
|
|
destination.setInvocationRateLimitPerSecond(invocationRateLimitPerSecond);
|
|
destination.setLastModifiedTime(Instant.now());
|
|
apiDestinationStore.put(key, destination);
|
|
LOG.infov("Restored API Destination: {0}", name);
|
|
return destination;
|
|
}
|
|
|
|
public synchronized ApiDestination deleteApiDestination(String name, String region) {
|
|
String key = apiDestinationKey(region, name);
|
|
ApiDestination destination = apiDestinationStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"ApiDestination " + name + " does not exist.", 400));
|
|
apiDestinationStore.delete(key);
|
|
LOG.infov("Deleted API Destination: {0}", name);
|
|
return destination;
|
|
}
|
|
|
|
public List<ApiDestination> listApiDestinations(String namePrefix, String connectionArn, String region) {
|
|
String prefix = "api-destination:" + region + ":";
|
|
List<ApiDestination> destinations = new ArrayList<>(apiDestinationStore.scan(k -> {
|
|
if (!k.startsWith(prefix)) {
|
|
return false;
|
|
}
|
|
ApiDestination dest = apiDestinationStore.get(k).orElse(null);
|
|
if (dest == null) {
|
|
return false;
|
|
}
|
|
if (namePrefix != null && !namePrefix.isBlank()
|
|
&& !dest.getName().startsWith(namePrefix)) {
|
|
return false;
|
|
}
|
|
if (connectionArn != null && !connectionArn.isBlank()
|
|
&& !connectionArn.equals(dest.getConnectionArn())) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}));
|
|
destinations.sort(Comparator.comparing(ApiDestination::getName));
|
|
return destinations;
|
|
}
|
|
|
|
public Connection findConnectionByArn(String connectionArn, String region) {
|
|
if (connectionArn == null || connectionArn.isBlank()) {
|
|
throw new AwsException("ResourceNotFoundException", "Connection ARN is required.", 400);
|
|
}
|
|
if (AwsArnUtils.isArn(connectionArn)) {
|
|
AwsArnUtils.Arn parsed = AwsArnUtils.parse(connectionArn);
|
|
String resource = parsed.resource();
|
|
if (resource.startsWith("connection/")) {
|
|
String remainder = resource.substring("connection/".length());
|
|
int slash = remainder.indexOf('/');
|
|
String name = slash > 0 ? remainder.substring(0, slash) : remainder;
|
|
String connRegion = parsed.region().isEmpty() ? region : parsed.region();
|
|
Optional<Connection> opt = connectionStore.get(connectionKey(connRegion, name));
|
|
// The ARN carries a generated id: one for a connection deleted and recreated under the same name must not match
|
|
if (opt.isPresent() && connectionArn.equals(opt.get().getConnectionArn())) {
|
|
return opt.get();
|
|
}
|
|
}
|
|
}
|
|
return connectionStore.scan(k -> {
|
|
Connection c = connectionStore.get(k).orElse(null);
|
|
return c != null && connectionArn.equals(c.getConnectionArn());
|
|
}).stream().findFirst().orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Connection " + connectionArn + " does not exist.", 400));
|
|
}
|
|
|
|
public ApiDestination findApiDestinationByArn(String arn, String region) {
|
|
if (arn == null || arn.isBlank()) {
|
|
return null;
|
|
}
|
|
if (AwsArnUtils.isArn(arn)) {
|
|
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
|
String resource = parsed.resource();
|
|
if (resource.startsWith("api-destination/")) {
|
|
String remainder = resource.substring("api-destination/".length());
|
|
int slash = remainder.indexOf('/');
|
|
String name = slash > 0 ? remainder.substring(0, slash) : remainder;
|
|
String destRegion = parsed.region().isEmpty() ? region : parsed.region();
|
|
Optional<ApiDestination> opt = apiDestinationStore.get(apiDestinationKey(destRegion, name));
|
|
// Same as connections: an ARN for a destination deleted and recreated under the same name is stale
|
|
if (opt.isPresent() && arn.equals(opt.get().getArn())) {
|
|
return opt.get();
|
|
}
|
|
}
|
|
}
|
|
return apiDestinationStore.scan(k -> {
|
|
ApiDestination d = apiDestinationStore.get(k).orElse(null);
|
|
return d != null && arn.equals(d.getArn());
|
|
}).stream().findFirst().orElse(null);
|
|
}
|
|
|
|
private static String apiDestinationKey(String region, String name) {
|
|
return "api-destination:" + region + ":" + name;
|
|
}
|
|
|
|
private static void validateApiDestinationName(String name) {
|
|
if (name == null || name.isBlank()) {
|
|
throw new AwsException("ValidationException", "Name is required.", 400);
|
|
}
|
|
if (name.length() > 64 || !API_DESTINATION_NAME_PATTERN.matcher(name).matches()) {
|
|
throw new AwsException("ValidationException",
|
|
"Name must match [\\.\\-_A-Za-z0-9]+ and be at most 64 characters.", 400);
|
|
}
|
|
}
|
|
|
|
private static void validateInvocationEndpoint(String invocationEndpoint) {
|
|
URI uri;
|
|
try {
|
|
uri = new URI(invocationEndpoint);
|
|
} catch (URISyntaxException e) {
|
|
throw new AwsException("ValidationException", "InvocationEndpoint is not a valid URL.", 400);
|
|
}
|
|
String scheme = uri.getScheme();
|
|
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
|
throw new AwsException("ValidationException",
|
|
"InvocationEndpoint must be an HTTP or HTTPS URL.", 400);
|
|
}
|
|
// getHost() is null for a missing host (https://:8080), and for a '*' in the host, which AWS only allows in the path
|
|
if (uri.getHost() == null) {
|
|
throw new AwsException("ValidationException",
|
|
"InvocationEndpoint must include a valid host, and a '*' wildcard is only allowed in the path.", 400);
|
|
}
|
|
}
|
|
|
|
private static void validateHttpMethod(String httpMethod) {
|
|
if (httpMethod == null || httpMethod.isBlank()) {
|
|
throw new AwsException("ValidationException", "HttpMethod is required.", 400);
|
|
}
|
|
if (!ALLOWED_HTTP_METHODS.contains(httpMethod)) {
|
|
throw new AwsException("ValidationException",
|
|
"HttpMethod must be one of GET, HEAD, POST, OPTIONS, PUT, DELETE, PATCH.", 400);
|
|
}
|
|
}
|
|
|
|
private void captureToArchives(Map<String, Object> entry, String busStoreKey,
|
|
String eventId, String region, String accountId) {
|
|
EventBus bus = getInAccount(busStore, accountId, busStoreKey).orElse(null);
|
|
if (bus == null) {
|
|
return;
|
|
}
|
|
String busArn = bus.getArn();
|
|
String archivePrefix = "archive:" + region + ":";
|
|
List<Archive> candidates = accountScan(archiveStore, accountId, k ->
|
|
k.startsWith(archivePrefix)
|
|
&& getInAccount(archiveStore, accountId, k).map(a ->
|
|
a.getState() == ArchiveState.ENABLED
|
|
&& busArn.equals(a.getEventSourceArn())).orElse(false));
|
|
|
|
for (Archive archive : candidates) {
|
|
if (matchesPattern(entry, archive.getEventPattern())) {
|
|
String evKey = archivedEventKey(region, archive.getArchiveName());
|
|
List<ArchivedEvent> stored = new ArrayList<>(
|
|
getInAccount(archivedEventStore, accountId, evKey).orElse(new ArrayList<>()));
|
|
ArchivedEvent ae = new ArchivedEvent(
|
|
eventId,
|
|
Instant.now(),
|
|
(String) entry.get("Source"),
|
|
(String) entry.get("DetailType"),
|
|
(String) entry.get("Detail"),
|
|
busArn
|
|
);
|
|
stored.add(ae);
|
|
putInAccount(archivedEventStore, accountId, evKey, stored);
|
|
archive.setEventCount(archive.getEventCount() + 1);
|
|
putInAccount(archiveStore, accountId, archiveKey(region, archive.getArchiveName()), archive);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────── Replays ────────────────────────────
|
|
|
|
public Replay startReplay(String replayName, String description, String eventSourceArn,
|
|
Instant eventStartTime, Instant eventEndTime,
|
|
String destinationArn, String region) {
|
|
if (replayName == null || replayName.isBlank()) {
|
|
throw new AwsException("ValidationException", "ReplayName is required.", 400);
|
|
}
|
|
String key = replayKey(region, replayName);
|
|
if (replayStore.get(key).isPresent()) {
|
|
throw new AwsException("ResourceAlreadyExistsException",
|
|
"Replay already exists: " + replayName, 400);
|
|
}
|
|
|
|
// resolve archive
|
|
String archiveName = archiveNameFromArn(eventSourceArn);
|
|
Archive archive = archiveStore.get(archiveKey(region, archiveName))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Archive not found: " + archiveName, 400));
|
|
|
|
List<ArchivedEvent> events = archivedEventStore
|
|
.get(archivedEventKey(region, archiveName))
|
|
.orElse(List.of());
|
|
|
|
String capturedAccountId = regionResolver.getAccountId();
|
|
|
|
Replay replay = new Replay();
|
|
replay.setReplayName(replayName);
|
|
replay.setReplayArn(regionResolver.buildArn("events", region, "replay/" + replayName));
|
|
replay.setDescription(description);
|
|
replay.setEventSourceArn(eventSourceArn);
|
|
replay.setDestinationArn(destinationArn);
|
|
replay.setEventStartTime(eventStartTime);
|
|
replay.setEventEndTime(eventEndTime);
|
|
replay.setState(ReplayState.STARTING);
|
|
replay.setReplayStartTime(Instant.now());
|
|
replay.setAccountId(capturedAccountId);
|
|
replayStore.put(key, replay);
|
|
|
|
replayDispatcher.dispatch(
|
|
replay,
|
|
events,
|
|
entries -> putEvents(entries, region, capturedAccountId),
|
|
(name, state) -> updateReplayStateForAccount(capturedAccountId, name, state, region),
|
|
time -> updateReplayLastReplayedForAccount(capturedAccountId, replayName, time, region)
|
|
);
|
|
|
|
LOG.infov("Started replay: {0} from archive {1}", replayName, archiveName);
|
|
return replay;
|
|
}
|
|
|
|
public Replay describeReplay(String replayName, String region) {
|
|
return replayStore.get(replayKey(region, replayName))
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Replay not found: " + replayName, 400));
|
|
}
|
|
|
|
public Replay cancelReplay(String replayName, String region) {
|
|
String key = replayKey(region, replayName);
|
|
Replay replay = replayStore.get(key)
|
|
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
|
"Replay not found: " + replayName, 400));
|
|
if (replay.getState() != ReplayState.RUNNING && replay.getState() != ReplayState.STARTING) {
|
|
throw new AwsException("IllegalStatusException",
|
|
"Replay is not in a cancellable state: " + replay.getState(), 400);
|
|
}
|
|
boolean signalled = replayDispatcher.requestCancel(replay.getReplayArn());
|
|
if (!signalled) {
|
|
// already completed between check and cancel
|
|
replay = replayStore.get(key).orElse(replay);
|
|
} else {
|
|
replay.setState(ReplayState.CANCELLING);
|
|
replay.setStateReason("Cancellation requested.");
|
|
replayStore.put(key, replay);
|
|
}
|
|
return replay;
|
|
}
|
|
|
|
public List<Replay> listReplays(String namePrefix, String eventSourceArn,
|
|
ReplayState state, String region) {
|
|
String prefix = "replay:" + region + ":";
|
|
return replayStore.scan(k -> {
|
|
if (!k.startsWith(prefix)) return false;
|
|
Replay r = replayStore.get(k).orElse(null);
|
|
if (r == null) return false;
|
|
if (namePrefix != null && !namePrefix.isBlank()
|
|
&& !r.getReplayName().startsWith(namePrefix)) {
|
|
return false;
|
|
}
|
|
if (eventSourceArn != null && !eventSourceArn.isBlank()
|
|
&& !eventSourceArn.equals(r.getEventSourceArn())) {
|
|
return false;
|
|
}
|
|
if (state != null && state != r.getState()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
|
|
void updateReplayState(String replayName, ReplayState state, String region) {
|
|
updateReplayStateForAccount(null, replayName, state, region);
|
|
}
|
|
|
|
private void updateReplayStateForAccount(String accountId, String replayName,
|
|
ReplayState state, String region) {
|
|
String key = replayKey(region, replayName);
|
|
getInAccount(replayStore, accountId, key).ifPresent(r -> {
|
|
r.setState(state);
|
|
if (state == ReplayState.COMPLETED || state == ReplayState.CANCELLED
|
|
|| state == ReplayState.FAILED) {
|
|
r.setReplayEndTime(Instant.now());
|
|
}
|
|
putInAccount(replayStore, accountId, key, r);
|
|
LOG.debugv("Replay {0} transitioned to {1}", replayName, state);
|
|
});
|
|
}
|
|
|
|
void updateReplayLastReplayed(String replayName, Instant eventTime, String region) {
|
|
updateReplayLastReplayedForAccount(null, replayName, eventTime, region);
|
|
}
|
|
|
|
private void updateReplayLastReplayedForAccount(String accountId, String replayName,
|
|
Instant eventTime, String region) {
|
|
String key = replayKey(region, replayName);
|
|
getInAccount(replayStore, accountId, key).ifPresent(r -> {
|
|
r.setEventLastReplayedTime(eventTime);
|
|
putInAccount(replayStore, accountId, key, r);
|
|
});
|
|
}
|
|
|
|
// ──────────────────────────── Storage key helpers ────────────────────────────
|
|
|
|
private static String archiveKey(String region, String archiveName) {
|
|
return "archive:" + region + ":" + archiveName;
|
|
}
|
|
|
|
private static String archivedEventKey(String region, String archiveName) {
|
|
return "archivedEvents:" + region + ":" + archiveName;
|
|
}
|
|
|
|
private static String replayKey(String region, String replayName) {
|
|
return "replay:" + region + ":" + replayName;
|
|
}
|
|
|
|
private static String connectionKey(String region, String connectionName) {
|
|
return "connection:" + region + ":" + connectionName;
|
|
}
|
|
|
|
private static String archiveNameFromArn(String arn) {
|
|
if (arn == null) {
|
|
return null;
|
|
}
|
|
return AwsArnUtils.resourceIfArnFor(arn, "events")
|
|
.filter(resource -> resource.startsWith("archive/"))
|
|
.map(resource -> resource.substring("archive/".length()))
|
|
.orElse(arn);
|
|
}
|
|
|
|
private void startSchedulerIfNeeded(Rule rule) {
|
|
if (ruleScheduler != null
|
|
&& rule.getState() == RuleState.ENABLED
|
|
&& rule.getScheduleExpression() != null
|
|
&& !rule.getScheduleExpression().isBlank()) {
|
|
String region = rule.getRegion() != null ? rule.getRegion() : regionResolver.getDefaultRegion();
|
|
String key = ruleKey(region, rule.getEventBusName(), rule.getName());
|
|
String accountId = rule.getAccountId();
|
|
ruleScheduler.startScheduler(
|
|
rule.getArn(),
|
|
rule.getScheduleExpression(),
|
|
() -> {
|
|
Rule r = getInAccount(ruleStore, accountId, key).orElse(null);
|
|
List<Target> t = getInAccount(targetStore, accountId, key).orElse(List.of());
|
|
return new RuleScheduler.ScheduleData(r, t);
|
|
}
|
|
);
|
|
}
|
|
}
|
|
|
|
private <V> List<V> accountScan(StorageBackend<String, V> store, String accountId,
|
|
Predicate<String> filter) {
|
|
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
|
|
return aware.scanForAccount(accountId, filter);
|
|
}
|
|
return store.scan(filter);
|
|
}
|
|
|
|
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
|
|
|
@Override
|
|
public List<ExplorerResource> getResources() {
|
|
List<ExplorerResource> resources = new ArrayList<>();
|
|
for (EventBus bus : busStore.scan(k -> true)) {
|
|
addExplorerResource(resources, bus.getArn(), "events:event-bus",
|
|
bus.getCreatedTime(), bus.getTags());
|
|
}
|
|
for (Rule rule : ruleStore.scan(k -> true)) {
|
|
addExplorerResource(resources, rule.getArn(), "events:rule",
|
|
rule.getCreatedAt(), rule.getTags());
|
|
}
|
|
return resources;
|
|
}
|
|
|
|
@Override
|
|
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
|
return Set.of(
|
|
new SupportedResourceType("events:event-bus", "events", true),
|
|
new SupportedResourceType("events:rule", "events", true));
|
|
}
|
|
|
|
private static void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
|
|
Instant createdAt, Map<String, String> tags) {
|
|
if (arn == null) {
|
|
return;
|
|
}
|
|
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
|
out.add(new ExplorerResource(arn, resourceType, "events",
|
|
parsed.region(), parsed.accountId(),
|
|
createdAt != null ? createdAt : Instant.now(),
|
|
tags != null ? tags : Map.of()));
|
|
}
|
|
}
|