mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+261
@@ -0,0 +1,261 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class LambdaConcurrencyLimiterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OTHER_REGION = "ap-northeast-1";
|
||||
private static final String ARN = "arn:aws:lambda:us-east-1:000000000000:function:fn";
|
||||
private static final String ARN2 = "arn:aws:lambda:us-east-1:000000000000:function:other";
|
||||
private static final String ARN_OTHER_REGION = "arn:aws:lambda:ap-northeast-1:000000000000:function:fn-apne1";
|
||||
|
||||
private LambdaFunction fn(String arn, Integer reserved) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("fn");
|
||||
fn.setFunctionArn(arn);
|
||||
fn.setReservedConcurrentExecutions(reserved);
|
||||
return fn;
|
||||
}
|
||||
|
||||
private LambdaFunction fn(Integer reserved) {
|
||||
return fn(ARN, reserved);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsetReserved_countsAgainstAccountPool() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(2, 0);
|
||||
LambdaConcurrencyLimiter.Permit p1 = limiter.acquire(fn(null));
|
||||
LambdaConcurrencyLimiter.Permit p2 = limiter.acquire(fn(null));
|
||||
AwsException ex = assertThrows(AwsException.class, () -> limiter.acquire(fn(null)));
|
||||
assertEquals(429, ex.getHttpStatus());
|
||||
p1.close();
|
||||
p2.close();
|
||||
assertEquals(0, limiter.unreservedInflightCount(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedN_allowsUpToN_thenThrows() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
LambdaFunction f = fn(2);
|
||||
LambdaConcurrencyLimiter.Permit p1 = limiter.acquire(f);
|
||||
LambdaConcurrencyLimiter.Permit p2 = limiter.acquire(f);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> limiter.acquire(f));
|
||||
assertEquals("TooManyRequestsException", ex.getErrorCode());
|
||||
assertEquals(429, ex.getHttpStatus());
|
||||
|
||||
p1.close();
|
||||
LambdaConcurrencyLimiter.Permit p3 = limiter.acquire(f);
|
||||
p2.close();
|
||||
p3.close();
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedZero_throwsImmediately() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> limiter.acquire(fn(0)));
|
||||
assertEquals(429, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedPool_doesNotConsumeUnreserved() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(3, 0);
|
||||
limiter.setReserved(ARN, 2);
|
||||
// Reserved function consumes its own pool, not the region pool
|
||||
try (LambdaConcurrencyLimiter.Permit p1 = limiter.acquire(fn(ARN, 2));
|
||||
LambdaConcurrencyLimiter.Permit p2 = limiter.acquire(fn(ARN, 2));
|
||||
// Unreserved function can still use the full regionLimit - totalReserved = 1
|
||||
LambdaConcurrencyLimiter.Permit p3 = limiter.acquire(fn(ARN2, null))) {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> limiter.acquire(fn(ARN2, null)));
|
||||
assertEquals(429, ex.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reset_preservesInflightCounterWhenBusy() {
|
||||
// If a function is deleted while invocations are still running, and the
|
||||
// same ARN is recreated, new invocations must see the remaining inflight
|
||||
// so we don't transiently over-subscribe.
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
LambdaFunction before = fn(3);
|
||||
LambdaConcurrencyLimiter.Permit held = limiter.acquire(before);
|
||||
assertEquals(1, limiter.inflightCount(ARN));
|
||||
|
||||
limiter.reset(ARN);
|
||||
assertEquals(1, limiter.inflightCount(ARN), "inflight retained while permit is open");
|
||||
|
||||
LambdaFunction recreated = fn(3);
|
||||
try (LambdaConcurrencyLimiter.Permit p2 = limiter.acquire(recreated)) {
|
||||
assertEquals(2, limiter.inflightCount(ARN));
|
||||
}
|
||||
held.close();
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reset_keepsIdleInflightCounterToAvoidUndercount() {
|
||||
// The counter is intentionally retained across reset to close the
|
||||
// window where a concurrent acquire could otherwise allocate a fresh
|
||||
// counter and undercount inflight permits already in flight.
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
try (LambdaConcurrencyLimiter.Permit p = limiter.acquire(fn(1))) {
|
||||
assertEquals(1, limiter.inflightCount(ARN));
|
||||
}
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
limiter.reset(ARN);
|
||||
// Counter still present at zero; new acquires share it.
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
try (LambdaConcurrencyLimiter.Permit p = limiter.acquire(fn(1))) {
|
||||
assertEquals(1, limiter.inflightCount(ARN));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateAndSetReserved_allowsReductionEvenWhenOverCommitted() {
|
||||
// Simulate an over-committed state: total reserved exceeds the
|
||||
// unreserved minimum's ceiling. (e.g. region-concurrency-limit was
|
||||
// lowered at runtime, or state was migrated from earlier behavior.)
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(1000, 100);
|
||||
// Bypass validation by using setReserved directly so we can engineer
|
||||
// the broken state that validateAndSetReserved should still let us recover from.
|
||||
limiter.setReserved(ARN, 950);
|
||||
// Now totalReserved=950, unreserved capacity = 50 < min(100). Any
|
||||
// increase should still be blocked.
|
||||
assertThrows(AwsException.class, () -> limiter.validateAndSetReserved(ARN, 951));
|
||||
// But a reduction must succeed so the operator can recover.
|
||||
assertDoesNotThrow(() -> limiter.validateAndSetReserved(ARN, 500));
|
||||
assertEquals(500, limiter.totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatePut_rejectsWhenUnreservedMinViolated() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(1000, 100);
|
||||
// totalReserved=0, max allowed for new function = 1000 - 100 = 900
|
||||
assertDoesNotThrow(() -> limiter.validateAndSetReserved(ARN, 900));
|
||||
AwsException ex = assertThrows(AwsException.class, () -> limiter.validateAndSetReserved(ARN, 901));
|
||||
assertEquals("LimitExceededException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatePut_excludesSelfWhenUpdating() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(1000, 100);
|
||||
limiter.setReserved(ARN, 500);
|
||||
// Updating the same ARN to 900 should succeed (self is excluded from "other")
|
||||
assertDoesNotThrow(() -> limiter.validateAndSetReserved(ARN, 900));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatePut_considersOtherFunctions() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(1000, 100);
|
||||
limiter.setReserved(ARN2, 500);
|
||||
// otherReserved=500, max for ARN = 1000 - 100 - 500 = 400
|
||||
assertDoesNotThrow(() -> limiter.validateAndSetReserved(ARN, 400));
|
||||
assertThrows(AwsException.class, () -> limiter.validateAndSetReserved(ARN, 401));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reset_clearsReservedEntry() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
limiter.setReserved(ARN, 1);
|
||||
limiter.reset(ARN);
|
||||
assertEquals(0, limiter.totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setReserved_returnsPreviousValue() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
assertNull(limiter.setReserved(ARN, 5));
|
||||
assertEquals(5, limiter.setReserved(ARN, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearReserved_returnsClearedValue() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
limiter.setReserved(ARN, 7);
|
||||
assertEquals(7, limiter.clearReserved(ARN));
|
||||
assertNull(limiter.clearReserved(ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackReservedIfExpected_restoresWhenUnchanged() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
limiter.setReserved(ARN, 5);
|
||||
limiter.setReserved(ARN, 10); // now at 10
|
||||
limiter.rollbackReservedIfExpected(ARN, 10, 5);
|
||||
assertEquals(5, limiter.totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackReservedIfExpected_skipsWhenConcurrentlyChanged() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
// Request A wrote 10 (previous null), then another request superseded to 20
|
||||
limiter.setReserved(ARN, 10);
|
||||
limiter.setReserved(ARN, 20);
|
||||
// A's rollback expects 10 still present — must not clobber 20
|
||||
limiter.rollbackReservedIfExpected(ARN, 10, null);
|
||||
assertEquals(20, limiter.totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void totalReserved_tracksOverlappingUpdates() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
limiter.setReserved(ARN, 50);
|
||||
limiter.setReserved(ARN2, 30);
|
||||
assertEquals(80, limiter.totalReserved(REGION));
|
||||
limiter.setReserved(ARN, 100); // +50
|
||||
assertEquals(130, limiter.totalReserved(REGION));
|
||||
limiter.clearReserved(ARN2); // -30
|
||||
assertEquals(100, limiter.totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void permit_closeIsIdempotent() {
|
||||
// Future callers must not be able to drive the inflight counter
|
||||
// negative by double-closing a permit (try-with-resources +
|
||||
// explicit close, retry logic, etc.).
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter();
|
||||
LambdaConcurrencyLimiter.Permit p = limiter.acquire(fn(3));
|
||||
assertEquals(1, limiter.inflightCount(ARN));
|
||||
p.close();
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
p.close(); // second close must be a no-op
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
p.close(); // ...and so must the third
|
||||
assertEquals(0, limiter.inflightCount(ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void regions_areIndependent() {
|
||||
LambdaConcurrencyLimiter limiter = new LambdaConcurrencyLimiter(1000, 100);
|
||||
// Fill one region's reserved pool near the limit
|
||||
limiter.validateAndSetReserved(ARN, 900);
|
||||
// Another region starts fresh — Put up to 900 still allowed
|
||||
assertDoesNotThrow(() -> limiter.validateAndSetReserved(ARN_OTHER_REGION, 900));
|
||||
assertEquals(900, limiter.totalReserved(REGION));
|
||||
assertEquals(900, limiter.totalReserved(OTHER_REGION));
|
||||
|
||||
// Unreserved pool is also per-region
|
||||
LambdaConcurrencyLimiter small = new LambdaConcurrencyLimiter(1, 0);
|
||||
try (LambdaConcurrencyLimiter.Permit usEast = small.acquire(fn(ARN, null));
|
||||
LambdaConcurrencyLimiter.Permit apne1 = small.acquire(fn(ARN_OTHER_REGION, null))) {
|
||||
// Same exhaustion in us-east-1, but ap-northeast-1 has its own slot
|
||||
// (already consumed by apne1 above, so second acquire there also throws)
|
||||
assertThrows(AwsException.class, () -> small.acquire(fn(ARN2, null)));
|
||||
assertThrows(AwsException.class, () -> small.acquire(fn(ARN_OTHER_REGION, null)));
|
||||
}
|
||||
// After close, both regions have capacity again
|
||||
try (LambdaConcurrencyLimiter.Permit reacquire = small.acquire(fn(ARN, null))) {
|
||||
assertEquals(1, small.unreservedInflightCount(REGION));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,4 +237,195 @@ class LambdaServiceTest {
|
||||
LambdaFunction updated = service.updateFunctionCode(REGION, "update-fn", Map.of());
|
||||
assertNotEquals(originalRevision, updated.getRevisionId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rehydrateConcurrency_restoresReservedFromStore() {
|
||||
// Simulate a persisted state: functions already live in the store
|
||||
// with reserved values before the limiter is populated.
|
||||
service.createFunction(REGION, baseRequest("persisted-a"));
|
||||
service.createFunction(REGION, baseRequest("persisted-b"));
|
||||
service.putFunctionConcurrency(REGION, "persisted-a", 300);
|
||||
service.putFunctionConcurrency(REGION, "persisted-b", 200);
|
||||
|
||||
// Build a second service over the same store with a fresh limiter.
|
||||
LambdaFunctionStore store = new LambdaFunctionStore(new InMemoryStorage<>());
|
||||
// Copy the two persisted functions into the new store to emulate a
|
||||
// restart with the same disk state.
|
||||
for (LambdaFunction fn : new java.util.ArrayList<>(
|
||||
service.listFunctions(REGION))) {
|
||||
store.save(REGION, fn);
|
||||
}
|
||||
LambdaService rebooted = new LambdaService(store, new WarmPool(),
|
||||
new CodeStore(Path.of("target/test-data/lambda-code")),
|
||||
new ZipExtractor(), new RegionResolver(REGION, "000000000000"));
|
||||
|
||||
// Starts empty…
|
||||
assertEquals(0, rebooted.concurrencyLimiter().totalReserved(REGION));
|
||||
// …until rehydrate walks the store and re-registers the reserved values.
|
||||
rebooted.rehydrateConcurrency();
|
||||
assertEquals(500, rebooted.concurrencyLimiter().totalReserved(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention() throws Exception {
|
||||
// Two different functions racing a Put near the unreserved floor.
|
||||
// Both try to reserve an amount that — summed — would push the
|
||||
// region below unreserved-min. reservedLock must serialize so that
|
||||
// only one wins.
|
||||
service.createFunction(REGION, baseRequest("multi-a"));
|
||||
service.createFunction(REGION, baseRequest("multi-b"));
|
||||
|
||||
// Defaults: regionLimit=1000, unreservedMin=100. Each Put asks for
|
||||
// 500; together they would leave 0 unreserved.
|
||||
java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newFixedThreadPool(2);
|
||||
java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1);
|
||||
try {
|
||||
java.util.concurrent.Future<Throwable> fA = pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
service.putFunctionConcurrency(REGION, "multi-a", 500);
|
||||
return null;
|
||||
} catch (Throwable t) { return t; }
|
||||
});
|
||||
java.util.concurrent.Future<Throwable> fB = pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
service.putFunctionConcurrency(REGION, "multi-b", 500);
|
||||
return null;
|
||||
} catch (Throwable t) { return t; }
|
||||
});
|
||||
start.countDown();
|
||||
|
||||
Throwable rA = fA.get();
|
||||
Throwable rB = fB.get();
|
||||
|
||||
// Exactly one must have been rejected with LimitExceededException.
|
||||
int successes = (rA == null ? 1 : 0) + (rB == null ? 1 : 0);
|
||||
assertEquals(1, successes, "exactly one Put must win");
|
||||
Throwable rejected = rA != null ? rA : rB;
|
||||
assertTrue(rejected instanceof AwsException
|
||||
&& "LimitExceededException".equals(((AwsException) rejected).getErrorCode()),
|
||||
"other Put must be rejected, got " + rejected);
|
||||
assertEquals(500,
|
||||
service.concurrencyLimiter().totalReserved(REGION),
|
||||
"limiter total must reflect only the winning Put");
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void putFunctionConcurrency_rollsBackLimiterIfSaveFails() {
|
||||
// If functionStore.save throws after the limiter has been updated,
|
||||
// the limiter must be restored so Σreserved stays consistent with
|
||||
// what the store actually persisted.
|
||||
FailingStore failing = new FailingStore();
|
||||
LambdaService svc = new LambdaService(failing, new WarmPool(),
|
||||
new CodeStore(Path.of("target/test-data/lambda-code")),
|
||||
new ZipExtractor(), new RegionResolver(REGION, "000000000000"));
|
||||
svc.createFunction(REGION, baseRequest("rb-fn"));
|
||||
// Baseline: Put of 300 succeeds
|
||||
svc.putFunctionConcurrency(REGION, "rb-fn", 300);
|
||||
assertEquals(300, svc.concurrencyLimiter().totalReserved(REGION));
|
||||
|
||||
// Now make the next save() explode and try to Put 500
|
||||
failing.shouldFail = true;
|
||||
assertThrows(RuntimeException.class,
|
||||
() -> svc.putFunctionConcurrency(REGION, "rb-fn", 500));
|
||||
|
||||
// Limiter must have rolled back to the previous 300
|
||||
assertEquals(300, svc.concurrencyLimiter().totalReserved(REGION),
|
||||
"limiter must unwind on save failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFunction_preservesInflightPermitUntilItCloses() {
|
||||
// A deleteFunction that lands while an invocation is still holding a
|
||||
// permit must not drop the counter — the permit close() at the end
|
||||
// of the running invocation still has to decrement something valid.
|
||||
service.createFunction(REGION, baseRequest("del-inflight"));
|
||||
service.putFunctionConcurrency(REGION, "del-inflight", 2);
|
||||
|
||||
LambdaFunction fn = service.getFunction(REGION, "del-inflight");
|
||||
String arn = fn.getFunctionArn();
|
||||
LambdaConcurrencyLimiter.Permit held =
|
||||
service.concurrencyLimiter().acquire(fn);
|
||||
assertEquals(1, service.concurrencyLimiter().inflightCount(arn));
|
||||
|
||||
service.deleteFunction(REGION, "del-inflight");
|
||||
|
||||
// Reserved is cleared from the limiter, but the inflight counter
|
||||
// must still be live for the held permit to decrement into.
|
||||
assertEquals(0, service.concurrencyLimiter().totalReserved(REGION));
|
||||
assertEquals(1, service.concurrencyLimiter().inflightCount(arn),
|
||||
"inflight must survive delete until the permit closes");
|
||||
|
||||
held.close();
|
||||
assertEquals(0, service.concurrencyLimiter().inflightCount(arn));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test helper: a LambdaFunctionStore whose save() throws on demand so
|
||||
* tests can exercise the LambdaService rollback path.
|
||||
*/
|
||||
private static final class FailingStore extends LambdaFunctionStore {
|
||||
boolean shouldFail = false;
|
||||
FailingStore() {
|
||||
super(new InMemoryStorage<String, LambdaFunction>());
|
||||
}
|
||||
@Override
|
||||
public void save(String region, LambdaFunction fn) {
|
||||
if (shouldFail) {
|
||||
throw new RuntimeException("injected save failure");
|
||||
}
|
||||
super.save(region, fn);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentPutFunctionConcurrency_endsInConsistentState() throws Exception {
|
||||
// Exercise the per-function serialization in concurrencyOpLocks:
|
||||
// two threads racing Put on the same function must leave the
|
||||
// limiter and the persisted reserved value in agreement with
|
||||
// whichever write landed last.
|
||||
service.createFunction(REGION, baseRequest("race-fn"));
|
||||
|
||||
int iterations = 50;
|
||||
java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
int a = 100 + i;
|
||||
int b = 200 + i;
|
||||
java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1);
|
||||
java.util.concurrent.Future<Integer> fA = pool.submit(() -> {
|
||||
start.await();
|
||||
return service.putFunctionConcurrency(REGION, "race-fn", a)
|
||||
.getReservedConcurrentExecutions();
|
||||
});
|
||||
java.util.concurrent.Future<Integer> fB = pool.submit(() -> {
|
||||
start.await();
|
||||
return service.putFunctionConcurrency(REGION, "race-fn", b)
|
||||
.getReservedConcurrentExecutions();
|
||||
});
|
||||
start.countDown();
|
||||
fA.get();
|
||||
fB.get();
|
||||
|
||||
LambdaFunction fn = service.getFunction(REGION, "race-fn");
|
||||
Integer stored = fn.getReservedConcurrentExecutions();
|
||||
assertTrue(stored.equals(a) || stored.equals(b),
|
||||
"store should reflect one of the two writes, got " + stored);
|
||||
// The real invariant: the limiter's Σreserved for this
|
||||
// region must agree with what was persisted. Comparing
|
||||
// getFunctionConcurrency() to stored would be a tautology —
|
||||
// both read the same LambdaFunction field — so assert
|
||||
// against the limiter's independently-maintained total.
|
||||
assertEquals(stored.intValue(),
|
||||
service.concurrencyLimiter().totalReserved(REGION),
|
||||
"limiter totalReserved must match persisted reserved value");
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user