mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 10:38:00 -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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user