mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(redshift-data): answer a statement only in the Region it ran in (#9487)
ListStatements scanned every Region's statements, and DescribeStatement, GetStatementResult, GetStatementResultV2 and CancelStatement read a statement by its bare id from any Region. The statement store now reads and lists only the request's Region, placing a statement by the Region it records and a batch's sub-statement by its batch's; a statement saved without a Region belongs to the default Region. Keys are unchanged, so the restart pass and the TTL sweep still see every Region.
This commit is contained in:
1 parent
df8989cf5b
commit
84258c11fb
5 files changed
+157
-6
No files matched your search
@@ -1161,7 +1161,6 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
|
||||
List<RedshiftDataStatementStore.StoredStatement> all = store.values().stream()
|
||||
.filter(s -> s.id.indexOf(':') < 0)
|
||||
.filter(s -> nameFilter == null || nameFilter.equals(s.statementName))
|
||||
.filter(s -> statusFilter == null || statusFilter.equalsIgnoreCase(s.status.name()))
|
||||
.sorted(Comparator.comparing((RedshiftDataStatementStore.StoredStatement s) -> s.createdAt).reversed())
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
@@ -43,24 +44,32 @@ class RedshiftDataStatementStore {
|
||||
private final Duration ttl;
|
||||
private final Clock clock;
|
||||
private final RedshiftDataIdempotencyStore idempotency;
|
||||
private final RegionResolver regions;
|
||||
// Created by the CDI lifecycle in start(); the test constructor never starts it, so unit
|
||||
// tests that build the store directly drive sweep() by hand and spawn no background thread.
|
||||
private ScheduledExecutorService sweeper;
|
||||
|
||||
@Inject
|
||||
RedshiftDataStatementStore(StorageFactory storageFactory, EmulatorConfig config, RedshiftDataIdempotencyStore idempotency) {
|
||||
RedshiftDataStatementStore(StorageFactory storageFactory, EmulatorConfig config, RedshiftDataIdempotencyStore idempotency,
|
||||
RegionResolver regions) {
|
||||
this.statements = storageFactory.create("redshift-data", "statements.json",
|
||||
new TypeReference<Map<String, StoredStatement>>() {});
|
||||
this.ttl = Duration.ofHours(Math.max(1, config.services().redshiftData().resultTtlHours()));
|
||||
this.clock = Clock.systemUTC();
|
||||
this.idempotency = idempotency;
|
||||
this.regions = regions;
|
||||
}
|
||||
|
||||
RedshiftDataStatementStore(int resultTtlHours, Clock clock) {
|
||||
this(resultTtlHours, clock, new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default
|
||||
}
|
||||
|
||||
RedshiftDataStatementStore(int resultTtlHours, Clock clock, RegionResolver regions) {
|
||||
this.statements = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
this.ttl = Duration.ofHours(Math.max(1, resultTtlHours));
|
||||
this.clock = clock;
|
||||
this.idempotency = null;
|
||||
this.regions = regions;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -114,22 +123,44 @@ class RedshiftDataStatementStore {
|
||||
return createdAt.plus(ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement {@code id} names in the request's account and Region, or null when it ran in another Region. A batch's
|
||||
* sub-statement ({@code <batch id>:<n>}) belongs to its batch's Region.
|
||||
*/
|
||||
StoredStatement get(String id) {
|
||||
return statements.get(id).map(StoredStatement::snapshot).orElse(null);
|
||||
StoredStatement stored = statements.get(id).map(StoredStatement::snapshot).orElse(null);
|
||||
if (stored == null) {
|
||||
return null;
|
||||
}
|
||||
int childSuffix = id.indexOf(':');
|
||||
StoredStatement owner = childSuffix < 0 ? stored : statements.get(id.substring(0, childSuffix)).orElse(null);
|
||||
return owner != null && inRequestRegion(owner) ? stored : null;
|
||||
}
|
||||
|
||||
StoredStatement getForAccount(String accountId, String id) {
|
||||
return statements.getForAccount(accountId, id).map(StoredStatement::snapshot).orElse(null);
|
||||
}
|
||||
|
||||
/** The request's account's statements that ran in the request's Region, batches' sub-statements left out. */
|
||||
List<StoredStatement> values() {
|
||||
return statements.scan(k -> true).stream().map(StoredStatement::summary).toList();
|
||||
return statements.scan(k -> k.indexOf(':') < 0).stream()
|
||||
.filter(this::inRequestRegion)
|
||||
.map(StoredStatement::summary).toList();
|
||||
}
|
||||
|
||||
void clear() {
|
||||
statements.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Statement ids are random, so a statement keeps its key and is placed by the Region it records. One stored before
|
||||
* statements recorded a Region is the default Region's, as {@code RegionScopedStorage} reads a regionless key.
|
||||
*/
|
||||
private boolean inRequestRegion(StoredStatement statement) {
|
||||
String region = statement.region == null ? regions.getDefaultRegion() : statement.region;
|
||||
return region.equals(regions.getRegion());
|
||||
}
|
||||
|
||||
String accountId() {
|
||||
return statements.accountId();
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.PersistentStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
@@ -530,7 +531,7 @@ class RedshiftDataIdempotencyServiceTest {
|
||||
.thenReturn(new AccountAwareStorageBackend<>(delegate, null, "000000000000"));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().redshiftData().resultTtlHours()).thenReturn(24);
|
||||
return new RedshiftDataStatementStore(factory, config, receipts);
|
||||
return new RedshiftDataStatementStore(factory, config, receipts, new RegionResolver("us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package io.floci.aws.services.redshiftdata;
|
||||
|
||||
import io.floci.aws.services.redshift.spectrum.SpectrumSession;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A Redshift Data API statement is Regional: it is listed, described, read and cancelled only in the Region it was
|
||||
* run in. Another Region answers {@code ResourceNotFoundException}, as it does for an id that doesn't exist.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class RedshiftDataRegionScopingIntegrationTest {
|
||||
|
||||
private static final String HOME = "us-east-1";
|
||||
private static final String OTHER = "eu-west-1";
|
||||
|
||||
@Inject
|
||||
RedshiftDataService service;
|
||||
|
||||
@InjectMock
|
||||
RedshiftDataResourceResolver resolver;
|
||||
|
||||
@InjectMock
|
||||
RedshiftDataConnectionFactory connectionFactory;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws SQLException {
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:regional", "127.0.0.1", 5439, "dev", "admin", "x",
|
||||
new SpectrumSession("000000000000", "000000000000:regional", "dev", List.of(), false)));
|
||||
when(connectionFactory.open(any())).thenThrow(new SQLException("connection refused"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearStatements() {
|
||||
service.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementIsListedAndReachedOnlyInTheRegionItRanIn() {
|
||||
String id = call(HOME, "ExecuteStatement",
|
||||
"{\"ClusterIdentifier\":\"regional\",\"Database\":\"dev\",\"DbUser\":\"admin\",\"Sql\":\"select 1\",\"WaitTimeSeconds\":10}")
|
||||
.statusCode(200).extract().path("Id");
|
||||
String byId = "{\"Id\":\"" + id + "\"}";
|
||||
call(HOME, "DescribeStatement", byId).statusCode(200).body("Status", equalTo("FAILED"));
|
||||
|
||||
call(OTHER, "ListStatements", "{}").statusCode(200).body("Statements.Id", not(hasItem(id)));
|
||||
notFound(call(OTHER, "DescribeStatement", byId));
|
||||
notFound(call(OTHER, "GetStatementResult", byId));
|
||||
notFound(call(OTHER, "GetStatementResultV2", byId));
|
||||
notFound(call(OTHER, "CancelStatement", byId));
|
||||
|
||||
call(HOME, "ListStatements", "{}").statusCode(200).body("Statements.Id", hasItem(id));
|
||||
call(HOME, "DescribeStatement", byId).statusCode(200).body("Id", equalTo(id));
|
||||
call(HOME, "GetStatementResult", byId).statusCode(400).body("__type", equalTo("ValidationException"));
|
||||
call(HOME, "CancelStatement", byId).statusCode(400).body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse call(String region, String action, String body) {
|
||||
return given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "RedshiftData." + action)
|
||||
.header("Authorization",
|
||||
"AWS4-HMAC-SHA256 Credential=AKID/20260101/" + region + "/redshift-data/aws4_request")
|
||||
.body(body)
|
||||
.when().post("/").then();
|
||||
}
|
||||
|
||||
private static void notFound(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+27
-1
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -44,7 +45,8 @@ class RedshiftDataStatementStoreTest {
|
||||
doThrow(new UncheckedIOException(new IOException("receipt replacement failed")))
|
||||
.when(receipts).sweep();
|
||||
}
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(factory, config, receipts);
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(factory, config, receipts,
|
||||
new RegionResolver("us-east-1", "000000000000"));
|
||||
Instant now = Instant.now();
|
||||
store.putForAccount("111111111111", statement("same-id", now.minus(Duration.ofHours(48))));
|
||||
store.putForAccount("222222222222", statement("same-id", now.minus(Duration.ofHours(1))));
|
||||
@@ -109,6 +111,30 @@ class RedshiftDataStatementStoreTest {
|
||||
return s;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementIsReadAndListedOnlyInTheRegionItRanInAndALegacyOneInTheDefaultRegion() {
|
||||
RegionResolver regions = mock(RegionResolver.class);
|
||||
when(regions.getDefaultRegion()).thenReturn("us-east-1");
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC(), regions);
|
||||
RedshiftDataStatementStore.StoredStatement batch = statement("batch", Instant.now());
|
||||
batch.region = "eu-west-1";
|
||||
store.put(batch);
|
||||
store.put(statement("batch:1", Instant.now()));
|
||||
store.put(statement("legacy", Instant.now()));
|
||||
|
||||
when(regions.getRegion()).thenReturn("eu-west-1");
|
||||
assertNotNull(store.get("batch"));
|
||||
assertNotNull(store.get("batch:1"));
|
||||
assertNull(store.get("legacy"));
|
||||
assertEquals(List.of("batch"), store.values().stream().map(s -> s.id).toList());
|
||||
|
||||
when(regions.getRegion()).thenReturn("us-east-1");
|
||||
assertNull(store.get("batch"));
|
||||
assertNull(store.get("batch:1"));
|
||||
assertNotNull(store.get("legacy"));
|
||||
assertEquals(List.of("legacy"), store.values().stream().map(s -> s.id).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putThenGet() {
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
|
||||
|
||||
Reference in new issue
Block a user