Files
floci/compatibility-tests/compat-terraform/test/elasticache_single_node.bats
T
Allen Sanborn 684239b0ef fix(elasticache): create single-node redis clusters and close provisioning races (#3634)
* feat(elasticache): support single-node redis clusters in CreateCacheCluster

CreateCacheCluster refused every engine but memcached, telling callers to use
CreateReplicationGroup instead. Real AWS accepts Engine=redis and Engine=valkey
there as long as the cluster has one node, and that is exactly the call
terraform's aws_elasticache_cluster with engine = "redis" emits, so every such
example failed against Floci.

A single-node redis or valkey cluster is now provisioned the way a
cluster-mode-disabled replication group is: the same Valkey container, fronted by
the same auth proxy on a port from the same range, so the endpoint a describe
reports actually answers RESP. It is stored apart from replication groups, since
one created this way has none and must not appear in DescribeReplicationGroups.

NumCacheNodes greater than 1 is refused with the message a live account gives.
Following AWS, the cluster carries no ConfigurationEndpoint (that is memcached's
node discovery endpoint) and reports its node under CacheNodes when the request
sets ShowCacheNodeInfo, which is where terraform-provider-aws reads the port.

The memcached path is unchanged. ElastiCacheMemcachedIntegrationTest asserted the
old refusal with Engine=redis; it now asserts it with an engine ElastiCache
really does not have.

* fix(elasticache): address review findings

Cross-type id collision closed both directions through one provisioningIds
claim set (the claimed thing is one namespace: container name + proxy key);
wire code corrected to CacheClusterAlreadyExists; create request grown to
round-trip the optional members Terraform reads back, guarded by a
compat-terraform bats config asserting plan -detailed-exitcode after apply;
ListTagsForResource cluster arm brought to parity with the replicationgroup
arm without regressing memcached/member fall-through; standalone clusters
join getResources; create/delete responses no longer leak CacheNodes.

* fix(elasticache): correct review-round test assertion, bats port pin, docs note

The cross-type guard test asserted never() on a tryStart its own setup
legitimately performs — times(1), matching the sibling test. The single-node
bats config pinned port 6379, which the parallel bats runner's sibling
replication-group config fills first from the range base (the allocator
refuses rather than substitutes) — pinned to 6395. AtRestEncryptionEnabled
noted in docs as output-only on real AWS's CreateCacheCluster.

* docs(elasticache): the output-only note belongs to the single-node prose, not the CreateReplicationGroup row

AtRestEncryptionEnabled is a legitimate input member of
CreateReplicationGroupMessage; it is absent only from CreateCacheClusterMessage.

* fix(elasticache): reserve persisted ports on restore, cross-store id uniqueness, validate subnet group

Three findings from the PR review, all on the single-node cache cluster path.

Ports of records that survive a restart are now reserved before Floci serves
anything. Standalone cache clusters and cluster-mode-disabled replication groups
are not re-provisioned, but they still advertise the port they were given, and
nothing put those ports back into the in-use set: a create after a restart was
handed a port a live record still published, and the two then contended over one
reservation, so the first delete freed it and the next create took it again. A
delete now releases only a port this process actually reserved for that record,
since a restored record whose port was already taken advertises one it does not
own.

The id check spans all three stores that answer DescribeCacheClusters. A
standalone redis cluster, a Memcached cluster and a replication group can no
longer share an id in either direction. Both services read the same backends:
StorageFactory keys them by file path and hands the second caller the first
caller's instance, so no new wiring is needed for the two services to agree on
one namespace.

CacheSubnetGroupName must now name a subnet group that exists, instead of being
stored as a reference a describe reports and a caller cannot look up.
CreateReplicationGroup still does not make that check; it is called out in the
service and in the docs rather than changed here.

* style(elasticache): drop em dash in transient-field comment

* fix(elasticache): close the id and port gaps the delta review found

CreateReplicationGroup's duplicate-id check read only the group and redis
cluster stores, so a group could take the id of a live memcached cluster
while CreateCacheCluster refused the same collision the other way round.
Check the third store too, which is what makes the documented "an id is
taken across all three at once" actually hold.

Two port-reservation fixes alongside it. The claim on a new cache
cluster's port was recorded after the synchronized block that stores the
record, so a delete landing in the gap found nothing to release and
stranded the reservation; it now happens under the same monitor as the
put. And deleteReplicationGroup freed the group's port unconditionally,
while the cluster path has guarded that since the restore work went in: a
record restored from disk whose port was already taken advertises a port
it does not own, and freeing it hands a live record's port to the next
create. The holder set now covers both kinds, keyed by id, which is safe
because an id is unique across the stores.

* docs(elasticache): say which engines the subnet-group check covers

CreateCacheCluster with Engine=memcached routes to a create that takes
only the cluster id, so CacheSubnetGroupName is dropped on that path: not
checked, not echoed. The page claimed the check unqualified. Also name
CreateReplicationGroup in the id-uniqueness paragraph, now that it makes
the same check.

* test(elasticache): cover the ordinary group delete that frees its port

The two port tests around it both step past the create path: one deletes a
group written straight into the store, the other one restored after a
restart. So the claim recorded when a group is created in process had
nothing behind it, and dropping it would leave the suite green while every
DeleteReplicationGroup leaked its proxy port for the life of the process.

* fix(elasticache): claim the id on the memcached create path too

CreateCacheCluster for memcached checked the three stores for a duplicate id
and went straight on to start its container, without joining the in-flight
claim set the redis cluster and replication group paths take. No create path
persists its record until after container startup, so a memcached create and
a redis create for one id could both read three empty stores and both write,
leaving the id in two stores with DescribeCacheClusters reporting it twice
and the two containers and proxy registrations colliding under one name.

Move that set out of ElastiCacheService into an ElastiCacheProvisioningIds
bean both services inject, so the claim covers every engine, and take it in
the memcached path before the store checks with the same try/finally release.
A collision with an in-flight create is refused with the fault the store-hit
path already produces, CacheClusterAlreadyExistsFault.

* fix(elasticache): complete the CacheNode shape and correct the memcached fault code

DescribeCacheClusters returned a CacheNode carrying only an id, a status and an
endpoint. terraform-provider-aws dereferences CacheNodeCreateTime and
ParameterGroupStatus while adopting the resource without a nil check, so the
compat-terraform job created floci-tf-redis-single successfully and then died on
the very next refresh with "Unexpected nil pointer" naming both fields. The
endpoint was never the problem; the node shape was incomplete.

Both are stable metadata AWS returns on every available node, and both were
already known here: a single-node cluster's node was created with the cluster,
and its parameter group carries the same in-sync status already reported for the
cluster. CustomerAvailabilityZone is emitted from the cluster's AZ for the same
reason -- a node whose AZ disagrees with its cluster is a permanent plan diff.
Memcached returns early well above this block, so its wire output is unchanged.

Separately, the id claim added on the memcached create path threw
CacheClusterAlreadyExistsFault. The wire code is CacheClusterAlreadyExists -- the
Fault suffix is the botocore shape name, not the code an SDK matches on -- which
this branch had already established on the redis side and then contradicted.
Both memcached throw sites now use the wire code, including the pre-existing one,
and the five test assertions that pinned the wrong spelling are corrected.

* test(elasticache): stop the single-node fixture pinning the shared suite's port

The compat-terraform job runs every stack against one Floci, and this branch's
new elasticache-single-node-tf pinned port 6395 -- the same port main.tf already
pins for the replication group the `terraform` suite creates. ElastiCache
refuses a pinned port that is already reserved, by design, so the two stacks can
only both succeed if the first is fully destroyed before the second applies.

That is what the last run showed: elasticache_single_node failed its apply, so
its destroy never ran, 6395 stayed held, and the `terraform` suite then failed
with "Port 6395 is already in use by another replication group" -- a second
failure that reads like an allocator bug and is really a fixture collision.
Fixing the node shape removes the trigger but not the collision, which would
remain a teardown-ordering dependency between two independent suites.

6396 is free and inside the 6379-6399 proxy range.

* test(elasticache): name the extracted XmlPath instead of inferring it with var

Review follow-up: this was the only `var` in the file, and the type it hides
(io.restassured.path.xml.XmlPath) is the one a reader needs in order to follow
the getString/getInt calls immediately below it.

No behaviour change.

* style(test): import ArrayList and LinkedHashMap instead of naming them inline

AGENTS.md asks for imports rather than inline fully-qualified names.
ElastiCacheQueryHandlerTest had three: new java.util.ArrayList<>(...) and
two new java.util.LinkedHashMap<>(...). LinkedHashMap was already imported;
ArrayList is added.
2026-09-22 22:26:15 -04:00

131 lines
4.8 KiB
Bash

#!/usr/bin/env bats
# ElastiCache single-node Redis Compatibility Test
#
# Applies an aws_elasticache_cluster with engine = "redis", the shape terraform
# sends to CreateCacheCluster rather than CreateReplicationGroup, and verifies
# both sides of the contract: the read-back is honest enough that a second plan
# wants nothing (the optional snapshot and maintenance arguments included), and
# the node endpoint terraform hands out is a real Redis/Valkey answering RESP.
setup_file() {
load 'test_helper/common-setup'
EC_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/elasticache-single-node-tf" && pwd)"
cd "$EC_TF_DIR"
echo "# === ElastiCache Single-Node Redis Test ===" >&3
echo "# Endpoint: $FLOCI_ENDPOINT" >&3
echo "# Config: $EC_TF_DIR" >&3
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
echo "# --- terraform init ---" >&3
run terraform init -input=false -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform init failed: $output" >&3
return 1
fi
echo "# --- terraform apply (single-node redis) ---" >&3
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform apply failed: $output" >&3
return 1
fi
}
teardown_file() {
load 'test_helper/common-setup'
EC_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/elasticache-single-node-tf" && pwd)"
cd "$EC_TF_DIR"
terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
}
setup() {
load 'test_helper/common-setup'
EC_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/elasticache-single-node-tf" && pwd)"
}
# Sends one RESP command over /dev/tcp and echoes whatever the server replies
# within the read window. No redis-cli in this image, so raw RESP it is.
valkey_command() {
local host="$1" port="$2"
shift 2
local payload="*$#\r\n"
local arg
for arg in "$@"; do
payload+="\$${#arg}\r\n${arg}\r\n"
done
exec 9<>"/dev/tcp/${host}/${port}" || return 1
printf '%b' "$payload" >&9
local reply="" chunk
while IFS= read -r -t 3 -u 9 chunk; do
reply+="${chunk}"$'\n'
done
exec 9<&- 9>&-
printf '%s' "$reply"
}
@test "ElastiCache single node: terraform reads back the engine and port" {
run terraform -chdir="$EC_TF_DIR" output -raw engine
assert_success
assert_output "redis"
run terraform -chdir="$EC_TF_DIR" output -raw port
assert_success
assert_output "6396"
}
@test "ElastiCache single node: describe reports one node, no replication group" {
run aws_cmd elasticache describe-cache-clusters \
--cache-cluster-id floci-tf-redis-single --show-cache-node-info
assert_success
[ "$(json_get "$output" '.CacheClusters[0].Engine')" = "redis" ]
[ "$(json_get "$output" '.CacheClusters[0].NumCacheNodes')" = "1" ]
[ "$(json_get "$output" '.CacheClusters[0].CacheNodes | length')" = "1" ]
[ "$(json_get "$output" '.CacheClusters[0].ReplicationGroupId')" = "null" ]
# a cluster created this way is not a replication group and must not answer as one
run aws_cmd elasticache describe-replication-groups \
--replication-group-id floci-tf-redis-single
assert_failure
}
@test "ElastiCache single node: the optional arguments read back as sent" {
run aws_cmd elasticache describe-cache-clusters --cache-cluster-id floci-tf-redis-single
assert_success
[ "$(json_get "$output" '.CacheClusters[0].SnapshotRetentionLimit')" = "5" ]
[ "$(json_get "$output" '.CacheClusters[0].SnapshotWindow')" = "03:00-05:00" ]
[ "$(json_get "$output" '.CacheClusters[0].PreferredMaintenanceWindow')" = "tue:04:00-tue:05:00" ]
}
# The critical assertion: the endpoint terraform hands out fronts a real cache.
@test "ElastiCache single node: the node endpoint answers RESP" {
host=$(terraform -chdir="$EC_TF_DIR" output -raw cache_node_address)
port=$(terraform -chdir="$EC_TF_DIR" output -raw cache_node_port)
run valkey_command "$host" "$port" PING
assert_success
assert_output --partial "PONG"
run valkey_command "$host" "$port" SET tf-single-node-key a-value
assert_success
assert_output --partial "OK"
run valkey_command "$host" "$port" GET tf-single-node-key
assert_success
assert_output --partial "a-value"
}
# Guards against read-back drift (the class of bug in floci-io/floci#2481):
# a second plan straight after apply must not want to change anything.
@test "ElastiCache single node: re-plan after apply is clean" {
cd "$EC_TF_DIR"
run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode
assert_success
assert_output --partial "No changes"
}