mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(lambda): enforce reserved and per-region concurrency (#424)
* feat(lambda): enforce reserved concurrency at invocation time
Introduce LambdaConcurrencyLimiter using AtomicInteger + CAS. Acquire a
permit before invoke and release in finally for both sync and async
paths. DryRun skips enforcement. Functions without a reserved value are
not enforced in this step (account-pool enforcement will follow).
Reset inflight counters when a function is deleted to prevent leaks.
* test(lambda): use JUnit Assertions in LambdaConcurrencyLimiterTest
AssertJ is not on the unit-test classpath; switch to the Jupiter
assertions already used by sibling tests.
* feat(lambda): enforce account-wide concurrency pool and validate Put
Extend LambdaConcurrencyLimiter with an account-shared unreserved pool
sized as accountLimit - Σreserved. Functions without a reserved value
now share this pool; exhaustion returns TooManyRequestsException.
PutFunctionConcurrency rejects values that would leave less than
unreserved-concurrency-min (AWS default: 100) available, matching AWS's
LimitExceededException behavior.
Config: floci.services.lambda.account-concurrency-limit (default 1000)
and floci.services.lambda.unreserved-concurrency-min (default 100).
Docs and controller javadoc updated accordingly.
* feat(lambda): rehydrate reserved concurrency and handle throttle in pollers
On startup, LambdaService walks functionStore.listAll() and re-registers
reserved values with the limiter so validatePut and the unreserved pool
see the correct totals before the first Put of the session.
SQS/Kinesis/DynamoDB Streams pollers now catch TooManyRequestsException
explicitly. SQS lets messages return via visibility timeout; Kinesis and
DynamoDB Streams skip advancing the shard iterator, so records are
redelivered on the next poll.
* test(lambda): add SDK compatibility tests for concurrency enforcement
Verify end-to-end wire behavior: LimitExceededException on Put that
violates unreserved-min, TooManyRequestsException on Event invoke when
reserved=0, and DryRun bypassing the concurrency gate.
* fix(lambda): close concurrency races in limiter and rehydrate
- Recompute cap inside the unreserved CAS loop so concurrent setReserved
does not leave permits granted above the live pool.
- Replace validatePut + setReserved with a single validateAndSetReserved
guarded by a reservedLock; concurrent Puts for different functions
can no longer each pass validation against stale totals.
- Rehydrate only $LATEST entries so published versions do not
double-count into totalReserved().
* fix(lambda): address PR review feedback
- Partition limiter state by region. AWS Lambda concurrency is per
account-per-region; functions in different regions no longer share
the same reserved totals or unreserved pool.
- PutFunctionConcurrency and DeleteFunctionConcurrency now roll back
the limiter update if functionStore.save() fails, so limiter and
persisted state stay consistent.
- Replace the awkward (InvokeResult) null cast in the DynamoDB Streams
poller with a plain forward declaration.
* refactor(lambda): rename account-concurrency-limit to region-concurrency-limit
The limit applies per-region (AWS Lambda's "account-level" quota is
actually per-account-per-region). Rename the config key, field, and
accessor to match what the value controls, and clarify the doc note.
No functional change.
* fix(lambda): O(1) region total and compare-and-rollback on save failure
- Maintain per-region AtomicInteger running total of reserved values,
updated under reservedLock on every mutation. acquireUnreserved reads
the cap in O(1) without iterating the map, eliminating the weakly-
consistent partial-sum window that existed when reads happened off
the lock while writes were serialized.
- Replace unconditional rollback with rollbackReservedIfExpected: the
limiter only restores the previous value if the current entry still
matches what the caller wrote, so a concurrent successful Put cannot
be clobbered by an earlier request's rollback after its save fails.
* docs(lambda): scrub remaining account-wide wording and document drain semantics
Replace lingering "account-wide" / "account pool" phrasing with
per-region terminology in the controller javadoc and unit-test comment.
Two references remain by design: EmulatorConfig and the lambda service
doc quote AWS's own "account-level" label to explain the renamed key.
Also fold two follow-up review items into this change:
- Replace fully-qualified AwsException / InvokeResult references in the
SQS, Kinesis, and DynamoDB Streams pollers with normal imports.
- Document that reducing or clearing a reserved value does not kill
already-inflight invocations, mirroring AWS behavior and causing a
brief drain window where total inflight may exceed the region limit.
* fix(lambda): serialize Put/Delete per function and preserve busy inflight
- Wrap PutFunctionConcurrency and DeleteFunctionConcurrency in a
per-function lock so concurrent requests for the same ARN can't
interleave the limiter update and the store save in a way that
leaves them out of sync.
- Retain the inflight counter on reset when permits are still open,
so an ARN recreated under load sees the remaining inflight rather
than starting fresh and briefly allowing more than reserved capacity.
Idle counters (value 0) are still dropped to prevent leaks.
- Tests now close acquired permits via try-with-resources and cover
both the retain-while-busy and drop-when-idle reset behaviors.
* test(lambda): close all permits via try-with-resources
Close the acquire() result in regions_areIndependent so the test leaves
no inflight state behind and accurately asserts both the exhausted and
recovered cases.
* perf(lambda): avoid regex split in regionOf on the invoke hot path
regionOf() runs on every acquire/release. Replace String.split(":"),
which uses regex and allocates an array, with a single pass that finds
the fourth ':' segment and returns a substring — same semantics, no
allocation beyond the returned region string.
* fix(lambda): keep per-function lock map and tighten compat assertion
- deleteFunction no longer removes the per-function entry from
concurrencyOpLocks. Removing it could race with a concurrent
Put/Delete still synchronized on the old lock object, letting the
next request create a fresh lock and run in parallel — defeating
the very serialization the map provides. The map grows by one
Object per deleted function, acceptable for a local emulator.
- LambdaConcurrencyTest now asserts the wire-level error identity
(400 status + "LimitExceededException" errorCode) for the Put
rejection. The Lambda SDK v2 model does not declare a typed
LimitExceededException class, so wire-level assertions catch
protocol-fidelity regressions more precisely than the previous
generic LambdaException check.
* fix(lambda): retain inflight counter on reset and allow over-committed reductions
- reset() no longer drops idle inflight counters. The previous
counter.get()==0 + remove pattern races with a concurrent
acquireReserved that has already obtained the AtomicInteger
reference and is about to increment it: a successful remove
between those two moments would leave the next acquire to
allocate a fresh counter and silently undercount inflight,
permitting reserved over-subscription.
- validateAndSetReserved now allows any value <= the function's
current reservation unconditionally. Reductions cannot worsen
unreserved capacity, so blocking them in an already over-committed
state (e.g. after lowering region-concurrency-limit at runtime)
prevented operators from recovering. Increases still go through
the unreserved-min check.
* fix(lambda): take per-function lock in deleteFunction
A concurrent deleteFunction + Put/DeleteFunctionConcurrency for the
same ARN could interleave the limiter reset and the store delete,
leaving the limiter holding (or clearing) state for a function the
store no longer knows about. Wrap the limiter+store mutations in the
same lockForConcurrencyOp(arn) used by the concurrency endpoints.
Tighten the surrounding comment so it describes the current code
rather than the lock-removal call that earlier revisions used to have.
* test(lambda): wire a real concurrency limiter into the test constructor
The package-private LambdaService constructor used by unit tests passed
null for concurrencyLimiter, so the null-guards in
putFunctionConcurrency / deleteFunctionConcurrency / deleteFunction made
those paths silently skip validation and limiter bookkeeping under tests.
That hid divergence from production behavior.
Construct a default LambdaConcurrencyLimiter (AWS defaults: 1000 / 100)
in the test ctor so the same enforcement runs in unit tests.
* test(lambda): cover concurrent PutFunctionConcurrency for the same ARN
Verify that the per-function lock in LambdaService serializes racing
Puts so the limiter and the functionStore always agree on whichever
write landed last. 50 iterations across two threads against the same
function exercise the lock discipline and assert store/limiter
consistency on every iteration.
* docs: document reserved concurrency config keys
- docs/services/lambda.md: drop redundant "(enforced at invocation)"
from the PutFunctionConcurrency table entry (the admonition below
already explains enforcement); add region-concurrency-limit and
unreserved-concurrency-min to the Configuration YAML sample.
- docs/configuration/application-yml.md: mirror the two new keys in
the top-level reference sample so every known lambda setting is
discoverable in one place.
* refactor(lambda): address review feedback (A)
- LambdaServiceTest.concurrentPutFunctionConcurrency now asserts against
limiter.totalReserved(region) instead of getFunctionConcurrency(), which
read the same field as the value under test. The new assertion actually
proves the limiter and the persisted store stayed in agreement.
- Expose a package-private concurrencyLimiter() accessor on LambdaService
so tests can inspect limiter state without reflection.
- Drop unused Permit.NOOP: the reserved=null path now runs through
acquireUnreserved and always returns a real decrement closure.
- Document the intentional unbounded growth of the inflight counter map
(race avoidance on reset) and concurrencyOpLocks (race avoidance on
deleteFunction). Both are acceptable for a local emulator workload.
* test(lambda): add rehydrate, multi-ARN race, and qualified-invoke coverage
- LambdaServiceTest.rehydrateConcurrency_restoresReservedFromStore
prepopulates a LambdaFunctionStore with reserved values, builds a
fresh LambdaService over it, and verifies totalReserved(region) goes
from 0 to the expected sum after the @PostConstruct hook runs.
- LambdaServiceTest.multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention
races two Puts on different ARNs that would together push the region
below unreserved-min. reservedLock must let exactly one win; the
other must fail with LimitExceededException and the limiter's total
must reflect only the winning reservation.
- Compat LambdaConcurrencyTest.invoke_withVersionQualifier_stillHonorsReservedOnLatest
publishes a version, sets reserved=0, and invokes with the qualifier
set. Today Floci drops the qualifier and routes to $LATEST, so the
reservation throttles the call. This test locks the behavior in: a
future qualifier-routing change must either copy the reservation onto
the snapshot or key the limiter off the base ARN to keep it green.
* refactor(lambda): idempotent permits, warn on malformed ARN, more tests
- Wrap acquire()/release() counter closures in an AtomicBoolean guard so
a double-close of a Permit can never drive the inflight counter
negative. Future callers that mix try-with-resources with explicit
close, or that add retry logic around invoke, stay safe by default.
- regionOf() now warns once per unique malformed input instead of
silently coalescing everything into "unknown". The first occurrence
is logged so a bug that passes a bare function name into the limiter
is debuggable without spamming the log.
- New LambdaServiceTest.putFunctionConcurrency_rollsBackLimiterIfSaveFails
injects a failing LambdaFunctionStore and verifies the limiter total
is restored when functionStore.save throws.
- New LambdaServiceTest.deleteFunction_preservesInflightPermitUntilItCloses
holds a permit through a deleteFunction call and asserts the inflight
counter stays live until the permit is closed.
- New LambdaConcurrencyLimiterTest.permit_closeIsIdempotent locks in the
double-close guarantee.
This commit is contained in:
1 parent
38eb0125a9
commit
fb26731131
14 files changed
+1111
-31
No files matched your search
@@ -509,6 +509,22 @@ public interface EmulatorConfig {
|
||||
|
||||
/** Docker network to attach Lambda containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* Concurrent executions ceiling applied per region. AWS Lambda's
|
||||
* "account-level" concurrency is in fact a per-region quota (default 1000);
|
||||
* Floci mirrors that semantics and partitions counters by the region
|
||||
* segment of each function ARN.
|
||||
*/
|
||||
@WithDefault("1000")
|
||||
int regionConcurrencyLimit();
|
||||
|
||||
/**
|
||||
* Minimum unreserved concurrency that must remain after PutFunctionConcurrency,
|
||||
* matching AWS (100). Puts that would leave less than this are rejected.
|
||||
*/
|
||||
@WithDefault("100")
|
||||
int unreservedConcurrencyMin();
|
||||
}
|
||||
|
||||
interface Ec2ServiceConfig {
|
||||
|
||||
+13
-1
@@ -1,10 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
@@ -129,7 +131,17 @@ public class DynamoDbStreamsEventSourcePoller {
|
||||
esm.getUuid(), records.size(), esm.getFunctionName());
|
||||
|
||||
String eventJson = buildDynamoDbEvent(records, esm);
|
||||
var invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
InvokeResult invokeResult;
|
||||
try {
|
||||
invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
} catch (AwsException e) {
|
||||
if ("TooManyRequestsException".equals(e.getErrorCode())) {
|
||||
LOG.infov("DynamoDB Streams ESM {0}: function {1} throttled, shard iterator not advanced",
|
||||
esm.getUuid(), fn.getFunctionName());
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (invokeResult.getFunctionError() == null) {
|
||||
String newestSeq = records.get(records.size() - 1).getSequenceNumber();
|
||||
|
||||
+13
-2
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
|
||||
@@ -118,8 +119,18 @@ public class KinesisEventSourcePoller {
|
||||
|
||||
if (!records.isEmpty()) {
|
||||
String eventJson = buildKinesisEvent(records, esm, shard.getShardId());
|
||||
InvokeResult invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
|
||||
InvokeResult invokeResult;
|
||||
try {
|
||||
invokeResult = executorService.invoke(fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
} catch (AwsException e) {
|
||||
if ("TooManyRequestsException".equals(e.getErrorCode())) {
|
||||
LOG.infov("Kinesis ESM {0}: function {1} throttled, shard iterator not advanced",
|
||||
esm.getUuid(), fn.getFunctionName());
|
||||
continue;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (invokeResult.getFunctionError() == null) {
|
||||
String newestSeq = records.get(records.size() - 1).getSequenceNumber();
|
||||
esm.getShardSequenceNumbers().put(shard.getShardId(), newestSeq);
|
||||
|
||||
+3
-2
@@ -30,8 +30,9 @@ import java.util.Map;
|
||||
* The class-level {@code @Path("/")} lets each method declare its own absolute
|
||||
* version prefix rather than inheriting a single one.
|
||||
*
|
||||
* The stored value is not enforced at invocation time — this is a stub so that
|
||||
* tools and SDKs expecting the endpoint to exist can proceed.
|
||||
* The stored value is enforced at invocation time by
|
||||
* {@link LambdaConcurrencyLimiter}; Put also validates against the per-region
|
||||
* unreserved-minimum.
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Enforces Lambda concurrency limits at invocation time.
|
||||
*
|
||||
* <p>AWS Lambda concurrency is scoped to an account <b>per region</b>; a
|
||||
* function's reserved value does not compete with functions in other regions.
|
||||
* Accordingly this limiter partitions its state by region (extracted from the
|
||||
* function ARN), and the configured {@code regionLimit}/{@code unreservedMin}
|
||||
* apply independently to each region.
|
||||
*
|
||||
* <p>Two layers of enforcement:
|
||||
* <ul>
|
||||
* <li><b>Reserved (per-function)</b>: when a function has a reserved value,
|
||||
* inflight invocations are counted against that value and do not consume
|
||||
* the region's unreserved pool.</li>
|
||||
* <li><b>Unreserved (region-shared)</b>: functions without a reserved value
|
||||
* share {@code regionLimit - Σreserved} permits within their region.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaConcurrencyLimiter {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaConcurrencyLimiter.class);
|
||||
/** Tracks malformed ARNs already logged so the warn fires once per unique input. */
|
||||
private static final Set<String> LOGGED_MALFORMED_ARNS =
|
||||
Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
|
||||
/**
|
||||
* Inflight counts per function ARN (globally unique). Entries are
|
||||
* retained even when the count drops to zero — see {@link #reset} for
|
||||
* the race this avoids. The map therefore grows by one entry per
|
||||
* distinct ARN the limiter has ever seen, including entries left over
|
||||
* from functions that have been deleted and recreated under a new
|
||||
* name. For a local emulator the resulting footprint is negligible.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, AtomicInteger> inflight = new ConcurrentHashMap<>();
|
||||
/** Reserved values partitioned by region. */
|
||||
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Integer>> reservedByRegion
|
||||
= new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Running sum of {@link #reservedByRegion} values per region. Maintained
|
||||
* under {@link #reservedLock} on every mutation so that unreserved
|
||||
* acquisition can read a consistent cap in O(1).
|
||||
*/
|
||||
private final ConcurrentHashMap<String, AtomicInteger> regionReservedTotal = new ConcurrentHashMap<>();
|
||||
/** Unreserved inflight counters partitioned by region. */
|
||||
private final ConcurrentHashMap<String, AtomicInteger> unreservedByRegion = new ConcurrentHashMap<>();
|
||||
/** Guards atomic validate-then-set and rollback operations on the reserved state. */
|
||||
private final Object reservedLock = new Object();
|
||||
private final int regionLimit;
|
||||
private final int unreservedMin;
|
||||
|
||||
@Inject
|
||||
public LambdaConcurrencyLimiter(EmulatorConfig config) {
|
||||
this(config.services().lambda().regionConcurrencyLimit(),
|
||||
config.services().lambda().unreservedConcurrencyMin());
|
||||
}
|
||||
|
||||
/** Test-only constructor with explicit limits. */
|
||||
LambdaConcurrencyLimiter(int regionLimit, int unreservedMin) {
|
||||
this.regionLimit = regionLimit;
|
||||
this.unreservedMin = unreservedMin;
|
||||
}
|
||||
|
||||
/** Test-only no-arg constructor using AWS defaults (1000 / 100). */
|
||||
LambdaConcurrencyLimiter() {
|
||||
this(1000, 100);
|
||||
}
|
||||
|
||||
public Permit acquire(LambdaFunction fn) {
|
||||
Integer r = fn.getReservedConcurrentExecutions();
|
||||
String region = regionOf(fn.getFunctionArn());
|
||||
if (r == null) {
|
||||
return acquireUnreserved(region);
|
||||
}
|
||||
return acquireReserved(fn.getFunctionArn(), r);
|
||||
}
|
||||
|
||||
private Permit acquireReserved(String key, int limit) {
|
||||
AtomicInteger counter = inflight.computeIfAbsent(key, k -> new AtomicInteger());
|
||||
while (true) {
|
||||
int current = counter.get();
|
||||
if (current >= limit) {
|
||||
throw throttle();
|
||||
}
|
||||
if (counter.compareAndSet(current, current + 1)) {
|
||||
return idempotentPermit(counter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Permit acquireUnreserved(String region) {
|
||||
AtomicInteger counter = unreservedByRegion.computeIfAbsent(region, k -> new AtomicInteger());
|
||||
AtomicInteger reservedTotal = regionTotal(region);
|
||||
while (true) {
|
||||
int current = counter.get();
|
||||
// reservedTotal is an AtomicInteger updated under reservedLock on
|
||||
// each reserved change, so the cap is consistent and computed in
|
||||
// O(1) regardless of the number of reserved functions.
|
||||
int cap = Math.max(0, regionLimit - reservedTotal.get());
|
||||
if (current >= cap) {
|
||||
throw throttle();
|
||||
}
|
||||
if (counter.compareAndSet(current, current + 1)) {
|
||||
return idempotentPermit(counter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps {@code counter.decrementAndGet()} in a close-once guard so a
|
||||
* future caller that accidentally double-closes a permit cannot drive
|
||||
* the inflight counter negative.
|
||||
*/
|
||||
private static Permit idempotentPermit(AtomicInteger counter) {
|
||||
AtomicBoolean closed = new AtomicBoolean(false);
|
||||
return () -> {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
counter.decrementAndGet();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register (or update) a function's reserved value without validation.
|
||||
* Intended for startup rehydration from persisted state.
|
||||
*
|
||||
* @return the previous value, or {@code null} if none was set.
|
||||
*/
|
||||
public Integer setReserved(String functionArn, int value) {
|
||||
synchronized (reservedLock) {
|
||||
return writeReserved(functionArn, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the cleared value, or {@code null} if no reservation was set.
|
||||
*/
|
||||
public Integer clearReserved(String functionArn) {
|
||||
synchronized (reservedLock) {
|
||||
return writeReserved(functionArn, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically validates and applies a reserved value within the function's
|
||||
* region. Two concurrent Puts for different functions cannot each pass
|
||||
* validation against stale totals and then collectively push the region's
|
||||
* unreserved capacity below the minimum.
|
||||
*
|
||||
* @return the previous reserved value for this ARN, or {@code null} if none;
|
||||
* callers may use it with {@link #rollbackReservedIfExpected} on a
|
||||
* subsequent persistence failure.
|
||||
* @throws AwsException {@code LimitExceededException} if the value would
|
||||
* drop unreserved below the minimum.
|
||||
*/
|
||||
public Integer validateAndSetReserved(String functionArn, int target) {
|
||||
String region = regionOf(functionArn);
|
||||
synchronized (reservedLock) {
|
||||
ConcurrentHashMap<String, Integer> regionReserved = reservedOf(region);
|
||||
int currentForThis = regionReserved.getOrDefault(functionArn, 0);
|
||||
// A reduction (or no-op) cannot decrease unreserved capacity any
|
||||
// further than it already is, so always allow it. This lets
|
||||
// operators recover from an over-committed state — e.g. after
|
||||
// lowering region-concurrency-limit at runtime — without first
|
||||
// having to delete every reservation.
|
||||
if (target > currentForThis) {
|
||||
int otherReserved = regionTotal(region).get() - currentForThis;
|
||||
int maxAllowed = regionLimit - unreservedMin - otherReserved;
|
||||
if (target > maxAllowed) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"Specified ReservedConcurrentExecutions for function decreases account's "
|
||||
+ "UnreservedConcurrentExecution below its minimum value of ["
|
||||
+ unreservedMin + "].", 400);
|
||||
}
|
||||
}
|
||||
return writeReserved(functionArn, target);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Conditionally restores a prior reserved value if the current value still
|
||||
* matches {@code expectedCurrent}. Used by callers that updated the limiter
|
||||
* before a persistence step and need to undo the change on failure without
|
||||
* clobbering a concurrent successful write.
|
||||
*/
|
||||
public void rollbackReservedIfExpected(String functionArn,
|
||||
Integer expectedCurrent,
|
||||
Integer rollbackTo) {
|
||||
synchronized (reservedLock) {
|
||||
Integer actual = reservedOf(regionOf(functionArn)).get(functionArn);
|
||||
if (!Objects.equals(actual, expectedCurrent)) {
|
||||
// A newer update has superseded ours; leave it alone.
|
||||
return;
|
||||
}
|
||||
writeReserved(functionArn, rollbackTo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the reserved entry for a deleted function. The inflight counter
|
||||
* is intentionally retained — permits held by still-running invocations
|
||||
* decrement into it on close, and an ARN recreated later reuses the same
|
||||
* counter so new invocations correctly see any remaining inflight.
|
||||
*
|
||||
* <p>The counter is also retained even when it momentarily reads zero:
|
||||
* conditionally removing it would race with a concurrent
|
||||
* {@code acquireReserved} that has already obtained the {@code AtomicInteger}
|
||||
* reference and is about to increment it. After such a race the next
|
||||
* acquire would allocate a fresh counter and undercount the inflight
|
||||
* permit, allowing reserved over-subscription. The trade-off is one
|
||||
* {@code AtomicInteger} per historical function, which is bounded for an
|
||||
* emulator workload.
|
||||
*/
|
||||
public void reset(String functionArn) {
|
||||
synchronized (reservedLock) {
|
||||
writeReserved(functionArn, null);
|
||||
}
|
||||
}
|
||||
|
||||
public int totalReserved(String region) {
|
||||
return regionTotal(region).get();
|
||||
}
|
||||
|
||||
public int availableUnreserved(String region) {
|
||||
AtomicInteger counter = unreservedByRegion.get(region);
|
||||
int inflightNow = counter == null ? 0 : counter.get();
|
||||
return Math.max(0, regionLimit - totalReserved(region) - inflightNow);
|
||||
}
|
||||
|
||||
int inflightCount(String functionArn) {
|
||||
AtomicInteger counter = inflight.get(functionArn);
|
||||
return counter == null ? 0 : counter.get();
|
||||
}
|
||||
|
||||
int unreservedInflightCount(String region) {
|
||||
AtomicInteger counter = unreservedByRegion.get(region);
|
||||
return counter == null ? 0 : counter.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called with {@link #reservedLock} held. Updates the per-function
|
||||
* reserved entry and the region's running total in one atomic step from the
|
||||
* perspective of any code that also holds the lock.
|
||||
*/
|
||||
private Integer writeReserved(String functionArn, Integer newValue) {
|
||||
String region = regionOf(functionArn);
|
||||
ConcurrentHashMap<String, Integer> regionReserved = reservedOf(region);
|
||||
Integer previous = newValue == null
|
||||
? regionReserved.remove(functionArn)
|
||||
: regionReserved.put(functionArn, newValue);
|
||||
int delta = (newValue == null ? 0 : newValue) - (previous == null ? 0 : previous);
|
||||
if (delta != 0) {
|
||||
regionTotal(region).addAndGet(delta);
|
||||
}
|
||||
return previous;
|
||||
}
|
||||
|
||||
private ConcurrentHashMap<String, Integer> reservedOf(String region) {
|
||||
return reservedByRegion.computeIfAbsent(region, k -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
private AtomicInteger regionTotal(String region) {
|
||||
return regionReservedTotal.computeIfAbsent(region, k -> new AtomicInteger());
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the region segment from a Lambda function ARN. Falls back to
|
||||
* {@code "unknown"} if the ARN is malformed so state still partitions
|
||||
* cleanly rather than mixing with another region's data.
|
||||
*
|
||||
* <p>This is called on every acquire/release, so the parse avoids the
|
||||
* regex machinery and array allocation of {@code String.split(":")} by
|
||||
* scanning for the fourth ':' segment (index 3 in an ARN:
|
||||
* {@code arn:aws:lambda:REGION:account:function:name}).
|
||||
*/
|
||||
private static String regionOf(String arn) {
|
||||
if (arn == null) {
|
||||
warnMalformed("<null>");
|
||||
return "unknown";
|
||||
}
|
||||
int segmentStart = 0;
|
||||
int delimiters = 0;
|
||||
for (int i = 0; i < arn.length(); i++) {
|
||||
if (arn.charAt(i) == ':') {
|
||||
if (delimiters == 2) {
|
||||
segmentStart = i + 1;
|
||||
} else if (delimiters == 3) {
|
||||
return arn.substring(segmentStart, i);
|
||||
}
|
||||
delimiters++;
|
||||
}
|
||||
}
|
||||
warnMalformed(arn);
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
private static void warnMalformed(String arn) {
|
||||
if (LOGGED_MALFORMED_ARNS.add(arn)) {
|
||||
LOG.warnv("Concurrency limiter received non-ARN function identifier "
|
||||
+ "\"{0}\"; bucketing under region=\"unknown\". This likely "
|
||||
+ "indicates a bare function name reached the limiter.", arn);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException throttle() {
|
||||
return new AwsException("TooManyRequestsException", "Rate Exceeded.", 429);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Permit extends AutoCloseable {
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
}
|
||||
+30
-11
@@ -32,6 +32,7 @@ public class LambdaExecutorService {
|
||||
|
||||
private final WarmPool warmPool;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final LambdaConcurrencyLimiter concurrencyLimiter;
|
||||
private final ExecutorService asyncExecutor = new ThreadPoolExecutor(
|
||||
Math.max(4, Runtime.getRuntime().availableProcessors() * 2),
|
||||
Math.max(8, Runtime.getRuntime().availableProcessors() * 4),
|
||||
@@ -40,25 +41,43 @@ public class LambdaExecutorService {
|
||||
new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
|
||||
@Inject
|
||||
public LambdaExecutorService(WarmPool warmPool, ObjectMapper objectMapper) {
|
||||
public LambdaExecutorService(WarmPool warmPool,
|
||||
ObjectMapper objectMapper,
|
||||
LambdaConcurrencyLimiter concurrencyLimiter) {
|
||||
this.warmPool = warmPool;
|
||||
this.objectMapper = objectMapper;
|
||||
this.concurrencyLimiter = concurrencyLimiter;
|
||||
}
|
||||
|
||||
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
|
||||
switch (type) {
|
||||
case DryRun -> {
|
||||
return new InvokeResult(204, null, new byte[0], null, requestId);
|
||||
}
|
||||
case Event -> {
|
||||
asyncExecutor.submit(() -> executeSync(fn, payload, requestId));
|
||||
return new InvokeResult(202, null, new byte[0], null, requestId);
|
||||
}
|
||||
default -> {
|
||||
return executeSync(fn, payload, requestId);
|
||||
if (type == InvocationType.DryRun) {
|
||||
return new InvokeResult(204, null, new byte[0], null, requestId);
|
||||
}
|
||||
|
||||
LambdaConcurrencyLimiter.Permit permit = concurrencyLimiter.acquire(fn);
|
||||
|
||||
if (type == InvocationType.Event) {
|
||||
try {
|
||||
asyncExecutor.submit(() -> {
|
||||
try {
|
||||
executeSync(fn, payload, requestId);
|
||||
} finally {
|
||||
permit.close();
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
permit.close();
|
||||
throw e;
|
||||
}
|
||||
return new InvokeResult(202, null, new byte[0], null, requestId);
|
||||
}
|
||||
|
||||
try {
|
||||
return executeSync(fn, payload, requestId);
|
||||
} finally {
|
||||
permit.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -43,6 +44,7 @@ public class LambdaService {
|
||||
|
||||
private final LambdaFunctionStore functionStore;
|
||||
private final LambdaExecutorService executorService;
|
||||
private final LambdaConcurrencyLimiter concurrencyLimiter;
|
||||
private final WarmPool warmPool;
|
||||
private final CodeStore codeStore;
|
||||
private final ZipExtractor zipExtractor;
|
||||
@@ -56,8 +58,28 @@ public class LambdaService {
|
||||
private final KinesisEventSourcePoller kinesisPoller;
|
||||
private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
|
||||
private final ConcurrentHashMap<String, Integer> versionCounters = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Per-function locks covering PutFunctionConcurrency,
|
||||
* DeleteFunctionConcurrency, and deleteFunction itself. Serializing the
|
||||
* limiter update + persistence pair against itself for a given function
|
||||
* prevents the limiter and store from diverging on interleaved concurrent
|
||||
* requests.
|
||||
*
|
||||
* <p>Entries are intentionally never removed — see {@code deleteFunction}
|
||||
* for the race this avoids. The map therefore grows by one {@code Object}
|
||||
* per distinct function ARN the emulator has ever seen (create/delete
|
||||
* cycles with fresh names included). Acceptable footprint for a local
|
||||
* emulator workload.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, Object> concurrencyOpLocks = new ConcurrentHashMap<>();
|
||||
|
||||
/** Package-private constructor for testing without CDI. Config defaults (timeout=3, memory=128) apply. */
|
||||
/**
|
||||
* Package-private constructor for testing without CDI. Config defaults
|
||||
* (timeout=3, memory=128) apply. A real {@link LambdaConcurrencyLimiter}
|
||||
* with AWS-default limits is wired so concurrency operations exercise
|
||||
* the same validation and bookkeeping as production rather than
|
||||
* silently no-op'ing past null checks.
|
||||
*/
|
||||
LambdaService(LambdaFunctionStore functionStore,
|
||||
WarmPool warmPool,
|
||||
CodeStore codeStore,
|
||||
@@ -65,6 +87,7 @@ public class LambdaService {
|
||||
RegionResolver regionResolver) {
|
||||
this.functionStore = functionStore;
|
||||
this.executorService = null;
|
||||
this.concurrencyLimiter = new LambdaConcurrencyLimiter();
|
||||
this.warmPool = warmPool;
|
||||
this.codeStore = codeStore;
|
||||
this.zipExtractor = zipExtractor;
|
||||
@@ -82,6 +105,7 @@ public class LambdaService {
|
||||
@Inject
|
||||
public LambdaService(LambdaFunctionStore functionStore,
|
||||
LambdaExecutorService executorService,
|
||||
LambdaConcurrencyLimiter concurrencyLimiter,
|
||||
WarmPool warmPool,
|
||||
CodeStore codeStore,
|
||||
ZipExtractor zipExtractor,
|
||||
@@ -96,6 +120,7 @@ public class LambdaService {
|
||||
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller) {
|
||||
this.functionStore = functionStore;
|
||||
this.executorService = executorService;
|
||||
this.concurrencyLimiter = concurrencyLimiter;
|
||||
this.warmPool = warmPool;
|
||||
this.codeStore = codeStore;
|
||||
this.zipExtractor = zipExtractor;
|
||||
@@ -110,6 +135,40 @@ public class LambdaService {
|
||||
this.dynamodbStreamsPoller = dynamodbStreamsPoller;
|
||||
}
|
||||
|
||||
/** Package-private accessor for tests that want to assert limiter state directly. */
|
||||
LambdaConcurrencyLimiter concurrencyLimiter() {
|
||||
return concurrencyLimiter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rehydrates reserved concurrency into the limiter from persisted function state.
|
||||
* Without this, restarts leave {@code totalReserved()=0} and allow validatePut /
|
||||
* unreserved-pool sizing to drift until each function is re-Put.
|
||||
*/
|
||||
@PostConstruct
|
||||
void rehydrateConcurrency() {
|
||||
if (concurrencyLimiter == null) {
|
||||
return;
|
||||
}
|
||||
int count = 0;
|
||||
for (LambdaFunction fn : functionStore.listAll()) {
|
||||
// Reserved concurrency is a function-level property; published
|
||||
// versions share the $LATEST record's value. Skip non-$LATEST
|
||||
// entries to avoid double-counting into totalReserved().
|
||||
if (!"$LATEST".equals(fn.getVersion())) {
|
||||
continue;
|
||||
}
|
||||
Integer reserved = fn.getReservedConcurrentExecutions();
|
||||
if (reserved != null) {
|
||||
concurrencyLimiter.setReserved(fn.getFunctionArn(), reserved);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
LOG.infov("Restored reserved concurrency for {0} function(s)", count);
|
||||
}
|
||||
}
|
||||
|
||||
public LambdaFunction createFunction(String region, Map<String, Object> request) {
|
||||
String functionName = (String) request.get("FunctionName");
|
||||
String role = (String) request.get("Role");
|
||||
@@ -230,10 +289,23 @@ public class LambdaService {
|
||||
}
|
||||
|
||||
public void deleteFunction(String region, String functionName) {
|
||||
getFunction(region, functionName); // throws 404 if not found
|
||||
LambdaFunction fn = getFunction(region, functionName); // throws 404 if not found
|
||||
String arn = fn.getFunctionArn();
|
||||
warmPool.drainFunction(functionName);
|
||||
codeStore.delete(functionName);
|
||||
functionStore.delete(region, functionName);
|
||||
// Take the same per-function lock used by Put/DeleteFunctionConcurrency
|
||||
// so a concurrent concurrency mutation cannot interleave with the
|
||||
// limiter reset and store delete and leave the two views out of sync.
|
||||
// The lock entry itself stays in the map after the delete: removing it
|
||||
// could race with another thread already synchronized on the same
|
||||
// object, letting a follow-up request allocate a fresh lock and run
|
||||
// in parallel — the very serialization this map exists to prevent.
|
||||
synchronized (lockForConcurrencyOp(arn)) {
|
||||
if (concurrencyLimiter != null) {
|
||||
concurrencyLimiter.reset(arn);
|
||||
}
|
||||
codeStore.delete(functionName);
|
||||
functionStore.delete(region, functionName);
|
||||
}
|
||||
LOG.infov("Deleted Lambda function: {0}", functionName);
|
||||
}
|
||||
|
||||
@@ -597,8 +669,29 @@ public class LambdaService {
|
||||
"ReservedConcurrentExecutions must be a non-negative integer", 400);
|
||||
}
|
||||
LambdaFunction fn = getFunction(region, functionName);
|
||||
fn.setReservedConcurrentExecutions(reservedConcurrentExecutions);
|
||||
functionStore.save(region, fn);
|
||||
String arn = fn.getFunctionArn();
|
||||
// Serialize limiter update + store save for this function so that two
|
||||
// concurrent Puts cannot leave the limiter and persisted state out of
|
||||
// sync, regardless of which call acquires the reservedLock first.
|
||||
synchronized (lockForConcurrencyOp(arn)) {
|
||||
Integer previousReserved = null;
|
||||
boolean limiterUpdated = false;
|
||||
if (concurrencyLimiter != null) {
|
||||
previousReserved = concurrencyLimiter.validateAndSetReserved(
|
||||
arn, reservedConcurrentExecutions);
|
||||
limiterUpdated = true;
|
||||
}
|
||||
fn.setReservedConcurrentExecutions(reservedConcurrentExecutions);
|
||||
try {
|
||||
functionStore.save(region, fn);
|
||||
} catch (RuntimeException e) {
|
||||
if (limiterUpdated) {
|
||||
concurrencyLimiter.rollbackReservedIfExpected(
|
||||
arn, reservedConcurrentExecutions, previousReserved);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
|
||||
@@ -609,8 +702,29 @@ public class LambdaService {
|
||||
|
||||
public void deleteFunctionConcurrency(String region, String functionName) {
|
||||
LambdaFunction fn = getFunction(region, functionName);
|
||||
fn.setReservedConcurrentExecutions(null);
|
||||
functionStore.save(region, fn);
|
||||
String arn = fn.getFunctionArn();
|
||||
synchronized (lockForConcurrencyOp(arn)) {
|
||||
Integer previousReserved = null;
|
||||
boolean limiterCleared = false;
|
||||
if (concurrencyLimiter != null) {
|
||||
previousReserved = concurrencyLimiter.clearReserved(arn);
|
||||
limiterCleared = true;
|
||||
}
|
||||
fn.setReservedConcurrentExecutions(null);
|
||||
try {
|
||||
functionStore.save(region, fn);
|
||||
} catch (RuntimeException e) {
|
||||
if (limiterCleared && previousReserved != null) {
|
||||
concurrencyLimiter.rollbackReservedIfExpected(
|
||||
arn, null, previousReserved);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Object lockForConcurrencyOp(String functionArn) {
|
||||
return concurrencyOpLocks.computeIfAbsent(functionArn, k -> new Object());
|
||||
}
|
||||
|
||||
public LambdaFunction getFunctionByUrlId(String urlId) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
@@ -146,8 +147,18 @@ public class SqsEventSourcePoller {
|
||||
|
||||
String eventJson = buildSqsEvent(messages, esm);
|
||||
LOG.infov("ESM {0}: invoking function {1}", esm.getUuid(), fn.getFunctionName());
|
||||
InvokeResult result = executorService.invoke(
|
||||
fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
InvokeResult result;
|
||||
try {
|
||||
result = executorService.invoke(
|
||||
fn, eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
} catch (AwsException e) {
|
||||
if ("TooManyRequestsException".equals(e.getErrorCode())) {
|
||||
LOG.infov("ESM {0}: function {1} throttled, messages will return to queue after visibility timeout",
|
||||
esm.getUuid(), fn.getFunctionName());
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (result.getFunctionError() == null) {
|
||||
Set<String> failedIds = extractBatchItemFailures(esm, result);
|
||||
|
||||
Reference in new issue
Block a user