Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(core): let RequestScopes run background work in a given region (#5054)

Hector Ventura971dc01f349d
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java
index 539b868f30..dc389a3409 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestScopes.java
@@ -7,7 +7,10 @@ import io.quarkus.arc.ManagedContext;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
-/** Runs work that happens outside an HTTP request, such as a background worker, as a given account. */
+/**
+ * Runs work that happens outside an HTTP request, such as a background worker, as a given account
+ * and, optionally, in a given region.
+ */
public final class RequestScopes {
private RequestScopes() {}
@@ -17,15 +20,28 @@ public final class RequestScopes {
* a fresh thread would otherwise fall back to the default account.
*/
public static void runAs(String accountId, Runnable body) {
- callAs(accountId, () -> {
+ runAs(accountId, null, body);
+ }
+
+ /**
+ * {@link #runAs(String, Runnable)} that also sets the region, and the region's partition, so
+ * {@link RegionResolver#getRegion()}, {@link RegionResolver#getPartition()} and region-keyed
+ * lookups inside {@code body} see the resource's region instead of the default one.
+ */
+ public static void runAs(String accountId, String region, Runnable body) {
+ callAs(accountId, region, () -> {
body.run();
return null;
});
}
public static <T> T callAs(String accountId, Supplier<T> body) {
+ return callAs(accountId, null, body);
+ }
+
+ public static <T> T callAs(String accountId, String region, Supplier<T> body) {
try {
- return callAsChecked(accountId, body::get);
+ return callAsChecked(accountId, region, body::get);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
@@ -34,14 +50,22 @@ public final class RequestScopes {
}
}
+ public static <T> T callAsChecked(String accountId, Callable<T> body) throws Exception {
+ return callAsChecked(accountId, null, body);
+ }
+
/**
- * {@link #callAs} for a body that throws checked exceptions, which propagate unchanged. Runs
- * the body directly when {@code accountId} is null or Arc is not running; restores the previous
- * account when the request scope was already active, and terminates the scope it activated.
+ * {@link #callAs} for a body that throws checked exceptions, which propagate unchanged. Sets the
+ * account when {@code accountId} is non-null and the region and its partition when
+ * {@code region} is non-null; a region outside every published partition leaves the partition
+ * unset, so {@link RegionResolver#getPartition()} falls back to the deployment's, as it does for
+ * a request. Runs the body directly when both are null or Arc is not running; restores the
+ * previous values when the request scope was already active, and terminates the scope it
+ * activated.
*/
- public static <T> T callAsChecked(String accountId, Callable<T> body) throws Exception {
+ public static <T> T callAsChecked(String accountId, String region, Callable<T> body) throws Exception {
ArcContainer container = Arc.container();
- if (accountId == null || container == null || !container.isRunning()) {
+ if ((accountId == null && region == null) || container == null || !container.isRunning()) {
return body.call();
}
ManagedContext requestContext = container.requestContext();
@@ -51,14 +75,24 @@ public final class RequestScopes {
}
RequestContext ctx = container.instance(RequestContext.class).get();
String previousAccountId = alreadyActive ? ctx.getAccountId() : null;
+ String previousRegion = alreadyActive ? ctx.getRegion() : null;
+ String previousPartition = alreadyActive ? ctx.getPartition() : null;
try {
- ctx.setAccountId(accountId);
+ if (accountId != null) {
+ ctx.setAccountId(accountId);
+ }
+ if (region != null) {
+ ctx.setRegion(region);
+ ctx.setPartition(AwsPartitions.forRegion(region).map(AwsPartition::id).orElse(null));
+ }
return body.call();
} finally {
if (!alreadyActive) {
requestContext.terminate();
} else {
ctx.setAccountId(previousAccountId);
+ ctx.setRegion(previousRegion);
+ ctx.setPartition(previousPartition);
}
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
index 055918d7b8..2a5f097c4d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
@@ -6,10 +6,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
-import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
-import io.quarkus.arc.Arc;
-import io.quarkus.arc.ManagedContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
@@ -941,7 +939,7 @@ public class CloudFormationService implements ResourceProvider {
String templateBody = cs.getTemplateBody();
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
- return submitOperation(() -> runUnderScope(accountId, region, () -> {
+ return submitOperation(() -> RequestScopes.runAs(accountId, region, () -> {
executeTemplate(stack, templateBody, params, isCreate, region, accountId);
String status = stack.getStatus();
cs.setExecutionStatus(status != null && (status.contains("ROLLBACK") || status.endsWith("_FAILED"))
@@ -950,43 +948,6 @@ public class CloudFormationService implements ResourceProvider {
}));
}
- /**
- * Runs {@code body} under the stack's account and region, so downstream services resolve the
- * same scope as the CloudFormation request that submitted this background operation.
- */
- private void runUnderScope(String accountId, String region, Runnable body) {
- ManagedContext requestContext = Arc.container().requestContext();
- boolean alreadyActive = requestContext.isActive();
- if (!alreadyActive) {
- requestContext.activate();
- }
- // Background workers normally have no active scope, so a fresh one is activated and
- // terminated below. But if we ran inside an already-active scope, restore its previous
- // scope afterwards so we never leave the overridden values behind on a reused thread.
- RequestContext ctx = Arc.container().instance(RequestContext.class).get();
- String previousAccountId = alreadyActive ? ctx.getAccountId() : null;
- String previousRegion = alreadyActive ? ctx.getRegion() : null;
- String previousPartition = alreadyActive ? ctx.getPartition() : null;
- try {
- if (accountId != null) {
- ctx.setAccountId(accountId);
- }
- if (region != null) {
- ctx.setRegion(region);
- ctx.setPartition(regionResolver.partitionForRegion(region));
- }
- body.run();
- } finally {
- if (!alreadyActive) {
- requestContext.terminate();
- } else {
- ctx.setAccountId(previousAccountId);
- ctx.setRegion(previousRegion);
- ctx.setPartition(previousPartition);
- }
- }
- }
-
// ── DeleteChangeSet ───────────────────────────────────────────────────────
public void deleteChangeSet(String stackName, String changeSetName, String region) {
@@ -1042,7 +1003,7 @@ public class CloudFormationService implements ResourceProvider {
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
try {
- return submitOperation(() -> runUnderScope(accountId, region,
+ return submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> deleteStackResources(stack, region, accountId)));
} catch (AwsException e) {
if ("LimitExceededException".equals(e.getErrorCode())) {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestScopesRegionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestScopesRegionIntegrationTest.java
new file mode 100644
index 0000000000..ac8e4009b1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestScopesRegionIntegrationTest.java
@@ -0,0 +1,90 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+@QuarkusTest
+class RequestScopesRegionIntegrationTest {
+
+ @Inject
+ RegionResolver regionResolver;
+
+ @Test
+ void runAsWithRegionSetsTheRegionAndItsPartition() {
+ AtomicReference<String> seen = new AtomicReference<>();
+ runOffRequestThread(() -> RequestScopes.runAs("111122223333", "cn-north-1",
+ () -> seen.set(regionResolver.getAccountId() + "|" + regionResolver.getRegion()
+ + "|" + regionResolver.getPartition())));
+ assertEquals("111122223333|cn-north-1|aws-cn", seen.get());
+ }
+
+ @Test
+ void accountOnlyRunAsLeavesTheDefaultRegion() {
+ AtomicReference<String> seen = new AtomicReference<>();
+ runOffRequestThread(() -> RequestScopes.runAs("111122223333",
+ () -> seen.set(regionResolver.getRegion() + "|" + regionResolver.getPartition())));
+ assertEquals(regionResolver.getDefaultRegion() + "|" + regionResolver.getDefaultPartition(), seen.get());
+ }
+
+ @Test
+ void nestedScopeRestoresTheOuterAccountRegionAndPartition() {
+ AtomicReference<String> inner = new AtomicReference<>();
+ AtomicReference<String> outerAfter = new AtomicReference<>();
+ runOffRequestThread(() -> RequestScopes.runAs("111122223333", "eu-west-1", () -> {
+ RequestScopes.runAs("444455556666", "cn-north-1",
+ () -> inner.set(regionResolver.getAccountId() + "|" + regionResolver.getRegion()
+ + "|" + regionResolver.getPartition()));
+ outerAfter.set(regionResolver.getAccountId() + "|" + regionResolver.getRegion()
+ + "|" + regionResolver.getPartition());
+ }));
+ assertEquals("444455556666|cn-north-1|aws-cn", inner.get());
+ assertEquals("111122223333|eu-west-1|aws", outerAfter.get());
+ }
+
+ @Test
+ void regionOutsideEveryPartitionFallsBackToTheDeploymentPartition() {
+ AtomicReference<String> seen = new AtomicReference<>();
+ runOffRequestThread(() -> RequestScopes.runAs(null, "xx-nowhere-9",
+ () -> seen.set(regionResolver.getRegion() + "|" + regionResolver.getPartition())));
+ assertEquals("xx-nowhere-9|" + regionResolver.getDefaultPartition(), seen.get());
+ }
+
+ @Test
+ void callAsReturnsTheBodysValueInTheRegion() {
+ AtomicReference<String> result = new AtomicReference<>();
+ runOffRequestThread(() -> result.set(
+ RequestScopes.callAs(null, "ap-southeast-2", regionResolver::getRegion)));
+ assertEquals("ap-southeast-2", result.get());
+ assertNotEquals("ap-southeast-2", regionResolver.getDefaultRegion());
+ }
+
+ /**
+ * Background workers run on threads with no active request scope; reproduce that. Anything the
+ * worker throws, including while a scope is restored after the body, fails the test.
+ */
+ private static void runOffRequestThread(Runnable body) {
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ Thread thread = Thread.ofVirtual().start(() -> {
+ try {
+ body.run();
+ } catch (Throwable t) {
+ failure.set(t);
+ }
+ });
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ if (failure.get() != null) {
+ throw new AssertionError("background worker failed", failure.get());
+ }
+ }
+}