* fix(lambda): restore create-copy-start ordering for provided runtimes
The refactor in #466 changed ContainerLauncher from create → copy →
start to createAndStart → copy, breaking provided.* runtimes whose
entrypoint execs /var/runtime/bootstrap immediately on start — before
the file has been copied in.
Split ContainerLifecycleManager into create(spec) and
startCreated(containerId, spec) so ContainerLauncher can copy code and
the bootstrap file into the container filesystem before starting it.
Other services (ECS, ECR, EKS, MSK, ElastiCache, RDS) continue using
createAndStart since they have no pre-start file copy requirement.
Fixes#494
* test(lambda): verify create-copy-start ordering for provided runtimes
Update ContainerLauncherTest to use the new create/startCreated API
and add two ordering tests:
- launchFunction_createsBeforeCopyAndStartsAfter: verifies the
create → copy → startCreated sequence for any runtime using
Mockito InOrder.
- launchProvidedRuntime_copiesBootstrapBeforeStart: verifies the same
ordering specifically for provided.al2023 with a bootstrap file,
and asserts createAndStart is never called. This is the exact
regression from #466 that caused exit 127.
* refactor: delegate createAndStart to create + startCreated
Eliminate duplicated container-creation logic by making createAndStart
a thin delegate to create(spec) + startCreated(containerId, spec).
Future fixes to either step now apply to both call paths automatically.
* test(lambda): add SDK compatibility test for provided runtime invoke
Create and invoke a provided.al2023 function using the shell-based
bootstrap from LambdaUtils.providedRuntimeZip(). Asserts the response
contains the expected payload without timeout or FunctionError.
This test fails on 1.5.4 (Read timed out after 120s due to the
create-start ordering regression in #466) and passes on the fix.
* docs: add @param to create() and rename misleading test
- Add missing @param spec tag to ContainerLifecycleManager.create()
for consistency with surrounding methods.
- Rename launchFunctionCopiesCode to launchFunction_createsWithoutBindMounts
to reflect what the test actually asserts. Remove the getDockerClient
verify that didn't prove code copying.
* test(lambda): stub Docker copy chain and add cleanup for provided runtime test
- Stub dockerClient.copyArchiveToContainerCmd → withRemotePath →
withTarInputStream so copy operations execute against the mock
instead of throwing silently. Ordering tests now verify actual
Docker copy invocations between create and startCreated.
- Provided runtime test asserts both /var/task and /var/runtime
remote paths were targeted.
- Add sdk-test-provided-fn to @AfterAll cleanup in LambdaTest so
assertion failures don't leak the function across test runs.
* test(lambda): drain tar InputStream in copy mock to prevent thread leaks
Each copy mock now returns a fresh CopyArchiveToContainerCmd that
drains the PipedInputStream on exec(), so the background tar writer
thread can complete instead of blocking when the pipe buffer fills.
Remote paths are captured via the mock's withRemotePath answer and
asserted from the shared list.
Also adds sdk-test-provided-fn to @AfterAll cleanup in the compat
test to prevent function leaks on assertion failure.
* refactor(lambda): drop unused ContainerInfo variable from launch
The return value of startCreated() was assigned but never read.
Remove the variable and its now-unused import.
* test(lambda): include getDockerClient in InOrder verification
Add the getDockerClient() call between create() and
copyArchiveToContainerCmd() in both ordering tests so the verified
sequence matches the actual call flow in ContainerLauncher.launch().
* style: remove redundant doAnswer import
The wildcard import already covers it.
PutRecord and PutRecords were hardcoding "shardId-000000000000" in responses
regardless of which shard the record was routed to. Storage-side routing
(selectShard) was already picking the correct shard; only the handler response
was wrong.
Add PutRecordResult record and putRecordWithShardId method that exposes the
resolved shard to handlers. Keep the existing putRecord(...) String overload
for internal callers (KinesisStreamingForwarder, tests) to avoid churn.
Fixes cross-shard distribution assertions in downstream SDK tests.
Shutdown hooks could not reach Floci's HTTP endpoint (e.g.
`aws --endpoint-url http://localhost:4566 ...`) because they ran in
the ShutdownEvent observer, which Quarkus fires only AFTER the HTTP
server has already stopped.
Split the lifecycle:
- onPreShutdown(@Observes ShutdownDelayInitiatedEvent) runs stop hooks
while the HTTP server is still accepting connections.
- onStop(@Observes ShutdownEvent) handles resource cleanup only.
Enable the pre-shutdown phase via `quarkus.shutdown.delay-enabled:
true`. No `delay` value is set, so observers run synchronously with
no artificial sleep introduced.
Swallow all hook failures (including InterruptedException) without
restoring the interrupt flag, so the subsequent ShutdownEvent cleanup
phase always runs with a clean thread state and resource shutdown is
guaranteed even when hooks fail.
Fixesfloci-io/floci#431
* fix(ses): store text and html body separately and return raw as RawData
The inspection endpoint (/_aws/ses) previously collapsed bodyHtml and
bodyText into a single field, making both text_part and html_part
identical. Split SentEmail.body into bodyText and bodyHtml so the
inspection response correctly distinguishes the two, with null for the
absent part — matching LocalStack 4.14.0 behavior.
Raw emails now use a dedicated rawData field and constructor. The
inspection endpoint returns RawData (the full MIME message) without
Destination, Subject, or Body fields, matching LocalStack's shape.
Tests: 4 new integration tests covering text+html separation, text-only
(html_part=null), html-only (text_part=null), and raw email (RawData
without Body/Subject/Destination).
* fix(ses): parse and store ReplyToAddresses
ReplyToAddresses was silently dropped on both SES v1 (Query) and v2
(REST JSON) send paths. Parse it from the request, store it on
SentEmail, and return it in the inspection endpoint (/_aws/ses) for
non-raw emails. The field is omitted when empty, matching LocalStack
behavior.
* fix(ses): return all regions in inspection endpoint
LocalStack's /_aws/ses returns emails from all regions regardless of
request headers, with each message carrying its own Region field.
Floci previously filtered by the default region, hiding emails sent
to other regions.
- Add region field to SentEmail, set on send.
- SesInspectionController GET now calls getAllEmails() (no region
filter) and reads region from each email.
- DELETE clears all regions.
* refactor(ses): remove unused RegionResolver and use putNull for region
SesInspectionController no longer filters by region, so the injected
RegionResolver is dead code. Remove it and align the null-region
handling with other optional fields (putNull instead of empty string).
* fix(ses): use bulk clear and add v1 ReplyToAddresses test
- clearAllEmails() now calls emailStore.clear() instead of deleting
entries one-by-one, avoiding N disk writes on persistent backends.
- New SesIntegrationTest covering the SES v1 Query path for
ReplyToAddresses: sends via SendEmail with ReplyToAddresses.member.1
and verifies round-trip through the /_aws/ses inspection endpoint.
* refactor(ses): simplify getEmails/clearEmails to region-agnostic
The inspection endpoint now returns all regions unconditionally, so
the region-scoped getEmails(region) and clearEmails(region) are dead
code. Replace them with parameter-less getEmails() and clearEmails(),
and drop the intermediate getAllEmails/clearAllEmails aliases.
* fix(ses): add backward-compat alias for legacy Body field and multi-region test
- @JsonAlias("Body") on bodyText so persisted SentEmail objects from
before the text/html split still deserialize their body into bodyText
rather than silently losing it.
- New test: send emails in two different regions (us-east-1 and
ap-northeast-1) and verify /_aws/ses returns both with correct
per-message Region values.
* refactor(ses): move region and replyToAddresses into SentEmail constructors
Both fields were set via setters immediately after construction, which
is inconsistent with the other fields that are constructor arguments.
Add them to the Simple and Raw constructors so all required state is
established at creation time.
* refactor(ses): align sendEmail parameter order with SentEmail constructor
Move region to the first parameter position so the argument order
matches the SentEmail constructor (messageId, region, source, to, cc,
bcc, replyTo, subject, bodyText, bodyHtml). No functional change.
* refactor(ses): remove unused RegionResolver and validate rawMessage
- SesService no longer uses RegionResolver (region is always passed as
a parameter from controllers). Remove the field, constructor parameter,
and import.
- sendRawEmail now rejects null/blank rawMessage with
InvalidParameterValue, preventing a stored email that would appear
as non-raw in the inspection endpoint.
* fix(ses): validate source in sendRawEmail
sendRawEmail lacked the null/blank check on source that sendEmail
already had, allowing stored messages with Source=null and a 200
response. Add the same guard for consistency.
* refactor(ses): remove unused EmulatorConfig from SesService constructor
The config parameter was injected but never referenced.
* revert: restore EmulatorConfig in SesService constructor
Removing the unused EmulatorConfig parameter caused an awscli compat
test failure (SES: verify identities deleted). The parameter likely
influences Quarkus CDI initialization ordering — StorageFactory may
depend on EmulatorConfig being resolved first. Restore with
@SuppressWarnings("unused") to document intent.
* fix(ses): omit empty CcAddresses and BccAddresses from inspection response
LocalStack omits these keys when the list is empty rather than returning
an empty array. Apply the same !isEmpty() guard already used for
ReplyToAddresses.
* fix(ses): omit empty ToAddresses and restore region parameter order
- Apply the same !isEmpty() guard to ToAddresses so it is omitted from
the inspection response when empty, consistent with CcAddresses,
BccAddresses, and ReplyToAddresses.
- Revert sendEmail parameter order: move region back to the last
position to match the convention used by all other SesService methods
(verifyEmailIdentity, deleteIdentity, listIdentities, etc.).
* refactor(ses): remove unused EmulatorConfig from SesService constructor
The config parameter was injected but never referenced. A previous
attempt to remove it (76d6c22) was reverted due to a CI failure, but
that failure may have been flaky (S3 Notifications queue filter
round-trip, a known pre-existing issue). Retrying after rebase onto
latest main.
PersistentStorage, HybridStorage, and WalStorage used Stream.toList(),
which returns an unmodifiable list in Java 16+. InMemoryStorage built an
ArrayList, so callers that mutate the scan result work in unit tests
(all using in-memory backend) but fail at runtime on persistent backends.
This was the root cause of #482: CloudWatchLogsService.describeLogGroups
calls result.sort(...) on the scan result, which throws
UnsupportedOperationException when running against any non-memory store.
Same latent bug at CloudWatchLogsService.getLogEvents and
CognitoService.listGroups (callers copy into ArrayList first, so they
happen to work).
Rather than patch the two call sites, align all StorageBackend
implementations on a documented "returns a new mutable list" contract.
Tests added to each backend to lock in the behavior.
- Add normalize() + startsWith(bucketDir) guards to resolveObjectPath
and resolveVersionedPath in S3Service (primary defense)
- Add controller-level validateKeyNoTraversal mirroring the service
pattern with try/catch for InvalidPathException (null bytes → 400)
- Add validateRawUri to catch percent-encoded traversal (%2e%2e)
before Vert.x normalization strips it
- Strip leading slashes from keys before filesystem resolution to
allow legitimate S3 keys like /file.txt without escaping the bucket
- Add integration tests for %2e%2e, %00, and %2E%2E vectors
asserting 400 InvalidKey
- Add unit tests for service-layer traversal rejection
* fix(kms): support ECC_SECG_P256K1 via BouncyCastle JCA
use BC for EC keygen, KeyFactory, and Signature on ECC_* specs. Add test.
* fix(kms): support ECC_SECG_P256K1 via BouncyCastle JCA
* fix: support arithmetic in DynamoDB SET expressions
SET expressions like `SET cnt = cnt + :inc` or
`SET cnt = if_not_exists(cnt, :start) + :inc` silently ignored
the arithmetic operator - only the left operand was assigned.
Add `findArithmeticOperator()` to locate `+`/`-` outside function
parentheses, and evaluate both operands via `evaluateSetExpr` with
BigDecimal arithmetic.
Closes#479
* fix: address review - path-aware evaluateSetExpr, proper error handling
- Make evaluateSetExpr use hasValueAtPath/getValueAtPath for nested
path support (e.g. SET a.b = a.b + :inc)
- Throw ValidationException for non-numeric operands instead of
silent no-op
- Catch NumberFormatException on BigDecimal parsing
* fix: add integration and compatibility tests for SET arithmetic
- Add DynamoDbIntegrationTest for if_not_exists + arithmetic (repro from #479)
- Add Java SDK compatibility test covering increment, consecutive
increments, and subtraction
The Go AWS SDK v2 (used by Terraform AWS provider v6.x) percent-encodes
the colons and slashes of the resource ARN in the request path. Our
path param matcher left the value encoded, so extractBucketName's
lastIndexOf(":bucket/") never matched and every tag call returned 400.
On top of that, S3 Control is a REST-XML protocol but AwsExceptionMapper
emits JSON. The Go SDK's XML deserializer choked on the JSON body with
"XML syntax error on line 1: unexpected EOF", masking the real error.
Fix:
- URL-decode the ARN path param before parsing; malformed percent-
encoding is turned into an InvalidRequest 400 instead of propagating
IllegalArgumentException to the JSON mapper
- Catch AwsException in each S3 Control handler and serialize it as an
S3-style <Error> XML body (mirrors the pattern S3Controller already
uses)
Fixes the regression #341/#363 missed because the Java SDK compat test
sends literal colons and slashes.
* feat(lambda): support ScalingConfig.MaximumConcurrency on SQS event source mappings
Wire-level support for ScalingConfig on CreateEventSourceMapping,
UpdateEventSourceMapping, GetEventSourceMapping, and
ListEventSourceMappings:
- New ScalingConfig model carrying MaximumConcurrency (Integer, nullable).
- Create and Update parse ScalingConfig from the request, validate range
(2-1000), reject non-SQS event sources with InvalidParameterValueException.
- Response includes ScalingConfig only when a cap is set; omitted when
null, matching AWS behavior.
- Update with an empty ScalingConfig clears the cap (AWS reset semantics).
The value is persisted on the EventSourceMapping but not yet enforced at
invocation time — the SQS poller today serializes to one concurrent
invocation per ESM regardless. Real parallel dispatch capped by
MaximumConcurrency is a follow-up (Scope B).
Tests:
- EsmIntegrationTest: 6 new cases covering round-trip, below/above range
rejection, non-SQS rejection, omission when unset, add-then-clear via
update.
- LambdaEsmScalingConfigTest (SDK compat): 5 cases verifying SDK typed
ScalingConfig round-trips, InvalidParameterValueException on range
violations, and add/clear lifecycle via update.
* fix(lambda): reject non-integer MaximumConcurrency and ScalingConfig on non-SQS sources
- parseScalingConfig now detects fractional values (e.g. 2.5) and
returns InvalidParameterValueException instead of silently truncating.
- Empty ScalingConfig ({}) on a non-SQS event source is now rejected.
Previously the non-SQS check only fired when MaximumConcurrency was
non-null, so an empty ScalingConfig on Kinesis / DynamoDB Streams
slipped through.
- Two new integration tests cover both cases.
* fix(lambda): tighten ScalingConfig input validation
- Reject non-object ScalingConfig (e.g. "foo", []) with 400 instead of
silently treating it as absent. In update paths this previously cleared
an existing cap unintentionally.
- Reject non-numeric MaximumConcurrency (e.g. string "7"). AWS expects a
JSON number on the wire; the previous toString + parseInt path accepted
strings that real AWS would reject.
- Use longValue() before range-checking to avoid intValue() overflow on
large inputs (e.g. 5000000000) that would produce a negative value and
a misleading error message.
- Two new integration tests: string MaximumConcurrency and non-object
ScalingConfig.
* fix(lambda): add NaN/Infinity guard and expand ScalingConfig test coverage
- parseScalingConfig now explicitly rejects NaN and Infinity rather than
letting them fall through to longValue() with a misleading error.
- The post-range non-SQS guard was flagged as dead code by the reviewer
but is in fact reachable (non-SQS + valid numeric MaximumConcurrency).
Retained and confirmed by the existing @Order(43) test.
- New tests: update range validation (below/above on PUT), and list
with mixed ScalingConfig presence across ESMs.
* feat(kinesis): implement UpdateStreamMode
UpdateStreamMode previously returned 400 UnsupportedOperation. The
terraform-provider-aws calls UpdateStreamMode unconditionally on every
refresh of an aws_kinesis_stream resource, so the second `terraform
apply` errored even though the stream was functional.
Changes:
- Add UpdateStreamMode handler. Resolves the stream by StreamARN (the
AWS API does not accept StreamName here), validates StreamMode is
PROVISIONED or ON_DEMAND, requires the stream to be ACTIVE, and
treats same-mode requests as a no-op so terraform refresh succeeds.
Same-mode no-op mirrors the IncreaseStreamRetentionPeriod behaviour
introduced in #342 for the same reason.
- Honor StreamModeDetails.StreamMode in CreateStream.
- Emit StreamModeDetails on DescribeStream and DescribeStreamSummary
responses so terraform refresh observes the actual mode and stops
re-planning the resource.
Closes#440
* chore: retrigger CI (flaky S3 notifications test)
LOG.errorf(String, Object...) treats trailing args as format params,
so the catch-all exception handler in AwsJson11Controller silently
dropped the stack trace. Switch to errorf(Throwable, String, Object...)
so unexpected failures surface with their cause attached, matching
the pattern used in AwsJsonController and AwsJsonCborController.
Refs floci-io/floci #482
* fix(ecr): fixing port and network issues on ecr
* fix: issue on merge with main
* fix(ecr): connect containers to network after start only when port bindings exist
FIFO sendMessage silently dropped the queue-level DelaySeconds
attribute: messages were stored and then made immediately receivable,
regardless of the queue's configured default (issue #475).
Resolve the effective delay from the DelaySeconds queue attribute
before the FIFO/standard split. FIFO always uses the queue-level
value (AWS does not accept per-message DelaySeconds on FIFO queues);
the standard path keeps its existing per-message behavior. Apply
the resolved delay via Message.setVisibleAt in both branches.
Known limitation out of scope for this patch: Message.visibleAt is
@JsonIgnore, so delayed visibility does not survive a restart -- same
constraint the standard path already had. Tracking for a follow-up.
Fixes#475
Adds a bedrock-runtime service stub so AWS SDK and CLI clients can target
Floci for local development of Bedrock Runtime callers. Dummy responses
only: no real model inference.
- Register bedrock-runtime in ResolvedServiceCatalog under both "bedrock"
and "bedrock-runtime" credential scopes (boto3 signs with signingName
"bedrock" while some clients use the endpoint id)
- POST /model/{modelId}/converse returns a fixed assistant message plus
synthetic usage and latency metrics matching the AWS Converse contract
- POST /model/{modelId}/invoke returns an Anthropic-shaped body for
anthropic.* and *.anthropic.* model ids, generic {"outputs": [...]}
otherwise. Request body is passed through as opaque bytes
- {modelId:.+} path regex accepts full ARNs (inference profiles,
provisioned throughput) in addition to plain ids
- converse-stream and invoke-with-response-stream return 501 so SDKs
get a clear error instead of 404
- Response building uses JsonNode rather than typed POJOs, avoiding
native-image reflection registration
13 new integration tests (Converse + InvokeModel happy paths, validation,
inference-profile ids and ARNs, 501 streaming responses). Full suite
remains green: 2263 tests, 0 failures.
Adds the Resource Groups Tagging API as a new JSON 1.1 service
(X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*).
New service files:
- ResourceTagMapping model (resourceArn + LinkedHashMap tags)
- ResourceGroupsTaggingService — in-memory store keyed by
region::arn, implements TagResources, UntagResources,
GetResources (with ResourceARNList, TagFilter, and
ResourceTypeFilter support), GetTagKeys, GetTagValues
- ResourceGroupsTaggingJsonHandler — dispatches all five actions,
builds JSON responses matching the AWS wire format
Pagination uses a Base64-encoded offset token for all list
operations. ResourceTypeFilters support both "service:type" and
bare "service" formats parsed from ARN structure.
Wiring:
- EmulatorConfig: ResourceGroupsTaggingServiceConfig (enabled=true)
- ResolvedServiceCatalog: descriptor with target prefix
ResourceGroupsTaggingAPI_20170126., credential scope "tagging"
- AwsJson11Controller: injected handler, case "tagging"
Tests:
- 14 integration tests: tag multiple ARNs, get all / by ARN list /
by tag filter / by tag key only / by resource type / by service
type, pagination, GetTagKeys, GetTagValues, UntagResources,
verify removal
- HealthControllerIntegrationTest updated to include "tagging"
* feat: implement local Data Lake stack (Athena, Glue, and Firehose)
* fix: adding athena, firehose and glue documentation
* fix: updating dataLateTest
Adds EBS volume support to the EC2 service — the minimum viable
volume API needed to unblock AWS metadata workflows.
New model classes:
- Volume (volumeId, volumeType, size, state, availabilityZone,
encrypted, iops, snapshotId, createTime, tags, attachments)
- VolumeAttachment (instanceId, device, state, attachTime,
deleteOnTermination, volumeId)
Service changes (Ec2Service):
- In-memory ConcurrentHashMap store keyed by region::volumeId
- createVolume() with TagSpecification support
- describeVolumes() with ID list + filter support
- deleteVolume() with InvalidVolume.NotFound on missing ID
- Filter support: volume-id, status, volume-type,
availability-zone, encrypted, tag:*, tag-key, tag-value
Handler changes (Ec2QueryHandler):
- CreateVolume, DescribeVolumes, DeleteVolume cases in switch
- volumeXml() serializer matching AWS EC2 Query Protocol wire
format (volumeSet/item, attachmentSet, nextToken)
- TagSpecification.N.ResourceType=volume parsing on create
Integration tests (Ec2IntegrationTest):
- create → describe by ID
- filter by status and volume-type
- delete → NotFound on subsequent describe
- InvalidVolume.NotFound error case
Replaces the stubs in both the query and JSON protocol handlers with a
full implementation that delegates to the existing getMetricStatistics
storage and aggregation logic.
- Add MetricStat, MetricDataQuery, and MetricDataResult records to
CloudWatchMetricsService
- getMetricData() iterates queries, buckets by period, resolves the
requested statistic (Average/Sum/Min/Max/SampleCount/p*), and
returns Complete results
- Query handler: parseMetricDataQueries walks the deeply nested
MetricDataQueries.member.N.* form encoding
- JSON handler: parseInstantNode handles numeric epoch timestamps sent
by AWS SDK v2 (GetMetricData uses the JSON protocol); previously the
time filter silently failed, returning all stored data
Go AWS SDK v2 expression.Builder joins top-level UpdateExpression
clauses with '\n' (e.g. "SET #a = :a\nADD #b :b"). Two bugs in the
clause walker silently dropped clauses on these inputs:
1. indexOfKeyword only accepted a literal space as the left word
boundary, so a keyword preceded by \n/\t/\r was rejected. This
meant findNextClauseKeyword returned -1 for the next clause, and
the current clause helper consumed the next clause's text as its
own operand. For "SET x = :a\nADD y :b" applySetClause swallowed
":a\nADD y :b" as the SET value, failed the placeholder lookup,
and neither SET nor ADD ran. Relaxed the boundary check to accept
any whitespace via Character.isWhitespace.
2. indexOfKeyword returned -1 at the first non-boundary occurrence of
a keyword, even when a valid match existed later. An attribute
named oldSET in "REMOVE oldSET SET newAttr = :v" masked the real
SET. Looped past non-boundary hits until a boundary match or end
of string.
3. applyRemoveClause, applyAddClause, and applyDeleteClause advanced
on the next comma before checking for a clause keyword, so an
intra-clause comma in a following SET (e.g. "ADD a :v SET b = :b,
c = :c") consumed the SET keyword. Aligned all three helpers with
applySetClause's "earlier of next clause keyword or next comma
wins" rule.
Closes#430.
Real AWS accepts bare name, partial ARN (ACCT:function:NAME), and full
ARN (arn:aws:lambda:REGION:ACCT:function:NAME) for every endpoint that
takes {FunctionName}, optionally suffixed with :qualifier. Floci only
matched the stored short name, so ~20 Lambda endpoints 404'd on ARN
forms.
Introduce LambdaArnUtils.resolve() as the single parse point; normalize
inputs in LambdaService at every user-facing method so downstream store,
warm-pool, code-store, and alias-store operations all use the canonical
short name. createFunction now deduplicates across name/ARN forms.
- Enforce region match when a full function ARN is supplied (400 on
mismatch with the request region or with an event-source ARN region).
- Tag endpoints require an unqualified full function ARN; reject
qualified ARNs and partial ARNs.
- URL config endpoints reconcile ARN-embedded qualifier with ?Qualifier=
and 400 on conflict.
- listEventSourceMappings normalizes its FunctionName filter so partial
ARNs no longer miss stored mappings.
Fixesfloci-io/floci#434.
AWS Kinesis GetRecords documents MillisBehindLatest as the time delta
between the consumer position and the shard tip in milliseconds.
Floci was returning the count of records remaining in the shard instead,
so downstream iterator-age metrics and lag-based alerting were wrong
(e.g. 10 records ahead surfaced as 10ms of lag).
Use the ApproximateArrivalTimestamp already stamped at PutRecord time to
compute the delta. Returns 0 when the consumer is at the shard tip, the
shard is empty, or no records were returned.
Move Kinesis streaming destination forwarding logic into a dedicated
KinesisStreamingForwarder class, injected directly into DynamoDbService.
This decouples Kinesis forwarding from DynamoDB Streams at the DI level —
the two features are independent in real AWS and should not share a
null-guard or lifecycle dependency.
Main's PR #419 solves the in-container case when FLOCI_STORAGE_HOST_PERSISTENT_PATH is set to an absolute host path (via the updated docker-compose.yml). This adds a zero-config fallback: when Floci detects it's running inside a container and host-persistent-path is still its relative default (./data), bind-mounting into a sibling container fails on Docker Desktop. In that case, use a dedicated named volume (floci-ecr-registry-data) so docker compose up works without requiring users to update their compose file.
* 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.
* feat(dynamodb): add EnableKinesisStreamingDestination support
Implement EnableKinesisStreamingDestination, DisableKinesisStreamingDestination,
and DescribeKinesisStreamingDestination API actions for DynamoDB.
When a Kinesis streaming destination is enabled on a table, all item mutations
(INSERT/MODIFY/REMOVE) are automatically forwarded to the configured Kinesis
stream. The Kinesis record payload matches the AWS format with awsRegion,
eventName, tableName, and dynamodb (Keys, NewImage, OldImage, etc.).
Closes#426
* fix(dynamodb): address review feedback for KinesisStreamingDestination
- Decouple Kinesis forwarding from DDB Streams: forwardToKinesisDestinations
is now called directly from DynamoDbService mutation hooks, independent of
whether DDB Streams is enabled
- Fix ApproximateCreationDateTime to use milliseconds (was seconds)
- Remove SequenceNumber and StreamViewType from Kinesis payload (not present
in real AWS)
- Add ApproximateCreationDateTimePrecision inside dynamodb record node
- Return ValidationException when disabling an already-disabled destination
- Simplify persistTable to accept TableDefinition directly
- Add test for disable-already-disabled and payload format assertions
ListUserPoolClients was returning full UserPoolClient objects including
ClientSecret, GenerateSecret, AllowedOAuthFlows, AllowedOAuthScopes,
CreationDate and LastModifiedDate. Per the AWS API spec, this action
returns UserPoolClientDescription containing only ClientId, ClientName
and UserPoolId.
Add clientToDescriptionNode() for the list response, matching the
existing pattern where ListUserPools uses userPoolToDescriptionNode().
DescribeUserPoolClient continues to return the full object via
clientToNode().