Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(emr-serverless): tag, untag and list tags for applications (#4667)

David5aad012e7848
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 6379645ffb..bc3f0a49d0 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -346,6 +346,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>emr</artifactId>
</dependency>
+ <!-- EMR Serverless client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>emrserverless</artifactId>
+ </dependency>
<!-- WAF v2 client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index abb6276214..afa787a256 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -19,6 +19,7 @@ import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient;
import software.amazon.awssdk.services.emr.EmrClient;
+import software.amazon.awssdk.services.emrserverless.EmrServerlessClient;
import software.amazon.awssdk.services.wafv2.Wafv2Client;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
@@ -902,6 +903,14 @@ public final class TestFixtures {
.build();
}
+ public static EmrServerlessClient emrServerlessClient() {
+ return EmrServerlessClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static Wafv2Client wafv2Client() {
return Wafv2Client.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrServerlessTagTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrServerlessTagTest.java
new file mode 100644
index 0000000000..9c450aa539
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EmrServerlessTagTest.java
@@ -0,0 +1,73 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.emrserverless.EmrServerlessClient;
+import software.amazon.awssdk.services.emrserverless.model.CreateApplicationResponse;
+import software.amazon.awssdk.services.emrserverless.model.ResourceNotFoundException;
+
+import java.util.Map;
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("EMR Serverless tags")
+class EmrServerlessTagTest {
+
+ private static EmrServerlessClient emr;
+ private static String applicationId;
+ private static String arn;
+
+ @BeforeAll
+ static void setup() {
+ emr = TestFixtures.emrServerlessClient();
+ CreateApplicationResponse created = emr.createApplication(r -> r
+ .name(TestFixtures.uniqueName("tagged-app"))
+ .releaseLabel("emr-7.5.0")
+ .type("SPARK")
+ .clientToken(UUID.randomUUID().toString())
+ .tags(Map.of("team", "data")));
+ applicationId = created.applicationId();
+ arn = created.arn();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (emr == null) {
+ return;
+ }
+ try {
+ emr.deleteApplication(r -> r.applicationId(applicationId));
+ }
+ catch (Exception ignored) {
+ // Cleanup is best effort: the application is unique to this run and the emulator is disposable.
+ }
+ emr.close();
+ }
+
+ @Test
+ @DisplayName("TagResource, UntagResource and ListTagsForResource round trip on the application ARN")
+ void tagRoundTrip() {
+ assertThat(emr.listTagsForResource(r -> r.resourceArn(arn)).tags()).containsExactly(Map.entry("team", "data"));
+
+ emr.tagResource(r -> r.resourceArn(arn).tags(Map.of("env", "dev", "team", "platform")));
+ assertThat(emr.listTagsForResource(r -> r.resourceArn(arn)).tags())
+ .containsOnly(Map.entry("team", "platform"), Map.entry("env", "dev"));
+ assertThat(emr.getApplication(r -> r.applicationId(applicationId)).application().tags())
+ .containsEntry("env", "dev");
+
+ emr.untagResource(r -> r.resourceArn(arn).tagKeys("env"));
+ assertThat(emr.listTagsForResource(r -> r.resourceArn(arn)).tags()).containsOnly(Map.entry("team", "platform"));
+ }
+
+ @Test
+ @DisplayName("An unknown application is ResourceNotFoundException")
+ void unknownApplication() {
+ String missing = arn.substring(0, arn.lastIndexOf('/') + 1) + "00missing00";
+ assertThatThrownBy(() -> emr.listTagsForResource(r -> r.resourceArn(missing)))
+ .isInstanceOf(ResourceNotFoundException.class);
+ }
+}
diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md
index ec13b85a0e..ccc902cbab 100644
--- a/docs/services/emr-serverless.md
+++ b/docs/services/emr-serverless.md
@@ -20,10 +20,19 @@ The emulator implements the standard AWS `emr-serverless` service endpoints:
* `DELETE /applications/{applicationId}` (DeleteApplication)
* `POST /applications/{applicationId}/start` (StartApplication)
* `POST /applications/{applicationId}/stop` (StopApplication)
+* `POST /tags/{resourceArn}` (TagResource)
+* `DELETE /tags/{resourceArn}?tagKeys=...` (UntagResource)
+* `GET /tags/{resourceArn}` (ListTagsForResource)
+
+The tagging operations work on application ARNs, as `CreateApplication` returns them
+(`arn:aws:emr-serverless:<region>:<account>:/applications/<id>`). They share the tags `CreateApplication`
+stores, so `GetApplication` always reports the current set. Following the EMR Serverless user guide, a
+resource holds at most 50 tags, and `aws:` in any case is reserved as the prefix of a tag key or value.
## Limitations and Differences from AWS
* **Jobs not implemented**: Floci supports the provisioning of the `Application` management plane (which satisfies tools like Terraform's `aws_emrserverless_application` resource). Executing actual Spark or Hive jobs against these applications via `StartJobRun` is not currently implemented.
* **Instant Start/Stop**: Floci marks the application `STARTED` or `STOPPED` immediately without provisioning actual compute capacity in the background.
* **Data Plane**: Floci does not implement the data-plane API or any execution environments.
-* **Tagging APIs**: `TagResource`, `UntagResource`, and `ListTagsForResource` are currently unsupported.
+* **Job run tags**: job runs are not emulated, so a job run ARN (`.../jobruns/<id>`) answers
+ `ResourceNotFoundException` on the tagging APIs.
diff --git a/docs/services/index.md b/docs/services/index.md
index a8e3105d5d..793122cc9d 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -78,7 +78,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [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 | 8 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 |
-| [EMR Serverless](emr-serverless.md) | `/applications/*` | REST JSON | 7 |
+| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 10 |
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 6 |
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 58 |
| [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 17 |
diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java
index 090c6188a4..acf369f9bd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessService.java
@@ -19,14 +19,25 @@ import jakarta.inject.Inject;
import java.time.Instant;
import java.util.Date;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
public class EmrServerlessService {
+ // The EMR Serverless user guide's tagging limitations: at most 50 user-created tags per resource
+ // (the model's TagMap max of 200 only bounds a single request), and no "aws:" prefix, in any case,
+ // on a key or a value. TagKey and TagValue share one character set in the API model.
+ private static final int MAX_TAGS = 50;
+ private static final String RESERVED_PREFIX = "aws:";
+ private static final Pattern TAG_TEXT = Pattern.compile("[A-Za-z0-9 /_.:=+@-]*");
+ private static final Pattern RESOURCE = Pattern.compile("/applications/([0-9a-zA-Z]+)(?:/jobruns/([0-9a-zA-Z]+))?");
+
private final EmulatorConfig config;
private final AccountAwareStorageBackend<Application> storage;
@@ -74,6 +85,9 @@ public class EmrServerlessService {
app.setStateDetails("");
app.setCreatedAt(now);
app.setUpdatedAt(now);
+ if (request.getTags() != null) {
+ validateTags(request.getTags());
+ }
app.setTags(request.getTags());
app.setArchitecture(request.getArchitecture());
app.setInitialCapacity(request.getInitialCapacity());
@@ -107,7 +121,7 @@ public class EmrServerlessService {
);
}
- public Application updateApplication(String applicationId, UpdateApplicationRequest request) {
+ public synchronized Application updateApplication(String applicationId, UpdateApplicationRequest request) {
Application app = getApplication(applicationId);
String state = app.getState();
@@ -169,7 +183,7 @@ public class EmrServerlessService {
return app;
}
- public void deleteApplication(String applicationId) {
+ public synchronized void deleteApplication(String applicationId) {
Application app = getApplication(applicationId);
String state = app.getState();
if (!"CREATED".equals(state) && !"STOPPED".equals(state)) {
@@ -178,7 +192,7 @@ public class EmrServerlessService {
storage.delete(applicationId);
}
- public void startApplication(String applicationId) {
+ public synchronized void startApplication(String applicationId) {
Application app = getApplication(applicationId);
String state = app.getState();
if ("STARTED".equals(state) || "STARTING".equals(state)) {
@@ -189,7 +203,7 @@ public class EmrServerlessService {
storage.put(applicationId, app);
}
- public void stopApplication(String applicationId) {
+ public synchronized void stopApplication(String applicationId) {
Application app = getApplication(applicationId);
String state = app.getState();
if ("STOPPED".equals(state) || "STOPPING".equals(state)) {
@@ -200,6 +214,104 @@ public class EmrServerlessService {
storage.put(applicationId, app);
}
+ // ---- Tags ---------------------------------------------------------------------------------
+
+ public synchronized Map<String, String> listTags(String arn) {
+ Application app = applicationFor(arn);
+ return app.getTags() != null ? new LinkedHashMap<>(app.getTags()) : new LinkedHashMap<>();
+ }
+
+ /** Adds the tags to the application's, replacing any with the same key. */
+ public synchronized void tagResource(String arn, Map<String, String> tags) {
+ Application app = applicationFor(arn);
+ // An empty map is a valid TagMap (min 0) and changes nothing; the dispatcher already refuses a
+ // missing one.
+ if (tags == null) {
+ throw new AwsException("ValidationException", "tags is required", 400);
+ }
+ validateTags(tags);
+ Map<String, String> merged = app.getTags() != null ? new LinkedHashMap<>(app.getTags()) : new LinkedHashMap<>();
+ merged.putAll(tags);
+ if (merged.size() > MAX_TAGS) {
+ throw new AwsException("ValidationException",
+ "A resource can have at most " + MAX_TAGS + " tags.", 400);
+ }
+ app.setTags(merged);
+ storage.put(app.getApplicationId(), app);
+ }
+
+ public synchronized void untagResource(String arn, List<String> tagKeys) {
+ Application app = applicationFor(arn);
+ if (tagKeys == null || tagKeys.isEmpty()) {
+ throw new AwsException("ValidationException", "tagKeys is required", 400);
+ }
+ tagKeys.forEach(EmrServerlessService::validateTagKey);
+ if (app.getTags() == null || app.getTags().isEmpty()) {
+ return;
+ }
+ Map<String, String> remaining = new LinkedHashMap<>(app.getTags());
+ tagKeys.forEach(remaining::remove);
+ app.setTags(remaining);
+ storage.put(app.getApplicationId(), app);
+ }
+
+ /**
+ * The application an EMR Serverless ARN names:
+ * {@code arn:<partition>:emr-serverless:<region>:<account>:/applications/<id>}, the form
+ * CreateApplication returns. A job run ARN ({@code .../jobruns/<id>}) is refused, as job runs are
+ * not emulated.
+ */
+ private Application applicationFor(String arn) {
+ AwsArnUtils.Arn parsed;
+ try {
+ parsed = AwsArnUtils.parse(arn);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("ValidationException", "Invalid resourceArn: " + arn, 400);
+ }
+ Matcher matcher = RESOURCE.matcher(parsed.resource());
+ if (!"emr-serverless".equals(parsed.service()) || !matcher.matches()) {
+ throw new AwsException("ValidationException", "Invalid resourceArn: " + arn, 400);
+ }
+ if (matcher.group(2) != null) {
+ throw new AwsException("ResourceNotFoundException", "Job run " + matcher.group(2) + " not found", 404);
+ }
+ return storage.get(matcher.group(1))
+ .filter(app -> arn.equals(app.getArn()))
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource " + arn + " not found", 404));
+ }
+
+ /** At most 50 tags, each key and value within TagKey and TagValue and free of the reserved prefix. */
+ private static void validateTags(Map<String, String> tags) {
+ if (tags.size() > MAX_TAGS) {
+ throw new AwsException("ValidationException",
+ "A resource can have at most " + MAX_TAGS + " tags.", 400);
+ }
+ tags.forEach((key, value) -> {
+ validateTagKey(key);
+ if (hasReservedPrefix(key)) {
+ throw new AwsException("ValidationException",
+ "Tag keys may not begin with the reserved prefix aws: (" + key + ")", 400);
+ }
+ if (value == null || value.length() > 256 || !TAG_TEXT.matcher(value).matches()) {
+ throw new AwsException("ValidationException", "Invalid value for tag " + key, 400);
+ }
+ if (hasReservedPrefix(value)) {
+ throw new AwsException("ValidationException",
+ "Tag values may not begin with the reserved prefix aws: (tag " + key + ")", 400);
+ }
+ });
+ }
+
+ private static void validateTagKey(String key) {
+ if (key == null || key.isEmpty() || key.length() > 128 || !TAG_TEXT.matcher(key).matches()) {
+ throw new AwsException("ValidationException", "Invalid tag key: " + key, 400);
+ }
+ }
+
+ private static boolean hasReservedPrefix(String text) {
+ return text.regionMatches(true, 0, RESERVED_PREFIX, 0, RESERVED_PREFIX.length());
+ }
+
private String generateId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagHandler.java
new file mode 100644
index 0000000000..103805062a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagHandler.java
@@ -0,0 +1,60 @@
+package io.github.hectorvent.floci.services.emrserverless;
+
+import io.github.hectorvent.floci.core.common.TagHandler;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * EMR Serverless on the shared {@code /tags/{resourceArn}} path. The wire shape is the common one (a
+ * lowercase {@code tags} map, a {@code tagKeys} query and {@code POST}), except that TagResource and
+ * UntagResource answer 200 rather than 204, and payloads are validated strictly.
+ */
+@ApplicationScoped
+public class EmrServerlessTagHandler implements TagHandler {
+
+ private final EmrServerlessService service;
+
+ @Inject
+ public EmrServerlessTagHandler(EmrServerlessService service) {
+ this.service = service;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "emr-serverless";
+ }
+
+ /** Tag values must be JSON strings, as the model's TagMap declares; nothing is coerced. */
+ @Override
+ public boolean strictTagValidation() {
+ return true;
+ }
+
+ @Override
+ public int tagResourceSuccessStatus() {
+ return 200;
+ }
+
+ @Override
+ public int untagResourceSuccessStatus() {
+ return 200;
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return service.listTags(arn);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ service.tagResource(arn, tags);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ service.untagResource(arn, tagKeys);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagIntegrationTest.java
new file mode 100644
index 0000000000..e374980251
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessTagIntegrationTest.java
@@ -0,0 +1,236 @@
+package io.github.hectorvent.floci.services.emrserverless;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.json.JsonPath;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.aMapWithSize;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@QuarkusTest
+class EmrServerlessTagIntegrationTest {
+
+ @Inject
+ EmrServerlessService service;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static RequestSpecification emr() {
+ return given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=TEST/20260929/us-east-1/emr-serverless/aws4_request, "
+ + "SignedHeaders=host;x-amz-date, Signature=test")
+ .contentType("application/json")
+ .urlEncodingEnabled(false);
+ }
+
+ /** The SDK sends the ARN as one path segment with ':' and '/' percent-encoded. */
+ private static String tagsPath(String arn) {
+ return "/tags/" + URLEncoder.encode(arn, StandardCharsets.UTF_8);
+ }
+
+ private static String[] createApplication(String tagsJson) {
+ JsonPath created = emr()
+ .body("""
+ { "name": "tags-%s", "releaseLabel": "emr-7.5.0", "type": "SPARK",
+ "clientToken": "%s", "tags": %s }
+ """.formatted(UUID.randomUUID().toString().substring(0, 8), UUID.randomUUID(), tagsJson))
+ .when().post("/applications")
+ .then().statusCode(200)
+ .extract().jsonPath();
+ return new String[] {created.getString("applicationId"), created.getString("arn")};
+ }
+
+ @Test
+ void tagsRoundTripOnTheApplicationArnAndShowInGetApplication() {
+ String[] app = createApplication("{ \"team\": \"data\" }");
+ String arn = app[1];
+
+ emr().when().get(tagsPath(arn))
+ .then().statusCode(200)
+ .body("tags.team", equalTo("data"));
+
+ emr().body("{ \"tags\": { \"env\": \"dev\", \"team\": \"platform\" } }")
+ .when().post(tagsPath(arn))
+ .then().statusCode(200);
+
+ emr().when().get(tagsPath(arn))
+ .then().statusCode(200)
+ .body("tags", aMapWithSize(2))
+ .body("tags.team", equalTo("platform"))
+ .body("tags.env", equalTo("dev"));
+ emr().when().get("/applications/" + app[0])
+ .then().statusCode(200)
+ .body("application.tags.env", equalTo("dev"));
+
+ emr().when().delete(tagsPath(arn) + "?tagKeys=env")
+ .then().statusCode(200);
+
+ emr().when().get(tagsPath(arn))
+ .then().statusCode(200)
+ .body("tags", not(hasKey("env")))
+ .body("tags.team", equalTo("platform"));
+ }
+
+ @Test
+ void unknownApplicationsAndJobRunsAreNotFoundAndBadTagsAreRefused() {
+ String arn = createApplication("{}")[1];
+ String missing = arn.substring(0, arn.lastIndexOf('/') + 1) + "00missing00";
+
+ emr().when().get(tagsPath(missing))
+ .then().statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ emr().when().get(tagsPath(arn + "/jobruns/00abc00"))
+ .then().statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ emr().body("{ \"tags\": { \"bad#key\": \"x\" } }")
+ .when().post(tagsPath(arn))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+
+ StringBuilder tooMany = new StringBuilder("{ \"tags\": {");
+ for (int i = 0; i < 51; i++) {
+ tooMany.append(i == 0 ? "" : ",").append("\"k").append(i).append("\": \"v\"");
+ }
+ tooMany.append("} }");
+ emr().body(tooMany.toString())
+ .when().post(tagsPath(arn))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void nonStringValuesAndBadUntagKeysAreRefused() {
+ String arn = createApplication("{}")[1];
+
+ emr().body("{ \"tags\": { \"team\": 123 } }")
+ .when().post(tagsPath(arn))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ emr().when().delete(tagsPath(arn) + "?tagKeys=")
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ emr().when().delete(tagsPath(arn) + "?tagKeys=" + URLEncoder.encode("bad#key", StandardCharsets.UTF_8))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ emr().when().get(tagsPath(arn))
+ .then().statusCode(200)
+ .body("tags", aMapWithSize(0));
+ }
+
+ @Test
+ void createApplicationAppliesTheSameTagRules() {
+ StringBuilder tooMany = new StringBuilder("{");
+ for (int i = 0; i < 51; i++) {
+ tooMany.append(i == 0 ? "" : ",").append("\"k").append(i).append("\": \"v\"");
+ }
+ tooMany.append("}");
+ for (String tags : List.of(tooMany.toString(), "{ \"bad#key\": \"v\" }")) {
+ emr().body("""
+ { "name": "limits", "releaseLabel": "emr-7.5.0", "type": "SPARK",
+ "clientToken": "%s", "tags": %s }
+ """.formatted(UUID.randomUUID(), tags))
+ .when().post("/applications")
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+ }
+
+ /**
+ * The user guide's tagging limitations: at most 50 user-created tags per resource, and "aws:" in any
+ * case is reserved as the prefix of a key or a value. An empty tags map is valid and changes nothing.
+ */
+ @Test
+ void theUserGuideLimitsApplyAndAnEmptyMapIsANoOp() {
+ String arn = createApplication("{ \"team\": \"data\" }")[1];
+ StringBuilder fortyNine = new StringBuilder("{ \"tags\": {");
+ for (int i = 0; i < 49; i++) {
+ fortyNine.append(i == 0 ? "" : ",").append("\"k").append(i).append("\": \"v\"");
+ }
+ fortyNine.append("} }");
+
+ emr().body(fortyNine.toString()).when().post(tagsPath(arn)).then().statusCode(200);
+ emr().when().get(tagsPath(arn)).then().statusCode(200).body("tags", aMapWithSize(50));
+ emr().body("{ \"tags\": { \"one-more\": \"v\" } }")
+ .when().post(tagsPath(arn))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+
+ for (String reserved : List.of("{ \"aws:owner\": \"x\" }", "{ \"AWS:owner\": \"x\" }",
+ "{ \"Aws:owner\": \"x\" }", "{ \"owner\": \"aWs:x\" }")) {
+ emr().body("{ \"tags\": " + reserved + " }")
+ .when().post(tagsPath(arn))
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ emr().body("{ \"tags\": {} }").when().post(tagsPath(arn)).then().statusCode(200);
+ emr().when().get(tagsPath(arn)).then().statusCode(200).body("tags", aMapWithSize(50));
+ }
+
+ /** Tag writes read, change and store the whole application; concurrent ones must not lose each other. */
+ @Test
+ void concurrentTagWritesAreAllKept() throws Exception {
+ String arn = createApplication("{}")[1];
+ int threads = 16;
+ CountDownLatch go = new CountDownLatch(1);
+ ExecutorService pool = Executors.newFixedThreadPool(threads);
+ try {
+ List<Future<?>> futures = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ String key = "k" + i;
+ futures.add(pool.submit(() -> {
+ go.await();
+ service.tagResource(arn, Map.of(key, "v"));
+ return null;
+ }));
+ }
+ go.countDown();
+ for (Future<?> future : futures) {
+ future.get(10, TimeUnit.SECONDS);
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+
+ assertEquals(threads, service.listTags(arn).size());
+ }
+
+ @Test
+ void anEmptyTagMapChangesNothingButMissingTagsOrKeysAreRefused() {
+ String arn = createApplication("{ \"team\": \"data\" }")[1];
+
+ service.tagResource(arn, Map.of());
+ assertEquals(Map.of("team", "data"), service.listTags(arn));
+ assertEquals("ValidationException",
+ assertThrows(AwsException.class,
+ () -> service.tagResource(arn, null)).getErrorCode());
+ assertEquals("ValidationException",
+ assertThrows(AwsException.class,
+ () -> service.untagResource(arn, List.of())).getErrorCode());
+ }
+}