fix(pipes): keep a pipe unchanged when its storage write fails (#9704)

This commit is contained in:
Daniël van Ziel authored and GitHub committed 2026-11-28 21:32:47 -04:00
1 parent d6adf625ff
commit 18efc30c73
2 files changed
+184 -41

No files matched your search

@@ -16,6 +16,7 @@ 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.core.storage.StorageJson;
import io.floci.aws.services.pipes.model.DesiredState;
import io.floci.aws.services.pipes.model.Pipe;
import io.floci.aws.services.pipes.model.PipeState;
@@ -179,7 +180,7 @@ public class PipesService implements TagHandler, ResourceProvider {
* <p>Validation runs on the same retrieved pipe the write then mutates, so a pipe replaced
* between two lookups cannot be validated as one pipe and updated as another.
*/
private Pipe writePipeConfiguration(String name, String target, String roleArn, String description,
private synchronized Pipe writePipeConfiguration(String name, String target, String roleArn, String description,
DesiredState desiredState, String enrichment,
JsonNode sourceParameters, JsonNode targetParameters,
JsonNode enrichmentParameters, String region,
@@ -196,32 +197,64 @@ public class PipesService implements TagHandler, ResourceProvider {
targetParameters != null ? targetParameters : pipe.getTargetParameters());
}
writeProperty(target, clearUnsetProperties, pipe::setTarget);
writeProperty(roleArn, clearUnsetProperties, pipe::setRoleArn);
writeProperty(description, clearUnsetProperties, pipe::setDescription);
writeProperty(enrichment, clearUnsetProperties, pipe::setEnrichment);
writeProperty(sourceParameters, clearUnsetProperties, pipe::setSourceParameters);
writeProperty(targetParameters, clearUnsetProperties, pipe::setTargetParameters);
writeProperty(enrichmentParameters, clearUnsetProperties, pipe::setEnrichmentParameters);
// A pipe always has a desired state: createPipe defaults it to RUNNING and currentState is
// read off it. A null therefore leaves both alone on either path, rather than clearing a
// state the poller and currentState would then contradict.
if (desiredState != null) {
pipe.setDesiredState(desiredState);
pipe.setCurrentState(desiredState == DesiredState.RUNNING ? PipeState.RUNNING : PipeState.STOPPED);
if (desiredState == DesiredState.RUNNING) {
poller.startPolling(pipe);
} else {
poller.stopPolling(pipe);
writeChange(key, pipe, () -> {
writeProperty(target, clearUnsetProperties, pipe::setTarget);
writeProperty(roleArn, clearUnsetProperties, pipe::setRoleArn);
writeProperty(description, clearUnsetProperties, pipe::setDescription);
writeProperty(enrichment, clearUnsetProperties, pipe::setEnrichment);
writeProperty(sourceParameters, clearUnsetProperties, pipe::setSourceParameters);
writeProperty(targetParameters, clearUnsetProperties, pipe::setTargetParameters);
writeProperty(enrichmentParameters, clearUnsetProperties, pipe::setEnrichmentParameters);
// A pipe always has a desired state: createPipe defaults it to RUNNING and currentState is
// read off it. A null therefore leaves both alone on either path, rather than clearing a
// state the poller and currentState would then contradict.
if (desiredState != null) {
applyDesiredState(pipe, desiredState);
}
pipe.setLastModifiedTime(Instant.now());
});
if (desiredState == DesiredState.RUNNING) {
poller.startPolling(pipe);
} else if (desiredState != null) {
poller.stopPolling(pipe);
}
pipe.setLastModifiedTime(Instant.now());
storage.put(key, pipe);
LOG.infov("Updated pipe: {0}", name);
return pipe;
}
private static void applyDesiredState(Pipe pipe, DesiredState desiredState) {
pipe.setDesiredState(desiredState);
pipe.setCurrentState(desiredState == DesiredState.RUNNING ? PipeState.RUNNING : PipeState.STOPPED);
pipe.setLastModifiedTime(Instant.now());
}
/**
* Applies {@code change} to the stored {@code pipe} and writes it. The backends hand out the stored
* instance, so a write that throws would leave the change visible to every later read while the
* journal never received it: the pipe is put back as it was before the failure propagates. Callers are
* synchronized, so no other change lands between the snapshot and the rollback.
*/
private void writeChange(String key, Pipe pipe, Runnable change) {
Pipe before = StorageJson.copy(pipe);
try {
change.run();
storage.put(key, pipe);
} catch (RuntimeException e) {
pipe.setTarget(before.getTarget());
pipe.setRoleArn(before.getRoleArn());
pipe.setDescription(before.getDescription());
pipe.setEnrichment(before.getEnrichment());
pipe.setSourceParameters(before.getSourceParameters());
pipe.setTargetParameters(before.getTargetParameters());
pipe.setEnrichmentParameters(before.getEnrichmentParameters());
pipe.setDesiredState(before.getDesiredState());
pipe.setCurrentState(before.getCurrentState());
pipe.setTags(before.getTags());
pipe.setLastModifiedTime(before.getLastModifiedTime());
throw e;
}
}
/** Applies one property under the unset meaning {@code clearUnsetProperties} selects. */
private static <T> void writeProperty(T value, boolean clearUnsetProperties, Consumer<T> setter) {
if (value != null || clearUnsetProperties) {
@@ -252,32 +285,26 @@ public class PipesService implements TagHandler, ResourceProvider {
.collect(Collectors.toList());
}
public Pipe startPipe(String name, String region) {
public synchronized Pipe startPipe(String name, String region) {
String key = region + "::" + name;
Pipe pipe = storage.get(key)
.orElseThrow(() -> new AwsException("NotFoundException",
"Pipe " + name + " does not exist.", 404));
pipe.setDesiredState(DesiredState.RUNNING);
pipe.setCurrentState(PipeState.RUNNING);
pipe.setLastModifiedTime(Instant.now());
storage.put(key, pipe);
writeChange(key, pipe, () -> applyDesiredState(pipe, DesiredState.RUNNING));
poller.startPolling(pipe);
LOG.infov("Started pipe: {0}", name);
return pipe;
}
public Pipe stopPipe(String name, String region) {
public synchronized Pipe stopPipe(String name, String region) {
String key = region + "::" + name;
Pipe pipe = storage.get(key)
.orElseThrow(() -> new AwsException("NotFoundException",
"Pipe " + name + " does not exist.", 404));
writeChange(key, pipe, () -> applyDesiredState(pipe, DesiredState.STOPPED));
poller.stopPolling(pipe);
pipe.setDesiredState(DesiredState.STOPPED);
pipe.setCurrentState(PipeState.STOPPED);
pipe.setLastModifiedTime(Instant.now());
storage.put(key, pipe);
LOG.infov("Stopped pipe: {0}", name);
return pipe;
}
@@ -319,22 +346,19 @@ public class PipesService implements TagHandler, ResourceProvider {
Pipe pipe = findByArn(arn, region);
Map<String, String> merged = new HashMap<>(pipe.getTags() != null ? pipe.getTags() : Map.of());
merged.putAll(tags);
pipe.setTags(merged);
String key = region + "::" + pipe.getName();
storage.put(key, pipe);
writeChange(region + "::" + pipe.getName(), pipe, () -> pipe.setTags(merged));
}
/** Gives the pipe a new map without {@code tagKeys}, one tag call at a time, as {@link #tagResource}. */
@Override
public synchronized void untagResource(String region, String arn, List<String> tagKeys) {
Pipe pipe = findByArn(arn, region);
if (pipe.getTags() != null && tagKeys != null) {
Map<String, String> remaining = new HashMap<>(pipe.getTags());
Map<String, String> remaining = new HashMap<>(pipe.getTags() != null ? pipe.getTags() : Map.of());
if (tagKeys != null) {
tagKeys.forEach(remaining::remove);
pipe.setTags(remaining);
}
String key = region + "::" + pipe.getName();
storage.put(key, pipe);
writeChange(region + "::" + pipe.getName(), pipe,
() -> pipe.setTags(pipe.getTags() != null ? remaining : null));
}
/**
@@ -21,10 +21,18 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
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.TimeoutException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
@@ -42,17 +50,19 @@ class PipesServiceTest {
private AccountAwareStorageBackend<Pipe> storage;
private PipesService pipesService;
private PipesPoller poller;
private Instant lastModifiedBefore;
@BeforeEach
void setUp() {
storage = AccountAwareStorageBackend.inMemory("000000000000");
storage = Mockito.spy(AccountAwareStorageBackend.<Pipe>inMemory("000000000000"));
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
Mockito.doReturn(storage).when(storageFactory)
.create(Mockito.anyString(), Mockito.anyString(), Mockito.any());
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
PipesPoller poller = Mockito.mock(PipesPoller.class);
poller = Mockito.mock(PipesPoller.class);
pipesService = new PipesService(storageFactory, regionResolver, poller);
}
@@ -949,6 +959,115 @@ class PipesServiceTest {
assertEquals("AUTOMATIC_BISECT", stored.path("OnPartialBatchItemFailure").asText());
}
private Pipe createPipeWithTag(DesiredState desiredState) {
Pipe pipe = pipesService.createPipe("sqs-pipe", SQS_SOURCE, STANDARD_TARGET, PIPE_ROLE,
"original", desiredState, null, null, null, null, Map.of("env", "dev"), "us-east-1");
Mockito.clearInvocations(poller);
lastModifiedBefore = pipe.getLastModifiedTime();
return pipe;
}
private void failNextWrite() {
Mockito.doThrow(new IllegalStateException("journal append failed"))
.when(storage).put(Mockito.anyString(), any());
}
private void assertPipeUnchanged(Pipe before, DesiredState desiredState, PipeState currentState) {
Pipe stored = pipesService.describePipe("sqs-pipe", "us-east-1");
assertEquals("original", stored.getDescription());
assertEquals(desiredState, stored.getDesiredState());
assertEquals(currentState, stored.getCurrentState());
assertEquals(Map.of("env", "dev"), stored.getTags());
assertEquals(lastModifiedBefore, stored.getLastModifiedTime());
Mockito.verifyNoInteractions(poller);
}
@Test
void failedWriteLeavesUpdatePipeUnapplied() {
Pipe before = createPipeWithTag(DesiredState.RUNNING);
failNextWrite();
assertThrows(IllegalStateException.class, () -> pipesService.updatePipe("sqs-pipe", null, null,
"changed", DesiredState.STOPPED, null, null, null, null, "us-east-1"));
assertPipeUnchanged(before, DesiredState.RUNNING, PipeState.RUNNING);
}
@Test
void failedWriteLeavesStopPipeUnapplied() {
Pipe before = createPipeWithTag(DesiredState.RUNNING);
failNextWrite();
assertThrows(IllegalStateException.class, () -> pipesService.stopPipe("sqs-pipe", "us-east-1"));
assertPipeUnchanged(before, DesiredState.RUNNING, PipeState.RUNNING);
}
@Test
void failedWriteLeavesStartPipeUnapplied() {
Pipe before = createPipeWithTag(DesiredState.STOPPED);
failNextWrite();
assertThrows(IllegalStateException.class, () -> pipesService.startPipe("sqs-pipe", "us-east-1"));
assertPipeUnchanged(before, DesiredState.STOPPED, PipeState.STOPPED);
}
@Test
void failedWriteLeavesTagChangesUnapplied() {
Pipe before = createPipeWithTag(DesiredState.STOPPED);
failNextWrite();
assertThrows(IllegalStateException.class,
() -> pipesService.tagResource("us-east-1", before.getArn(), Map.of("team", "a")));
assertThrows(IllegalStateException.class,
() -> pipesService.untagResource("us-east-1", before.getArn(), List.of("env")));
assertPipeUnchanged(before, DesiredState.STOPPED, PipeState.STOPPED);
}
@Test
void failedUpdateDoesNotRollBackATagCallThatRanAlongsideIt() throws Exception {
Pipe pipe = createPipeWithTag(DesiredState.STOPPED);
CountDownLatch writing = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Mockito.doAnswer(invocation -> {
writing.countDown();
release.await();
throw new IllegalStateException("journal append failed");
}).doCallRealMethod().when(storage).put(Mockito.anyString(), any());
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> update = executor.submit(() -> pipesService.updatePipe("sqs-pipe", null, null,
"changed", null, null, null, null, null, "us-east-1"));
assertTrue(writing.await(10, TimeUnit.SECONDS));
Future<?> tag = executor.submit(
() -> pipesService.tagResource("us-east-1", pipe.getArn(), Map.of("team", "a")));
assertThrows(TimeoutException.class, () -> tag.get(200, TimeUnit.MILLISECONDS));
release.countDown();
assertThrows(ExecutionException.class, () -> update.get(10, TimeUnit.SECONDS));
tag.get(10, TimeUnit.SECONDS);
} finally {
release.countDown();
executor.shutdownNow();
}
Pipe stored = pipesService.describePipe("sqs-pipe", "us-east-1");
assertEquals("original", stored.getDescription());
assertEquals(Map.of("env", "dev", "team", "a"), stored.getTags());
}
@Test
void stopPipeStopsThePollerOnceTheWriteSucceeded() {
Pipe pipe = createPipeWithTag(DesiredState.RUNNING);
pipesService.stopPipe("sqs-pipe", "us-east-1");
assertEquals(PipeState.STOPPED, pipesService.describePipe("sqs-pipe", "us-east-1").getCurrentState());
Mockito.verify(poller).stopPolling(pipe);
}
private static JsonNode sourceParameters(String json) {
try {
return MAPPER.readTree(json);