mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(iot): route shadow events through topic rules (#5260)
* feat(iot): route shadow events through topic rules Successful classic and named shadow changes, from the REST API and from MQTT reserved topics, now reach the topic rules engine and MQTT subscribers on the AWS response topics with AWS payload shapes. Shadow documents keep metadata, clientid() reports N/A for messages without an MQTT client, and MQTT rejected responses carry the numeric status code. Closes floci-io/floci#5256 * fix(iot): compute the shadow delta through nested objects GetThingShadow and the update/delta event compared desired and reported only at the top level, so one differing nested field put the whole desired object in the delta. AWS compares nested objects key by key and arrays whole, and the delta event carries the stored desired metadata of exactly the delta values. * fix(iot): give a shadow stored without metadata its leaf metadata A shadow persisted before metadata was kept now reads back with a metadata mirror of its state stamped with its stored timestamp, so GetThingShadow and the update/documents and update/delta events carry metadata for its existing leaves, as AWS does for every state leaf. * fix(iot): reject a shadow name outside the AWS pattern A whitespace-only shadow name no longer addresses the classic shadow, so DELETE ?name=%20 cannot delete it. As on AWS, an empty name is the classic shadow and any name that is not 1 to 64 of [a-zA-Z0-9:_-] fails with InvalidRequestException. * fix(iot): ignore a shadow request on a named topic with an invalid name As on AWS, an MQTT request on $aws/things/<thing>/shadow/name/<name>/<op> whose name is not a valid shadow name, empty included, is not a shadow request: nothing is published and the classic shadow is untouched. Before, an empty name updated the classic shadow and a blank one was rejected on the classic shadow's topic. * docs(iot): note that wildcard rule filters receive shadow events Verified on AWS IoT: rules FROM '#' and '+/things/<thing>/shadow/#' receive the $aws shadow update events. Adds a test locking in the existing matcher behavior. * fix(iot): keep only the most recent recorded publish events The recorder kept every publish, and shadow events now go through it too. Only tests read it, so it now keeps the most recent 1,000 events and drops the oldest. * test(iot): read shadow rule queues without the 5s poll * fix(iot): match AWS shadow names, delta numbers and clientToken echo Accept the reserved $package shadow name and reject any other name containing $ with 'Invalid shadow name : <name>'; a name failing the pattern answers 'Bad Request'. Compare delta numbers as AWS does (equal when both double and long values are, integers beyond long exactly), which also stops a number beyond the double range failing the update, and echo a whitespace clientToken.
This commit is contained in:
1 parent
f7240b8ace
commit
534571b2a3
14 files changed
+1327
-120
No files matched your search
@@ -830,6 +830,85 @@ class IotTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void namedShadowUpdateReachesATopicRuleOnItsAcceptedTopic() throws Exception {
|
||||
String ruleName = "java_iot_shadow_rule";
|
||||
String thingName = "java-iot-shadow-rule-thing";
|
||||
String queueUrl = sqs.createQueue(CreateQueueRequest.builder()
|
||||
.queueName("java-iot-shadow-rule-queue")
|
||||
.build()).queueUrl();
|
||||
|
||||
try {
|
||||
iot.createTopicRule(CreateTopicRuleRequest.builder()
|
||||
.ruleName(ruleName)
|
||||
.topicRulePayload(TopicRulePayload.builder()
|
||||
.sql("SELECT *, topic() AS topic, clientid() AS cid "
|
||||
+ "FROM '$aws/things/+/shadow/name/building/update/accepted' "
|
||||
+ "WHERE endswith(clientToken, 'inbound')")
|
||||
.ruleDisabled(false)
|
||||
.actions(Action.builder()
|
||||
.sqs(SqsAction.builder()
|
||||
.roleArn(TestFixtures.globalArn(
|
||||
"iam", "000000000000", "role/iot-rule-role"))
|
||||
.queueUrl(queueUrl)
|
||||
.useBase64(false)
|
||||
.build())
|
||||
.build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
iotData.updateThingShadow(UpdateThingShadowRequest.builder()
|
||||
.thingName(thingName)
|
||||
.shadowName("building")
|
||||
.payload(SdkBytes.fromUtf8String(
|
||||
"{\"state\":{\"desired\":{\"temp\":20}},\"clientToken\":\"x:outbound\"}"))
|
||||
.build());
|
||||
UpdateThingShadowResponse updated = iotData.updateThingShadow(UpdateThingShadowRequest.builder()
|
||||
.thingName(thingName)
|
||||
.shadowName("building")
|
||||
.payload(SdkBytes.fromUtf8String(
|
||||
"{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"x:inbound\"}"))
|
||||
.build());
|
||||
JsonNode accepted = OBJECT_MAPPER.readTree(updated.payload().asByteArray());
|
||||
|
||||
ReceiveMessageResponse received = sqs.receiveMessage(ReceiveMessageRequest.builder()
|
||||
.queueUrl(queueUrl)
|
||||
.maxNumberOfMessages(10)
|
||||
.waitTimeSeconds(5)
|
||||
.build());
|
||||
assertThat(received.messages()).hasSize(1);
|
||||
JsonNode message = OBJECT_MAPPER.readTree(received.messages().get(0).body());
|
||||
assertThat(message.path("topic").asText())
|
||||
.isEqualTo("$aws/things/" + thingName + "/shadow/name/building/update/accepted");
|
||||
assertThat(message.path("cid").asText()).isEqualTo("N/A");
|
||||
assertThat(message.path("clientToken").asText()).isEqualTo("x:inbound");
|
||||
assertThat(message.at("/state/desired/temp").asInt()).isEqualTo(21);
|
||||
assertThat(message.path("version").asLong()).isEqualTo(accepted.path("version").asLong());
|
||||
|
||||
ReceiveMessageResponse outbound = sqs.receiveMessage(ReceiveMessageRequest.builder()
|
||||
.queueUrl(queueUrl)
|
||||
.maxNumberOfMessages(10)
|
||||
.waitTimeSeconds(1)
|
||||
.build());
|
||||
assertThat(outbound.messages()).isEmpty();
|
||||
} finally {
|
||||
try {
|
||||
iot.deleteTopicRule(DeleteTopicRuleRequest.builder().ruleName(ruleName).build());
|
||||
} catch (ResourceNotFoundException ignored) {
|
||||
// The rule was never created; there is nothing to clean up.
|
||||
}
|
||||
try {
|
||||
iotData.deleteThingShadow(DeleteThingShadowRequest.builder()
|
||||
.thingName(thingName)
|
||||
.shadowName("building")
|
||||
.build());
|
||||
} catch (software.amazon.awssdk.services.iotdataplane.model.ResourceNotFoundException ignored) {
|
||||
// Name clash with the IoT control-plane ResourceNotFoundException; the shadow was never created.
|
||||
}
|
||||
sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void thingTypesGroupsAndJobs() {
|
||||
String thingType = "java-iot-type";
|
||||
|
||||
@@ -317,7 +317,8 @@ def test_iot_data_retained_messages_and_shadow_conflicts(iot_data_client, unique
|
||||
thingName=thing_name,
|
||||
payload=json.dumps({"version": 1, "state": {"desired": {"color": None}}}).encode(),
|
||||
)
|
||||
document = json.loads(updated["payload"].read())
|
||||
assert json.loads(updated["payload"].read())["version"] == 2
|
||||
document = json.loads(iot_data_client.get_thing_shadow(thingName=thing_name)["payload"].read())
|
||||
assert "color" not in document["state"]["desired"]
|
||||
assert document["state"]["desired"]["mode"] == "auto"
|
||||
try:
|
||||
@@ -521,7 +522,7 @@ def test_mqtt_shadow_reserved_topics(unique_name):
|
||||
topic, payload = mqtt_read_publish(subscriber)
|
||||
assert topic == f"$aws/things/{thing_name}/shadow/delete/accepted"
|
||||
deleted = json.loads(payload)
|
||||
assert deleted["state"]["desired"]["color"] == "blue"
|
||||
assert deleted["version"] == got["version"]
|
||||
assert deleted["clientToken"] == "delete-token"
|
||||
|
||||
|
||||
|
||||
+25
-2
@@ -261,6 +261,23 @@ Required phase 7 reserved-topic behavior:
|
||||
|
||||
Reserved request topics are handled by Floci before normal MQTT fan-out. The original `$aws/...` request publish is not routed as an application message; generated accepted, rejected, documents, and delta responses are published back through `IotMqttBrokerService.publish(...)` so matching MQTT subscribers receive broker-native messages.
|
||||
|
||||
### Shadow Events
|
||||
|
||||
A successful classic or named shadow change reaches MQTT subscribers and the topic rules on the AWS response topics, whether it came from an MQTT request or from the REST `UpdateThingShadow` and `DeleteThingShadow` APIs. A rule such as `SELECT * FROM '$aws/things/+/shadow/name/building/update/accepted'` therefore fires for both. As on AWS, a rule whose filter starts with a wildcard, such as `'#'` or `'+/things/+/shadow/#'`, receives them too. The events are published in the order accepted, documents, delta, and carry one timestamp (epoch seconds) per operation:
|
||||
|
||||
- `update/accepted`, which is also the `UpdateThingShadow` response: `state` exactly as sent, null leaves kept, `metadata` mirroring it with `{"timestamp": ...}` per leaf (an array gets one entry per element), the new `version`, `timestamp`, and `clientToken` when the request had one.
|
||||
- `update/documents`: `previous` (JSON `null` on the first update) and `current`, each `{state, metadata, version}` as stored, plus `timestamp` and `clientToken`.
|
||||
- `update/delta`, only when desired differs from reported: `version`, `timestamp`, `state` with the desired values whose reported value is missing or different, compared key by key through nested objects and whole for arrays, the stored desired `metadata` of exactly those values, and `clientToken`.
|
||||
- `get/accepted`, for an MQTT get only (`GetThingShadow` publishes nothing): `state` with `desired`, `reported` and, when non-empty, `delta`, the stored `metadata`, `version`, the current `timestamp`, and `clientToken`.
|
||||
- `delete/accepted`: the deleted `version`, `timestamp`, and `clientToken`. `DeleteThingShadow` returns `version` and `timestamp`.
|
||||
- `rejected`, for an MQTT request only: `code` (the HTTP status as a number), `message`, and `clientToken` once the request parsed. A version conflict is `409` with `Version conflict`, a payload that is not JSON is `400` with `Invalid JSON`.
|
||||
|
||||
An empty `name` is the classic shadow. A name that is not 1 to 64 of `$`, `a-z`, `A-Z`, `0-9`, `:`, `_` and `-` fails with `InvalidRequestException` (`Bad Request`), and an MQTT request on such a named topic, empty name included, is ignored as on AWS, with no `rejected`. A name containing `$` other than the reserved `$package` fails with `InvalidRequestException` (`Invalid shadow name : <name>`), which an MQTT request receives as a `400` `rejected`. `$package` is served as an ordinary named shadow: AWS's reserved document schema, and its omission of `metadata`, are not emulated.
|
||||
|
||||
Shadow events are evaluated only against the rules of the shadow's region. A REST change belongs to the region of its SigV4 credential, and MQTT shadows live in the default region (`FLOCI_DEFAULT_REGION`). `clientid()` is `N/A` for every shadow event, as on AWS. The MQTT broker itself has no region or account, so its subscribers receive the shadow events of every region and account, as they receive a republish.
|
||||
|
||||
Shadow responses are produced only by the shadow service in reaction to a request, and each one is fanned out once, recorded once and rule-evaluated once. Response topics are never parsed as requests. A `republish` action stays record plus fan-out, with no rule re-evaluation and no shadow processing, even when it targets a shadow request topic. Broker publish and fan-out are not recursive.
|
||||
|
||||
Implementation notes:
|
||||
|
||||
- Vert.x MQTT handles the wire protocol and connection lifecycle.
|
||||
@@ -276,6 +293,10 @@ Current accepted limitation:
|
||||
- Persistent offline sessions are not modeled yet.
|
||||
- QoS 2 and advanced MQTT 5 property semantics remain follow-up scope.
|
||||
- At most 1,000 MQTT publishes are pending rule evaluation, running or waiting. While that many are pending, further publishes are still delivered to subscribers but their topic rules are skipped, with one warning logged until the backlog drains.
|
||||
- Shadow state is merged shallowly: a nested object in `desired` or `reported` replaces the stored value of its top-level key instead of being merged into it.
|
||||
- REST shadow errors are not published to `rejected`.
|
||||
- MQTT shadow request topics are not themselves delivered to rules or subscribers.
|
||||
- An IoT Data `Publish` to a shadow request topic does not update the shadow, and a `republish` that targets a shadow request topic is not processed as a shadow request.
|
||||
|
||||
## Implementation Shape
|
||||
|
||||
@@ -285,6 +306,7 @@ The MQTT integration should keep service behavior separated from broker mechanic
|
||||
- The broker publish handler detects AWS IoT reserved topics.
|
||||
- IoT reserved-topic handling lives in IoT service code or a focused reserved-topic handler, not in packet parsing code.
|
||||
- AWS-generated shadow responses are published back through `IotMqttBrokerService.publish(...)` so regular MQTT subscribers receive broker-native messages.
|
||||
- MQTT and REST shadow changes share one `IotService` path that fans each response out once, records it once and hands its rule evaluation to the caller's rule runner: the JAX-RS request thread for REST, so the rules run before the response returns, and the broker's rule worker for MQTT.
|
||||
|
||||
## Phase 7 Completion Criteria
|
||||
|
||||
@@ -313,6 +335,7 @@ Supported rule behavior:
|
||||
- IoT Data `Publish` and MQTT publishes use the same rule dispatch path. An IoT Data `Publish` evaluates its rules before it returns. An MQTT publish evaluates them on the broker's rule worker, so neither its PUBACK nor its fan-out waits for rule actions, and a republished message can reach subscribers before or after the source message's other deliveries; AWS gives no ordering guarantee there either.
|
||||
- Rule matching is region-scoped: an IoT Data `Publish` evaluates the rules of the region named by its SigV4 credential, and a rule's actions target the rule's own region.
|
||||
- Publishes that carry no region (MQTT, or an IoT Data `Publish` whose `Authorization` header is absent or not SigV4) are evaluated against every region's rules.
|
||||
- Device shadow events on the `$aws/things/...` response topics reach rules as well, evaluated only against the rules of the shadow's region; see [Shadow Events](#shadow-events).
|
||||
- Actions receive the projected document, which is the payload itself for a statement that selects only `*`.
|
||||
- `republish` action republishes to another MQTT topic through `IotMqttBrokerService`.
|
||||
- `sqs` action sends to an SQS queue through Floci's SQS service boundary.
|
||||
@@ -350,8 +373,8 @@ Semantics:
|
||||
|
||||
- Keywords and function names are case insensitive, field names are case sensitive.
|
||||
- `topic()` is the full MQTT topic, `topic(n)` is its nth segment counting from 1.
|
||||
- `clientid()` is the MQTT client that published the message, or `n/a` for an IoT Data `Publish`
|
||||
over HTTP, as on AWS. `accountid()` is the account that owns the rule. `timestamp()` is the
|
||||
- `clientid()` is the MQTT client that published the message, or `N/A` for an IoT Data `Publish`
|
||||
over HTTP and for a device shadow event, as on AWS. `accountid()` is the account that owns the rule. `timestamp()` is the
|
||||
current time in milliseconds since the epoch. `newuuid()` is a fresh random UUID.
|
||||
- `isNull(x)` is true only for a JSON `null`, `isUndefined(x)` only for a missing field or an
|
||||
undefined expression. Neither is ever undefined itself.
|
||||
|
||||
@@ -600,7 +600,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
String topic = message.topicName();
|
||||
if (topic.startsWith("$aws/")) {
|
||||
iotService.get().handleReservedMqttPublish(topic, payload, this::publish);
|
||||
iotService.get().handleReservedMqttPublish(topic, payload, rules -> evaluateRulesOnWorker(topic, rules));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,16 +2,22 @@ package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
|
||||
@ApplicationScoped
|
||||
public class IotPublishEventRecorder {
|
||||
|
||||
private final List<IotPublishEvent> events = new ArrayList<>();
|
||||
static final int MAX_RETAINED_EVENTS = 1_000;
|
||||
|
||||
private final Deque<IotPublishEvent> events = new ArrayDeque<>();
|
||||
|
||||
public synchronized void record(String topic, byte[] payload) {
|
||||
events.add(new IotPublishEvent(topic, payload == null ? new byte[0] : payload.clone()));
|
||||
events.addLast(new IotPublishEvent(topic, payload == null ? new byte[0] : payload.clone()));
|
||||
while (events.size() > MAX_RETAINED_EVENTS) {
|
||||
events.pollFirst();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized List<IotPublishEvent> recentEvents() {
|
||||
|
||||
@@ -71,7 +71,6 @@ import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -83,6 +82,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 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)|(,)");
|
||||
public static final int MAX_POLICY_VERSIONS = 5;
|
||||
@@ -90,6 +90,9 @@ public class IotService {
|
||||
/** One lock for every policy version write and the policy delete, so a cap check, an append and a delete cannot interleave. */
|
||||
private final Object policyWriteLock = new Object();
|
||||
|
||||
/** One lock for every shadow update and delete, so a shadow's previous, current and version stay consistent. */
|
||||
private final Object shadowWriteLock = new Object();
|
||||
|
||||
/** certificateId to the partition and key it was last found under; see {@link #findRegisteredCertificate}. */
|
||||
private final Map<String, CertificateLocation> certificateLocations = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -797,43 +800,240 @@ public class IotService {
|
||||
return new java.util.TreeSet<>(policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The shadow as AWS's GetThingShadow returns it: the stored state with the delta, when there is
|
||||
* one, the stored metadata, the version and the current time. Publishes nothing.
|
||||
*/
|
||||
public JsonNode getThingShadow(String thingName, String shadowName, String region) {
|
||||
IotShadow shadow = shadowStore.get(shadowKey(region, thingName, shadowName))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shadow not found: " + thingName, 404));
|
||||
return readJson(shadow.getDocument());
|
||||
.orElseThrow(() -> shadowNotFound(thingName));
|
||||
ObjectNode document = storedShadowDocument(shadow);
|
||||
ObjectNode state = (ObjectNode) document.get("state");
|
||||
ObjectNode delta = shadowDelta(state.path("desired"), state.path("reported"));
|
||||
if (!delta.isEmpty()) {
|
||||
state.set("delta", delta);
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("state", state);
|
||||
response.set("metadata", document.get("metadata"));
|
||||
response.put("version", shadow.getVersion());
|
||||
response.put("timestamp", Instant.now().getEpochSecond());
|
||||
return response;
|
||||
}
|
||||
|
||||
public JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String region) {
|
||||
return updateThingShadow(thingName, shadowName, request, region, Runnable::run);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the update and returns the update/accepted document, which is also the
|
||||
* UpdateThingShadow response, after publishing accepted, documents and, when desired and
|
||||
* reported differ, delta, each handing its rule evaluation to {@code ruleRunner}.
|
||||
*/
|
||||
JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String region,
|
||||
Executor ruleRunner) {
|
||||
ShadowUpdate update;
|
||||
synchronized (shadowWriteLock) {
|
||||
update = writeShadowUpdate(thingName, shadowName, request, region);
|
||||
}
|
||||
ReservedShadowTopic topics = new ReservedShadowTopic(thingName, shadowName, "update");
|
||||
publishShadowEvent(topics.acceptedTopic(), update.accepted(), region, ruleRunner);
|
||||
publishShadowEvent(topics.documentsTopic(), update.documents(), region, ruleRunner);
|
||||
if (update.delta() != null) {
|
||||
publishShadowEvent(topics.deltaTopic(), update.delta(), region, ruleRunner);
|
||||
}
|
||||
return update.accepted();
|
||||
}
|
||||
|
||||
public JsonNode deleteThingShadow(String thingName, String shadowName, String region) {
|
||||
return deleteThingShadow(thingName, shadowName, null, region, Runnable::run);
|
||||
}
|
||||
|
||||
/** Deletes the shadow and returns the delete/accepted document after publishing it. */
|
||||
JsonNode deleteThingShadow(String thingName, String shadowName, String clientToken, String region,
|
||||
Executor ruleRunner) {
|
||||
ObjectNode accepted = objectMapper.createObjectNode();
|
||||
synchronized (shadowWriteLock) {
|
||||
String key = shadowKey(region, thingName, shadowName);
|
||||
IotShadow shadow = shadowStore.get(key).orElseThrow(() -> shadowNotFound(thingName));
|
||||
shadowStore.delete(key);
|
||||
accepted.put("version", shadow.getVersion());
|
||||
}
|
||||
accepted.put("timestamp", Instant.now().getEpochSecond());
|
||||
withClientToken(accepted, clientToken);
|
||||
publishShadowEvent(new ReservedShadowTopic(thingName, shadowName, "delete").acceptedTopic(), accepted, region,
|
||||
ruleRunner);
|
||||
return accepted;
|
||||
}
|
||||
|
||||
/** The read-modify-write of one update; the caller holds {@link #shadowWriteLock}. */
|
||||
private ShadowUpdate writeShadowUpdate(String thingName, String shadowName, JsonNode request, String region) {
|
||||
String key = shadowKey(region, thingName, shadowName);
|
||||
IotShadow existing = shadowStore.get(key).orElse(null);
|
||||
ObjectNode document = existing == null ? objectMapper.createObjectNode() : (ObjectNode) readJson(existing.getDocument()).deepCopy();
|
||||
long currentVersion = existing == null ? 0 : existing.getVersion();
|
||||
if (request.hasNonNull("version") && request.path("version").asLong() != currentVersion) {
|
||||
throw new AwsException("ConflictException", "Version conflict", 409);
|
||||
}
|
||||
ObjectNode state = document.withObject("/state");
|
||||
long timestamp = Instant.now().getEpochSecond();
|
||||
String clientToken = request.path("clientToken").asText(null);
|
||||
ObjectNode document = existing == null ? emptyShadowDocument() : storedShadowDocument(existing);
|
||||
ObjectNode previous = existing == null ? null : shadowSnapshot(document, currentVersion);
|
||||
ObjectNode state = (ObjectNode) document.get("state");
|
||||
ObjectNode metadata = (ObjectNode) document.get("metadata");
|
||||
JsonNode requestState = request.path("state");
|
||||
mergeObject(state, "desired", requestState.path("desired"));
|
||||
mergeObject(state, "reported", requestState.path("reported"));
|
||||
mergeShadowSection(state, metadata, "desired", requestState.path("desired"), timestamp);
|
||||
mergeShadowSection(state, metadata, "reported", requestState.path("reported"), timestamp);
|
||||
long version = currentVersion + 1;
|
||||
document.put("version", version);
|
||||
document.put("timestamp", Instant.now().getEpochSecond());
|
||||
document.put("timestamp", timestamp);
|
||||
|
||||
IotShadow shadow = new IotShadow();
|
||||
shadow.setThingName(thingName);
|
||||
shadow.setShadowName(shadowName);
|
||||
shadow.setShadowName(blankToNull(shadowName));
|
||||
shadow.setVersion(version);
|
||||
shadow.setDocument(document.toString());
|
||||
shadowStore.put(key, shadow);
|
||||
|
||||
ObjectNode accepted = objectMapper.createObjectNode();
|
||||
if (!requestState.isMissingNode()) {
|
||||
accepted.set("state", requestState);
|
||||
accepted.set("metadata", shadowMetadata(requestState, timestamp));
|
||||
}
|
||||
accepted.put("version", version);
|
||||
accepted.put("timestamp", timestamp);
|
||||
withClientToken(accepted, clientToken);
|
||||
|
||||
ObjectNode documents = objectMapper.createObjectNode();
|
||||
if (previous == null) {
|
||||
documents.putNull("previous");
|
||||
} else {
|
||||
documents.set("previous", previous);
|
||||
}
|
||||
documents.set("current", shadowSnapshot(document, version));
|
||||
documents.put("timestamp", timestamp);
|
||||
withClientToken(documents, clientToken);
|
||||
|
||||
ObjectNode deltaState = shadowDelta(state.path("desired"), state.path("reported"));
|
||||
if (deltaState.isEmpty()) {
|
||||
return new ShadowUpdate(accepted, documents, null);
|
||||
}
|
||||
ObjectNode delta = objectMapper.createObjectNode();
|
||||
delta.put("version", version);
|
||||
delta.put("timestamp", timestamp);
|
||||
delta.set("state", deltaState);
|
||||
delta.set("metadata", deltaMetadata(deltaState, metadata.path("desired")));
|
||||
withClientToken(delta, clientToken);
|
||||
return new ShadowUpdate(accepted, documents, delta);
|
||||
}
|
||||
|
||||
private AwsException shadowNotFound(String thingName) {
|
||||
return new AwsException("ResourceNotFoundException", "Shadow not found: " + thingName, 404);
|
||||
}
|
||||
|
||||
private ObjectNode emptyShadowDocument() {
|
||||
ObjectNode document = objectMapper.createObjectNode();
|
||||
document.putObject("state");
|
||||
document.putObject("metadata");
|
||||
return document;
|
||||
}
|
||||
|
||||
public JsonNode deleteThingShadow(String thingName, String shadowName, String region) {
|
||||
JsonNode document = getThingShadow(thingName, shadowName, region);
|
||||
shadowStore.delete(shadowKey(region, thingName, shadowName));
|
||||
/** The stored document with {@code state} and {@code metadata} objects; one stored before metadata was kept gets metadata stamped with its stored timestamp. */
|
||||
private ObjectNode storedShadowDocument(IotShadow shadow) {
|
||||
ObjectNode document = readJson(shadow.getDocument()) instanceof ObjectNode stored ? stored : objectMapper.createObjectNode();
|
||||
if (!document.path("state").isObject()) {
|
||||
document.putObject("state");
|
||||
}
|
||||
if (!document.path("metadata").isObject()) {
|
||||
document.set("metadata", shadowMetadata(document.get("state"), document.path("timestamp").asLong()));
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
/** The {@code previous} or {@code current} member of update/documents, which carries no timestamp. */
|
||||
private ObjectNode shadowSnapshot(ObjectNode document, long version) {
|
||||
ObjectNode snapshot = objectMapper.createObjectNode();
|
||||
snapshot.set("state", document.get("state").deepCopy());
|
||||
snapshot.set("metadata", document.get("metadata").deepCopy());
|
||||
snapshot.put("version", version);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** The desired values whose reported value is missing or different: nested objects compared key by key, arrays and scalars whole. */
|
||||
private ObjectNode shadowDelta(JsonNode desired, JsonNode reported) {
|
||||
ObjectNode delta = objectMapper.createObjectNode();
|
||||
if (!desired.isObject()) {
|
||||
return delta;
|
||||
}
|
||||
desired.fields().forEachRemaining(entry -> {
|
||||
JsonNode desiredValue = entry.getValue();
|
||||
JsonNode reportedValue = reported.path(entry.getKey());
|
||||
if (desiredValue.isObject() && reportedValue.isObject()) {
|
||||
ObjectNode nested = shadowDelta(desiredValue, reportedValue);
|
||||
if (!nested.isEmpty()) {
|
||||
delta.set(entry.getKey(), nested);
|
||||
}
|
||||
} else if (reportedValue.isMissingNode() || !sameShadowValue(desiredValue, reportedValue)) {
|
||||
delta.set(entry.getKey(), desiredValue);
|
||||
}
|
||||
});
|
||||
return delta;
|
||||
}
|
||||
|
||||
/**
|
||||
* As on AWS, two numbers are equal when both their double and long values are; integers beyond long and
|
||||
* anything else, arrays included, compare exactly.
|
||||
*/
|
||||
private static boolean sameShadowValue(JsonNode desired, JsonNode reported) {
|
||||
if (desired.isNumber() && reported.isNumber() && !desired.isBigInteger() && !reported.isBigInteger()) {
|
||||
return desired.doubleValue() == reported.doubleValue() && desired.longValue() == reported.longValue();
|
||||
}
|
||||
return desired.equals(reported);
|
||||
}
|
||||
|
||||
/** The stored desired metadata of exactly the values in {@code delta}, following nested objects. */
|
||||
private ObjectNode deltaMetadata(JsonNode delta, JsonNode desiredMetadata) {
|
||||
ObjectNode metadata = objectMapper.createObjectNode();
|
||||
delta.fields().forEachRemaining(entry -> {
|
||||
JsonNode valueMetadata = desiredMetadata.get(entry.getKey());
|
||||
if (valueMetadata == null) {
|
||||
return;
|
||||
}
|
||||
if (entry.getValue().isObject() && valueMetadata.isObject()) {
|
||||
metadata.set(entry.getKey(), deltaMetadata(entry.getValue(), valueMetadata));
|
||||
} else {
|
||||
metadata.set(entry.getKey(), valueMetadata.deepCopy());
|
||||
}
|
||||
});
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/** AWS's metadata mirror of a state value: every leaf, a null included, becomes the update timestamp. */
|
||||
private JsonNode shadowMetadata(JsonNode value, long timestamp) {
|
||||
if (value.isObject()) {
|
||||
ObjectNode metadata = objectMapper.createObjectNode();
|
||||
value.fields().forEachRemaining(entry -> metadata.set(entry.getKey(), shadowMetadata(entry.getValue(), timestamp)));
|
||||
return metadata;
|
||||
}
|
||||
if (value.isArray()) {
|
||||
ArrayNode metadata = objectMapper.createArrayNode();
|
||||
value.forEach(element -> metadata.add(shadowMetadata(element, timestamp)));
|
||||
return metadata;
|
||||
}
|
||||
ObjectNode leaf = objectMapper.createObjectNode();
|
||||
leaf.put("timestamp", timestamp);
|
||||
return leaf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes one shadow response: fanned out to MQTT subscribers once, recorded once and
|
||||
* evaluated once against the topic rules of the shadow's region, as a message with no MQTT client.
|
||||
*/
|
||||
private void publishShadowEvent(String topic, JsonNode payload, String region, Executor ruleRunner) {
|
||||
byte[] bytes = payload.toString().getBytes(StandardCharsets.UTF_8);
|
||||
mqttBrokerService.publish(topic, bytes);
|
||||
handlePublish(topic, bytes, true, region, null, ruleRunner);
|
||||
}
|
||||
|
||||
public List<String> listNamedShadowsForThing(String thingName, String region) {
|
||||
String prefix = "shadow:" + region + ":" + thingName + ":";
|
||||
return shadowStore.scan(key -> key.startsWith(prefix)).stream()
|
||||
@@ -1314,30 +1514,54 @@ public class IotService {
|
||||
.toList();
|
||||
}
|
||||
|
||||
void handleReservedMqttPublish(String topic, byte[] payload, BiConsumer<String, byte[]> publisher) {
|
||||
/**
|
||||
* Answers a device shadow request published on an MQTT reserved topic. Every response goes
|
||||
* through {@link #publishShadowEvent}, and a failure after the request parsed keeps its clientToken.
|
||||
*/
|
||||
void handleReservedMqttPublish(String topic, byte[] payload, Executor ruleRunner) {
|
||||
ReservedShadowTopic shadowTopic = parseReservedShadowTopic(topic);
|
||||
if (shadowTopic == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String region = config.defaultRegion();
|
||||
JsonNode request;
|
||||
try {
|
||||
request = objectMapper.readTree(payload == null || payload.length == 0 ? "{}".getBytes(StandardCharsets.UTF_8) : payload);
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("IoT shadow request on {0} is not JSON: {1}", topic, e.getMessage());
|
||||
publishShadowRejected(shadowTopic, 400, "Invalid JSON", null, region, ruleRunner);
|
||||
return;
|
||||
}
|
||||
String clientToken = request.path("clientToken").asText(null);
|
||||
try {
|
||||
JsonNode request = readJson(payload == null || payload.length == 0 ? "{}" : new String(payload, java.nio.charset.StandardCharsets.UTF_8));
|
||||
String clientToken = request.path("clientToken").asText(null);
|
||||
String region = config.defaultRegion();
|
||||
switch (shadowTopic.operation()) {
|
||||
case "update" -> publishShadowUpdate(shadowTopic, request, clientToken, region, publisher);
|
||||
case "get" -> publishShadowGet(shadowTopic, clientToken, region, publisher);
|
||||
case "delete" -> publishShadowDelete(shadowTopic, clientToken, region, publisher);
|
||||
default -> publishRejected(shadowTopic.rejectedTopic(), "InvalidRequestException",
|
||||
"Unsupported shadow operation: " + shadowTopic.operation(), clientToken, publisher);
|
||||
case "update" -> updateThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), request, region, ruleRunner);
|
||||
case "get" -> publishShadowEvent(shadowTopic.acceptedTopic(),
|
||||
withClientToken(getThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), region), clientToken),
|
||||
region, ruleRunner);
|
||||
case "delete" -> deleteThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), clientToken, region,
|
||||
ruleRunner);
|
||||
default -> publishShadowRejected(shadowTopic, 400,
|
||||
"Unsupported shadow operation: " + shadowTopic.operation(), clientToken, region, ruleRunner);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
publishRejected(shadowTopic.rejectedTopic(), e.getErrorCode(), e.getMessage(), null, publisher);
|
||||
} catch (Exception e) {
|
||||
publishRejected(shadowTopic.rejectedTopic(), "InvalidRequestException", e.getMessage(), null, publisher);
|
||||
publishShadowRejected(shadowTopic, e.getHttpStatus(), e.getMessage(), clientToken, region, ruleRunner);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "IoT shadow request on {0} failed", topic);
|
||||
publishShadowRejected(shadowTopic, 400, Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()),
|
||||
clientToken, region, ruleRunner);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishShadowRejected(ReservedShadowTopic topic, int code, String message, String clientToken,
|
||||
String region, Executor ruleRunner) {
|
||||
ObjectNode rejected = objectMapper.createObjectNode();
|
||||
rejected.put("code", code);
|
||||
rejected.put("message", message);
|
||||
withClientToken(rejected, clientToken);
|
||||
publishShadowEvent(topic.rejectedTopic(), rejected, region, ruleRunner);
|
||||
}
|
||||
|
||||
private void validateThingName(String thingName) {
|
||||
if (thingName == null || !THING_NAME_PATTERN.matcher(thingName).matches()) {
|
||||
throw new AwsException("InvalidRequestException", "Invalid thing name: " + thingName, 400);
|
||||
@@ -1384,7 +1608,18 @@ public class IotService {
|
||||
private String policyKey(String region, String policyName) { return "policy:" + region + ":" + policyName; }
|
||||
private String policyAttachmentKey(String region, String policyName) { return "policy-attachment:" + region + ":" + policyName; }
|
||||
private String thingPrincipalKey(String region, String thingName) { return "thing-principal:" + region + ":" + thingName; }
|
||||
private String shadowKey(String region, String thingName, String shadowName) { return "shadow:" + region + ":" + thingName + ":" + (shadowName == null ? "" : shadowName); }
|
||||
private String shadowKey(String region, String thingName, String shadowName) {
|
||||
if (shadowName == null || shadowName.isEmpty()) {
|
||||
return "shadow:" + region + ":" + thingName + ":";
|
||||
}
|
||||
if (!SHADOW_NAME_PATTERN.matcher(shadowName).matches()) {
|
||||
throw new AwsException("InvalidRequestException", "Bad Request", 400);
|
||||
}
|
||||
if (shadowName.contains("$") && !"$package".equals(shadowName)) {
|
||||
throw new AwsException("InvalidRequestException", "Invalid shadow name : " + shadowName, 400);
|
||||
}
|
||||
return "shadow:" + region + ":" + thingName + ":" + shadowName;
|
||||
}
|
||||
private String topicRuleKey(String region, String ruleName) { return "topic-rule:" + region + ":" + ruleName; }
|
||||
private String retainedMessageKey(String topic) { return "retained:" + topic; }
|
||||
private String jobKey(String region, String jobId) { return "job:" + region + ":" + jobId; }
|
||||
@@ -1729,81 +1964,14 @@ public class IotService {
|
||||
return i == topicParts.length;
|
||||
}
|
||||
|
||||
private void publishShadowUpdate(ReservedShadowTopic topic, JsonNode request, String clientToken, String region,
|
||||
BiConsumer<String, byte[]> publisher) {
|
||||
JsonNode previous = shadowStore.get(shadowKey(region, topic.thingName(), topic.shadowName()))
|
||||
.map(IotShadow::getDocument)
|
||||
.map(this::readJson)
|
||||
.orElse(null);
|
||||
JsonNode current = updateThingShadow(topic.thingName(), topic.shadowName(), request, region);
|
||||
ObjectNode accepted = withClientToken(current.deepCopy(), clientToken);
|
||||
publishJson(topic.acceptedTopic(), accepted, publisher);
|
||||
|
||||
ObjectNode documents = objectMapper.createObjectNode();
|
||||
if (previous != null) {
|
||||
documents.set("previous", previous);
|
||||
}
|
||||
documents.set("current", current);
|
||||
documents.put("timestamp", Instant.now().getEpochSecond());
|
||||
publishJson(topic.documentsTopic(), documents, publisher);
|
||||
|
||||
ObjectNode deltaState = objectMapper.createObjectNode();
|
||||
JsonNode desired = current.path("state").path("desired");
|
||||
JsonNode reported = current.path("state").path("reported");
|
||||
if (desired.isObject()) {
|
||||
desired.fields().forEachRemaining(entry -> {
|
||||
JsonNode reportedValue = reported.path(entry.getKey());
|
||||
if (reportedValue.isMissingNode() || !reportedValue.equals(entry.getValue())) {
|
||||
deltaState.set(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!deltaState.isEmpty()) {
|
||||
ObjectNode delta = objectMapper.createObjectNode();
|
||||
delta.set("state", deltaState);
|
||||
delta.put("version", current.path("version").asLong());
|
||||
delta.put("timestamp", Instant.now().getEpochSecond());
|
||||
publishJson(topic.deltaTopic(), delta, publisher);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishShadowGet(ReservedShadowTopic topic, String clientToken, String region, BiConsumer<String, byte[]> publisher) {
|
||||
ObjectNode accepted = withClientToken(getThingShadow(topic.thingName(), topic.shadowName(), region).deepCopy(), clientToken);
|
||||
publishJson(topic.acceptedTopic(), accepted, publisher);
|
||||
}
|
||||
|
||||
private void publishShadowDelete(ReservedShadowTopic topic, String clientToken, String region, BiConsumer<String, byte[]> publisher) {
|
||||
ObjectNode accepted = withClientToken(deleteThingShadow(topic.thingName(), topic.shadowName(), region).deepCopy(), clientToken);
|
||||
publishJson(topic.acceptedTopic(), accepted, publisher);
|
||||
}
|
||||
|
||||
private ObjectNode withClientToken(JsonNode document, String clientToken) {
|
||||
ObjectNode node = document instanceof ObjectNode objectNode ? objectNode : objectMapper.createObjectNode();
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
if (clientToken != null && !clientToken.isEmpty()) {
|
||||
node.put("clientToken", clientToken);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private void publishRejected(String topic, String code, String message, String clientToken, BiConsumer<String, byte[]> publisher) {
|
||||
ObjectNode rejected = objectMapper.createObjectNode();
|
||||
rejected.put("code", code);
|
||||
rejected.put("message", message == null ? code : message);
|
||||
rejected.put("timestamp", Instant.now().getEpochSecond());
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
rejected.put("clientToken", clientToken);
|
||||
}
|
||||
publishJson(topic, rejected, publisher);
|
||||
}
|
||||
|
||||
private void publishJson(String topic, JsonNode payload, BiConsumer<String, byte[]> publisher) {
|
||||
try {
|
||||
publisher.accept(topic, objectMapper.writeValueAsBytes(payload));
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
private ReservedShadowTopic parseReservedShadowTopic(String topic) {
|
||||
if (!topic.startsWith("$aws/things/")) {
|
||||
return null;
|
||||
@@ -1812,29 +1980,38 @@ public class IotService {
|
||||
if (parts.length == 5 && "things".equals(parts[1]) && "shadow".equals(parts[3])) {
|
||||
return new ReservedShadowTopic(parts[2], null, parts[4]);
|
||||
}
|
||||
if (parts.length == 7 && "things".equals(parts[1]) && "shadow".equals(parts[3]) && "name".equals(parts[4])) {
|
||||
if (parts.length == 7 && "things".equals(parts[1]) && "shadow".equals(parts[3]) && "name".equals(parts[4])
|
||||
&& SHADOW_NAME_PATTERN.matcher(parts[5]).matches()) {
|
||||
return new ReservedShadowTopic(parts[2], parts[5], parts[6]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void mergeObject(ObjectNode parent, String field, JsonNode patch) {
|
||||
if (patch == null || patch.isMissingNode()) {
|
||||
/**
|
||||
* Applies one section of an update shallowly, to the state and its metadata alike: a value sets
|
||||
* the top-level key, a null removes it, and a null section removes the whole section.
|
||||
*/
|
||||
private void mergeShadowSection(ObjectNode state, ObjectNode metadata, String section, JsonNode patch, long timestamp) {
|
||||
if (patch.isMissingNode()) {
|
||||
return;
|
||||
}
|
||||
if (patch.isNull()) {
|
||||
parent.remove(field);
|
||||
state.remove(section);
|
||||
metadata.remove(section);
|
||||
return;
|
||||
}
|
||||
if (!patch.isObject()) {
|
||||
return;
|
||||
}
|
||||
ObjectNode target = parent.withObject("/" + field);
|
||||
ObjectNode stateSection = state.withObject("/" + section);
|
||||
ObjectNode metadataSection = metadata.withObject("/" + section);
|
||||
patch.fields().forEachRemaining(entry -> {
|
||||
if (entry.getValue().isNull()) {
|
||||
target.remove(entry.getKey());
|
||||
stateSection.remove(entry.getKey());
|
||||
metadataSection.remove(entry.getKey());
|
||||
} else {
|
||||
target.set(entry.getKey(), entry.getValue());
|
||||
stateSection.set(entry.getKey(), entry.getValue());
|
||||
metadataSection.set(entry.getKey(), shadowMetadata(entry.getValue(), timestamp));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1999,6 +2176,9 @@ public class IotService {
|
||||
public record Page<T>(List<T> items, String nextToken) {
|
||||
}
|
||||
|
||||
private record ShadowUpdate(ObjectNode accepted, ObjectNode documents, ObjectNode delta) {
|
||||
}
|
||||
|
||||
private record TaggableResource(Map<String, String> tags, java.util.function.Consumer<Map<String, String>> updateTags) {
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package io.github.hectorvent.floci.services.iot.rules;
|
||||
/**
|
||||
* What a rule can ask about the message beyond its payload: the topic it was published on,
|
||||
* the MQTT client that sent it ({@code null} when it did not arrive over MQTT, which
|
||||
* {@code clientid()} reports as {@code n/a} as AWS does), and the account that owns the rule.
|
||||
* {@code clientid()} reports as {@code N/A} as AWS does), and the account that owns the rule.
|
||||
*/
|
||||
public record RuleSqlContext(String topic, String clientId, String accountId) {
|
||||
}
|
||||
@@ -56,7 +56,7 @@ public final class RuleSqlEvaluator {
|
||||
private static final Pattern NUMERIC_STRING = Pattern.compile("-?\\d+(\\.\\d+)?([eE]-?\\d+)?");
|
||||
|
||||
/** What {@code clientid()} returns for a message that did not arrive over MQTT, as AWS documents. */
|
||||
private static final String NO_MQTT_CLIENT = "n/a";
|
||||
private static final String NO_MQTT_CLIENT = "N/A";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ObjectReader payloadReader;
|
||||
|
||||
@@ -35,6 +35,15 @@ class IotDataIntegrationTest {
|
||||
.body("{\"state\":{\"reported\":{\"color\":\"green\"}}}")
|
||||
.when()
|
||||
.post("/things/phase-five-thing/shadow")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("state.desired", nullValue())
|
||||
.body("state.reported.color", equalTo("green"))
|
||||
.body("version", equalTo(2));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/things/phase-five-thing/shadow")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("state.desired.color", equalTo("blue"))
|
||||
@@ -180,6 +189,14 @@ class IotDataIntegrationTest {
|
||||
.body("{\"version\":1,\"state\":{\"desired\":{\"color\":null}}}")
|
||||
.when()
|
||||
.post("/things/mvp1-shadow/shadow")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("state.desired.color", nullValue())
|
||||
.body("version", equalTo(2));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/things/mvp1-shadow/shadow")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("state.desired.color", nullValue())
|
||||
|
||||
+204
-3
@@ -2,10 +2,12 @@ package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.testing.IotMqttTlsProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
@@ -23,6 +25,9 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
@@ -43,6 +48,8 @@ class IotMqttEnabledIntegrationTest {
|
||||
static final int AWS_MAX_PAYLOAD = 128 * 1024;
|
||||
private static final String BROKER_URI = "tcp://127.0.0.1:" + IotMqttTlsProfile.PLAIN_PORT;
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private static final String BUILDING_RULE_SQL = "SELECT *, topic() AS topic, clientid() AS cid "
|
||||
+ "FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound')";
|
||||
|
||||
@Inject
|
||||
IotPublishEventRecorder eventRecorder;
|
||||
@@ -306,8 +313,9 @@ class IotMqttEnabledIntegrationTest {
|
||||
MqttPublish rejected = subscriber.takePublish();
|
||||
JsonNode payload = readJson(rejected.payload());
|
||||
assertEquals("$aws/things/phase7Thing/shadow/update/rejected", rejected.topic());
|
||||
assertEquals("InvalidRequestException", payload.path("code").asText());
|
||||
assertTrue(payload.path("message").asText().length() > 0);
|
||||
assertEquals(400, payload.path("code").asInt());
|
||||
assertTrue(payload.path("code").isInt(), payload.toString());
|
||||
assertEquals("Invalid JSON", payload.path("message").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,8 +339,10 @@ class IotMqttEnabledIntegrationTest {
|
||||
MqttPublish deleteAccepted = subscriber.takePublish();
|
||||
JsonNode deletePayload = readJson(deleteAccepted.payload());
|
||||
assertEquals("$aws/things/phase7GetDelete/shadow/delete/accepted", deleteAccepted.topic());
|
||||
assertTrue(deletePayload.path("state").path("reported").path("online").asBoolean());
|
||||
assertEquals(getPayload.path("version").asLong(), deletePayload.path("version").asLong());
|
||||
assertTrue(deletePayload.path("timestamp").isNumber(), deletePayload.toString());
|
||||
assertEquals("delete-token", deletePayload.path("clientToken").asText());
|
||||
assertTrue(deletePayload.path("state").isMissingNode(), deletePayload.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -478,6 +488,197 @@ class IotMqttEnabledIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restNamedShadowUpdateReachesARuleOnItsAcceptedTopic() throws Exception {
|
||||
String thing = "shadowRuleRest" + System.nanoTime();
|
||||
String queueUrl = createQueue("shadow-rule-rest-" + System.nanoTime());
|
||||
String rule = "shadowRuleRest" + System.nanoTime();
|
||||
createSqsRule(rule, BUILDING_RULE_SQL, queueUrl);
|
||||
try {
|
||||
updateShadow(thing, "building", "{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"x:inbound\"}");
|
||||
|
||||
List<String> bodies = receiveMessages(queueUrl);
|
||||
assertEquals(1, bodies.size(), "one message per matching update: " + bodies);
|
||||
JsonNode message = OBJECT_MAPPER.readTree(bodies.get(0));
|
||||
assertEquals("$aws/things/" + thing + "/shadow/name/building/update/accepted", message.path("topic").asText());
|
||||
assertEquals("N/A", message.path("cid").asText());
|
||||
assertEquals("x:inbound", message.path("clientToken").asText());
|
||||
assertEquals(21, message.at("/state/desired/temp").asInt());
|
||||
assertTrue(message.at("/metadata/desired/temp/timestamp").isNumber(), message.toString());
|
||||
assertEquals(1, message.path("version").asInt());
|
||||
assertTrue(message.path("timestamp").isNumber(), message.toString());
|
||||
|
||||
updateShadow(thing, "building", "{\"state\":{\"desired\":{\"temp\":22}},\"clientToken\":\"x:outbound\"}");
|
||||
|
||||
assertEquals(List.of(), receiveMessages(queueUrl), "a nonmatching clientToken reaches no rule");
|
||||
} finally {
|
||||
deleteRule(rule);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqttNamedShadowUpdateReachesARuleOnItsAcceptedTopic() throws Exception {
|
||||
String thing = "shadowRuleMqtt" + System.nanoTime();
|
||||
String queueUrl = createQueue("shadow-rule-mqtt-" + System.nanoTime());
|
||||
String rule = "shadowRuleMqtt" + System.nanoTime();
|
||||
createSqsRule(rule, BUILDING_RULE_SQL, queueUrl);
|
||||
try {
|
||||
try (MqttTestClient publisher = connectMqtt("shadow-rule-pub")) {
|
||||
String update = "$aws/things/" + thing + "/shadow/name/building/update";
|
||||
publisher.publish(update, json("{\"state\":{\"desired\":{\"temp\":20}},\"clientToken\":\"x:outbound\"}"));
|
||||
publisher.publish(update, json("{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"x:inbound\"}"));
|
||||
}
|
||||
|
||||
// One worker runs the rules in publish order, so the outbound update was evaluated before the inbound one.
|
||||
List<String> bodies = awaitMessages(queueUrl);
|
||||
assertEquals(1, bodies.size(), "one message per matching update: " + bodies);
|
||||
JsonNode message = OBJECT_MAPPER.readTree(bodies.get(0));
|
||||
assertEquals("$aws/things/" + thing + "/shadow/name/building/update/accepted", message.path("topic").asText());
|
||||
assertEquals("N/A", message.path("cid").asText());
|
||||
assertEquals("x:inbound", message.path("clientToken").asText());
|
||||
assertEquals(21, message.at("/state/desired/temp").asInt());
|
||||
assertEquals(2, message.path("version").asInt());
|
||||
assertEquals(List.of(), receiveMessages(queueUrl), "a nonmatching clientToken reaches no rule");
|
||||
} finally {
|
||||
deleteRule(rule);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restClassicShadowUpdateAndDeleteReachRulesOnTheirAcceptedTopics() throws Exception {
|
||||
String thing = "shadowRuleClassic" + System.nanoTime();
|
||||
String queueUrl = createQueue("shadow-rule-classic-" + System.nanoTime());
|
||||
String updateRule = "shadowClassicUpdate" + System.nanoTime();
|
||||
String deleteRule = "shadowClassicDelete" + System.nanoTime();
|
||||
createSqsRule(updateRule, "SELECT *, topic() AS topic FROM '$aws/things/+/shadow/update/accepted' "
|
||||
+ "WHERE topic(3) = '" + thing + "'", queueUrl);
|
||||
createSqsRule(deleteRule, "SELECT *, topic() AS topic FROM '$aws/things/+/shadow/delete/accepted' "
|
||||
+ "WHERE topic(3) = '" + thing + "'", queueUrl);
|
||||
try {
|
||||
updateShadow(thing, null, "{\"state\":{\"reported\":{\"online\":true}}}");
|
||||
given()
|
||||
.when()
|
||||
.delete("/things/" + thing + "/shadow")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("version", equalTo(1));
|
||||
|
||||
Map<String, JsonNode> byTopic = new HashMap<>();
|
||||
for (String body : receiveMessages(queueUrl)) {
|
||||
JsonNode message = OBJECT_MAPPER.readTree(body);
|
||||
byTopic.put(message.path("topic").asText(), message);
|
||||
}
|
||||
JsonNode updated = byTopic.get("$aws/things/" + thing + "/shadow/update/accepted");
|
||||
JsonNode deleted = byTopic.get("$aws/things/" + thing + "/shadow/delete/accepted");
|
||||
assertEquals(2, byTopic.size(), byTopic.toString());
|
||||
assertTrue(updated.at("/state/reported/online").asBoolean(), updated.toString());
|
||||
assertEquals(1, updated.path("version").asInt());
|
||||
assertEquals(1, deleted.path("version").asInt());
|
||||
assertTrue(deleted.path("timestamp").isNumber(), deleted.toString());
|
||||
} finally {
|
||||
deleteRule(updateRule);
|
||||
deleteRule(deleteRule);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqttSubscriberReceivesTheAcceptedEventOfARestShadowUpdate() throws Exception {
|
||||
String thing = "shadowRestToMqtt" + System.nanoTime();
|
||||
String accepted = "$aws/things/" + thing + "/shadow/name/building/update/accepted";
|
||||
|
||||
try (MqttTestClient subscriber = connectMqtt("shadow-rest-sub")) {
|
||||
subscriber.subscribe(accepted);
|
||||
|
||||
updateShadow(thing, "building", "{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"rest-token\"}");
|
||||
|
||||
MqttPublish received = subscriber.takePublish();
|
||||
JsonNode payload = readJson(received.payload());
|
||||
assertEquals(accepted, received.topic());
|
||||
assertEquals(21, payload.at("/state/desired/temp").asInt());
|
||||
assertEquals("rest-token", payload.path("clientToken").asText());
|
||||
assertEquals(1, payload.path("version").asInt());
|
||||
}
|
||||
}
|
||||
|
||||
private String createQueue(String queueName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateQueue")
|
||||
.formParam("QueueName", queueName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
}
|
||||
|
||||
private List<String> receiveMessages(String queueUrl) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ReceiveMessage")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "10")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().xmlPath().getList("ReceiveMessageResponse.ReceiveMessageResult.Message.Body", String.class);
|
||||
}
|
||||
|
||||
/** The first non-empty receive on the queue within two seconds. */
|
||||
private List<String> awaitMessages(String queueUrl) throws InterruptedException {
|
||||
Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
List<String> received = receiveMessages(queueUrl);
|
||||
if (!received.isEmpty()) {
|
||||
return received;
|
||||
}
|
||||
Thread.sleep(25);
|
||||
}
|
||||
throw new AssertionError("No message arrived on " + queueUrl);
|
||||
}
|
||||
|
||||
private void createSqsRule(String ruleName, String sql, String queueUrl) {
|
||||
ObjectNode sqs = OBJECT_MAPPER.createObjectNode()
|
||||
.put("roleArn", "arn:aws:iam::000000000000:role/iot-rule-role")
|
||||
.put("queueUrl", queueUrl);
|
||||
ObjectNode payload = OBJECT_MAPPER.createObjectNode()
|
||||
.put("sql", sql)
|
||||
.put("ruleDisabled", false);
|
||||
payload.putArray("actions").addObject().set("sqs", sqs);
|
||||
ObjectNode body = OBJECT_MAPPER.createObjectNode();
|
||||
body.set("topicRulePayload", payload);
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body(body.toString())
|
||||
.when()
|
||||
.put("/rules/" + ruleName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void deleteRule(String ruleName) {
|
||||
given()
|
||||
.when()
|
||||
.delete("/rules/" + ruleName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void updateShadow(String thingName, String shadowName, String body) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/json")
|
||||
.body(body);
|
||||
if (shadowName != null) {
|
||||
request.queryParam("name", shadowName);
|
||||
}
|
||||
request
|
||||
.when()
|
||||
.post("/things/" + thingName + "/shadow")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private MqttTestClient connectMqtt(String clientId) throws MqttException {
|
||||
return connectMqttClientId(uniqueClientId(clientId));
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class IotPublishEventRecorderTest {
|
||||
|
||||
@Test
|
||||
void keepsOnlyTheMostRecentEvents() {
|
||||
IotPublishEventRecorder recorder = new IotPublishEventRecorder();
|
||||
int max = IotPublishEventRecorder.MAX_RETAINED_EVENTS;
|
||||
|
||||
for (int i = 0; i <= max; i++) {
|
||||
recorder.record("t/" + i, "{}".getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
List<IotPublishEvent> events = recorder.recentEvents();
|
||||
assertEquals(max, events.size());
|
||||
assertEquals("t/1", events.get(0).topic());
|
||||
assertEquals("t/" + max, events.get(events.size() - 1).topic());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
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.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
@@ -24,14 +25,18 @@ import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
@@ -39,6 +44,7 @@ import java.util.concurrent.Future;
|
||||
import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -48,6 +54,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -60,7 +67,8 @@ import static org.mockito.Mockito.when;
|
||||
* Rules engine behaviour of {@link IotService} with in-memory stores and mocked action targets:
|
||||
* one failing action never fails the publish or the other actions, the error action receives the
|
||||
* 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.
|
||||
* Also the five-version cap on a policy, including under racing creates, and the device shadow
|
||||
* events that reach MQTT subscribers and topic rules on the AWS response topics.
|
||||
*/
|
||||
class IotServiceTest {
|
||||
|
||||
@@ -70,6 +78,16 @@ class IotServiceTest {
|
||||
private static final String QUEUE_URL = "http://localhost:4566/000000000000/metrics";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:handler";
|
||||
private static final String ERROR_FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:errors";
|
||||
private static final String SHADOW_QUEUE_URL = "http://localhost:4566/000000000000/shadow-events";
|
||||
private static final String CLASSIC_QUEUE_URL = "http://localhost:4566/000000000000/classic-shadow-events";
|
||||
private static final String BUILDING_RULE_SQL = "SELECT *, topic() AS topic, clientid() AS cid "
|
||||
+ "FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound')";
|
||||
private static final String BUILDING_UPDATE = "$aws/things/sensor-1/shadow/name/building/update";
|
||||
private static final String NESTED_SHADOW_UPDATE = """
|
||||
{"state": {"desired": {"lights": {"color": {"r": 255, "g": 255, "b": 255}, "on": true}, "arr": [1, 2], "same": {"x": 1}},
|
||||
"reported": {"lights": {"color": {"r": 255, "g": 0, "b": 255}, "on": true}, "arr": [1, 3], "same": {"x": 1}}}}
|
||||
""";
|
||||
private static final String NESTED_DELTA = "{\"lights\":{\"color\":{\"g\":255}},\"arr\":[1,2]}";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final SqsService sqs = mock(SqsService.class);
|
||||
@@ -78,6 +96,8 @@ class IotServiceTest {
|
||||
private final FirehoseService firehose = mock(FirehoseService.class);
|
||||
private final CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
private final IotPublishEventRecorder recorder = new IotPublishEventRecorder();
|
||||
private final IotMqttBrokerService broker = mock(IotMqttBrokerService.class);
|
||||
private final AccountAwareStorageBackend<IotShadow> shadows = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
private IotService service;
|
||||
|
||||
@BeforeEach
|
||||
@@ -91,7 +111,7 @@ class IotServiceTest {
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
shadows,
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
@@ -103,7 +123,7 @@ class IotServiceTest {
|
||||
new RegionResolver(REGION, ACCOUNT),
|
||||
mapper,
|
||||
recorder,
|
||||
mock(IotMqttBrokerService.class),
|
||||
broker,
|
||||
sqs,
|
||||
mock(SnsService.class),
|
||||
mock(S3Service.class),
|
||||
@@ -703,4 +723,658 @@ class IotServiceTest {
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
|
||||
private JsonNode json(String value) throws Exception {
|
||||
return mapper.readTree(value);
|
||||
}
|
||||
|
||||
/** The node as it reads back from its JSON text, so a long and an int of the same value compare equal. */
|
||||
private JsonNode reparse(JsonNode node) throws Exception {
|
||||
return mapper.readTree(node.toString());
|
||||
}
|
||||
|
||||
private static String leaf(long timestamp) {
|
||||
return "{\"timestamp\":" + timestamp + "}";
|
||||
}
|
||||
|
||||
private static Set<String> fieldNames(JsonNode node) {
|
||||
Set<String> names = new LinkedHashSet<>();
|
||||
node.fieldNames().forEachRemaining(names::add);
|
||||
return names;
|
||||
}
|
||||
|
||||
private List<String> recordedTopics() {
|
||||
return recorder.recentEvents().stream().map(IotPublishEvent::topic).toList();
|
||||
}
|
||||
|
||||
private JsonNode recordedPayload(String topic) throws Exception {
|
||||
List<IotPublishEvent> matching = recorder.recentEvents().stream()
|
||||
.filter(event -> topic.equals(event.topic()))
|
||||
.toList();
|
||||
assertEquals(1, matching.size(), "events recorded on " + topic);
|
||||
return mapper.readTree(matching.get(0).payload());
|
||||
}
|
||||
|
||||
private static String sqsRule(String sql, String queueUrl) {
|
||||
return """
|
||||
{"sql": "%s", "actions": [{"sqs": {"queueUrl": "%s", "roleArn": "arn:aws:iam::000000000000:role/rule"}}]}
|
||||
""".formatted(sql, queueUrl);
|
||||
}
|
||||
|
||||
private void storeShadow(String thingName, String document) throws Exception {
|
||||
IotShadow shadow = new IotShadow();
|
||||
shadow.setThingName(thingName);
|
||||
shadow.setDocument(document);
|
||||
shadow.setVersion(json(document).path("version").asLong());
|
||||
shadows.put("shadow:" + REGION + ":" + thingName + ":", shadow);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadowUpdateReturnsTheRequestStateAsSentWithItsMetadataVersionTimestampAndClientToken() throws Exception {
|
||||
JsonNode request = json("""
|
||||
{"state": {"desired": {"color": "blue", "modes": ["eco", "boost"], "schedule": {"start": 8}, "legacy": null},
|
||||
"reported": null},
|
||||
"clientToken": "tok-1"}
|
||||
""");
|
||||
|
||||
JsonNode accepted = service.updateThingShadow("sensor-1", null, request, REGION);
|
||||
|
||||
long timestamp = accepted.get("timestamp").asLong();
|
||||
assertEquals(Set.of("state", "metadata", "version", "timestamp", "clientToken"), fieldNames(accepted));
|
||||
assertEquals(request.get("state"), accepted.get("state"));
|
||||
assertEquals(json("""
|
||||
{"desired": {"color": %1$s, "modes": [%1$s, %1$s], "schedule": {"start": %1$s}, "legacy": %1$s},
|
||||
"reported": %1$s}
|
||||
""".formatted(leaf(timestamp))), reparse(accepted.get("metadata")));
|
||||
assertEquals(1, accepted.get("version").asLong());
|
||||
assertEquals("tok-1", accepted.get("clientToken").asText());
|
||||
assertTrue(Math.abs(System.currentTimeMillis() / 1000 - timestamp) <= 5, "timestamp is in epoch seconds");
|
||||
|
||||
JsonNode second = service.updateThingShadow("sensor-1", null, json("{\"state\":{\"reported\":{\"color\":\"blue\"}}}"), REGION);
|
||||
|
||||
assertEquals(Set.of("state", "metadata", "version", "timestamp"), fieldNames(second));
|
||||
assertEquals(2, second.get("version").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankClientTokenIsEchoedInTheUpdateResponse() throws Exception {
|
||||
JsonNode accepted = service.updateThingShadow("sensor-15", null,
|
||||
json("{\"state\":{\"desired\":{\"c\":\"x\"}},\"clientToken\":\" \"}"), REGION);
|
||||
|
||||
assertEquals(" ", accepted.path("clientToken").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadowUpdatePublishesAcceptedDocumentsAndDeltaInThatOrderOnceEach() throws Exception {
|
||||
JsonNode accepted = service.updateThingShadow("sensor-1", "building",
|
||||
json("{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"tok-1\"}"), REGION);
|
||||
long first = accepted.get("timestamp").asLong();
|
||||
|
||||
assertEquals(List.of(BUILDING_UPDATE + "/accepted", BUILDING_UPDATE + "/documents", BUILDING_UPDATE + "/delta"),
|
||||
recordedTopics());
|
||||
assertEquals(reparse(accepted), recordedPayload(BUILDING_UPDATE + "/accepted"));
|
||||
JsonNode currentAfterFirst = json("""
|
||||
{"state": {"desired": {"color": "blue"}}, "metadata": {"desired": {"color": %s}}, "version": 1}
|
||||
""".formatted(leaf(first)));
|
||||
JsonNode documents = recordedPayload(BUILDING_UPDATE + "/documents");
|
||||
assertEquals(Set.of("previous", "current", "timestamp", "clientToken"), fieldNames(documents));
|
||||
assertTrue(documents.get("previous").isNull(), "previous is JSON null on the first update");
|
||||
assertEquals(currentAfterFirst, documents.get("current"));
|
||||
assertEquals(first, documents.get("timestamp").asLong());
|
||||
assertEquals("tok-1", documents.get("clientToken").asText());
|
||||
assertEquals(json("""
|
||||
{"version": 1, "timestamp": %d, "state": {"color": "blue"}, "metadata": {"color": %s}, "clientToken": "tok-1"}
|
||||
""".formatted(first, leaf(first))), recordedPayload(BUILDING_UPDATE + "/delta"));
|
||||
for (String topic : recordedTopics()) {
|
||||
ArgumentCaptor<byte[]> fannedOut = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(broker, times(1)).publish(eq(topic), fannedOut.capture());
|
||||
assertEquals(recordedPayload(topic), mapper.readTree(fannedOut.getValue()));
|
||||
}
|
||||
|
||||
recorder.clear();
|
||||
JsonNode reported = service.updateThingShadow("sensor-1", "building",
|
||||
json("{\"state\":{\"reported\":{\"color\":\"blue\"}}}"), REGION);
|
||||
long second = reported.get("timestamp").asLong();
|
||||
|
||||
assertEquals(List.of(BUILDING_UPDATE + "/accepted", BUILDING_UPDATE + "/documents"), recordedTopics(),
|
||||
"no delta once reported matches desired");
|
||||
JsonNode secondDocuments = recordedPayload(BUILDING_UPDATE + "/documents");
|
||||
assertEquals(Set.of("previous", "current", "timestamp"), fieldNames(secondDocuments));
|
||||
assertEquals(currentAfterFirst, secondDocuments.get("previous"));
|
||||
assertEquals(json("""
|
||||
{"state": {"desired": {"color": "blue"}, "reported": {"color": "blue"}},
|
||||
"metadata": {"desired": {"color": %s}, "reported": {"color": %s}},
|
||||
"version": 2}
|
||||
""".formatted(leaf(first), leaf(second))), secondDocuments.get("current"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedMetadataKeepsTheTimestampOfEveryKeyTheUpdateDidNotTouch() throws Exception {
|
||||
storeShadow("sensor-2", """
|
||||
{"state": {"desired": {"color": "red", "mode": "auto"}, "reported": {"color": "red"}},
|
||||
"metadata": {"desired": {"color": {"timestamp": 1000}, "mode": {"timestamp": 1000}},
|
||||
"reported": {"color": {"timestamp": 1000}}},
|
||||
"version": 4, "timestamp": 1000}
|
||||
""");
|
||||
|
||||
JsonNode accepted = service.updateThingShadow("sensor-2", null,
|
||||
json("{\"version\":4,\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
|
||||
long timestamp = accepted.get("timestamp").asLong();
|
||||
JsonNode documents = recordedPayload("$aws/things/sensor-2/shadow/update/documents");
|
||||
assertEquals(json("""
|
||||
{"state": {"desired": {"color": "red", "mode": "auto"}, "reported": {"color": "red"}},
|
||||
"metadata": {"desired": {"color": {"timestamp": 1000}, "mode": {"timestamp": 1000}},
|
||||
"reported": {"color": {"timestamp": 1000}}},
|
||||
"version": 4}
|
||||
"""), documents.get("previous"));
|
||||
assertEquals(json("""
|
||||
{"state": {"desired": {"color": "blue", "mode": "auto"}, "reported": {"color": "red"}},
|
||||
"metadata": {"desired": {"color": %s, "mode": {"timestamp": 1000}}, "reported": {"color": {"timestamp": 1000}}},
|
||||
"version": 5}
|
||||
""".formatted(leaf(timestamp))), documents.get("current"));
|
||||
JsonNode delta = recordedPayload("$aws/things/sensor-2/shadow/update/delta");
|
||||
assertEquals(json("{\"color\":\"blue\",\"mode\":\"auto\"}"), delta.get("state"));
|
||||
assertEquals(json("{\"color\":" + leaf(timestamp) + ",\"mode\":{\"timestamp\":1000}}"), delta.get("metadata"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullKeyOrSectionRemovesItFromStateAndMetadata() throws Exception {
|
||||
storeShadow("sensor-2", """
|
||||
{"state": {"desired": {"color": "red", "mode": "auto"}, "reported": {"color": "red"}},
|
||||
"metadata": {"desired": {"color": {"timestamp": 1000}, "mode": {"timestamp": 1000}},
|
||||
"reported": {"color": {"timestamp": 1000}}},
|
||||
"version": 4, "timestamp": 1000}
|
||||
""");
|
||||
|
||||
service.updateThingShadow("sensor-2", null, json("{\"state\":{\"desired\":{\"mode\":null},\"reported\":null}}"), REGION);
|
||||
|
||||
JsonNode current = recordedPayload("$aws/things/sensor-2/shadow/update/documents").get("current");
|
||||
assertEquals(json("{\"desired\":{\"color\":\"red\"}}"), current.get("state"));
|
||||
assertEquals(json("{\"desired\":{\"color\":{\"timestamp\":1000}}}"), current.get("metadata"));
|
||||
JsonNode stored = service.getThingShadow("sensor-2", null, REGION);
|
||||
assertEquals(json("{\"desired\":{\"color\":{\"timestamp\":1000}}}"), reparse(stored.get("metadata")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoredShadowWithoutMetadataIsUpdatedWithMetadataFromItsStoredTimestamp() throws Exception {
|
||||
storeShadow("sensor-3", "{\"state\":{\"desired\":{\"color\":\"red\"}},\"version\":2,\"timestamp\":1000}");
|
||||
|
||||
JsonNode accepted = service.updateThingShadow("sensor-3", null,
|
||||
json("{\"state\":{\"reported\":{\"color\":\"red\"}}}"), REGION);
|
||||
|
||||
long timestamp = accepted.get("timestamp").asLong();
|
||||
JsonNode documents = recordedPayload("$aws/things/sensor-3/shadow/update/documents");
|
||||
assertEquals(json("""
|
||||
{"state": {"desired": {"color": "red"}}, "metadata": {"desired": {"color": {"timestamp": 1000}}}, "version": 2}
|
||||
"""), documents.get("previous"));
|
||||
assertEquals(json("""
|
||||
{"state": {"desired": {"color": "red"}, "reported": {"color": "red"}},
|
||||
"metadata": {"desired": {"color": {"timestamp": 1000}}, "reported": {"color": %s}}, "version": 3}
|
||||
""".formatted(leaf(timestamp))), documents.get("current"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShadowStoredWithoutMetadataGetsMetadataFromItsStoredTimestamp() throws Exception {
|
||||
storeShadow("sensor-9", """
|
||||
{"state": {"desired": {"color": "red", "n": 1}, "reported": {"color": "blue"}}, "version": 3, "timestamp": 100}
|
||||
""");
|
||||
|
||||
JsonNode shadow = service.getThingShadow("sensor-9", null, REGION);
|
||||
|
||||
assertEquals(json("""
|
||||
{"desired": {"color": {"timestamp": 100}, "n": {"timestamp": 100}}, "reported": {"color": {"timestamp": 100}}}
|
||||
"""), reparse(shadow.get("metadata")));
|
||||
|
||||
service.updateThingShadow("sensor-9", null, json("{\"state\":{\"reported\":{\"n\":1}}}"), REGION);
|
||||
|
||||
JsonNode delta = recordedPayload("$aws/things/sensor-9/shadow/update/delta");
|
||||
assertEquals(json("{\"color\":\"red\"}"), delta.get("state"));
|
||||
assertEquals(json("{\"color\":{\"timestamp\":100}}"), delta.get("metadata"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyShadowNameIsTheClassicShadow() throws Exception {
|
||||
service.updateThingShadow("sensor-6", "", json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
|
||||
assertEquals("$aws/things/sensor-6/shadow/update/accepted", recordedTopics().get(0));
|
||||
assertEquals("blue", service.getThingShadow("sensor-6", null, REGION).at("/state/desired/color").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShadowNameOutsideThePatternIsRejectedAndLeavesTheClassicShadowIntact() throws Exception {
|
||||
JsonNode update = json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}");
|
||||
service.updateThingShadow("sensor-6", null, update, REGION);
|
||||
|
||||
List<Executable> calls = List.of(
|
||||
() -> service.getThingShadow("sensor-6", " ", REGION),
|
||||
() -> service.updateThingShadow("sensor-6", " ", update, REGION),
|
||||
() -> service.deleteThingShadow("sensor-6", " ", REGION),
|
||||
() -> service.getThingShadow("sensor-6", "bad!", REGION));
|
||||
for (Executable call : calls) {
|
||||
AwsException e = assertThrows(AwsException.class, call);
|
||||
assertEquals("InvalidRequestException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals("Bad Request", e.getMessage());
|
||||
}
|
||||
|
||||
JsonNode classic = service.getThingShadow("sensor-6", null, REGION);
|
||||
assertEquals("blue", classic.at("/state/desired/color").asText());
|
||||
assertEquals(1, classic.get("version").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShadowNameWithADollarOtherThanPackageIsAnInvalidShadowName() throws Exception {
|
||||
JsonNode update = json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}");
|
||||
for (String name : List.of("$", "$PACKAGE", "$package2", "a$b")) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.updateThingShadow("sensor-14", name, update, REGION));
|
||||
assertEquals("InvalidRequestException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals("Invalid shadow name : " + name, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReservedPackageShadowIsUpdatedReadAndDeleted() throws Exception {
|
||||
service.updateThingShadow("sensor-14", "$package",
|
||||
json("{\"state\":{\"reported\":{\"samplePackage\":{\"version\":\"1.0.0\"}}}}"), REGION);
|
||||
|
||||
assertEquals("1.0.0", service.getThingShadow("sensor-14", "$package", REGION)
|
||||
.at("/state/reported/samplePackage/version").asText());
|
||||
assertEquals(1, service.deleteThingShadow("sensor-14", "$package", REGION).get("version").asLong());
|
||||
assertThrows(AwsException.class, () -> service.getThingShadow("sensor-14", "$package", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleOnTheNamedShadowAcceptedTopicReceivesTheProjectionWithNoMqttClient() throws Exception {
|
||||
createRule("buildingRule", sqsRule(BUILDING_RULE_SQL, SHADOW_QUEUE_URL));
|
||||
|
||||
JsonNode accepted = service.updateThingShadow("sensor-1", "building",
|
||||
json("{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"job:inbound\"}"), REGION);
|
||||
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqs).sendMessage(eq(SHADOW_QUEUE_URL), body.capture(), eq(0), eq(REGION));
|
||||
JsonNode message = mapper.readTree(body.getValue());
|
||||
assertEquals(BUILDING_UPDATE + "/accepted", message.get("topic").asText());
|
||||
assertEquals("N/A", message.get("cid").asText());
|
||||
assertEquals("job:inbound", message.get("clientToken").asText());
|
||||
assertEquals(21, message.at("/state/desired/temp").asInt());
|
||||
assertEquals(accepted.get("version").asLong(), message.get("version").asLong());
|
||||
assertEquals(accepted.get("timestamp").asLong(), message.get("timestamp").asLong());
|
||||
assertEquals(reparse(accepted.get("metadata")), message.get("metadata"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleWhoseFilterStartsWithAWildcardReceivesShadowEvents() throws Exception {
|
||||
createRule("everythingRule", sqsRule("SELECT topic() AS topic FROM '#'", SHADOW_QUEUE_URL));
|
||||
createRule("anyPrefixRule", sqsRule("SELECT topic() AS topic FROM '+/things/sensor-13/shadow/#'", SHADOW_QUEUE_URL));
|
||||
|
||||
service.updateThingShadow("sensor-13", null, json("{\"state\":{\"desired\":{\"temp\":21}}}"), REGION);
|
||||
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqs, times(6)).sendMessage(eq(SHADOW_QUEUE_URL), body.capture(), eq(0), eq(REGION));
|
||||
List<String> topics = new ArrayList<>();
|
||||
for (String message : body.getAllValues()) {
|
||||
topics.add(mapper.readTree(message).get("topic").asText());
|
||||
}
|
||||
String update = "$aws/things/sensor-13/shadow/update";
|
||||
assertEquals(List.of(update + "/accepted", update + "/accepted", update + "/delta", update + "/delta",
|
||||
update + "/documents", update + "/documents"), topics.stream().sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNamedShadowRuleSkipsAnotherTokenTheClassicShadowAndAnotherShadowName() throws Exception {
|
||||
createRule("buildingRule", sqsRule(BUILDING_RULE_SQL, SHADOW_QUEUE_URL));
|
||||
String inbound = "{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"job:inbound\"}";
|
||||
|
||||
service.updateThingShadow("sensor-1", "building",
|
||||
json("{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"job:outbound\"}"), REGION);
|
||||
service.updateThingShadow("sensor-1", null, json(inbound), REGION);
|
||||
service.updateThingShadow("sensor-1", "other", json(inbound), REGION);
|
||||
|
||||
verify(sqs, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleOnTheClassicShadowAcceptedTopicFiresForTheClassicShadowOnly() throws Exception {
|
||||
createRule("classicRule", sqsRule("SELECT * FROM '$aws/things/+/shadow/update/accepted'", CLASSIC_QUEUE_URL));
|
||||
String update = "{\"state\":{\"desired\":{\"temp\":21}}}";
|
||||
|
||||
service.updateThingShadow("sensor-1", "building", json(update), REGION);
|
||||
verify(sqs, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
|
||||
|
||||
service.updateThingShadow("sensor-1", null, json(update), REGION);
|
||||
verify(sqs, times(1)).sendMessage(eq(CLASSIC_QUEUE_URL), anyString(), eq(0), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadowEventsReachOnlyTheRulesOfTheShadowsRegion() throws Exception {
|
||||
service.createTopicRule("buildingRule", json(sqsRule(BUILDING_RULE_SQL, SHADOW_QUEUE_URL)), "eu-west-1");
|
||||
String inbound = "{\"state\":{\"desired\":{\"temp\":21}},\"clientToken\":\"job:inbound\"}";
|
||||
|
||||
service.updateThingShadow("sensor-1", "building", json(inbound), REGION);
|
||||
verify(sqs, never()).sendMessage(anyString(), anyString(), anyInt(), anyString());
|
||||
|
||||
service.updateThingShadow("sensor-1", "building", json(inbound), "eu-west-1");
|
||||
verify(sqs, times(1)).sendMessage(eq(SHADOW_QUEUE_URL), anyString(), eq(0), eq("eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteReturnsTheDeletedVersionAndPublishesItOnDeleteAccepted() throws Exception {
|
||||
service.updateThingShadow("sensor-4", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
service.updateThingShadow("sensor-4", null, json("{\"state\":{\"desired\":{\"color\":\"red\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
|
||||
JsonNode deleted = service.deleteThingShadow("sensor-4", null, REGION);
|
||||
|
||||
assertEquals(Set.of("version", "timestamp"), fieldNames(deleted));
|
||||
assertEquals(2, deleted.get("version").asLong());
|
||||
assertEquals(List.of("$aws/things/sensor-4/shadow/delete/accepted"), recordedTopics());
|
||||
assertEquals(reparse(deleted), recordedPayload("$aws/things/sensor-4/shadow/delete/accepted"));
|
||||
verify(broker, times(1)).publish(eq("$aws/things/sensor-4/shadow/delete/accepted"), any());
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getThingShadow("sensor-4", null, REGION));
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReturnsStateWithDeltaTheStoredMetadataVersionAndTimestampAndPublishesNothing() throws Exception {
|
||||
JsonNode accepted = service.updateThingShadow("sensor-5", null, json("""
|
||||
{"state": {"desired": {"color": "blue", "mode": "auto"}, "reported": {"color": "red", "mode": "auto"}}}
|
||||
"""), REGION);
|
||||
long timestamp = accepted.get("timestamp").asLong();
|
||||
recorder.clear();
|
||||
|
||||
JsonNode shadow = service.getThingShadow("sensor-5", null, REGION);
|
||||
|
||||
assertEquals(Set.of("state", "metadata", "version", "timestamp"), fieldNames(shadow));
|
||||
assertEquals(json("""
|
||||
{"desired": {"color": "blue", "mode": "auto"}, "reported": {"color": "red", "mode": "auto"},
|
||||
"delta": {"color": "blue"}}
|
||||
"""), reparse(shadow.get("state")));
|
||||
assertEquals(json("""
|
||||
{"desired": {"color": %1$s, "mode": %1$s}, "reported": {"color": %1$s, "mode": %1$s}}
|
||||
""".formatted(leaf(timestamp))), reparse(shadow.get("metadata")));
|
||||
assertEquals(1, shadow.get("version").asLong());
|
||||
assertTrue(shadow.get("timestamp").asLong() >= timestamp);
|
||||
assertTrue(recorder.recentEvents().isEmpty(), "GetThingShadow publishes nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeavesOutTheDeltaWhenDesiredAndReportedAgree() throws Exception {
|
||||
service.updateThingShadow("sensor-5", null,
|
||||
json("{\"state\":{\"desired\":{\"color\":\"blue\"},\"reported\":{\"color\":\"blue\"}}}"), REGION);
|
||||
|
||||
assertFalse(service.getThingShadow("sensor-5", null, REGION).get("state").has("delta"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getComparesNumbersAsAwsDoesThroughNestedObjectsAndArraysExactly() throws Exception {
|
||||
service.updateThingShadow("sensor-15", null, json("{\"state\":{"
|
||||
+ "\"desired\":{\"n\":1.0,\"nested\":{\"n\":1.0},\"arr\":[1],\"objs\":[{\"n\":1}],"
|
||||
+ "\"max\":9223372036854775807,\"big\":10000000000000000000000,\"long\":9007199254740993,"
|
||||
+ "\"mixed\":9007199254740993,\"over\":9223372036854775807},"
|
||||
+ "\"reported\":{\"n\":1,\"nested\":{\"n\":1},\"arr\":[1.0],\"objs\":[{\"n\":1.0}],"
|
||||
+ "\"max\":9.223372036854776e18,\"big\":1e22,\"long\":9007199254740992,"
|
||||
+ "\"mixed\":9007199254740992.0,\"over\":1e19}}}"), REGION);
|
||||
|
||||
JsonNode shadow = service.getThingShadow("sensor-15", null, REGION);
|
||||
|
||||
assertEquals(json("{\"arr\":[1],\"objs\":[{\"n\":1}],\"big\":10000000000000000000000,"
|
||||
+ "\"long\":9007199254740993,\"mixed\":9007199254740993,\"over\":9223372036854775807}"),
|
||||
reparse(shadow.at("/state/delta")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateWithANumberBeyondTheDoubleRangeDoesNotThrow() throws Exception {
|
||||
JsonNode update = json("{\"state\":{\"desired\":{\"n\":1e309},\"reported\":{\"n\":0}}}");
|
||||
|
||||
assertDoesNotThrow(() -> service.updateThingShadow("sensor-16", null, update, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getComputesTheDeltaThroughNestedObjectsAndComparesArraysWhole() throws Exception {
|
||||
service.updateThingShadow("sensor-7", null, json(NESTED_SHADOW_UPDATE), REGION);
|
||||
|
||||
JsonNode shadow = service.getThingShadow("sensor-7", null, REGION);
|
||||
|
||||
assertEquals(json(NESTED_DELTA), reparse(shadow.get("state").get("delta")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deltaEventCarriesOnlyTheNestedDifferencesAndTheirStoredMetadata() throws Exception {
|
||||
JsonNode accepted = service.updateThingShadow("sensor-7", null, json(NESTED_SHADOW_UPDATE), REGION);
|
||||
long timestamp = accepted.get("timestamp").asLong();
|
||||
|
||||
JsonNode delta = recordedPayload("$aws/things/sensor-7/shadow/update/delta");
|
||||
|
||||
assertEquals(json(NESTED_DELTA), delta.get("state"));
|
||||
assertEquals(json("""
|
||||
{"lights": {"color": {"g": %1$s}}, "arr": [%1$s, %1$s]}
|
||||
""".formatted(leaf(timestamp))), delta.get("metadata"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void racingShadowUpdatesEachGetTheirOwnConsecutiveVersion() throws Exception {
|
||||
int writers = 8;
|
||||
int updatesEach = 25;
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(writers);
|
||||
List<Future<?>> outcomes = new ArrayList<>();
|
||||
try {
|
||||
for (int i = 0; i < writers; i++) {
|
||||
String key = "k" + i;
|
||||
outcomes.add(pool.submit(() -> {
|
||||
start.await();
|
||||
for (int n = 0; n < updatesEach; n++) {
|
||||
service.updateThingShadow("raced", null,
|
||||
json("{\"state\":{\"reported\":{\"" + key + "\":" + n + "}}}"), REGION);
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (Future<?> outcome : outcomes) {
|
||||
outcome.get();
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
assertEquals(writers * updatesEach, service.getThingShadow("raced", null, REGION).get("version").asLong());
|
||||
Set<Long> versions = new LinkedHashSet<>();
|
||||
for (IotPublishEvent event : recorder.recentEvents()) {
|
||||
if (event.topic().endsWith("/documents")) {
|
||||
JsonNode documents = mapper.readTree(event.payload());
|
||||
long current = documents.at("/current/version").asLong();
|
||||
versions.add(current);
|
||||
assertEquals(current - 1, documents.get("previous").isNull() ? 0 : documents.at("/previous/version").asLong());
|
||||
}
|
||||
}
|
||||
assertEquals(writers * updatesEach, versions.size());
|
||||
}
|
||||
|
||||
private void mqttShadowRequest(String topic, String payload) {
|
||||
Executor inline = Runnable::run;
|
||||
service.handleReservedMqttPublish(topic, payload.getBytes(StandardCharsets.UTF_8), inline);
|
||||
}
|
||||
|
||||
/** The payload fanned out on the topic, verifying the broker received exactly one publish on it. */
|
||||
private JsonNode fannedOut(String topic) throws Exception {
|
||||
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(broker, times(1)).publish(eq(topic), payload.capture());
|
||||
return mapper.readTree(payload.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttShadowUpdateFansOutRecordsAndAnswersEachEventOnce() throws Exception {
|
||||
String update = "$aws/things/sensor-7/shadow/name/building/update";
|
||||
|
||||
mqttShadowRequest(update, "{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"c-1\"}");
|
||||
|
||||
List<String> topics = List.of(update + "/accepted", update + "/documents", update + "/delta");
|
||||
assertEquals(topics, recordedTopics());
|
||||
for (String topic : topics) {
|
||||
assertEquals(recordedPayload(topic), fannedOut(topic));
|
||||
assertEquals("c-1", recordedPayload(topic).get("clientToken").asText());
|
||||
}
|
||||
verify(broker, times(3)).publish(anyString(), any());
|
||||
assertEquals("blue", service.getThingShadow("sensor-7", "building", REGION).at("/state/desired/color").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttShadowUpdateRunsTheRulesOnTheGivenRuleRunnerWithNoMqttClient() throws Exception {
|
||||
createRule("classicRule", sqsRule(
|
||||
"SELECT clientid() AS cid, topic() AS topic FROM '$aws/things/+/shadow/update/accepted'", CLASSIC_QUEUE_URL));
|
||||
List<Runnable> deferred = new ArrayList<>();
|
||||
|
||||
service.handleReservedMqttPublish("$aws/things/sensor-10/shadow/update",
|
||||
"{\"state\":{\"desired\":{\"color\":\"blue\"}}}".getBytes(StandardCharsets.UTF_8), deferred::add);
|
||||
|
||||
verifyNoInteractions(sqs);
|
||||
assertEquals(3, deferred.size(), "one rule evaluation per event");
|
||||
deferred.forEach(Runnable::run);
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
verify(sqs).sendMessage(eq(CLASSIC_QUEUE_URL), body.capture(), eq(0), eq(REGION));
|
||||
assertEquals(json("{\"cid\":\"N/A\",\"topic\":\"$aws/things/sensor-10/shadow/update/accepted\"}"),
|
||||
mapper.readTree(body.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttShadowGetPublishesGetAcceptedWithTheRequestClientToken() throws Exception {
|
||||
service.updateThingShadow("sensor-8", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
clearInvocations(broker);
|
||||
|
||||
mqttShadowRequest("$aws/things/sensor-8/shadow/get", "{\"clientToken\":\"g-1\"}");
|
||||
|
||||
JsonNode accepted = fannedOut("$aws/things/sensor-8/shadow/get/accepted");
|
||||
assertEquals(Set.of("state", "metadata", "version", "timestamp", "clientToken"), fieldNames(accepted));
|
||||
assertEquals("blue", accepted.at("/state/delta/color").asText());
|
||||
assertEquals("g-1", accepted.get("clientToken").asText());
|
||||
assertEquals(List.of("$aws/things/sensor-8/shadow/get/accepted"), recordedTopics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttShadowDeletePublishesDeleteAcceptedWithTheVersionAndClientToken() throws Exception {
|
||||
service.updateThingShadow("sensor-8", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
service.updateThingShadow("sensor-8", null, json("{\"state\":{\"desired\":{\"color\":\"red\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
clearInvocations(broker);
|
||||
|
||||
mqttShadowRequest("$aws/things/sensor-8/shadow/delete", "{\"clientToken\":\"d-1\"}");
|
||||
|
||||
JsonNode accepted = fannedOut("$aws/things/sensor-8/shadow/delete/accepted");
|
||||
assertEquals(Set.of("version", "timestamp", "clientToken"), fieldNames(accepted));
|
||||
assertEquals(2, accepted.get("version").asLong());
|
||||
assertEquals("d-1", accepted.get("clientToken").asText());
|
||||
assertEquals(List.of("$aws/things/sensor-8/shadow/delete/accepted"), recordedTopics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttVersionConflictPublishesRejectedWithTheHttpStatusAndClientToken() throws Exception {
|
||||
service.updateThingShadow("sensor-9", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
clearInvocations(broker);
|
||||
|
||||
mqttShadowRequest("$aws/things/sensor-9/shadow/update",
|
||||
"{\"version\":7,\"state\":{\"desired\":{\"color\":\"red\"}},\"clientToken\":\"c-9\"}");
|
||||
|
||||
assertEquals(json("{\"code\":409,\"message\":\"Version conflict\",\"clientToken\":\"c-9\"}"),
|
||||
fannedOut("$aws/things/sensor-9/shadow/update/rejected"));
|
||||
assertEquals(List.of("$aws/things/sensor-9/shadow/update/rejected"), recordedTopics());
|
||||
verify(broker, times(1)).publish(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restVersionConflictIsConflictExceptionWithStatus409() throws Exception {
|
||||
service.updateThingShadow("sensor-9", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.updateThingShadow("sensor-9", null,
|
||||
json("{\"version\":7,\"state\":{\"desired\":{\"color\":\"red\"}}}"), REGION));
|
||||
|
||||
assertEquals("ConflictException", e.getErrorCode());
|
||||
assertEquals(409, e.getHttpStatus());
|
||||
assertEquals("Version conflict", e.getMessage());
|
||||
assertTrue(recorder.recentEvents().isEmpty(), "a REST error publishes nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedMqttShadowJsonPublishesRejectedInvalidJsonWithoutAClientToken() throws Exception {
|
||||
mqttShadowRequest("$aws/things/sensor-9/shadow/update", "{\"clientToken\":\"c-9\",");
|
||||
|
||||
assertEquals(json("{\"code\":400,\"message\":\"Invalid JSON\"}"),
|
||||
fannedOut("$aws/things/sensor-9/shadow/update/rejected"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttGetOfAMissingShadowPublishesRejected404WithTheClientToken() throws Exception {
|
||||
mqttShadowRequest("$aws/things/nobody/shadow/name/building/get", "{\"clientToken\":\"g-2\"}");
|
||||
|
||||
JsonNode rejected = fannedOut("$aws/things/nobody/shadow/name/building/get/rejected");
|
||||
assertEquals(Set.of("code", "message", "clientToken"), fieldNames(rejected));
|
||||
assertEquals(404, rejected.get("code").asInt());
|
||||
assertEquals("g-2", rejected.get("clientToken").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsupportedMqttShadowOperationPublishesRejected400WithTheClientToken() throws Exception {
|
||||
mqttShadowRequest("$aws/things/sensor-9/shadow/name/building/list", "{\"clientToken\":\"u-1\"}");
|
||||
|
||||
assertEquals(json("{\"code\":400,\"message\":\"Unsupported shadow operation: list\",\"clientToken\":\"u-1\"}"),
|
||||
fannedOut("$aws/things/sensor-9/shadow/name/building/list/rejected"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttPublishOnAShadowResponseTopicIsNotProcessedAsARequest() throws Exception {
|
||||
mqttShadowRequest("$aws/things/sensor-11/shadow/update/accepted", "{\"state\":{\"desired\":{\"color\":\"blue\"}}}");
|
||||
mqttShadowRequest("$aws/things/sensor-11/shadow/name/building/update/delta", "{\"state\":{\"color\":\"blue\"}}");
|
||||
|
||||
verifyNoInteractions(broker);
|
||||
assertTrue(recorder.recentEvents().isEmpty());
|
||||
assertThrows(AwsException.class, () -> service.getThingShadow("sensor-11", null, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttRequestOnANamedTopicWithAnInvalidNameIsIgnored() throws Exception {
|
||||
service.updateThingShadow("sensor-12", null, json("{\"state\":{\"desired\":{\"color\":\"blue\"}}}"), REGION);
|
||||
recorder.clear();
|
||||
clearInvocations(broker);
|
||||
String update = "{\"state\":{\"desired\":{\"color\":\"green\"}},\"clientToken\":\"t\"}";
|
||||
|
||||
mqttShadowRequest("$aws/things/sensor-12/shadow/name/ /update", update);
|
||||
mqttShadowRequest("$aws/things/sensor-12/shadow/name//update", update);
|
||||
mqttShadowRequest("$aws/things/sensor-12/shadow/name/bad!/delete", "{}");
|
||||
mqttShadowRequest("$aws/things/sensor-12/shadow/name/ /get", "{}");
|
||||
|
||||
assertEquals(List.of(), recordedTopics());
|
||||
verifyNoInteractions(broker);
|
||||
JsonNode classic = service.getThingShadow("sensor-12", null, REGION);
|
||||
assertEquals("blue", classic.at("/state/desired/color").asText());
|
||||
assertEquals(1, classic.get("version").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttUpdateOnTheReservedPackageShadowIsApplied() throws Exception {
|
||||
String update = "$aws/things/sensor-14/shadow/name/$package/update";
|
||||
|
||||
mqttShadowRequest(update, "{\"state\":{\"reported\":{\"samplePackage\":{\"version\":\"1.0.0\"}}}}");
|
||||
|
||||
assertEquals(1, fannedOut(update + "/accepted").get("version").asLong());
|
||||
assertEquals("1.0.0", service.getThingShadow("sensor-14", "$package", REGION)
|
||||
.at("/state/reported/samplePackage/version").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anMqttUpdateOnADollarShadowNameOtherThanPackagePublishesRejected400() throws Exception {
|
||||
String update = "$aws/things/sensor-14/shadow/name/a$b/update";
|
||||
|
||||
mqttShadowRequest(update, "{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"c-14\"}");
|
||||
|
||||
assertEquals(json("{\"code\":400,\"message\":\"Invalid shadow name : a$b\",\"clientToken\":\"c-14\"}"),
|
||||
fannedOut(update + "/rejected"));
|
||||
assertEquals(List.of(update + "/rejected"), recordedTopics());
|
||||
assertEquals(List.of(), service.listNamedShadowsForThing("sensor-14", REGION));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -147,7 +147,7 @@ class IotTopicRuleSqlIntegrationTest {
|
||||
|
||||
publish("sqltest/functions/a", "{\"n\":null}");
|
||||
|
||||
assertEquals(List.of("{\"client\":\"n/a\",\"account\":\"000000000000\",\"u\":true}"),
|
||||
assertEquals(List.of("{\"client\":\"N/A\",\"account\":\"000000000000\",\"u\":true}"),
|
||||
republished("sqltest/functions-out"));
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ class IotTopicRuleSqlIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertEquals(List.of("{\"client\":\"n/a\"}"), republished("sqltest/httpclient-out"));
|
||||
assertEquals(List.of("{\"client\":\"N/A\"}"), republished("sqltest/httpclient-out"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class RuleSqlFunctionsTest {
|
||||
@Test
|
||||
void clientidIsTheMqttClientOrNaWhenTheMessageDidNotComeOverMqtt() {
|
||||
assertEquals("{\"client\":\"sensor-7\"}", text(evaluate("SELECT clientid() AS client FROM 'a/b'", MQTT, "{}")));
|
||||
assertEquals("{\"client\":\"n/a\"}", text(evaluate("SELECT clientid() AS client FROM 'a/b'", HTTP, "{}")));
|
||||
assertEquals("{\"client\":\"N/A\"}", text(evaluate("SELECT clientid() AS client FROM 'a/b'", HTTP, "{}")));
|
||||
assertTrue(evaluate("SELECT * FROM 'a/b' WHERE startswith(clientid(), 'sensor-')", MQTT, "{}").isPresent());
|
||||
assertFalse(evaluate("SELECT * FROM 'a/b' WHERE startswith(clientid(), 'sensor-')", HTTP, "{}").isPresent());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user