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

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

RequestScopes.runAs only set the account, so work running outside a
request resolved RegionResolver.getRegion() and getPartition() to the
deployment defaults. New runAs/callAs/callAsChecked overloads take a
region too and set it with its partition; a region outside every
published partition leaves the partition unset so it falls back to the
deployment's, as a request does. Inside an already active scope the
previous account, region and partition are restored. The account-only
methods keep their behaviour.

CloudFormationService's private runUnderScope, which did the same thing
for stack operations, now uses the shared method.

* test(core): fail the RequestScopes region test when the worker thread throws

The helper that runs each case on a fresh virtual thread joined it without
passing on the thread's exception, so a failure while a scope was restored
after the body could leave the recorded values intact and the test green.
It now captures anything the worker throws and fails the test with it.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-04 05:59:59 -04:00
1 parent 1b138812fa
commit 971dc01f34
3 files changed
+137 -52

No files matched your search

@@ -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 {
}
}
/**
* {@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.
*/
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. 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, 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);
}
}
}
@@ -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())) {
@@ -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());
}
}
}