Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(iot): honour attributePayload.merge, thingTypeName and expectedVersion on things (#6657)

Mario Toffiac6505c9144e6
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
index fb625d43eb..1750362cd0 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotTest.java
@@ -1020,6 +1020,80 @@ class IotTest {
iot.deleteThingType(DeleteThingTypeRequest.builder().thingTypeName(thingType).build());
}
+ @Test
+ void thingUpdateHonoursMergeThingTypeAndExpectedVersion() {
+ // AWS keeps a deprecated thing type for five minutes before it can be deleted, so on AWS the
+ // test borrows a test thing type the account already has, as fleetIndexSearch does.
+ String thingType = TestFixtures.isRealAws() ? existingTestThingType() : "java-iot-update-type";
+ assertThat(thingType)
+ .as("on AWS the account needs an active thing type whose name contains \"test\"")
+ .isNotNull();
+ String thingName = "java-iot-update-thing";
+ try {
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).build());
+ } catch (Exception ignored) {
+ // Nothing is left over from an earlier run.
+ }
+ if (!TestFixtures.isRealAws()) {
+ deleteThingTypeQuietly(thingType);
+ iot.createThingType(CreateThingTypeRequest.builder().thingTypeName(thingType).build());
+ }
+ iot.createThing(CreateThingRequest.builder()
+ .thingName(thingName)
+ .attributePayload(AttributePayload.builder().attributes(Map.of("env", "java", "owner", "iot")).build())
+ .build());
+
+ iot.updateThing(UpdateThingRequest.builder()
+ .thingName(thingName)
+ .attributePayload(AttributePayload.builder()
+ .attributes(Map.of("fw", "1.2", "owner", ""))
+ .merge(true)
+ .build())
+ .build());
+ DescribeThingResponse merged = iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build());
+ assertThat(merged.attributes()).isEqualTo(Map.of("env", "java", "fw", "1.2"));
+
+ iot.updateThing(UpdateThingRequest.builder().thingName(thingName).thingTypeName(thingType).build());
+ DescribeThingResponse typed = iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build());
+ assertThat(typed.thingTypeName()).isEqualTo(thingType);
+ assertThat(typed.attributes()).isEqualTo(Map.of("env", "java", "fw", "1.2"));
+
+ iot.updateThing(UpdateThingRequest.builder().thingName(thingName).removeThingType(true).build());
+ DescribeThingResponse untyped = iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build());
+ assertThat(untyped.thingTypeName()).isNull();
+
+ assertThatThrownBy(() -> iot.updateThing(UpdateThingRequest.builder()
+ .thingName(thingName)
+ .thingTypeName(thingType)
+ .removeThingType(true)
+ .build()))
+ .isInstanceOf(InvalidRequestException.class);
+
+ long version = untyped.version();
+ assertThatThrownBy(() -> iot.deleteThing(DeleteThingRequest.builder()
+ .thingName(thingName)
+ .expectedVersion(version - 1)
+ .build()))
+ .isInstanceOf(VersionConflictException.class);
+ assertThat(iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build()).version()).isEqualTo(version);
+
+ iot.deleteThing(DeleteThingRequest.builder().thingName(thingName).expectedVersion(version).build());
+ assertThatThrownBy(() -> iot.describeThing(DescribeThingRequest.builder().thingName(thingName).build()))
+ .isInstanceOf(ResourceNotFoundException.class);
+ if (!TestFixtures.isRealAws()) {
+ deleteThingTypeQuietly(thingType);
+ }
+ }
+
+ private void deleteThingTypeQuietly(String thingType) {
+ try {
+ iot.deprecateThingType(DeprecateThingTypeRequest.builder().thingTypeName(thingType).build());
+ iot.deleteThingType(DeleteThingTypeRequest.builder().thingTypeName(thingType).build());
+ } catch (Exception ignored) {
+ // Absent: nothing is left over from an earlier run.
+ }
+ }
+
@Test
void mqttConnectPublishSubscribe() throws Exception {
String topic = "devices/java-iot-mqtt/events";
diff --git a/docs/services/iot.md b/docs/services/iot.md
index 4914722c5c..888df8bd19 100644
--- a/docs/services/iot.md
+++ b/docs/services/iot.md
@@ -8,7 +8,7 @@ Status: complete for the local emulator slice.
Supported MVP 1 behavior:
-- Thing CRUD with idempotent identical `CreateThing`, duplicate-conflict semantics, `UpdateThing.expectedVersion`, and list pagination.
+- Thing CRUD with idempotent identical `CreateThing`, duplicate-conflict semantics, `UpdateThing.expectedVersion`, and list pagination. `UpdateThing` honours `attributePayload.merge` (an empty value removes an attribute), `thingTypeName` and `removeThingType`, and `DeleteThing` honours `expectedVersion`.
- Certificate basics: `CreateKeysAndCertificate`, `CreateCertificateFromCsr`, `DescribeCertificate`, `ListCertificates`, `UpdateCertificate`, and `DeleteCertificate` with active/attached delete constraints. `CreateKeysAndCertificate` returns a real X.509 client certificate issued by Floci's local CA (`GET /_floci/ca.pem`) with a fresh RSA 2048 key pair, valid until 2049-12-31T23:59:59Z as on AWS, and `certificateId` is the SHA-256 of the certificate's DER encoding as on AWS. `DescribeCertificate` reports `validity` and `certificateMode`. `CreateCertificateFromCsr` signs the request's public key (RSA of at least 2048 bits, or EC on P-256, P-384 or P-521) with the same CA and, as on AWS, returns no private key. `RegisterCertificateWithoutCA` registers a certificate from any issuer, as on AWS: no CA is checked, the status defaults to `INACTIVE`, `DescribeCertificate` reports `certificateMode` `SNI_ONLY`, a certificate already registered is `ResourceAlreadyExistsException`, and a PEM that does not parse is `CertificateValidationException`.
- Policy basics: `CreatePolicy`, `GetPolicy`, `ListPolicies`, `DeletePolicy`, policy version lifecycle, `AttachPolicy`, `DetachPolicy`, `ListAttachedPolicies`, and `ListTargetsForPolicy`.
- Thing principal basics: `AttachThingPrincipal`, `DetachThingPrincipal`, `ListThingPrincipals`, `ListPrincipalThings`, and the paginated `ListThingPrincipalsV2` and `ListPrincipalThingsV2`. Exclusive attachment is not modelled, so the V2 lists report every attachment as `NON_EXCLUSIVE_THING`, and a `thingPrincipalType` filter of `EXCLUSIVE_THING` returns none.
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
index b07c44a7d2..84ac0d0eda 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotController.java
@@ -112,21 +112,31 @@ public class IotController {
public Response updateThing(@PathParam("thingName") String thingName,
@Context HttpHeaders headers,
String body) {
- String region = regionResolver.resolveRegion(headers);
- Thing thing = iotService.updateThing(thingName, parseAttributes(body), parseExpectedVersion(body), region);
- ObjectNode response = objectMapper.createObjectNode();
- response.put("thingName", thing.getThingName());
- response.put("thingArn", thing.getThingArn());
- response.put("version", thing.getVersion());
- return Response.ok(response).build();
+ try {
+ JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
+ JsonNode payload = request.path("attributePayload");
+ Map<String, String> attributes = payload.path("attributes").isObject() ? parseAttributes(body) : null;
+ Long expectedVersion = request.hasNonNull("expectedVersion") ? request.path("expectedVersion").asLong() : null;
+ Thing thing = iotService.updateThing(thingName, attributes, payload.path("merge").asBoolean(),
+ request.path("thingTypeName").asText(null), request.path("removeThingType").asBoolean(),
+ expectedVersion, regionResolver.resolveRegion(headers));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("thingName", thing.getThingName());
+ response.put("thingArn", thing.getThingArn());
+ response.put("version", thing.getVersion());
+ return Response.ok(response).build();
+ } catch (JsonProcessingException e) {
+ throw new AwsException("InvalidRequestException", e.getMessage(), 400);
+ }
}
@DELETE
@Path("/things/{thingName}")
public Response deleteThing(@PathParam("thingName") String thingName,
+ @QueryParam("expectedVersion") Long expectedVersion,
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
- iotService.deleteThing(thingName, region);
+ iotService.deleteThing(thingName, expectedVersion, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@@ -895,15 +905,6 @@ public class IotController {
}
}
- private Long parseExpectedVersion(String body) {
- try {
- JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
- return request.hasNonNull("expectedVersion") ? request.path("expectedVersion").asLong() : null;
- } catch (JsonProcessingException e) {
- throw new AwsException("InvalidRequestException", e.getMessage(), 400);
- }
- }
-
private String parseThingTypeName(String body) {
try {
JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
index a0bebff1ea..01284f3ef7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.CertificateMaterialException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -60,6 +61,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -86,6 +88,7 @@ public class IotService {
static final String DEFAULT_ENDPOINT_TYPE = "iot:Data-ATS";
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
+ private static final Pattern THING_TYPE_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]+");
private static final Pattern SHADOW_NAME_PATTERN = Pattern.compile("[$a-zA-Z0-9:_-]{1,64}");
/** The {@code FirehoseSeparator} shape of the IoT API model. */
private static final Pattern FIREHOSE_SEPARATOR = Pattern.compile("([\\n\\t])|(\\r\\n)|(,)");
@@ -98,6 +101,8 @@ public class IotService {
/** One lock for every shadow update and delete, so a shadow's previous, current and version stay consistent. */
private final Object shadowWriteLock = new Object();
+ /** One lock for every UpdateThing and DeleteThing, so a merge, a version check and the write are one step. */
+ private final Object thingWriteLock = new Object();
/** certificateId to the partition and key it was last found under; see {@link #findRegisteredCertificate}. */
private final Map<String, CertificateLocation> certificateLocations = new ConcurrentHashMap<>();
@@ -287,25 +292,55 @@ public class IotService {
}
public Thing updateThing(String thingName, Map<String, String> attributes, Long expectedVersion, String region) {
- Thing thing = describeThing(thingName, region);
- if (expectedVersion != null && thing.getVersion() != expectedVersion) {
- throw new AwsException("VersionConflictException", "Thing version does not match expectedVersion", 409);
+ return updateThing(thingName, attributes, false, null, false, expectedVersion, region);
+ }
+
+ /** {@code attributes} is null when the request carries none, which leaves the stored ones as they are. */
+ public Thing updateThing(String thingName, Map<String, String> attributes, boolean merge, String thingTypeName,
+ boolean removeThingType, Long expectedVersion, String region) {
+ if (thingTypeName != null) {
+ validateThingTypeName(thingTypeName);
+ }
+ if (removeThingType && thingTypeName != null) {
+ throw new AwsException("InvalidRequestException", "Cannot remove thing type when thing type is not null", 400);
+ }
+ synchronized (thingWriteLock) {
+ Thing thing = describeThing(thingName, region);
+ if (thingTypeName != null && describeThingType(thingTypeName, region).isDeprecated()) {
+ throw new AwsException("InvalidRequestException",
+ "Can not update a thing to use deprecated thing type: " + thingTypeName, 400);
+ }
+ requireThingVersion(thing, expectedVersion);
+ if (attributes != null) {
+ Map<String, String> updated = merge ? new HashMap<>(thing.getAttributes()) : new HashMap<>();
+ updated.putAll(attributes);
+ updated.values().removeIf(String::isEmpty);
+ thing.setAttributes(updated);
+ }
+ if (thingTypeName != null || removeThingType) {
+ thing.setThingTypeName(thingTypeName);
+ }
+ thing.setVersion(thing.getVersion() + 1);
+ thing.setLastModifiedDate(Instant.now());
+ thingStore.put(thingKey(region, thingName), thing);
+ return thing;
}
- thing.setAttributes(attributes);
- thing.setVersion(thing.getVersion() + 1);
- thing.setLastModifiedDate(Instant.now());
- thingStore.put(thingKey(region, thingName), thing);
- return thing;
}
public void deleteThing(String thingName, String region) {
- describeThing(thingName, region);
- thingStore.delete(thingKey(region, thingName));
- for (String key : thingGroupMembershipStore.keys()) {
- if (key.startsWith("thing-group-membership:" + region + ":")) {
- Set<String> members = new HashSet<>(thingGroupMembershipStore.get(key).orElse(Set.of()));
- if (members.remove(thingName)) {
- thingGroupMembershipStore.put(key, members);
+ deleteThing(thingName, null, region);
+ }
+
+ public void deleteThing(String thingName, Long expectedVersion, String region) {
+ synchronized (thingWriteLock) {
+ requireThingVersion(describeThing(thingName, region), expectedVersion);
+ thingStore.delete(thingKey(region, thingName));
+ for (String key : thingGroupMembershipStore.keys()) {
+ if (key.startsWith("thing-group-membership:" + region + ":")) {
+ Set<String> members = new HashSet<>(thingGroupMembershipStore.get(key).orElse(Set.of()));
+ if (members.remove(thingName)) {
+ thingGroupMembershipStore.put(key, members);
+ }
}
}
}
@@ -1667,6 +1702,28 @@ public class IotService {
}
}
+ private static void validateThingTypeName(String thingTypeName) {
+ List<String> violations = new ArrayList<>();
+ String length = SmithyValidationErrors.lengthOutOfRange("thingTypeName", thingTypeName, 1, 128);
+ if (length != null) {
+ violations.add(length);
+ }
+ if (!THING_TYPE_NAME_PATTERN.matcher(thingTypeName).matches()) {
+ violations.add(SmithyValidationErrors.pattern("thingTypeName", thingTypeName,
+ THING_TYPE_NAME_PATTERN.pattern()));
+ }
+ if (!violations.isEmpty()) {
+ throw SmithyValidationErrors.exception("InvalidRequestException", violations);
+ }
+ }
+
+ private static void requireThingVersion(Thing thing, Long expectedVersion) {
+ if (expectedVersion != null && thing.getVersion() != expectedVersion) {
+ throw new AwsException("VersionConflictException",
+ "The version for thing " + thing.getThingName() + " does not match the expected version.", 409);
+ }
+ }
+
private void validateMqttClientId(String clientId) {
if (clientId == null || clientId.isBlank() || clientId.length() > 128 || clientId.startsWith("$")) {
throw new AwsException("InvalidRequestException", "Invalid MQTT clientId: " + clientId, 400);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
index caa5f7d000..fd3dff1d36 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotIntegrationTest.java
@@ -965,6 +965,109 @@ class IotIntegrationTest {
.body("__type", equalTo("InvalidRequestException"));
}
+ @Test
+ @Order(23)
+ void updateThingMergesAttributesAndSetsAndRemovesTheThingType() {
+ given()
+ .contentType("application/json")
+ .body("{\"thingTypeProperties\":{\"thingTypeDescription\":\"update semantics\"}}")
+ .when()
+ .post("/thing-types/update-semantics-type")
+ .then()
+ .statusCode(200);
+ given()
+ .contentType("application/json")
+ .body("{\"attributePayload\":{\"attributes\":{\"a\":\"1\",\"b\":\"2\"}}}")
+ .when()
+ .post("/things/update-semantics-thing")
+ .then()
+ .statusCode(200);
+
+ patchThing("update-semantics-thing", "{\"attributePayload\":{\"attributes\":{\"b\":\"\",\"c\":\"3\"},\"merge\":true}}", 2);
+ patchThing("update-semantics-thing", "{\"attributePayload\":{\"merge\":true}}", 3);
+
+ given()
+ .when()
+ .get("/things/update-semantics-thing")
+ .then()
+ .statusCode(200)
+ .body("attributes.size()", equalTo(2))
+ .body("attributes.a", equalTo("1"))
+ .body("attributes.c", equalTo("3"))
+ .body("attributes.b", nullValue())
+ .body("attributes.merge", nullValue());
+
+ patchThing("update-semantics-thing", "{\"thingTypeName\":\"update-semantics-type\"}", 4);
+
+ given()
+ .when()
+ .get("/things/update-semantics-thing")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", equalTo("update-semantics-type"))
+ .body("attributes.size()", equalTo(2));
+
+ patchThing("update-semantics-thing", "{\"removeThingType\":true}", 5);
+
+ given()
+ .when()
+ .get("/things/update-semantics-thing")
+ .then()
+ .statusCode(200)
+ .body("thingTypeName", nullValue())
+ .body("attributes.a", equalTo("1"))
+ .body("version", equalTo(5));
+
+ given().when().delete("/things/update-semantics-thing").then().statusCode(200);
+ given().when().post("/thing-types/update-semantics-type/deprecate").then().statusCode(200);
+ given().when().delete("/thing-types/update-semantics-type").then().statusCode(200);
+ }
+
+ @Test
+ @Order(24)
+ void deleteThingWithAStaleExpectedVersionIsAVersionConflict() {
+ createThingAndReturnArn("stale-delete-thing");
+
+ given()
+ .queryParam("expectedVersion", 7)
+ .when()
+ .delete("/things/stale-delete-thing")
+ .then()
+ .statusCode(409)
+ .body("__type", equalTo("VersionConflictException"))
+ .body("message", equalTo("The version for thing stale-delete-thing does not match the expected version."));
+
+ given()
+ .when()
+ .get("/things/stale-delete-thing")
+ .then()
+ .statusCode(200);
+
+ given()
+ .queryParam("expectedVersion", 1)
+ .when()
+ .delete("/things/stale-delete-thing")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/things/stale-delete-thing")
+ .then()
+ .statusCode(404);
+ }
+
+ private static void patchThing(String thingName, String body, int expectedVersionAfter) {
+ given()
+ .contentType("application/json")
+ .body(body)
+ .when()
+ .patch("/things/" + thingName)
+ .then()
+ .statusCode(200)
+ .body("version", equalTo(expectedVersionAfter));
+ }
+
private String createThingAndReturnArn(String thingName) {
return given()
.contentType("application/json")
diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
index 0b8a53f248..4409ea66c4 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.iot.model.IotPolicy;
import io.github.hectorvent.floci.services.iot.model.IotShadow;
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
+import io.github.hectorvent.floci.services.iot.model.Thing;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -33,6 +34,8 @@ import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -42,6 +45,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -71,7 +75,9 @@ import static org.mockito.Mockito.when;
* failure document, and the {@code firehose} and {@code cloudwatchLogs} actions deliver the payload.
* Also the five-version cap on a policy, including under racing creates, the device shadow
* events that reach MQTT subscribers and topic rules on the AWS response topics, and one stored
- * registration when identical RegisterCertificateWithoutCA calls race.
+ * registration when identical RegisterCertificateWithoutCA calls race. Last, how UpdateThing and
+ * DeleteThing treat the attributes, the thing type and the expected version, including racing merges
+ * and racing versioned updates and deletes.
*/
class IotServiceTest {
@@ -1621,4 +1627,275 @@ class IotServiceTest {
assertEquals(List.of(update + "/rejected"), recordedTopics());
assertEquals(List.of(), service.listNamedShadowsForThing("sensor-14", REGION));
}
+
+ @Test
+ void updateThingWithMergePutsTheGivenAttributesAndRemovesTheEmptyOnes() {
+ service.createThing("merged", Map.of("a", "1", "b", "2"), REGION);
+
+ Thing updated = service.updateThing("merged", Map.of("b", "", "c", "3", "missing", ""), true, null, false, null, REGION);
+
+ assertEquals(2L, updated.getVersion());
+ assertEquals(Map.of("a", "1", "c", "3"), service.describeThing("merged", REGION).getAttributes());
+ }
+
+ @Test
+ void updateThingWithoutMergeReplacesTheAttributesAndDropsTheEmptyOnes() {
+ service.createThing("replaced", Map.of("a", "1", "b", "2"), REGION);
+
+ service.updateThing("replaced", Map.of("e", "5", "f", ""), false, null, false, null, REGION);
+
+ assertEquals(Map.of("e", "5"), service.describeThing("replaced", REGION).getAttributes());
+ }
+
+ @Test
+ void updateThingWithoutAttributesKeepsThemAndAnEmptyMapClearsThemOnlyWithoutMerge() {
+ service.createThing("kept", Map.of("a", "1"), REGION);
+
+ service.updateThing("kept", null, true, null, false, null, REGION);
+ service.updateThing("kept", null, false, null, false, null, REGION);
+ service.updateThing("kept", Map.of(), true, null, false, null, REGION);
+
+ Thing kept = service.describeThing("kept", REGION);
+ assertEquals(Map.of("a", "1"), kept.getAttributes());
+ assertEquals(4L, kept.getVersion());
+
+ service.updateThing("kept", Map.of(), false, null, false, null, REGION);
+
+ Thing cleared = service.describeThing("kept", REGION);
+ assertEquals(Map.of(), cleared.getAttributes());
+ assertEquals(5L, cleared.getVersion());
+ }
+
+ @Test
+ void updateThingSetsAndRemovesTheThingTypeAndKeepsTheAttributes() {
+ service.createThingType("sensor-type", mapper.createObjectNode(), REGION);
+ service.createThing("typed", Map.of("a", "1"), REGION);
+
+ service.updateThing("typed", null, false, "sensor-type", false, null, REGION);
+
+ Thing typed = service.describeThing("typed", REGION);
+ assertEquals("sensor-type", typed.getThingTypeName());
+ assertEquals(Map.of("a", "1"), typed.getAttributes());
+
+ service.updateThing("typed", null, false, null, true, null, REGION);
+ assertNull(service.describeThing("typed", REGION).getThingTypeName());
+ assertDoesNotThrow(() -> service.updateThing("typed", null, false, null, true, null, REGION));
+
+ Thing untyped = service.describeThing("typed", REGION);
+ assertNull(untyped.getThingTypeName());
+ assertEquals(Map.of("a", "1"), untyped.getAttributes());
+ assertEquals(4L, untyped.getVersion());
+ }
+
+ @Test
+ void updateThingRejectsRemovingTheTypeWhileNamingOneBeforeLookingUpTheThing() {
+ service.createThingType("sensor-type", mapper.createObjectNode(), REGION);
+ service.createThing("typed", Map.of("a", "1"), REGION);
+
+ for (String thingName : List.of("typed", "no-such-thing")) {
+ AwsException e = assertThrows(AwsException.class,
+ () -> service.updateThing(thingName, null, false, "sensor-type", true, 99L, REGION));
+ assertEquals("InvalidRequestException", e.getErrorCode(), thingName);
+ assertEquals(400, e.getHttpStatus(), thingName);
+ assertEquals("Cannot remove thing type when thing type is not null", e.getMessage(), thingName);
+ }
+ Thing unchanged = service.describeThing("typed", REGION);
+ assertNull(unchanged.getThingTypeName());
+ assertEquals(1L, unchanged.getVersion());
+ }
+
+ @Test
+ void updateThingLooksUpTheThingTypeBeforeTheVersionAndRejectsADeprecatedType() {
+ service.createThing("typed", Map.of("a", "1"), REGION);
+ service.createThingType("old-type", mapper.createObjectNode(), REGION);
+ service.deprecateThingType("old-type", REGION);
+
+ AwsException missing = assertThrows(AwsException.class,
+ () -> service.updateThing("typed", null, false, "no-such-type", false, 99L, REGION));
+ assertEquals("ResourceNotFoundException", missing.getErrorCode());
+ assertEquals(404, missing.getHttpStatus());
+
+ AwsException deprecated = assertThrows(AwsException.class,
+ () -> service.updateThing("typed", Map.of("b", "2"), false, "old-type", false, 99L, REGION));
+ assertEquals("InvalidRequestException", deprecated.getErrorCode());
+ assertEquals(400, deprecated.getHttpStatus());
+ assertEquals("Can not update a thing to use deprecated thing type: old-type", deprecated.getMessage());
+
+ Thing unchanged = service.describeThing("typed", REGION);
+ assertNull(unchanged.getThingTypeName());
+ assertEquals(Map.of("a", "1"), unchanged.getAttributes());
+ assertEquals(1L, unchanged.getVersion());
+ }
+
+ @Test
+ void updateThingRejectsAnEmptyOrMalformedThingTypeName() {
+ service.createThingType("sensor-type", mapper.createObjectNode(), REGION);
+ service.createThing("typed", Map.of("a", "1"), "sensor-type", REGION);
+
+ String tooLong = "a".repeat(129);
+ String tooLongWithSpace = "a".repeat(128) + " ";
+ String emptyMessage = "2 validation errors detected: "
+ + "Value '' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1; "
+ + "Value '' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9:_-]+";
+ Map<String, String> expectedMessages = new LinkedHashMap<>();
+ expectedMessages.put("", emptyMessage);
+ expectedMessages.put(" ", "1 validation error detected: "
+ + "Value ' ' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9:_-]+");
+ expectedMessages.put("bad type", "1 validation error detected: "
+ + "Value 'bad type' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9:_-]+");
+ expectedMessages.put(tooLong, "1 validation error detected: "
+ + "Value '" + tooLong + "' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 128");
+ expectedMessages.put(tooLongWithSpace, "2 validation errors detected: "
+ + "Value '" + tooLongWithSpace + "' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 128; "
+ + "Value '" + tooLongWithSpace + "' at 'thingTypeName' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: [a-zA-Z0-9:_-]+");
+
+ for (Map.Entry<String, String> expected : expectedMessages.entrySet()) {
+ String thingTypeName = expected.getKey();
+ AwsException e = assertThrows(AwsException.class,
+ () -> service.updateThing("typed", null, false, thingTypeName, false, null, REGION));
+ assertEquals("InvalidRequestException", e.getErrorCode(), thingTypeName);
+ assertEquals(400, e.getHttpStatus(), thingTypeName);
+ assertEquals(expected.getValue(), e.getMessage(), thingTypeName);
+ }
+ AwsException removeWithEmpty = assertThrows(AwsException.class,
+ () -> service.updateThing("typed", null, false, "", true, null, REGION));
+ assertEquals("InvalidRequestException", removeWithEmpty.getErrorCode());
+ assertEquals(400, removeWithEmpty.getHttpStatus());
+ assertEquals(emptyMessage, removeWithEmpty.getMessage());
+
+ Thing unchanged = service.describeThing("typed", REGION);
+ assertEquals("sensor-type", unchanged.getThingTypeName());
+ assertEquals(Map.of("a", "1"), unchanged.getAttributes());
+ assertEquals(1L, unchanged.getVersion());
+ }
+
+ @Test
+ void concurrentMergeUpdatesKeepEveryAttribute() throws Exception {
+ service.createThing("raced", Map.of(), REGION);
+ int writers = 8;
+ int updatesPerWriter = 50;
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService pool = Executors.newFixedThreadPool(writers);
+ List<Future<?>> outcomes = new ArrayList<>();
+ try {
+ for (int i = 0; i < writers; i++) {
+ int writer = i;
+ outcomes.add(pool.submit(() -> {
+ start.await();
+ for (int update = 0; update < updatesPerWriter; update++) {
+ service.updateThing("raced", Map.of("t" + writer + "-" + update, "v"), true, null, false, null, REGION);
+ }
+ return null;
+ }));
+ }
+ start.countDown();
+ for (Future<?> outcome : outcomes) {
+ outcome.get(60, TimeUnit.SECONDS);
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+
+ Map<String, String> expected = new HashMap<>();
+ for (int writer = 0; writer < writers; writer++) {
+ for (int update = 0; update < updatesPerWriter; update++) {
+ expected.put("t" + writer + "-" + update, "v");
+ }
+ }
+ Thing raced = service.describeThing("raced", REGION);
+ assertEquals(expected, raced.getAttributes());
+ assertEquals(writers * updatesPerWriter + 1L, raced.getVersion());
+ }
+
+ @Test
+ void racingVersionedUpdatesAndDeletesConsumeAnExpectedVersionOnce() throws Exception {
+ Set<String> losers = Set.of("VersionConflictException", "ResourceNotFoundException");
+ ExecutorService pool = Executors.newFixedThreadPool(4);
+ try {
+ for (int round = 0; round < 200; round++) {
+ String name = "cas-" + round;
+ service.createThing(name, Map.of("a", "1"), REGION);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<String>> outcomes = new ArrayList<>();
+ for (int i = 0; i < 2; i++) {
+ outcomes.add(pool.submit(() -> {
+ start.await();
+ try {
+ service.updateThing(name, Map.of("b", "2"), true, null, false, 1L, REGION);
+ return "update";
+ } catch (AwsException e) {
+ return e.getErrorCode();
+ }
+ }));
+ outcomes.add(pool.submit(() -> {
+ start.await();
+ try {
+ service.deleteThing(name, 1L, REGION);
+ return "delete";
+ } catch (AwsException e) {
+ return e.getErrorCode();
+ }
+ }));
+ }
+ start.countDown();
+ List<String> results = new ArrayList<>();
+ for (Future<String> outcome : outcomes) {
+ results.add(outcome.get(60, TimeUnit.SECONDS));
+ }
+
+ String context = "round " + round + ": " + results;
+ List<String> winners = new ArrayList<>();
+ for (String result : results) {
+ if (result.equals("update") || result.equals("delete")) {
+ winners.add(result);
+ } else {
+ assertTrue(losers.contains(result), context);
+ }
+ }
+ assertEquals(1, winners.size(), context);
+ if (winners.getFirst().equals("update")) {
+ Thing updated = service.describeThing(name, REGION);
+ assertEquals(2L, updated.getVersion(), context);
+ assertEquals(Map.of("a", "1", "b", "2"), updated.getAttributes(), context);
+ } else {
+ AwsException gone = assertThrows(AwsException.class, () -> service.describeThing(name, REGION), context);
+ assertEquals("ResourceNotFoundException", gone.getErrorCode(), context);
+ }
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ }
+
+ @Test
+ void aStaleExpectedVersionIsAVersionConflictOnUpdateAndDeleteAndKeepsTheThing() {
+ service.createThing("versioned", Map.of("a", "1"), REGION);
+ service.updateThing("versioned", Map.of("a", "2"), false, null, false, 1L, REGION);
+ String message = "The version for thing versioned does not match the expected version.";
+
+ AwsException update = assertThrows(AwsException.class,
+ () -> service.updateThing("versioned", Map.of("a", "3"), false, null, false, 1L, REGION));
+ AwsException delete = assertThrows(AwsException.class, () -> service.deleteThing("versioned", 1L, REGION));
+
+ for (AwsException e : List.of(update, delete)) {
+ assertEquals("VersionConflictException", e.getErrorCode());
+ assertEquals(409, e.getHttpStatus());
+ assertEquals(message, e.getMessage());
+ }
+ Thing kept = service.describeThing("versioned", REGION);
+ assertEquals(Map.of("a", "2"), kept.getAttributes());
+ assertEquals(2L, kept.getVersion());
+
+ service.deleteThing("versioned", 2L, REGION);
+
+ assertEquals("ResourceNotFoundException",
+ assertThrows(AwsException.class, () -> service.describeThing("versioned", REGION)).getErrorCode());
+ }
}