diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java index cffcf75aaf..c16b570d9e 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java @@ -28,6 +28,7 @@ import software.amazon.awssdk.services.redshift.model.DeleteSnapshotCopyGrantReq import software.amazon.awssdk.services.redshift.model.DeleteTagsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsResponse; +import software.amazon.awssdk.services.redshift.model.DescribeClusterParametersRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsResponse; import software.amazon.awssdk.services.redshift.model.DescribeClusterSubnetGroupsRequest; @@ -41,10 +42,15 @@ import software.amazon.awssdk.services.redshift.model.DescribeTagsRequest; import software.amazon.awssdk.services.redshift.model.DescribeTagsResponse; import software.amazon.awssdk.services.redshift.model.ModifyClusterIamRolesRequest; import software.amazon.awssdk.services.redshift.model.ModifyClusterIamRolesResponse; +import software.amazon.awssdk.services.redshift.model.ModifyClusterParameterGroupRequest; import software.amazon.awssdk.services.redshift.model.ModifyClusterRequest; import software.amazon.awssdk.services.redshift.model.ModifyClusterResponse; +import software.amazon.awssdk.services.redshift.model.Parameter; import software.amazon.awssdk.services.redshift.model.RebootClusterRequest; import software.amazon.awssdk.services.redshift.model.RebootClusterResponse; +import software.amazon.awssdk.services.redshift.model.RedshiftException; +import software.amazon.awssdk.services.redshift.model.ResetClusterParameterGroupRequest; +import software.amazon.awssdk.services.redshift.model.ResetClusterParameterGroupResponse; import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotRequest; import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotResponse; import software.amazon.awssdk.services.redshift.model.Snapshot; @@ -277,6 +283,43 @@ class RedshiftOperationsTest { assertThat(foundPg.parameterGroupFamily()).isEqualTo("redshift-1.0"); assertThat(foundPg.description()).isEqualTo("Test parameter group for Redshift"); + DescribeClusterParametersRequest describeParameters = DescribeClusterParametersRequest.builder() + .parameterGroupName(pgName).build(); + List defaults = client.describeClusterParameters(describeParameters).parameters(); + String cursorDefault = defaults.stream() + .filter(parameter -> "max_cursor_result_set_size".equals(parameter.parameterName())) + .findFirst().orElseThrow().parameterValue(); + client.modifyClusterParameterGroup(ModifyClusterParameterGroupRequest.builder() + .parameterGroupName(pgName) + .parameters(Parameter.builder().parameterName("max_cursor_result_set_size").parameterValue("1000").build(), + Parameter.builder().parameterName("wlm_json_configuration").parameterValue("[{\"query_concurrency\":3}]").build()) + .build()); + + assertThatThrownBy(() -> client.resetClusterParameterGroup(ResetClusterParameterGroupRequest.builder() + .parameterGroupName(pgName).parameters(Parameter.builder().parameterValue("1000").build()).build())) + .isInstanceOf(RedshiftException.class).hasMessageContaining("ParameterName"); + + ResetClusterParameterGroupResponse reset = client.resetClusterParameterGroup(ResetClusterParameterGroupRequest.builder() + .parameterGroupName(pgName).resetAllParameters(false) + .parameters(Parameter.builder().parameterName("max_cursor_result_set_size").build()).build()); + + assertThat(reset.parameterGroupName()).isEqualTo(pgName); + assertThat(reset.parameterGroupStatus()).isNotBlank(); + List afterPartialReset = client.describeClusterParameters(describeParameters).parameters(); + assertThat(afterPartialReset).anySatisfy(parameter -> { + assertThat(parameter.parameterName()).isEqualTo("max_cursor_result_set_size"); + assertThat(parameter.parameterValue()).isEqualTo(cursorDefault); + assertThat(parameter.source()).isEqualTo("engine-default"); + }); + assertThat(client.describeClusterParameters(describeParameters.toBuilder().source("user").build()).parameters()) + .extracting(Parameter::parameterName).containsExactly("wlm_json_configuration"); + + client.resetClusterParameterGroup(ResetClusterParameterGroupRequest.builder() + .parameterGroupName(pgName).resetAllParameters(true).build()); + assertThat(client.describeClusterParameters(describeParameters).parameters()) + .allSatisfy(parameter -> assertThat(parameter.source()).isEqualTo("engine-default")); + assertThat(client.describeClusterParameters(describeParameters.toBuilder().source("user").build()).parameters()).isEmpty(); + // 3. Delete cluster parameter group client.deleteClusterParameterGroup(DeleteClusterParameterGroupRequest.builder() .parameterGroupName(pgName) diff --git a/compatibility-tests/sdk-test-python/tests/test_redshift_parameter_groups.py b/compatibility-tests/sdk-test-python/tests/test_redshift_parameter_groups.py new file mode 100644 index 0000000000..e44ae9309f --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_redshift_parameter_groups.py @@ -0,0 +1,56 @@ +"""Redshift parameter group compatibility with boto3's Query list encoding.""" + +from contextlib import closing + +import boto3 +import pytest +from botocore.exceptions import ClientError + + +def test_reset_all_accepts_empty_parameter_list(aws_config, client_config, unique_name): + name = f"pytest-redshift-pg-{unique_name}" + with closing(boto3.client("redshift", config=client_config, **aws_config)) as client: + client.create_cluster_parameter_group( + ParameterGroupName=name, + ParameterGroupFamily="redshift-1.0", + Description="Empty Query list regression", + ) + try: + initial = client.describe_cluster_parameters(ParameterGroupName=name)["Parameters"] + default_value = next( + parameter["ParameterValue"] + for parameter in initial + if parameter["ParameterName"] == "max_cursor_result_set_size" + ) + client.modify_cluster_parameter_group( + ParameterGroupName=name, + Parameters=[ + {"ParameterName": "max_cursor_result_set_size", "ParameterValue": "1000"} + ], + ) + + with pytest.raises(ClientError) as failure: + client.reset_cluster_parameter_group( + ParameterGroupName=name, ResetAllParameters=False, Parameters=[] + ) + assert failure.value.response["Error"]["Code"] == "InvalidParameterCombination" + unchanged = client.describe_cluster_parameters( + ParameterGroupName=name, Source="user" + )["Parameters"] + assert unchanged[0]["ParameterValue"] == "1000" + + response = client.reset_cluster_parameter_group( + ParameterGroupName=name, ResetAllParameters=True, Parameters=[] + ) + + assert response["ParameterGroupName"] == name + restored = client.describe_cluster_parameters(ParameterGroupName=name)["Parameters"] + parameter = next( + parameter + for parameter in restored + if parameter["ParameterName"] == "max_cursor_result_set_size" + ) + assert parameter["ParameterValue"] == default_value + assert parameter["Source"] == "engine-default" + finally: + client.delete_cluster_parameter_group(ParameterGroupName=name) diff --git a/docs/services/index.md b/docs/services/index.md index 1181b191f7..e932309b35 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -76,7 +76,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 43 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 44 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 61c0e84c3c..4c876ace30 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -30,6 +30,7 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name | | `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` | | `ModifyClusterParameterGroup` | Update parameter values on a group | +| `ResetClusterParameterGroup` | Reset selected parameters or all parameters to the emulated defaults | | `DeleteClusterParameterGroup` | Remove a parameter group | | `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group, parameter group, snapshot copy grant or snapshot schedule | | `DeleteTags` | Remove tags by key from a resource | @@ -64,6 +65,40 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity | +### Resetting parameter groups + +`ResetClusterParameterGroup` resets all parameters with `ResetAllParameters=true`, or the named +parameters with `ResetAllParameters=false` and a `Parameters` list. Each list entry needs only +`ParameterName`, and at most 20 entries are accepted. When the flag is omitted, Floci resets the +supplied names, or all parameters if no names were supplied. An explicit `true` cannot be combined +with a nonempty list, and an explicit `false` requires at least one name. An empty Query list, +encoded as `Parameters=`, is treated like an omitted list. The API reference describes the omitted flag as +defaulting to `true` but also describes supplying names without the flag; Floci resolves that +ambiguity by using whether names were supplied. These combinations have not been verified against +a live AWS cluster. + +Parameters report `Source=engine-default` initially, `user` after modification, and +`engine-default` after reset. `DescribeClusterParameters` accepts `Source=user` or +`Source=engine-default` to filter the result. The implicit `default.redshift-1.0` group is readable +but cannot be modified or reset. + +Creating a group named `default.redshift-1.0` is rejected. Earlier Floci versions allowed such a +group to be stored: for those legacy groups, both describe operations return the stored values, +and modify/reset remain available. The read-only built-in group is used only when no stored +group exists under that name. + +The default catalog remains limited to Floci's existing `max_cursor_result_set_size=0` and +`wlm_json_configuration={}` values, rather than the complete AWS engine catalog. Modifications to +other names are stored as before; resetting those names removes their overrides and omits them +from subsequent descriptions because Floci has no default to report. Resetting all parameters +restores the two catalog entries. Parameter groups remain metadata only: modifying or resetting +them does not change PostgreSQL settings, and Floci does not track the clusters' pending reboot +state. The reset response returns a descriptive `ParameterGroupStatus` message. + +Sources are persisted with parameter values. For older stored groups without a source, Floci +reports `engine-default` when the value matches its catalog and `user` otherwise. The old format +cannot distinguish an explicit assignment of a default value from an unchanged default. + ### Snapshot copy grants - **`KmsKeyId` defaults to an alias ARN.** Floci has no per-account AWS-managed key, so diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java index 952b612540..72600d8514 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.redshift; 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.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.IamEnforcementFilter; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -266,6 +267,13 @@ public class RedshiftQueryHandler { throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400); } List parameters = service.describeClusterParameters(parameterGroupName); + String source = params.getFirst("Source"); + if (source != null) { + if (!"user".equals(source) && !"engine-default".equals(source)) { + throw new AwsException("InvalidParameterValue", "Source must be user or engine-default.", 400); + } + parameters = parameters.stream().filter(parameter -> source.equals(parameter.getSource())).toList(); + } XmlBuilder xmlBuilder = new XmlBuilder() .start("DescribeClusterParametersResponse") @@ -303,6 +311,28 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "ResetClusterParameterGroup" -> { + List parameterNames = parseParameters(params).stream().map(Parameter::getParameterName).toList(); + String rawResetAll = params.getFirst("ResetAllParameters"); + if (rawResetAll != null && !"true".equalsIgnoreCase(rawResetAll) && !"false".equalsIgnoreCase(rawResetAll)) { + throw new AwsException("InvalidParameterValue", "ResetAllParameters must be a boolean.", 400); + } + boolean resetAll = rawResetAll == null ? parameterNames.isEmpty() : Boolean.parseBoolean(rawResetAll); + String parameterGroupName = params.getFirst("ParameterGroupName"); + service.resetClusterParameterGroup(parameterGroupName, resetAll, parameterNames); + String xml = new XmlBuilder() + .start("ResetClusterParameterGroupResponse", AwsNamespaces.REDSHIFT) + .start("ResetClusterParameterGroupResult") + .elem("ParameterGroupName", parameterGroupName) + .elem("ParameterGroupStatus", "Your parameter group has been updated.") + .end("ResetClusterParameterGroupResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("ResetClusterParameterGroupResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "DeleteClusterParameterGroup" -> { String parameterGroupName = params.getFirst("ParameterGroupName"); service.deleteClusterParameterGroup(parameterGroupName); @@ -1203,6 +1233,7 @@ public class RedshiftQueryHandler { if (param.getDataType() != null) { builder.elem("DataType", param.getDataType()); } + builder.elem("Source", param.getSource()); return builder.end("Parameter").build(); } @@ -1359,21 +1390,30 @@ public class RedshiftQueryHandler { } private static List parseParameters(MultivaluedMap params) { - List parsed = new ArrayList<>(); - readParameters(params, "Parameters.member", parsed); - readParameters(params, "Parameters.Parameter", parsed); - return parsed; - } - - private static void readParameters(MultivaluedMap params, String prefix, List parsed) { - for (int i = 1; ; i++) { - String name = params.getFirst(prefix + "." + i + ".ParameterName"); - if (name == null) { - break; + Map parsed = new LinkedHashMap<>(); + for (String key : params.keySet().stream().sorted().toList()) { + if ("Parameters".equals(key)) { + if (!"".equals(params.getFirst(key))) { + throw new AwsException("InvalidParameterValue", "Parameters must be an indexed list or empty.", 400); + } + continue; } - String value = params.getFirst(prefix + "." + i + ".ParameterValue"); - parsed.add(new Parameter(name, value)); + if (!key.startsWith("Parameters.")) { + continue; + } + if (!key.matches("Parameters\\.(?:member|Parameter)\\.[1-9]\\d*\\.[A-Za-z]+")) { + throw new AwsException("InvalidParameterValue", "Invalid Parameters member: " + key, 400); + } + String prefix = key.substring(0, key.lastIndexOf('.')); + String name = params.getFirst(prefix + ".ParameterName"); + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "Each parameter must have a ParameterName.", 400); + } + parsed.putIfAbsent(prefix, new Parameter(name, params.getFirst(prefix + ".ParameterValue"))); } + return parsed.entrySet().stream() + .sorted(Comparator.comparingInt(entry -> numericSuffix(entry.getKey()))) + .map(Map.Entry::getValue).toList(); } private static Map parseTags(MultivaluedMap params) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index cecdad9dfb..fdd7fefe44 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -62,6 +62,7 @@ public class RedshiftService { // The group every cluster starts on until one is named. static final String DEFAULT_PARAMETER_GROUP_NAME = "default.redshift-1.0"; + private static final int MAX_RESET_PARAMETERS = 20; private final AccountAwareStorageBackend clusters; private final AccountAwareStorageBackend snapshots; @@ -1104,6 +1105,9 @@ public class RedshiftService { // ── Parameter Group Operations ─────────────────────────────────────────── public ClusterParameterGroup createClusterParameterGroup(String parameterGroupName, String parameterGroupFamily, String description) { + if (DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName)) { + throw new AwsException("InvalidParameterValue", "The default parameter group name is reserved.", 400); + } if (parameterGroups.get(parameterGroupName).isPresent()) { throw new AwsException("ClusterParameterGroupAlreadyExists", "Cluster parameter group " + parameterGroupName + " already exists", 400); } @@ -1144,18 +1148,22 @@ public class RedshiftService { public List describeClusterParameters(String parameterGroupName) { ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + .or(() -> DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName) + ? Optional.of(defaultParameterGroup()) : Optional.empty()) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404)); - return group.getParameters(); + return group.getParameters().stream().map(RedshiftService::copyParameterWithSource).toList(); } public synchronized ClusterParameterGroup modifyClusterParameterGroup( String parameterGroupName, List updates) { + requireMutableParameterGroup(parameterGroupName); ClusterParameterGroup group = parameterGroups.get(parameterGroupName) .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + parameterGroupName + " not found", 404)); - List current = new ArrayList<>(group.getParameters()); + List current = new ArrayList<>(group.getParameters().stream() + .map(RedshiftService::copyParameterWithSource).toList()); for (Parameter update : updates) { boolean matched = false; for (int i = 0; i < current.size(); i++) { @@ -1163,6 +1171,7 @@ public class RedshiftService { if (existing.getParameterName().equals(update.getParameterName())) { // Preserve metadata (description, dataType) from existing parameter if not provided in update existing.setParameterValue(update.getParameterValue()); + existing.setSource("user"); if (update.getDescription() != null) { existing.setDescription(update.getDescription()); } @@ -1174,7 +1183,9 @@ public class RedshiftService { } } if (!matched) { - current.add(update); + Parameter added = copyParameterWithSource(update); + added.setSource("user"); + current.add(added); } } group.setParameters(current); @@ -1183,6 +1194,73 @@ public class RedshiftService { return group; } + public synchronized void resetClusterParameterGroup(String parameterGroupName, boolean resetAllParameters, + List parameterNames) { + requireMutableParameterGroup(parameterGroupName); + if (resetAllParameters && !parameterNames.isEmpty()) { + throw new AwsException("InvalidParameterCombination", + "Parameters cannot be specified when ResetAllParameters is true.", 400); + } + if (!resetAllParameters && parameterNames.isEmpty()) { + throw new AwsException("InvalidParameterCombination", + "At least one parameter is required when ResetAllParameters is false.", 400); + } + if (parameterNames.size() > MAX_RESET_PARAMETERS) { + throw new AwsException("InvalidParameterValue", "A maximum of 20 parameters can be reset.", 400); + } + ClusterParameterGroup group = parameterGroups.get(parameterGroupName) + .orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound", + "Cluster parameter group " + parameterGroupName + " not found", 404)); + Set names = new LinkedHashSet<>(); + for (String name : parameterNames) { + if (name == null || name.isBlank() || group.getParameters().stream() + .noneMatch(parameter -> name.equals(parameter.getParameterName()))) { + throw new AwsException("InvalidParameterValue", "Unknown parameter: " + name, 400); + } + names.add(name); + } + List defaults = ClusterParameterGroup.defaultParameters(); + List reset = defaults; + if (!resetAllParameters) { + reset = new ArrayList<>(); + for (Parameter parameter : group.getParameters()) { + if (names.contains(parameter.getParameterName())) { + defaults.stream().filter(candidate -> candidate.getParameterName().equals(parameter.getParameterName())) + .findFirst().ifPresent(reset::add); + } else { + reset.add(copyParameterWithSource(parameter)); + } + } + } + group.setParameters(reset); + parameterGroups.put(parameterGroupName, group); + parameterGroups.flush(); + } + + private void requireMutableParameterGroup(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400); + } + if (DEFAULT_PARAMETER_GROUP_NAME.equals(name) && parameterGroups.get(name).isEmpty()) { + throw new AwsException("InvalidParameterValue", "The default parameter group cannot be modified.", 400); + } + } + + private static Parameter copyParameterWithSource(Parameter parameter) { + Parameter copy = new Parameter(parameter.getParameterName(), parameter.getParameterValue(), + parameter.getDescription(), parameter.getDataType()); + String source = parameter.getSource(); + if (source == null) { + // Older persisted groups do not record whether a value was explicitly set to its default. + boolean engineDefault = ClusterParameterGroup.defaultParameters().stream().anyMatch(candidate -> + candidate.getParameterName().equals(parameter.getParameterName()) + && candidate.getParameterValue().equals(parameter.getParameterValue())); + source = engineDefault ? "engine-default" : "user"; + } + copy.setSource(source); + return copy; + } + public ClusterParameterGroup deleteClusterParameterGroup(String parameterGroupName) { Optional groupOpt = parameterGroups.get(parameterGroupName); if (groupOpt.isEmpty()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/ClusterParameterGroup.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/ClusterParameterGroup.java index 01e7cb1712..7d67e06a43 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/model/ClusterParameterGroup.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/ClusterParameterGroup.java @@ -50,10 +50,16 @@ public class ClusterParameterGroup { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } - private List parameters = new ArrayList<>(List.of( - new Parameter("max_cursor_result_set_size", "0", "Maximum cursor result set size", "integer"), - new Parameter("wlm_json_configuration", "{}", "WLM configuration", "string") - )); + private List parameters = defaultParameters(); + + public static List defaultParameters() { + List defaults = new ArrayList<>(List.of( + new Parameter("max_cursor_result_set_size", "0", "Maximum cursor result set size", "integer"), + new Parameter("wlm_json_configuration", "{}", "WLM configuration", "string") + )); + defaults.forEach(parameter -> parameter.setSource("engine-default")); + return defaults; + } public List getParameters() { return parameters; } public void setParameters(List parameters) { this.parameters = parameters; } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Parameter.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Parameter.java index 927969bdfe..43141e95b3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Parameter.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Parameter.java @@ -8,6 +8,7 @@ public class Parameter { private String parameterValue; private String description; private String dataType; + private String source; public Parameter() {} @@ -54,4 +55,12 @@ public class Parameter { public void setDataType(String dataType) { this.dataType = dataType; } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java index 546d443f5d..7364635a1b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java @@ -1,7 +1,12 @@ package io.github.hectorvent.floci.services.redshift; +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager; +import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup; +import io.github.hectorvent.floci.services.redshift.model.Parameter; import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.xml.XmlPath; @@ -15,7 +20,9 @@ import org.junit.jupiter.api.TestMethodOrder; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -53,6 +60,9 @@ public class RedshiftOperationsTest { @Inject RedshiftService service; + @Inject + StorageFactory storageFactory; + @Test @Order(1) void parameterGroupLifecycle() { @@ -115,6 +125,31 @@ public class RedshiftOperationsTest { .body(containsString("statement_timeout")) .body(containsString("5000")); + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "ResetClusterParameterGroup") + .formParam("ParameterGroupName", "pg-test-1") + .formParam("ResetAllParameters", "false") + .formParam("Parameters.Parameter.1.ParameterName", "statement_timeout") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeClusterParameters") + .formParam("ParameterGroupName", "pg-test-1") + .formParam("Source", "user") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(""))); + // 4. DeleteClusterParameterGroup given() .contentType("application/x-www-form-urlencoded") @@ -1161,4 +1196,97 @@ public class RedshiftOperationsTest { assertFault(response, 400, "InvalidParameterValue"); assertEquals("Invalid Marker.", XmlPath.from(response.asString()).getString("ErrorResponse.Error.Message")); } + + @Test + @Order(12) + void invalidResetListsLeaveStoredOverridesUnchanged() { + String name = "reset-validation-guard"; + service.createClusterParameterGroup(name, "redshift-1.0", "validation test"); + try { + service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "1000"))); + + assertFault(redshift("ResetClusterParameterGroup", "ParameterGroupName", name, "Parameters", "invalid"), + 400, "InvalidParameterValue"); + assertEquals("1000", service.describeClusterParameters(name).getFirst().getParameterValue()); + assertFault(redshift("ResetClusterParameterGroup", "ParameterGroupName", name, + "ResetAllParameters", "false", "Parameters", ""), 400, "InvalidParameterCombination"); + assertEquals("1000", service.describeClusterParameters(name).getFirst().getParameterValue()); + + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + List fields = new ArrayList<>(List.of("ParameterGroupName", name)); + for (int index = 1; index <= 21; index++) { + fields.add(prefix + "." + index + ".ParameterName"); + fields.add("max_cursor_result_set_size"); + } + assertFault(redshift("ResetClusterParameterGroup", fields.toArray(String[]::new)), + 400, "InvalidParameterValue"); + assertEquals("1000", service.describeClusterParameters(name).getFirst().getParameterValue()); + } + } finally { + service.deleteClusterParameterGroup(name); + } + } + + @Test + @Order(13) + void reservedDefaultNameRejectsCreationAndPreservesLegacyGroupLifecycle() { + String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; + assertFault(redshift("CreateClusterParameterGroup", "ParameterGroupName", name, + "ParameterGroupFamily", "redshift-1.0", "Description", "reserved"), 400, "InvalidParameterValue"); + assertFault(redshift("ResetClusterParameterGroup", "ParameterGroupName", name), 400, "InvalidParameterValue"); + + AccountAwareStorageBackend backend = storageFactory.create( + "redshift", "redshift-parameter-groups.json", new TypeReference>() {}); + assertTrue(backend.get(name).isEmpty()); + ClusterParameterGroup legacy = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); + legacy.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); + backend.put(name, legacy); + backend.flush(); + try { + redshift("DescribeClusterParameterGroups", "ParameterGroupName", name).then().statusCode(200) + .body(containsString("legacy custom group")); + redshift("DescribeClusterParameters", "ParameterGroupName", name).then().statusCode(200) + .body(containsString("1000")); + redshift("ModifyClusterParameterGroup", "ParameterGroupName", name, + "Parameters.Parameter.1.ParameterName", "max_cursor_result_set_size", + "Parameters.Parameter.1.ParameterValue", "2000").then().statusCode(200); + redshift("DescribeClusterParameters", "ParameterGroupName", name).then().statusCode(200) + .body(containsString("2000")); + redshift("ResetClusterParameterGroup", "ParameterGroupName", name, + "Parameters.Parameter.1.ParameterName", "max_cursor_result_set_size").then().statusCode(200); + redshift("DescribeClusterParameters", "ParameterGroupName", name).then().statusCode(200) + .body(containsString("0")) + .body(containsString("engine-default")); + redshift("DeleteClusterParameterGroup", "ParameterGroupName", name).then().statusCode(200); + } finally { + backend.delete(name); + backend.flush(); + } + redshift("DescribeClusterParameterGroups", "ParameterGroupName", name).then().statusCode(200) + .body(not(containsString("legacy custom group"))); + assertFault(redshift("ResetClusterParameterGroup", "ParameterGroupName", name), 400, "InvalidParameterValue"); + } + + @Test + @Order(14) + void botocoreEmptyListResetsAllParameters() { + String name = "reset-empty-list"; + service.createClusterParameterGroup(name, "redshift-1.0", "empty list test"); + try { + service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "1000"))); + + redshift("ResetClusterParameterGroup", "ParameterGroupName", name, + "ResetAllParameters", "true", "Parameters", "").then().statusCode(200); + + assertEquals("0", service.describeClusterParameters(name).getFirst().getParameterValue()); + assertEquals("engine-default", service.describeClusterParameters(name).getFirst().getSource()); + service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "1000"))); + + redshift("ResetClusterParameterGroup", "ParameterGroupName", name, "Parameters", "").then().statusCode(200); + + assertEquals("0", service.describeClusterParameters(name).getFirst().getParameterValue()); + } finally { + service.deleteClusterParameterGroup(name); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java index 5624f7d5c4..2dce874427 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java @@ -39,6 +39,222 @@ class RedshiftQueryHandlerTest { private RedshiftIamDbUserResolver iamDbUserResolver; private RegionResolver regionResolver; + @Test + void resetClusterParameterGroupReturnsAwsQueryResponse() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("ResetAllParameters", "true"); + + Response response = handler.handle("ResetClusterParameterGroup", params); + + assertEquals(200, response.getStatus()); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("")); + assertTrue(xml.contains("reset-pg")); + assertTrue(xml.contains("")); + verify(service).resetClusterParameterGroup("reset-pg", true, List.of()); + } + + @Test + void resetClusterParameterGroupDefaultsToAllWithoutNames() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + + handler.handle("ResetClusterParameterGroup", params); + + verify(service).resetClusterParameterGroup("reset-pg", true, List.of()); + } + + @Test + void resetClusterParameterGroupAcceptsBothQueryMemberFormatsWithoutValues() { + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("ResetAllParameters", "false"); + params.putSingle(prefix + ".1.ParameterName", "wlm_json_configuration"); + + handler.handle("ResetClusterParameterGroup", params); + } + + verify(service, times(2)).resetClusterParameterGroup("reset-pg", false, List.of("wlm_json_configuration")); + } + + @Test + void resetClusterParameterGroupDefaultsToSelectedNamesWhenNamesAreGiven() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Parameters.Parameter.1.ParameterName", "wlm_json_configuration"); + + handler.handle("ResetClusterParameterGroup", params); + + verify(service).resetClusterParameterGroup("reset-pg", false, List.of("wlm_json_configuration")); + } + + @Test + void resetClusterParameterGroupDoesNotTreatSparseNamesAsResetAll() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Parameters.Parameter.2.ParameterName", "wlm_json_configuration"); + + handler.handle("ResetClusterParameterGroup", params); + + verify(service).resetClusterParameterGroup("reset-pg", false, List.of("wlm_json_configuration")); + } + + @Test + void resetClusterParameterGroupRejectsInvalidBoolean() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("ResetAllParameters", "invalid"); + + AwsException failure = assertThrows(AwsException.class, + () -> handler.handle("ResetClusterParameterGroup", params)); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(service, never()).resetClusterParameterGroup(any(), anyBoolean(), anyList()); + } + + @Test + void resetClusterParameterGroupAcceptsBotocoreEmptyListForResetAll() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Parameters", ""); + params.putSingle("ResetAllParameters", "true"); + + Response response = handler.handle("ResetClusterParameterGroup", params); + + assertEquals(200, response.getStatus()); + verify(service).resetClusterParameterGroup("reset-pg", true, List.of()); + } + + @Test + void resetClusterParameterGroupTreatsEmptyListLikeOmittedList() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Parameters", ""); + + handler.handle("ResetClusterParameterGroup", params); + + verify(service).resetClusterParameterGroup("reset-pg", true, List.of()); + } + + @Test + void resetClusterParameterGroupRejectsNonemptyBareParameters() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Parameters", "invalid"); + + AwsException failure = assertThrows(AwsException.class, + () -> handler.handle("ResetClusterParameterGroup", params)); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(service, never()).resetClusterParameterGroup(any(), anyBoolean(), anyList()); + } + + @Test + void resetClusterParameterGroupPassesAllSuppliedNamesToServiceForValidation() { + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + for (int index = 1; index <= 21; index++) { + params.putSingle(prefix + "." + index + ".ParameterName", "max_cursor_result_set_size"); + } + + handler.handle("ResetClusterParameterGroup", params); + } + ArgumentCaptor> names = ArgumentCaptor.captor(); + verify(service, times(2)).resetClusterParameterGroup(eq("reset-pg"), eq(false), names.capture()); + assertTrue(names.getAllValues().stream().allMatch(value -> value.size() == 21)); + } + + @Test + void modifyClusterParameterGroupRejectsMembersWithoutNames() { + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle(prefix + ".1.ParameterValue", "1000"); + + AwsException failure = assertThrows(AwsException.class, + () -> handler.handle("ModifyClusterParameterGroup", params)); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + } + verify(service, never()).modifyClusterParameterGroup(any(), anyList()); + } + + @Test + void modifyClusterParameterGroupReadsSparseMembersInNumericOrder() { + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle(prefix + ".10.ParameterName", "max_cursor_result_set_size"); + params.putSingle(prefix + ".10.ParameterValue", "2000"); + params.putSingle(prefix + ".2.ParameterName", "max_cursor_result_set_size"); + params.putSingle(prefix + ".2.ParameterValue", "1000"); + + handler.handle("ModifyClusterParameterGroup", params); + } + + ArgumentCaptor> updates = ArgumentCaptor.captor(); + verify(service, times(2)).modifyClusterParameterGroup(eq("reset-pg"), updates.capture()); + for (List parameters : updates.getAllValues()) { + assertEquals(List.of("1000", "2000"), parameters.stream().map(Parameter::getParameterValue).toList()); + } + } + + @Test + void resetClusterParameterGroupCountsMembersRatherThanFields() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + for (int index = 1; index <= 20; index++) { + params.putSingle("Parameters.Parameter." + index + ".ParameterName", "max_cursor_result_set_size"); + params.putSingle("Parameters.Parameter." + index + ".ParameterValue", "ignored"); + } + + handler.handle("ResetClusterParameterGroup", params); + + ArgumentCaptor> names = ArgumentCaptor.captor(); + verify(service).resetClusterParameterGroup(eq("reset-pg"), eq(false), names.capture()); + assertEquals(20, names.getValue().size()); + } + + @Test + void resetClusterParameterGroupRejectsMembersWithoutNamesBeforeChoosingResetAll() { + for (String prefix : List.of("Parameters.Parameter", "Parameters.member")) { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle(prefix + ".1.ParameterValue", "1000"); + + AwsException failure = assertThrows(AwsException.class, + () -> handler.handle("ResetClusterParameterGroup", params)); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + params.putSingle(prefix + ".2.ParameterName", "wlm_json_configuration"); + assertThrows(AwsException.class, () -> handler.handle("ResetClusterParameterGroup", params)); + params.putSingle(prefix + ".1.ParameterName", " "); + assertThrows(AwsException.class, () -> handler.handle("ResetClusterParameterGroup", params)); + } + verify(service, never()).resetClusterParameterGroup(any(), anyBoolean(), anyList()); + } + + @Test + void describeClusterParametersFiltersAndSerializesSource() { + Parameter overridden = new Parameter("max_cursor_result_set_size", "1000"); + overridden.setSource("user"); + Parameter engineDefault = new Parameter("wlm_json_configuration", "{}"); + engineDefault.setSource("engine-default"); + when(service.describeClusterParameters("reset-pg")).thenReturn(List.of(overridden, engineDefault)); + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("ParameterGroupName", "reset-pg"); + params.putSingle("Source", "user"); + + Response response = handler.handle("DescribeClusterParameters", params); + + String xml = (String) response.getEntity(); + assertTrue(xml.contains("user")); + assertFalse(xml.contains("wlm_json_configuration")); + } + @BeforeEach void setUp() { service = mock(RedshiftService.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index 326f010bfc..af54fc1e5c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -36,6 +36,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -1415,6 +1416,196 @@ class RedshiftServiceTest { assertEquals("integer", modified.getDataType()); } + @Test + void resetClusterParameterGroupRestoresOnlySelectedDefaults() { + ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); + when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + service.modifyClusterParameterGroup("reset-pg", List.of( + new Parameter("max_cursor_result_set_size", "1000"), + new Parameter("wlm_json_configuration", "custom"))); + + service.resetClusterParameterGroup("reset-pg", false, List.of("max_cursor_result_set_size")); + + List parameters = service.describeClusterParameters("reset-pg"); + assertEquals("0", parameters.get(0).getParameterValue()); + assertEquals("engine-default", parameters.get(0).getSource()); + assertEquals("integer", parameters.get(0).getDataType()); + assertEquals("custom", parameters.get(1).getParameterValue()); + assertEquals("user", parameters.get(1).getSource()); + verify(parameterGroupBackend, times(2)).flush(); + } + + @Test + void resetAllClusterParametersDropsOverridesOutsideDefaultCatalog() { + ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); + group.getTags().put("owner", "analytics"); + when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + service.modifyClusterParameterGroup("reset-pg", List.of( + new Parameter("max_cursor_result_set_size", "1000"), new Parameter("custom_parameter", "value"))); + + service.resetClusterParameterGroup("reset-pg", true, List.of()); + + List parameters = service.describeClusterParameters("reset-pg"); + assertEquals(2, parameters.size()); + assertEquals("0", parameters.get(0).getParameterValue()); + assertEquals("{}", parameters.get(1).getParameterValue()); + assertTrue(parameters.stream().allMatch(parameter -> "engine-default".equals(parameter.getSource()))); + assertEquals("analytics", group.getTags().get("owner")); + assertEquals("description", group.getDescription()); + } + + @Test + void resetClusterParametersValidatesEveryNameBeforeMutating() { + ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); + group.getParameters().get(0).setParameterValue("1000"); + when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + + AwsException failure = assertThrows(AwsException.class, () -> service.resetClusterParameterGroup( + "reset-pg", false, List.of("max_cursor_result_set_size", "missing"))); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + assertEquals("1000", group.getParameters().get(0).getParameterValue()); + verify(parameterGroupBackend, never()).put(anyString(), any()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void resetClusterParameterGroupRejectsMissingGroup() { + AwsException failure = assertThrows(AwsException.class, + () -> service.resetClusterParameterGroup("missing", true, List.of())); + + assertEquals("ClusterParameterGroupNotFound", failure.getErrorCode()); + assertEquals(404, failure.getHttpStatus()); + } + + @Test + void resetClusterParameterGroupRejectsDefaultGroup() { + AwsException failure = assertThrows(AwsException.class, () -> service.resetClusterParameterGroup( + RedshiftService.DEFAULT_PARAMETER_GROUP_NAME, true, List.of())); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void createClusterParameterGroupRejectsReservedDefaultName() { + AwsException failure = assertThrows(AwsException.class, () -> service.createClusterParameterGroup( + RedshiftService.DEFAULT_PARAMETER_GROUP_NAME, "redshift-1.0", "custom")); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(parameterGroupBackend, never()).put(anyString(), any()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void describeLegacyDefaultNamedGroupPreservesStoredParameters() { + String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; + ClusterParameterGroup stored = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); + stored.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); + when(parameterGroupBackend.get(name)).thenReturn(Optional.of(stored)); + + assertEquals("legacy custom group", service.describeClusterParameterGroups(name).getFirst().getDescription()); + List parameters = service.describeClusterParameters(name); + + assertEquals(1, parameters.size()); + assertEquals("1000", parameters.getFirst().getParameterValue()); + assertEquals("user", parameters.getFirst().getSource()); + assertEquals("1000", stored.getParameters().getFirst().getParameterValue()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void legacyDefaultNamedGroupCanBeModifiedAndReset() { + String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; + ClusterParameterGroup stored = new ClusterParameterGroup(name, "redshift-1.0", "legacy custom group"); + stored.setParameters(List.of(new Parameter("max_cursor_result_set_size", "1000"))); + when(parameterGroupBackend.get(name)).thenReturn(Optional.of(stored)); + + service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "2000"))); + assertEquals("2000", service.describeClusterParameters(name).getFirst().getParameterValue()); + service.resetClusterParameterGroup(name, false, List.of("max_cursor_result_set_size")); + + assertEquals("0", service.describeClusterParameters(name).getFirst().getParameterValue()); + assertEquals("engine-default", service.describeClusterParameters(name).getFirst().getSource()); + assertEquals("legacy custom group", service.describeClusterParameterGroups(name).getFirst().getDescription()); + verify(parameterGroupBackend, times(2)).put(eq(name), any()); + verify(parameterGroupBackend, times(2)).flush(); + } + + @Test + void implicitDefaultGroupRemainsReadOnly() { + String name = RedshiftService.DEFAULT_PARAMETER_GROUP_NAME; + + List parameters = service.describeClusterParameters(name); + AwsException failure = assertThrows(AwsException.class, + () -> service.modifyClusterParameterGroup(name, List.of(new Parameter("max_cursor_result_set_size", "2000")))); + + assertEquals("0", parameters.getFirst().getParameterValue()); + assertEquals("engine-default", parameters.getFirst().getSource()); + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(parameterGroupBackend, never()).put(anyString(), any()); + } + + @Test + void resetClusterParameterGroupRequiresNamesUnlessResettingAll() { + AwsException failure = assertThrows(AwsException.class, + () -> service.resetClusterParameterGroup("reset-pg", false, List.of())); + + assertEquals("InvalidParameterCombination", failure.getErrorCode()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void resetClusterParameterGroupRejectsConflictingOptions() { + AwsException failure = assertThrows(AwsException.class, () -> service.resetClusterParameterGroup( + "reset-pg", true, List.of("max_cursor_result_set_size"))); + + assertEquals("InvalidParameterCombination", failure.getErrorCode()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void resetClusterParameterGroupRejectsMoreThanTwentyParameters() { + AwsException failure = assertThrows(AwsException.class, () -> service.resetClusterParameterGroup( + "reset-pg", false, Collections.nCopies(21, "max_cursor_result_set_size"))); + + assertEquals("InvalidParameterValue", failure.getErrorCode()); + verify(parameterGroupBackend, never()).flush(); + } + + @Test + void describeLegacyClusterParametersInfersSourceWithoutChangingStoredValues() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + ClusterParameterGroup group = mapper.readValue(""" + {"parameterGroupName":"legacy", "parameters":[ + {"parameterName":"max_cursor_result_set_size","parameterValue":"0"}, + {"parameterName":"wlm_json_configuration","parameterValue":"custom"} + ]} + """, ClusterParameterGroup.class); + when(parameterGroupBackend.get("legacy")).thenReturn(Optional.of(group)); + + List parameters = service.describeClusterParameters("legacy"); + + assertEquals("engine-default", parameters.get(0).getSource()); + assertEquals("user", parameters.get(1).getSource()); + assertNull(group.getParameters().get(0).getSource()); + } + + @Test + void resetSourceSurvivesSerialization() throws Exception { + ClusterParameterGroup group = new ClusterParameterGroup("reset-pg", "redshift-1.0", "description"); + when(parameterGroupBackend.get("reset-pg")).thenReturn(Optional.of(group)); + service.modifyClusterParameterGroup("reset-pg", List.of(new Parameter("max_cursor_result_set_size", "0"))); + assertEquals("user", service.describeClusterParameters("reset-pg").getFirst().getSource()); + service.resetClusterParameterGroup("reset-pg", true, List.of()); + ObjectMapper mapper = new ObjectMapper(); + + ClusterParameterGroup reloaded = mapper.readValue(mapper.writeValueAsString(group), ClusterParameterGroup.class); + + assertEquals("engine-default", reloaded.getParameters().getFirst().getSource()); + assertEquals("0", reloaded.getParameters().getFirst().getParameterValue()); + } + @Test void createAndListTagsForCluster() { Cluster cluster = new Cluster();