perf(core): drop per-request lookups and allocations on the shared request path (#7323)

* perf(core): drop per-request lookups on the shared request path

Every request resolved the EmulatorConfig and ResolvedServiceCatalog CDI
beans again in the claim, account and signature filters, fetched the
RequestContext through Instance.get() on each storage operation, built a
URI for the Host even when the header was present, formatted the Date
header from scratch, and let CloudTrail copy its key set to find no
trails.

The filters resolve config and catalog once. AccountAwareStorageBackend
and RegionResolver keep the RequestContext client proxy. RequestHost reads
the Host header before it touches the URI. The Date header is cached per
second as one immutable pair. StorageBackend gets isEmpty(), which every
in-memory map implements directly, and emitS3DataEvent returns at once
when no trail exists.

* perf(core): read the query map once and mint request ids without SecureRandom

AccountContextFilter asked UriInfo for the query parameters up to six
times per request, and each call builds a new map wrapper. It now reads
them once and hands the map to its helpers.

AwsRequestIdFilter drew its UUID from SecureRandom. A request id is not a
secret, so it is now a version 4 UUID built from ThreadLocalRandom, with
the same format and the same single id in all three headers.

* perf(core): scope AccountAwareStorageBackend.isEmpty to the current account

keys() and scan() only see the current account, so isEmpty() now
answers for that account too. A delegate with no entries at all still
answers without copying its key set.

* chore(cognito): give the sign-up scope test one request context that follows the calling thread

AccountAwareStorageBackend keeps the RequestContext it gets from the
Instance, as the request scoped client proxy forwards to the current
request. The test handed out a different context per get() call from a
ThreadLocal, so the kept one pinned both threads to the first account.
It now hands out one context whose account id follows the thread.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-02 21:14:52 -04:00
1 parent 6abdb4cc44
commit 055036508e
17 files changed
+183 -28

No files matched your search

@@ -12,6 +12,7 @@ import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
@@ -58,6 +59,8 @@ public class AccountContextFilter implements ContainerRequestFilter {
// this class also carries the JAX-RS @Provider annotation.
private final jakarta.inject.Provider<EmulatorConfig> configProvider;
private final jakarta.inject.Provider<ResolvedServiceCatalog> catalogProvider;
private volatile EmulatorConfig config;
private volatile ResolvedServiceCatalog catalog;
@Inject
public AccountContextFilter(AccountResolver accountResolver,
@@ -74,6 +77,24 @@ public class AccountContextFilter implements ContainerRequestFilter {
this.catalogProvider = catalogProvider;
}
private EmulatorConfig config() {
EmulatorConfig resolved = config;
if (resolved == null) {
resolved = configProvider.get();
config = resolved;
}
return resolved;
}
private ResolvedServiceCatalog catalog() {
ResolvedServiceCatalog resolved = catalog;
if (resolved == null) {
resolved = catalogProvider.get();
catalog = resolved;
}
return resolved;
}
@Override
public void filter(ContainerRequestContext ctx) {
Object pinnedAccount = ctx.getProperty(PINNED_ACCOUNT_PROPERTY);
@@ -84,14 +105,15 @@ public class AccountContextFilter implements ContainerRequestFilter {
applyRegion(regionResolver.resolveRegionFromAuth(null));
return;
}
String sessionToken = extractSessionToken(ctx);
MultivaluedMap<String, String> query = ctx.getUriInfo().getQueryParameters();
String sessionToken = extractSessionToken(ctx, query);
String auth = ctx.getHeaderString("Authorization");
if (rejectAmbiguousRegion(ctx, auth)) {
if (rejectAmbiguousRegion(ctx, auth, query)) {
return;
}
String akid = resourceInfo != null && catalogProvider.get().byResourceClass(resourceInfo.getResourceClass())
String akid = resourceInfo != null && catalog().byResourceClass(resourceInfo.getResourceClass())
.map(ServiceDescriptor::acceptsLegacyAuthorization).orElse(false)
&& !configProvider.get().services().iam().enforcementEnabled()
&& !config().services().iam().enforcementEnabled()
? accountResolver.extractS3AccessKeyId(auth) : accountResolver.extractAccessKeyId(auth);
if (akid != null) {
requestContext.setAccountId(resolveAccount(akid, accountResolver.resolve(auth)));
@@ -112,19 +134,19 @@ public class AccountContextFilter implements ContainerRequestFilter {
// must not let the query string pick an account that IAM then never checks.
boolean hasAuthHeader = auth != null && !auth.isBlank();
String credential = hasAuthHeader
? null : ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
? null : query.getFirst("X-Amz-Credential");
if (credential != null && !credential.isEmpty()
&& ctx.getUriInfo().getQueryParameters().containsKey("X-Amz-Algorithm")) {
&& query.containsKey("X-Amz-Algorithm")) {
String presignedAkid = accountResolver.extractPresignedAccessKeyId(credential);
requestContext.setAccountId(
resolveAccount(presignedAkid, accountResolver.resolveFromPresignedCredential(credential)));
requestContext.setAccessKeyId(presignedAkid);
requestContext.setSessionToken(sessionToken);
boolean sigV4a = SigV4aSignature.ALGORITHM.equals(
ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Algorithm"));
query.getFirst("X-Amz-Algorithm"));
String region = sigV4a
? regionResolver.resolveRegionFromRegionSet(
ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Region-Set"))
query.getFirst("X-Amz-Region-Set"))
: regionResolver.resolveRegionFromPresignedCredential(credential);
applyRegion(region);
if (rejectUnknownRegion(ctx, region, SigV4CredentialScope.serviceNameFromCredential(credential))) {
@@ -141,12 +163,12 @@ public class AccountContextFilter implements ContainerRequestFilter {
}
}
private String extractSessionToken(ContainerRequestContext ctx) {
private String extractSessionToken(ContainerRequestContext ctx, MultivaluedMap<String, String> query) {
String token = ctx.getHeaderString("X-Amz-Security-Token");
if (token != null && !token.isBlank()) {
return token.trim();
}
token = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Security-Token");
token = query.getFirst("X-Amz-Security-Token");
if (token != null && !token.isBlank()) {
return token.trim();
}
@@ -164,11 +186,12 @@ public class AccountContextFilter implements ContainerRequestFilter {
}
/** Refuses delimiters in region interpretations used by request context or downstream dispatch. */
private boolean rejectAmbiguousRegion(ContainerRequestContext ctx, String authorization) {
private boolean rejectAmbiguousRegion(ContainerRequestContext ctx, String authorization,
MultivaluedMap<String, String> query) {
String queryCredential = authorization == null || authorization.isBlank()
? ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential") : null;
? query.getFirst("X-Amz-Credential") : null;
String parsedAuthorization = queryCredential == null ? authorization
: IamEnforcementFilter.requestAuthorization(null, ctx.getUriInfo().getQueryParameters());
: IamEnforcementFilter.requestAuthorization(null, query);
// Some Query routes synthesize this header even without X-Amz-Algorithm. Inspect the
// same region they use, in addition to the split credential used by request context.
String region = regionResolver.resolveRegionFromAuthOrNull(parsedAuthorization);
@@ -195,7 +218,7 @@ public class AccountContextFilter implements ContainerRequestFilter {
private boolean rejectUnknownRegion(ContainerRequestContext ctx, String region, Optional<String> signingName) {
boolean ambiguous = RegionResolver.containsArnDelimiter(region);
if (!ambiguous && (RegionResolver.isKnownRegion(region)
|| configProvider.get().partitions().allowUnknownRegions())) {
|| config().partitions().allowUnknownRegions())) {
return false;
}
LOG.debugv("Refusing request signed for unknown region {0} (service {1}): {2} {3}",
@@ -247,7 +270,7 @@ public class AccountContextFilter implements ContainerRequestFilter {
* service in every partition.
*/
private void rejectPartitionAbsentService(ContainerRequestContext ctx, String signingName) {
if (signingName == null || !configProvider.get().partitions().strict()) {
if (signingName == null || !config().partitions().strict()) {
return;
}
Optional<AwsPartition> partition = AwsPartitions.find(requestContext.getPartition());
@@ -5,6 +5,7 @@ import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.ext.Provider;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
@@ -21,9 +22,20 @@ public class AwsDateHeaderFilter implements ContainerResponseFilter {
private static final DateTimeFormatter RFC_822 = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
private record DateHeader(long second, String text) { }
// The pair is replaced as a whole so a reader never mixes seconds.
private volatile DateHeader cached;
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
responseContext.getHeaders().putSingle("Date",
ZonedDateTime.now(GMT).format(RFC_822));
long now = System.currentTimeMillis() / 1000;
DateHeader header = cached;
if (header == null || header.second() != now) {
header = new DateHeader(now,
ZonedDateTime.ofInstant(Instant.ofEpochSecond(now), GMT).format(RFC_822));
cached = header;
}
responseContext.getHeaders().putSingle("Date", header.text());
}
}
@@ -47,6 +47,7 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
// Lazily resolved: JAX-RS providers are instantiated before runtime config
// mappings exist (same pattern as GlobalCorsFilter).
private final jakarta.inject.Provider<EmulatorConfig> configProvider;
private volatile EmulatorConfig config;
@Inject
public AwsProtocolClaimFilter(ProtocolClaimer claimer, ResolvedServiceCatalog catalog,
@@ -56,6 +57,15 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
this.configProvider = configProvider;
}
private EmulatorConfig config() {
EmulatorConfig resolved = config;
if (resolved == null) {
resolved = configProvider.get();
config = resolved;
}
return resolved;
}
@Override
public void filter(ContainerRequestContext ctx) {
ClaimSignals signals = ClaimSignals.from(ctx);
@@ -64,7 +74,7 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
if (claim.isEmpty()) {
LOG.warnv("Unclaimable RPC-signaled request: {0} {1} Content-Type={2} Smithy-Protocol={3}",
signals.method(), signals.path(), signals.contentType(), signals.smithyProtocol());
if (configProvider.get().protocols().strictClaiming()) {
if (config().protocols().strictClaiming()) {
ctx.abortWith(unknownOperationResponse(404,
"Unable to determine the wire protocol for this request"));
}
@@ -79,14 +89,14 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
.replacePath(AwsQueryController.QUERY_GET_PATH).build());
}
if (resolved.protocol() == WireProtocol.REST) {
refuseUnknownServiceScope(ctx, signals, catalog, configProvider.get());
refuseUnknownServiceScope(ctx, signals, catalog, config());
return;
}
if (resolved.protocol() == WireProtocol.RPCV2_JSON) {
LOG.warnv("Received rpc-v2-json request for service {0} operation {1} — protocol not implemented",
resolved.service() != null ? resolved.service().externalKey() : "unknown",
resolved.operation());
if (configProvider.get().protocols().strictClaiming()) {
if (config().protocols().strictClaiming()) {
ctx.abortWith(unknownOperationResponse(400,
"The rpc-v2-json protocol is not supported"));
}
@@ -7,6 +7,7 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
/**
* Adds AWS request-id response headers to every HTTP response.
@@ -56,6 +57,14 @@ public class AwsRequestIdFilter implements ContainerResponseFilter {
return value.toString();
}
}
return UUID.randomUUID().toString();
return newRequestId();
}
// A request id is not a secret, so it does not need SecureRandom.
private static String newRequestId() {
ThreadLocalRandom random = ThreadLocalRandom.current();
long high = (random.nextLong() & 0xFFFFFFFFFFFF0FFFL) | 0x0000000000004000L;
long low = (random.nextLong() & 0x3FFFFFFFFFFFFFFFL) | 0x8000000000000000L;
return new UUID(high, low).toString();
}
}
@@ -50,6 +50,8 @@ public class RegionResolver {
@Inject
Instance<RequestContext> requestContextInstance;
private volatile RequestContext requestContextProxy;
@Inject
public RegionResolver(EmulatorConfig config) {
this(config.defaultRegion(), config.defaultAccountId(),
@@ -244,6 +246,15 @@ public class RegionResolver {
return AwsPartitions.forRegion(region).map(AwsPartition::id).orElse(defaultPartition);
}
private RequestContext requestContext() {
RequestContext proxy = requestContextProxy;
if (proxy == null) {
proxy = requestContextInstance.get();
requestContextProxy = proxy;
}
return proxy;
}
/**
* The partition of the current request when called from a request context, or the
* deployment's partition otherwise (async workers, startup, tests).
@@ -251,7 +262,7 @@ public class RegionResolver {
public String getPartition() {
if (requestContextInstance != null) {
try {
String partition = requestContextInstance.get().getPartition();
String partition = requestContext().getPartition();
if (partition != null) {
return partition;
}
@@ -269,7 +280,7 @@ public class RegionResolver {
public String getRegion() {
if (requestContextInstance != null) {
try {
String region = requestContextInstance.get().getRegion();
String region = requestContext().getRegion();
if (region != null) {
return region;
}
@@ -287,7 +298,7 @@ public class RegionResolver {
public String getAccountId() {
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
String accountId = requestContext().getAccountId();
if (accountId != null) {
return accountId;
}
@@ -16,7 +16,11 @@ public final class RequestHost {
}
public static String of(ContainerRequestContext requestContext) {
return of(requestContext.getHeaderString("Host"), requestContext.getUriInfo().getRequestUri());
String hostHeader = requestContext.getHeaderString("Host");
if (hostHeader != null && !hostHeader.isBlank()) {
return hostHeader.trim();
}
return of(hostHeader, requestContext.getUriInfo().getRequestUri());
}
/**
@@ -125,6 +125,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
// Lazily resolved: JAX-RS providers are instantiated before runtime config mappings exist
// (the AwsProtocolClaimFilter pattern).
private final jakarta.inject.Provider<EmulatorConfig> configProvider;
private volatile EmulatorConfig config;
private final IamService iamService;
private final ResolvedServiceCatalog catalog;
private final CurrentVertxRequest currentVertxRequest;
@@ -142,9 +143,18 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
this.currentVertxRequest = currentVertxRequest;
}
private EmulatorConfig config() {
EmulatorConfig resolved = config;
if (resolved == null) {
resolved = configProvider.get();
config = resolved;
}
return resolved;
}
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
if (!configProvider.get().auth().validateSignatures()) {
if (!config().auth().validateSignatures()) {
return;
}
Class<?> resource = resourceInfo != null ? resourceInfo.getResourceClass() : null;
@@ -42,6 +42,7 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
private final StorageBackend<String, V> delegate;
private final Instance<RequestContext> requestContextInstance;
private volatile RequestContext requestContextProxy;
private final String defaultAccountId;
// Accounts that own keys here, so findAnyAccountEntry does one get per account instead of a scan.
@@ -141,6 +142,16 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
.collect(Collectors.toUnmodifiableSet());
}
@Override
public boolean isEmpty() {
// A store nothing has written answers without the key copy below.
if (delegate.isEmpty()) {
return true;
}
String prefix = prefix() + "/";
return delegate.keys().stream().noneMatch(k -> k.startsWith(prefix));
}
@Override
public void flush() {
delegate.flush();
@@ -591,10 +602,19 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return prefix();
}
private RequestContext requestContext() {
RequestContext proxy = requestContextProxy;
if (proxy == null) {
proxy = requestContextInstance.get();
requestContextProxy = proxy;
}
return proxy;
}
private String prefix() {
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
String accountId = requestContext().getAccountId();
if (accountId != null) {
return accountId;
}
@@ -96,6 +96,11 @@ public class HybridStorage<K, V> implements StorageBackend<K, V> {
return Set.copyOf(store.keySet());
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
@Override
public void flush() {
persistToDisk();
@@ -64,6 +64,11 @@ public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
return Set.copyOf(store.keySet());
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
@Override
public void flush() {
// No-op for in-memory storage
@@ -251,6 +251,11 @@ public class PartitionedFileStorage<E> implements StorageBackend<String, Map<Str
return Collections.unmodifiableSet(store.keySet());
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
/**
* Writes every dirty shard; in journal mode this is a compaction.
*
@@ -113,6 +113,11 @@ public class PersistentStorage<K, V> implements StorageBackend<K, V> {
return Set.copyOf(store.keySet());
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
@Override
public void flush() {
persistToDisk();
@@ -53,6 +53,11 @@ public interface StorageBackend<K, V> {
/** Return all keys in this store. */
Set<K> keys();
/** Whether the store holds no entries. */
default boolean isEmpty() {
return keys().isEmpty();
}
/** Persist data to disk if applicable. */
void flush();
@@ -211,6 +211,11 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
return Set.copyOf(store.keySet());
}
@Override
public boolean isEmpty() {
return store.isEmpty();
}
@Override
public void flush() {
compact();
@@ -447,6 +447,9 @@ public class CloudTrailService {
}
public void emitS3DataEvent(S3EventInput in) {
if (store.isEmpty()) {
return;
}
try {
String region = in.region() != null ? in.region() : regionResolver.getDefaultRegion();
List<MatchedTrail> matched = trailsMatching(region, in);
@@ -35,6 +35,23 @@ class AccountAwareStorageBackendTest {
assertEquals("111111111111", storage.accountId());
}
@Test
void isEmptyLooksOnlyAtTheCurrentAccount() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
AccountAwareStorageBackend<String> first =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
AccountAwareStorageBackend<String> second =
new AccountAwareStorageBackend<>(raw, null, "222222222222");
assertTrue(first.isEmpty());
assertTrue(second.isEmpty());
first.put("resource", "value");
assertFalse(first.isEmpty());
assertTrue(second.isEmpty());
}
@Test
void putAllPrefixesEveryEntryWithTheRequestScope() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
@@ -58,7 +58,13 @@ class CognitoSignUpCreationScopeTest {
void overlappingSignUpReservesOnlyTheSameAccountAndUsername(
boolean firstRequestIsAdmin, boolean differentAccount) throws Exception {
Instance<RequestContext> contexts = mock(Instance.class);
when(contexts.get()).thenAnswer(invocation -> requestContext.get());
// One context that forwards to the calling thread's, as the request scoped client proxy does.
when(contexts.get()).thenReturn(new RequestContext() {
@Override
public String getAccountId() {
return requestContext.get().getAccountId();
}
});
RegionResolver regionResolver = new RegionResolver("us-east-1", FIRST_ACCOUNT) {
@Override
public String getAccountId() {