fix(codepipeline): poll S3 source changes (#3525)

* fix(codepipeline): poll S3 source changes

* fix(codepipeline): serialize source polling baselines
This commit is contained in:
Franklin G. Mendoza authored and GitHub committed 2026-09-14 10:11:15 -04:00
1 parent 5648be79c4
commit ffd2488f02
4 files changed
+525 -9

No files matched your search

+5
View File
@@ -25,6 +25,11 @@ Stages execute in declaration order. Actions with the same `runOrder` execute in
A `QUEUED` or `PARALLEL` pipeline holds at most 50 active executions, as on AWS;
`StartPipelineExecution` beyond that returns `ConcurrentPipelineExecutionsLimitExceededException`.
S3 source actions poll for source changes by default, matching AWS when `PollForSourceChanges` is
omitted or set to `true`. Floci establishes a baseline for the configured object and starts one new
execution when its version ID or ETag changes, recording `PollForSourceChanges` as the execution
trigger. Set `PollForSourceChanges` to `false` to disable this polling path.
The following providers execute against local Floci services:
| Category | Provider | Behavior |
@@ -46,6 +46,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
@@ -55,6 +56,9 @@ public class CodePipelineService {
private static final String DEFAULT_PIPELINE_TYPE = "V1";
private static final int MAX_ACTIVE_EXECUTIONS = 50;
private static final long POLL_INTERVAL_MS = 100L;
private static final long SOURCE_POLL_INTERVAL_MS = 500L;
private static final String SOURCE_POLL_TYPE = "source-poll";
private static final String MISSING_SOURCE_REVISION = "missing";
private final AccountAwareStorageBackend<CodePipelinePipeline> pipelineStore;
private final AccountAwareStorageBackend<CodePipelineExecution> executionStore;
@@ -65,7 +69,9 @@ public class CodePipelineService {
private final LambdaService lambdaService;
private final S3Service s3Service;
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
private final ScheduledExecutorService sourcePoller = Executors.newSingleThreadScheduledExecutor();
private final Map<String, Object> pipelineLocks = new ConcurrentHashMap<>();
private final Map<String, Object> sourcePollLocks = new ConcurrentHashMap<>();
// Admission is serialized per pipeline on its own lock. A QUEUED worker holds the pipelineLocks
// monitor for its whole run, so counting under that monitor would block StartPipelineExecution
// until the running execution finished.
@@ -162,6 +168,165 @@ public class CodePipelineService {
putExecution(execution);
});
}
initializePersistedSourcePollingBaselines();
sourcePoller.scheduleWithFixedDelay(
this::pollS3SourcesSafely, SOURCE_POLL_INTERVAL_MS, SOURCE_POLL_INTERVAL_MS, TimeUnit.MILLISECONDS);
}
private void initializePersistedSourcePollingBaselines() {
for (CodePipelinePipeline pipeline : pipelineStore.scanAllAccounts()) {
ensureSourcePollingBaselines(pipeline);
}
}
private void resetSourcePollingBaselines(CodePipelinePipeline pipeline) {
deleteSourcePollingBaselines(pipeline.getAccountId(), pipeline.getRegion(), pipeline.getName());
ensureSourcePollingBaselines(pipeline);
}
private void ensureSourcePollingBaselines(CodePipelinePipeline pipeline) {
forEachPolledS3Source(pipeline, (stageName, action) -> {
String cursorId = sourcePollCursorId(pipeline.getName(), stageName, action.path("name").asText());
String key = itemKey(pipeline.getRegion(), SOURCE_POLL_TYPE, cursorId);
if (itemStore.getForAccount(pipeline.getAccountId(), key).isPresent()) {
return;
}
String revision = observeS3SourceRevision(action);
storeSourcePollCursor(pipeline, cursorId, revision);
});
}
private void deleteSourcePollingBaselines(String account, String region, String pipelineName) {
String prefix = itemKey(region, SOURCE_POLL_TYPE, pipelineName + "::");
for (String key : itemStore.keysForAccount(account)) {
if (key.startsWith(prefix)) {
itemStore.deleteForAccount(account, key);
}
}
}
private void pollS3SourcesSafely() {
try {
for (CodePipelinePipeline pipeline : pipelineStore.scanAllAccounts()) {
pollS3Sources(pipeline);
}
} catch (RuntimeException e) {
LOG.warn("CodePipeline S3 source polling cycle failed", e);
}
}
private void pollS3Sources(CodePipelinePipeline pipeline) {
String pollLockKey = pipelineLockKey(
pipeline.getAccountId(), pipeline.getRegion(), pipeline.getName());
synchronized (sourcePollLocks.computeIfAbsent(pollLockKey, ignored -> new Object())) {
Optional<CodePipelinePipeline> currentPipeline = pipelineStore.getForAccount(
pipeline.getAccountId(), pipelineKey(pipeline.getRegion(), pipeline.getName()));
if (currentPipeline.isEmpty()) {
return;
}
pollS3SourcesLocked(currentPipeline.get());
}
}
private void pollS3SourcesLocked(CodePipelinePipeline pipeline) {
forEachPolledS3Source(pipeline, (stageName, action) -> {
String actionName = action.path("name").asText();
String cursorId = sourcePollCursorId(pipeline.getName(), stageName, actionName);
String key = itemKey(pipeline.getRegion(), SOURCE_POLL_TYPE, cursorId);
Optional<CodePipelineStoredItem> existing = itemStore.getForAccount(pipeline.getAccountId(), key);
if (existing.isEmpty()) {
storeSourcePollCursor(pipeline, cursorId, observeS3SourceRevision(action));
return;
}
String previous = existing.get().getData().path("revision").asText(MISSING_SOURCE_REVISION);
String current;
try {
current = observeS3SourceRevision(action);
} catch (RuntimeException e) {
LOG.debugf(e, "Unable to poll CodePipeline S3 source %s/%s", pipeline.getName(), actionName);
return;
}
if (Objects.equals(previous, current)) {
return;
}
if (MISSING_SOURCE_REVISION.equals(current)) {
updateSourcePollCursor(existing.get(), current);
return;
}
JsonNode config = action.path("configuration");
String bucket = config.path("S3Bucket").asText(config.path("BucketName").asText(null));
String objectKey = config.path("S3ObjectKey").asText(config.path("ObjectKey").asText(null));
ObjectNode request = mapper.createObjectNode().put("name", pipeline.getName());
startPipelineExecution(request, pipeline.getRegion(), pipeline.getAccountId(),
"PollForSourceChanges", "s3://" + bucket + "/" + objectKey);
updateSourcePollCursor(existing.get(), current);
});
}
private void forEachPolledS3Source(CodePipelinePipeline pipeline, S3SourceConsumer consumer) {
for (JsonNode stage : pipeline.getDeclaration().path("stages")) {
String stageName = stage.path("name").asText();
for (JsonNode action : stage.path("actions")) {
JsonNode type = action.path("actionTypeId");
if (!"Source".equals(type.path("category").asText())
|| !"AWS".equals(type.path("owner").asText())
|| !"S3".equals(type.path("provider").asText())) {
continue;
}
JsonNode config = action.path("configuration");
String bucket = config.path("S3Bucket").asText(config.path("BucketName").asText(null));
String objectKey = config.path("S3ObjectKey").asText(config.path("ObjectKey").asText(null));
if (bucket == null || bucket.isBlank() || objectKey == null || objectKey.isBlank()) {
continue;
}
if (!Boolean.parseBoolean(config.path("PollForSourceChanges").asText("true"))) {
continue;
}
consumer.accept(stageName, action);
}
}
}
private String observeS3SourceRevision(JsonNode action) {
JsonNode config = action.path("configuration");
String bucket = config.path("S3Bucket").asText(config.path("BucketName").asText(null));
String key = config.path("S3ObjectKey").asText(config.path("ObjectKey").asText(null));
try {
S3Object object = s3Service.headObject(bucket, key);
return object.getVersionId() != null
? "version:" + object.getVersionId() : "etag:" + unquoteETag(object.getETag());
} catch (AwsException e) {
if ("NoSuchBucket".equals(e.getErrorCode()) || "NoSuchKey".equals(e.getErrorCode())) {
return MISSING_SOURCE_REVISION;
}
throw e;
}
}
private void storeSourcePollCursor(CodePipelinePipeline pipeline, String cursorId, String revision) {
ObjectNode data = mapper.createObjectNode().put("revision", revision);
storeItem(pipeline.getAccountId(), pipeline.getRegion(), SOURCE_POLL_TYPE, cursorId, "ACTIVE", data);
}
private void updateSourcePollCursor(CodePipelineStoredItem item, String revision) {
item.setData(mapper.createObjectNode().put("revision", revision));
item.setUpdated(now());
putItem(item);
}
private static String sourcePollCursorId(String pipelineName, String stageName, String actionName) {
return pipelineName + "::" + stageName + "::" + actionName;
}
private static String unquoteETag(String eTag) {
return eTag == null ? null : eTag.replace("\"", "");
}
@FunctionalInterface
private interface S3SourceConsumer {
void accept(String stageName, JsonNode action);
}
private ObjectNode createPipeline(JsonNode request, String region, String account) {
@@ -182,7 +347,11 @@ public class CodePipelineService {
pipeline.setDeclaration(normalizeDeclaration(declaration, 1));
pipeline.setTags(parseTags(request.path("tags")));
initializeTransitions(pipeline);
putPipeline(pipeline);
String pollLockKey = pipelineLockKey(account, region, name);
synchronized (sourcePollLocks.computeIfAbsent(pollLockKey, ignored -> new Object())) {
putPipeline(pipeline);
resetSourcePollingBaselines(pipeline);
}
ObjectNode response = mapper.createObjectNode();
response.set("pipeline", pipeline.getDeclaration());
if (!pipeline.getTags().isEmpty()) {
@@ -200,7 +369,11 @@ public class CodePipelineService {
pipeline.setUpdated(now());
pipeline.setDeclaration(normalizeDeclaration(declaration, version));
initializeTransitions(pipeline);
putPipeline(pipeline);
String pollLockKey = pipelineLockKey(account, region, name);
synchronized (sourcePollLocks.computeIfAbsent(pollLockKey, ignored -> new Object())) {
putPipeline(pipeline);
resetSourcePollingBaselines(pipeline);
}
ObjectNode response = mapper.createObjectNode();
response.set("pipeline", pipeline.getDeclaration());
return response;
@@ -225,11 +398,15 @@ public class CodePipelineService {
private ObjectNode deletePipeline(JsonNode request, String region, String account) {
String name = text(request, "name");
validatePipelineName(name);
pipelineStore.deleteForAccount(account, pipelineKey(region, name));
for (String key : executionStore.keysForAccount(account)) {
if (key.startsWith(region + ":" + name + ":")) {
executionStore.deleteForAccount(account, key);
String pollLockKey = pipelineLockKey(account, region, name);
synchronized (sourcePollLocks.computeIfAbsent(pollLockKey, ignored -> new Object())) {
pipelineStore.deleteForAccount(account, pipelineKey(region, name));
for (String key : executionStore.keysForAccount(account)) {
if (key.startsWith(region + ":" + name + ":")) {
executionStore.deleteForAccount(account, key);
}
}
deleteSourcePollingBaselines(account, region, name);
}
return mapper.createObjectNode();
}
@@ -256,6 +433,11 @@ public class CodePipelineService {
}
private ObjectNode startPipelineExecution(JsonNode request, String region, String account) {
return startPipelineExecution(request, region, account, "StartPipelineExecution", "manual");
}
private ObjectNode startPipelineExecution(JsonNode request, String region, String account,
String triggerType, String triggerDetail) {
CodePipelinePipeline pipeline = requirePipeline(account, region, text(request, "name"));
String clientToken = request.path("clientRequestToken").asText(null);
if (clientToken != null) {
@@ -282,8 +464,8 @@ public class CodePipelineService {
execution.setSourceRevisions(objectList(request.path("sourceRevisions")));
execution.setVariables(variableList(request.path("variables")));
Map<String, String> trigger = new LinkedHashMap<>();
trigger.put("triggerType", "StartPipelineExecution");
trigger.put("triggerDetail", "manual");
trigger.put("triggerType", triggerType);
trigger.put("triggerDetail", triggerDetail);
if (clientToken != null) {
trigger.put("clientRequestToken", clientToken);
}
@@ -1499,7 +1681,11 @@ public class CodePipelineService {
}
private static String lockKey(CodePipelineExecution execution) {
return execution.getAccountId() + ":" + execution.getRegion() + ":" + execution.getPipelineName();
return pipelineLockKey(execution.getAccountId(), execution.getRegion(), execution.getPipelineName());
}
private static String pipelineLockKey(String account, String region, String pipelineName) {
return account + ":" + region + ":" + pipelineName;
}
private static String artifactKey(CodePipelineExecution execution, String artifactName) {
@@ -1546,6 +1732,7 @@ public class CodePipelineService {
@PreDestroy
void shutdown() {
sourcePoller.shutdownNow();
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
@@ -328,6 +328,222 @@ class CodePipelineIntegrationTest {
""".formatted(pipelineName)).then().statusCode(200);
}
@Test
void s3SourcePollingStartsExactlyOneExecutionForARevisionChange() throws Exception {
createBucket("codepipeline-poll-source");
createBucket("codepipeline-poll-destination");
putObject("codepipeline-poll-source", "source.zip", "baseline artifact");
String pipelineName = "s3-source-polling-pipeline";
post("CreatePipeline", pipeline(pipelineName, """
{
"name": "Source",
"actions": [{
"name": "SourceObject",
"actionTypeId": {
"category": "Source",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"S3Bucket": "codepipeline-poll-source",
"S3ObjectKey": "source.zip"
},
"outputArtifacts": [{"name": "SourceOutput"}]
}]
},
{
"name": "Deploy",
"actions": [{
"name": "DeployObject",
"actionTypeId": {
"category": "Deploy",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"BucketName": "codepipeline-poll-destination",
"ObjectKey": "deployed.zip"
},
"inputArtifacts": [{"name": "SourceOutput"}]
}]
}
"""))
.then().statusCode(200);
Thread.sleep(1200);
post("ListPipelineExecutions", """
{"pipelineName": "%s"}
""".formatted(pipelineName))
.then()
.statusCode(200)
.body("pipelineExecutionSummaries", hasSize(0));
putObject("codepipeline-poll-source", "source.zip", "changed artifact");
Response executions = waitForPipelineExecutionCount(pipelineName, 1);
String executionId = executions.jsonPath().getString("pipelineExecutionSummaries[0].pipelineExecutionId");
waitForExecution(pipelineName, executionId, "Succeeded");
post("GetPipelineExecution", """
{"pipelineName": "%s", "pipelineExecutionId": "%s"}
""".formatted(pipelineName, executionId))
.then()
.statusCode(200)
.body("pipelineExecution.trigger.triggerType", equalTo("PollForSourceChanges"))
.body("pipelineExecution.trigger.triggerDetail",
equalTo("s3://codepipeline-poll-source/source.zip"));
given()
.get("/codepipeline-poll-destination/deployed.zip")
.then()
.statusCode(200)
.body(equalTo("changed artifact"));
Thread.sleep(1200);
post("ListPipelineExecutions", """
{"pipelineName": "%s"}
""".formatted(pipelineName))
.then()
.statusCode(200)
.body("pipelineExecutionSummaries", hasSize(1));
post("DeletePipeline", """
{"name": "%s"}
""".formatted(pipelineName)).then().statusCode(200);
}
@Test
void s3SourcePollingStartsWhenPreviouslyMissingObjectAppears() throws Exception {
createBucket("codepipeline-poll-missing-source");
createBucket("codepipeline-poll-missing-destination");
String pipelineName = "s3-source-polling-missing-object";
post("CreatePipeline", pipeline(pipelineName, """
{
"name": "Source",
"actions": [{
"name": "SourceObject",
"actionTypeId": {
"category": "Source",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"S3Bucket": "codepipeline-poll-missing-source",
"S3ObjectKey": "source.zip"
},
"outputArtifacts": [{"name": "SourceOutput"}]
}]
},
{
"name": "Deploy",
"actions": [{
"name": "DeployObject",
"actionTypeId": {
"category": "Deploy",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"BucketName": "codepipeline-poll-missing-destination",
"ObjectKey": "deployed.zip"
},
"inputArtifacts": [{"name": "SourceOutput"}]
}]
}
"""))
.then().statusCode(200);
Thread.sleep(700);
post("ListPipelineExecutions", """
{"pipelineName": "%s"}
""".formatted(pipelineName))
.then()
.statusCode(200)
.body("pipelineExecutionSummaries", hasSize(0));
putObject("codepipeline-poll-missing-source", "source.zip", "first available artifact");
Response executions = waitForPipelineExecutionCount(pipelineName, 1);
String executionId = executions.jsonPath().getString("pipelineExecutionSummaries[0].pipelineExecutionId");
waitForExecution(pipelineName, executionId, "Succeeded");
post("GetPipelineExecution", """
{"pipelineName": "%s", "pipelineExecutionId": "%s"}
""".formatted(pipelineName, executionId))
.then()
.statusCode(200)
.body("pipelineExecution.trigger.triggerType", equalTo("PollForSourceChanges"));
post("DeletePipeline", """
{"name": "%s"}
""".formatted(pipelineName)).then().statusCode(200);
}
@Test
void s3SourcePollingDisabledDoesNotStartExecution() throws Exception {
createBucket("codepipeline-poll-disabled-source");
putObject("codepipeline-poll-disabled-source", "source.zip", "baseline artifact");
String pipelineName = "s3-source-polling-disabled";
post("CreatePipeline", pipeline(pipelineName, """
{
"name": "Source",
"actions": [{
"name": "SourceObject",
"actionTypeId": {
"category": "Source",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"S3Bucket": "codepipeline-poll-disabled-source",
"S3ObjectKey": "source.zip",
"PollForSourceChanges": "false"
},
"outputArtifacts": [{"name": "SourceOutput"}]
}]
},
{
"name": "Deploy",
"actions": [{
"name": "PlaceholderAction",
"actionTypeId": {
"category": "Deploy",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"BucketName": "unused-codepipeline-destination",
"ObjectKey": "deployed.zip"
},
"inputArtifacts": [{"name": "SourceOutput"}]
}]
}
"""))
.then().statusCode(200);
putObject("codepipeline-poll-disabled-source", "source.zip", "changed artifact");
Thread.sleep(1200);
post("ListPipelineExecutions", """
{"pipelineName": "%s"}
""".formatted(pipelineName))
.then()
.statusCode(200)
.body("pipelineExecutionSummaries", hasSize(0));
post("DeletePipeline", """
{"name": "%s"}
""".formatted(pipelineName)).then().statusCode(200);
}
@Test
void listPipelineExecutionsValidatesFilterAndMaxResults() {
String pipelineName = "list-executions-validation-pipeline";
@@ -1234,6 +1450,21 @@ class CodePipelineIntegrationTest {
throw new AssertionError("Custom action job was not created");
}
private Response waitForPipelineExecutionCount(String pipelineName, int expectedCount) throws Exception {
Instant deadline = Instant.now().plus(Duration.ofSeconds(5));
Response response;
do {
response = post("ListPipelineExecutions", """
{"pipelineName": "%s"}
""".formatted(pipelineName));
if (response.jsonPath().getList("pipelineExecutionSummaries").size() == expectedCount) {
return response;
}
Thread.sleep(50);
} while (Instant.now().isBefore(deadline));
throw new AssertionError("Pipeline execution count did not reach " + expectedCount);
}
private void waitForExecution(String pipelineName, String executionId, String expected) throws Exception {
Instant deadline = Instant.now().plus(Duration.ofSeconds(5));
String status;
@@ -10,13 +10,21 @@ import io.github.hectorvent.floci.services.codebuild.CodeBuildService;
import io.github.hectorvent.floci.services.codedeploy.CodeDeployService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class CodePipelineServiceTest {
@@ -32,6 +40,91 @@ class CodePipelineServiceTest {
mock(LambdaService.class),
mock(S3Service.class));
@Test
void sourcePollingAndPipelineUpdateSerializeBaselineChanges() throws Exception {
S3Service s3Service = mock(S3Service.class);
S3Object source = new S3Object();
source.setETag("\"baseline\"");
AtomicInteger headCalls = new AtomicInteger();
CountDownLatch pollEntered = new CountDownLatch(1);
CountDownLatch releasePoll = new CountDownLatch(1);
when(s3Service.headObject("source-bucket", "source.zip")).thenAnswer(invocation -> {
int call = headCalls.incrementAndGet();
if (call == 2) {
pollEntered.countDown();
if (!releasePoll.await(2, TimeUnit.SECONDS)) {
throw new IllegalStateException("Timed out waiting to release the source poll");
}
}
return source;
});
CodePipelineService pollingService = new CodePipelineService(
new InMemoryStorageFactory(),
mapper,
mock(CodeBuildService.class),
mock(CodeDeployService.class),
mock(LambdaService.class),
s3Service);
String pipelineRequest = """
{
"pipeline": {
"name": "polling-pipeline",
"roleArn": "arn:aws:iam::000000000000:role/codepipeline-role",
"artifactStore": {"type": "S3", "location": "codepipeline-artifacts"},
"stages": [{
"name": "Source",
"actions": [{
"name": "SourceObject",
"actionTypeId": {
"category": "Source",
"owner": "AWS",
"provider": "S3",
"version": "1"
},
"configuration": {
"S3Bucket": "source-bucket",
"S3ObjectKey": "source.zip"
},
"outputArtifacts": [{"name": "SourceOutput"}]
}]
}, {
"name": "Approve",
"actions": [{
"name": "ManualApproval",
"actionTypeId": {
"category": "Approval",
"owner": "AWS",
"provider": "Manual",
"version": "1"
}
}]
}]
}
}
""";
JsonNode request = mapper.readTree(pipelineRequest);
try {
pollingService.handle("CreatePipeline", request, REGION, ACCOUNT);
pollingService.resumePersistedExecutions();
assertTrue(pollEntered.await(2, TimeUnit.SECONDS));
JsonNode updateRequest = mapper.readTree(pipelineRequest);
CompletableFuture<JsonNode> update = CompletableFuture.supplyAsync(
() -> pollingService.handle("UpdatePipeline", updateRequest, REGION, ACCOUNT));
Thread.sleep(150);
assertFalse(update.isDone(), "UpdatePipeline must wait for the in-flight source poll");
releasePoll.countDown();
update.get(2, TimeUnit.SECONDS);
} finally {
releasePoll.countDown();
pollingService.shutdown();
}
}
@Test
void aStartAfterShutdownIsRefusedAndTheExecutionIsPersistedAsFailed() throws Exception {
handle("CreatePipeline", """