feat(lambda): make reactive S3 sync toggleable and optionally async (#6548)

* feat(lambda): make reactive S3 sync toggleable and optionally async, reporting LastUpdateStatus while it runs

* fix(lambda): run async reactive S3 syncs as the uploader's account, keep InProgress continuous, and queue the latest source per function

* fix(lambda): clear a failed reactive sync's LastUpdateStatus on UpdateFunctionConfiguration, and test async syncs from a second account

* test(lambda): share LambdaCodeSourcesProfile for the async reactive sync test, reuse LambdaWebZips, and extract the failed-sync setup
This commit is contained in:
floverfelt authored and GitHub committed 2026-10-25 21:55:13 -04:00
1 parent bffffedb88
commit 89be5c1742
12 files changed
+475 -29

No files matched your search

@@ -3272,6 +3272,30 @@ public interface EmulatorConfig {
*/
Optional<List<String>> allowedPaths();
}
ReactiveS3Sync reactiveS3Sync();
interface ReactiveS3Sync {
/**
* When true, uploading a new object to the S3 bucket and key a function was deployed
* from re-deploys that function's {@code $LATEST} and drains its warm containers. When
* false, the object is only stored, as in AWS.
*
* Env var: FLOCI_SERVICES_LAMBDA_REACTIVE_S3_SYNC_ENABLED
*/
@WithDefault("true")
boolean enabled();
/**
* When true, the re-deploy runs in the background so the S3 upload returns at once;
* the function reports {@code LastUpdateStatus=InProgress} until it finishes. When
* false, the upload returns only after the function has been re-deployed.
*
* Env var: FLOCI_SERVICES_LAMBDA_REACTIVE_S3_SYNC_ASYNC
*/
@WithDefault("false")
boolean async();
}
}
interface Ec2ServiceConfig {
@@ -746,7 +746,11 @@ public class LambdaController {
.format(Instant.ofEpochMilli(fn.getLastModified()).atOffset(ZoneOffset.UTC)));
node.put("RevisionId", fn.getRevisionId());
node.put("Version", fn.getVersion());
node.put("LastUpdateStatus", "Successful");
node.put("LastUpdateStatus", lambdaService.lastUpdateStatus(fn));
String lastUpdateStatusReason = lambdaService.lastUpdateStatusReason(fn);
if (lastUpdateStatusReason != null) {
node.put("LastUpdateStatusReason", lastUpdateStatusReason);
}
// Architectures — always present; default x86_64
ArrayNode archNode = node.putArray("Architectures");
@@ -67,6 +67,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
@@ -165,6 +166,9 @@ public class LambdaService implements ResourceProvider {
"Environment", "EphemeralStorage", "TracingConfig", "DeadLetterConfig",
"VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig", "DurableConfig");
private static final Executor REACTIVE_SYNC_THREADS =
task -> Thread.ofVirtual().name("lambda-reactive-s3-sync").start(task);
private final LambdaFunctionStore functionStore;
private final LambdaExecutorService executorService;
private final LambdaConcurrencyLimiter concurrencyLimiter;
@@ -183,6 +187,9 @@ public class LambdaService implements ResourceProvider {
private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
private final StorageFactory storageFactory;
private final LambdaLayerService layerService;
private final Map<String, PendingReactiveSync> pendingReactiveSyncs = new ConcurrentHashMap<>();
private final Map<String, Integer> runningReactiveSyncs = new ConcurrentHashMap<>();
private final Map<String, String> failedReactiveSyncs = new ConcurrentHashMap<>();
private final Ec2Service ec2Service;
/** Null in the constructors tests use, exactly as the other optional collaborators above are. */
private final CustomResourceLiveness customResourceLiveness;
@@ -775,6 +782,7 @@ public class LambdaService implements ResourceProvider {
// Drain warm containers — they have stale code mounted
warmPool.drainEnvironment(fn);
failedReactiveSyncs.remove(fn.getFunctionArn());
functionStore.save(region, fn);
LOG.infov("Updated code for function: {0}", functionName);
@@ -996,6 +1004,8 @@ public class LambdaService implements ResourceProvider {
warmPool.drainEnvironment(fn);
functionStore.save(region, fn);
// LastUpdateStatus reports the last update of either kind, so this one replaces a failed sync's.
failedReactiveSyncs.remove(fn.getFunctionArn());
LOG.infov("Updated configuration for function: {0}", functionName);
return fn;
}
@@ -1116,6 +1126,7 @@ public class LambdaService implements ResourceProvider {
reclaimLegacyCodeDirectoryIfUnused(functionName);
versionCounters.remove(versionCounterKey(region, fn));
versionCounters.remove(legacyVersionCounterKey(region, functionName));
failedReactiveSyncs.remove(arn);
if (aliasStore != null) {
for (LambdaAlias alias : aliasStore.list(region, functionName)) {
aliasStore.delete(region, functionName, alias.getName());
@@ -4140,6 +4151,9 @@ public class LambdaService implements ResourceProvider {
* functions linked to the updated object.
*/
public void onS3ObjectUpdated(@Observes S3ObjectUpdatedEvent event) {
if (!reactiveS3SyncEnabled()) {
return;
}
LOG.debugv("Observing S3 update: {0}/{1}", event.bucketName(), event.key());
// For simplicity, we scan all functions in the default region
// Most local dev setups use a single region.
@@ -4148,32 +4162,118 @@ public class LambdaService implements ResourceProvider {
// other account would silently never hot-reload from S3.
String region = regionResolver.getDefaultRegion();
List<LambdaFunction> functions = functionStore.listAllAccounts(region);
boolean async = reactiveS3SyncAsync();
for (LambdaFunction fn : functions) {
if (!event.bucketName().equals(fn.getS3Bucket()) || !event.key().equals(fn.getS3Key())) {
continue;
}
synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
if (fn.isHotReload()) {
continue;
}
if (event.bucketName().equals(fn.getS3Bucket()) && event.key().equals(fn.getS3Key())) {
LOG.infov("Reactive S3 Sync: updating function {0} from s3://{1}/{2}",
fn.getFunctionName(), event.bucketName(), event.key());
try {
try (DeploymentPackage zip = readS3Package(fn, event.bucketName(), event.key(), region)) {
extractZipCodePackage(fn, zip, region);
}
fn.setLastModified(Instant.now().toEpochMilli());
fn.setRevisionId(UUID.randomUUID().toString());
functionStore.saveForAccount(ownerAccount(fn), region, fn);
// Push to warm workers
warmPool.pushCodeUpdate(fn);
} catch (Exception e) {
LOG.warnv("Failed reactive sync for function {0}: {1}", fn.getFunctionName(), e.getMessage());
}
}
if (!async) {
syncFromS3(fn, event.bucketName(), event.key(), region);
continue;
}
// The newest upload replaces any source still waiting, and a queued sync reads its object
// when it starts, so one queued sync per function covers every upload before it. The
// uploader's account goes with it: S3 resolves the bucket in the caller's account, and
// the background thread has no request of its own.
String functionArn = fn.getFunctionArn();
PendingReactiveSync source = new PendingReactiveSync(regionResolver.getAccountId(),
event.bucketName(), event.key());
if (pendingReactiveSyncs.put(functionArn, source) == null) {
String ownerAccountId = ownerAccount(fn);
String functionName = fn.getFunctionName();
REACTIVE_SYNC_THREADS.execute(() -> syncQueued(ownerAccountId, region, functionName, functionArn));
}
}
}
/** Re-reads the function, which may have been redeployed or deleted while the sync was queued. */
private void syncQueued(String ownerAccountId, String region, String functionName, String functionArn) {
// Marked running before the pending source is taken, so the function never reports neither.
runningReactiveSyncs.merge(functionArn, 1, Integer::sum);
try {
synchronized (lockForConcurrencyOp(functionArn)) {
PendingReactiveSync source = pendingReactiveSyncs.remove(functionArn);
if (source == null) {
return;
}
RequestScopes.runAs(source.accountId(), () ->
functionStore.getForAccount(ownerAccountId, region, functionName)
.ifPresent(fn -> deployFromS3(fn, source.bucketName(), source.key(), region)));
}
} finally {
runningReactiveSyncs.computeIfPresent(functionArn, (arn, count) -> count == 1 ? null : count - 1);
}
}
private void syncFromS3(LambdaFunction fn, String bucketName, String key, String region) {
String functionArn = fn.getFunctionArn();
runningReactiveSyncs.merge(functionArn, 1, Integer::sum);
try {
synchronized (lockForConcurrencyOp(functionArn)) {
deployFromS3(fn, bucketName, key, region);
}
} finally {
runningReactiveSyncs.computeIfPresent(functionArn, (arn, count) -> count == 1 ? null : count - 1);
}
}
/** Callers hold the function's lock. */
private void deployFromS3(LambdaFunction fn, String bucketName, String key, String region) {
if (fn.isHotReload()) {
return;
}
if (bucketName.equals(fn.getS3Bucket()) && key.equals(fn.getS3Key())) {
LOG.infov("Reactive S3 Sync: updating function {0} from s3://{1}/{2}",
fn.getFunctionName(), bucketName, key);
try {
try (DeploymentPackage zip = readS3Package(fn, bucketName, key, region)) {
extractZipCodePackage(fn, zip, region);
}
fn.setLastModified(Instant.now().toEpochMilli());
fn.setRevisionId(UUID.randomUUID().toString());
functionStore.saveForAccount(ownerAccount(fn), region, fn);
// Push to warm workers
warmPool.pushCodeUpdate(fn);
failedReactiveSyncs.remove(fn.getFunctionArn());
} catch (Exception e) {
LOG.warnv("Failed reactive sync for function {0}: {1}", fn.getFunctionName(), e.getMessage());
failedReactiveSyncs.put(fn.getFunctionArn(), "Reactive S3 sync from s3://" + bucketName
+ "/" + key + " failed: " + e.getMessage());
}
}
}
/**
* The function's LastUpdateStatus, which only a reactive S3 sync moves off Successful:
* InProgress from the upload until the re-deploy of {@code $LATEST} finishes, Failed when the
* last one could not. Held in memory, so a restart cannot leave an update reported as running.
*/
public String lastUpdateStatus(LambdaFunction fn) {
if (!"$LATEST".equals(fn.getVersion())) {
return "Successful";
}
String functionArn = fn.getFunctionArn();
// Pending first: a sync marks itself running before it takes the pending source.
if (pendingReactiveSyncs.containsKey(functionArn) || runningReactiveSyncs.containsKey(functionArn)) {
return "InProgress";
}
return failedReactiveSyncs.containsKey(functionArn) ? "Failed" : "Successful";
}
/** Why the last reactive S3 sync of {@code $LATEST} failed, or null when it did not. */
public String lastUpdateStatusReason(LambdaFunction fn) {
return "Failed".equals(lastUpdateStatus(fn)) ? failedReactiveSyncs.get(fn.getFunctionArn()) : null;
}
private boolean reactiveS3SyncEnabled() {
return config == null || config.services().lambda().reactiveS3Sync().enabled();
}
private boolean reactiveS3SyncAsync() {
return config != null && config.services().lambda().reactiveS3Sync().async();
}
private record PendingReactiveSync(String accountId, String bucketName, String key) {
}
}