Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ public void processLinkedAttributeWrite(AttributeEvent event) {
doLinkedAttributeWrite(agent.getAgentLink(event), event, ignoreAndConverted.value);

if (agent.isUpdateOnWrite().orElse(false) || agentLink.getUpdateOnWrite().orElse(false)) {
updateLinkedAttribute(event.getRef(), ignoreAndConverted.value);
updateLinkedAttribute(
event.getRef(),
ignoreAndConverted.value,
timerService.getCurrentTimeMillis(),
Objects.toString(event.getSource(), ""));
}
}
}
Expand Down Expand Up @@ -204,6 +208,11 @@ protected final void sendAttributeEvent(AttributeEvent event) {
@Override
public final void updateLinkedAttribute(
final AttributeRef attributeRef, final Object value, long timestamp) {
updateLinkedAttribute(attributeRef, value, timestamp, null);
}

private void updateLinkedAttribute(
AttributeRef attributeRef, Object value, long timestamp, String optimisticWriteSource) {
Attribute<?> attribute = linkedAttributes.get(attributeRef);

if (attribute == null) {
Expand All @@ -225,7 +234,8 @@ public final void updateLinkedAttribute(
}

AttributeEvent attributeEvent =
new AttributeEvent(attributeRef, ignoreAndConverted.value, timestamp);
new AttributeEvent(attributeRef, ignoreAndConverted.value, timestamp)
.setOptimisticWriteSource(optimisticWriteSource);
LOG.log(System.Logger.Level.TRACE, () -> "Sending linked attribute update: " + attributeEvent);
assetService.sendAttributeEvent(attributeEvent);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -540,13 +540,14 @@ protected boolean processAttributeEvent(AttributeEvent event) throws AssetProces

AttributeEvent enrichedEvent =
new AttributeEvent(
asset,
attribute,
event.getSource(),
event.getValue().orElse(null),
event.getTimestamp(),
attribute.getValue().orElse(null),
attribute.getTimestamp().orElse(0L));
asset,
attribute,
event.getSource(),
event.getValue().orElse(null),
event.getTimestamp(),
attribute.getValue().orElse(null),
attribute.getTimestamp().orElse(0L))
.setOptimisticWriteSource(event.getOptimisticWriteSource());

// Do standard JSR-380 validation on the event
Set<ConstraintViolation<AttributeEvent>> validationFailures =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
import static org.openremote.manager.gateway.GatewayClientService.CLIENT_EVENT_SESSION_PREFIX;
import static org.openremote.manager.gateway.GatewayConnector.ASSET_READ_EVENT_NAME_INITIAL;
import static org.openremote.model.syslog.SyslogCategory.GATEWAY;
import static org.openremote.model.value.MetaItemType.AGENT_LINK;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.netty.channel.ChannelHandler;
import java.net.URI;
import java.net.URISyntaxException;
Expand All @@ -34,6 +37,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
Expand All @@ -42,6 +46,7 @@
import org.openremote.agent.protocol.websocket.WebsocketIOClient;
import org.openremote.container.Container;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.agent.AgentService;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.event.ClientEventService;
Expand Down Expand Up @@ -88,6 +93,15 @@ public class GatewayClientConnector implements AutoCloseable {
private static final Logger LOG =
SyslogCategory.getLogger(GATEWAY, GatewayClientConnector.class.getName());
protected static final int GATEWAY_SYNC_TIMEOUT_MILLIS = 60000;
// Match the default Manager UI write timeout.
private static final long PENDING_WRITE_TIMEOUT_MILLIS = 5000;
private final Cache<AttributeRef, Deque<PendingWrite>> pendingWrites =
CacheBuilder.newBuilder()
.expireAfterWrite(Duration.ofMillis(PENDING_WRITE_TIMEOUT_MILLIS))
.build();

private record PendingWrite(long receivedAt, Object value) {}

protected final ClientEventService clientEventService;
protected final TimerService timerService;
protected final AssetStorageService assetStorageService;
Expand Down Expand Up @@ -122,10 +136,10 @@ public GatewayClientConnector(
activeTunnelSessions = tunnelFactory != null ? new CopyOnWriteArrayList<>() : null;

if (!connection.isDisabled()) {
client = createClient();
if (connection.getAttributeFilters() != null && !connection.getAttributeFilters().isEmpty()) {
attributeTimestamps = new ConcurrentHashMap<>();
}
client = createClient();
}
}

Expand Down Expand Up @@ -160,6 +174,7 @@ public void close() throws Exception {
if (realmAssetEventConsumer != null) {
clientEventService.removeSubscription(realmAssetEventConsumer);
}
pendingWrites.invalidateAll();
}

protected WebsocketIOClient<String> createClient() {
Expand Down Expand Up @@ -238,6 +253,7 @@ protected String getAuthTokenEndpoint() throws URISyntaxException, IllegalArgume
}

protected CompletableFuture<Void> doInit() {
pendingWrites.invalidateAll();
// Clear gateway API version
gatewayAPIVersion = null;
// Set init future which will be completed when gateway asset sync is complete
Expand Down Expand Up @@ -356,8 +372,7 @@ protected void onCentralManagerMessage(String message) {
case GatewayDisconnectEvent disconnectEvent ->
LOG.info("Central manager requested disconnect: reason=" + disconnectEvent.getReason());
// An attribute event has occurred for a gateway descendant asset
case AttributeEvent attributeEvent ->
assetProcessingService.sendAttributeEvent(attributeEvent, getClass().getSimpleName());
case AttributeEvent attributeEvent -> onCentralManagerAttributeWrite(attributeEvent);
// An asset event has occurred for a gateway descendant asset
case AssetEvent assetEvent -> {
if (assetEvent.getCause() == AssetEvent.Cause.CREATE
Expand Down Expand Up @@ -430,6 +445,79 @@ protected void onCentralManagerMessage(String message) {
}
}

private void onCentralManagerAttributeWrite(AttributeEvent event) {
if (attributeTimestamps == null || event.getRef() == null) {
assetProcessingService.sendAttributeEvent(event, getClass().getSimpleName());
return;
}

long now = timerService.getCurrentTimeMillis();
PendingWrite write = new PendingWrite(now, event.getValue().orElse(null));
pendingWrites
.asMap()
.compute(
event.getRef(),
(ref, writes) -> {
if (writes == null) {
writes = new ArrayDeque<>();
}
writes.removeIf(
pending -> now - pending.receivedAt() >= PENDING_WRITE_TIMEOUT_MILLIS);
writes.addLast(write);
return writes;
});
try {
assetProcessingService.sendAttributeEvent(event, getClass().getSimpleName());
} catch (RuntimeException e) {
removePendingWrite(event.getRef(), pending -> pending == write);
throw e;
}
}

private boolean matchesPendingWrite(AttributeEvent event) {
if (!AgentService.class.getSimpleName().equals(event.getSource())
|| event.getMeta() == null
|| !event.getMeta().has(AGENT_LINK)
|| event.getOptimisticWriteSource() != null
|| event.isOutdated()) {
return false;
}

// Agent telemetry can also match. Limit the bypass to one matching update per recent write.
long now = timerService.getCurrentTimeMillis();
Object value = event.getValue().orElse(null);
return removePendingWrite(
event.getRef(),
pending ->
pending.receivedAt() <= event.getTimestamp()
&& now - pending.receivedAt() < PENDING_WRITE_TIMEOUT_MILLIS
&& (pending.value() == null
? value == null
: ValueUtil.getValueCoerced(pending.value(), event.getTypeClass())
.filter(expected -> Objects.deepEquals(expected, value))
.isPresent()));
}

private boolean removePendingWrite(AttributeRef ref, Predicate<PendingWrite> matches) {
AtomicReference<PendingWrite> removed = new AtomicReference<>();
pendingWrites
.asMap()
.computeIfPresent(
ref,
(key, writes) -> {
for (Iterator<PendingWrite> iterator = writes.iterator(); iterator.hasNext(); ) {
PendingWrite write = iterator.next();
if (matches.test(write)) {
iterator.remove();
removed.set(write);
break;
}
}
return writes.isEmpty() ? null : writes;
});
return removed.get() != null;
}

/**
* Synchronize the current active tunnel sessions async with what the central instance thinks are
* open.
Expand Down Expand Up @@ -770,6 +858,20 @@ protected EventFilter<AttributeEvent> getOutboundAttributeEventFilter() {
return ev;
}

// Skip any events for attributes excluded by sync rules
if (connection.getAssetSyncRules() != null) {
GatewayAssetSyncRule syncRule =
connection
.getAssetSyncRules()
.getOrDefault(ev.getAssetType(), connection.getAssetSyncRules().get("*"));
if (syncRule != null
&& syncRule.excludeAttributes != null
&& syncRule.excludeAttributes.contains(ev.getName())) {
LOG.finest(() -> "Attribute event excluded due to sync rule: " + ev);
return null;
}
}

boolean allowEvent =
predicatesWithFilters.stream()
.filter(
Expand All @@ -790,7 +892,13 @@ protected EventFilter<AttributeEvent> getOutboundAttributeEventFilter() {
if (filter.getSkipAlways() != null && filter.getSkipAlways()) {
return false;
}
if (filter.getValueChange() != null && filter.getValueChange()) {
Optional<Long> duration = filter.getDurationParsed();
if (duration.isPresent()
&& getClass().getSimpleName().equals(ev.getOptimisticWriteSource())) {
return false;
}
boolean pendingWrite = duration.isPresent() && matchesPendingWrite(ev);
if (!pendingWrite && Boolean.TRUE.equals(filter.getValueChange())) {
if (!Objects.equals(ev.getValue(), ev.getOldValue())) {
LOG.finest(
() ->
Expand All @@ -801,7 +909,7 @@ protected EventFilter<AttributeEvent> getOutboundAttributeEventFilter() {
return true;
}
}
if (filter.getDelta() != null) {
if (!pendingWrite && filter.getDelta() != null) {
if (Number.class.isAssignableFrom(ev.getTypeClass())) {
double delta = filter.getDelta();
double value = ev.getValue(Double.class).orElse(0d);
Expand All @@ -817,57 +925,34 @@ protected EventFilter<AttributeEvent> getOutboundAttributeEventFilter() {
}
}
}
if (filter.getDurationParsed().isPresent()) {
boolean allow =
filter
.getDurationParsed()
.map(
durationMillis -> {
Long lastSendMillis = attributeTimestamps.get(ev.getRef());
if (lastSendMillis == null
|| timerService.getCurrentTimeMillis() - lastSendMillis
> durationMillis) {
LOG.finest(
() ->
"Gateway client for '"
+ connection.getLocalRealm()
+ "' duration setting has allowed attribute event: "
+ ev.getRef());
attributeTimestamps.put(
ev.getRef(), timerService.getCurrentTimeMillis());
return true;
}
LOG.finest(
() ->
"Gateway client for '"
+ connection.getLocalRealm()
+ "' duration setting has blocked attribute event: "
+ ev.getRef());
return false;
})
.orElse(true);

return allow;
if (duration.isPresent()) {
long now = timerService.getCurrentTimeMillis();
Long lastSendMillis = attributeTimestamps.get(ev.getRef());
if (lastSendMillis == null || now - lastSendMillis > duration.get()) {
attributeTimestamps.put(ev.getRef(), now);
LOG.finest(
() ->
"Gateway client for '"
+ connection.getLocalRealm()
+ "' duration setting has allowed attribute event: "
+ ev.getRef());
return true;
}
if (pendingWrite) {
return true;
}
LOG.finest(
() ->
"Gateway client for '"
+ connection.getLocalRealm()
+ "' duration setting has blocked attribute event: "
+ ev.getRef());
}

return false;
})
.orElse(true);

// Skip any events for attributes excluded by sync rules
if (allowEvent && connection.getAssetSyncRules() != null) {
GatewayAssetSyncRule syncRule =
connection
.getAssetSyncRules()
.getOrDefault(ev.getAssetType(), connection.getAssetSyncRules().get("*"));
if (syncRule != null
&& syncRule.excludeAttributes != null
&& syncRule.excludeAttributes.contains(ev.getName())) {
LOG.finest(() -> "Attribute event excluded due to sync rule: " + ev);
allowEvent = false;
}
}

return allowEvent ? ev : null;
};
}
Expand Down
Loading
Loading