mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(elasticache): add serverless cache APIs (#5366)
* feat(elasticache): add serverless cache APIs Add CreateServerlessCache, DescribeServerlessCaches, ModifyServerlessCache and DeleteServerlessCache over the Query protocol. Each cache is backed by a hidden cluster that the ordinary cluster APIs do not list, with its own user-group authentication path in the proxy. * fix(elasticache): sua loi container rollback, validation tag, leak log stream va npipe hang - Thu hoi container va storage khi tao Memcached provisioning that bai - Format thong bao loi deleteCacheCluster chua cluster id - Validate tag key trong CreateServerlessCache khi co tag value - Chuan hoa case-insensitive cho userGroupId va region key cho nhom attachment - Giai phong dung logStream khi stop container trong ElastiCache va Memcached container manager - Tat validateAfterInactivity tren npipe trong FlociDockerHttpClient de tranh deadlock tren Windows * fix(elasticache): release serverless backing on reset and make delete and list tolerant - release backing clusters and user group attachments in clear() - let DeleteServerlessCache be retried after the backing cluster is already gone - keep DescribeServerlessCaches working when one cache has lost its backing - drop the unused replaceTags and document that tags are create-only * fix(core): drop the named-pipe stale-connection change, #5400 makes it
This commit is contained in:
1 parent
379086f818
commit
bac2c7cbf9
21 files changed
+1892
-85
No files matched your search
+1
@@ -64,6 +64,7 @@ class AwsQueryActionRoutingParityTest {
|
||||
new QueryHandler("iam", HANDLERS_ROOT + "iam/IamQueryHandler.java"),
|
||||
new QueryHandler("sns", HANDLERS_ROOT + "sns/SnsQueryHandler.java"),
|
||||
new QueryHandler("elasticache", HANDLERS_ROOT + "elasticache/ElastiCacheQueryHandler.java"),
|
||||
new QueryHandler("elasticache", HANDLERS_ROOT + "elasticache/ElastiCacheServerlessQueryHandler.java"),
|
||||
new QueryHandler("rds", HANDLERS_ROOT + "rds/RdsQueryHandler.java"),
|
||||
new QueryHandler("rds", HANDLERS_ROOT + "docdb/DocDbQueryHandler.java"),
|
||||
new QueryHandler("rds", HANDLERS_ROOT + "neptune/NeptuneQueryHandler.java"),
|
||||
|
||||
+27
-1
@@ -28,8 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -41,13 +43,14 @@ class ElastiCacheMemcachedServiceTest {
|
||||
private ElastiCacheMemcachedContainerManager containerManager;
|
||||
private ElastiCacheProvisioningIds provisioningIds;
|
||||
private AccountAwareStorageBackend<CacheSubnetGroup> subnetGroups;
|
||||
private EmulatorConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
containerManager = mock(ElastiCacheMemcachedContainerManager.class);
|
||||
provisioningIds = new ElastiCacheProvisioningIds();
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
config = mock(EmulatorConfig.class);
|
||||
|
||||
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElastiCacheServiceConfig ecConfig = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
|
||||
@@ -394,4 +397,27 @@ class ElastiCacheMemcachedServiceTest {
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
region, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUnknownClusterIncludesClusterIdInErrorMessage() {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.deleteCacheCluster("missing-cluster"));
|
||||
assertEquals("CacheClusterNotFound", ex.getErrorCode());
|
||||
assertEquals("Cache cluster missing-cluster not found.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisioningFailureRollsBackContainerAndStorage() {
|
||||
StorageFactory failingStorageFactory = mock(StorageFactory.class);
|
||||
AccountAwareStorageBackend<CacheCluster> store = spy(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
doThrow(new RuntimeException("Storage failure")).when(store).put(anyString(), any());
|
||||
when(failingStorageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> store);
|
||||
|
||||
ElastiCacheMemcachedService failingService = new ElastiCacheMemcachedService(
|
||||
containerManager, failingStorageFactory, config, provisioningIds, REGION_RESOLVER);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> failingService.createCacheCluster(request("fail-cluster")));
|
||||
|
||||
verify(containerManager).stop(any(ElastiCacheContainerHandle.class));
|
||||
assertTrue(store.get("fail-cluster").isEmpty());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -47,7 +47,8 @@ class ElastiCacheQueryHandlerTest {
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
handler = new ElastiCacheQueryHandler(sigV4Validator, service, memcachedService, regionResolver);
|
||||
handler = new ElastiCacheQueryHandler(sigV4Validator, service, memcachedService, regionResolver,
|
||||
mock(ElastiCacheServerlessQueryHandler.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
|
||||
import software.amazon.awssdk.services.elasticache.model.ServerlessCache;
|
||||
import software.amazon.awssdk.services.elasticache.model.ServerlessCacheNotFoundException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(ServerlessTestProfile.class)
|
||||
class ElastiCacheServerlessIntegrationTest {
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
@Inject
|
||||
Ec2Service ec2;
|
||||
|
||||
private ElastiCacheClient client() {
|
||||
return ElastiCacheClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkCrudRoundtripsMetadataAndKeepsTheSameEndpoint() {
|
||||
String region = "us-east-1";
|
||||
String vpc = ec2.createVpc(region, "10.65.0.0/16", false).getVpcId();
|
||||
String subnet = ec2.createSubnet(region, vpc, "10.65.1.0/24", region + "a").getSubnetId();
|
||||
String securityGroup = ec2.createSecurityGroup(region, "serverless-first", "first", vpc).getGroupId();
|
||||
String updatedGroup = ec2.createSecurityGroup(region, "serverless-second", "second", vpc).getGroupId();
|
||||
try (ElastiCacheClient client = client()) {
|
||||
ServerlessCache created = client.createServerlessCache(request -> request.serverlessCacheName("sdk-serverless")
|
||||
.engine("valkey").description("first").securityGroupIds(securityGroup).subnetIds(subnet)
|
||||
.snapshotRetentionLimit(3).dailySnapshotTime("03:00")
|
||||
.cacheUsageLimits(limits -> limits.dataStorage(storage -> storage.maximum(5).unit("GB"))
|
||||
.ecpuPerSecond(ecpu -> ecpu.maximum(1000)))
|
||||
.tags(tag -> tag.key("team").value("test"))).serverlessCache();
|
||||
assertEquals("available", created.status());
|
||||
assertEquals("valkey", created.engine());
|
||||
assertNotNull(created.createTime());
|
||||
assertNotNull(created.endpoint());
|
||||
assertEquals(created.endpoint(), created.readerEndpoint());
|
||||
assertTrue(created.arn().endsWith(":serverlesscache:sdk-serverless"));
|
||||
assertEquals(List.of(securityGroup), created.securityGroupIds());
|
||||
assertEquals(List.of(subnet), created.subnetIds());
|
||||
assertEquals(5, created.cacheUsageLimits().dataStorage().maximum());
|
||||
assertEquals(3, created.snapshotRetentionLimit());
|
||||
assertEquals("03:00", created.dailySnapshotTime());
|
||||
assertEquals("test", client.listTagsForResource(request -> request.resourceName(created.arn()))
|
||||
.tagList().getFirst().value());
|
||||
ServerlessCache updated = client.modifyServerlessCache(request -> request.serverlessCacheName("sdk-serverless")
|
||||
.description("second").securityGroupIds(updatedGroup)).serverlessCache();
|
||||
assertEquals(created.endpoint(), updated.endpoint());
|
||||
assertEquals("second", updated.description());
|
||||
assertEquals(List.of(updatedGroup), updated.securityGroupIds());
|
||||
assertEquals("second", client.describeServerlessCaches(request -> request.serverlessCacheName("sdk-serverless"))
|
||||
.serverlessCaches().getFirst().description());
|
||||
assertTrue(client.describeCacheClusters().cacheClusters().stream()
|
||||
.noneMatch(cluster -> created.endpoint().equals(cluster.configurationEndpoint())));
|
||||
assertEquals("deleting", client.deleteServerlessCache(request -> request.serverlessCacheName("sdk-serverless"))
|
||||
.serverlessCache().status());
|
||||
assertThrows(ServerlessCacheNotFoundException.class,
|
||||
() -> client.describeServerlessCaches(request -> request.serverlessCacheName("sdk-serverless")));
|
||||
} finally {
|
||||
try (ElastiCacheClient client = client()) {
|
||||
try {
|
||||
client.deleteServerlessCache(request -> request.serverlessCacheName("sdk-serverless"));
|
||||
} catch (ServerlessCacheNotFoundException expected) {
|
||||
// Already deleted by the successful test path.
|
||||
}
|
||||
}
|
||||
ec2.deleteSecurityGroup(region, updatedGroup);
|
||||
ec2.deleteSecurityGroup(region, securityGroup);
|
||||
ec2.deleteSubnet(region, subnet);
|
||||
ec2.deleteVpc(region, vpc);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerValkeyPreservesDataAndAuthenticatesCurrentGroupMembers() throws Exception {
|
||||
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless data plane");
|
||||
try (ElastiCacheClient client = client()) {
|
||||
client.createUser(request -> request.userId("serverless-alice").userName("alice").engine("valkey")
|
||||
.accessString("on ~* +@all").passwords("alice-password-123"));
|
||||
client.createUser(request -> request.userId("serverless-bob").userName("bob").engine("valkey")
|
||||
.accessString("on ~* +@all").passwords("bob-password-123"));
|
||||
client.createUserGroup(request -> request.userGroupId("serverless-team").engine("valkey").userIds("serverless-alice"));
|
||||
try {
|
||||
ServerlessCache cache = client.createServerlessCache(request -> request.serverlessCacheName("serverless-data")
|
||||
.engine("valkey").userGroupId("serverless-team")).serverlessCache();
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "PING");
|
||||
assertTrue(line(socket).startsWith("-NOAUTH"));
|
||||
}
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "AUTH", "alice", "alice-password-123");
|
||||
assertEquals("+OK\r\n", line(socket));
|
||||
resp(socket, "SET", "serverless-key", "retained");
|
||||
assertEquals("+OK\r\n", line(socket));
|
||||
ServerlessCache updated = client.modifyServerlessCache(request -> request.serverlessCacheName("serverless-data")
|
||||
.description("changed while connected")).serverlessCache();
|
||||
assertEquals(cache.endpoint(), updated.endpoint());
|
||||
resp(socket, "GET", "serverless-key");
|
||||
assertEquals("$8\r\n", line(socket));
|
||||
assertEquals("retained\r\n", line(socket));
|
||||
}
|
||||
client.modifyUserGroup(request -> request.userGroupId("serverless-team")
|
||||
.userIdsToAdd("serverless-bob").userIdsToRemove("serverless-alice"));
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "AUTH", "alice", "alice-password-123");
|
||||
assertTrue(line(socket).startsWith("-ERR invalid username-password"));
|
||||
}
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "AUTH", "bob", "bob-password-123");
|
||||
assertEquals("+OK\r\n", line(socket));
|
||||
resp(socket, "GET", "serverless-key");
|
||||
assertEquals("$8\r\n", line(socket));
|
||||
assertEquals("retained\r\n", line(socket));
|
||||
}
|
||||
client.modifyUserGroup(request -> request.userGroupId("serverless-team").userIdsToRemove("serverless-bob"));
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "PING");
|
||||
assertTrue(line(socket).startsWith("-NOAUTH"));
|
||||
}
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "AUTH", "bob", "bob-password-123");
|
||||
assertTrue(line(socket).startsWith("-ERR invalid username-password"));
|
||||
}
|
||||
client.modifyServerlessCache(request -> request.serverlessCacheName("serverless-data").removeUserGroup(true));
|
||||
try (Socket socket = socket(cache)) {
|
||||
resp(socket, "PING");
|
||||
assertEquals("+PONG\r\n", line(socket));
|
||||
}
|
||||
} finally {
|
||||
deleteIfPresent(client, "serverless-data");
|
||||
client.deleteUserGroup(request -> request.userGroupId("serverless-team"));
|
||||
client.deleteUser(request -> request.userId("serverless-alice"));
|
||||
client.deleteUser(request -> request.userId("serverless-bob"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerMemcachedPreservesValuesAcrossMetadataChanges() throws Exception {
|
||||
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for the serverless Memcached data plane");
|
||||
try (ElastiCacheClient client = client()) {
|
||||
try {
|
||||
ServerlessCache cache = client.createServerlessCache(request -> request.serverlessCacheName("serverless-memcached")
|
||||
.engine("memcached")).serverlessCache();
|
||||
try (Socket socket = socket(cache)) {
|
||||
text(socket, "set serverless-key 0 60 8\r\nretained\r\n");
|
||||
assertEquals("STORED\r\n", line(socket));
|
||||
ServerlessCache updated = client.modifyServerlessCache(request -> request.serverlessCacheName("serverless-memcached")
|
||||
.description("same data")).serverlessCache();
|
||||
assertEquals(cache.endpoint(), updated.endpoint());
|
||||
text(socket, "get serverless-key\r\n");
|
||||
assertEquals("VALUE serverless-key 0 8\r\n", line(socket));
|
||||
assertEquals("retained\r\n", line(socket));
|
||||
assertEquals("END\r\n", line(socket));
|
||||
}
|
||||
assertTrue(client.describeCacheClusters().cacheClusters().stream()
|
||||
.noneMatch(cluster -> "memcached".equals(cluster.engine())));
|
||||
} finally {
|
||||
deleteIfPresent(client, "serverless-memcached");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteIfPresent(ElastiCacheClient client, String name) {
|
||||
try {
|
||||
client.deleteServerlessCache(request -> request.serverlessCacheName(name));
|
||||
} catch (ServerlessCacheNotFoundException expected) {
|
||||
// Creation failed before publication, or the successful test already deleted it.
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean dockerAvailable() throws IOException, InterruptedException {
|
||||
Process process;
|
||||
try {
|
||||
process = new ProcessBuilder("docker", "info").redirectOutput(ProcessBuilder.Redirect.DISCARD)
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
} catch (IOException expected) {
|
||||
// Docker CLI is optional on development machines.
|
||||
return false;
|
||||
}
|
||||
if (!process.waitFor(10, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
return false;
|
||||
}
|
||||
return process.exitValue() == 0;
|
||||
}
|
||||
|
||||
private static Socket socket(ServerlessCache cache) throws IOException {
|
||||
Socket socket = new Socket(cache.endpoint().address(), cache.endpoint().port());
|
||||
socket.setSoTimeout(10_000);
|
||||
return socket;
|
||||
}
|
||||
|
||||
private static void resp(Socket socket, String... values) throws IOException {
|
||||
StringBuilder request = new StringBuilder("*" + values.length + "\r\n");
|
||||
for (String value : values) {
|
||||
request.append('$').append(value.getBytes(StandardCharsets.UTF_8).length).append("\r\n")
|
||||
.append(value).append("\r\n");
|
||||
}
|
||||
text(socket, request.toString());
|
||||
}
|
||||
|
||||
private static void text(Socket socket, String value) throws IOException {
|
||||
socket.getOutputStream().write(value.getBytes(StandardCharsets.UTF_8));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
|
||||
private static String line(Socket socket) throws IOException {
|
||||
InputStream input = socket.getInputStream();
|
||||
StringBuilder result = new StringBuilder();
|
||||
int next;
|
||||
while ((next = input.read()) != -1) {
|
||||
result.append((char) next);
|
||||
if (result.length() >= 2 && result.charAt(result.length() - 2) == '\r'
|
||||
&& result.charAt(result.length() - 1) == '\n') {
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
throw new IOException("Connection closed before reply terminator");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createServerlessCacheWithTagValueMissingKeyReturnsInvalidParameterValue() {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20261010/us-east-1/elasticache/aws4_request")
|
||||
.formParam("Action", "CreateServerlessCache")
|
||||
.formParam("ServerlessCacheName", "tag-fail-cache")
|
||||
.formParam("Engine", "valkey")
|
||||
.formParam("Tags.Tag.1.Value", "malformed-value")
|
||||
.when()
|
||||
.post(endpoint)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("InvalidParameterValue"))
|
||||
.body(containsString("Tag key cannot be null or empty"));
|
||||
|
||||
try (ElastiCacheClient client = client()) {
|
||||
assertThrows(ServerlessCacheNotFoundException.class,
|
||||
() -> client.describeServerlessCaches(r -> r.serverlessCacheName("tag-fail-cache")));
|
||||
}
|
||||
}
|
||||
}
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ValkeyClusterFormation;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ServerlessCache;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheAuthProxy;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ElastiCacheServerlessServiceTest {
|
||||
private ElastiCacheServerlessService service;
|
||||
private ElastiCacheService runtime;
|
||||
private ElastiCacheMemcachedService memcached;
|
||||
private ElastiCacheContainerManager containers;
|
||||
private ElastiCacheProxyManager proxies;
|
||||
private StorageFactory factory;
|
||||
private EmulatorConfig config;
|
||||
private RegionResolver resolver;
|
||||
private Ec2Service ec2;
|
||||
private KmsService kms;
|
||||
private RequestContext context;
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
factory = mock(StorageFactory.class);
|
||||
context = new RequestContext();
|
||||
context.setAccountId("000000000000");
|
||||
context.setRegion("us-east-1");
|
||||
Instance<RequestContext> requestInstance = mock(Instance.class);
|
||||
when(requestInstance.get()).thenReturn(context);
|
||||
Map<String, AccountAwareStorageBackend<?>> stores = new ConcurrentHashMap<>();
|
||||
when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation -> stores.computeIfAbsent(
|
||||
invocation.getArgument(1), file -> new AccountAwareStorageBackend<>(new InMemoryStorage<>(), requestInstance, "000000000000")));
|
||||
config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElastiCacheServiceConfig settings = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.elasticache()).thenReturn(settings);
|
||||
when(settings.proxyBasePort()).thenReturn(17400);
|
||||
when(settings.proxyMaxPort()).thenReturn(17401);
|
||||
when(settings.defaultImage()).thenReturn("valkey/valkey:8");
|
||||
when(settings.defaultMemcachedImage()).thenReturn("memcached:1.6");
|
||||
when(config.hostname()).thenReturn(Optional.of("localhost"));
|
||||
resolver = spy(new RegionResolver("us-east-1", "000000000000"));
|
||||
doAnswer(invocation -> context.getAccountId()).when(resolver).getAccountId();
|
||||
doAnswer(invocation -> context.getRegion()).when(resolver).getRegion();
|
||||
containers = mock(ElastiCacheContainerManager.class);
|
||||
when(containers.tryStart(anyString(), anyString(), any())).thenReturn(
|
||||
new ElastiCacheContainerHandle("container", "backing", "localhost", 6379));
|
||||
proxies = mock(ElastiCacheProxyManager.class);
|
||||
ec2 = mock(Ec2Service.class);
|
||||
when(ec2.describeSubnets(anyString(), anyList(), anyMap())).thenAnswer(invocation -> {
|
||||
List<String> ids = invocation.getArgument(1);
|
||||
return ids.stream().filter(id -> id.equals("subnet-local")).map(id -> {
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId(id);
|
||||
subnet.setVpcId("vpc-local");
|
||||
return subnet;
|
||||
}).toList();
|
||||
});
|
||||
when(ec2.describeSecurityGroups(anyString(), anyList(), anyList(), anyMap())).thenAnswer(invocation -> {
|
||||
List<String> ids = invocation.getArgument(1);
|
||||
return ids.stream().filter(id -> id.equals("sg-local") || id.equals("sg-new")).map(id -> {
|
||||
SecurityGroup group = new SecurityGroup();
|
||||
group.setGroupId(id);
|
||||
group.setVpcId("vpc-local");
|
||||
return group;
|
||||
}).toList();
|
||||
});
|
||||
kms = mock(KmsService.class);
|
||||
when(kms.describeKey(anyString(), anyString())).thenThrow(new AwsException("NotFoundException", "Missing key", 400));
|
||||
runtime = new ElastiCacheService(containers, proxies, mock(ValkeyClusterFormation.class), factory,
|
||||
config, ec2, resolver, kms, new ElastiCacheProvisioningIds());
|
||||
memcached = new ElastiCacheMemcachedService(mock(ElastiCacheMemcachedContainerManager.class), factory,
|
||||
config, new ElastiCacheProvisioningIds(), resolver);
|
||||
service = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime);
|
||||
runtime.createUser("alice", "alice", AuthMode.PASSWORD, List.of("password-a"), "on ~* +@all", "valkey");
|
||||
runtime.createUser("bob", "bob", AuthMode.PASSWORD, List.of("password-b"), "on ~* +@all", "valkey");
|
||||
runtime.createUserGroup("team", "valkey", List.of("alice"), "us-east-1");
|
||||
}
|
||||
|
||||
private ElastiCacheServerlessService.CreateServerlessCacheRequest create(String name, String engine, String group) {
|
||||
return new ElastiCacheServerlessService.CreateServerlessCacheRequest(name, engine, null, "description",
|
||||
List.of("subnet-local"), List.of("sg-local"), group, null, null, 0, null, List.of(),
|
||||
Map.of("team", "local"));
|
||||
}
|
||||
|
||||
private ElastiCacheServerlessService.ModifyServerlessCacheRequest modify(String name, String group, Boolean remove) {
|
||||
return new ElastiCacheServerlessService.ModifyServerlessCacheRequest(name, "updated", null, null,
|
||||
List.of("sg-new"), group, remove, null, null, null);
|
||||
}
|
||||
|
||||
private void error(String code, Runnable action) {
|
||||
assertEquals(code, assertThrows(AwsException.class, action::run).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsHiddenRuntimeMutatesMetadataAndReleasesPortOnDelete() {
|
||||
ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
assertEquals("available", cache.getStatus());
|
||||
assertEquals(cache.getEndpoint(), cache.getReaderEndpoint());
|
||||
assertTrue(runtime.findCacheClusters(null).isEmpty());
|
||||
error("CacheClusterNotFound", () -> runtime.deleteCacheCluster(cache.getBackingCacheClusterId()));
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
ServerlessCache updated = service.modifyServerlessCache(modify("cache", null, null));
|
||||
assertEquals(cache.getEndpoint(), updated.getEndpoint());
|
||||
assertEquals(cache.getBackingCacheClusterId(), updated.getBackingCacheClusterId());
|
||||
assertEquals("updated", updated.getDescription());
|
||||
assertEquals(List.of("sg-new"), updated.getSecurityGroupIds());
|
||||
error("ServerlessCacheAlreadyExistsFault", () -> service.createServerlessCache(create("cache", "valkey", "team")));
|
||||
assertEquals(List.of("us-east-1/cache"), List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()));
|
||||
service.deleteServerlessCache("cache");
|
||||
assertTrue(service.describeServerlessCaches(null).isEmpty());
|
||||
runtime.deleteUserGroup("team");
|
||||
ServerlessCache replacement = service.createServerlessCache(create("replacement", "valkey", null));
|
||||
assertEquals(cache.getEndpoint().port(), replacement.getEndpoint().port());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteIsRetryableAfterBackingWasAlreadyRemoved() {
|
||||
ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
runtime.deleteServerlessBacking(cache.getBackingCacheClusterId());
|
||||
service.deleteServerlessCache("cache");
|
||||
error("ServerlessCacheNotFoundFault", () -> service.getServerlessCache("cache"));
|
||||
runtime.deleteUserGroup("team");
|
||||
}
|
||||
|
||||
@Test
|
||||
void listingSurvivesACacheWhoseBackingIsMissing() {
|
||||
ServerlessCache broken = service.createServerlessCache(create("broken", "valkey", null));
|
||||
service.createServerlessCache(create("healthy", "valkey", null));
|
||||
runtime.deleteServerlessBacking(broken.getBackingCacheClusterId());
|
||||
assertEquals(2, service.describeServerlessCaches(null).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetReleasesBackingClustersAndUserGroupAttachments() {
|
||||
ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
service.clear();
|
||||
assertTrue(service.describeServerlessCaches(null).isEmpty());
|
||||
error("CacheClusterNotFound", () -> runtime.deleteServerlessBacking(cache.getBackingCacheClusterId()));
|
||||
runtime.deleteUserGroup("team");
|
||||
}
|
||||
|
||||
@Test
|
||||
void credentialsReadLiveMembershipAndUpdatedUserGroup() {
|
||||
ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator = ArgumentCaptor.forClass(
|
||||
ElastiCacheAuthProxy.PasswordValidator.class);
|
||||
verify(proxies).startProxy(eq(cache.getBackingCacheClusterId()), any(), anyInt(), anyString(), anyInt(),
|
||||
validator.capture(), eq("cache"));
|
||||
assertTrue(validator.getValue().validatePassword("alice", "password-a"));
|
||||
assertFalse(validator.getValue().validatePassword("bob", "password-b"));
|
||||
runtime.modifyUserGroup("team", List.of("bob"), List.of("alice"), null);
|
||||
assertFalse(validator.getValue().validatePassword("alice", "password-a"));
|
||||
assertTrue(validator.getValue().validatePassword("bob", "password-b"));
|
||||
runtime.modifyUser("bob", AuthMode.PASSWORD, List.of("password-b-updated"), null, null, null);
|
||||
assertFalse(validator.getValue().validatePassword("bob", "password-b"));
|
||||
assertTrue(validator.getValue().validatePassword("bob", "password-b-updated"));
|
||||
runtime.createUserGroup("other", "valkey", List.of("alice"), "us-east-1");
|
||||
service.modifyServerlessCache(modify("cache", "other", false));
|
||||
assertTrue(validator.getValue().validatePassword("alice", "password-a"));
|
||||
assertFalse(validator.getValue().validatePassword("bob", "password-b"));
|
||||
assertTrue(List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()).isEmpty());
|
||||
service.modifyServerlessCache(modify("cache", null, true));
|
||||
assertFalse(validator.getValue().hasMembers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationAndFailedAllocationLeaveNoAssociationOrRecord() {
|
||||
error("UserGroupNotFound", () -> service.createServerlessCache(create("missing", "valkey", "absent")));
|
||||
error("InvalidParameterCombination", () -> service.createServerlessCache(create("memcached", "memcached", "team")));
|
||||
error("InvalidParameterValue", () -> service.createServerlessCache(create("bad_name", "valkey", null)));
|
||||
verifyNoInteractions(proxies);
|
||||
when(containers.tryStart(anyString(), anyString(), any())).thenThrow(new IllegalStateException("allocation failed"));
|
||||
assertThrows(IllegalStateException.class, () -> service.createServerlessCache(create("failed", "valkey", "team")));
|
||||
assertTrue(List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()).isEmpty());
|
||||
assertTrue(service.describeServerlessCaches(null).isEmpty());
|
||||
assertTrue(runtime.findCacheClusters(null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackingCleanupStillDetachesTheUserGroupAfterAFailedCreate() {
|
||||
IllegalStateException creationFailure = new IllegalStateException("record failed");
|
||||
doThrow(creationFailure).when(resolver).buildArn("elasticache", "us-east-1", "serverlesscache:failed");
|
||||
doThrow(new IllegalStateException("stop failed")).when(proxies).stopProxy(anyString());
|
||||
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class,
|
||||
() -> service.createServerlessCache(create("failed", "valkey", "team")));
|
||||
|
||||
assertSame(creationFailure, thrown);
|
||||
assertEquals(1, thrown.getSuppressed().length);
|
||||
assertTrue(runtime.getUserGroup("team").getServerlessCacheEngines().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedDeletionKeepsGroupProtectedUntilRetrySucceeds() {
|
||||
ServerlessCache cache = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
doThrow(new IllegalStateException("stop failed")).when(proxies).stopProxy(cache.getBackingCacheClusterId());
|
||||
assertThrows(IllegalStateException.class, () -> service.deleteServerlessCache("cache"));
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
doNothing().when(proxies).stopProxy(cache.getBackingCacheClusterId());
|
||||
service.deleteServerlessCache("cache");
|
||||
runtime.deleteUserGroup("team");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rehydratedServiceRetainsRuntimeIdentityAndAssociation() {
|
||||
ServerlessCache original = service.createServerlessCache(create("cache", "valkey", "team"));
|
||||
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, runtime, memcached, runtime);
|
||||
assertEquals(original.getBackingCacheClusterId(), reloaded.getServerlessCache("cache").getBackingCacheClusterId());
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
reloaded.deleteServerlessCache("cache");
|
||||
runtime.deleteUserGroup("team");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyAttachedGroupRemainsAuthRequiredAndCannotAuthenticate() {
|
||||
runtime.createUserGroup("empty", "valkey", List.of(), "us-east-1");
|
||||
ServerlessCache cache = service.createServerlessCache(create("empty-cache", "valkey", "empty"));
|
||||
ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator = ArgumentCaptor.forClass(
|
||||
ElastiCacheAuthProxy.PasswordValidator.class);
|
||||
verify(proxies).startProxy(eq(cache.getBackingCacheClusterId()), any(), anyInt(), anyString(), anyInt(),
|
||||
validator.capture(), eq("empty-cache"));
|
||||
assertTrue(validator.getValue().hasMembers());
|
||||
assertNull(validator.getValue().memberAuthMode("default"));
|
||||
assertFalse(validator.getValue().validatePassword(null, "password-a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentDuplicateCannotRemoveWinningAssociation() throws Exception {
|
||||
CountDownLatch allocating = new CountDownLatch(1);
|
||||
CountDownLatch complete = new CountDownLatch(1);
|
||||
when(containers.tryStart(anyString(), anyString(), any())).thenAnswer(invocation -> {
|
||||
allocating.countDown();
|
||||
assertTrue(complete.await(10, TimeUnit.SECONDS));
|
||||
return new ElastiCacheContainerHandle("container", "backing", "localhost", 6379);
|
||||
});
|
||||
CompletableFuture<ServerlessCache> first = CompletableFuture.supplyAsync(() ->
|
||||
service.createServerlessCache(create("race", "valkey", "team")));
|
||||
assertTrue(allocating.await(10, TimeUnit.SECONDS));
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
CompletableFuture<String> second = CompletableFuture.supplyAsync(() -> {
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> service.createServerlessCache(create("race", "valkey", "team")));
|
||||
return exception.getErrorCode();
|
||||
});
|
||||
complete.countDown();
|
||||
assertEquals("race", first.get(10, TimeUnit.SECONDS).getServerlessCacheName());
|
||||
assertEquals("ServerlessCacheAlreadyExistsFault", second.get(10, TimeUnit.SECONDS));
|
||||
assertEquals(List.of("us-east-1/race"), List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotsAndUnsupportedTransitionsFailWithoutMutation() {
|
||||
ElastiCacheServerlessService.CreateServerlessCacheRequest base = create("snapshot", "valkey", "team");
|
||||
error("InvalidParameterValue", () -> service.createServerlessCache(new ElastiCacheServerlessService.CreateServerlessCacheRequest(
|
||||
base.serverlessCacheName(), base.engine(), null, null, null, null, "team", null, null, null, null,
|
||||
List.of("arn:aws:elasticache:us-east-1:000000000000:serverlesscachesnapshot:test"), null)));
|
||||
assertTrue(List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()).isEmpty());
|
||||
service.createServerlessCache(base);
|
||||
error("InvalidParameterValue", () -> service.deleteServerlessCache("snapshot", "final-snapshot"));
|
||||
error("InvalidParameterValue", () -> service.modifyServerlessCache(new ElastiCacheServerlessService.ModifyServerlessCacheRequest(
|
||||
"snapshot", "must-not-change", "redis", null, null, null, null, null, null, null)));
|
||||
error("UserGroupNotFound", () -> service.modifyServerlessCache(modify("snapshot", "absent", false)));
|
||||
assertEquals("description", service.getServerlessCache("snapshot").getDescription());
|
||||
assertEquals("team", service.getServerlessCache("snapshot").getUserGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistentRestartRestoresHiddenRuntimeCredentialsAndPortOwnership() {
|
||||
StorageFactory persistent = persistentFactory();
|
||||
ElastiCacheService persistedRuntime = newRuntime(persistent);
|
||||
ElastiCacheServerlessService persisted = new ElastiCacheServerlessService(persistent, resolver, persistedRuntime, memcached, persistedRuntime);
|
||||
persistedRuntime.createUser("member", "member", AuthMode.PASSWORD, List.of("secret"), "on ~* +@all", "valkey");
|
||||
persistedRuntime.createUserGroup("persisted-team", "valkey", List.of("member"), "us-east-1");
|
||||
ServerlessCache original = persisted.createServerlessCache(create("persistent", "valkey", "persisted-team"));
|
||||
persistent.shutdownAll();
|
||||
StorageFactory reloadedFactory = persistentFactory();
|
||||
ElastiCacheService reloadedRuntime = newRuntime(reloadedFactory);
|
||||
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(reloadedFactory, resolver, reloadedRuntime, memcached, reloadedRuntime);
|
||||
reloadedFactory.loadAll();
|
||||
clearInvocations(proxies);
|
||||
reloadedRuntime.restorePersistedRuntime().join();
|
||||
ServerlessCache restored = reloaded.getServerlessCache("persistent");
|
||||
assertEquals(original.getBackingCacheClusterId(), restored.getBackingCacheClusterId());
|
||||
assertEquals(original.getEndpoint(), restored.getEndpoint());
|
||||
assertEquals("000000000000", restored.getAccountId());
|
||||
assertTrue(reloadedRuntime.findCacheClusters(null).isEmpty());
|
||||
ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator = ArgumentCaptor.forClass(
|
||||
ElastiCacheAuthProxy.PasswordValidator.class);
|
||||
verify(proxies).startProxy(eq(restored.getBackingCacheClusterId()), any(), anyInt(), anyString(), anyInt(),
|
||||
validator.capture(), eq("persistent"));
|
||||
assertTrue(validator.getValue().validatePassword("member", "secret"));
|
||||
assertEquals(List.of("us-east-1/persistent"), List.copyOf(reloadedRuntime.getUserGroup("persisted-team").getServerlessCacheEngines().keySet()));
|
||||
reloaded.deleteServerlessCache("persistent");
|
||||
reloadedRuntime.deleteUserGroup("persisted-team");
|
||||
ServerlessCache replacement = reloaded.createServerlessCache(create("reused", "valkey", null));
|
||||
assertEquals(original.getEndpoint().port(), replacement.getEndpoint().port());
|
||||
reloaded.deleteServerlessCache("reused");
|
||||
reloadedFactory.shutdownAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void credentialsAndRestoreUseRecordedOwnerOutsideRequestScope() {
|
||||
context.setAccountId("111111111111");
|
||||
context.setRegion("cn-north-1");
|
||||
runtime.createUser("alice", "alice", AuthMode.PASSWORD, List.of("owner-secret"), "on ~* +@all", "valkey");
|
||||
runtime.createUserGroup("team", "valkey", List.of("alice"), "us-east-1");
|
||||
ServerlessCache original = service.createServerlessCache(create("account-cache", "valkey", "team"));
|
||||
assertTrue(original.getArn().startsWith("arn:aws-cn:elasticache:cn-north-1:111111111111:"));
|
||||
context.setAccountId("000000000000");
|
||||
context.setRegion("us-east-1");
|
||||
assertTrue(service.describeServerlessCaches(null).isEmpty());
|
||||
ElastiCacheService reloadedRuntime = newRuntime(factory);
|
||||
clearInvocations(proxies);
|
||||
reloadedRuntime.restorePersistedRuntime().join();
|
||||
ArgumentCaptor<ElastiCacheAuthProxy.PasswordValidator> validator = ArgumentCaptor.forClass(
|
||||
ElastiCacheAuthProxy.PasswordValidator.class);
|
||||
verify(proxies).startProxy(eq(original.getBackingCacheClusterId()), any(), anyInt(), anyString(), anyInt(),
|
||||
validator.capture(), eq("account-cache"));
|
||||
assertTrue(validator.getValue().validatePassword("alice", "owner-secret"));
|
||||
assertFalse(validator.getValue().validatePassword("alice", "password-a"));
|
||||
AccountAwareStorageBackend<CacheCluster> backing = factory.create("elasticache", "elasticache-redis-clusters.json", null);
|
||||
assertTrue(backing.getForAccount("000000000000", original.getBackingCacheClusterId()).isEmpty());
|
||||
assertTrue(backing.getForAccount("111111111111", original.getBackingCacheClusterId()).isPresent());
|
||||
context.setAccountId("111111111111");
|
||||
context.setRegion("cn-north-1");
|
||||
ElastiCacheServerlessService reloaded = new ElastiCacheServerlessService(factory, resolver, reloadedRuntime, memcached, reloadedRuntime);
|
||||
assertEquals(original.getEndpoint(), reloaded.getServerlessCache("account-cache").getEndpoint());
|
||||
reloaded.deleteServerlessCache("account-cache");
|
||||
runtime.deleteUserGroup("team");
|
||||
}
|
||||
|
||||
private ElastiCacheService newRuntime(StorageFactory activeFactory) {
|
||||
return new ElastiCacheService(containers, proxies, mock(ValkeyClusterFormation.class), activeFactory,
|
||||
config, ec2, resolver, kms, new ElastiCacheProvisioningIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingNetworkAndKmsDependenciesAreRejectedBeforeRuntimeAllocation() {
|
||||
for (ElastiCacheServerlessService.CreateServerlessCacheRequest request : List.of(
|
||||
new ElastiCacheServerlessService.CreateServerlessCacheRequest("missing-subnet", "valkey", null,
|
||||
null, List.of("subnet-absent"), null, "team", null, null, null, null, null, null),
|
||||
new ElastiCacheServerlessService.CreateServerlessCacheRequest("missing-sg", "valkey", null,
|
||||
null, null, List.of("sg-absent"), "team", null, null, null, null, null, null),
|
||||
new ElastiCacheServerlessService.CreateServerlessCacheRequest("missing-key", "valkey", null,
|
||||
null, null, null, "team", "missing", null, null, null, null, null))) {
|
||||
error("InvalidParameterValue", () -> service.createServerlessCache(request));
|
||||
}
|
||||
verifyNoInteractions(proxies);
|
||||
assertTrue(List.copyOf(runtime.getUserGroup("team").getServerlessCacheEngines().keySet()).isEmpty());
|
||||
assertTrue(service.describeServerlessCaches(null).isEmpty());
|
||||
}
|
||||
|
||||
private StorageFactory persistentFactory() {
|
||||
EmulatorConfig persistenceConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(persistenceConfig.defaultAccountId()).thenReturn("000000000000");
|
||||
when(persistenceConfig.storage().persistentPath()).thenReturn(directory.toString());
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn("persistent");
|
||||
when(access.storageFlushInterval(anyString())).thenReturn(60_000L);
|
||||
return new StorageFactory(persistenceConfig, access);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyingUserGroupWithDifferentCasePreservesAssociation() {
|
||||
service.createServerlessCache(create("case-cache", "valkey", "team"));
|
||||
service.modifyServerlessCache(modify("case-cache", "TEAM", null));
|
||||
ServerlessCache cache = service.getServerlessCache("case-cache");
|
||||
assertEquals("team", cache.getUserGroupId());
|
||||
|
||||
// Deleting the user group should still fail because it is in use by case-cache
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
|
||||
service.deleteServerlessCache("case-cache");
|
||||
assertNotNull(runtime.deleteUserGroup("team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNamedServerlessCachesInDifferentRegionsMaintainIndependentGroupTracking() {
|
||||
context.setRegion("us-east-1");
|
||||
service.createServerlessCache(create("multi-cache", "valkey", "team"));
|
||||
|
||||
context.setRegion("eu-west-1");
|
||||
service.createServerlessCache(create("multi-cache", "valkey", "team"));
|
||||
|
||||
// Delete cache in eu-west-1
|
||||
service.deleteServerlessCache("multi-cache");
|
||||
|
||||
// The user group should still be associated with the us-east-1 cache
|
||||
error("InvalidUserGroupState", () -> runtime.deleteUserGroup("team"));
|
||||
|
||||
context.setRegion("us-east-1");
|
||||
service.deleteServerlessCache("multi-cache");
|
||||
|
||||
assertNotNull(runtime.deleteUserGroup("team"));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class ServerlessTestProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.rds.mock", "true", "floci.services.docdb.mock", "true",
|
||||
"floci.docker.resource-namespace", "issue4650-serverless");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user