diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java index 78e1c3df3e..e5597cb571 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.appconfig; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; @@ -44,6 +45,7 @@ public class AppConfigService { private static final int MAX_DEPLOYMENT_PAGE_TOKENS = 1000; private static final int MAX_MONITORS = 5; private static final int MAX_ARN_LENGTH = 2048; + private static final ObjectMapper COPIER = new ObjectMapper(); private static final Pattern ROLE_ARN = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:role/.*"); @Inject @@ -84,7 +86,7 @@ public class AppConfigService { return applicationStore.scan(k -> true); } - public void deleteApplication(String idOrName) { + public synchronized void deleteApplication(String idOrName) { applicationStore.get(idOrName) .or(() -> listApplications().stream().filter(a -> idOrName.equals(a.getName())).findFirst()) .ifPresent(application -> applicationStore.delete(application.getId())); @@ -212,7 +214,7 @@ public class AppConfigService { .toList(); } - public void deleteConfigurationProfile(String applicationIdentifier, String profileIdentifier) { + public synchronized void deleteConfigurationProfile(String applicationIdentifier, String profileIdentifier) { String appId = resolveApplication(applicationIdentifier).getId(); // Unlike deleteApplication (a single, unscoped ID), a profile is nested under an // application - a mismatched appId must not be able to delete another application's @@ -343,7 +345,7 @@ public class AppConfigService { return result; } - public void deleteDeploymentStrategy(String id) { + public synchronized void deleteDeploymentStrategy(String id) { // Predefined strategies aren't real stored resources (see builtinStrategy above) - // silently no-op'ing here would report success for a delete that did nothing, and the // "deleted" strategy would still show up in every subsequent Get/List call. @@ -551,18 +553,29 @@ public class AppConfigService { return getApplication(appId).getTags(); } - public void tagApplication(String appId, Map tags) { - Application app = getApplication(appId); + public synchronized void tagApplication(String appId, Map tags) { + Application app = copy(getApplication(appId)); app.getTags().putAll(tags); applicationStore.put(app.getId(), app); } - public void untagApplication(String appId, List tagKeys) { - Application app = getApplication(appId); + public synchronized void untagApplication(String appId, List tagKeys) { + Application app = copy(getApplication(appId)); tagKeys.forEach(app.getTags()::remove); applicationStore.put(app.getId(), app); } + /** + * A copy of a stored entity for a write to change and put back. The in-memory stores hand out the + * stored instance itself, so changing it in place would change an entity a caller read earlier, + * such as one a GetApplication is still serializing, under that caller. The models are plain + * Jackson beans, as storage persists them, so a round trip copies every field. + */ + @SuppressWarnings("unchecked") + private static T copy(T entity) { + return (T) COPIER.convertValue(entity, entity.getClass()); + } + private static String shortId(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTaggingTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTaggingTest.java new file mode 100644 index 0000000000..cdb2756124 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTaggingTest.java @@ -0,0 +1,108 @@ +package io.github.hectorvent.floci.services.appconfig; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.core.storage.WriteProfile; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import io.github.hectorvent.floci.testing.ParkingStore; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * TagResource and UntagResource on an application read it, change its tags and write it back. They + * change a copy, so an application read before the write keeps its prior tags, and they hold the + * service lock, so a DeleteApplication arriving mid-write waits for it rather than finish first and + * have the write store the application again. + */ +class AppConfigServiceTaggingTest { + + private static final String ACCOUNT = "000000000000"; + private static final String APPLICATIONS = "appconfig-applications.json"; + + @Test + void anApplicationReadBeforeATagOrUntagKeepsItsPriorTags() { + AppConfigService service = new AppConfigService(new InMemoryStorageFactory(ACCOUNT), null); + Application created = service.createApplication(Map.of("Name", "orders")); + service.tagApplication(created.getId(), Map.of("team", "payments")); + Application beforeTag = service.getApplication(created.getId()); + + service.tagApplication(created.getId(), Map.of("tier", "gold")); + + assertEquals(Map.of("team", "payments"), beforeTag.getTags()); + Application beforeUntag = service.getApplication(created.getId()); + assertEquals(Map.of("team", "payments", "tier", "gold"), beforeUntag.getTags()); + + service.untagApplication(created.getId(), List.of("team")); + + assertEquals(Map.of("team", "payments", "tier", "gold"), beforeUntag.getTags()); + assertEquals(Map.of("tier", "gold"), service.getApplication(created.getId()).getTags()); + } + + /** + * The tag write is parked inside its write to the store, inside the section the service lock + * guards, and the delete must be seen waiting on it. + */ + @Test + void anApplicationDeletedDuringATagWriteStaysDeleted() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppConfigService service = serviceWithApplicationStore(store); + Application app = service.createApplication(Map.of("Name", "orders")); + + store.parkNextWrite(); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future tag = pool.submit(() -> service.tagApplication(app.getId(), Map.of("team", "payments"))); + assertTrue(store.awaitParked(), "the tag write must reach the store"); + AtomicReference deleteThread = new AtomicReference<>(); + Future delete = pool.submit(() -> { + deleteThread.set(Thread.currentThread()); + service.deleteApplication(app.getId()); + }); + awaitBlockedOrDone(deleteThread, delete); + assertFalse(delete.isDone(), "the delete ran while a tag write on the same application was mid-flight"); + assertEquals(Thread.State.BLOCKED, deleteThread.get().getState(), + "the delete waits on the service's monitor"); + + store.release(); + tag.get(2, TimeUnit.SECONDS); + delete.get(2, TimeUnit.SECONDS); + } catch (ExecutionException e) { + throw new AssertionError(e.getCause()); + } finally { + store.release(); + pool.shutdownNow(); + } + + assertTrue(service.listApplications().isEmpty(), "the application outlived its delete"); + } + + /** An AppConfig service whose application store is {@code store} and every other store in memory. */ + private static AppConfigService serviceWithApplicationStore(StorageBackend store) { + return new AppConfigService(new StorageFactory(null, null) { + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> typeReference, WriteProfile profile) { + return fileName.equals(APPLICATIONS) + ? new AccountAwareStorageBackend<>((StorageBackend) (Object) store, null, ACCOUNT) + : AccountAwareStorageBackend.inMemory(ACCOUNT); + } + }, null); + } +}