From 715430700c72626d1a6d7936212444e8b0e9c903 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Wed, 8 Jul 2026 12:59:21 +0300 Subject: [PATCH 001/119] Sync persistent RPC (v2) status Edge->Cloud and delete in both directions --- .../server/controller/RpcV2Controller.java | 36 +++++++++++++++++- .../service/edge/EdgeContextComponent.java | 4 ++ .../service/edge/EdgeMsgConstructorUtils.java | 12 ++++-- .../processor/device/DeviceEdgeProcessor.java | 37 ++++++++++++++++++- .../server/service/rpc/TbRpcService.java | 4 ++ .../server/common/data/rpc/RpcStatus.java | 6 +-- .../server/common/data/rpc/RpcStatusTest.java | 10 ++--- common/edge-api/src/main/proto/edge.proto | 1 + 8 files changed, 96 insertions(+), 14 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index 412e775327..3f7041f863 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.controller; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.FutureCallback; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; @@ -24,6 +25,7 @@ import jakarta.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -35,8 +37,13 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.server.ResponseStatusException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.edge.EdgeEventActionType; +import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; @@ -46,12 +53,15 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.permission.Operation; +import java.util.List; import java.util.UUID; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_ID; @@ -74,6 +84,9 @@ import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CU @Slf4j public class RpcV2Controller extends AbstractRpcController { + @Autowired + private TbRpcService tbRpcService; + private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " + "The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " + "See example below. We will review the properties of the RPC call one-by-one below. " + @@ -230,15 +243,19 @@ public class RpcV2Controller extends AbstractRpcController { Rpc rpc = checkRpcId(rpcId, Operation.DELETE); if (rpc != null) { - if (rpc.getStatus().isPushDeleteNotificationToCore()) { + if (rpc.getStatus().isIntermediate()) { RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId()); log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc); tbClusterService.pushMsgToCore(removeMsg, null); } - rpcService.deleteRpc(getTenantId(), rpcId); + tbRpcService.deleteRpc(getTenantId(), rpcId); rpc.setStatus(RpcStatus.DELETED); + // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status + // (the actor RemoveRpcActorMsg above only covers non-terminal RPCs). + pushRpcDeleteToEdges(rpc); + TbMsg msg = TbMsg.newMsg() .type(TbMsgType.RPC_DELETED) .originator(rpc.getDeviceId()) @@ -248,4 +265,19 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null); } } + + private void pushRpcDeleteToEdges(Rpc rpc) throws ThingsboardException { + List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(getTenantId(), rpc.getDeviceId()); + if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { + return; + } + ObjectNode body = JacksonUtil.newObjectNode(); + body.put("requestUUID", rpc.getId().getId().toString()); + body.put("rpcStatus", RpcStatus.DELETED.name()); + for (EdgeId edgeId : relatedEdgeIds) { + EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(getTenantId(), edgeId, EdgeEventType.DEVICE, + EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); + tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(getTenantId(), edgeEvent)); + } + } } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index fbb3591bb5..e7885081b1 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -58,6 +58,7 @@ import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings; import org.thingsboard.server.service.edge.rpc.EdgeRpcService; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.service.edge.rpc.processor.EdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.alarm.AlarmProcessor; import org.thingsboard.server.service.edge.rpc.processor.alarm.comment.AlarmCommentProcessor; @@ -134,6 +135,9 @@ public class EdgeContextComponent { @Autowired private DeviceService deviceService; + @Autowired + private TbRpcService tbRpcService; + @Autowired private DomainService domainService; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java index 2417931e0b..0778bd4401 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java @@ -272,20 +272,23 @@ public class EdgeMsgConstructorUtils { responseBuilder.setResponse(body.get("response").asText()); } builder.setResponseMsg(responseBuilder.build()); - } else { + } else if (body.has("method")) { RpcRequestMsg.Builder requestBuilder = RpcRequestMsg.newBuilder(); requestBuilder.setMethod(body.get("method").asText()); requestBuilder.setParams(body.get("params").asText()); builder.setRequestMsg(requestBuilder.build()); } + // else: status-only message (rpcStatus set in constructDeviceRpcMsg) carries neither request nor response body return builder.build(); } private static DeviceRpcCallMsg.Builder constructDeviceRpcMsg(UUID deviceId, JsonNode body) { DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() .setDeviceIdMSB(deviceId.getMostSignificantBits()) - .setDeviceIdLSB(deviceId.getLeastSignificantBits()) - .setRequestId(body.get("requestId").asInt()); + .setDeviceIdLSB(deviceId.getLeastSignificantBits()); + if (body.get("requestId") != null) { + builder.setRequestId(body.get("requestId").asInt()); + } if (body.get("oneway") != null) { builder.setOneway(body.get("oneway").asBoolean()); } @@ -312,6 +315,9 @@ public class EdgeMsgConstructorUtils { if (body.get("sessionId") != null) { builder.setSessionId(body.get("sessionId").asText()); } + if (body.get("rpcStatus") != null) { + builder.setRpcStatus(body.get("rpcStatus").asText()); + } return builder; } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index dab3efd911..ed8e948f5a 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -22,6 +22,7 @@ import com.google.common.util.concurrent.SettableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.data.util.Pair; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonNode; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; @@ -37,7 +38,10 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; +import org.thingsboard.server.common.data.id.RpcId; +import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcError; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgDataType; @@ -138,7 +142,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr @Override public ListenableFuture processDeviceRpcCallFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg); - if (deviceRpcCallMsg.hasResponseMsg()) { + if (deviceRpcCallMsg.hasRpcStatus()) { + // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID). + return processDeviceRpcStatusFromEdge(tenantId, deviceRpcCallMsg); + } else if (deviceRpcCallMsg.hasResponseMsg()) { return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasRequestMsg()) { return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg); @@ -146,6 +153,34 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr return Futures.immediateFuture(null); } + private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { + RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { + // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. + if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { + edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + } + return Futures.immediateFuture(null); + } + RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus()); + Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); + if (existingRpc == null) { + return Futures.immediateFuture(null); + } + if (!existingRpc.getStatus().isIntermediate() && rpcStatus.isIntermediate()) { + // guard against out-of-order status uplinks regressing a terminal RPC (e.g. stale DELIVERED after SUCCESSFUL) + log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already terminal [{}]", + tenantId, rpcId, rpcStatus, existingRpc.getStatus()); + return Futures.immediateFuture(null); + } + JsonNode response = null; + if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) { + response = JacksonUtil.toJsonNode(deviceRpcCallMsg.getResponseMsg().getResponse()); + } + edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response); + return Futures.immediateFuture(null); + } + private ListenableFuture processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { SettableFuture futureToSet = SettableFuture.create(); UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()); diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index 912e8242c6..de7112b7d0 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -80,4 +80,8 @@ public class TbRpcService { return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } + public void deleteRpc(TenantId tenantId, RpcId rpcId) { + rpcService.deleteRpc(tenantId, rpcId); + } + } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java index b731fbe125..9e07943570 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java @@ -29,10 +29,10 @@ public enum RpcStatus { DELETED(false); @Getter - private final boolean pushDeleteNotificationToCore; + private final boolean intermediate; - RpcStatus(boolean pushDeleteNotificationToCore) { - this.pushDeleteNotificationToCore = pushDeleteNotificationToCore; + RpcStatus(boolean intermediate) { + this.intermediate = intermediate; } } diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java index 0c0f5a810e..638b486ae2 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java @@ -26,20 +26,20 @@ import static org.thingsboard.server.common.data.rpc.RpcStatus.SENT; class RpcStatusTest { - private static final List pushDeleteNotificationToCoreStatuses = List.of( + private static final List intermediateStatuses = List.of( QUEUED, SENT, DELIVERED ); @Test - void isPushDeleteNotificationToCoreStatusTest() { + void isIntermediateStatusTest() { var rpcStatuses = RpcStatus.values(); for (var status : rpcStatuses) { - if (pushDeleteNotificationToCoreStatuses.contains(status)) { - assertThat(status.isPushDeleteNotificationToCore()).isTrue(); + if (intermediateStatuses.contains(status)) { + assertThat(status.isIntermediate()).isTrue(); } else { - assertThat(status.isPushDeleteNotificationToCore()).isFalse(); + assertThat(status.isIntermediate()).isFalse(); } } } diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 520b4ac493..148940196e 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -390,6 +390,7 @@ message DeviceRpcCallMsg { optional string additionalInfo = 12; optional string serviceId = 13; optional string sessionId = 14; + optional string rpcStatus = 15; } message RpcRequestMsg { From dd369b28326d267c8edb58cac2a02b54d39eca48 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Wed, 8 Jul 2026 15:55:34 +0300 Subject: [PATCH 002/119] Move pushRpcDeleteToEdges from controller to service layer --- .../server/controller/RpcV2Controller.java | 27 --------------- .../processor/device/DeviceEdgeProcessor.java | 12 +++++-- .../server/service/rpc/TbRpcService.java | 34 +++++++++++++++++++ 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index 3f7041f863..3e55895db1 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -15,7 +15,6 @@ */ package org.thingsboard.server.controller; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.FutureCallback; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; @@ -37,13 +36,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.server.ResponseStatusException; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.EdgeUtils; -import org.thingsboard.server.common.data.edge.EdgeEvent; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; -import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceId; -import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; @@ -53,7 +47,6 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; -import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.config.annotations.ApiOperation; @@ -61,7 +54,6 @@ import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.permission.Operation; -import java.util.List; import java.util.UUID; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_ID; @@ -252,10 +244,6 @@ public class RpcV2Controller extends AbstractRpcController { tbRpcService.deleteRpc(getTenantId(), rpcId); rpc.setStatus(RpcStatus.DELETED); - // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status - // (the actor RemoveRpcActorMsg above only covers non-terminal RPCs). - pushRpcDeleteToEdges(rpc); - TbMsg msg = TbMsg.newMsg() .type(TbMsgType.RPC_DELETED) .originator(rpc.getDeviceId()) @@ -265,19 +253,4 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null); } } - - private void pushRpcDeleteToEdges(Rpc rpc) throws ThingsboardException { - List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(getTenantId(), rpc.getDeviceId()); - if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { - return; - } - ObjectNode body = JacksonUtil.newObjectNode(); - body.put("requestUUID", rpc.getId().getId().toString()); - body.put("rpcStatus", RpcStatus.DELETED.name()); - for (EdgeId edgeId : relatedEdgeIds) { - EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(getTenantId(), edgeId, EdgeEventType.DEVICE, - EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); - tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(getTenantId(), edgeEvent)); - } - } } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index ed8e948f5a..d9bb0fe310 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -144,7 +144,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg); if (deviceRpcCallMsg.hasRpcStatus()) { // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID). - return processDeviceRpcStatusFromEdge(tenantId, deviceRpcCallMsg); + return processDeviceRpcStatusFromEdge(tenantId, edge, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasResponseMsg()) { return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasRequestMsg()) { @@ -153,12 +153,18 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr return Futures.immediateFuture(null); } - private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { + private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. + // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges. if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { - edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + try { + edgeSynchronizationManager.getEdgeId().set(edge.getId()); + edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + } finally { + edgeSynchronizationManager.getEdgeId().remove(); + } } return Futures.immediateFuture(null); } diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index de7112b7d0..7489151d11 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -16,12 +16,18 @@ package org.thingsboard.server.service.rpc; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.edge.EdgeEventActionType; +import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; @@ -31,9 +37,14 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; +import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.queue.util.TbCoreComponent; +import java.util.List; + @TbCoreComponent @Service @RequiredArgsConstructor @@ -41,6 +52,8 @@ import org.thingsboard.server.queue.util.TbCoreComponent; public class TbRpcService { private final RpcService rpcService; private final TbClusterService tbClusterService; + private final EdgeService edgeService; + private final EdgeSynchronizationManager edgeSynchronizationManager; public Rpc save(TenantId tenantId, Rpc rpc) { Rpc saved = rpcService.save(rpc); @@ -81,7 +94,28 @@ public class TbRpcService { } public void deleteRpc(TenantId tenantId, RpcId rpcId) { + Rpc rpc = rpcService.findById(tenantId, rpcId); rpcService.deleteRpc(tenantId, rpcId); + // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status. + // Skipped when the delete originated from an edge (edge-sync context) so it is not echoed back. + if (rpc != null && edgeSynchronizationManager.getEdgeId().get() == null) { + pushRpcDeleteToEdges(tenantId, rpc); + } + } + + private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) { + List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(tenantId, rpc.getDeviceId()); + if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { + return; + } + ObjectNode body = JacksonUtil.newObjectNode(); + body.put("requestUUID", rpc.getId().getId().toString()); + body.put("rpcStatus", RpcStatus.DELETED.name()); + for (EdgeId edgeId : relatedEdgeIds) { + EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE, + EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); + tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(tenantId, edgeEvent)); + } } } From 9f06464c803ff941d8788eb5ec1b6e717273a312 Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Mon, 13 Jul 2026 23:19:16 +0200 Subject: [PATCH 003/119] Update tbel to 1.2.11 and add java.util.Formatter sandbox test --- .../service/script/TbelInvokeServiceTest.java | 14 ++++++++++++++ pom.xml | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java index 8618e515c8..7a8d3f68a6 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java @@ -301,6 +301,20 @@ class TbelInvokeServiceTest extends AbstractTbelInvokeTest { }); } + @Test + void givenForbiddenFormatter_whenInvoking_thenThrowsRuntimeError() throws ExecutionException, InterruptedException { + UUID scriptId = evalScript("new java.util.Formatter(\"/tmp/test.txt\")"); + assertThatThrownBy(() -> invokeScript(scriptId, "{\"temperature\":25}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.RUNTIME); + assertThat(ex.getCause().getMessage()).contains("could not resolve class: java.util.Formatter"); + }); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScriptResultString(scriptId, "{}"); diff --git a/pom.xml b/pom.xml index 7d42f9f1c7..87280de7e1 100755 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ 3.9.5 3.25.5 1.76.0 - 1.2.10 + 1.2.11 1.18.46 1.2.5 1.2.5 From 43851cd3f0236ebf9603ee6f2b297b59c471e98f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:27 +0300 Subject: [PATCH 004/119] Fix Nashorn Global PropertyMap leak on JS script release --- .../script/NashornJsInvokeServiceTest.java | 85 +++++++++++++++++++ .../script/api/js/NashornJsInvokeService.java | 16 +++- 2 files changed, 97 insertions(+), 4 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index 01a5f1b6fc..c76eac8c61 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -17,13 +17,17 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import delight.nashornsandbox.NashornSandbox; +import delight.nashornsandbox.NashornSandboxes; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.TbStopWatch; +import org.thingsboard.script.api.RuleNodeScriptFactory; import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.TbScriptException; import org.thingsboard.script.api.js.NashornJsInvokeService; @@ -31,6 +35,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; @@ -222,6 +227,86 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { }); } + @Test + void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { + UUID scriptId = evalScript("return msg;"); + String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("true"); + + invokeService.release(scriptId).get(); + + // the property must be deleted, not just set to undefined: an abandoned binding keeps + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("false"); + } + + @Test + void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception { + UUID scriptId = evalScript("return {doubled: msg.temperature * 2};"); + assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42"); + } + + @Test + void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception { + UUID writer = evalScript("compatSharedState = 777; return msg;"); + UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};"); + invokeScript(writer, "{}"); + assertThat(invokeScript(reader, "{}")).contains("\"seen\":777"); + } + + @Test + void givenIifeWrappedEval_thenCompilationErrorUnchanged() { + String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;"; + + String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript, + "msg", "metadata", "msgType"); + NashornSandbox legacySandbox = NashornSandboxes.create(); + legacySandbox.allowNoBraces(false); + legacySandbox.allowLoadFunctions(true); + legacySandbox.setMaxPreparedStatements(30); + int legacyErrorLine = -1; + try { + legacySandbox.eval(legacyScript); + } catch (ScriptException e) { + legacyErrorLine = e.getLineNumber(); + } + assertThat(legacyErrorLine).isGreaterThan(0); + final int expectedLine = legacyErrorLine; + + assertThatThrownBy(() -> evalScript(badScript)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION); + assertThat(ex.getBody()).contains(badScript); + assertThat(ex.getCause()).isInstanceOf(ScriptException.class); + // The IIFE wrapper shifts sandbox-reported line numbers by a constant +2 + // (the beautifier splits the wrapper prefix onto its own lines). Reported + // lines never matched the user's source anyway (the sandbox instrumentation + // already offsets them), so only the small constant shift is tolerated here. + assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2); + }); + } + + @Test + void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception { + UUID scriptId = evalScript("return msg;"); + invokeScript(scriptId, "{}"); + invokeService.release(scriptId).get(); + assertThatThrownBy(() -> invokeScript(scriptId, "{}")) + .isInstanceOf(ExecutionException.class) + .hasMessageContaining("No compiled script found"); + } + + private Object evalInEngine(String expression) throws Exception { + Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox"); + if (sandbox != null) { + return ((NashornSandbox) sandbox).eval(expression); + } + return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScript(scriptId, "{}"); diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index 1ef2eeb6da..bb95c60481 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -140,14 +140,21 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { @Override protected ListenableFuture doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) { + // A top-level function declaration creates a non-configurable property on the Nashorn Global + // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap + // shape history forever. Declaring the function inside an IIFE and assigning it to a global + // property keeps the property configurable, allowing doRelease() to actually delete it. + // The prefix stays on the first line so that script line numbers in errors are unchanged. + String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { try { evalLock.lock(); try { if (useJsSandbox) { - sandbox.eval(jsScript); + sandbox.eval(wrappedScript); } else { - engine.eval(jsScript); + engine.eval(wrappedScript); } } finally { evalLock.unlock(); @@ -182,10 +189,11 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { } protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { + String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; if (useJsSandbox) { - sandbox.eval(scriptInfo.getFunctionName() + " = undefined;"); + sandbox.eval(deleteScript); } else { - engine.eval(scriptInfo.getFunctionName() + " = undefined;"); + engine.eval(deleteScript); } } From b67fc8dfb1ad1ca22dc076047f8ee37743b894f2 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:39 +0300 Subject: [PATCH 005/119] Release EdgeGrpcClient channel on failed connect and guard send/disconnect race --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 146 +++++++++++------- 1 file changed, 92 insertions(+), 54 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index 7e58a2cb9f..f96fe8b38f 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -86,7 +86,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private StreamObserver inputStream; - private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); + private final ReentrantLock connectionLock = new ReentrantLock(); @Override public void connect(String edgeKey, @@ -127,19 +127,38 @@ public class EdgeGrpcClient implements EdgeRpcClient { .build()); } - channel = builder.build(); - EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); - log.info("[{}] Sending a connect request to the TB!", edgeKey); - this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) - .setConnectRequestMsg(ConnectRequestMsg.newBuilder() - .setEdgeRoutingKey(edgeKey) - .setEdgeSecret(edgeSecret) - .setEdgeVersion(getNewestEdgeVersion()) - .setMaxInboundMessageSize(maxInboundMessageSize) - .build()) - .build()); + connectionLock.lock(); + try { + channel = builder.build(); + EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); + log.info("[{}] Sending a connect request to the TB!", edgeKey); + this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, channel, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) + .setConnectRequestMsg(ConnectRequestMsg.newBuilder() + .setEdgeRoutingKey(edgeKey) + .setEdgeSecret(edgeSecret) + .setEdgeVersion(getNewestEdgeVersion()) + .setMaxInboundMessageSize(maxInboundMessageSize) + .build()) + .build()); + } catch (RuntimeException e) { + // Release the half-built channel, otherwise every failed reconnect attempt leaks + // its event loops and executors, and the next attempt may not recover at all. + log.error("[{}] Failed to establish the connection, shutting down the channel!", edgeKey, e); + if (channel != null) { + try { + channel.shutdownNow(); + } catch (Exception shutdownEx) { + log.error("[{}] Exception during shutdownNow of the failed channel", edgeKey, shutdownEx); + } + } + channel = null; + inputStream = null; + throw e; + } finally { + connectionLock.unlock(); + } } public static EdgeVersion getNewestEdgeVersion() { @@ -147,6 +166,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } private StreamObserver initOutputStream(String edgeKey, + ManagedChannel streamChannel, Consumer onUplinkResponse, Consumer onEdgeUpdate, Consumer onDownlink, @@ -166,7 +186,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -188,7 +208,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void onError(Throwable t) { log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -204,77 +224,95 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { - if (!onError) { - try { - if (inputStream != null) { - inputStream.onCompleted(); + disconnect(onError, null); + } + + private void disconnect(boolean onError, ManagedChannel expectedChannel) throws InterruptedException { + ManagedChannel channelToShutdown; + connectionLock.lock(); + try { + // A terminated stream reports its error asynchronously and may lose the race with a + // reconnect: ignore such stale callbacks instead of tearing down the fresh channel. + if (expectedChannel != null && channel != expectedChannel) { + log.info("The channel was already replaced by a reconnect. Skipping disconnect of the stale channel."); + return; + } + if (!onError) { + try { + if (inputStream != null) { + inputStream.onCompleted(); + } + } catch (Exception e) { + log.error("Exception during onCompleted", e); } - } catch (Exception e) { - log.error("Exception during onCompleted", e); } + // Clear the references under the lock so that no send can start against a stream + // whose channel is shutting down - such a write leaks the compressed ByteBuf. + inputStream = null; + channelToShutdown = channel; + channel = null; + } finally { + connectionLock.unlock(); } - if (channel != null) { - channel.shutdown(); + if (channelToShutdown != null) { + channelToShutdown.shutdown(); int attempt = 0; do { try { - channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); + channelToShutdown.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { - channel.shutdownNow(); + channelToShutdown.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; - } while (!channel.isTerminated()); + } while (!channelToShutdown.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { - uplinkMsgLock.lock(); - try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setUplinkMsg(msg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(msg) + .build()); } @Override public void sendSyncRequestMsg(boolean fullSyncRequired) { - uplinkMsgLock.lock(); - try { - SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() - .setFullSync(fullSyncRequired) - .build(); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) - .setSyncRequestMsg(syncRequestMsg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() + .setFullSync(fullSyncRequired) + .build(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) + .setSyncRequestMsg(syncRequestMsg) + .build()); } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { - uplinkMsgLock.lock(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setDownlinkResponseMsg(downlinkResponseMsg) + .build()); + } + + private void sendRequestMsg(RequestMsg requestMsg) { + connectionLock.lock(); try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setDownlinkResponseMsg(downlinkResponseMsg) - .build()); + if (inputStream == null) { + throw new IllegalStateException("Edge is not connected to the cloud. The message is discarded!"); + } + inputStream.onNext(requestMsg); } finally { - uplinkMsgLock.unlock(); + connectionLock.unlock(); } } From 03df2a333ab0aad89f64d8ff397addcdf81e98e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 28 Aug 2026 12:08:27 +0300 Subject: [PATCH 006/119] Keep the edge event check alive when an edge reconnects during session teardown --- .../service/edge/rpc/EdgeGrpcService.java | 192 +++++++++++------- 1 file changed, 115 insertions(+), 77 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index e1211c53a7..4de478fe34 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -83,10 +83,11 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; -import java.util.function.Function; +import java.util.function.Predicate; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -310,13 +311,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession session = sessions.get(edgeId); - if (session != null && session.isConnected()) { + EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); - destroySession(session); - session.cleanUp(); - sessions.remove(edgeId); - sessionsById.remove(session.getSessionId()); + sessionsById.remove(toRemove.getSessionId()); final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -324,7 +322,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - cancelScheduleEdgeEventsCheck(edgeId); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); + toRemove.cleanUp(); } } @@ -365,16 +365,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i Edge edge = edgeGrpcSession.getEdge(); TenantId tenantId = edge.getTenantId(); log.info("[{}][{}] edge [{}] connected successfully.", tenantId, edgeGrpcSession.getSessionId(), edgeId); - if (sessions.containsKey(edgeId)) { - EdgeGrpcSession existing = sessions.get(edgeId); - if (existing != null) { - log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), existing.getSessionId(), edgeId); - destroySession(existing); - sessionsById.remove(existing.getSessionId()); - } - } - sessions.put(edgeId, edgeGrpcSession); + EdgeGrpcSession replaced = attachSession(edgeId, edgeGrpcSession); sessionsById.put(edgeGrpcSession.getSessionId(), edgeGrpcSession); + if (replaced != null) { + log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), replaced.getSessionId(), edgeId); + sessionsById.remove(replaced.getSessionId()); + } final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -387,9 +383,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs); edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); + if (replaced != null) { + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(replaced); + } } private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) { @@ -451,55 +450,62 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - cancelScheduleEdgeEventsCheck(edgeId); - - if (sessions.containsKey(edgeId)) { - ScheduledFuture edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> { + Runnable edgeEventCheck = () -> { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, true); } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); } else { scheduleEdgeEventsCheck(session); } - } finally { - newEventLock.unlock(); + } else { + scheduleEdgeEventsCheck(session); } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } finally { + newEventLock.unlock(); } - }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS); - sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask); + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + }; + + // arm the next check only while this exact session is still the current one, atomically with + // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the + // re-arm nor cancel a check that belongs to a session other than the one it is tearing down + sessions.compute(edgeId, (id, current) -> { + if (current != session) { + log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]", + tenantId, edgeId.getId()); + return current; + } + cancelScheduleEdgeEventsCheck(edgeId); + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); - } else { - log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]", - tenantId, edgeId.getId()); - } + return current; + }); } private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { @@ -532,24 +538,20 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void onEdgeDisconnect(Edge edge, UUID sessionId) { EdgeId edgeId = edge.getId(); log.info("[{}][{}] edge disconnected!", edgeId, sessionId); - EdgeGrpcSession current = sessions.get(edgeId); - if (current != null && current.getSessionId().equals(sessionId)) { - EdgeGrpcSession toRemove = sessions.remove(edgeId); - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - sessionNewEvents.remove(edgeId); - } finally { - newEventLock.unlock(); - } - destroySession(toRemove); + EdgeGrpcSession toRemove = detachSession(edgeId, current -> current.getSessionId().equals(sessionId)); + if (toRemove != null) { + // sessionNewEvents is deliberately left as is: clearing it here could wipe the flag a + // reconnecting session has just set, and updateSessionEventsFlag only lifts FALSE, not a + // missing entry, which would leave the check loop idle forever. deleteEdge still clears it sessionsById.remove(sessionId); + edgeIdServiceIdCache.evict(edgeId); TenantId tenantId = toRemove.getEdge().getTenantId(); - save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); + save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); + pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); EdgeGrpcSession stale = sessionsById.remove(sessionId); @@ -564,7 +566,41 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - edgeIdServiceIdCache.evict(edgeId); + } + + /** + * Registers the session as the current one for the edge and cancels the edge event check armed by + * the session it replaces, as a single atomic step. Returns the replaced session, or null if there + * was none - the caller is responsible for destroying it outside of this critical section. + */ + private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { + AtomicReference replaced = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + replaced.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return session; + }); + return replaced.get(); + } + + /** + * Detaches the edge's registered session and cancels its edge event check as a single atomic step, + * but only if that session satisfies shouldDetach. Returns the detached session, or null if the + * predicate rejected it - most importantly when another session has taken the edge over in the + * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose + * the check it has just armed. The caller destroys the returned session outside the atomic step. + */ + private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { + AtomicReference detached = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + if (current == null || !shouldDetach.test(current)) { + return current; + } + detached.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return null; + }); + return detached.get(); } private void destroySession(EdgeGrpcSession session) { @@ -686,7 +722,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); + // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer + // session must not be evicted by the cleanup of the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { @@ -715,11 +753,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return result; } - private void tryToDestroyZombieSessions(List sessionsToRemove, Function removeFunc) { + private void tryToDestroyZombieSessions(List sessionsToRemove, Consumer removeFunc) { for (EdgeGrpcSession toRemove : sessionsToRemove) { log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId()); if (toRemove.destroy()) { - removeFunc.apply(toRemove); + removeFunc.accept(toRemove); } } } From 1a15b5c94f729e0a7b09b13ca2e4a70b5c73e061 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 007/119] report every conflicting entity before installing a solution template Only rule chains, profiles and dashboards were checked upfront, so a template with a clashing customer, asset, device or edge died mid install on a DB constraint and had to be rolled back. All of them are validated now, and every conflict is named and reported at once instead of repeating the same sentence per entity type. Rule chains are looked up by exact name and dashboards by exact title, since the paged text search matches with 'contains' and could report a different entity as the conflict. The install dialog also stopped repeating "Failed to install " inside the error details, since it is already shown right above them. --- .../service/iot_hub/DefaultIotHubService.java | 5 +- .../solutions/DefaultSolutionService.java | 147 +++++++++++------- .../iot_hub/DefaultIotHubServiceTest.java | 35 +++++ .../solutions/DefaultSolutionServiceTest.java | 133 ++++++++++++++++ 4 files changed, 262 insertions(+), 58 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index f7cc08391a..cd90af6f26 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -952,7 +952,10 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + // The dialog already says "Failed to install ''" above the details, so only a + // failing dependency is worth naming here - for the root entry that would just repeat itself. + result.setErrorMessage(entry.isRoot() ? e.getMessage() + : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 34e56275e2..d84e681be6 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -32,7 +32,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -42,7 +41,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -151,12 +149,15 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -177,6 +178,11 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -291,71 +297,102 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - + SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { //TODO: check other entities. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, + title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, + title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, + name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, + name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, + name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return null; + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); + solutionInstallResponse.setSuccess(false); + solutionInstallResponse.setDetails(details.toString()); + return solutionInstallResponse; + } + + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (StringUtils.isEmpty(name)) { + continue; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, so those are looked up as is - skipping them + * here would let the install die on a DB constraint again. + */ + private static boolean isRandomizedAtInstall(String name) { + return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. + */ + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + if (conflictDescriptions.isEmpty()) { + return; } + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + private static T firstOrNull(Collection data) { + return data == null || data.isEmpty() ? null : data.iterator().next(); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { @@ -1450,10 +1487,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1467,7 +1500,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c252b58103..bfe0db5750 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -344,6 +344,41 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the install dialog already shows "Failed to install ''" right above these details + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // a failing dependency is not the item the dialog names, so it has to be named here + assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..a8c5697a42 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,133 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + Device device = new Device(); + device.setName("Existing device"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getDetails()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} From 56866d30c8522842a7d12b2c50e11108debe919c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 008/119] compose the failed dependency sentence in the dialog, not in the service The service was pre-composing "Failed to install dependency '':", which can never be translated and made the backend depend on the dialog already printing the root item above the details. It now reports the failure itself, and the dialog prefixes a localized sentence when the entry that failed is not the root. --- .../service/iot_hub/DefaultIotHubService.java | 5 +---- .../service/iot_hub/DefaultIotHubServiceTest.java | 15 ++++++++++----- .../iot-hub/iot-hub-install-dialog.component.ts | 6 ++++++ .../src/assets/locale/locale.constant-en_US.json | 1 + 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index cd90af6f26..f7109c3bf2 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -952,10 +952,7 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - // The dialog already says "Failed to install ''" above the details, so only a - // failing dependency is worth naming here - for the root entry that would just repeat itself. - result.setErrorMessage(entry.isRoot() ? e.getMessage() - : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index bfe0db5750..c48e5896a1 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -345,7 +345,7 @@ class DefaultIotHubServiceTest { } @Test - void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String rootVersionId = UUID.randomUUID().toString(); @@ -356,12 +356,12 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); - // the install dialog already shows "Failed to install ''" right above these details + // the sentence around the failure belongs to the dialog, which localizes it assertThat(result.getErrorMessage()).isEqualTo("install failed"); } @Test - void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String depVersionId = UUID.randomUUID().toString(); @@ -374,8 +374,13 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); - // a failing dependency is not the item the dialog names, so it has to be named here - assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index e4816d19ad..c55d708bcb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -339,6 +339,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 98f59ec8a9..aefce04e88 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,6 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}':", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From 0d275e0d2cf75dca4f50506fe9107e80e3911829 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 009/119] address review comments on the install validation - rule chains are looked up under the name from the rule chain file, the same source the install uses, instead of the name in rule_chains.json - the details end with a blank line, so the partial rollback warning the dialog appends does not land inside the last list item - an exception without a message falls back to its type, so the failing entry is still named - the dependency prefix is only added when the server sent an error message, since the fallback sentence names the root item --- .../service/iot_hub/DefaultIotHubService.java | 8 +++-- .../solutions/DefaultSolutionService.java | 22 ++++++++++++- .../iot_hub/DefaultIotHubServiceTest.java | 18 ++++++++++ .../solutions/DefaultSolutionServiceTest.java | 33 ++++++++++++++++++- .../iot-hub-install-dialog.component.ts | 10 +++--- 5 files changed, 83 insertions(+), 8 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index f7109c3bf2..1e41211cb2 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -947,12 +948,15 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + // an exception without a message would leave both the entry and the result blank, + // and the dialog would have nothing to name the failing entry by + String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); + resultEntry.setErrorMessage(failure); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(e.getMessage()); + result.setErrorMessage(failure); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index d84e681be6..216960f4fe 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -321,7 +321,7 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -345,6 +345,9 @@ public class DefaultSolutionService implements SolutionService { conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + // the dialog appends its own sentences to these details, so the list has to end with a blank line + details.append(System.lineSeparator()); + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); solutionInstallResponse.setDetails(details.toString()); @@ -391,6 +394,23 @@ public class DefaultSolutionService implements SolutionService { return "'" + value + "'"; } + /** + * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, + * so the conflict has to be looked up under the name the install will actually create. + */ + private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { + if (StringUtils.isEmpty(definition.getFile())) { + return null; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + return null; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; + } + private static T firstOrNull(Collection data) { return data == null || data.isEmpty() ? null : data.iterator().next(); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c48e5896a1..e34fd92d3c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -384,6 +384,24 @@ class DefaultIotHubServiceTest { verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index a8c5697a42..04096c3cc3 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,15 +25,19 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -57,6 +61,8 @@ class DefaultSolutionServiceTest { private AssetService assetService; @Mock private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; @InjectMocks private DefaultSolutionService service; @@ -89,6 +95,8 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); + // the dialog appends its own sentences, so the details have to end with a blank line + assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -111,6 +119,23 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -122,7 +147,13 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); } private void writeEntitiesFile(String fileName, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index c55d708bcb..54a8409063 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -338,10 +338,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + const serverError = result.errorMessage; + let message = serverError || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + // The title already names the item being installed, so only a failing dependency has to be named + // here - and only when the server reported the failure, since the fallback above names the root. + const failedDependency = serverError + ? (result.entries ?? []).find(entry => !entry.root && entry.errorMessage) : undefined; if (failedDependency) { message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; } From 6fe4852f9b953e9d73ac009de56031550f4b650a Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:56:03 +0300 Subject: [PATCH 010/119] address the second review pass on the install validation - the dialog no longer mistakes a MISSING plan entry for the failing one: such entries carry an error message of their own with no name, so the lookup now also requires the WILL_INSTALL status - the whole dependency sentence lives in the locale bundle as one key with a name and an error parameter, instead of a fragment glued to the server message, and the partial rollback warning is appended as its own paragraph by the dialog rather than relying on the details ending with a blank line - a rule chain is validated under the type from the rule chain file too, so an EDGE chain is no longer looked up among the CORE ones - names are deduplicated before the lookup rather than when formatting, so a template repeating a name queries once - the entity type and the name come from the definition itself for the five lists that carry both, which removes the pairing hazard - ExceptionUtil.getMessage replaces the hand-rolled fallback, and the single-use firstOrNull helper is inlined - the dashboard check moved after the device one to match the provision order the comment claims, and the unreachable empty-list guard is gone - tests cover both profile types, edges, the rule chain type and its two unresolvable-name branches, the deduplicated lookup and a json file holding null --- .../service/iot_hub/DefaultIotHubService.java | 10 +- .../solutions/DefaultSolutionService.java | 130 ++++++++++-------- .../solutions/DefaultSolutionServiceTest.java | 88 +++++++++++- .../iot-hub-install-dialog.component.ts | 14 +- .../assets/locale/locale.constant-en_US.json | 2 +- 5 files changed, 173 insertions(+), 71 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 1e41211cb2..f7f5fae4a5 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -20,8 +20,8 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -948,15 +948,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - // an exception without a message would leave both the entry and the result blank, - // and the dialog would have nothing to name the failing entry by - String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); - resultEntry.setErrorMessage(failure); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(failure); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 216960f4fe..cdeb9c06af 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -124,6 +124,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition; import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; @@ -181,7 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; - private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + private static final String RANDOM_PLACEHOLDER = "$random"; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,32 +322,23 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), - name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, name -> assetProfileService.findAssetProfileByName(tenantId, name)); - collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, - title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); - collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, - title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); - collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, - name -> assetService.findAssetByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, - name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, - name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); - - // the dialog appends its own sentences to these details, so the list has to end with a blank line - details.append(System.lineSeparator()); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -354,65 +346,91 @@ public class DefaultSolutionService implements SolutionService { return solutionInstallResponse; } + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); + } + } + } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); for (T definition : definitions) { String name = nameExtractor.apply(definition); - if (StringUtils.isEmpty(name)) { + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); + } + } + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate continue; } - HasName existing = lookup.apply(name); - if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } /** * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of - * every other entity are used as written, placeholder included, so those are looked up as is - skipping them - * here would let the install die on a DB constraint again. + * every other entity are used as written, placeholder included, and must be looked up as is. */ - private static boolean isRandomizedAtInstall(String name) { - return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); } /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { - if (conflictDescriptions.isEmpty()) { - return; - } + private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); - } - - private static String quoted(String value) { - return "'" + value + "'"; - } - - /** - * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, - * so the conflict has to be looked up under the name the install will actually create. - */ - private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { - if (StringUtils.isEmpty(definition.getFile())) { - return null; - } - Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); - if (!Files.exists(ruleChainPath)) { - // provisionRuleChains logs and skips such a definition, so there is nothing to validate - return null; - } - JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); - return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; - } - - private static T firstOrNull(Collection data) { - return data == null || data.isEmpty() ? null : data.iterator().next(); + .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) + .append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 04096c3cc3..d89012057b 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -24,13 +24,19 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; @@ -42,6 +48,8 @@ import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -63,6 +71,12 @@ class DefaultSolutionServiceTest { private DashboardService dashboardService; @Mock private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; @InjectMocks private DefaultSolutionService service; @@ -95,8 +109,6 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); - // the dialog appends its own sentences, so the details have to end with a blank line - assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -136,6 +148,78 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + Device device = new Device(); + device.setName("Sensor"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(deviceService); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 54a8409063..f777a4da31 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -340,19 +340,21 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage) : undefined; + // The title already names the item being installed, so only a failing dependency has to be named here, and + // only when the server reported the failure - the fallback above names the root. A missing entry carries an + // error message of its own, so the failing one is the entry the cascade actually tried to install. + const failedDependency = serverError ? (result.entries ?? []).find( + entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { - message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index aefce04e88..b5f51fd6d4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,7 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", - "install-dependency-error": "Failed to install the dependency '{{name}}':", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From f97bc57694821c4ef8d8ca05222e9319cd44c9d7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 8 Sep 2026 13:36:49 +0300 Subject: [PATCH 011/119] address the PE review notes on the install report - drop the java.util.Collection import that stayed behind when firstOrNull was inlined - cap each report section at ten names plus "and N more": a template can hold hundreds of devices, and the dialog renders these details without the height cap the plain-text branch has - leave the details empty when the server reported no message of its own, since the description above them already names the item that failed - cover the asset conflict, the capped report and the remaining mocks in the validation test --- .../solutions/DefaultSolutionService.java | 14 ++++++--- .../solutions/DefaultSolutionServiceTest.java | 31 +++++++++++++++++-- .../iot-hub-install-dialog.component.html | 14 +++++---- .../iot-hub-install-dialog.component.ts | 18 ++++++----- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index cdeb9c06af..352d4d4e17 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -150,7 +150,6 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -183,6 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_REPORTED_CONFLICTS = 10; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -338,7 +338,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -427,10 +428,13 @@ public class DefaultSolutionService implements SolutionService { * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) - .append(System.lineSeparator()); + .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { + details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + } + details.append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d89012057b..d28955e742 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; @@ -46,6 +47,8 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; @@ -88,7 +91,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionNamesEveryConflictingEntity() throws IOException { writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); - writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); Customer customer = new Customer(); customer.setTitle("Existing customer"); @@ -96,6 +99,9 @@ class DefaultSolutionServiceTest { device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); @@ -108,6 +114,7 @@ class DefaultSolutionServiceTest { .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) @@ -220,6 +227,25 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } + @Test + void testValidateSolutionCapsTheNamesItLists() throws IOException { + String definitions = IntStream.rangeClosed(1, 12) + .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") + .collect(Collectors.joining(",")); + writeEntitiesFile("devices.json", "[" + definitions + "]"); + for (int i = 1; i <= 12; i++) { + Device device = new Device(); + device.setName("Sensor " + i); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + } + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()) + .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " + + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -231,7 +257,8 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); } private void writeFile(String relativePath, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index 25c5ca2089..d267ccf57e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -141,12 +141,14 @@ @case ('error') {

{{ 'iot-hub.install-error-title' | translate }}

{{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

- @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
- {{ errorMessage }} -
+ @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
+ {{ errorMessage }} +
+ } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index f777a4da31..5fe6879e5e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage ?? ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -331,18 +331,19 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -354,7 +355,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); + const warning = this.translate.instant('iot-hub.install-rollback-partial'); + message = message ? message + '\n\n' + warning : warning; } this.errorMessage = message; return; From 79e1a9ff77dca592fb12085dbd313285137cef53 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 12:54:04 +0300 Subject: [PATCH 012/119] address the second PE review pass on the install report - rename the cap to MAX_LISTED_NAMES_PER_TYPE: it shortens the printed list, it does not limit what is validated - say how many conflicts a type has in total, and add a note when names were left out, so the "rename or delete them" instruction stays true - keep only the names in the conflict map, the entities were never read for anything else - one way of saying "there are no details" in the dialog, and one comment instead of two that open the same way - cover the whole branch of the cap (10, 11 and 12 names) and the profile name that comes from both the json file and the directory --- .../solutions/DefaultSolutionService.java | 36 ++++++---- .../solutions/DefaultSolutionServiceTest.java | 71 ++++++++++++++----- .../iot-hub-install-dialog.component.ts | 17 +++-- 3 files changed, 82 insertions(+), 42 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 352d4d4e17..d8ec610c58 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -182,7 +182,9 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; - private static final int MAX_REPORTED_CONFLICTS = 10; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,7 +323,7 @@ public class DefaultSolutionService implements SolutionService { }); // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. - Map> conflicts = new LinkedHashMap<>(); + Map> conflicts = new LinkedHashMap<>(); collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -338,8 +340,11 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); + conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, + names.stream().map(name -> "'" + name + "'").toList())); + if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -351,7 +356,7 @@ public class DefaultSolutionService implements SolutionService { * The entity type and the name both come from the definition, so a list can not end up checked against the * wrong type by mistake. */ - private void collectConflicts(Map> conflicts, List definitions, + private void collectConflicts(Map> conflicts, List definitions, Function lookup) { Set checked = new HashSet<>(); for (EntityDefinition definition : definitions) { @@ -361,7 +366,7 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { Set checked = new HashSet<>(); for (T definition : definitions) { @@ -372,14 +377,14 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflict(Map> conflicts, EntityType entityType, String name, + private void collectConflict(Map> conflicts, EntityType entityType, String name, Function lookup) { if (StringUtils.isEmpty(name)) { return; } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); } } @@ -387,7 +392,7 @@ public class DefaultSolutionService implements SolutionService { * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. */ - private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, List definitions) { Set checked = new HashSet<>(); for (ReferenceableEntityDefinition definition : definitions) { @@ -426,13 +431,16 @@ public class DefaultSolutionService implements SolutionService { /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, - * instead of the same sentence repeated for every type. + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); - if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { - details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); } details.append(System.lineSeparator()); } diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d28955e742..b1b5f1726a 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -18,6 +18,8 @@ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -61,6 +63,10 @@ class DefaultSolutionServiceTest { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); @@ -95,15 +101,14 @@ class DefaultSolutionServiceTest { Customer customer = new Customer(); customer.setTitle("Existing customer"); - Device device = new Device(); - device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); Asset asset = new Asset(); asset.setName("Existing asset"); when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -184,9 +189,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); - Device device = new Device(); - device.setName("Sensor"); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -227,23 +230,47 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } - @Test - void testValidateSolutionCapsTheNamesItLists() throws IOException { - String definitions = IntStream.rangeClosed(1, 12) - .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") - .collect(Collectors.joining(",")); - writeEntitiesFile("devices.json", "[" + definitions + "]"); - for (int i = 1; i <= 12; i++) { - Device device = new Device(); - device.setName("Sensor " + i); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()) - .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " - + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @Test @@ -261,6 +288,12 @@ class DefaultSolutionServiceTest { deviceProfileService, assetProfileService, edgeService); } + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + private void writeFile(String relativePath, String content) throws IOException { Path file = tempDir.resolve(relativePath); Files.createDirectories(file.getParent()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 5fe6879e5e..552120b83f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage ?? ''; + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -338,12 +338,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -355,8 +354,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - const warning = this.translate.instant('iot-hub.install-rollback-partial'); - message = message ? message + '\n\n' + warning : warning; + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; From 27f83a1102a31e4538a092f82f6c720c1f8eead9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 13:56:22 +0300 Subject: [PATCH 013/119] name what the install still does not pre-validate The TODO predates the report and most of it is done now - customers, assets, devices, edges, dashboards, rule chains and both profile types are all checked before anything is created. What is left is the entities that still only fail at provision time. --- .../server/service/solutions/DefaultSolutionService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index d8ec610c58..ecdb313639 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -301,7 +301,8 @@ public class DefaultSolutionService implements SolutionService { } SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - //TODO: check other entities. + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); From 99465e283cf8ee97ae722d590e191125f5b00078 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 15:27:34 +0300 Subject: [PATCH 014/119] quote the names where the conflict is collected The map then holds what the report prints, which leaves appendConflicts a plain pass-through and matches PE, where the entity group descriptions arrive already formatted. --- .../service/solutions/DefaultSolutionService.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index ecdb313639..b279d693ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -341,9 +341,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, - names.stream().map(name -> "'" + name + "'").toList())); - if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } @@ -385,7 +384,7 @@ public class DefaultSolutionService implements SolutionService { } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); } } @@ -430,6 +429,10 @@ public class DefaultSolutionService implements SolutionService { return title.contains(RANDOM_PLACEHOLDER); } + private static String quoted(String value) { + return "'" + value + "'"; + } + /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} From 11fe42de7aa596c02ad161d54e2b34459bf73e08 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 12:07:21 +0300 Subject: [PATCH 015/119] Keep the edge event check and its new events flag with the session that owns the edge --- .../service/edge/rpc/EdgeGrpcService.java | 126 +++++++++++------- 1 file changed, 77 insertions(+), 49 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 4de478fe34..5fdd67e0b3 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -311,7 +311,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + EdgeGrpcSession toRemove = detachSession(edgeId); if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); sessionsById.remove(toRemove.getSessionId()); @@ -322,7 +322,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); toRemove.cleanUp(); } @@ -386,7 +385,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); if (replaced != null) { - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(replaced); } } @@ -450,47 +448,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - Runnable edgeEventCheck = () -> { - try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); - } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } - } else { - scheduleEdgeEventsCheck(session); - } - } finally { - newEventLock.unlock(); - } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); - } - }; - // arm the next check only while this exact session is still the current one, atomically with // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the // re-arm nor cancel a check that belongs to a session other than the one it is tearing down @@ -501,13 +458,66 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return current; } cancelScheduleEdgeEventsCheck(edgeId); - sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule( + () -> processEvents(session, edgeId, tenantId), ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); return current; }); } + private void processEvents(EdgeGrpcSession session, EdgeId edgeId, TenantId tenantId) { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + if (sessions.get(edgeId) != session) { + log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]", + tenantId, edgeId.getId()); + return; + } + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + sessionNewEvents.put(edgeId, true); + } finally { + newEventLock.unlock(); + } + } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); + } else { + scheduleEdgeEventsCheck(session); + } + } else { + scheduleEdgeEventsCheck(session); + } + } finally { + newEventLock.unlock(); + } + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + } + private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { boolean isMigrationProcessed = edgeEventsMigrationProcessed.getOrDefault(edgeId, Boolean.FALSE); if (!isMigrationProcessed) { @@ -550,7 +560,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -572,6 +581,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i * Registers the session as the current one for the edge and cancels the edge event check armed by * the session it replaces, as a single atomic step. Returns the replaced session, or null if there * was none - the caller is responsible for destroying it outside of this critical section. + *

+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of + * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession}, + * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or + * acquiring the per-edge new events lock - has to be done by the caller once compute has returned. */ private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { AtomicReference replaced = new AtomicReference<>(); @@ -583,12 +597,19 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return replaced.get(); } + private EdgeGrpcSession detachSession(EdgeId edgeId) { + return detachSession(edgeId, s -> true); + } + /** * Detaches the edge's registered session and cancels its edge event check as a single atomic step, * but only if that session satisfies shouldDetach. Returns the detached session, or null if the * predicate rejected it - most importantly when another session has taken the edge over in the * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose * the check it has just armed. The caller destroys the returned session outside the atomic step. + *

+ * The remapping function is subject to the same "cheap non-blocking work only" rule as + * {@link #attachSession(EdgeId, EdgeGrpcSession)}. */ private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { AtomicReference detached = new AtomicReference<>(); @@ -603,6 +624,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return detached.get(); } + /** + * Stops the session's edge event consumer and shuts down its executor, collecting the session for a + * later retry if that fails. This can block for seconds - {@code KafkaEdgeGrpcSession.destroy()} + * gives the consumer executor up to 5s to terminate - so it must never be called from inside a + * {@link #sessions} remapping function. + */ private void destroySession(EdgeGrpcSession session) { try (session) { if (!session.destroy()) { @@ -722,9 +749,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer - // session must not be evicted by the cleanup of the one it replaced - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); + // detach by identity: the edge may have reconnected since the zombie scan, and that newer + // session must neither be evicted nor have its edge event check cancelled by the cleanup of + // the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> detachSession(s.getEdge().getId(), current -> current == s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { From a0c6bd4416be26f12ff9ef43488c2bf996c047e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 12:07:22 +0300 Subject: [PATCH 016/119] Add EdgeGrpcService tests for the edge session reconnect race --- .../rpc/EdgeGrpcServiceReconnectTest.java | 338 ++++++++++++++++++ 1 file changed, 338 insertions(+) create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java new file mode 100644 index 0000000000..8b90004e25 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java @@ -0,0 +1,338 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc; + +import com.google.common.util.concurrent.Futures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; +import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; +import org.thingsboard.server.queue.TbQueueConsumer; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Covers the reconnect race between a session that is being torn down and the session that has already + * taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new + * events flag of the session that replaced it. + */ +class EdgeGrpcServiceReconnectTest { + + // long enough that an armed check never actually fires during a test + private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; + private static final String THIS_NODE = "test-core"; + + private EdgeGrpcService service; + private ScheduledExecutorService edgeEventProcessingExecutorService; + private TbTransactionalCache edgeIdServiceIdCache; + + private TenantId tenantId; + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + tenantId = TenantId.fromUUID(UUID.randomUUID()); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(tenantId); + edge.setName("test-edge"); + + EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); + ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); + + GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); + // run future callbacks inline so the re-arm is observable without waiting on a pool + doAnswer(invocation -> { + invocation.getArgument(0, Runnable.class).run(); + return null; + }).when(grpcCallbackExecutorService).execute(any()); + + EdgeContextComponent ctx = mock(EdgeContextComponent.class); + when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); + when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); + when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); + + TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + + edgeIdServiceIdCache = mock(TbTransactionalCache.class); + // this node is the recorded owner of the edge, which is what a live local session implies + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); + + service = new EdgeGrpcService(); + ReflectionTestUtils.setField(service, "ctx", ctx); + ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); + ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); + ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); + ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); + ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + } + + @AfterEach + void tearDown() { + edgeEventProcessingExecutorService.shutdownNow(); + } + + @Test + void checkIsArmedForTheCurrentSession() { + EdgeGrpcSession session = newSession(); + sessions().put(edgeId, session); + + scheduleEdgeEventsCheck(session); + + ScheduledFuture armed = edgeEventChecks().get(edgeId); + assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); + assertThat(armed.isCancelled()).isFalse(); + } + + @Test + void checkIsNotArmedForASupersededSession() { + EdgeGrpcSession current = newSession(); + EdgeGrpcSession superseded = newSession(); + sessions().put(edgeId, current); + scheduleEdgeEventsCheck(current); + ScheduledFuture armedByCurrent = edgeEventChecks().get(edgeId); + + scheduleEdgeEventsCheck(superseded); + + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the superseded session must neither cancel nor replace the current session's check") + .isSameAs(armedByCurrent); + assertThat(armedByCurrent.isCancelled()).isFalse(); + } + + @Test + void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + ScheduledFuture armedCheck = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(session); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); + assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); + verify(edgeIdServiceIdCache).evict(edgeId); + verify(session).destroy(); + } + + @Test + void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { + EdgeGrpcSession first = newSession(); + onEdgeConnect(first); + // the edge reconnects before the gRPC stream of the first session is closed + EdgeGrpcSession second = newSession(); + onEdgeConnect(second); + ScheduledFuture armedBySecond = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(first); + + assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); + assertThat(sessionsById()).containsKey(second.getSessionId()); + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the check armed by the reconnected session survives the teardown of the one it replaced") + .isSameAs(armedBySecond); + assertThat(armedBySecond.isCancelled()).isFalse(); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + void disconnectDoesNotClearTheNewEventsFlag() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + assertThat(newEvents()).containsEntry(edgeId, true); + + onEdgeDisconnect(session); + + assertThat(newEvents()) + .as("clearing the flag here would wipe the one a reconnecting session has just raised") + .containsEntry(edgeId, true); + } + + @Test + void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { + EdgeGrpcSession session = newSession(); + when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); + sessions().put(edgeId, session); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + processEvents(session); + + assertThat(newEvents()).containsEntry(edgeId, false); + verify(session).processHighPriorityEvents(); + verify(session).processEdgeEvents(); + assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); + } + + @Test + void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { + EdgeGrpcSession superseded = newSession(); + EdgeGrpcSession current = newSession(); + sessions().put(edgeId, current); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + // cancel(true) cannot stop a check that has already started, so it runs against the old session + processEvents(superseded); + + assertThat(newEvents()) + .as("consuming the flag here would leave the reconnected session with nothing to fetch") + .containsEntry(edgeId, true); + verify(superseded, never()).processHighPriorityEvents(); + verify(superseded, never()).processEdgeEvents(); + assertThat(edgeEventChecks()).doesNotContainKey(edgeId); + } + + @Test + void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + when(zombie.destroy()).thenReturn(true); + sessions().put(edgeId, zombie); + scheduleEdgeEventsCheck(zombie); + ScheduledFuture armedByZombie = edgeEventChecks().get(edgeId); + + cleanupZombieSessions(); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(armedByZombie.isCancelled()) + .as("the removed zombie must not leave an armed check behind") + .isTrue(); + } + + @Test + void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + EdgeGrpcSession reconnected = newSession(); + sessions().put(edgeId, zombie); + // the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up + when(zombie.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, reconnected); + scheduleEdgeEventsCheck(reconnected); + return true; + }); + + cleanupZombieSessions(); + + assertThat(sessions().get(edgeId)).isSameAs(reconnected); + ScheduledFuture armedByReconnected = edgeEventChecks().get(edgeId); + assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); + assertThat(armedByReconnected.isCancelled()).isFalse(); + } + + private EdgeGrpcSession newSession() { + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + stubSession(session); + return session; + } + + private KafkaEdgeGrpcSession newZombieSession() { + KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); + stubSession(session); + @SuppressWarnings("unchecked") + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + @SuppressWarnings("unchecked") + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(consumer.isStopped()).thenReturn(false); + when(session.getConsumer()).thenReturn(consumerManager); + return session; + } + + private void stubSession(EdgeGrpcSession session) { + when(session.getEdge()).thenReturn(edge); + when(session.getTenantId()).thenReturn(tenantId); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.isConnected()).thenReturn(false); + when(session.destroy()).thenReturn(true); + } + + private void onEdgeConnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); + } + + private void onEdgeDisconnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); + } + + private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); + } + + private void processEvents(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); + } + + private void cleanupZombieSessions() { + ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); + } + + private ConcurrentMap sessions() { + return field("sessions"); + } + + private ConcurrentMap sessionsById() { + return field("sessionsById"); + } + + private ConcurrentMap> edgeEventChecks() { + return field("sessionEdgeEventChecks"); + } + + private Map newEvents() { + return field("sessionNewEvents"); + } + + private ConcurrentMap migrationProcessed() { + return field("edgeEventsMigrationProcessed"); + } + + @SuppressWarnings("unchecked") + private T field(String name) { + return (T) ReflectionTestUtils.getField(service, name); + } + +} From 33e0cb6619925078d0b1b9f08aa713137bb241e8 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 13:58:57 +0300 Subject: [PATCH 017/119] Revert "Release EdgeGrpcClient channel on failed connect and guard send/disconnect race" This reverts commit b67fc8dfb1ad1ca22dc076047f8ee37743b894f2. --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 146 +++++++----------- 1 file changed, 54 insertions(+), 92 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index f96fe8b38f..7e58a2cb9f 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -86,7 +86,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private StreamObserver inputStream; - private final ReentrantLock connectionLock = new ReentrantLock(); + private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); @Override public void connect(String edgeKey, @@ -127,38 +127,19 @@ public class EdgeGrpcClient implements EdgeRpcClient { .build()); } - connectionLock.lock(); - try { - channel = builder.build(); - EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); - log.info("[{}] Sending a connect request to the TB!", edgeKey); - this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, channel, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) - .setConnectRequestMsg(ConnectRequestMsg.newBuilder() - .setEdgeRoutingKey(edgeKey) - .setEdgeSecret(edgeSecret) - .setEdgeVersion(getNewestEdgeVersion()) - .setMaxInboundMessageSize(maxInboundMessageSize) - .build()) - .build()); - } catch (RuntimeException e) { - // Release the half-built channel, otherwise every failed reconnect attempt leaks - // its event loops and executors, and the next attempt may not recover at all. - log.error("[{}] Failed to establish the connection, shutting down the channel!", edgeKey, e); - if (channel != null) { - try { - channel.shutdownNow(); - } catch (Exception shutdownEx) { - log.error("[{}] Exception during shutdownNow of the failed channel", edgeKey, shutdownEx); - } - } - channel = null; - inputStream = null; - throw e; - } finally { - connectionLock.unlock(); - } + channel = builder.build(); + EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); + log.info("[{}] Sending a connect request to the TB!", edgeKey); + this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) + .setConnectRequestMsg(ConnectRequestMsg.newBuilder() + .setEdgeRoutingKey(edgeKey) + .setEdgeSecret(edgeSecret) + .setEdgeVersion(getNewestEdgeVersion()) + .setMaxInboundMessageSize(maxInboundMessageSize) + .build()) + .build()); } public static EdgeVersion getNewestEdgeVersion() { @@ -166,7 +147,6 @@ public class EdgeGrpcClient implements EdgeRpcClient { } private StreamObserver initOutputStream(String edgeKey, - ManagedChannel streamChannel, Consumer onUplinkResponse, Consumer onEdgeUpdate, Consumer onDownlink, @@ -186,7 +166,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { - EdgeGrpcClient.this.disconnect(true, streamChannel); + EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -208,7 +188,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void onError(Throwable t) { log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { - EdgeGrpcClient.this.disconnect(true, streamChannel); + EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -224,95 +204,77 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { - disconnect(onError, null); - } - - private void disconnect(boolean onError, ManagedChannel expectedChannel) throws InterruptedException { - ManagedChannel channelToShutdown; - connectionLock.lock(); - try { - // A terminated stream reports its error asynchronously and may lose the race with a - // reconnect: ignore such stale callbacks instead of tearing down the fresh channel. - if (expectedChannel != null && channel != expectedChannel) { - log.info("The channel was already replaced by a reconnect. Skipping disconnect of the stale channel."); - return; - } - if (!onError) { - try { - if (inputStream != null) { - inputStream.onCompleted(); - } - } catch (Exception e) { - log.error("Exception during onCompleted", e); + if (!onError) { + try { + if (inputStream != null) { + inputStream.onCompleted(); } + } catch (Exception e) { + log.error("Exception during onCompleted", e); } - // Clear the references under the lock so that no send can start against a stream - // whose channel is shutting down - such a write leaks the compressed ByteBuf. - inputStream = null; - channelToShutdown = channel; - channel = null; - } finally { - connectionLock.unlock(); } - if (channelToShutdown != null) { - channelToShutdown.shutdown(); + if (channel != null) { + channel.shutdown(); int attempt = 0; do { try { - channelToShutdown.awaitTermination(timeoutSecs, TimeUnit.SECONDS); + channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { - channelToShutdown.shutdownNow(); + channel.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; - } while (!channelToShutdown.isTerminated()); + } while (!channel.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setUplinkMsg(msg) - .build()); + uplinkMsgLock.lock(); + try { + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(msg) + .build()); + } finally { + uplinkMsgLock.unlock(); + } } @Override public void sendSyncRequestMsg(boolean fullSyncRequired) { - SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() - .setFullSync(fullSyncRequired) - .build(); - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) - .setSyncRequestMsg(syncRequestMsg) - .build()); + uplinkMsgLock.lock(); + try { + SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() + .setFullSync(fullSyncRequired) + .build(); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) + .setSyncRequestMsg(syncRequestMsg) + .build()); + } finally { + uplinkMsgLock.unlock(); + } } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setDownlinkResponseMsg(downlinkResponseMsg) - .build()); - } - - private void sendRequestMsg(RequestMsg requestMsg) { - connectionLock.lock(); + uplinkMsgLock.lock(); try { - if (inputStream == null) { - throw new IllegalStateException("Edge is not connected to the cloud. The message is discarded!"); - } - inputStream.onNext(requestMsg); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setDownlinkResponseMsg(downlinkResponseMsg) + .build()); } finally { - connectionLock.unlock(); + uplinkMsgLock.unlock(); } } From 970d590a642ca5d14ab765085f44676f4b18f8b8 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 15:02:46 +0300 Subject: [PATCH 018/119] Serialize JS script release under evalLock and cover both Nashorn backends --- .../script/NashornJsInvokeServiceTest.java | 5 +- .../script/api/js/NashornJsInvokeService.java | 16 ++- .../NashornJsInvokeServiceLifecycleTest.java | 122 ++++++++++++++++++ 3 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index c76eac8c61..1b0ac652b0 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -231,12 +231,13 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { UUID scriptId = evalScript("return msg;"); String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); - assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("true"); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(true); invokeService.release(scriptId).get(); // the property must be deleted, not just set to undefined: an abandoned binding keeps - assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("false"); + // its slot in the Global's PropertyMap forever + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(false); } @Test diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index bb95c60481..32ab55f7ef 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -144,7 +144,8 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap // shape history forever. Declaring the function inside an IIFE and assigning it to a global // property keeps the property configurable, allowing doRelease() to actually delete it. - // The prefix stays on the first line so that script line numbers in errors are unchanged. + // The prefix stays on the first line to preserve line numbering on the raw engine path; + // the sandbox beautifier reformats the wrapper and shifts reported error lines anyway. String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { @@ -190,10 +191,15 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; - if (useJsSandbox) { - sandbox.eval(deleteScript); - } else { - engine.eval(deleteScript); + evalLock.lock(); + try { + if (useJsSandbox) { + sandbox.eval(deleteScript); + } else { + engine.eval(deleteScript); + } + } finally { + evalLock.unlock(); } } diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java new file mode 100644 index 0000000000..cdfd2d8e93 --- /dev/null +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -0,0 +1,122 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.script.api.js; + +import delight.nashornsandbox.NashornSandbox; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.script.api.ScriptType; +import org.thingsboard.script.api.TbScriptException; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.stats.StatsFactory; + +import javax.script.ScriptEngine; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +/** + * Covers the JS global scope lifecycle against both backends the service can be configured with. + * The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since + * {@code js.local.use_js_sandbox} defaults to true. + */ +class NashornJsInvokeServiceLifecycleTest { + + private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; + + private NashornJsInvokeService service; + private boolean useJsSandbox; + + @AfterEach + void tearDown() { + if (service != null) { + service.stop(); + } + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID scriptId = UUID.randomUUID(); + + JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); + assertThat(hasGlobalProperty(scriptInfo)).isTrue(); + assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); + + service.doRelease(scriptId); + + assertThat(hasGlobalProperty(scriptInfo)).isFalse(); + assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class); + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID releasedId = UUID.randomUUID(); + UUID retainedId = UUID.randomUUID(); + + JsScriptInfo released = eval(releasedId, "return {v: 1};"); + JsScriptInfo retained = eval(retainedId, "return {v: 2};"); + + service.doRelease(releasedId); + + assertThat(hasGlobalProperty(released)).isFalse(); + assertThat(hasGlobalProperty(retained)).isTrue(); + assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); + } + + private void givenService(boolean useJsSandbox) { + this.useJsSandbox = useJsSandbox; + service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); + ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); + ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); + ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); + ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); + ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); + ReflectionTestUtils.setField(service, "maxMemory", 104857600L); + service.init(); + } + + private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { + service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); + return service.scriptInfoMap.get(scriptId); + } + + private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { + return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); + } + + private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { + String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; + Object result = useJsSandbox + ? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) + : ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); + return Boolean.TRUE.equals(result); + } + +} From bd25bee271ecd9ba540022a4b840db1e0f3f059d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:42:54 +0300 Subject: [PATCH 019/119] give the validation a result type of its own validateSolution borrowed SolutionInstallResponse and used null to say that nothing conflicts, so the call site had to test two different ways of saying "go ahead". It returns a SolutionValidationResult now, built through passed() or conflictsFound(report) - the private constructor keeps the two states honest - and the install response is assembled where the install actually answers. --- .../solutions/DefaultSolutionService.java | 23 +++++--- .../data/SolutionValidationResult.java | 43 ++++++++++++++ .../solutions/DefaultSolutionServiceTest.java | 57 +++++++++---------- 3 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index b279d693ef..ad8c6a224b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -111,6 +111,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -257,9 +258,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -300,7 +301,7 @@ public class DefaultSolutionService implements SolutionService { } } - SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { //TODO: pre-validate what still only fails at provision time: customer users (unique by email), // alarm rules and calculated fields. @@ -338,7 +339,7 @@ public class DefaultSolutionService implements SolutionService { collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { - return null; + return SolutionValidationResult.passed(); } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); @@ -346,10 +347,14 @@ public class DefaultSolutionService implements SolutionService { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(details.toString()); - return solutionInstallResponse; + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; } /** diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..407290e487 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions.data; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index b1b5f1726a..860a6d3a0c 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -41,7 +41,7 @@ import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; -import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import java.io.IOException; import java.nio.file.Files; @@ -111,18 +111,17 @@ class DefaultSolutionServiceTest { .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.isSuccess()).isFalse(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported - assertThat(result.getDetails()) + assertThat(result.getConflictReport()) .doesNotContain("Customer $random") .doesNotContain("New device") .doesNotContain("New asset"); @@ -136,10 +135,10 @@ class DefaultSolutionServiceTest { dashboard.setTitle("Overview"); when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } @@ -153,10 +152,10 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } @@ -176,10 +175,10 @@ class DefaultSolutionServiceTest { when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()).containsSubsequence( + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( "- **Device profile**: 'thermostat'", "- **Asset profile**: 'building'", "- **Edge**: 'Main edge'"); @@ -191,9 +190,9 @@ class DefaultSolutionServiceTest { when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); } @@ -203,7 +202,7 @@ class DefaultSolutionServiceTest { "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(ruleChainService); } @@ -217,16 +216,16 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); } @Test void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { writeEntitiesFile("devices.json", "null"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(deviceService); } @@ -240,17 +239,17 @@ class DefaultSolutionServiceTest { names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) .thenReturn(existingDevice(name))); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); int hidden = conflictCount - LISTED_NAMES_PER_TYPE; String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); if (hidden > 0) { - assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); } else { - assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); } } @@ -267,9 +266,9 @@ class DefaultSolutionServiceTest { profile.setName("Sensor profile"); when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @@ -278,12 +277,12 @@ class DefaultSolutionServiceTest { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); } @Test void testValidateSolutionWithoutEntityFiles() { - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, deviceProfileService, assetProfileService, edgeService); } From 63387b45b0f61a2b49a91582c44e0ac51ef12f51 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:54:57 +0300 Subject: [PATCH 020/119] use the SPDX license header on the new file The base branch switched every header to the SPDX form while this branch was open, so the one file this branch adds was the only one left with the old block comment. --- .../data/SolutionValidationResult.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java index 407290e487..4b6b07c54b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.solutions.data; import lombok.AccessLevel; From 04feee5c87f0bfd9e032e20fe2fa21113f5876bb Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:07:24 +0300 Subject: [PATCH 021/119] use the SPDX license header on the new test class The base switched every header to the SPDX form yesterday, so the files this branch adds were the only ones left with the old block comment and license:check failed on them once the base was merged in. --- .../server/service/solutions/DefaultSolutionServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 860a6d3a0c..d34798fe14 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 /** * Copyright © 2016-2026 The Thingsboard Authors * From 5887f01bb362c104db086c5983a3ad5e72141b87 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:12:39 +0300 Subject: [PATCH 022/119] drop the old license block left under the SPDX header license:format prepends the header it expects without recognising the block comment the files were created with, so both new files carried the license twice. They now have only the two SPDX lines, the same as every other file that this repository shares with CE. --- .../solutions/DefaultSolutionServiceTest.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d34798fe14..d65868a7fb 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,20 +1,5 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; From 5595dde55e8b3fe76005b32c3ad21cf3474c0677 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Mon, 14 Sep 2026 19:05:49 +0300 Subject: [PATCH 023/119] feat(iot-hub): group the hero search popup, and give the search page filters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two surfaces, one defect between them: a query answered by several content types could not show all of them. **The hero popup** asked /api/versions/published for one flat page of ten rows by install count and grouped that page on the client. Ten rows cannot hold four of each of six item types, so whichever types filled the page took it and the rest had no section at all — and an absent section was indistinguishable from "no matches of this type". Measured against the catalogue, `temperature` returns 71 matches across five types; a flat top-16 by install count shows no calculated field and no alarm rule, and by relevance it shows none of the 22 devices. On `gateway` neither ordering surfaces one of the 12 matching widgets. It asks for a grouped answer now. The server caps each type and puts `typeTotal` on every row, so the client renders what it was given: one section per type, the header a link to that type page carrying the current query and, when more of that type exists, a "+N more ›" chip. Count and chevron appear together or not at all — on a section already showing everything a chevron points at nothing. The footer names where it goes rather than an ordering. **The search page** keeps its flat paginated grid — the site's equivalent is a browsable catalogue with indexed page URLs, so neither product groups there — and gains what it was missing beside the type pages: * A filter panel: item type, category, use case. Type is new, this being the one page that mixes them. There is no catalogue-wide filterInfo endpoint, so the six per-type answers are merged client-side. Counts are deliberately not rendered: filterInfo takes no text query, so beside a searched result they would be the whole catalogue's numbers describing a different answer. * A page size that follows the column count, read from a hidden probe carrying the grid's own classes rather than restated from its media queries: max(12, columns × 3). Fifteen at every width ended a page mid-row at four and six columns. * One card layout. Calculated fields, alarm rules and rule chains render as a compact horizontal row that needs a wide cell; the type pages narrow the grid for them, a mixed grid cannot, and those rows truncated their own titles. **Relevance** is a sort option on all four surfaces that carry a search field, and the default on each. With text it ranks the answer; without it the backend substitutes the install count, so browsing keeps the order it had. Nothing switches on the field state — a control that relabels itself unasked was tried and rejected. Also here: the search page moves onto the type pages' frame — one even padding on the card, the component full bleed — which removes four breakpoints' worth of negative margins, each written to cancel that padding for one element. --- .../dashboard-widget-select.component.ts | 12 + .../iot-hub/iot-hub-browse.component.ts | 16 ++ .../iot-hub/iot-hub-components.module.ts | 3 + .../iot-hub/iot-hub-facet-list.component.html | 31 ++ .../iot-hub/iot-hub-facet-list.component.scss | 92 ++++++ .../iot-hub/iot-hub-facet-list.component.ts | 83 ++++++ .../iot-hub/iot-hub-item-card.component.html | 4 +- .../iot-hub/iot-hub-item-card.component.ts | 13 + .../iot-hub/iot-hub-search.component.html | 120 +++++--- .../iot-hub/iot-hub-search.component.scss | 190 +++++++++--- .../iot-hub/iot-hub-search.component.ts | 270 ++++++++++++++---- .../iot-hub-creator-profile.component.html | 5 +- .../pages/iot-hub/iot-hub-home.component.html | 67 +++-- .../pages/iot-hub/iot-hub-home.component.scss | 35 +++ .../pages/iot-hub/iot-hub-home.component.ts | 46 ++- .../iot-hub-search-page.component.scss | 101 ++----- .../models/iot-hub/iot-hub-version.models.ts | 27 ++ .../assets/locale/locale.constant-en_US.json | 4 + 18 files changed, 884 insertions(+), 235 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index d93a1e504e..57c621eb8d 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -88,7 +88,19 @@ export class DashboardWidgetSelectComponent { includeDeprecated = false; searchFocused = false; + /** + * Relevance leads, and is therefore the default (iotHubSelectedSortIndex starts at 0). This + * panel has a search field, which is the only thing relevance ranks by; with the field empty + * the backend substitutes the install count, so the picker opens on the order it always had. + * + * scadaFirst is unaffected: the backend prepends it ahead of the caller's sort AND ahead of + * relevance, so a SCADA context still lists SCADA widgets first. + * + * Fourth copy of this list — the others are in TbIotHubSearchComponent, TbIotHubBrowseComponent + * and IOT_HUB_SORT_OPTIONS on thingsboard.io. Kept in step by hand. + */ iotHubSortOptions: WidgetSelectSortOption[] = [ + { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 11352f1d04..785bd48660 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -126,7 +126,17 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy activeHardwareTypes = new Set(); activeVendors = new Set(); + /** + * Relevance leads, and is therefore the default (selectedSortIndex starts at 0). A type page + * carries a search field, which is the only thing relevance ranks by; with the field empty the + * backend substitutes the install count, so browsing keeps the order it always had. + * + * Kept in step by hand with TbIotHubSearchComponent's list and with IOT_HUB_SORT_OPTIONS on + * thingsboard.io — three copies, because the two products share no code and this component + * predates the search page's list. + */ sortOptions: SortOption[] = [ + { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } @@ -176,6 +186,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (params['search']) { this.textSearch = params['search']; } + // A search section header on a creator profile lands here scoped to that creator. The + // bound input wins: an embedded host (the add-item dialog) sets its own scope, and must + // not pick one up from whatever URL happens to be open behind the dialog. + if (!this.creatorId && !this.embedded && params['creatorId']) { + this.creatorId = params['creatorId']; + } if (this.fixedSubType) { const subtypes = this.getActiveSubtypes(); if (subtypes) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index 53e2493651..00ce18b4c0 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -14,6 +14,7 @@ import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component'; import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component'; import { TbIotHubSearchComponent } from './iot-hub-search.component'; +import { TbIotHubFacetListComponent } from './iot-hub-facet-list.component'; import { TbIotHubInstalledItemsTableComponent } from './iot-hub-installed-items-table.component'; import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items-dialog.component'; import { TbPeConnectivityMethodPromptComponent } from './pe-connectivity-method-prompt.component'; @@ -36,6 +37,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbPeConnectivityMethodPromptComponent, @@ -64,6 +66,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbPeConnectivityMethodPromptComponent, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html new file mode 100644 index 0000000000..dfde943c22 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -0,0 +1,31 @@ + + + + {{ label | translate }} + + + @if (searchable) { +

+ } + +
+ @for (option of visibleOptions; track trackByKey($index, option)) { + + {{ labelFor(option.key) }} + + } +
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss new file mode 100644 index 0000000000..e5fc43f803 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +@import "./iot-hub-common"; + +// Values follow the type pages' filter panel so the two read as one control, minus its deep +// left indent: that indent exists because the panel there sits in a wider rail. +.tb-iot-hub-facet-panel.mat-expansion-panel { + box-shadow: none; + border-radius: 0; + background: transparent; + + // Indented from the column's edges, because the rules between facets are not: they span the + // whole column, as they do on the type pages. The host sets --tb-facet-indent to whatever + // puts this text on the page's own left margin. + .mat-expansion-panel-header { + padding: 8px 16px 8px var(--tb-facet-indent, 16px); + height: 48px; + min-height: 48px; + } + + ::ng-deep .mat-expansion-panel-header-title { + font-size: 14px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); + } + + ::ng-deep .mat-expansion-panel-body { + padding: 0 8px 8px var(--tb-facet-indent, 16px); + } + + mat-checkbox { + display: block; + overflow: hidden; + + &:hover { + background: rgba(0, 0, 0, 0.04); + } + } + + .tb-iot-hub-facet-items { + // Uncapped until the list is long enough to need it, so a three-option facet does not + // reserve a scroll area it never uses. + &.scrollable { + max-height: 280px; + overflow-y: auto; + } + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } + + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } + } + } + + .tb-iot-hub-facet-search { + @include tb-iot-hub-search-container; + margin: 4px 8px 8px 0; + + mat-icon { + @include tb-iot-hub-search-icon(rgba(0, 0, 0, 0.54)); + } + + input { + @include tb-iot-hub-search-input-text(0.2px); + } + + .tb-iot-hub-facet-search-clear.mat-mdc-icon-button { + @include tb-iot-hub-search-clear; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts new file mode 100644 index 0000000000..b9b5625fce --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { Component, EventEmitter, Input, Output } from '@angular/core'; +import { FilterParamInfo } from '@shared/models/iot-hub/iot-hub-item.models'; + +/** + * One checkbox facet of a filter panel: a title, the options with their item counts, and the + * set of keys currently selected. Presentational only - it owns no filter state and issues no + * request; the host decides what a toggle means. + * + * Written for the cross-type search page, which needs three plain facets (item type, category, + * use case). The type pages keep their own panel in TbIotHubBrowseComponent: theirs carries + * facets this one has no notion of - grouped connectivity, vendor lists, per-type subtypes - + * so folding the two together would mean parameterising that panel for a shape it never uses. + */ +@Component({ + selector: 'tb-iot-hub-facet-list', + standalone: false, + templateUrl: './iot-hub-facet-list.component.html', + styleUrls: ['./iot-hub-facet-list.component.scss'] +}) +export class TbIotHubFacetListComponent { + + /** Translation key for the facet's heading. */ + @Input() label: string; + + @Input() options: FilterParamInfo[] = []; + + /** Keys the host currently has selected. Read, never written. */ + @Input() selected = new Set(); + + /** + * Turns an option key into what the user reads. Defaults to the key, which is already the + * display value for categories and use cases; item types come through as enum names and need + * their translated plural. + */ + @Input() labelFor: (key: string) => string = (key) => key; + + /** + * Open on first render. The host decides: a short, always-relevant facet earns the space it + * takes, a long one costs the reader the facets below it — on the search page all three + * headings fit above the fold only because two of them start closed. + */ + @Input() expanded = true; + + @Output() toggled = new EventEmitter(); + + /** + * Above this many options the facet gets its own search box and a scroll cap. Matches the + * threshold the type pages' panel uses, so the two feel the same at the same list lengths. + */ + private static readonly SEARCH_THRESHOLD = 8; + + search = ''; + + get searchable(): boolean { + return this.options.length > TbIotHubFacetListComponent.SEARCH_THRESHOLD; + } + + get visibleOptions(): FilterParamInfo[] { + const needle = this.search.trim().toLowerCase(); + if (!needle) { + return this.options; + } + return this.options.filter(o => this.labelFor(o.key).toLowerCase().includes(needle)); + } + + get scrollable(): boolean { + return this.visibleOptions.length > TbIotHubFacetListComponent.SEARCH_THRESHOLD; + } + + isSelected(key: string): boolean { + return this.selected.has(key); + } + + onToggle(key: string): void { + this.toggled.emit(key); + } + + trackByKey(_index: number, option: FilterParamInfo): string { + return option.key; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html index cbde4bbf83..16bca59bf7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html @@ -78,7 +78,9 @@ } @else {
- {{ getPlaceholderIcon() }} + + {{ getPlaceholderIcon() }}
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index 22a4eaf323..f57582fb29 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -23,6 +23,16 @@ export class TbIotHubItemCardComponent { @Input() showTypeChip = true; @Input() showSubtype = false; @Input() mode: 'default' | 'add' = 'default'; + /** + * `auto` lets the item's type choose, which is what a single-type grid wants: calculated + * fields, alarm rules and rule chains have nothing to preview, so they get a compact row and + * the grid gives them wider cells. + * + * `preview` forces the tall card on every type. A grid that mixes types cannot widen its + * cells for some rows only, and a horizontal row squeezed into a cell sized for a preview + * truncates its own title and leaves the rest of the cell empty. + */ + @Input() layout: 'auto' | 'preview' = 'auto'; @Output() cardClick = new EventEmitter(); @Output() creatorClick = new EventEmitter(); @Output() installClick = new EventEmitter(); @@ -47,6 +57,9 @@ export class TbIotHubItemCardComponent { } isCompactLayout(): boolean { + if (this.layout === 'preview') { + return false; + } return this.item.type === ItemType.CALCULATED_FIELD || this.item.type === ItemType.ALARM_RULE || this.item.type === ItemType.RULE_CHAIN; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html index c737e1e96c..5963b7c003 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html @@ -4,14 +4,26 @@ SPDX-License-Identifier: Apache-2.0 --> -
+
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }}
- -
+ + + + +
+ @if (showFilters) { + + }
-
+
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }} @@ -76,7 +88,59 @@
-
+ + +
+ @if (activeFilterCount > 0) { + + } + + + @if (categoryOptions.length > 0) { + + + + } + @if (useCaseOptions.length > 0) { + + + } +
+
+ +
+ + +
+ @if (showFilters) { + + }
@@ -100,39 +164,27 @@
} - - @if (resultGroups.length > 0) { -
- @for (group of resultGroups; track group.type) { -
- - - -
- @for (item of group.items; track item.id) { - - - } -
-
+ + @if (results.length > 0) { +
+ @for (item of results; track item.id) { + + }
}
+
@if (isLoading) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 4b43ad5b3c..2556d03f3d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -8,6 +8,14 @@ flex-direction: column; } +// The page hands this component the card's full width and its own side padding as a variable. +// Rows that are ordinary content pad themselves back in; the divider and the filter rail are +// the two things that are supposed to reach the edge, so they do not. +.tb-search-pad { + padding-left: var(--tb-search-side-pad, 0px); + padding-right: var(--tb-search-side-pad, 0px); +} + .tb-search-results-count-mobile { display: none; margin-left: auto; @@ -143,49 +151,135 @@ overflow: auto; } -// Categories / sections -.tb-search-categories { +// Card grid +.tb-search-card-grid { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 20px; + + // Probe: zero-height element used only to read the computed column count. + // Keeps display: grid and non-zero width so grid-template-columns resolves. + &.tb-search-card-grid-probe { + width: 100%; + height: 0; + gap: 0; + overflow: hidden; + visibility: hidden; + pointer-events: none; + } +} + +// Filter button — the drawer's trigger, and where the active count is shown +.tb-search-filter-btn { + flex-shrink: 0; +} + +.tb-search-filter-count { + margin-left: 6px; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 9px; + background: rgba(0, 0, 0, 0.08); + font-size: 12px; + line-height: 18px; + font-variant-numeric: tabular-nums; +} + +// Content: facet sidebar beside the grid +// The page gives this component the viewport's remaining height and expects its body to scroll +// inside, not to grow past the white card. So the row takes that height and BOTH columns scroll +// themselves — the grid as it always did, the facets likewise. A facet list can then be any +// length at all without reaching the page behind it. +.tb-search-layout { display: flex; - flex-direction: column; - gap: 48px; + gap: 24px; + height: 100%; + min-height: 0; + + .tb-results-container { + flex: 1; + min-width: 0; + // Only on the right: the gap to the rail already separates it on the left. + padding-right: var(--tb-search-side-pad, 0px); + } } -// Section header -.tb-search-section-header { - font-size: 18px; - font-weight: 500; - line-height: 24px; - color: rgba(0, 0, 0, 0.87); - padding: 0; - margin-bottom: 12px; +.tb-search-facets-desktop { + width: 232px; + flex-shrink: 0; + border-right: 1px solid rgba(0, 0, 0, 0.12); + + // The component is already full-bleed, so this column starts at the card's edge with no + // margin of its own and every rule drawn across it reaches that edge. The indent goes INSIDE + // each facet — padding here would inset the rules too — and matches the page's own margin, so + // the words line up with the heading above them. + --tb-facet-indent: var(--tb-search-side-pad, 16px); + + align-self: stretch; + height: 100%; + overflow-y: auto; + padding-top: 20px; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } - mat-icon { - font-size: 24px; - width: 24px; - height: 24px; + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } } } -// Card grid -.tb-search-card-grid { - display: grid; - grid-template-columns: repeat(5, 1fr); - gap: 20px; +// The close button and heading belong to the narrow layout only. +.tb-search-facets-header { + display: none; + height: 48px; + font-size: 16px; + font-weight: 500; +} - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); +.tb-search-facets { + display: flex; + flex-direction: column; + padding-bottom: 24px; + + // The type pages put a rule between filter sections. No gap and no padding around it: the + // rule sits flush between two sections, edge to edge, rather than floating inside a gap. + tb-iot-hub-facet-list + tb-iot-hub-facet-list { + border-top: 1px solid rgba(0, 0, 0, 0.12); } } +.tb-search-facets-clear { + align-self: flex-start; + margin-left: calc(var(--tb-facet-indent, 16px) - 16px); +} + // Responsive @media #{$mat-gt-xxl} { .tb-search-card-grid { grid-template-columns: repeat(6, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(4, 1fr); - } } } @@ -193,9 +287,6 @@ .tb-search-card-grid { grid-template-columns: repeat(4, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); - } } } @@ -203,9 +294,6 @@ .tb-search-card-grid { grid-template-columns: repeat(3, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(2, 1fr); - } } } @@ -229,9 +317,6 @@ .tb-search-card-grid { grid-template-columns: repeat(2, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(1, 1fr); - } } } @@ -268,3 +353,38 @@ margin-left: 0; } } + +// The sidebar costs a whole card column, so below this width it stops being a column: the +// panel collapses, and the Filter button opens it as a block above the results. +@media #{$mat-lt-lg} { + .tb-search-layout { + flex-direction: column; + } + + .tb-search-facets-desktop { + display: none; + // As a block above the results it is ordinary content, not a rail, so it lines up with + // the rows above it rather than with the card's edge. + width: 100%; + height: auto; + max-height: 60vh; + border-right: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.12); + padding-right: 0; + + &.opened { + display: block; + } + } + + .tb-search-facets-header { + display: flex; + } +} + +// Wide enough for the sidebar, so the button that opens the block has nothing to open. +@media #{$mat-gt-md} { + .tb-search-filter-btn { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts index f915be77e1..6326a52010 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { forkJoin, Subject, Subscription } from 'rxjs'; @@ -8,27 +8,38 @@ import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { FilterParamInfo, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from './iot-hub-actions.service'; -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; -} - interface SortOption { value: string; label: string; direction: Direction; } -const TYPE_ORDER: ItemType[] = [ +/** Sort property served by relevance ranking. With no text the backend substitutes the + * install count, so it is a safe default in both states. */ +const RELEVANCE = 'relevance'; + +/** + * Item types the Type facet offers, in the order every other cross-type surface uses (the hero + * popup's sections, the site's). Fixed rather than sorted by count: the counts move with the + * catalogue and a facet whose options reshuffle under the pointer is hard to use. + */ +const FACET_ITEM_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; +/** + * Rows a page holds, as a multiple of the column count, so a page always ends on a complete row. + * The floor keeps a one- or two-column phone layout from falling to three cards a page. + */ +const ROWS_PER_PAGE = 3; +const MIN_PAGE_SIZE = 12; + @Component({ selector: 'tb-iot-hub-search', standalone: false, @@ -37,32 +48,64 @@ const TYPE_ORDER: ItemType[] = [ }) export class TbIotHubSearchComponent implements OnInit, OnDestroy { - readonly ItemType = ItemType; - @Input() searchText = ''; @Input() creatorId: string; @Input() showCreator = true; + /** + * Render the filter panel. The search page does; the creator profile does not - it is already + * scoped to one creator, and the site's profile has no panel either. + */ + @Input() showFilters = true; @Output() searchTextChange = new EventEmitter(); get searchPlaceholderKey(): string { return this.creatorId ? 'iot-hub.search-published-items' : 'iot-hub.search'; } - resultGroups: SearchResultGroup[] = []; + results: MpItemVersionView[] = []; totalElements = 0; isLoading = false; hasError = false; private retryTimer: any = null; - pageSize = 15; pageIndex = 0; - pageSizeOptions = [15, 30, 60]; + + /** + * Read from a hidden probe that carries the real grid's classes, not guessed from breakpoints: + * the grid's column count is a CSS fact, and duplicating its media queries in TypeScript is a + * second source of truth that drifts the first time someone edits the stylesheet. + */ + @ViewChild('cardGridProbe', { static: true }) cardGridProbe!: ElementRef; + cols = 5; + pageSize = MIN_PAGE_SIZE; + + get pageSizeOptions(): number[] { + const base = Math.max(MIN_PAGE_SIZE, this.cols * ROWS_PER_PAGE); + return [base, base * 2, base * 4]; + } + + /** Filter panel state. Empty sets mean "no filter", which is what the query object expects. */ + /** Narrow widths only: the facet panel is a block above the results, not a sidebar. */ + filtersOpen = false; + typeOptions: FilterParamInfo[] = []; + categoryOptions: FilterParamInfo[] = []; + useCaseOptions: FilterParamInfo[] = []; + activeTypes = new Set(); + activeCategories = new Set(); + activeUseCases = new Set(); sortOptions: SortOption[] = [ + { value: RELEVANCE, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } ]; + /** + * Relevance is the default in BOTH states, which is why nothing here switches on whether the + * search field has text. With text it ranks the answer; without it the backend substitutes the + * install count, so a user who never opens this menu sees the order they always saw while + * browsing and the best matches once they type. + */ selectedSortIndex = 0; installedWidgets: IotHubInstalledItem[] = []; @@ -83,6 +126,11 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { ) {} ngOnInit(): void { + this.measureCols(); + this.observeGridWidth(); + if (this.showFilters) { + this.loadFilterInfo(); + } this.loadInstalledItems(); this.searchSubscription = this.searchSubject.pipe( debounceTime(300), @@ -96,6 +144,148 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.searchSubscription?.unsubscribe(); + this.resizeSubscription?.unsubscribe(); + this.resizeObserver?.disconnect(); + } + + // Filters + + getTypeLabel = (key: string): string => { + const translationKey = itemTypeTranslations.get(key as ItemType); + return translationKey ? this.translate.instant(translationKey + '-plural') : key; + }; + + onTypeToggle(key: string): void { + this.toggle(this.activeTypes, key); + } + + onCategoryToggle(key: string): void { + this.toggle(this.activeCategories, key); + } + + onUseCaseToggle(key: string): void { + this.toggle(this.activeUseCases, key); + } + + get activeFilterCount(): number { + return this.activeTypes.size + this.activeCategories.size + this.activeUseCases.size; + } + + clearFilters(): void { + if (this.activeFilterCount === 0) { + return; + } + this.activeTypes.clear(); + this.activeCategories.clear(); + this.activeUseCases.clear(); + this.pageIndex = 0; + this.loadResults(); + } + + private toggle(set: Set, key: string): void { + if (set.has(key)) { + set.delete(key); + } else { + set.add(key); + } + this.pageIndex = 0; + this.loadResults(); + } + + /** + * There is no catalogue-wide filterInfo endpoint - it answers per item type - so the six + * answers are merged here, the way the site merges the same six at build time. Counts are + * deliberately not rendered: filterInfo takes no text query, so beside a searched result they + * would be the whole catalogue's numbers pretending to describe this answer. + */ + private loadFilterInfo(): void { + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin( + FACET_ITEM_TYPES.map(type => this.iotHubApiService.getFilterInfo(type, config)) + ).subscribe({ + next: infos => { + // Every item type is offered, not only the ones filterInfo reports facets for: the + // endpoint describes a type's categories and vendors, never how many items it has, and + // a type whose items carry no categories would vanish from its own facet. + this.typeOptions = FACET_ITEM_TYPES.map(type => ({ + key: type as string, + totalItems: 0, + totalInstallCount: 0 + })); + this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories)); + this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases)); + }, + // A facet panel that failed to load is an empty panel, never a broken page: the grid + // beside it answers the query perfectly well without it. + error: () => {} + }); + } + + private mergeFacet(lists: (FilterParamInfo[] | undefined)[]): FilterParamInfo[] { + const byKey = new Map(); + for (const list of lists) { + for (const option of list || []) { + const seen = byKey.get(option.key); + if (seen) { + seen.totalItems += option.totalItems; + seen.totalInstallCount += option.totalInstallCount; + } else { + byKey.set(option.key, { ...option }); + } + } + } + return [...byKey.values()] + .filter(o => o.totalItems > 0) + .sort((a, b) => a.key.localeCompare(b.key)); + } + + // Column count -> page size + + private resizeObserver?: ResizeObserver; + private resizeSubject = new Subject(); + private resizeSubscription?: Subscription; + + private observeGridWidth(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el || typeof ResizeObserver === 'undefined') { + return; + } + this.resizeSubscription = this.resizeSubject.pipe(debounceTime(150)).subscribe(() => { + const before = this.pageSizeOptions[0]; + this.measureCols(); + if (this.pageSizeOptions[0] === before) { + return; + } + // Keep the user roughly where they were in the list rather than on the same page number: + // page 4 of 12-card pages is a different place from page 4 of 18-card pages. + const firstItem = this.pageIndex * this.pageSize; + this.pageSize = this.pageSizeOptions[0]; + this.pageIndex = Math.floor(firstItem / this.pageSize); + this.loadResults(); + }); + this.resizeObserver = new ResizeObserver(() => this.resizeSubject.next()); + this.resizeObserver.observe(el); + } + + private measureCols(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el) { + return; + } + // Force layout so grid-template-columns resolves to pixel tracks rather than `repeat(...)`. + void el.offsetWidth; + const tracks = getComputedStyle(el).gridTemplateColumns; + if (!tracks || tracks === 'none') { + this.cols = 1; + } else if (tracks.startsWith('repeat(')) { + const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); + this.cols = match ? parseInt(match[1], 10) : 1; + } else { + this.cols = Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); + } + if (!this.pageSizeOptions.includes(this.pageSize)) { + this.pageSize = this.pageSizeOptions[0]; + } } onSearchInput(): void { @@ -159,33 +349,9 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { } // Type helpers - isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; - } - - getTypeLabel(type: ItemType): string { - const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; - } - - getTypeRoute(type: ItemType): string { - switch (type) { - case ItemType.WIDGET: return 'widgets'; - case ItemType.SOLUTION_TEMPLATE: return 'solution-templates'; - case ItemType.CALCULATED_FIELD: return 'calculated-fields'; - case ItemType.ALARM_RULE: return 'alarm-rules'; - case ItemType.RULE_CHAIN: return 'rule-chains'; - case ItemType.DEVICE: return 'devices'; - default: return 'widgets'; - } - } - navigateToType(type: ItemType): void { - const search = this.searchText?.trim() || undefined; - void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); - } + + // Installed items getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined { @@ -281,7 +447,7 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { error: () => { this.isLoading = false; this.hasError = true; - this.resultGroups = []; + this.results = []; this.totalElements = 0; } }); @@ -291,30 +457,22 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { const sort = this.sortOptions[this.selectedSortIndex]; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(this.pageSize, this.pageIndex, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink, { creatorId: this.creatorId || undefined }); + const query = new MpItemVersionQuery(pageLink, { + creatorId: this.creatorId || undefined, + // Empty sets are left off the query entirely - an empty array would narrow to nothing. + types: this.activeTypes.size ? [...this.activeTypes] : undefined, + categories: this.activeCategories.size ? [...this.activeCategories] : undefined, + useCases: this.activeUseCases.size ? [...this.activeUseCases] : undefined + }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true, ignoreErrors: true }); } private applyResults(data: MpItemVersionView[], totalElements: number): void { this.totalElements = totalElements; - this.resultGroups = this.groupResults(data); + this.results = data; this.isLoading = false; } - private groupResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return TYPE_ORDER - .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); - } private loadInstalledItems(): void { const config = { ignoreLoading: true }; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html index d91164a6c3..51d834e8ed 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html @@ -96,7 +96,10 @@
- + +

{{ 'iot-hub.published-items' | translate }} ({{ creator.publishedCount }})

diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index cf4007b511..995ee4395d 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -85,37 +85,54 @@ } @else { @for (group of searchResultGroups; track group.type) { - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} + + + {{ getSearchGroupLabel(group.type) }} + @if (group.remaining > 0) { + + {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} + chevron_right + + } + + + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }} +
+ } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} +
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - -
-
- } + + } +
} }
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index de032d8f1a..d8934e82ff 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -242,6 +242,41 @@ line-height: 20px; letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); + // The header spans the panel so the count can sit against the right edge. Material's own + // label span is only as wide as its text. + width: 100%; + } + } + + // Section header — the label IS the link into the type page: title left, how much is not shown + // plus a chevron right. There is deliberately no per-section "see all" row under the items; + // six of those on one panel is what this variant was chosen to avoid. + .tb-search-popup-group-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + width: 100%; + cursor: pointer; + outline: none; + } + + .tb-search-popup-group-more { + display: flex; + align-items: center; + gap: 2px; + flex-shrink: 0; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.25px; + color: $tb-primary-color; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index fffd19c021..b4ecd8ca98 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -35,6 +35,10 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; items: MpItemVersionView[]; + /** Rows of this type behind the answer, from the response's typeTotal. */ + total: number; + /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ + remaining: number; } const SEARCH_GROUP_ORDER: ItemType[] = [ @@ -42,6 +46,11 @@ const SEARCH_GROUP_ORDER: ItemType[] = [ ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; +/** Relevance ranking. Sent only while the field has text: with an empty field the backend + * substitutes the install count anyway, and this component knows the field state, so it sends + * the honest value rather than leaning on that safety net. */ +const RELEVANCE = 'relevance'; + @Component({ selector: 'tb-iot-hub-home', standalone: false, @@ -156,9 +165,16 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { distinctUntilChanged(), switchMap(text => { this.searchLoading = true; - const sortOrder: SortOrder = { property: 'totalInstallCount', direction: Direction.DESC }; - const pageLink = new PageLink(10, 0, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); + const trimmed = text.trim(); + // Two states, one panel: popularity answers "what is worth looking at" with an empty + // field, relevance answers "what did I ask for" once there is one. + const sortOrder: SortOrder = trimmed + ? { property: RELEVANCE, direction: Direction.DESC } + : { property: 'totalInstallCount', direction: Direction.DESC }; + // The server sizes a grouped answer itself - the top rows of every type, one screen - so + // this page size is ignored, and page must stay 0 (a non-zero page is a 400). + const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); + const query = new MpItemVersionQuery(pageLink, { grouped: true }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); }) ).subscribe(result => { @@ -237,6 +253,17 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { void this.router.navigate(['/iot-hub/search'], { queryParams: { search } }); } + /** + * The section header is the way into the rest of a type - the panel carries no per-section + * "see all" row, which would put six identical calls to action on one panel. The query goes + * with it, so the type page opens on the same search rather than on the whole type. + */ + navigateToSection(type: ItemType): void { + this.searchAutoTrigger?.closePanel(); + const search = this.searchText?.trim() || undefined; + void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); + } + isCompactType(type: ItemType): boolean { return type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE @@ -523,6 +550,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); } + /** + * Reads the sections the server built. It no longer decides membership - a grouped response + * arrives already capped at four per type - so all this does is put the types in the panel's + * fixed order and carry each one's typeTotal onto the header. + */ private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] { const groupMap = new Map(); for (const item of items) { @@ -538,6 +570,12 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } return SEARCH_GROUP_ORDER .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); + .map(type => { + const groupItems = groupMap.get(type); + // Every row of a type carries the same typeTotal. The fallback keeps a non-grouped + // response rendering correctly - which is what a stale backend would send. + const total = groupItems[0].typeTotal ?? groupItems.length; + return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; + }); } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss index 1e617fb1f3..b824aade8c 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss @@ -8,12 +8,18 @@ height: 100%; } +// Same frame as the type pages (iot-hub-items-page): one even padding on the card, the hero +// inside it, and the component below pulled out to the card's edges. It replaces four +// breakpoints' worth of hand-written negative margins — one per element that needed to reach +// an edge — and is why the filter rail, the heading and the grid now line up by construction. +.tb-search-page { + padding: 40px 40px 48px; +} // Back button .tb-search-back-btn { align-self: flex-start; - margin-top: 40px; - margin-left: 123px; + margin-left: -8px; } // Title @@ -30,100 +36,37 @@ color: rgba(0, 0, 0, 0.54); } +// Full bleed, and it pads its own rows back in through --tb-search-side-pad. The rail and the +// dividers are the parts that must reach the edge; everything else lines up with the hero. tb-iot-hub-search { flex: 1; min-height: 0; - padding-left: 123px; - padding-right: 123px; - - ::ng-deep { - .tb-search-divider { - margin-left: -123px; - margin-right: -123px; - } - - .tb-results-container { - padding-right: 123px; - padding-bottom: 40px; - margin-right: -123px; - } - } -} - -// Responsive -@media #{$mat-lt-xxl} { - .tb-search-back-btn { - margin-left: 40px; - } - - tb-iot-hub-search { - padding-left: 40px; - padding-right: 40px; - - ::ng-deep { - .tb-search-divider { - margin-left: -40px; - margin-right: -40px; - } - - .tb-results-container { - padding-right: 40px; - margin-right: -40px; - } - } - } + --tb-search-side-pad: 40px; + margin-left: -40px; + margin-right: -40px; } @media #{$mat-lt-lg} { - .tb-search-back-btn { - margin-top: 24px; - margin-left: 24px; + .tb-search-page { + padding: 24px 24px 32px; } tb-iot-hub-search { - padding-left: 24px; - padding-right: 24px; - - ::ng-deep { - .tb-search-divider { - margin-left: -24px; - margin-right: -24px; - } - - .tb-results-container { - padding-right: 24px; - padding-bottom: 24px; - margin-right: -24px; - } - } + --tb-search-side-pad: 24px; + margin-left: -24px; + margin-right: -24px; } } @media #{$mat-lt-sm} { .tb-search-page { + padding: 16px 16px 24px; gap: 16px; } - .tb-search-back-btn { - margin-top: 16px; - margin-left: 16px; - } - tb-iot-hub-search { - padding-left: 16px; - padding-right: 16px; - - ::ng-deep { - .tb-search-divider { - margin-left: -16px; - margin-right: -16px; - } - - .tb-results-container { - padding-right: 16px; - padding-bottom: 16px; - margin-right: -16px; - } - } + --tb-search-side-pad: 16px; + margin-left: -16px; + margin-right: -16px; } } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 349a4f62e8..b98fc30952 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -106,6 +106,12 @@ export interface MpItemVersionView { resources: MpItemVersionResource[]; relatedItems?: string[]; checksum?: string; + /** + * Rows of this item's type behind a grouped response. A flat read does not omit it — the + * column is projected as NULL and serialised, so the field arrives as `null` there. Read it + * with `??`, never with a truthiness test. + */ + typeTotal?: number | null; } // 404 body shapes returned by the public listing item-version endpoint @@ -118,7 +124,15 @@ export interface ListingItemVersionNotFound { } export interface MpItemVersionQueryOptions { + /** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */ type?: string; + /** + * Several item types at once, for a cross-type surface whose Type facet is multi-select. + * Emitted as a repeated `type` parameter, which is the shape the backend reads + * (`@RequestParam List type`). Kept separate from `type` rather than widening it, + * so a caller that means "exactly this type" cannot be handed an array by accident. + */ + types?: string[]; peOnly?: boolean; creatorId?: string; categories?: string[]; @@ -131,6 +145,13 @@ export interface MpItemVersionQueryOptions { connectivity?: string[]; vendors?: string[]; scadaFirst?: boolean; + /** + * Ask for the top four of each item type in one response instead of a flat page. + * Every row then carries `typeTotal`, the number of rows of its type behind the answer, + * which is what the section header's "+N more" counts. Grouped responses are one screen: + * the backend rejects a non-zero `page`. + */ + grouped?: boolean; } export class MpItemVersionQuery { @@ -142,6 +163,9 @@ export class MpItemVersionQuery { if (o.type) { query += `&type=${o.type}`; } + if (o.types?.length) { + query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); + } if (o.peOnly != null) { query += `&peOnly=${o.peOnly}`; } @@ -178,6 +202,9 @@ export class MpItemVersionQuery { if (o.scadaFirst != null) { query += `&scadaFirst=${o.scadaFirst}`; } + if (o.grouped != null) { + query += `&grouped=${o.grouped}`; + } return query; } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 98f59ec8a9..e19cb64cff 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3708,6 +3708,7 @@ "search": "Search...", "search-published-items": "Search published items...", "see-all-results": "See all results", + "see-results-for": "See results for \"{{ search }}\"", "no-search-results": "No results found for '{{ search }}'", "no-items-available": "No items available", "search-results": "Search results", @@ -3730,6 +3731,7 @@ "type": "Type", "items-per-page": "Items per page", "filter": "Filter", + "clear-filters": "Clear filters", "available": "Available", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", "items-page-desc-dashboards": "Explore dashboards to find pre-built visualization templates and interactive UI layouts you can deploy in minutes to bring your IoT data to life.", @@ -3774,9 +3776,11 @@ "search-alarm-rules": "Search alarm rules...", "search-rule-chains": "Search rule chains...", "search-devices": "Search devices...", + "sort-most-relevant": "Most relevant", "sort-most-installed": "Most installed", "sort-newest": "Newest", "sort-name": "Name (A-Z)", + "section-more": "{ count, plural, =1 {+1 more} other {+# more} }", "type-filter-label": "Type", "category": "Category", "use-case": "Use case", From bb43fffa04ab6f3d62101e260b02ad2e359910f3 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 12:45:34 +0300 Subject: [PATCH 024/119] fix(iot-hub): call the grouped versions endpoint The Hub answers a sectioned search at /api/versions/published/grouped rather than through a flag on the flat read. That endpoint takes the filters and a sort key only - it sizes its own answer - so the popup asks through its own API method and its own query string, and sends no page, page size or sort order. MpItemVersionGroupedView mirrors what comes back: the view plus typeTotal, always set, rather than the flat view with a nullable field and a comment about when it is null. MpItemVersionQueryOptions loses grouped with it. --- .../src/app/core/http/iot-hub-api.service.ts | 21 +++++++- .../pages/iot-hub/iot-hub-home.component.ts | 22 ++++----- .../models/iot-hub/iot-hub-version.models.ts | 49 +++++++++++++------ 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 33f19d285f..f4d87a5ce5 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,7 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -81,6 +81,25 @@ export class IotHubApiService { ); } + /** + * The sectioned answer: at most four rows of each item type, every row carrying the size of its + * section. Its own endpoint, which is why this is its own method - it takes no page, page size + * or sort direction, and sending them would be sending what the server does not read. + */ + public getPublishedVersionsGrouped(query: MpItemVersionQuery, + config?: IotHubRequestConfig): Observable> { + if (query.options.tbVersion == null) { + query.options.tbVersion = tbVersionToInt(env.tbVersion); + } + if (query.options.peOnly == null) { + query.options.peOnly = false; + } + return this.http.get>( + `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, + { params: this.buildParams(config) } + ); + } + public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index b4ecd8ca98..cf26d52bbe 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -9,7 +9,7 @@ import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -34,7 +34,7 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; - items: MpItemVersionView[]; + items: MpItemVersionGroupedView[]; /** Rows of this type behind the answer, from the response's typeTotal. */ total: number; /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ @@ -62,7 +62,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResults: MpItemVersionView[] = []; + searchResults: MpItemVersionGroupedView[] = []; searchResultGroups: SearchResultGroup[] = []; searchLoaded = false; searchLoading = false; @@ -171,11 +171,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { const sortOrder: SortOrder = trimmed ? { property: RELEVANCE, direction: Direction.DESC } : { property: 'totalInstallCount', direction: Direction.DESC }; - // The server sizes a grouped answer itself - the top rows of every type, one screen - so - // this page size is ignored, and page must stay 0 (a non-zero page is a 400). + // The grouped endpoint sizes its own answer, so the page size here is never sent. const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink, { grouped: true }); - return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); + const query = new MpItemVersionQuery(pageLink); + return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }); }) ).subscribe(result => { this.searchResults = result.data; @@ -555,8 +554,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { * arrives already capped at four per type - so all this does is put the types in the panel's * fixed order and carry each one's typeTotal onto the header. */ - private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); + private groupSearchResults(items: MpItemVersionGroupedView[]): SearchResultGroup[] { + const groupMap = new Map(); for (const item of items) { if (!SEARCH_GROUP_ORDER.includes(item.type)) { continue; @@ -572,8 +571,9 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { .filter(type => groupMap.has(type)) .map(type => { const groupItems = groupMap.get(type); - // Every row of a type carries the same typeTotal. The fallback keeps a non-grouped - // response rendering correctly - which is what a stale backend would send. + // Every row of a type carries the same typeTotal, so the first one answers for the + // section. The fallback covers a backend too old to have the grouped endpoint, whose + // rows arrive without it. const total = groupItems[0].typeTotal ?? groupItems.length; return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; }); diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index b98fc30952..4aaaeeaa62 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -106,12 +106,18 @@ export interface MpItemVersionView { resources: MpItemVersionResource[]; relatedItems?: string[]; checksum?: string; +} + +/** + * A row of a grouped search: the view plus the size of the section it belongs to. Its own type + * rather than a nullable field on the view, matching what the endpoint returns. + */ +export interface MpItemVersionGroupedView extends MpItemVersionView { /** - * Rows of this item's type behind a grouped response. A flat read does not omit it — the - * column is projected as NULL and serialised, so the field arrives as `null` there. Read it - * with `??`, never with a truthiness test. + * Rows of this row's item type behind the answer — what a "+N more" header subtracts the + * shown rows from. Always set: the grouped endpoint projects it for every row it returns. */ - typeTotal?: number | null; + typeTotal: number; } // 404 body shapes returned by the public listing item-version endpoint @@ -145,20 +151,36 @@ export interface MpItemVersionQueryOptions { connectivity?: string[]; vendors?: string[]; scadaFirst?: boolean; - /** - * Ask for the top four of each item type in one response instead of a flat page. - * Every row then carries `typeTotal`, the number of rows of its type behind the answer, - * which is what the section header's "+N more" counts. Grouped responses are one screen: - * the backend rejects a non-zero `page`. - */ - grouped?: boolean; } export class MpItemVersionQuery { constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {} + /** + * The grouped endpoint's query string: the filters, plus a sort key. It sizes its own answer, + * so it declares no page or page size, and each key's direction is fixed by its chain, so it + * declares no sort order either - sending any of the three would be sending something the + * server does not read. + */ + public toGroupedQuery(): string { + const text = this.pageLink.textSearch?.trim(); + let query = '?'; + if (text?.length) { + query += `textSearch=${encodeURIComponent(text)}&`; + } + if (this.pageLink.sortOrder) { + query += `sortProperty=${this.pageLink.sortOrder.property}&`; + } + return query + this.filtersToQuery(); + } + public toQuery(): string { - let query = this.pageLink.toQuery(); + return this.pageLink.toQuery() + this.filtersToQuery(); + } + + /** Every filter, as `&name=value` pairs - shared by both query strings above. */ + private filtersToQuery(): string { + let query = ''; const o = this.options; if (o.type) { query += `&type=${o.type}`; @@ -202,9 +224,6 @@ export class MpItemVersionQuery { if (o.scadaFirst != null) { query += `&scadaFirst=${o.scadaFirst}`; } - if (o.grouped != null) { - query += `&grouped=${o.grouped}`; - } return query; } } From 6eaf10dfd4572a6ec9e4fc3e9a6998b08e7c7b55 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:01:05 +0300 Subject: [PATCH 025/119] fix(iot-hub): keep the hero search alive when a request fails --- .../home/pages/iot-hub/iot-hub-home.component.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index cf26d52bbe..6108a9bd4e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -4,9 +4,10 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/co import { Router } from '@angular/router'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; import { BreakpointObserver } from '@angular/cdk/layout'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; +import { emptyPageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -174,7 +175,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { // The grouped endpoint sizes its own answer, so the page size here is never sent. const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); const query = new MpItemVersionQuery(pageLink); - return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }); + // A failed request must not end the subscription: the interceptor reports it, and the + // panel goes back to an empty answer the next keystroke can replace. + return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( + catchError(() => of(emptyPageData())) + ); }) ).subscribe(result => { this.searchResults = result.data; @@ -572,9 +577,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { .map(type => { const groupItems = groupMap.get(type); // Every row of a type carries the same typeTotal, so the first one answers for the - // section. The fallback covers a backend too old to have the grouped endpoint, whose - // rows arrive without it. - const total = groupItems[0].typeTotal ?? groupItems.length; + // section. + const total = groupItems[0].typeTotal; return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; }); } From 09dbf7b0c06e40c5d16e1e3f7568b6cb1cd3d4a3 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:20:56 +0300 Subject: [PATCH 026/119] refactor(iot-hub): read the hero popup's sections as sections --- .../src/app/core/http/iot-hub-api.service.ts | 13 ++--- .../pages/iot-hub/iot-hub-home.component.html | 2 +- .../pages/iot-hub/iot-hub-home.component.ts | 51 +++++++------------ .../models/iot-hub/iot-hub-version.models.ts | 15 +++--- 4 files changed, 34 insertions(+), 47 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index f4d87a5ce5..987f9f214b 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,7 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -82,19 +82,20 @@ export class IotHubApiService { } /** - * The sectioned answer: at most four rows of each item type, every row carrying the size of its - * section. Its own endpoint, which is why this is its own method - it takes no page, page size - * or sort direction, and sending them would be sending what the server does not read. + * The sectioned answer: one section per item type, in the server's order, each holding at most + * four rows and the total behind them. Its own endpoint, which is why this is its own method - + * it takes no page, page size or sort direction, and sending them would be sending what the + * server does not read. */ public getPublishedVersionsGrouped(query: MpItemVersionQuery, - config?: IotHubRequestConfig): Observable> { + config?: IotHubRequestConfig): Observable { if (query.options.tbVersion == null) { query.options.tbVersion = tbVersionToInt(env.tbVersion); } if (query.options.peOnly == null) { query.options.peOnly = false; } - return this.http.get>( + return this.http.get( `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, { params: this.buildParams(config) } ); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 995ee4395d..07905a8d21 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -72,7 +72,7 @@ - } @else if (searchResults.length === 0 && searchLoaded) { + } @else if (searchResultGroups.length === 0 && searchLoaded) {
search_off diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 6108a9bd4e..47c1ca06e1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -7,10 +7,9 @@ import { BreakpointObserver } from '@angular/cdk/layout'; import { forkJoin, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; -import { emptyPageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -35,14 +34,16 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; - items: MpItemVersionGroupedView[]; - /** Rows of this type behind the answer, from the response's typeTotal. */ + items: MpItemVersionView[]; + /** Rows of this type behind the answer, from the section's total. */ total: number; /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ remaining: number; } -const SEARCH_GROUP_ORDER: ItemType[] = [ +/** The types this popup lays out. A section of anything else is dropped rather than rendered + * without a label - the platform publishes no dashboards. Order comes from the server. */ +const SEARCH_GROUP_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; @@ -63,7 +64,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResults: MpItemVersionGroupedView[] = []; searchResultGroups: SearchResultGroup[] = []; searchLoaded = false; searchLoading = false; @@ -178,12 +178,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( - catchError(() => of(emptyPageData())) + catchError(() => of([] as MpItemVersionSection[])) ); }) - ).subscribe(result => { - this.searchResults = result.data; - this.searchResultGroups = this.groupSearchResults(result.data); + ).subscribe(sections => { + this.searchResultGroups = this.toResultGroups(sections); this.searchLoaded = true; this.searchLoading = false; }); @@ -559,27 +558,15 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { * arrives already capped at four per type - so all this does is put the types in the panel's * fixed order and carry each one's typeTotal onto the header. */ - private groupSearchResults(items: MpItemVersionGroupedView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - if (!SEARCH_GROUP_ORDER.includes(item.type)) { - continue; - } - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return SEARCH_GROUP_ORDER - .filter(type => groupMap.has(type)) - .map(type => { - const groupItems = groupMap.get(type); - // Every row of a type carries the same typeTotal, so the first one answers for the - // section. - const total = groupItems[0].typeTotal; - return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; - }); + private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { + return sections + .filter(section => SEARCH_GROUP_TYPES.includes(section.itemType)) + .map(section => ({ + type: section.itemType, + items: section.items, + total: section.total, + remaining: Math.max(0, section.total - section.items.length) + })); } + } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 4aaaeeaa62..4c1f79718b 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -109,15 +109,14 @@ export interface MpItemVersionView { } /** - * A row of a grouped search: the view plus the size of the section it belongs to. Its own type - * rather than a nullable field on the view, matching what the endpoint returns. + * One item type's share of a grouped search: the rows to show and how many exist behind them. + * A grouped answer is a list of these, in the server's section order, and a type nothing matched + * has no section — so a "+N more" header is `total - items.length`. */ -export interface MpItemVersionGroupedView extends MpItemVersionView { - /** - * Rows of this row's item type behind the answer — what a "+N more" header subtracts the - * shown rows from. Always set: the grouped endpoint projects it for every row it returns. - */ - typeTotal: number; +export interface MpItemVersionSection { + itemType: ItemType; + total: number; + items: MpItemVersionView[]; } // 404 body shapes returned by the public listing item-version endpoint From 19cbfc403a7da9076a7250ce8ffcdae728914da9 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:44:36 +0300 Subject: [PATCH 027/119] fix(iot-hub): keep the grouped query string well-formed without text --- .../shared/models/iot-hub/iot-hub-version.models.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 4c1f79718b..c48a232098 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -163,14 +163,16 @@ export class MpItemVersionQuery { */ public toGroupedQuery(): string { const text = this.pageLink.textSearch?.trim(); - let query = '?'; + const parts: string[] = []; if (text?.length) { - query += `textSearch=${encodeURIComponent(text)}&`; + parts.push(`textSearch=${encodeURIComponent(text)}`); } if (this.pageLink.sortOrder) { - query += `sortProperty=${this.pageLink.sortOrder.property}&`; + parts.push(`sortProperty=${this.pageLink.sortOrder.property}`); } - return query + this.filtersToQuery(); + // filtersToQuery() emits leading ampersands, which is what toQuery() needs after a page link; + // here they may be the whole query string, so the first one is dropped. + return `?${`${parts.join('&')}${this.filtersToQuery()}`.replace(/^&/, '')}`; } public toQuery(): string { From 3af7b71740c6a3541a584b568247ee09c3b1c6ac Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 14:00:41 +0300 Subject: [PATCH 028/119] refactor(iot-hub): give the grouped read its own query, without a page link --- .../src/app/core/http/iot-hub-api.service.ts | 39 +++-- .../pages/iot-hub/iot-hub-home.component.ts | 15 +- .../models/iot-hub/iot-hub-version.models.ts | 137 +++++++++--------- 3 files changed, 104 insertions(+), 87 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 987f9f214b..25c6253bae 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,13 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { + MpItemVersionGroupedQuery, + MpItemVersionQuery, + MpItemVersionQueryOptions, + MpItemVersionSection, + MpItemVersionView +} from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -69,12 +75,7 @@ export class IotHubApiService { } public getPublishedVersions(query: MpItemVersionQuery, config?: IotHubRequestConfig): Observable> { - if (query.options.tbVersion == null) { - query.options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (query.options.peOnly == null) { - query.options.peOnly = false; - } + this.applyPlatformFilters(query.options); return this.http.get>( `${this.baseUrl}/api/versions/published${query.toQuery()}`, { params: this.buildParams(config) } @@ -87,20 +88,28 @@ export class IotHubApiService { * it takes no page, page size or sort direction, and sending them would be sending what the * server does not read. */ - public getPublishedVersionsGrouped(query: MpItemVersionQuery, + public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, config?: IotHubRequestConfig): Observable { - if (query.options.tbVersion == null) { - query.options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (query.options.peOnly == null) { - query.options.peOnly = false; - } + this.applyPlatformFilters(query.options); return this.http.get( - `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, + `${this.baseUrl}/api/versions/published/grouped${query.toQuery()}`, { params: this.buildParams(config) } ); } + /** + * What this platform can install, filled in for a caller that did not say: items built for a + * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. + */ + private applyPlatformFilters(options: MpItemVersionQueryOptions): void { + if (options.tbVersion == null) { + options.tbVersion = tbVersionToInt(env.tbVersion); + } + if (options.peOnly == null) { + options.peOnly = false; + } + } + public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 47c1ca06e1..f36a8738a1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -9,7 +9,12 @@ import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/ import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { + MpItemVersionGroupedQuery, + MpItemVersionQuery, + MpItemVersionSection, + MpItemVersionView +} from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -169,12 +174,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { const trimmed = text.trim(); // Two states, one panel: popularity answers "what is worth looking at" with an empty // field, relevance answers "what did I ask for" once there is one. - const sortOrder: SortOrder = trimmed - ? { property: RELEVANCE, direction: Direction.DESC } - : { property: 'totalInstallCount', direction: Direction.DESC }; - // The grouped endpoint sizes its own answer, so the page size here is never sent. - const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); + const sortProperty = trimmed ? RELEVANCE : 'totalInstallCount'; + const query = new MpItemVersionGroupedQuery({}, trimmed, sortProperty); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index c48a232098..b194ab0371 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -152,79 +152,86 @@ export interface MpItemVersionQueryOptions { scadaFirst?: boolean; } +/** Every filter, as `&name=value` pairs - shared by both query shapes below. */ +function filtersToQuery(o: MpItemVersionQueryOptions): string { + let query = ''; + if (o.type) { + query += `&type=${o.type}`; + } + if (o.types?.length) { + query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); + } + if (o.peOnly != null) { + query += `&peOnly=${o.peOnly}`; + } + if (o.creatorId) { + query += `&creatorId=${o.creatorId}`; + } + if (o.categories?.length) { + query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); + } + if (o.useCases?.length) { + query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); + } + if (o.cfTypes?.length) { + query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.widgetTypes?.length) { + query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.ruleChainTypes?.length) { + query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.tbVersion != null) { + query += `&tbVersion=${o.tbVersion}`; + } + if (o.hardwareTypes?.length) { + query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); + } + if (o.connectivity?.length) { + query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); + } + if (o.vendors?.length) { + query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); + } + if (o.scadaFirst != null) { + query += `&scadaFirst=${o.scadaFirst}`; + } + return query; +} + +/** A paged read: the filters, and the page to cut out of them. */ export class MpItemVersionQuery { constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {} - /** - * The grouped endpoint's query string: the filters, plus a sort key. It sizes its own answer, - * so it declares no page or page size, and each key's direction is fixed by its chain, so it - * declares no sort order either - sending any of the three would be sending something the - * server does not read. - */ - public toGroupedQuery(): string { - const text = this.pageLink.textSearch?.trim(); + public toQuery(): string { + return this.pageLink.toQuery() + filtersToQuery(this.options); + } +} + +/** + * A sectioned read: the filters, what to search for, and which key orders a section. + * + * No `PageLink`, because the grouped endpoint takes no page and no page size - it sizes its own + * answer from the section limit - and no sort direction either, each key's direction being fixed + * by the chain the server switches on. A page link here could only carry values nobody sends. + */ +export class MpItemVersionGroupedQuery { + constructor(public options: MpItemVersionQueryOptions = {}, + public textSearch?: string, + public sortProperty?: string) {} + + public toQuery(): string { const parts: string[] = []; + const text = this.textSearch?.trim(); if (text?.length) { parts.push(`textSearch=${encodeURIComponent(text)}`); } - if (this.pageLink.sortOrder) { - parts.push(`sortProperty=${this.pageLink.sortOrder.property}`); + if (this.sortProperty) { + parts.push(`sortProperty=${this.sortProperty}`); } - // filtersToQuery() emits leading ampersands, which is what toQuery() needs after a page link; + // filtersToQuery() emits leading ampersands, which is what a page link needs in front of it; // here they may be the whole query string, so the first one is dropped. - return `?${`${parts.join('&')}${this.filtersToQuery()}`.replace(/^&/, '')}`; - } - - public toQuery(): string { - return this.pageLink.toQuery() + this.filtersToQuery(); - } - - /** Every filter, as `&name=value` pairs - shared by both query strings above. */ - private filtersToQuery(): string { - let query = ''; - const o = this.options; - if (o.type) { - query += `&type=${o.type}`; - } - if (o.types?.length) { - query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); - } - if (o.peOnly != null) { - query += `&peOnly=${o.peOnly}`; - } - if (o.creatorId) { - query += `&creatorId=${o.creatorId}`; - } - if (o.categories?.length) { - query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); - } - if (o.useCases?.length) { - query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); - } - if (o.cfTypes?.length) { - query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.widgetTypes?.length) { - query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.ruleChainTypes?.length) { - query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.tbVersion != null) { - query += `&tbVersion=${o.tbVersion}`; - } - if (o.hardwareTypes?.length) { - query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); - } - if (o.connectivity?.length) { - query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); - } - if (o.vendors?.length) { - query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); - } - if (o.scadaFirst != null) { - query += `&scadaFirst=${o.scadaFirst}`; - } - return query; + return `?${`${parts.join('&')}${filtersToQuery(this.options)}`.replace(/^&/, '')}`; } } From 26aad8e47500093f841cfd3d824a99dd955ec568 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 16:31:42 +0300 Subject: [PATCH 029/119] docs(iot-hub): say what the section mapper does now --- .../app/modules/home/pages/iot-hub/iot-hub-home.component.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index f36a8738a1..ebd8485dd7 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -555,9 +555,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } /** - * Reads the sections the server built. It no longer decides membership - a grouped response - * arrives already capped at four per type - so all this does is put the types in the panel's - * fixed order and carry each one's typeTotal onto the header. + * Reads the sections the server built: they arrive capped and in the order to render them, so + * this only drops the types this panel has no layout for and works out each header's "+N more". */ private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { return sections From e5a4a7e48920f32a046755df2794060157f3cc3a Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:26:27 +0300 Subject: [PATCH 030/119] refactor(iot-hub): one sort menu and one cross-type list, and two failures the panels now survive The sort options lived in three arrays behind three identical local interfaces, and 'relevance' was spelled four ways; the six cross-type item types lived in two more arrays, byte-identical and renamed by this branch on both sides. Adding one option here meant editing three places, and a seventh item type would have needed two. All of it moves to iot-hub-item.models.ts as SortOption, IOT_HUB_SORT_OPTIONS, RELEVANCE_SORT_PROPERTY and CROSS_TYPE_ITEM_TYPES. The type list stays separate from CREATOR_VISIBLE_ITEM_TYPES, which holds the same six: that one is a membership test carrying the type tabs' order, this one is display order with DEVICE leading, and folding them together would have silently reordered the Type facet. The hero popup now sends relevance in both states like every other surface, rather than switching on whether the field has text. Both spellings ask the server for the same rows - with no text it substitutes the install count either way - so this is the code agreeing with the decision recorded on TBIOH-33, not a behaviour change. Two failures that were not survivable: - One of the six getFilterInfo calls failing emptied the whole filter panel. forkJoin is all-or-nothing, so typeOptions went unassigned although it needs no server data, and the i?.categories guards below could never fire. Each request now carries its own catchError, which is what those guards already expected. - A section arriving without items would have thrown inside a subscribe callback, out of reach of the catchError upstream, leaving the popup on its spinner. The response is an unvalidated cast of a new endpoint, so items is defaulted. The facet list held a Set the host mutated in place, which works only while that component is on default change detection. The host now hands over a new Set per toggle. SearchResultGroup.total went unread, and @for takes a track expression rather than a TrackByFunction. --- .../src/app/core/http/iot-hub-api.service.ts | 7 +- .../dashboard-widget-select.component.ts | 31 ++--- .../iot-hub/iot-hub-browse.component.ts | 31 ++--- .../iot-hub/iot-hub-facet-list.component.html | 2 +- .../iot-hub/iot-hub-facet-list.component.ts | 7 +- .../iot-hub/iot-hub-search.component.ts | 106 ++++++++---------- .../pages/iot-hub/iot-hub-home.component.ts | 55 +++++---- .../models/iot-hub/iot-hub-item.models.ts | 44 ++++++++ 8 files changed, 139 insertions(+), 144 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 25c6253bae..7f3b299962 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -83,10 +83,9 @@ export class IotHubApiService { } /** - * The sectioned answer: one section per item type, in the server's order, each holding at most - * four rows and the total behind them. Its own endpoint, which is why this is its own method - - * it takes no page, page size or sort direction, and sending them would be sending what the - * server does not read. + * The sectioned answer: one section per item type, in the server's order, each capped by the + * server and carrying the total behind that cap. Its own endpoint, which takes no page, page + * size or sort direction. */ public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, config?: IotHubRequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index 57c621eb8d..7cb0eddd2b 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -21,7 +21,12 @@ import { ItemSizeStrategy } from '@shared/components/grid/scroll-grid.component' import { coerceBoolean } from '@shared/decorators/coercion'; import { TranslateService } from '@ngx-translate/core'; import { MpItemVersionQuery, MpItemVersionView, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + WidgetCategory +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; @@ -38,12 +43,6 @@ type selectWidgetMode = 'installed' | 'iotHub'; type installedSubMode = 'default' | 'allWidgets'; type iotHubSubMode = 'default' | 'allWidgets' | 'installed' | 'category'; -interface WidgetSelectSortOption { - value: string; - label: string; - direction: Direction; -} - const LOGICAL_ALL_WIDGETS = '__logical_all_widgets__'; const LOGICAL_INSTALLED_FROM_IOT_HUB = '__logical_installed_from_iot_hub__'; @@ -89,22 +88,10 @@ export class DashboardWidgetSelectComponent { searchFocused = false; /** - * Relevance leads, and is therefore the default (iotHubSelectedSortIndex starts at 0). This - * panel has a search field, which is the only thing relevance ranks by; with the field empty - * the backend substitutes the install count, so the picker opens on the order it always had. - * - * scadaFirst is unaffected: the backend prepends it ahead of the caller's sort AND ahead of - * relevance, so a SCADA context still lists SCADA widgets first. - * - * Fourth copy of this list — the others are in TbIotHubSearchComponent, TbIotHubBrowseComponent - * and IOT_HUB_SORT_OPTIONS on thingsboard.io. Kept in step by hand. + * scadaFirst is unaffected by the sort: the backend prepends it ahead of the caller's key AND + * ahead of relevance, so a SCADA context still lists SCADA widgets first. */ - iotHubSortOptions: WidgetSelectSortOption[] = [ - { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + readonly iotHubSortOptions = IOT_HUB_SORT_OPTIONS; iotHubSelectedSortIndex = 0; @Input() diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 785bd48660..63f561ddad 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -4,10 +4,15 @@ import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnDe import { Subject } from 'rxjs'; import { debounceTime, takeUntil } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { PageData } from '@shared/models/page/page-data'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, CREATOR_VISIBLE_ITEM_TYPES } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CREATOR_VISIBLE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType +} from '@shared/models/iot-hub/iot-hub-item.models'; import { widgetTypeTranslations, cfTypeTranslations, ruleChainTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; import { IotHubInstalledItem, DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -16,12 +21,6 @@ import { ActivatedRoute, Router } from '@angular/router'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils'; -interface SortOption { - value: string; - label: string; - direction: Direction; -} - @Component({ selector: 'tb-iot-hub-browse', standalone: false, @@ -126,21 +125,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy activeHardwareTypes = new Set(); activeVendors = new Set(); - /** - * Relevance leads, and is therefore the default (selectedSortIndex starts at 0). A type page - * carries a search field, which is the only thing relevance ranks by; with the field empty the - * backend substitutes the install count, so browsing keeps the order it always had. - * - * Kept in step by hand with TbIotHubSearchComponent's list and with IOT_HUB_SORT_OPTIONS on - * thingsboard.io — three copies, because the two products share no code and this component - * predates the search page's list. - */ - sortOptions: SortOption[] = [ - { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + readonly sortOptions = IOT_HUB_SORT_OPTIONS; typeTabs: { type: ItemType; label: string }[] = CREATOR_VISIBLE_ITEM_TYPES.map(t => ({ type: t, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html index dfde943c22..8468ddc04b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -22,7 +22,7 @@ }
- @for (option of visibleOptions; track trackByKey($index, option)) { + @for (option of visibleOptions; track option.key) { {{ labelFor(option.key) }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts index b9b5625fce..7bcafacccc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts @@ -26,7 +26,8 @@ export class TbIotHubFacetListComponent { @Input() options: FilterParamInfo[] = []; - /** Keys the host currently has selected. Read, never written. */ + /** Keys the host currently has selected. Read, never written - the host hands over a new Set + * on every toggle rather than mutating this one. */ @Input() selected = new Set(); /** @@ -76,8 +77,4 @@ export class TbIotHubFacetListComponent { onToggle(key: string): void { this.toggled.emit(key); } - - trackByKey(_index: number, option: FilterParamInfo): string { - return option.key; - } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts index 6326a52010..7378d45d60 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts @@ -3,36 +3,22 @@ import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { FilterParamInfo, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CROSS_TYPE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + itemTypeTranslations +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from './iot-hub-actions.service'; -interface SortOption { - value: string; - label: string; - direction: Direction; -} - -/** Sort property served by relevance ranking. With no text the backend substitutes the - * install count, so it is a safe default in both states. */ -const RELEVANCE = 'relevance'; - -/** - * Item types the Type facet offers, in the order every other cross-type surface uses (the hero - * popup's sections, the site's). Fixed rather than sorted by count: the counts move with the - * catalogue and a facet whose options reshuffle under the pointer is hard to use. - */ -const FACET_ITEM_TYPES: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; - /** * Rows a page holds, as a multiple of the column count, so a page always ends on a complete row. * The floor keeps a one- or two-column phone layout from falling to three cards a page. @@ -84,7 +70,8 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { return [base, base * 2, base * 4]; } - /** Filter panel state. Empty sets mean "no filter", which is what the query object expects. */ + // Filter panel state. Empty sets mean "no filter", which is what the query object expects. + /** Narrow widths only: the facet panel is a block above the results, not a sidebar. */ filtersOpen = false; typeOptions: FilterParamInfo[] = []; @@ -94,18 +81,7 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { activeCategories = new Set(); activeUseCases = new Set(); - sortOptions: SortOption[] = [ - { value: RELEVANCE, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; - /** - * Relevance is the default in BOTH states, which is why nothing here switches on whether the - * search field has text. With text it ranks the answer; without it the backend substitutes the - * install count, so a user who never opens this menu sees the order they always saw while - * browsing and the best matches once they type. - */ + readonly sortOptions = IOT_HUB_SORT_OPTIONS; selectedSortIndex = 0; installedWidgets: IotHubInstalledItem[] = []; @@ -156,15 +132,18 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { }; onTypeToggle(key: string): void { - this.toggle(this.activeTypes, key); + this.activeTypes = this.toggled(this.activeTypes, key); + this.reloadFromFirstPage(); } onCategoryToggle(key: string): void { - this.toggle(this.activeCategories, key); + this.activeCategories = this.toggled(this.activeCategories, key); + this.reloadFromFirstPage(); } onUseCaseToggle(key: string): void { - this.toggle(this.activeUseCases, key); + this.activeUseCases = this.toggled(this.activeUseCases, key); + this.reloadFromFirstPage(); } get activeFilterCount(): number { @@ -175,19 +154,26 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { if (this.activeFilterCount === 0) { return; } - this.activeTypes.clear(); - this.activeCategories.clear(); - this.activeUseCases.clear(); - this.pageIndex = 0; - this.loadResults(); + this.activeTypes = new Set(); + this.activeCategories = new Set(); + this.activeUseCases = new Set(); + this.reloadFromFirstPage(); } - private toggle(set: Set, key: string): void { - if (set.has(key)) { - set.delete(key); - } else { - set.add(key); + /** + * Returns a new Set rather than mutating the one passed in: TbIotHubFacetListComponent holds + * this very instance as an @Input, and a mutation it cannot see is a trap for the first person + * to put that component on OnPush. + */ + private toggled(set: Set, key: string): Set { + const next = new Set(set); + if (!next.delete(key)) { + next.add(key); } + return next; + } + + private reloadFromFirstPage(): void { this.pageIndex = 0; this.loadResults(); } @@ -197,27 +183,30 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { * answers are merged here, the way the site merges the same six at build time. Counts are * deliberately not rendered: filterInfo takes no text query, so beside a searched result they * would be the whole catalogue's numbers pretending to describe this answer. + * + * Each request carries its own catchError so one type's failure costs that type's categories + * and use cases, not the panel: a bare forkJoin is all-or-nothing, and the Type facet needs no + * server data at all. */ private loadFilterInfo(): void { const config = { ignoreLoading: true, ignoreErrors: true }; forkJoin( - FACET_ITEM_TYPES.map(type => this.iotHubApiService.getFilterInfo(type, config)) + CROSS_TYPE_ITEM_TYPES.map(type => + this.iotHubApiService.getFilterInfo(type, config).pipe(catchError(() => of(null))) + ) ).subscribe({ next: infos => { // Every item type is offered, not only the ones filterInfo reports facets for: the // endpoint describes a type's categories and vendors, never how many items it has, and // a type whose items carry no categories would vanish from its own facet. - this.typeOptions = FACET_ITEM_TYPES.map(type => ({ + this.typeOptions = CROSS_TYPE_ITEM_TYPES.map(type => ({ key: type as string, totalItems: 0, totalInstallCount: 0 })); this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories)); this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases)); - }, - // A facet panel that failed to load is an empty panel, never a broken page: the grid - // beside it answers the query perfectly well without it. - error: () => {} + } }); } @@ -348,11 +337,6 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { this.loadResults(); } - // Type helpers - - - - // Installed items getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined { switch (item.type) { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index ebd8485dd7..577ed03a08 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -15,7 +15,13 @@ import { MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CROSS_TYPE_ITEM_TYPES, + getItemTypeIcon, + ItemType, + itemTypeTranslations, + RELEVANCE_SORT_PROPERTY +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; @@ -40,24 +46,10 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; items: MpItemVersionView[]; - /** Rows of this type behind the answer, from the section's total. */ - total: number; - /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ + /** How many rows of this type the header offers beyond the ones shown. Zero renders no "+N more". */ remaining: number; } -/** The types this popup lays out. A section of anything else is dropped rather than rendered - * without a label - the platform publishes no dashboards. Order comes from the server. */ -const SEARCH_GROUP_TYPES: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; - -/** Relevance ranking. Sent only while the field has text: with an empty field the backend - * substitutes the install count anyway, and this component knows the field state, so it sends - * the honest value rather than leaning on that safety net. */ -const RELEVANCE = 'relevance'; - @Component({ selector: 'tb-iot-hub-home', standalone: false, @@ -172,10 +164,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); - // Two states, one panel: popularity answers "what is worth looking at" with an empty - // field, relevance answers "what did I ask for" once there is one. - const sortProperty = trimmed ? RELEVANCE : 'totalInstallCount'; - const query = new MpItemVersionGroupedQuery({}, trimmed, sortProperty); + // Relevance in both states, the same value every other IoT Hub surface sends: with an + // empty field the backend substitutes the install count, so this panel opens on + // popularity without having to say so. See TBIOH-33 for the decision. + const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( @@ -556,17 +548,24 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { /** * Reads the sections the server built: they arrive capped and in the order to render them, so - * this only drops the types this panel has no layout for and works out each header's "+N more". + * this only drops the types this panel has no layout for - the platform publishes no dashboards + * - and works out each header's "+N more". + * + * `items` is defaulted because the response is an unvalidated cast of a new endpoint, and a + * throw here lands in a subscribe callback, where it would leave the panel on its spinner + * rather than reaching the catchError upstream. */ private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { return sections - .filter(section => SEARCH_GROUP_TYPES.includes(section.itemType)) - .map(section => ({ - type: section.itemType, - items: section.items, - total: section.total, - remaining: Math.max(0, section.total - section.items.length) - })); + .filter(section => CROSS_TYPE_ITEM_TYPES.includes(section.itemType)) + .map(section => { + const items = section.items ?? []; + return { + type: section.itemType, + items, + remaining: Math.max(0, section.total - items.length) + }; + }); } } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index abdddc1734..68ca5c0158 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 +import { Direction } from '@shared/models/page/sort-order'; + export enum ItemType { WIDGET = 'WIDGET', DASHBOARD = 'DASHBOARD', @@ -54,6 +56,48 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; +/** + * Item types a surface that mixes them lays out, in the order they are shown. Distinct from + * CREATOR_VISIBLE_ITEM_TYPES, which is the same six as a membership test and carries the type + * tabs' own order: here DEVICE leads, matching the hero popup's sections and the website. + */ +export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ + ItemType.DEVICE, + ItemType.SOLUTION_TEMPLATE, + ItemType.WIDGET, + ItemType.CALCULATED_FIELD, + ItemType.ALARM_RULE, + ItemType.RULE_CHAIN, +]; + +/** Sort property served by relevance ranking. */ +export const RELEVANCE_SORT_PROPERTY = 'relevance'; + +export interface SortOption { + value: string; + label: string; + direction: Direction; +} + +/** + * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers + * them in: the first entry is the default each surface opens on. + * + * Relevance is that default in both states. With text it ranks the answer; with none the backend + * substitutes the install count, so a surface opens on the order it opened on before and nothing + * switches on the field state. Agreed with the product owner and recorded on TBIOH-33, which + * supersedes that ticket's SCOPE-IN 2, SCOPE-IN 4 and AC-4. + * + * One list rather than one per surface: a new key must reach all of them, and the surface that + * missed it would keep a different default without failing. + */ +export const IOT_HUB_SORT_OPTIONS: SortOption[] = [ + { value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, + { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, + { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, + { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } +]; + export interface FilterParamInfo { key: string; totalItems: number; From 2d72735070a4dca445ee832b1e58a9b5df37079b Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:26:27 +0300 Subject: [PATCH 031/119] style(iot-hub): close the formatting left behind by the layout and grouping changes The results container kept its old indentation after being wrapped in .tb-search-layout, so it read as a sibling of the wrapper and the two closing tags lined up at the same depth while closing different elements. The popup's @for sat in an ng-container carrying no directive. Removing the -compact rule left a blank line before the closing brace in four places. --- .../iot-hub/iot-hub-search.component.html | 80 +++++++++---------- .../iot-hub/iot-hub-search.component.scss | 4 - .../pages/iot-hub/iot-hub-home.component.html | 48 ++++++----- 3 files changed, 63 insertions(+), 69 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html index 5963b7c003..ca98ed1c0c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html @@ -142,48 +142,48 @@ } -
- - @if (hasError) { -
-
-

{{ 'iot-hub.network-server-unavailable' | translate }}

-

{{ 'iot-hub.network-server-unavailable-text' | translate }}

- -
- } +
+ + @if (hasError) { +
+
+

{{ 'iot-hub.network-server-unavailable' | translate }}

+

{{ 'iot-hub.network-server-unavailable-text' | translate }}

+ +
+ } - - @if (!hasError && totalElements === 0 && searchText?.trim()) { -
-
-

{{ 'iot-hub.no-items-found' | translate }}

-

{{ 'iot-hub.try-adjusting-search' | translate }}

-
- } + + @if (!hasError && totalElements === 0 && searchText?.trim()) { +
+
+

{{ 'iot-hub.no-items-found' | translate }}

+

{{ 'iot-hub.try-adjusting-search' | translate }}

+
+ } - - @if (results.length > 0) { -
- @for (item of results; track item.id) { - - - } -
- } -
+ + @if (results.length > 0) { +
+ @for (item of results; track item.id) { + + + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 2556d03f3d..32c7a51458 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -279,21 +279,18 @@ @media #{$mat-gt-xxl} { .tb-search-card-grid { grid-template-columns: repeat(6, 1fr); - } } @media #{$mat-lt-xl} { .tb-search-card-grid { grid-template-columns: repeat(4, 1fr); - } } @media #{$mat-lt-xmd} { .tb-search-card-grid { grid-template-columns: repeat(3, 1fr); - } } @@ -316,7 +313,6 @@ .tb-search-card-grid { grid-template-columns: repeat(2, 1fr); - } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 07905a8d21..c4d720976b 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -97,32 +97,30 @@ } - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} -
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }}
-
- } - + } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} + +
+ + } } } From edf81221ad1bd23b70eb150b2ceaafe1fa04dc92 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:27:19 +0300 Subject: [PATCH 032/119] fix(iot-hub): encode creatorId and type into the query string These were the only two of the thirteen fields interpolated raw, and creatorId is not an internal value: iot-hub-browse and the creator profile both read it straight off the route with nothing between the URL and the request, so a crafted id could close the parameter and append its own. The UUID shape is a convention here, not something this code enforces. --- .../src/app/shared/models/iot-hub/iot-hub-version.models.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index b194ab0371..a5afaea23c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -156,7 +156,7 @@ export interface MpItemVersionQueryOptions { function filtersToQuery(o: MpItemVersionQueryOptions): string { let query = ''; if (o.type) { - query += `&type=${o.type}`; + query += `&type=${encodeURIComponent(o.type)}`; } if (o.types?.length) { query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); @@ -165,7 +165,7 @@ function filtersToQuery(o: MpItemVersionQueryOptions): string { query += `&peOnly=${o.peOnly}`; } if (o.creatorId) { - query += `&creatorId=${o.creatorId}`; + query += `&creatorId=${encodeURIComponent(o.creatorId)}`; } if (o.categories?.length) { query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); From 5f3c374036f6b3f30659cd5a07938783ad2a9763 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 14:00:48 +0300 Subject: [PATCH 033/119] Stop installing and deploying boot jars, Windows zips and debs --- TEST_FAST.md | 2 +- msa/pom.xml | 11 ++++----- pom.xml | 65 +++++++++------------------------------------------- 3 files changed, 16 insertions(+), 62 deletions(-) diff --git a/TEST_FAST.md b/TEST_FAST.md index fbea72db9c..28f4b4059a 100644 --- a/TEST_FAST.md +++ b/TEST_FAST.md @@ -42,7 +42,7 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag |----------------------------|-------------------------------------------|--------------------------------------------------------------| | `-Dpkg.skip=true` | All of the below (bootjar + deb + rpm + zip) | Yes | | `-Dpkg.skip.bootjar=true` | `spring-boot:repackage` (`*-boot.jar`) | Yes — tests use the regular `.jar`, not the fat boot jar | -| `-Dpkg.skip.deb=true` | Gradle `buildDeb` + Maven `attach-artifact` | Yes — MSA docker modules copy the DEB from `target/` directly | +| `-Dpkg.skip.deb=true` | Gradle `buildDeb` | Yes — MSA docker modules copy the DEB from `target/` directly | | `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM | | `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP | diff --git a/msa/pom.xml b/msa/pom.xml index 3ffd8ed28b..a44cbbb93c 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -55,10 +55,7 @@ - + skip-deb @@ -71,9 +68,9 @@ none - + skip-pkg diff --git a/pom.xml b/pom.xml index 6ecad4cd2c..0c563899c5 100755 --- a/pom.xml +++ b/pom.xml @@ -34,14 +34,13 @@ Individual flags below can be set independently for finer control. --> false - + false @@ -50,11 +49,6 @@ module depends on the ZIP artifact, so this flag can be toggled freely without breaking downstream modules. --> false - - ${pkg.package.phase} thingsboard ${project.name} /var/log/${pkg.name} @@ -215,26 +209,7 @@ - - - skip-deb - - - pkg.skip.deb - true - - - - none - - - - + skip-pkg @@ -248,7 +223,6 @@ true true true - none @@ -565,6 +539,8 @@ ${pkg.skip.bootjar} ${pkg.mainClass} boot + + false ZIP true true @@ -641,28 +617,9 @@ ${pkg.skip.zip} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-deb - ${pkg.deb.phase} - - attach-artifact - - - - - ${project.build.directory}/${pkg.name}.deb - deb - deb - - + + false From 87a6f3088181c5a91bcf512af3cc4e4a316d5abd Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 14:02:33 +0300 Subject: [PATCH 034/119] Stop deploying the ui-ngx jar --- ui-ngx/pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index 164ce0d056..42b0fac027 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -71,6 +71,14 @@ + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + From dab4ec72f9df0089c6651b29e794c766e5e601e6 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 14:38:38 +0300 Subject: [PATCH 035/119] refactor(iot-hub): drop the creatorId query parameter nothing produces The type page adopted `?creatorId=` from the URL whenever its input was unbound. Nothing in the platform builds such a URL: the only navigations carrying query parameters send `search` and `itemType`, and the creator profile scopes its list by binding the component's input rather than by navigating. The branch was reachable only by typing the parameter in by hand, and there it rescoped a Hub-wide type page with no visible sign of why the counts had changed. Both live callers - the creator profile and the add-item dialog - bind the input, which the removed code deferred to in any case. --- .../home/components/iot-hub/iot-hub-browse.component.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 63f561ddad..2be0408826 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -171,12 +171,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (params['search']) { this.textSearch = params['search']; } - // A search section header on a creator profile lands here scoped to that creator. The - // bound input wins: an embedded host (the add-item dialog) sets its own scope, and must - // not pick one up from whatever URL happens to be open behind the dialog. - if (!this.creatorId && !this.embedded && params['creatorId']) { - this.creatorId = params['creatorId']; - } if (this.fixedSubType) { const subtypes = this.getActiveSubtypes(); if (subtypes) { From 6aae7899bf9c8a55bef1904b4a9be3db74153838 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 14:38:38 +0300 Subject: [PATCH 036/119] docs(iot-hub): cite what a reader can find Two comments explaining why relevance is the default in both states pointed at an internal ticket, one of them at three numbered sections of it that are being rewritten precisely because the code no longer matches them. Neither pointer is reachable from this repository, and the numbering is due to move. The reasoning stays inline, with the accepted cost named: the menu reads "Most relevant" over an install-ordered list until the user types. --- .../modules/home/pages/iot-hub/iot-hub-home.component.ts | 4 ++-- .../src/app/shared/models/iot-hub/iot-hub-item.models.ts | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 577ed03a08..91511f533d 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -165,8 +165,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { this.searchLoading = true; const trimmed = text.trim(); // Relevance in both states, the same value every other IoT Hub surface sends: with an - // empty field the backend substitutes the install count, so this panel opens on - // popularity without having to say so. See TBIOH-33 for the decision. + // empty field the backend serves the install count under this key, so the panel opens on + // popularity without this component having to know it. const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index 68ca5c0158..8fbe84440b 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -83,10 +83,11 @@ export interface SortOption { * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers * them in: the first entry is the default each surface opens on. * - * Relevance is that default in both states. With text it ranks the answer; with none the backend - * substitutes the install count, so a surface opens on the order it opened on before and nothing - * switches on the field state. Agreed with the product owner and recorded on TBIOH-33, which - * supersedes that ticket's SCOPE-IN 2, SCOPE-IN 4 and AC-4. + * Relevance is that default with or without text. With text it ranks the answer; with none the + * backend serves the install count under the same key, so a surface opens on the order it opened + * on before and nothing here switches on the field state. The cost is a menu reading "Most + * relevant" over an install-ordered list until the user types; the alternative - flipping the + * selector once text appears - moves a control the user did not touch and reorders nothing. * * One list rather than one per surface: a new key must reach all of them, and the surface that * missed it would keep a different default without failing. From 256c575b42519b24b05f9c14751f4f6b11f02865 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 16 Sep 2026 14:46:00 +0300 Subject: [PATCH 037/119] warn that updating a solution template recreates everything it installed Updating a solution template deletes and reinstalls every entity it created, and unlike the other item types it is not stopped by the modified-entity check, so a tenant's own edits to those dashboards, devices and rule chains are lost without warning. The dialog showed the generic "replace the current version" wording, which does not suggest anything is destroyed. A second, smaller mismatch: a listing renamed between releases shows one name in the installed-items table and another in the dialog that table opens, because the dialog took its title from the published version while the table reads the tracking row. - show a dedicated description for SOLUTION_TEMPLATE that names what is deleted and recreated, and says local changes are lost - take the item details title from the tracking row while the dialog shows exactly the installed version; any other displayed version keeps its own name --- .../iot-hub/iot-hub-item-detail-dialog.component.html | 2 +- .../iot-hub/iot-hub-item-detail-dialog.component.ts | 11 +++++++++++ .../iot-hub/iot-hub-update-dialog.component.html | 4 ++-- .../iot-hub/iot-hub-update-dialog.component.ts | 11 +++++++++++ ui-ngx/src/assets/locale/locale.constant-en_US.json | 1 + 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html index 28e7e74e6d..83f8b69dc4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html @@ -13,7 +13,7 @@
}
- {{ item.name }} + {{ itemTitle }}
{{ getTypeIcon() }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts index d1c6f4f194..12a8900610 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts @@ -172,6 +172,17 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }} -

{{ 'iot-hub.update-desc' | translate }}

+

{{ updateDescKey | translate }}

} @case ('updating') {

{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}

-

{{ 'iot-hub.update-desc' | translate }}

+

{{ updateDescKey | translate }}

} @case ('success') {

{{ 'iot-hub.update-success-title' | translate }}

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts index ec4a48cd2d..e5472c45a1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts @@ -59,6 +59,17 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Fri, 21 Aug 2026 15:35:03 +0300 Subject: [PATCH 038/119] Honour skip.yarn in the JS module tests and packaging The yarn test execution in msa/js-executor declared its own skip flag, which overrode the mojo default of ${skip.yarn}, so a build run with -Dskip.yarn=true still invoked yarn run test with no node_modules installed. The two JS packaging modules had the same gap: the ZIP assembly requires a launcher binary produced by yarn run pkg, so it failed on a missing file rather than being skipped along with the yarn work that would have produced it. Both now follow skip.yarn while continuing to honour maven.test.skip. --- msa/js-executor/pom.xml | 26 +++++++++++++++++++++++++- msa/web-ui/pom.xml | 5 +++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 5d28be03f8..8c35b773db 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -30,6 +30,18 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows + + ${skip.yarn} + + ${skip.yarn} pre-integration-test @@ -112,7 +124,7 @@ test - ${maven.test.skip} + ${yarn.test.skip} --mutex network run test @@ -206,6 +218,18 @@ + + skip-yarn-test + + + maven.test.skip + true + + + + true + + yarn-start diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index b2d148d5b2..f2f5e31309 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -32,6 +32,11 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows + + ${skip.yarn} pre-integration-test From 6172ca8963f6feffe4ddcf80dc079f1dbbdd0e3c Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 21 Aug 2026 15:54:50 +0300 Subject: [PATCH 039/119] Add a skip.ui.build flag that skips only the UI builds frontend-maven-plugin reads skip.yarn on its own, so -Dskip.yarn=true switches off every yarn invocation in the project at once. That is the right shortcut for a local backend build, but it is too blunt for CI: it also silences the msa/js-executor sandbox tests, which are the only yarn-driven tests worth keeping. skip.ui.build is declared once in the root pom and defaults to ${skip.yarn}. It is wired into the frontend-maven-plugin configuration of ui-ngx and msa/web-ui, and into the pkg.skip.zip of msa/web-ui, whose Windows ZIP bundles the launcher that `yarn run pkg` produces. It is deliberately NOT wired into msa/js-executor: with -Dskip.ui.build=true that module still runs its yarn install, its `yarn run pkg` and its sandbox tests. Behaviour: no flags everything builds and is tested as before -Dskip.ui.build=true ui-ngx and msa/web-ui skip; msa/js-executor still builds and runs its tests -Dskip.yarn=true everything skips, exactly as before The element is declared at plugin level rather than per execution so that it also covers the executions contributed by the yarn-build and yarn-start profiles, and so that node/yarn itself is no longer downloaded when there is nothing to run. --- msa/web-ui/pom.xml | 7 +++++-- pom.xml | 7 +++++++ ui-ngx/pom.xml | 3 +++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index f2f5e31309..93d2ecff76 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -33,10 +33,10 @@ ${project.build.directory}/package/linux ${project.build.directory}/package/windows - ${skip.yarn} + ${skip.ui.build} pre-integration-test @@ -65,6 +65,9 @@ target ${basedir} + + ${skip.ui.build} diff --git a/pom.xml b/pom.xml index 0c563899c5..11c0e52c30 100755 --- a/pom.xml +++ b/pom.xml @@ -28,6 +28,13 @@ 17 17 ${basedir} + + ${skip.yarn} none none + ${skip.ui.build} From 21e5d93aeca3ffc038cee2f3290df0a59c86e826 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 15:05:42 +0300 Subject: [PATCH 040/119] Skip all packaging when the UI build is skipped Packages built without the UI are incomplete, so -Dskip.yarn=true and -Dskip.ui.build=true now imply -Dpkg.skip=true through dedicated profiles in the root pom and msa/pom.xml. This replaces the module-level pkg.skip.zip properties in msa/js-executor and msa/web-ui, which shadowed the root skip-pkg profile and made -Dpkg.skip=true build their Windows ZIPs again. --- TEST_FAST.md | 2 ++ msa/js-executor/pom.xml | 5 ----- msa/pom.xml | 25 +++++++++++++++++++++++++ msa/web-ui/pom.xml | 5 ----- pom.xml | 37 ++++++++++++++++++++++++++++++++++++- 5 files changed, 63 insertions(+), 11 deletions(-) diff --git a/TEST_FAST.md b/TEST_FAST.md index 28f4b4059a..11f8969fca 100644 --- a/TEST_FAST.md +++ b/TEST_FAST.md @@ -46,6 +46,8 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag | `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM | | `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP | +`-Dskip.yarn=true` and `-Dskip.ui.build=true` imply `-Dpkg.skip=true`: packages built without the UI are incomplete. + ## Testcontainers compatibility with the Docker API workaround In case your tests failed to run testcontainers due to unsupported Docker API version diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 8c35b773db..3a4a1ccda4 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -30,11 +30,6 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows - - ${skip.yarn} + + skip-pkg-without-yarn + + + skip.yarn + true + + + + none + + + + skip-pkg-without-ui-build + + + skip.ui.build + true + + + + none + + black-box-tests diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 93d2ecff76..9e616482cf 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -32,11 +32,6 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows - - ${skip.ui.build} pre-integration-test diff --git a/pom.xml b/pom.xml index 11c0e52c30..77706d1627 100755 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,8 @@ cover msa/js-executor, whose yarn install and sandbox tests keep running. frontend-maven-plugin reads skip.yarn itself, so that property cannot be narrowed to a subset of the modules; this one can, and it defaults to skip.yarn so that - -Dskip.yarn=true still skips every yarn invocation in the project exactly as before. --> + -Dskip.yarn=true still skips every yarn invocation in the project exactly as before. + Either flag also skips all packaging (see the skip-pkg-without-* profiles). --> ${skip.yarn} none none @@ -233,6 +234,40 @@ + + + skip-pkg-without-yarn + + + skip.yarn + true + + + + true + true + true + true + + + + skip-pkg-without-ui-build + + + skip.ui.build + true + + + + true + true + true + true + + + packaging From c5a3bea6dfed1da693bc6263c36e0fa2bc9708f1 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 15:22:10 +0300 Subject: [PATCH 041/119] fix(iot-hub): let the keyboard reach every row of the search popup The popup keeps focus in the input and walks its rows with an active-descendant key manager, which only knows about options. A section header written as a span with role="button" and tabindex="0" is therefore unreachable: the arrow keys skip it, its keyup.enter can never fire because it can never hold focus, and Tab does not help since leaving the input closes the panel. That header is the only way from the popup into a type page, so without a mouse there was no way in at all. The footer had the same shape, though its action is also on the input's own Enter. The header also sat inside the group's label element, which is presentational, so the section's name came out as the header's whole text - "Devices +12 more" - wrapping a control nobody could operate. Header and footer are now options like every other row. They take part in arrow navigation, they read as part of the list, and the group wrapper goes away with the label it was distorting. Rows also acted on (click) alone. Pressing Enter on a highlighted result runs _selectViaInteraction, which is not a DOM click, so the card never opened from the keyboard. Every row now acts on (onSelectionChange) guarded by isUserInput, one path for pointer and keyboard both. Enter in the field needed a guard to go with that: the trigger acts on keydown and this handler runs on keyup, which the trigger's preventDefault does not stop, so one Enter would have opened a result and then navigated away from it. --- .../pages/iot-hub/iot-hub-home.component.html | 76 +++++++++---------- .../pages/iot-hub/iot-hub-home.component.scss | 66 +++++++--------- .../pages/iot-hub/iot-hub-home.component.ts | 9 +++ 3 files changed, 75 insertions(+), 76 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index c4d720976b..b2be21ac32 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -85,53 +85,51 @@ } @else { @for (group of searchResultGroups; track group.type) { - - - {{ getSearchGroupLabel(group.type) }} - @if (group.remaining > 0) { - - {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} - chevron_right - - } - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} -
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - -
-
+ + {{ getSearchGroupLabel(group.type) }} + @if (group.remaining > 0) { + + {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} + chevron_right + } -
+ + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }} +
+ } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} + +
+
+ } } } - +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index d8934e82ff..98b4ab0389 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,45 +220,32 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); - // Section group — 12px gap between groups - .mat-mdc-optgroup + .mat-mdc-optgroup .mat-mdc-optgroup-label { + // Section header — an option like every other row, not a button beside them, so the arrow keys + // reach it and a screen reader reads it in the list. It IS the way into the type page: title + // left, how much is not shown plus a chevron right. There is deliberately no per-section + // "see all" row under the items; six of those on one panel is what this variant avoids. + // Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H, 12px above each section. + .mat-mdc-option.tb-search-popup-group-header { + padding: 4px 16px; + min-height: 28px; margin-top: 12px; + + &:first-child { + margin-top: 0; + } + + .mdc-list-item__primary-text { + justify-content: space-between; + } } - // Section title — Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H - .mat-mdc-optgroup .mat-mdc-optgroup-label { - padding: 4px 16px; - min-height: 28px; + .tb-search-popup-group-label { font-size: 14px; font-weight: 500; line-height: 20px; letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); white-space: nowrap; - - .mdc-list-item__primary-text { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - // The header spans the panel so the count can sit against the right edge. Material's own - // label span is only as wide as its text. - width: 100%; - } - } - - // Section header — the label IS the link into the type page: title left, how much is not shown - // plus a chevron right. There is deliberately no per-section "see all" row under the items; - // six of those on one panel is what this variant was chosen to avoid. - .tb-search-popup-group-header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - width: 100%; - cursor: pointer; - outline: none; } .tb-search-popup-group-more { @@ -281,7 +268,7 @@ } // Item row — Design: 8px V / 16px H, 16px gap, centered - .mat-mdc-optgroup .mat-mdc-option:not(.mat-mdc-option-multiple) { + .mat-mdc-option:not(.mat-mdc-option-multiple) { padding: 8px 16px; min-height: auto; height: auto; @@ -426,26 +413,31 @@ } // Footer — Design: 40px h, 8px V / 16px H, 1px top border, tb-primary text - .tb-search-popup-footer { + .mat-mdc-option.tb-search-popup-footer { position: sticky; bottom: 0; + z-index: 1; border-top: 1px solid rgba(0, 0, 0, 0.12); height: 40px; min-height: 40px; padding: 8px 16px; - display: flex; - align-items: center; - justify-content: flex-start; font-size: 14px; font-weight: 500; line-height: 20px; letter-spacing: 0.25px; color: $tb-primary-color; - cursor: pointer; background: white; white-space: nowrap; - &:hover { + .mdc-list-item__primary-text { + justify-content: flex-start; + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + &:hover:not(.mdc-list-item--disabled), + &.mat-mdc-option-active:not(.mdc-list-item--disabled) { background: #f5f5f5; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 91511f533d..8e6038ef96 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -239,7 +239,16 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { setTimeout(() => this.searchAutoTrigger?.openPanel()); } + /** + * Enter in the field opens the search page - unless the panel has an option highlighted, which + * the trigger has already acted on during keydown. This runs on keyup, which preventDefault on + * the keydown does not stop, so without the guard one Enter would both open a result and + * navigate away from it. + */ onSearch(): void { + if (this.searchAutoTrigger?.activeOption) { + return; + } this.seeAllResults(); } From ccf0581ac38f75461b8dc7511ddce557ef4701b2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 15:35:28 +0300 Subject: [PATCH 042/119] Generate build-info outside the packaging profile Activating any other root profile (skip-pkg, skip-pkg-without-*) switches off the activeByDefault packaging profile, which held the only build-info execution, so such builds had no build-info.properties and ProjectInfo failed at runtime. The jar plugin config (logback.xml exclusion, manifest) moves out of the profile for the same reason. --- pom.xml | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index 77706d1627..0a46f54ab1 100755 --- a/pom.xml +++ b/pom.xml @@ -554,21 +554,6 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - **/logback.xml - - - - ${pkg.implementationTitle} - ${project.version} - - - - org.springframework.boot spring-boot-maven-plugin @@ -597,7 +582,6 @@ repackage - build-info @@ -717,6 +701,18 @@ org.apache.maven.plugins maven-jar-plugin ${jar-plugin.version} + + + + **/logback.xml + + + + ${pkg.implementationTitle} + ${project.version} + + + org.apache.maven.plugins @@ -727,6 +723,20 @@ org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} + + + + build-info + + build-info + + + + false + + + org.thingsboard From 14e3025a24842b66d4df2c67fec1faace5e6a4a1 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 17 Sep 2026 13:15:27 +0300 Subject: [PATCH 043/119] fix(iot-hub): make the popup's Enter guard and row padding hold on their own Three things from the re-review, two of them introduced by the commit that turned the popup's header and footer into options. **The Enter guard never fired.** It asked the autocomplete trigger for its active option during keyup, but the trigger clears that inside the same keydown - it calls _selectViaInteraction and then _resetActiveItem, which with no autoActiveFirstOption sets the active index to -1. So the guard always fell through, and one Enter on a highlighted row opened it and then navigated away from it. That is worse than the behaviour before, where the click handler simply never ran. The row that acts now records it through rowSelectedByUser, which does not depend on the order the two handlers run in, and typing clears the flag since a pointer selection leaves no keyup behind it. **The header's own padding was overridden.** Under one ancestor chain, `.mat-mdc-option.tb-search-popup-group-header` and `.mat-mdc-option:not(.mat-mdc-option-multiple)` both weigh (0,4,0), and the second was declared later, so every section header shipped 8px taller than the 4px the comment above it documents - with up to six of them in a 424px panel. The catch-all could not match the old span header; it matches an option. Each row kind now carries its own class and the shared parts sit in one rule, so nothing here rests on source order. The footer had the same collision and only won by being declared last. **The hover-scrollbar block is a mixin.** This branch added a second byte-identical copy of it. Both now call tb-iot-hub-hover-scrollbar from the partial they already import. The mixin records what is deliberately NOT settled here: whether these panels should keep a thumb that is invisible until hover, and whether to add the standardised scrollbar-width / scrollbar-color that Firefox reads, is a question for the IoT Hub filter UI as a whole - iot-hub-browse and dashboard-widget-select carry the same treatment and predate this branch. --- .../components/iot-hub/_iot-hub-common.scss | 36 +++++++++++++++++ .../iot-hub/iot-hub-facet-list.component.scss | 27 +------------ .../iot-hub/iot-hub-search.component.scss | 27 +------------ .../pages/iot-hub/iot-hub-home.component.html | 8 ++-- .../pages/iot-hub/iot-hub-home.component.scss | 40 +++++++++++-------- .../pages/iot-hub/iot-hub-home.component.ts | 31 +++++++++++--- 6 files changed, 91 insertions(+), 78 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss index d247f20112..96697ebe74 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss @@ -119,3 +119,39 @@ pointer-events: none; } } + +// Scroll area that shows its thumb only while the container is hovered — the filter panels' +// own treatment, kept here so the two that use it cannot drift apart. +// +// Not the app-wide one: theme.scss keeps its thumb permanently visible. Whether these panels +// should do the same, and whether to add the standardised scrollbar-width / scrollbar-color +// that Firefox reads, is a question for the IoT Hub filter UI as a whole rather than for one +// panel; iot-hub-browse and dashboard-widget-select carry copies of this same treatment. +@mixin tb-iot-hub-hover-scrollbar { + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } + + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss index e5fc43f803..4df80a68e1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss @@ -45,32 +45,7 @@ overflow-y: auto; } - &::-webkit-scrollbar { - width: 6px; - } - - &::-webkit-scrollbar-track { - background-color: transparent; - } - - &::-webkit-scrollbar-thumb { - background-color: transparent; - border-radius: 3px; - } - - &:hover { - &::-webkit-scrollbar-track { - background-color: rgba(0, 0, 0, 0.04); - } - - &::-webkit-scrollbar-thumb { - background-color: rgba(0, 0, 0, 0.2); - - &:hover { - background-color: rgba(0, 0, 0, 0.35); - } - } - } + @include tb-iot-hub-hover-scrollbar; } .tb-iot-hub-facet-search { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 32c7a51458..3f946404ad 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -221,32 +221,7 @@ overflow-y: auto; padding-top: 20px; - &::-webkit-scrollbar { - width: 6px; - } - - &::-webkit-scrollbar-track { - background-color: transparent; - } - - &::-webkit-scrollbar-thumb { - background-color: transparent; - border-radius: 3px; - } - - &:hover { - &::-webkit-scrollbar-track { - background-color: rgba(0, 0, 0, 0.04); - } - - &::-webkit-scrollbar-thumb { - background-color: rgba(0, 0, 0, 0.2); - - &:hover { - background-color: rgba(0, 0, 0, 0.35); - } - } - } + @include tb-iot-hub-hover-scrollbar; } // The close button and heading belong to the narrow layout only. diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index b2be21ac32..564f89ca46 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -86,7 +86,7 @@ } @else { @for (group of searchResultGroups; track group.type) { + (onSelectionChange)="rowSelectedByUser($event) && navigateToSection(group.type)"> {{ getSearchGroupLabel(group.type) }} @if (group.remaining > 0) { @@ -96,8 +96,8 @@ } @for (item of group.items; track item.id) { - + @if (isCompactType(item.type)) {
{{ getCompactIcon(item) }} @@ -123,7 +123,7 @@ } } + (onSelectionChange)="rowSelectedByUser($event) && seeAllResults()"> @if (searchText?.trim(); as query) { {{ 'iot-hub.see-results-for' | translate:{ search: query } }} } @else { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 98b4ab0389..8a89ebae44 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,6 +220,27 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); + // Every row of the panel shares the flex line and the highlight; the boxes differ per kind + // below. Each kind is selected by its own class rather than by leaning on source order, since + // .mat-mdc-option. and .mat-mdc-option:not(...) tie on specificity. + .mat-mdc-option { + .mdc-list-item__primary-text { + display: flex; + align-items: center; + gap: 16px; + width: 100%; + } + + &:hover:not(.mdc-list-item--disabled), + &.mat-mdc-option-active:not(.mdc-list-item--disabled) { + background: rgba(0, 0, 0, 0.04); + } + + .mat-icon, tb-icon { + margin-right: 0; + } + } + // Section header — an option like every other row, not a button beside them, so the arrow keys // reach it and a screen reader reads it in the list. It IS the way into the type page: title // left, how much is not shown plus a chevron right. There is deliberately no per-section @@ -268,26 +289,10 @@ } // Item row — Design: 8px V / 16px H, 16px gap, centered - .mat-mdc-option:not(.mat-mdc-option-multiple) { + .mat-mdc-option.tb-search-popup-item { padding: 8px 16px; min-height: auto; height: auto; - - &:hover:not(.mdc-list-item--disabled), - &.mat-mdc-option-active:not(.mdc-list-item--disabled) { - background: rgba(0, 0, 0, 0.04); - } - - .mat-icon, tb-icon { - margin-right: 0; - } - - .mdc-list-item__primary-text { - display: flex; - align-items: center; - gap: 16px; - width: 100%; - } } // Thumbnail — Design: 99px x 56px, 4px radius, 1px border, 4% bg @@ -392,6 +397,7 @@ .tb-search-popup-no-results { pointer-events: none; opacity: 1 !important; + padding: 8px 16px; } .tb-search-popup-no-results-content { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 8e6038ef96..4efb672e33 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -3,6 +3,7 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; +import { MatOptionSelectionChange } from '@angular/material/core'; import { BreakpointObserver } from '@angular/cdk/layout'; import { forkJoin, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; @@ -66,6 +67,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef; + private enterHandledByRow = false; private searchSubject = new Subject(); private searchSubscription: Subscription; @@ -217,6 +219,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchInput(): void { + this.enterHandledByRow = false; this.searchLoading = true; this.searchSubject.next(this.searchText || ''); } @@ -240,13 +243,31 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } /** - * Enter in the field opens the search page - unless the panel has an option highlighted, which - * the trigger has already acted on during keydown. This runs on keyup, which preventDefault on - * the keydown does not stop, so without the guard one Enter would both open a result and - * navigate away from it. + * Gate on every row's selection: false for the panel's own bookkeeping, true when the user + * picked the row - and then it records that this keystroke has been dealt with. + * + * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own + * handler on keyup, and preventDefault on the first does not stop the second. The trigger's + * activeOption cannot tell them apart either: it clears it inside that same keydown, so by + * keyup it reads empty whether or not a row acted. The row that acted says so instead, which + * does not depend on the order the two handlers run in. + */ + rowSelectedByUser(event: MatOptionSelectionChange): boolean { + if (!event.isUserInput) { + return false; + } + this.enterHandledByRow = true; + return true; + } + + /** + * Enter in the field opens the search page, unless a row has just acted on this same press. + * The flag is also cleared on input, since a pointer selection sets it with no keyup to follow + * and would otherwise swallow the next Enter. */ onSearch(): void { - if (this.searchAutoTrigger?.activeOption) { + if (this.enterHandledByRow) { + this.enterHandledByRow = false; return; } this.seeAllResults(); From c410558dcaa7ef4a793ad7ee11c2c1087cb2e366 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 17 Sep 2026 15:29:46 +0300 Subject: [PATCH 044/119] fix(iot-hub): arm the popup's Enter flag only where a keyup is coming The flag was set by any user selection, but only the keyboard leaves a second half to deal with: the trigger acts on keydown, the field's own handler on keyup, and preventDefault on the first does not stop the second. A pointer selection is finished when it returns, so the flag stayed set with nothing to consume it, and the next onSearch took the early return - click a result, close the detail dialog, press the magnifier, and the search page did not open. The magnifier is the plain case because it calls onSearch with no keystroke at all; Enter in the field does the same once the dialog restores focus there. It is armed from the trigger's activeOption now, which is readable only at that moment - the trigger holds it while it calls _selectViaInteraction and clears it on the next line of its own handler - and which a pointer never sets. Focusing the field and clearing it drop the flag as well, which covers the one pointer selection that can still arm it: arrowing to a row and then clicking a different one. --- .../pages/iot-hub/iot-hub-home.component.ts | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 4efb672e33..cf242faeb3 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -225,6 +225,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchFocus(): void { + this.enterHandledByRow = false; if (!this.searchLoaded) { this.searchLoading = true; this.searchSubject.next(this.searchText || ''); @@ -236,6 +237,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }; clearSearch(): void { + this.enterHandledByRow = false; this.searchText = ''; this.searchSubject.next(''); this.searchInputRef?.nativeElement?.focus(); @@ -244,26 +246,30 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { /** * Gate on every row's selection: false for the panel's own bookkeeping, true when the user - * picked the row - and then it records that this keystroke has been dealt with. + * picked the row - and then it records whether a keyup is still coming for it. * * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own - * handler on keyup, and preventDefault on the first does not stop the second. The trigger's - * activeOption cannot tell them apart either: it clears it inside that same keydown, so by - * keyup it reads empty whether or not a row acted. The row that acted says so instead, which - * does not depend on the order the two handlers run in. + * handler on keyup, and preventDefault on the first does not stop the second. Only the + * keyboard leaves that second half to deal with, so only the keyboard arms the flag: a pointer + * selection is finished when it returns, and a flag left standing there would swallow the next + * onSearch - which the magnifier button can raise with no keystroke at all. + * + * activeOption is what tells the two apart, and it is readable only here: the trigger holds it + * while it calls _selectViaInteraction and clears it on the next line of its own handler, so by + * keyup it reads empty either way. A pointer never sets it. */ rowSelectedByUser(event: MatOptionSelectionChange): boolean { if (!event.isUserInput) { return false; } - this.enterHandledByRow = true; + this.enterHandledByRow = !!this.searchAutoTrigger?.activeOption; return true; } /** * Enter in the field opens the search page, unless a row has just acted on this same press. - * The flag is also cleared on input, since a pointer selection sets it with no keyup to follow - * and would otherwise swallow the next Enter. + * Every path that re-enters the field clears the flag too, so nothing survives the keystroke + * it belongs to - including an arrow-then-click, the one selection that arms it by pointer. */ onSearch(): void { if (this.enterHandledByRow) { From 191d7798143120f11e0c44e375d0c9d8099d7028 Mon Sep 17 00:00:00 2001 From: Dmytro Pinkevych <49400214+pinkevmladchy@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:39:14 +0300 Subject: [PATCH 045/119] Keep IoT Hub markdown table columns from overlapping (#16138) * Keep IoT Hub markdown table columns from overlapping Long unbreakable values in solution instruction tables (logins, e-mails, passwords) overflowed their own column and ran under the copy icon. Cells now break such tokens with overflow-wrap: anywhere, cells holding a copy button reserve room for the icon, and the table is sized by its content instead of splitting the width equally between all columns. * Let preformatted content in markdown table cells wrap With auto layout a cell holding a preformatted block keeps the whole line as its min-content width, which the table cannot shrink below: in a 396px host the table measured 701px and a host that hides horizontal overflow, such as the item detail dialog's .dlg-body, cut the overflow off with no way to scroll to it. Relaxing the block and the code inside it to pre-wrap lets the cell shrink with the table. * Derive the copy icon space in table cells from the icon geometry The 44px reserved on the right of a copy-code cell was derived by hand from the copy icon chip declared 45 lines above it, so nudging the chip's width or offset would silently put the cell text back under the icon. Both numbers now live in $copy-icon-width and $copy-icon-offset, used by the chip itself and by the reservation, which is written as width plus the gap on either side. --- .../iot-hub/iot-hub-markdown.component.scss | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss index 2a946348ad..c25c67e729 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss @@ -3,6 +3,10 @@ $text-color: rgba(0,0,0,0.76); $link-color: #2a7dec; $copy-button-color: #2a7dec; +// Geometry of the copy icon chip, shared by the chip itself and by the space table +// cells reserve for it, so the two cannot drift apart. +$copy-icon-width: 38px; +$copy-icon-offset: 3px; $code-block-border-color: rgba(42, 125, 236, .2); $code-default-color: #212529; @@ -169,10 +173,10 @@ $gallery-border-hover-color: #2a7dec; div { background-color: #fff; position: absolute; - width: 38px; + width: $copy-icon-width; height: 28px; - top: 3px; - right: 3px; + top: $copy-icon-offset; + right: $copy-icon-offset; padding: 8px 10px 0; img { @@ -204,9 +208,30 @@ $gallery-border-hover-color: #2a7dec; } th, td { + // Long unbreakable tokens (logins, e-mails, passwords) must never overflow their + // own column. `anywhere` also drops the cell min-content width down to a single + // character, so auto layout can always squeeze the table into the available + // width instead of overflowing (and getting clipped by `overflow: hidden`). + overflow-wrap: break-word; // fallback for engines without `anywhere` + overflow-wrap: anywhere; + + // Text is not the only thing that can outgrow a column: a preformatted block keeps + // its whole line as min-content width, which auto layout cannot shrink, so the table + // would push past its container and get cut off by a host that hides horizontal + // overflow (iot-hub-item-detail-dialog's .dlg-body). Wrap it inside the cell instead. + // Prism sets `white-space: pre` on both the block and the code inside it, so both + // have to be relaxed for the cell to shrink. + pre, pre > code { + white-space: pre-wrap; + } + div.code-wrapper { display: inline-block; width: 100%; + // Reserve room for the absolutely positioned copy icon, plus the same gap on its + // far side, so the cell text does not run underneath it and the reservation + // follows the chip if its geometry ever changes. + padding-right: $copy-icon-width + 2 * $copy-icon-offset; button.clipboard-btn { top: -6px; @@ -275,11 +300,10 @@ $gallery-border-hover-color: #2a7dec; margin-top: 20px; margin-bottom: 20px; overflow: hidden; - table-layout: fixed; - - &.auto { - table-layout: auto; - } + // Columns are sized to their content: with fixed layout every column got the + // same width, so cells with long values (e-mails, logins, tokens) had to wrap + // mid-word while short columns kept a lot of unused space. + table-layout: auto; > thead { background-color: $table-header-background-color; From 89e2e086fb05980208b62d630e0737bce58c1263 Mon Sep 17 00:00:00 2001 From: Dmytro Pinkevych <49400214+pinkevmladchy@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:39:29 +0300 Subject: [PATCH 046/119] Refresh the installed items count after an install, update or delete (#16139) * Refresh the installed items count after an install, update or delete The IoT Hub items page loaded its installed-items counter once, so installing, updating or deleting an item from the embedded browse list left the counter showing a stale number until the page was reloaded. The browse component now emits installedItemsChanged whenever it refreshes its own installed-items state, and the page reloads the counter on that event. * Refresh the installed items count from the device wizard and deep links too The device install wizard registers the install as soon as the entity steps finish, but closing it with the header X or with Cancel on a still-pending later step resolved to false, so the caller never reloaded. It now reports 'installed' once the server has the installed item, whichever way it is closed. The deep-linked item dialog is opened by the items page itself, so its outcome was discarded. It now refreshes the browse grid, which in turn announces the new count. --- .../device-install-dialog.component.ts | 9 ++++++++- .../iot-hub/iot-hub-browse.component.ts | 12 +++++++++++- .../iot-hub/iot-hub-items-page.component.html | 3 ++- .../pages/iot-hub/iot-hub-items-page.component.ts | 15 ++++++++++++--- 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 676ad706b1..7f991316ee 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -95,6 +95,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -357,7 +363,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + /** + * Fired whenever an install, update or delete changed what this tenant has installed, so a host + * page showing its own installed-items counter can refresh it instead of waiting for a reload. + */ + @Output() installedItemsChanged = new EventEmitter(); @Input() set activeType(value: ItemType) { if (value && value !== this._activeType) { const wasInit = !!this._activeType; @@ -627,7 +632,11 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy }); } - private reloadInstalledItems(): void { + /** + * Re-reads what is installed for the active type and announces the change. Public so a host page + * that opens the item detail dialog itself can refresh this grid through the same path. + */ + reloadInstalledItems(): void { const config = {ignoreLoading: true}; const pageLink = new PageLink(10000, 0); if (this.activeType === ItemType.WIDGET) { @@ -643,6 +652,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.installedItemCounts = counts; }); } + this.installedItemsChanged.emit(); } private loadFilterInfo(): void { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html index 59a42eab29..5787b5ecf0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html @@ -35,7 +35,8 @@ + [hideTabs]="true" + (installedItemsChanged)="loadInstalledCount()"> diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts index b89448be3c..07beff5559 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { TbIotHubBrowseComponent } from '@home/components/iot-hub/iot-hub-browse.component'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { PageLink } from '@shared/models/page/page-link'; @@ -83,6 +84,8 @@ export class TbIotHubItemsPageComponent implements OnInit { config: ItemTypePageConfig; installedItemsCount = 0; + @ViewChild(TbIotHubBrowseComponent) private browse: TbIotHubBrowseComponent; + constructor( private route: ActivatedRoute, private router: Router, @@ -109,7 +112,7 @@ export class TbIotHubItemsPageComponent implements OnInit { window.open(this.iotHubApiService.baseUrl + '/signup', '_blank'); } - private loadInstalledCount(): void { + loadInstalledCount(): void { this.iotHubApiService.getInstalledItemsCount(this.config.type, { ignoreLoading: true }).subscribe(count => { this.installedItemsCount = count; }); @@ -147,7 +150,13 @@ export class TbIotHubItemsPageComponent implements OnInit { 'default', true, openItem.preview - ).subscribe(); + ).subscribe(result => { + // The deep-linked dialog is opened by this page rather than by the grid, so its outcome + // has to be fed back in by hand — the grid then refreshes and announces the new count. + if (result === 'installed' || result === 'updated' || result === 'deleted') { + this.browse?.reloadInstalledItems(); + } + }); }); } From b02a7d0817c053f779b54f8e952a62d72e4d8772 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Tue, 22 Sep 2026 16:43:19 +0300 Subject: [PATCH 047/119] Fix license headers --- .../service/edge/rpc/EdgeGrpcServiceTest.java | 17 ++--------------- .../js/NashornJsInvokeServiceLifecycleTest.java | 17 ++--------------- 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 7b71c65c9f..80730f9f53 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc; import org.junit.jupiter.api.BeforeEach; diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java index cdfd2d8e93..673e06d5a8 100644 --- a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.script.api.js; import delight.nashornsandbox.NashornSandbox; From d9f5ec7b433854c1682707d4729c5298e6d9f31f Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Thu, 24 Sep 2026 11:11:59 +0200 Subject: [PATCH 048/119] Updated gateway sync branch config --- application/src/main/resources/thingsboard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 2de4c21c8a..a527a4108c 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1428,7 +1428,7 @@ transport: # URL of gateways dashboard repository repository_url: "${TB_GATEWAY_DASHBOARD_SYNC_REPOSITORY_URL:https://github.com/thingsboard/gateway-management-extensions-dist.git}" # Branch of gateways dashboard repository to work with - branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.0.0}" + branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.2.0}" # Fetch frequency in hours for gateways dashboard repository fetch_frequency: "${TB_GATEWAY_DASHBOARD_SYNC_FETCH_FREQUENCY:24}" ssl: From d37e0c3506c9df31347127218af5b41443da8640 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Thu, 24 Sep 2026 22:09:51 +0200 Subject: [PATCH 049/119] Add CARTO as a separate map provider with an optional API key (#16189) * Add API key support for CARTO basemap layers * Move CARTO basemaps to a dedicated map provider and drop legacy HERE v2 credentials - Add MapProvider.carto with its own layer types, settings and TbCartoMapLayer; the API key is optional since CARTO serves tiles without one. - Read CARTO layers stored under the OpenStreetMap provider as CARTO layers (normalized in the layer factory and in the map layers settings form), so existing widgets migrate on the next settings save without an upgrade script. - Reset the API key when switching to CARTO instead of keeping the previous provider's key. - Remove the useV3 toggle and app_id/app_code fields from legacy HERE settings; leaflet-providers 4.x only supports HERE v3 with an API key. --------- Co-authored-by: Vladyslav Prykhodko --- ui-ngx/package.json | 2 +- .../widget/lib/maps-legacy/map-models.ts | 6 -- .../lib/maps-legacy/providers/here-map.ts | 11 ++- .../components/widget/lib/maps/map-layer.ts | 31 +++++++- .../common/map/map-layer-row.component.html | 8 +++ .../common/map/map-layer-row.component.ts | 14 +++- .../map-layer-settings-panel.component.html | 18 ++++- .../map/map-layer-settings-panel.component.ts | 18 ++++- .../common/map/map-layers.component.ts | 5 +- .../here-map-provider-settings.component.html | 23 ++---- .../here-map-provider-settings.component.ts | 34 ++------- .../shared/models/widget/maps/map.models.ts | 72 +++++++++++++++++-- .../assets/locale/locale.constant-en_US.json | 16 +++-- ui-ngx/yarn.lock | 8 +-- 14 files changed, 181 insertions(+), 85 deletions(-) diff --git a/ui-ngx/package.json b/ui-ngx/package.json index c830027a3c..c410d5bed4 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -61,7 +61,7 @@ "jszip": "^3.10.1", "leaflet": "1.9.4", "leaflet-polylinedecorator": "1.6.0", - "leaflet-providers": "2.0.0", + "leaflet-providers": "4.0.0", "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.12.35", diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts index b918e859e6..a34f88e9b0 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts @@ -121,9 +121,6 @@ export const hereMapProviderTranslationMap = new Map( export interface HereMapProviderSettings { mapProviderHere: HereMapProvider; credentials: { - useV3: boolean; - app_id: string; - app_code: string; apiKey: string; }; } @@ -131,9 +128,6 @@ export interface HereMapProviderSettings { export const defaultHereMapProviderSettings: HereMapProviderSettings = { mapProviderHere: HereMapProvider.hereNormalDay, credentials: { - useV3: true, - app_id: 'AhM6TzD9ThyK78CT3ptx', - app_code: 'p6NPiITB3Vv0GMUFnkLOOg', apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } }; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts index 5afa3c4c6d..64f4f6752b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import L from 'leaflet'; import LeafletMap from '../leaflet-map'; -import { DEFAULT_ZOOM_LEVEL, WidgetUnitedMapSettings } from '../map-models'; +import { DEFAULT_ZOOM_LEVEL, defaultHereMapProviderSettings, WidgetUnitedMapSettings } from '../map-models'; import { WidgetContext } from '@home/models/widget-component.models'; -import { isDefinedAndNotNull } from '@core/utils'; +import { hereV3Provider } from '@shared/models/widget/maps/map.models'; export class HEREMap extends LeafletMap { constructor(ctx: WidgetContext, $container: HTMLElement, options: WidgetUnitedMapSettings) { @@ -13,11 +13,8 @@ export class HEREMap extends LeafletMap { doubleClickZoom: !this.options.disableDoubleClickZooming, zoomControl: !this.options.disableZoomControl }).setView(options?.parsedDefaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL); - let provider = options.mapProviderHere || 'HERE.normalDay'; - if (options.credentials.useV3 && isDefinedAndNotNull(options.credentials.apiKey)) { - provider = options.mapProviderHere?.replace('HERE', 'HEREv3') || 'HEREv3.normalDay'; - } - const tileLayer = (L.tileLayer as any).provider(provider, options.credentials); + const apiKey = options.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey; + const tileLayer = L.tileLayer.provider(hereV3Provider(options.mapProviderHere), {apiKey}); tileLayer.addTo(map); super.setMap(map); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts index a79f290c9b..d61e81ca6e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 import { + CartoMapLayerSettings, CustomMapLayerSettings, + defaultCartoMapLayerSettings, defaultCustomMapLayerSettings, defaultGoogleMapLayerSettings, defaultHereMapLayerSettings, @@ -10,8 +12,10 @@ import { defaultTencentMapLayerSettings, GoogleMapLayerSettings, HereMapLayerSettings, + hereV3Provider, MapLayerSettings, MapProvider, + normalizeMapLayerSettings, OpenStreetMapLayerSettings, ReferenceLayerType, TencentMapLayerSettings, WEBGL_ERROR_EVENT @@ -46,9 +50,12 @@ export abstract class TbMapLayer { static fromSettings(ctx: WidgetContext, inputSettings: DeepPartial) { + inputSettings = normalizeMapLayerSettings(inputSettings as MapLayerSettings); switch (inputSettings.provider) { case MapProvider.openstreet: return new TbOpenStreetMapLayer(ctx, inputSettings); + case MapProvider.carto: + return new TbCartoMapLayer(ctx, inputSettings); case MapProvider.google: return new TbGoogleMapLayer(ctx, inputSettings); case MapProvider.tencent: @@ -212,6 +219,24 @@ class TbOpenStreetMapLayer extends TbMapLayer { } +class TbCartoMapLayer extends TbMapLayer { + + constructor(protected ctx: WidgetContext, + protected inputSettings: DeepPartial) { + super(ctx, inputSettings); + } + + protected defaultSettings(): CartoMapLayerSettings { + return defaultCartoMapLayerSettings; + } + + protected createLayer(): Observable { + const layer = L.tileLayer.provider(this.settings.layerType, {apikey: this.settings.apiKey || ''}); + return of(layer); + } + +} + class TbGoogleMapLayer extends TbMapLayer { static loadedApiKeysGlobal: {[key: string]: boolean} = {}; @@ -293,7 +318,7 @@ class TbHereMapLayer extends TbMapLayer { protected createLayer(): Observable { const apiKey = this.settings.apiKey || defaultHereMapLayerSettings.apiKey; - const layer = L.tileLayer.provider(this.settings.layerType, {useV3: true, apiKey} as any); + const layer = L.tileLayer.provider(hereV3Provider(this.settings.layerType), {apiKey}); return of(layer); } @@ -311,7 +336,9 @@ class TbCustomMapLayer extends TbMapLayer { } protected createLayer(): Observable { - const layer = L.tileLayer(this.settings.tileUrl); + const layer = L.tileLayer(this.settings.tileUrl, this.settings.customAttribution ? { + attribution: this.settings.customAttribution + } : undefined); return of(layer); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html index e19007a1e5..02ddc00901 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html @@ -23,6 +23,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts index 9680188046..93ed9be3f1 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts @@ -25,6 +25,8 @@ import { TbPopoverService } from '@shared/components/popover.service'; import { TranslateService } from '@ngx-translate/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -35,6 +37,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, tencentLayerTranslationMap, @@ -71,6 +75,10 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -110,6 +118,7 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] }); @@ -202,12 +211,15 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html index cdf24fd07c..a65dc5bf18 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html @@ -33,6 +33,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + @@ -62,12 +70,18 @@
-
+
+
widgets.maps.layer.provider.custom.attribution
+ + + +
+
widgets.maps.layer.credentials.credentials
widgets.maps.layer.credentials.api-key
- +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts index bddca3f360..5e4866df9c 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts @@ -5,6 +5,8 @@ import { TbPopoverComponent } from '@shared/components/popover.component'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -15,6 +17,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, referenceLayerTypes, referenceLayerTypeTranslationMap, tencentLayerTranslationMap, @@ -42,6 +46,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -81,6 +89,7 @@ export class MapLayerSettingsPanelComponent implements OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] } @@ -108,6 +117,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { return this.translate.instant(translationKey); } + hasApiKey(): boolean { + return mapProviderHasApiKey(this.layerFormGroup.get('provider').value); + } + applyLayerSettings() { const layerSettings: MapLayerSettings = this.layerFormGroup.value; this.mapLayerSettingsApplied.emit(layerSettings); @@ -126,12 +139,15 @@ export class MapLayerSettingsPanelComponent implements OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts index d6ac020c42..a73c9bfbb5 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts @@ -20,7 +20,8 @@ import { MapLayerSettings, mapLayerValid, mapLayerValidator, - MapProvider + MapProvider, + normalizeMapLayerSettings } from '@shared/models/widget/maps/map.models'; @Component({ @@ -93,7 +94,7 @@ export class MapLayersComponent implements ControlValueAccessor, OnInit, Validat } writeValue(value: MapLayerSettings[] | undefined): void { - const layers: MapLayerSettings[] = value || []; + const layers: MapLayerSettings[] = (value || []).map(layer => normalizeMapLayerSettings(layer)); this.layersFormGroup.setControl('layers', this.prepareLayersFormArray(layers), {emitEvent: false}); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html index d95bb0daa3..2131e54bdf 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html @@ -16,25 +16,10 @@
widgets.maps.credentials - - {{ 'widgets.maps.here-use-new-version-api-3' | translate }} - -
- - widgets.maps.here-app-id - - - - widgets.maps.here-app-code - - -
- - - widgets.maps.here-api-key - - - + + widgets.maps.here-api-key + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts index 823840b624..14d5236473 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts @@ -16,11 +16,11 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { TranslateService } from '@ngx-translate/core'; import { + defaultHereMapProviderSettings, HereMapProvider, HereMapProviderSettings, hereMapProviderTranslationMap } from '@home/components/widget/lib/maps-legacy/map-models'; -import { isDefinedAndNotNull } from '@core/utils'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({ @@ -67,25 +67,9 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup = this.fb.group({ mapProviderHere: [null, [Validators.required]], credentials: this.fb.group({ - useV3: [true], - app_id: [null, [Validators.required]], - app_code: [null, [Validators.required]], apiKey: [null, [Validators.required]] }) }); - this.providerSettingsFormGroup.get('credentials.useV3').valueChanges.pipe( - takeUntilDestroyed(this.destroyRef) - ).subscribe(value => { - if (value) { - this.providerSettingsFormGroup.get('credentials.apiKey').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').disable({emitEvent: false}); - } else { - this.providerSettingsFormGroup.get('credentials.apiKey').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').enable({emitEvent: false}); - } - }); this.providerSettingsFormGroup.valueChanges.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(() => { @@ -106,21 +90,17 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup.disable({emitEvent: false}); } else { this.providerSettingsFormGroup.enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); } } writeValue(value: HereMapProviderSettings): void { - if (!isDefinedAndNotNull(value.credentials.useV3)) { - if (isDefinedAndNotNull(value.credentials.app_id) && isDefinedAndNotNull(value.credentials.app_code)) { - value.credentials.useV3 = false; - } - } this.modelValue = value; - this.providerSettingsFormGroup.patchValue( - value, {emitEvent: false} - ); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); + this.providerSettingsFormGroup.patchValue({ + mapProviderHere: value?.mapProviderHere, + credentials: { + apiKey: value?.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey + } + }, {emitEvent: false}); } public validate(c: FormControl) { diff --git a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts index 3271c3dc36..a3dbcf63bc 100644 --- a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts +++ b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts @@ -832,6 +832,7 @@ export const defaultMapActionButtonSettings: MapActionButtonSettings = { export enum MapProvider { openstreet = 'openstreet', + carto = 'carto', google = 'google', here = 'here', tencent = 'tencent', @@ -843,6 +844,7 @@ export const mapProviders = Object.keys(MapProvider) as MapProvider[]; export const mapProviderTranslationMap = new Map( [ [MapProvider.openstreet, 'widgets.maps.layer.provider.openstreet.title'], + [MapProvider.carto, 'widgets.maps.layer.provider.carto.title'], [MapProvider.google, 'widgets.maps.layer.provider.google.title'], [MapProvider.here, 'widgets.maps.layer.provider.here.title'], [MapProvider.tencent, 'widgets.maps.layer.provider.tencent.title'], @@ -880,6 +882,9 @@ export const mapLayerValid = (layer: MapLayerSettings): boolean => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return !!openStreetLayer.layerType; + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return !!cartoLayer.layerType; case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return !!googleLayer.layerType; @@ -913,6 +918,9 @@ export const defaultLayerTitle = (layer: MapLayerSettings): string => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return openStreetMapLayerTranslationMap.get(openStreetLayer.layerType); + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return cartoLayerTranslationMap.get(cartoLayer.layerType); case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return googleMapLayerTranslationMap.get(googleLayer.layerType); @@ -932,9 +940,7 @@ export enum OpenStreetLayerType { openStreetHot = 'OpenStreetMap.HOT', esriWorldStreetMap = 'Esri.WorldStreetMap', esriWorldTopoMap = 'Esri.WorldTopoMap', - esriWorldImagery = 'Esri.WorldImagery', - cartoDbPositron = 'CartoDB.Positron', - cartoDbDarkMatter = 'CartoDB.DarkMatter' + esriWorldImagery = 'Esri.WorldImagery' } export const openStreetLayerTypes = Object.values(OpenStreetLayerType) as OpenStreetLayerType[]; @@ -945,9 +951,7 @@ export const openStreetMapLayerTranslationMap = new Map( + [ + [CartoLayerType.cartoPositron, 'widgets.maps.layer.provider.carto.positron'], + [CartoLayerType.cartoDarkMatter, 'widgets.maps.layer.provider.carto.dark-matter'] + ] +); + +export interface CartoMapLayerSettings extends MapLayerSettings { + provider: MapProvider.carto; + layerType: CartoLayerType; + apiKey?: string; +} + +export const defaultCartoMapLayerSettings: CartoMapLayerSettings = { + provider: MapProvider.carto, + layerType: CartoLayerType.cartoPositron, + apiKey: null +} + export enum GoogleLayerType { roadmap = 'roadmap', satellite = 'satellite', @@ -1021,6 +1051,16 @@ export const defaultHereMapLayerSettings: HereMapLayerSettings = { apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } +const hereV3Variants: {[v2Variant: string]: string} = { + normalDay: 'exploreDay', + normalNight: 'exploreNight', + hybridDay: 'exploreSatelliteDay', + terrainDay: 'topoDay' +}; + +export const hereV3Provider = (layerType: string): string => + `HERE.${hereV3Variants[layerType?.split('.')[1]] || hereV3Variants.normalDay}`; + export enum TencentLayerType { tencentNormal = 'Tencent.Normal', tencentSatellite = 'Tencent.Satellite', @@ -1050,6 +1090,7 @@ export const defaultTencentMapLayerSettings: TencentMapLayerSettings = { export interface CustomMapLayerSettings extends MapLayerSettings { provider: MapProvider.custom; tileUrl: string; + customAttribution?: string; } export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { @@ -1057,10 +1098,29 @@ export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { tileUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' } +export const mapProviderHasApiKey = (provider: MapProvider): boolean => + [MapProvider.carto, MapProvider.google, MapProvider.here].includes(provider); + +export const mapProviderRequiresApiKey = (provider: MapProvider): boolean => + [MapProvider.google, MapProvider.here].includes(provider); + +const legacyOpenStreetCartoLayerTypes = new Set(cartoLayerTypes); + +// CARTO layers used to be stored under the OpenStreetMap provider, keep reading them as CARTO layers +export const normalizeMapLayerSettings = (layer: MapLayerSettings): MapLayerSettings => { + if (layer?.provider === MapProvider.openstreet && + legacyOpenStreetCartoLayerTypes.has((layer as OpenStreetMapLayerSettings).layerType)) { + return {...layer, provider: MapProvider.carto}; + } + return layer; +}; + export const defaultMapLayerSettings = (provider: MapProvider): MapLayerSettings => { switch (provider) { case MapProvider.openstreet: return defaultOpenStreetMapLayerSettings; + case MapProvider.carto: + return defaultCartoMapLayerSettings; case MapProvider.google: return defaultGoogleMapLayerSettings; case MapProvider.here: diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index b5f51fd6d4..b3aa95d6ec 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -8563,9 +8563,12 @@ "hot": "HOT", "esri-street": "WorldStreetMap", "esri-topo": "WorldTopoMap", - "esri-imagery": "WorldImagery", - "cartodb-positron": "Positron", - "cartodb-dark-matter": "DarkMatter" + "esri-imagery": "WorldImagery" + }, + "carto": { + "title": "CARTO", + "positron": "Positron", + "dark-matter": "DarkMatter" }, "google": { "title": "Google", @@ -8589,7 +8592,9 @@ }, "custom": { "title": "Custom", - "tile-url": "Tile URL" + "tile-url": "Tile URL", + "attribution": "Copyright text", + "attribution-hint": "Displayed at the bottom of the map. Required by most tile providers." } }, "credentials": { @@ -8866,10 +8871,7 @@ "here-map-hybrid-day": "HERE.hybridDay", "here-map-terrain-day": "HERE.terrainDay", "credentials": "Credentials", - "here-app-id": "HERE app id", - "here-app-code": "HERE app code", "here-api-key": "HERE API key", - "here-use-new-version-api-3": "Use API version 3", "tencent-maps-api-key": "Tencent Maps API Key", "tencent-map-type-roadmap": "Roadmap", "tencent-map-type-satelite": "Satellite", diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 7d184f78dc..9b6453cd01 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -7576,10 +7576,10 @@ leaflet-polylinedecorator@1.6.0: dependencies: leaflet-rotatedmarker "^0.2.0" -leaflet-providers@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-2.0.0.tgz#dfdab9ca2dccc57c79e1462bc3dd20f78910afcb" - integrity sha512-CWwKEnHd66Qsx0m4o5q5ZOa60s00B91pMxnlr4Y22msubfs7dhbZhdMIz8bvZQkrZqi67ppI1fsZRS6vtrLcOA== +leaflet-providers@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-4.0.0.tgz#a98c5631a671c366739d8658e40be1d02e2c57cb" + integrity sha512-4m3Q4t0e+cHVNIPzlkW9HFWEgplImFRv8cnUFJYOfFoS6p2KosAfmh2Do6qk4HMdqutqbHMpv3F7sn/CUSw6oQ== leaflet-rotatedmarker@^0.2.0: version "0.2.0" From 84c1cfb26aca80d024738e4a8feaa718d7f05008 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 050/119] Bump jackson-bom from 2.21.5 to 2.21.6 to fix CVE-2026-68497 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a1136afd0f..37e3afe09f 100755 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 10.1.59 5.4.3 1.5.38 - 2.21.5 + 2.21.6 42.7.12 5.33.1 5.6.4 From 6e3818f83374ed17728c70cbdf3faba15603ea74 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 051/119] Bump amqp-client from 5.33.1 to 5.34.0 to fix CVE-2026-75516 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 37e3afe09f..157cd042ea 100755 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ 1.5.38 2.21.6 42.7.12 - 5.33.1 + 5.34.0 5.6.4 2.4.0-b180830.0359 0.12.5 From b16701288fde7d67bcd69c6107d803d6007735b2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 052/119] Bump wire-schema from 6.3.0 to 6.4.5 to fix CVE-2026-63126 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 157cd042ea..76b2c8ae4d 100755 --- a/pom.xml +++ b/pom.xml @@ -142,7 +142,7 @@ 1.11.0 4.4 1.0.4TB - 6.3.0 + 6.4.5 10.1.3 3.7.4 4.0.2 From ebebc194cbb8b54728322b1f9a64e371809370e3 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 10:28:38 +0300 Subject: [PATCH 053/119] Bump zstd-jni from 1.5.6-4 to 1.5.7-14 to fix CVE-2026-87795, CVE-2026-87823, and 5 others --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 76b2c8ae4d..db90bce5f5 100755 --- a/pom.xml +++ b/pom.xml @@ -77,6 +77,7 @@ 42.7.12 5.34.0 5.6.4 + 1.5.7-14 2.4.0-b180830.0359 0.12.5 0.10 @@ -1114,6 +1115,13 @@ ${httpclient5.version} + + + com.github.luben + zstd-jni + ${zstd-jni.version} + + org.springframework.boot spring-boot-dependencies From 0bc466a165c755fa8ce221665df1b1a8f28164ec Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Fri, 25 Sep 2026 10:45:58 +0300 Subject: [PATCH 054/119] Bump npm dependencies to fix CVE-2026-90711, CVE-2026-17495, CVE-2026-87776, and CVE-2026-84375 - proxy-addr 2.0.7 -> 2.0.8 (CVE-2026-90711, GHSA-jqcg-44mw-7w3h) - moment 2.30.1 -> 2.31.0 (CVE-2026-17495, GHSA-4p3w-j4w9-5jqw) - compression 1.8.1 -> 1.8.2 (CVE-2026-87776, GHSA-vc2v-76pw-4v95) - js-yaml 4.3.1 -> 4.3.2 in ui-ngx (CVE-2026-84375, GHSA-2883-xcg3-v3hh) --- msa/js-executor/yarn.lock | 12 ++++++------ msa/web-ui/package.json | 2 +- msa/web-ui/yarn.lock | 26 ++++++++++++++++---------- ui-ngx/package.json | 2 +- ui-ngx/yarn.lock | 27 ++++++++++++++------------- 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/msa/js-executor/yarn.lock b/msa/js-executor/yarn.lock index e4f6409a3d..bb1095b947 100644 --- a/msa/js-executor/yarn.lock +++ b/msa/js-executor/yarn.lock @@ -1170,9 +1170,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@^2.1.1, ms@^2.1.3: version "2.1.3" @@ -1332,9 +1332,9 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index e0099bbdc5..f557b40769 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -13,7 +13,7 @@ "build": "tsc" }, "dependencies": { - "compression": "^1.8.1", + "compression": "^1.8.2", "config": "^3.3.12", "connect-history-api-fallback": "1.6.0", "express": "^5.1.0", diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index 3e96bc2e85..ca2d727bf8 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -511,14 +511,15 @@ compressible@~2.0.18: dependencies: mime-db ">= 1.43.0 < 2" -compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== +compression@^1.8.2: + version "1.8.2" + resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" + integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== dependencies: bytes "3.1.2" compressible "~2.0.18" debug "2.6.9" + destroy "1.2.0" negotiator "~0.6.4" on-headers "~1.1.0" safe-buffer "5.2.1" @@ -604,6 +605,11 @@ depd@2.0.0, depd@^2.0.0: resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== +destroy@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" + integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== + detect-libc@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.4.tgz#f04715b8ba815e53b4d8109655b6508a6865a7e8" @@ -1127,9 +1133,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@2.0.0: version "2.0.0" @@ -1304,9 +1310,9 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" diff --git a/ui-ngx/package.json b/ui-ngx/package.json index c410d5bed4..ab946678a2 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -67,7 +67,7 @@ "libphonenumber-js": "^1.12.35", "maplibre-gl": "5.2.0", "marked": "~16.4.2", - "moment": "^2.30.1", + "moment": "^2.31.0", "moment-timezone": "^0.6.0", "ngx-clipboard": "^16.0.0", "ngx-daterangepicker-material": "^6.0.4", diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 9b6453cd01..a70a3e66fb 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -4861,13 +4861,14 @@ compressible@~2.0.18: mime-db ">= 1.43.0 < 2" compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== + version "1.8.2" + resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" + integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== dependencies: bytes "3.1.2" compressible "~2.0.18" debug "2.6.9" + destroy "1.2.0" negotiator "~0.6.4" on-headers "~1.1.0" safe-buffer "5.2.1" @@ -7363,9 +7364,9 @@ js-tokens@^4.0.0: integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^4.1.0, js-yaml@^4.3.0: - version "4.3.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.1.tgz#01216c001d67f48e2cd560d708c7af21090a3848" - integrity sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ== + version "4.3.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.2.tgz#8e44fb14a2643c59726bb15787b5f1512cb3d3fb" + integrity sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA== dependencies: argparse "^2.0.1" @@ -8104,10 +8105,10 @@ moment-timezone@^0.6.0: dependencies: moment "^2.29.4" -moment@^2.29.4, moment@^2.30.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== +moment@^2.29.4, moment@^2.31.0: + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== moo@^0.5.1: version "0.5.2" @@ -9110,9 +9111,9 @@ protocol-buffers-schema@^3.3.1: integrity sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw== proxy-addr@^2.0.7, proxy-addr@~2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" From a0684dc65f3ea7fce9fa807c6fa371659a232ce6 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Fri, 25 Sep 2026 10:45:58 +0300 Subject: [PATCH 055/119] Bump maplibre-gl from 5.2.0 to 6.11.2 to fix CVE-2026-85061 Fixes the XSS sanitizer bypass in DOM.sanitize() (GHSA-jrc7-96c5-q579, maplibre-gl <= 6.4.0). - v6 removed the internal map.transform: sync the GL map with Leaflet through the public jumpTo() and detect resizes from the container size - v6 is ESM-only and the worker must be registered via setWorkerUrl(): copy maplibre-gl-worker.mjs and its maplibre-gl-shared.mjs dependency to assets/maplibre-gl/ --- ui-ngx/angular.json | 10 + ui-ngx/package.json | 2 +- .../widget/lib/maps/leaflet/leaflet-tb.ts | 19 +- ui-ngx/yarn.lock | 262 +++++++----------- 4 files changed, 113 insertions(+), 180 deletions(-) diff --git a/ui-ngx/angular.json b/ui-ngx/angular.json index 08ffdd7b9a..49af337a74 100644 --- a/ui-ngx/angular.json +++ b/ui-ngx/angular.json @@ -77,6 +77,16 @@ "input": "node_modules/hugerte", "output": "/assets/hugerte/" }, + { + "glob": "maplibre-gl-worker.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, + { + "glob": "maplibre-gl-shared.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, { "glob": "marker-icon-2x.png", "input": "node_modules/leaflet/dist/images/", diff --git a/ui-ngx/package.json b/ui-ngx/package.json index ab946678a2..f72456f0a3 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -65,7 +65,7 @@ "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.12.35", - "maplibre-gl": "5.2.0", + "maplibre-gl": "6.11.2", "marked": "~16.4.2", "moment": "^2.31.0", "moment-timezone": "^0.6.0", diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts index 9ad91048d7..d092a0078f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts @@ -3,7 +3,7 @@ import L, { TB } from 'leaflet'; import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils'; import 'leaflet-providers'; -import { Map as MapLibreGLMap, LngLat as MapLibreGLLngLat } from 'maplibre-gl'; +import { Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; import '@geoman-io/leaflet-geoman-free'; import 'leaflet.markercluster'; import { MatIconRegistry } from '@angular/material/icon'; @@ -1070,6 +1070,9 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay return new ChinaProvider(type, options); } +// The worker is copied to assets by angular.json, bundlers cannot resolve it from import.meta.url +setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); + class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { options: TB.MapLibreGL.LeafletMapLibreGLMapOptions; @@ -1246,23 +1249,19 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { this._transformGL(gl); - if (gl.transform.width !== size.x || gl.transform.height !== size.y) { + if (container.clientWidth !== size.x || container.clientHeight !== size.y) { container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; gl.resize(); - } else { - gl._update(); } } private _transformGL(gl: MapLibreGLMap) { const center = this._map.getCenter(); - const tr = gl._getTransformForUpdate(); - if (!tr) { return; } - tr.setCenter(MapLibreGLLngLat.convert([center.lng, center.lat])); - tr.setZoom(this._map.getZoom() - 1); - gl.transform.apply(tr); - gl._fireMoveEvents(); + gl.jumpTo({ + center: [center.lng, center.lat], + zoom: this._map.getZoom() - 1 + }); } private _pinchZoom() { diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index a70a3e66fb..fdb5a6da01 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -2115,59 +2115,70 @@ resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-3.4.2.tgz#99caf114bb74d39c9e1baca99b907353ad8bf461" integrity sha512-IY+r3bxKW6Q6sIPiMC0L533DEfRJSXibjSI3Ft/w9Q8KQBNqEIvUFXt+09wV8S5BRk0a8uSF19YWxuRwEfI90g== -"@mapbox/geojson-rewind@^0.5.2": - version "0.5.2" - resolved "https://registry.yarnpkg.com/@mapbox/geojson-rewind/-/geojson-rewind-0.5.2.tgz#591a5d71a9cd1da1a0bf3420b3bea31b0fc7946a" - integrity sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA== - dependencies: - get-stream "^6.0.1" - minimist "^1.2.6" - -"@mapbox/jsonlint-lines-primitives@^2.0.2", "@mapbox/jsonlint-lines-primitives@~2.0.2": - version "2.0.2" - resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz#ce56e539f83552b58d10d672ea4d6fc9adc7b234" - integrity sha512-rY0o9A5ECsTQRVhv7tL/OyDpGAoUB4tTvLiW1DSzQGq4bvTPhNw1VpSNjDJc5GFZ2XuyOtSWSVN05qOtcD71qQ== +"@mapbox/jsonlint-lines-primitives@^2.0.3": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz#7d7b0b971fbaf6d60953272db4df03020d3fb004" + integrity sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg== -"@mapbox/point-geometry@0.1.0", "@mapbox/point-geometry@^0.1.0", "@mapbox/point-geometry@~0.1.0": - version "0.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-0.1.0.tgz#8a83f9335c7860effa2eeeca254332aa0aeed8f2" - integrity sha512-6j56HdLTwWGO0fJPlrZtdU/B13q8Uwmo18Ck2GnGgN9PCFyKTZ3UbXeEdRFh18i9XQ92eH2VdtpJHpBD3aripQ== +"@mapbox/point-geometry@^1.1.0", "@mapbox/point-geometry@~1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz#3328fb54b3a1273bc619bf0a6baad8de37181749" + integrity sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ== -"@mapbox/tiny-sdf@^2.0.6": - version "2.0.7" - resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.0.7.tgz#0d67d65a43195003b282764f2297c619736bbc6e" - integrity sha512-25gQLQMcpivjOSA40g3gO6qgiFPDpWRoMfd+G/GoppPIeP6JDaMMkMrEJnMZhKyyS6iKwVt5YKu02vCUyJM3Ug== +"@mapbox/tiny-sdf@^2.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz#95dae0dc371b8c55c53d70f3e25d56823427f4c8" + integrity sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg== -"@mapbox/unitbezier@^0.0.1": - version "0.0.1" - resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz#d32deb66c7177e9e9dfc3bbd697083e2e657ff01" - integrity sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw== +"@mapbox/unitbezier@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz#54319aff6c467bb1b909e04895c08cdb966bfbff" + integrity sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ== -"@mapbox/vector-tile@^1.3.1": - version "1.3.1" - resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-1.3.1.tgz#d3a74c90402d06e89ec66de49ec817ff53409666" - integrity sha512-MCEddb8u44/xfQ3oD+Srl/tNcQoqTw3goGk2oLsrFxOTc3dUp+kAnby3PvAeeBYSMSjSPD1nd1AJA6W49WnoUw== +"@mapbox/vector-tile@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz#71a75acb5ee20c20adca5c4e1ffb5ef95a56e351" + integrity sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q== dependencies: - "@mapbox/point-geometry" "~0.1.0" + "@mapbox/point-geometry" "~1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.0.0" -"@mapbox/whoots-js@^3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz#497c67a1cef50d1a2459ba60f315e448d2ad87fe" - integrity sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q== +"@maplibre/geojson-vt@^6.1.1": + version "6.1.1" + resolved "https://registry.yarnpkg.com/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz#25a032435b4ce2236ea0ba911aff5fb6d5454fc1" + integrity sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ== + dependencies: + kdbush "^4.1.0" -"@maplibre/maplibre-gl-style-spec@^23.1.0": - version "23.3.0" - resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-23.3.0.tgz#b69ab48cb3abead4e49213396c8f83492638b97c" - integrity sha512-IGJtuBbaGzOUgODdBRg66p8stnwj9iDXkgbYKoYcNiiQmaez5WVRfXm4b03MCDwmZyX93csbfHFWEJJYHnn5oA== +"@maplibre/maplibre-gl-style-spec@^26.4.4": + version "26.4.4" + resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz#e103d50f9eed8a44f1fde1c4970c5d2a47b19b78" + integrity sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA== dependencies: - "@mapbox/jsonlint-lines-primitives" "~2.0.2" - "@mapbox/unitbezier" "^0.0.1" + "@mapbox/jsonlint-lines-primitives" "^2.0.3" + "@mapbox/unitbezier" "^1.0.0" json-stringify-pretty-compact "^4.0.0" minimist "^1.2.8" quickselect "^3.0.0" - rw "^1.3.3" tinyqueue "^3.0.0" +"@maplibre/mlt@^1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@maplibre/mlt/-/mlt-1.3.0.tgz#3a9467d12a0b6edfcdba429dd3a260ca48f11129" + integrity sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + +"@maplibre/vt-pbf@^4.3.2": + version "4.3.2" + resolved "https://registry.yarnpkg.com/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz#cfcdbdadaf88b4cb8645e43c8eead77cd6546030" + integrity sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.1.0" + "@mat-datetimepicker/core@~16.0.1": version "16.0.1" resolved "https://registry.yarnpkg.com/@mat-datetimepicker/core/-/core-16.0.1.tgz#f2b19b6ed85f83a83f93be866af1a9564ac0d978" @@ -3503,13 +3514,6 @@ resolved "https://registry.yarnpkg.com/@types/flowjs/-/flowjs-2.13.14.tgz#62cdd8d5d8e0222e505e4a140e73cd385c0a496c" integrity sha512-OlZFH9hbOq5B+GeBjcM3UvvSailseRT+sKoi9jyFFczvvS1n1LTiTKJysDSLVWnUvGD+tsn7kxb6eC2uaJD+Zw== -"@types/geojson-vt@3.2.5": - version "3.2.5" - resolved "https://registry.yarnpkg.com/@types/geojson-vt/-/geojson-vt-3.2.5.tgz#b6c356874991d9ab4207533476dfbcdb21e38408" - integrity sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g== - dependencies: - "@types/geojson" "*" - "@types/geojson@*", "@types/geojson@^7946.0.10", "@types/geojson@^7946.0.16": version "7946.0.16" resolved "https://registry.yarnpkg.com/@types/geojson/-/geojson-7946.0.16.tgz#8ebe53d69efada7044454e3305c19017d97ced2a" @@ -3594,20 +3598,6 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.23.tgz#c1bb06db218acc8fc232da0447473fc2fb9d9841" integrity sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA== -"@types/mapbox__point-geometry@*", "@types/mapbox__point-geometry@^0.1.4": - version "0.1.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz#0ef017b75eedce02ff6243b4189210e2e6d5e56d" - integrity sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA== - -"@types/mapbox__vector-tile@^1.3.4": - version "1.3.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__vector-tile/-/mapbox__vector-tile-1.3.4.tgz#ad757441ef1d34628d9e098afd9c91423c1f8734" - integrity sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg== - dependencies: - "@types/geojson" "*" - "@types/mapbox__point-geometry" "*" - "@types/pbf" "*" - "@types/mime@^1": version "1.3.5" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.5.tgz#1ef302e01cf7d2b5a0fa526790c9123bf1d06690" @@ -3625,11 +3615,6 @@ dependencies: undici-types "~6.21.0" -"@types/pbf@*", "@types/pbf@^3.0.5": - version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/pbf/-/pbf-3.0.5.tgz#a9495a58d8c75be4ffe9a0bd749a307715c07404" - integrity sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA== - "@types/qs@*": version "6.9.16" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.16.tgz#52bba125a07c0482d26747d5d4947a64daf8f794" @@ -3686,13 +3671,6 @@ dependencies: "@types/node" "*" -"@types/supercluster@^7.1.3": - version "7.1.3" - resolved "https://registry.yarnpkg.com/@types/supercluster/-/supercluster-7.1.3.tgz#1a1bc2401b09174d9c9e44124931ec7874a72b27" - integrity sha512-Z0pOY34GDFl3Q6hUFYf3HkTwKEE02e7QgtJppBt+beEAxnyOpJua+voGFvxINBHa06GwLFFym7gRPY2SiKIfIA== - dependencies: - "@types/geojson" "*" - "@types/systemjs@6.15.3": version "6.15.3" resolved "https://registry.yarnpkg.com/@types/systemjs/-/systemjs-6.15.3.tgz#d758dceafee62d2ed4aad7d07342b145d623e260" @@ -4437,6 +4415,13 @@ beasties@0.3.5: postcss "^8.4.49" postcss-media-query-parser "^0.2.3" +bidi-js@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/bidi-js/-/bidi-js-1.1.0.tgz#c92efafe3fce3b9fdd30ba67bdddf0dd4d424af7" + integrity sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg== + dependencies: + require-from-string "^2.0.2" + big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -5606,10 +5591,10 @@ dunder-proto@^1.0.0, dunder-proto@^1.0.1: es-errors "^1.3.0" gopd "^1.2.0" -earcut@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.0.2.tgz#d478a29aaf99acf418151493048aa197d0512248" - integrity sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ== +earcut@^3.2.3: + version "3.2.3" + resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.2.3.tgz#74aec19555a7e28773429826729d2e4bfeb19022" + integrity sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q== eastasianwidth@^0.2.0: version "0.2.0" @@ -6483,11 +6468,6 @@ gensync@^1.0.0-beta.2: resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== -geojson-vt@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/geojson-vt/-/geojson-vt-4.0.2.tgz#1162f6c7d61a0ba305b1030621e6e111f847828a" - integrity sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A== - get-caller-file@^2.0.1, get-caller-file@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" @@ -6522,11 +6502,6 @@ get-proto@^1.0.1: dunder-proto "^1.0.1" es-object-atoms "^1.0.0" -get-stream@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - get-symbol-description@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.1.0.tgz#7bdd54e0befe8ffc9f3b4e203220d9f1e881b6ee" @@ -6536,7 +6511,7 @@ get-symbol-description@^1.1.0: es-errors "^1.3.0" get-intrinsic "^1.2.6" -gl-matrix@^3.4.3: +gl-matrix@^3.4.4: version "3.4.4" resolved "https://registry.yarnpkg.com/gl-matrix/-/gl-matrix-3.4.4.tgz#7789ee4982f62c7a7af447ee488f3bd6b0c77003" integrity sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ== @@ -6586,15 +6561,6 @@ glob@^13.0.0: minipass "^7.1.2" path-scurry "^2.0.0" -global-prefix@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-4.0.0.tgz#e9cc79aab9be1d03287e156a3f912dd0895463ed" - integrity sha512-w0Uf9Y9/nyHinEk5vMJKRie+wa4kR5hmDbEhGGds/kG1PwGLLHKRoNMeJOyCQjjBkANlnScqgzcFwGHgmgLkVA== - dependencies: - ini "^4.1.3" - kind-of "^6.0.3" - which "^4.0.0" - globals@^14.0.0: version "14.0.0" resolved "https://registry.yarnpkg.com/globals/-/globals-14.0.0.tgz#898d7413c29babcf6bafe56fcadded858ada724e" @@ -6853,11 +6819,6 @@ icss-utils@^5.0.0, icss-utils@^5.1.0: resolved "https://registry.yarnpkg.com/icss-utils/-/icss-utils-5.1.0.tgz#c6be6858abd013d768e98366ae47e25d5887b1ae" integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA== -ieee754@^1.1.12: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" - integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== - ignore-walk@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-8.0.0.tgz#380c173badc3a18c57ff33440753f0052f572b14" @@ -6918,11 +6879,6 @@ ini@^1.3.4: resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== -ini@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/ini/-/ini-4.1.3.tgz#4c359675a6071a46985eb39b14e4a2c0ec98a795" - integrity sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg== - ini@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/ini/-/ini-6.0.0.tgz#efc7642b276f6a37d22fdf56ef50889d7146bf30" @@ -7511,10 +7467,10 @@ katex@^0.16.0, katex@^0.16.25: dependencies: commander "^8.3.0" -kdbush@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.0.2.tgz#2f7b7246328b4657dd122b6c7f025fbc2c868e39" - integrity sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA== +kdbush@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.1.0.tgz#d504bc0447a59be4fb75533a5c25e316b3ed8859" + integrity sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ== keyv@^4.5.4: version "4.5.4" @@ -7528,7 +7484,7 @@ khroma@^2.1.0: resolved "https://registry.yarnpkg.com/khroma/-/khroma-2.1.0.tgz#45f2ce94ce231a437cf5b63c2e886e6eb42bbbb1" integrity sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw== -kind-of@^6.0.2, kind-of@^6.0.3: +kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== @@ -7825,37 +7781,29 @@ make-plural@^7.0.0: resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-7.4.0.tgz#fa6990dd550dea4de6b20163f74e5ed83d8a8d6d" integrity sha512-4/gC9KVNTV6pvYg2gFeQYTW3mWaoJt7WZE5vrp1KnQDgW92JtYZnzmZT81oj/dUTqAIu0ufI2x3dkgu3bB1tYg== -maplibre-gl@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-5.2.0.tgz#e3cdb66c82232cffbe149b032776484722caee4e" - integrity sha512-9zZKD0M80qtDsqBet+EDuAhoCeA/cnAuZAA0p3hcGKGbyjM/SH+R6wQvnBEgvJz9UhDynnkoKdUwhI+fUkHoXQ== - dependencies: - "@mapbox/geojson-rewind" "^0.5.2" - "@mapbox/jsonlint-lines-primitives" "^2.0.2" - "@mapbox/point-geometry" "^0.1.0" - "@mapbox/tiny-sdf" "^2.0.6" - "@mapbox/unitbezier" "^0.0.1" - "@mapbox/vector-tile" "^1.3.1" - "@mapbox/whoots-js" "^3.1.0" - "@maplibre/maplibre-gl-style-spec" "^23.1.0" +maplibre-gl@6.11.2: + version "6.11.2" + resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-6.11.2.tgz#25f1266666c16f6b935cabccba554c238a3cf394" + integrity sha512-Xh06pxoipjX/Ad1sUPGhiNh9go9naCNGZZ1IJm3sIeqK1kYGuMaMDSTIGDQ2igOLfVyukJU7kvEOA089VO7Z7g== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@mapbox/tiny-sdf" "^2.2.0" + "@mapbox/unitbezier" "^1.0.0" + "@mapbox/vector-tile" "^3.0.0" + "@maplibre/geojson-vt" "^6.1.1" + "@maplibre/maplibre-gl-style-spec" "^26.4.4" + "@maplibre/mlt" "^1.3.0" + "@maplibre/vt-pbf" "^4.3.2" "@types/geojson" "^7946.0.16" - "@types/geojson-vt" "3.2.5" - "@types/mapbox__point-geometry" "^0.1.4" - "@types/mapbox__vector-tile" "^1.3.4" - "@types/pbf" "^3.0.5" - "@types/supercluster" "^7.1.3" - earcut "^3.0.1" - geojson-vt "^4.0.2" - gl-matrix "^3.4.3" - global-prefix "^4.0.0" - kdbush "^4.0.2" + bidi-js "^1.1.0" + earcut "^3.2.3" + gl-matrix "^3.4.4" + kdbush "^4.1.0" murmurhash-js "^1.0.0" - pbf "^3.3.0" - potpack "^2.0.0" + pbf "^5.1.2" + potpack "^2.1.0" quickselect "^3.0.0" - supercluster "^8.0.1" tinyqueue "^3.0.0" - vt-pbf "^3.1.3" marked@^16.3.0, marked@~16.4.2: version "16.4.2" @@ -8845,12 +8793,11 @@ pathe@^2.0.1, pathe@^2.0.3: resolved "https://registry.yarnpkg.com/pathe/-/pathe-2.0.3.tgz#3ecbec55421685b70a9da872b2cff3e1cbed1716" integrity sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w== -pbf@^3.2.1, pbf@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/pbf/-/pbf-3.3.0.tgz#1790f3d99118333cc7f498de816028a346ef367f" - integrity sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q== +pbf@^5.0.0, pbf@^5.1.0, pbf@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/pbf/-/pbf-5.1.2.tgz#07c427819eda32f02f1ec9741558f61444f2e1c0" + integrity sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w== dependencies: - ieee754 "^1.1.12" resolve-protobuf-schema "^2.1.0" photoswipe@^5.4.4: @@ -9053,7 +9000,7 @@ postinstall-prepare@^2.0.0: resolved "https://registry.yarnpkg.com/postinstall-prepare/-/postinstall-prepare-2.0.0.tgz#2a6867c1a13a05502aa115d0495efbbd778769cb" integrity sha512-lLFwEKdnGLAaRAm8OpXP6HwrXRW+b8Hh9vRhVHZKmCdobd+D21YM38BCDsi3zrePLSe8Tt0H/mbYkh7/ySQQMg== -potpack@^2.0.0: +potpack@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/potpack/-/potpack-2.1.0.tgz#fe548e2f9061e9937f17191c1ab6dd98ca30e02f" integrity sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ== @@ -9495,7 +9442,7 @@ run-parallel@^1.1.9: dependencies: queue-microtask "^1.2.2" -rw@1, rw@^1.3.3: +rw@1: version "1.3.3" resolved "https://registry.yarnpkg.com/rw/-/rw-1.3.3.tgz#3f862dfa91ab766b14885ef4d01124bfda074fb4" integrity sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ== @@ -10172,13 +10119,6 @@ sucrase@^3.35.0: tinyglobby "^0.2.11" ts-interface-checker "^0.1.9" -supercluster@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/supercluster/-/supercluster-8.0.1.tgz#9946ba123538e9e9ab15de472531f604e7372df5" - integrity sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ== - dependencies: - kdbush "^4.0.2" - supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -10787,15 +10727,6 @@ vscode-uri@~3.1.0: resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.1.0.tgz#dd09ec5a66a38b5c3fffc774015713496d14e09c" integrity sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ== -vt-pbf@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/vt-pbf/-/vt-pbf-3.1.3.tgz#68fd150756465e2edae1cc5c048e063916dcfaac" - integrity sha512-2LzDFzt0mZKZ9IpVF2r69G9bXaP2Q2sArJCmcCgvfTdCCZzSyz4aCLoQyUilu37Ll56tCblIZrXFIjNUpGIlmA== - dependencies: - "@mapbox/point-geometry" "0.1.0" - "@mapbox/vector-tile" "^1.3.1" - pbf "^3.2.1" - watchpack@2.4.4: version "2.4.4" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.4.tgz#473bda72f0850453da6425081ea46fc0d7602947" @@ -11025,13 +10956,6 @@ which@^2.0.1: dependencies: isexe "^2.0.0" -which@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/which/-/which-4.0.0.tgz#cd60b5e74503a3fbcfbf6cd6b4138a8bae644c1a" - integrity sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg== - dependencies: - isexe "^3.1.1" - which@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/which/-/which-6.0.0.tgz#a3a721a14cdd9b991a722e493c177eeff82ff32a" From 862b224dd7e4e770804ffad3411255166daa4501 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 16:19:59 +0300 Subject: [PATCH 056/119] Reject non-user JWT scopes on WebSocket API --- .../controller/plugin/TbWebSocketHandler.java | 17 +++++++- .../server/controller/TwoFactorAuthTest.java | 42 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java index a7e3ed4ba9..2e8dda4d32 100644 --- a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java +++ b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.BeanCreationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Service; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.PongMessage; @@ -34,6 +35,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.limit.LimitedApi; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.config.WebSocketConfiguration; import org.thingsboard.server.dao.tenant.TbTenantProfileCache; @@ -55,6 +57,7 @@ import org.thingsboard.server.service.ws.telemetry.cmd.TelemetryCmdsWrapper; import java.io.IOException; import java.security.InvalidParameterException; +import java.util.EnumSet; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -76,6 +79,8 @@ import static org.thingsboard.server.service.ws.DefaultWebSocketService.NUMBER_O @RequiredArgsConstructor public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint { + private static final Set USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER); + private final ConcurrentMap internalSessionMap = new ConcurrentHashMap<>(); private final ConcurrentMap externalSessionMap = new ConcurrentHashMap<>(); @@ -181,7 +186,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke log.trace("{} Authenticating session", sessionRef); SecurityUser securityCtx; try { - securityCtx = authenticationProvider.authenticate(authCmd.getToken()); + securityCtx = authenticate(authCmd.getToken()); } catch (Exception e) { close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage())); return; @@ -317,7 +322,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke SecurityUser securityCtx = null; String token = StringUtils.substringAfter(session.getUri().getQuery(), "token="); if (StringUtils.isNotEmpty(token)) { - securityCtx = authenticationProvider.authenticate(token); + securityCtx = authenticate(token); } return WebSocketSessionRef.builder() .sessionId(UUID.randomUUID().toString()) @@ -328,6 +333,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke .build(); } + private SecurityUser authenticate(String token) { + SecurityUser securityUser = authenticationProvider.authenticate(token); + if (!USER_AUTHORITIES.contains(securityUser.getAuthority())) { + throw new BadCredentialsException("Token is invalid"); + } + return securityUser; + } + private SessionMetaData getSessionMd(String internalSessionId) { SessionMetaData sessionMd = internalSessionMap.get(internalSessionId); if (sessionMd == null) { diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java index 3170d9480f..4618ebf4e0 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java @@ -13,6 +13,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionStatus; @@ -23,6 +25,8 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.query.EntityData; +import org.thingsboard.server.common.data.query.EntityTypeFilter; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.model.JwtPair; import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; @@ -40,6 +44,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; import org.thingsboard.server.service.security.auth.rest.LoginRequest; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.EntityDataUpdate; import java.time.Duration; import java.util.Arrays; @@ -141,6 +146,43 @@ public class TwoFactorAuthTest extends AbstractControllerTest { assertThat(currentUser.getId()).isEqualTo(user.getId()); } + @Test + public void testWsAuthCmd_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + + wsClient = buildAndConnectWebSocketClient(); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWsQueryToken_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + + wsClient = buildAndConnectWebSocketClient("/api/ws?token=" + token); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + Device device = createDevice("2FA device", "2FA device token"); + + EntityTypeFilter deviceFilter = new EntityTypeFilter(); + deviceFilter.setEntityType(EntityType.DEVICE); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(deviceFilter); + + assertThat(update.getData().getData()).singleElement() + .extracting(EntityData::getEntityId).isEqualTo(device.getId()); + } + @Test public void testTwoFaPreVerificationTokenLifetime() throws Exception { configureTotpTwoFa(twoFaSettings -> { From b8628b0c7562a47b45c38b87119ead9fb4a1aa77 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 057/119] Bump io.netty from 4.1.137.Final to 4.1.138.Final to fix CVE-2026-93488, CVE-2026-93491, and 4 others --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index db90bce5f5..304e1874e2 100755 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ entries below once TB migrates its tests off the deprecated @SpyBean/@MockBean to @MockitoSpyBean/@MockitoBean. --> 3.5.13 3.18.0 - 4.1.137.Final + 4.1.138.Final 10.1.59 5.4.3 1.5.38 From b4f24ac998f6a9231585aadbe66da256e13741b8 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 058/119] Bump jackson-bom from 2.21.6 to 2.21.7 to fix CVE-2026-89425 and CVE-2026-91777 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 304e1874e2..d407c6abdd 100755 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 10.1.59 5.4.3 1.5.38 - 2.21.6 + 2.21.7 42.7.12 5.34.0 5.6.4 From b3930b66921aeca13a9bedaf42a1e9244001dc14 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 059/119] Bump zookeeper from 3.9.5 to 3.9.6 to fix CVE-2026-59969 and CVE-2026-84439 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d407c6abdd..31053c56e9 100755 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ 2.0.0-M15 2.0.1 5.6.0 - 3.9.5 + 3.9.6 3.25.5 1.76.0 1.2.10 From c24219461ae6cd050d7e4b12558d2ac65481da65 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 060/119] Bump freemarker from 2.3.34 to 2.3.35 to fix CVE-2026-84939 --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 31053c56e9..76920fadeb 100755 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,7 @@ 5.34.0 5.6.4 1.5.7-14 + 2.3.35 2.4.0-b180830.0359 0.12.5 0.10 @@ -1122,6 +1123,13 @@ ${zstd-jni.version} + + + org.freemarker + freemarker + ${freemarker.version} + + org.springframework.boot spring-boot-dependencies From f2053b3bd663e721b800b79527534bde013af1c2 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 28 Sep 2026 17:39:48 +0200 Subject: [PATCH 061/119] Persist cloud RPC deletes for offline edges, accept post-TIMEOUT retries and parse edge RPC responses safely --- .../server/controller/RpcV2Controller.java | 2 +- .../processor/device/DeviceEdgeProcessor.java | 36 +++++++++++-------- .../server/service/rpc/TbRpcService.java | 20 ++++++----- .../server/common/data/rpc/RpcStatus.java | 5 +++ 4 files changed, 39 insertions(+), 24 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index fc6e93afe1..fefec61c22 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -228,7 +228,7 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToCore(removeMsg, null); } - tbRpcService.deleteRpc(getTenantId(), rpcId); + tbRpcService.deleteRpc(getTenantId(), rpc); rpc.setStatus(RpcStatus.DELETED); TbMsg msg = TbMsg.newMsg() diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index 0362d40e45..7ad1125533 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -142,33 +142,39 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); + if (existingRpc == null) { + // RPC is unknown to the cloud (edge-originated or already deleted) - nothing to sync + log.debug("[{}][{}] Ignoring RPC status [{}] from edge - RPC not found", tenantId, rpcId, deviceRpcCallMsg.getRpcStatus()); + return Futures.immediateFuture(null); + } if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges. - if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { - try { - edgeSynchronizationManager.getEdgeId().set(edge.getId()); - edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); - } finally { - edgeSynchronizationManager.getEdgeId().remove(); - } + try { + edgeSynchronizationManager.getEdgeId().set(edge.getId()); + edgeCtx.getTbRpcService().deleteRpc(tenantId, existingRpc); + } finally { + edgeSynchronizationManager.getEdgeId().remove(); } return Futures.immediateFuture(null); } RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus()); - Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); - if (existingRpc == null) { - return Futures.immediateFuture(null); - } - if (!existingRpc.getStatus().isIntermediate() && rpcStatus.isIntermediate()) { - // guard against out-of-order status uplinks regressing a terminal RPC (e.g. stale DELIVERED after SUCCESSFUL) - log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already terminal [{}]", + if (!existingRpc.getStatus().isIntermediate() && existingRpc.getStatus() != RpcStatus.TIMEOUT && rpcStatus.isIntermediate()) { + // guard against a final RPC regressing to an intermediate status (e.g. stale DELIVERED after SUCCESSFUL). + // TIMEOUT is not final - the device actor retries the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED). + log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already final [{}]", tenantId, rpcId, rpcStatus, existingRpc.getStatus()); return Futures.immediateFuture(null); } JsonNode response = null; if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) { - response = JacksonUtil.toJsonNode(deviceRpcCallMsg.getResponseMsg().getResponse()); + String payload = deviceRpcCallMsg.getResponseMsg().getResponse(); + try { + response = JacksonUtil.toJsonNode(payload); + } catch (IllegalArgumentException e) { + response = JacksonUtil.newObjectNode().put("error", payload); + } } edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response); return Futures.immediateFuture(null); diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index 57322f5600..b0a6a490ee 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -24,7 +24,7 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; -import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; +import org.thingsboard.server.dao.edge.EdgeEventService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; import org.thingsboard.server.dao.rpc.RpcService; @@ -40,6 +40,7 @@ public class TbRpcService { private final RpcService rpcService; private final TbClusterService tbClusterService; private final EdgeService edgeService; + private final EdgeEventService edgeEventService; private final EdgeSynchronizationManager edgeSynchronizationManager; public Rpc save(TenantId tenantId, Rpc rpc) { @@ -80,12 +81,14 @@ public class TbRpcService { return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } - public void deleteRpc(TenantId tenantId, RpcId rpcId) { - Rpc rpc = rpcService.findById(tenantId, rpcId); - rpcService.deleteRpc(tenantId, rpcId); - // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status. - // Skipped when the delete originated from an edge (edge-sync context) so it is not echoed back. - if (rpc != null && edgeSynchronizationManager.getEdgeId().get() == null) { + /** + * The only edge-aware RPC delete: propagates the delete to related edges (Cloud -> Edge) for ANY status. + * Other delete paths (RpcService.deleteRpc, TTL clean-up) intentionally do not sync, so each side expires its own copies. + */ + public void deleteRpc(TenantId tenantId, Rpc rpc) { + rpcService.deleteRpc(tenantId, rpc.getId()); + // skipped when the delete originated from an edge (edge-sync context) so it is not echoed back + if (edgeSynchronizationManager.getEdgeId().get() == null) { pushRpcDeleteToEdges(tenantId, rpc); } } @@ -99,9 +102,10 @@ public class TbRpcService { body.put("requestUUID", rpc.getId().getId().toString()); body.put("rpcStatus", RpcStatus.DELETED.name()); for (EdgeId edgeId : relatedEdgeIds) { + // persisted (not high-priority) so the delete is replayed when the edge reconnects EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE, EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); - tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(tenantId, edgeEvent)); + edgeEventService.saveAsync(edgeEvent); } } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java index f80ad59c35..5a6b04f1ac 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java @@ -15,6 +15,11 @@ public enum RpcStatus { FAILED(false), DELETED(false); + /** + * {@code true} while the RPC is still pending in the device actor (not yet delivered/answered). + * Note: TIMEOUT is not intermediate, but it is not final either - the device actor may retry + * the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED) until retries are exhausted (then FAILED). + */ @Getter private final boolean intermediate; From 45102bc728d429cba6b031328c24aa73969662cb Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 28 Sep 2026 17:39:48 +0200 Subject: [PATCH 062/119] Add edge tests for persistent RPC status and delete sync --- .../server/edge/DeviceEdgeTest.java | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index 070eda60d5..9137724ef8 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -38,14 +38,18 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.rpc.Rpc; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.AttributesRequestMsg; import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; @@ -94,6 +98,9 @@ public class DeviceEdgeTest extends AbstractEdgeTest { @Autowired protected EdgeService edgeService; + @Autowired + protected RpcService rpcService; + @Test public void testDevices() throws Exception { // create device and assign to edge; update device @@ -657,6 +664,118 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(2, latestDeviceRpcCallMsg.getRetries()); } + @Test + public void testRpcV2StatusUpdateFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.QUEUED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.DELIVERED, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "{\"result\":\"ok\"}"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("ok", successful.getResponse().get("result").asText()); + + // stale intermediate status must not regress a final RPC + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.SUCCESSFUL, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2StatusRetryAfterTimeoutFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SENT); + + // TIMEOUT with retries left is followed by a re-delivery + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.TIMEOUT, null); + Assert.assertEquals(RpcStatus.TIMEOUT, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SENT, null); + Assert.assertEquals(RpcStatus.SENT, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2NonJsonResponseFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "not a json"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("not a json", successful.getResponse().get("error").asText()); + } + + @Test + public void testRpcV2StatusForUnknownRpcFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + RpcId unknownRpcId = new RpcId(Uuids.timeBased()); + + sendRpcStatusUplink(device, unknownRpcId, RpcStatus.DELIVERED, null); + doGet("/api/rpc/persistent/" + unknownRpcId.getId()).andExpect(status().isNotFound()); + } + + @Test + public void testRpcV2DeleteFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + edgeImitator.expectMessageAmount(1); + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELETED, null); + doGet("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isNotFound()); + // delete originated from the edge must not be echoed back + Assert.assertFalse(edgeImitator.waitForMessages(1)); + } + + @Test + public void testRpcV2DeleteFromCloud() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SUCCESSFUL); + + edgeImitator.expectMessageAmount(1); + doDelete("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isOk()); + Assert.assertTrue(edgeImitator.waitForMessages()); + + AbstractMessage latestMessage = edgeImitator.getLatestMessage(); + Assert.assertTrue(latestMessage instanceof DeviceRpcCallMsg); + DeviceRpcCallMsg deviceRpcCallMsg = (DeviceRpcCallMsg) latestMessage; + Assert.assertEquals(RpcStatus.DELETED.name(), deviceRpcCallMsg.getRpcStatus()); + Assert.assertEquals(rpc.getUuidId(), new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Assert.assertFalse(deviceRpcCallMsg.hasRequestMsg()); + Assert.assertFalse(deviceRpcCallMsg.hasResponseMsg()); + } + + private Rpc savePersistentRpc(Device device, RpcStatus status) { + Rpc rpc = new Rpc(new RpcId(Uuids.timeBased())); + rpc.setTenantId(tenantId); + rpc.setDeviceId(device.getId()); + rpc.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1)); + rpc.setRequest(JacksonUtil.newObjectNode().put("method", "test_method")); + rpc.setStatus(status); + return rpcService.save(rpc); + } + + private Rpc getPersistentRpc(RpcId rpcId) throws Exception { + return doGet("/api/rpc/persistent/" + rpcId.getId(), Rpc.class); + } + + private void sendRpcStatusUplink(Device device, RpcId rpcId, RpcStatus rpcStatus, String response) throws Exception { + DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() + .setDeviceIdMSB(device.getUuidId().getMostSignificantBits()) + .setDeviceIdLSB(device.getUuidId().getLeastSignificantBits()) + .setRequestUuidMSB(rpcId.getId().getMostSignificantBits()) + .setRequestUuidLSB(rpcId.getId().getLeastSignificantBits()) + .setRpcStatus(rpcStatus.name()); + if (response != null) { + builder.setResponseMsg(RpcResponseMsg.newBuilder().setResponse(response).build()); + } + UplinkMsg uplinkMsg = UplinkMsg.newBuilder().addDeviceRpcCallMsg(builder.build()).build(); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsg); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + private void sendAttributesRequestAndVerify(Device device, String scope, String attributesDataStr, String expectedKey, String expectedValue) throws Exception { JsonNode attributesData = JacksonUtil.toJsonNode(attributesDataStr); From 24c294fa357c813e1f4baa24b412bebc5592d89b Mon Sep 17 00:00:00 2001 From: Dmytro Skarzhynets Date: Tue, 29 Sep 2026 12:41:46 +0300 Subject: [PATCH 063/119] chore: move license header template out of repository root --- pom.xml | 2 +- .../main/python/license-headers/templates/license-header.txt | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename license-header.txt => tools/src/main/python/license-headers/templates/license-header.txt (100%) diff --git a/pom.xml b/pom.xml index 76920fadeb..e8f42b3243 100755 --- a/pom.xml +++ b/pom.xml @@ -891,7 +891,7 @@ -
${main.dir}/license-header.txt
+
${main.dir}/tools/src/main/python/license-headers/templates/license-header.txt
**/.env **/*.env diff --git a/license-header.txt b/tools/src/main/python/license-headers/templates/license-header.txt similarity index 100% rename from license-header.txt rename to tools/src/main/python/license-headers/templates/license-header.txt From ca95ecd4423292cae76372f3259bef6d22ae3df0 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 13:40:19 +0300 Subject: [PATCH 064/119] feat(iot-hub): show the search popup as one ranked list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The popup asked /api/versions/published/grouped and rendered one section per item type, so a query answered best by a widget still opened on devices. It now asks for page 0 of the flat read the search page makes (relevance sort, 10 rows) and renders those rows in the server's order, so the best match leads whatever its type. - Each row names its type before the author ("Widget · pinkevych.d"), in the type's colour with its itemTypeIcons icon. The verified mark moves in front of the author like on the item cards; an unverified author keeps the person icon. - Items without a screenshot (calculated fields, alarm rules, rule chains) sit in the same 99x56 frame as a screenshot with a 36px coloured tile inside, so names line up down the list. - The footer says "See all N results for ..." when the search matched more than the popup shows; N discounts the rows this page dropped (dashboards). - itemTypeColors joins itemTypeIcons as the one type palette; the hero reads it instead of repeating the six colours. Removes getPublishedVersionsGrouped, MpItemVersionGroupedQuery, MpItemVersionSection and the iot-hub.section-more key. --- .../src/app/core/http/iot-hub-api.service.ts | 16 --- .../pages/iot-hub/iot-hub-home.component.html | 67 ++++++----- .../pages/iot-hub/iot-hub-home.component.scss | 112 +++++++++--------- .../pages/iot-hub/iot-hub-home.component.ts | 100 +++++++--------- .../models/iot-hub/iot-hub-item.models.ts | 15 +++ .../models/iot-hub/iot-hub-version.models.ts | 38 ------ .../assets/locale/locale.constant-en_US.json | 2 +- 7 files changed, 151 insertions(+), 199 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 7f3b299962..c5037048fb 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -7,10 +7,8 @@ import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { - MpItemVersionGroupedQuery, MpItemVersionQuery, MpItemVersionQueryOptions, - MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; @@ -82,20 +80,6 @@ export class IotHubApiService { ); } - /** - * The sectioned answer: one section per item type, in the server's order, each capped by the - * server and carrying the total behind that cap. Its own endpoint, which takes no page, page - * size or sort direction. - */ - public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, - config?: IotHubRequestConfig): Observable { - this.applyPlatformFilters(query.options); - return this.http.get( - `${this.baseUrl}/api/versions/published/grouped${query.toQuery()}`, - { params: this.buildParams(config) } - ); - } - /** * What this platform can install, filled in for a caller that did not say: items built for a * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 564f89ca46..5963c9e536 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -72,7 +72,7 @@ - } @else if (searchResultGroups.length === 0 && searchLoaded) { + } @else if (searchResults.length === 0 && searchLoaded) {
search_off @@ -84,48 +84,53 @@
} @else { - @for (group of searchResultGroups; track group.type) { - - {{ getSearchGroupLabel(group.type) }} - @if (group.remaining > 0) { - - {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} - chevron_right - - } - - @for (item of group.items; track item.id) { - + @for (item of searchResults; track item.id) { + + +
@if (isCompactType(item.type)) {
{{ getCompactIcon(item) }}
+ } @else if (getItemImage(item); as imgUrl) { + } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
+ {{ getItemTypeIcon(item.type) }} } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} +
+
+ {{ item.name }} + + + + {{ getItemTypeIcon(item.type) }} + {{ getItemTypeLabel(item.type) }} -
- - } + @if (item.creatorDisplayName) { + + @if (item.creatorVerified) { + verified + } @else { + person + } + {{ item.creatorDisplayName }} + + } + +
+
} } @if (searchText?.trim(); as query) { - {{ 'iot-hub.see-results-for' | translate:{ search: query } }} + @if (searchTotal > searchResults.length) { + {{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }} + } @else { + {{ 'iot-hub.see-results-for' | translate:{ search: query } }} + } } @else { {{ 'iot-hub.see-all-results' | translate }} } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 8a89ebae44..157d6e1faf 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -241,53 +241,6 @@ } } - // Section header — an option like every other row, not a button beside them, so the arrow keys - // reach it and a screen reader reads it in the list. It IS the way into the type page: title - // left, how much is not shown plus a chevron right. There is deliberately no per-section - // "see all" row under the items; six of those on one panel is what this variant avoids. - // Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H, 12px above each section. - .mat-mdc-option.tb-search-popup-group-header { - padding: 4px 16px; - min-height: 28px; - margin-top: 12px; - - &:first-child { - margin-top: 0; - } - - .mdc-list-item__primary-text { - justify-content: space-between; - } - } - - .tb-search-popup-group-label { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - white-space: nowrap; - } - - .tb-search-popup-group-more { - display: flex; - align-items: center; - gap: 2px; - flex-shrink: 0; - font-size: 12px; - font-weight: 500; - line-height: 16px; - letter-spacing: 0.25px; - color: $tb-primary-color; - - .mat-icon { - width: 18px; - height: 18px; - font-size: 18px; - line-height: 18px; - } - } - // Item row — Design: 8px V / 16px H, 16px gap, centered .mat-mdc-option.tb-search-popup-item { padding: 8px 16px; @@ -322,11 +275,11 @@ color: rgba(0, 0, 0, 0.38); } - // Icon square — Design: 56x56, 4.667px radius, colored bg + // Icon tile for an item with no screenshot, centred in the thumbnail frame: 36x36, colored bg .tb-search-popup-icon-square { - width: 56px; - height: 56px; - border-radius: 4.667px; + width: 36px; + height: 36px; + border-radius: 6px; flex-shrink: 0; display: flex; align-items: center; @@ -334,9 +287,9 @@ } .tb-search-popup-icon-inner { - font-size: 28px; - width: 28px; - height: 28px; + font-size: 22px; + width: 22px; + height: 22px; color: white !important; --tb-icon-color: white; } @@ -373,13 +326,64 @@ letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); white-space: nowrap; + min-width: 0; mat-icon { + flex-shrink: 0; font-size: 16px; width: 16px; height: 16px; margin-right: 0; color: rgba(0, 0, 0, 0.54); + + // Same teal the IoT Hub item cards give a verified creator. + &.tb-search-popup-verified { + color: #00695c; + } + } + } + + // Shares the meta row with the item type, so a long name is cut rather than overflowing. + .tb-search-popup-author-name { + overflow: hidden; + text-overflow: ellipsis; + } + + // Meta row: the item type, a middle dot, then the author - "Widget · pinkevych.d". + .tb-search-popup-meta { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + } + + // Item type in its own colour, darkened so the paler ones (rule chain, calculated field) stay + // legible as text. + .tb-search-popup-type { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.25px; + color: color-mix(in srgb, var(--tb-search-popup-type-color, #5f6368) 75%, #000); + white-space: nowrap; + + tb-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + color: inherit; + } + + // No author, nothing to separate from. + &:not(:last-child)::after { + content: '·'; + font-weight: 700; + color: rgba(0, 0, 0, 0.54); } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index cf242faeb3..c7c6a9ad07 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -10,16 +10,14 @@ import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/ import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { - MpItemVersionGroupedQuery, - MpItemVersionQuery, - MpItemVersionSection, - MpItemVersionView -} from '@shared/models/iot-hub/iot-hub-version.models'; +import { PageData } from '@shared/models/page/page-data'; +import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CROSS_TYPE_ITEM_TYPES, + getItemTypeColor, getItemTypeIcon, ItemType, + itemTypeColors, itemTypeTranslations, RELEVANCE_SORT_PROPERTY } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -44,12 +42,11 @@ interface HeroTypeConfig { icon: string; } -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; - /** How many rows of this type the header offers beyond the ones shown. Zero renders no "+N more". */ - remaining: number; -} +/** + * Rows the search popup shows: the first page of the search page's own request, so the popup is + * a preview of what "See results for ..." opens on. + */ +const SEARCH_POPUP_PAGE_SIZE = 10; @Component({ selector: 'tb-iot-hub-home', @@ -62,7 +59,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResultGroups: SearchResultGroup[] = []; + searchResults: MpItemVersionView[] = []; + /** + * What the footer's "See all N results" counts: the matches less the rows this page dropped, so + * a panel that shows everything it can open never claims more. Rows beyond this page that the + * panel could not show are still counted - only this page's drops are known. + */ + searchTotal = 0; searchLoaded = false; searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @@ -74,27 +77,27 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { heroTypes: HeroTypeConfig[] = [ { - type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: '#4b63cc', + type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: itemTypeColors[ItemType.DEVICE], icon: 'assets/iot-hub/hero-device-cluster.svg' }, { - type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: '#2b6bb4', + type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: itemTypeColors[ItemType.SOLUTION_TEMPLATE], icon: 'assets/iot-hub/hero-solution-template-cluster.svg' }, { - type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: '#2c9755', + type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: itemTypeColors[ItemType.WIDGET], icon: 'assets/iot-hub/hero-widget-cluster.svg' }, { - type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: '#3cb4e0', + type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: itemTypeColors[ItemType.CALCULATED_FIELD], icon: 'assets/iot-hub/hero-calculated-field-cluster.svg' }, { - type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: '#d66f2e', + type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: itemTypeColors[ItemType.ALARM_RULE], icon: 'assets/iot-hub/hero-alarm-rule-cluster.svg' }, { - type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: '#a95ae2', + type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: itemTypeColors[ItemType.RULE_CHAIN], icon: 'assets/iot-hub/hero-rule-chain-cluster.svg' } ]; @@ -166,18 +169,26 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); + // One flat list ranked across every type, so the best match leads whatever its type. // Relevance in both states, the same value every other IoT Hub surface sends: with an // empty field the backend serves the install count under this key, so the panel opens on // popularity without this component having to know it. - const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); + const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC }; + const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder); + const query = new MpItemVersionQuery(pageLink); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. - return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( - catchError(() => of([] as MpItemVersionSection[])) + return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe( + catchError(() => of({ data: [], totalElements: 0 } as PageData)) ); }) - ).subscribe(sections => { - this.searchResultGroups = this.toResultGroups(sections); + ).subscribe(page => { + // The platform publishes no dashboards, so a type this panel has no layout for is dropped; + // the popup then shows fewer rows rather than asking for more. + const data = page.data ?? []; + this.searchResults = data.filter(item => CROSS_TYPE_ITEM_TYPES.includes(item.type)); + this.searchTotal = Math.max(this.searchResults.length, + (page.totalElements ?? 0) - (data.length - this.searchResults.length)); this.searchLoaded = true; this.searchLoading = false; }); @@ -285,17 +296,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { void this.router.navigate(['/iot-hub/search'], { queryParams: { search } }); } - /** - * The section header is the way into the rest of a type - the panel carries no per-section - * "see all" row, which would put six identical calls to action on one panel. The query goes - * with it, so the type page opens on the same search rather than on the whole type. - */ - navigateToSection(type: ItemType): void { - this.searchAutoTrigger?.closePanel(); - const search = this.searchText?.trim() || undefined; - void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); - } - isCompactType(type: ItemType): boolean { return type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE @@ -314,9 +314,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { return getItemTypeIcon(type); } - getSearchGroupLabel(type: ItemType): string { + getItemTypeColor(type: ItemType): string { + return getItemTypeColor(type); + } + + getItemTypeLabel(type: ItemType): string { const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; + return key ? this.translate.instant(key) : type; } navigateToBrowse(type: ItemType): void { @@ -582,26 +586,4 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); } - /** - * Reads the sections the server built: they arrive capped and in the order to render them, so - * this only drops the types this panel has no layout for - the platform publishes no dashboards - * - and works out each header's "+N more". - * - * `items` is defaulted because the response is an unvalidated cast of a new endpoint, and a - * throw here lands in a subscribe callback, where it would leave the panel on its spinner - * rather than reaching the catchError upstream. - */ - private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { - return sections - .filter(section => CROSS_TYPE_ITEM_TYPES.includes(section.itemType)) - .map(section => { - const items = section.items ?? []; - return { - type: section.itemType, - items, - remaining: Math.max(0, section.total - items.length) - }; - }); - } - } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index 8fbe84440b..e21582ea1a 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -41,6 +41,21 @@ export const itemTypeIcons: Record = { export const getItemTypeIcon = (type?: string | null): string => type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category'; +// Canonical colour per item type - the IoT Hub home's type palette - for anything that marks an +// item's type with a colour: the hero's type cycle and the search popup's type label. +export const itemTypeColors: Record = { + [ItemType.WIDGET]: '#2c9755', + [ItemType.DASHBOARD]: '#5f6368', + [ItemType.SOLUTION_TEMPLATE]: '#2b6bb4', + [ItemType.CALCULATED_FIELD]: '#3cb4e0', + [ItemType.RULE_CHAIN]: '#a95ae2', + [ItemType.ALARM_RULE]: '#d66f2e', + [ItemType.DEVICE]: '#4b63cc' +}; + +export const getItemTypeColor = (type?: string | null): string => + type && itemTypeColors[type] ? itemTypeColors[type] : '#5f6368'; + /** * Item types discoverable to creators in the marketplace UI. * DASHBOARD is intentionally absent (IoT Hub no longer accepts Dashboard contributions). diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index a5afaea23c..685fc27cb1 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -108,17 +108,6 @@ export interface MpItemVersionView { checksum?: string; } -/** - * One item type's share of a grouped search: the rows to show and how many exist behind them. - * A grouped answer is a list of these, in the server's section order, and a type nothing matched - * has no section — so a "+N more" header is `total - items.length`. - */ -export interface MpItemVersionSection { - itemType: ItemType; - total: number; - items: MpItemVersionView[]; -} - // 404 body shapes returned by the public listing item-version endpoint // (GET /api/listings/public/by-slug/{slug}/item-version) when no // version matches the caller's edition / platform combination. @@ -208,30 +197,3 @@ export class MpItemVersionQuery { return this.pageLink.toQuery() + filtersToQuery(this.options); } } - -/** - * A sectioned read: the filters, what to search for, and which key orders a section. - * - * No `PageLink`, because the grouped endpoint takes no page and no page size - it sizes its own - * answer from the section limit - and no sort direction either, each key's direction being fixed - * by the chain the server switches on. A page link here could only carry values nobody sends. - */ -export class MpItemVersionGroupedQuery { - constructor(public options: MpItemVersionQueryOptions = {}, - public textSearch?: string, - public sortProperty?: string) {} - - public toQuery(): string { - const parts: string[] = []; - const text = this.textSearch?.trim(); - if (text?.length) { - parts.push(`textSearch=${encodeURIComponent(text)}`); - } - if (this.sortProperty) { - parts.push(`sortProperty=${this.sortProperty}`); - } - // filtersToQuery() emits leading ampersands, which is what a page link needs in front of it; - // here they may be the whole query string, so the first one is dropped. - return `?${`${parts.join('&')}${filtersToQuery(this.options)}`.replace(/^&/, '')}`; - } -} diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index e19cb64cff..f3818e8179 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3708,6 +3708,7 @@ "search": "Search...", "search-published-items": "Search published items...", "see-all-results": "See all results", + "see-all-results-for": "See all {{ count }} results for \"{{ search }}\"", "see-results-for": "See results for \"{{ search }}\"", "no-search-results": "No results found for '{{ search }}'", "no-items-available": "No items available", @@ -3780,7 +3781,6 @@ "sort-most-installed": "Most installed", "sort-newest": "Newest", "sort-name": "Name (A-Z)", - "section-more": "{ count, plural, =1 {+1 more} other {+# more} }", "type-filter-label": "Type", "category": "Category", "use-case": "Use case", From 368d6fd94d5a9c01998c0442c8527a7f32ccdb5f Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 065/119] refactor(iot-hub): one source for the platform scope and the type palette's default From the review: - iot-hub-api.service builds peOnly/tbVersion from one platformScope(), used by applyPlatformFilters and by the reads that wrote the pair into the URL by hand (filterInfo, widgetCategories, the listing item-version lookup). - DEFAULT_ITEM_TYPE_COLOR names the grey the palette falls back to; the alarm-rules-unavailable page reads itemTypeColors instead of its own copy. - isCompactItemType() next to CROSS_TYPE_ITEM_TYPES, used by the item card and the popup. - A stale "shared by both query shapes" comment left from the grouped query, and other comments, trimmed to the non-obvious intent. --- .../src/app/core/http/iot-hub-api.service.ts | 34 +++++++++---------- .../components/iot-hub/_iot-hub-common.scss | 8 +---- .../iot-hub/iot-hub-item-card.component.html | 3 +- .../iot-hub/iot-hub-item-card.component.ts | 15 +++----- ...-alarm-rules-unavailable-page.component.ts | 4 +-- .../iot-hub-creator-profile.component.html | 2 -- .../models/iot-hub/iot-hub-item.models.ts | 33 +++++++----------- .../models/iot-hub/iot-hub-version.models.ts | 9 ++--- 8 files changed, 40 insertions(+), 68 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index c5037048fb..fe579b5b88 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -80,31 +80,31 @@ export class IotHubApiService { ); } - /** - * What this platform can install, filled in for a caller that did not say: items built for a - * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. - */ + /** What this platform can install: no PE-only items, nothing built for a newer ThingsBoard. */ + private platformScope(): { peOnly: boolean; tbVersion: number } { + return { peOnly: false, tbVersion: tbVersionToInt(env.tbVersion) }; + } + + /** Fills in the platform scope wherever the caller did not set it. */ private applyPlatformFilters(options: MpItemVersionQueryOptions): void { - if (options.tbVersion == null) { - options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (options.peOnly == null) { - options.peOnly = false; - } + const scope = this.platformScope(); + options.tbVersion ??= scope.tbVersion; + options.peOnly ??= scope.peOnly; + } + + private platformScopeParams(): string[] { + const scope = this.platformScope(); + return [`peOnly=${scope.peOnly}`, `tbVersion=${scope.tbVersion}`]; } public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { - const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` - + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; + const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}?${this.platformScopeParams().join('&')}`; return this.http.get(url, { params: this.buildParams(config) }); } public getWidgetCategories(textSearch?: string, scadaFirst?: boolean, config?: IotHubRequestConfig): Observable { - const queryParams: string[] = [ - `peOnly=false`, - `tbVersion=${tbVersionToInt(env.tbVersion)}` - ]; + const queryParams: string[] = this.platformScopeParams(); if (textSearch?.trim()) { queryParams.push(`textSearch=${encodeURIComponent(textSearch.trim())}`); } @@ -144,7 +144,7 @@ export class IotHubApiService { public getListingItemVersion(slug: string, config?: IotHubRequestConfig): Observable { const queryParams = [ 'ce=true', - `tbVersion=${tbVersionToInt(env.tbVersion)}` + `tbVersion=${this.platformScope().tbVersion}` ]; return this.http.get( `${this.baseUrl}/api/listings/public/by-slug/${encodeURIComponent(slug)}/item-version?${queryParams.join('&')}`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss index 96697ebe74..b6264d6ce3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss @@ -120,13 +120,7 @@ } } -// Scroll area that shows its thumb only while the container is hovered — the filter panels' -// own treatment, kept here so the two that use it cannot drift apart. -// -// Not the app-wide one: theme.scss keeps its thumb permanently visible. Whether these panels -// should do the same, and whether to add the standardised scrollbar-width / scrollbar-color -// that Firefox reads, is a question for the IoT Hub filter UI as a whole rather than for one -// panel; iot-hub-browse and dashboard-widget-select carry copies of this same treatment. +// Scroll area whose thumb shows only while the container is hovered (the filter panels'). @mixin tb-iot-hub-hover-scrollbar { &::-webkit-scrollbar { width: 6px; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html index 16bca59bf7..4a73740979 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html @@ -78,8 +78,7 @@ } @else {
- + {{ getPlaceholderIcon() }}
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index f57582fb29..123de28c3f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Component, EventEmitter, Input, Output } from '@angular/core'; import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; +import { getItemTypeIcon, isCompactItemType, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { TranslateService } from '@ngx-translate/core'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -24,13 +24,8 @@ export class TbIotHubItemCardComponent { @Input() showSubtype = false; @Input() mode: 'default' | 'add' = 'default'; /** - * `auto` lets the item's type choose, which is what a single-type grid wants: calculated - * fields, alarm rules and rule chains have nothing to preview, so they get a compact row and - * the grid gives them wider cells. - * - * `preview` forces the tall card on every type. A grid that mixes types cannot widen its - * cells for some rows only, and a horizontal row squeezed into a cell sized for a preview - * truncates its own title and leaves the rest of the cell empty. + * `auto`: compact row for the types with nothing to preview (single-type grids widen their + * cells for it). `preview`: the tall card for every type, for grids that mix types. */ @Input() layout: 'auto' | 'preview' = 'auto'; @Output() cardClick = new EventEmitter(); @@ -60,9 +55,7 @@ export class TbIotHubItemCardComponent { if (this.layout === 'preview') { return false; } - return this.item.type === ItemType.CALCULATED_FIELD - || this.item.type === ItemType.ALARM_RULE - || this.item.type === ItemType.RULE_CHAIN; + return isCompactItemType(this.item.type); } getPreviewUrl(): string | null { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts index c648eeb14a..f8ec79e525 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts @@ -3,6 +3,7 @@ import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { environment as env } from '@env/environment'; +import { ItemType, itemTypeColors } from '@shared/models/iot-hub/iot-hub-item.models'; @Component({ selector: 'tb-iot-hub-alarm-rules-unavailable-page', @@ -12,8 +13,7 @@ import { environment as env } from '@env/environment'; }) export class TbIotHubAlarmRulesUnavailablePageComponent { - // Same colour as the ALARM_RULE HeroTypeConfig entry on the home page. - readonly alarmRulesColor = '#d66f2e'; + readonly alarmRulesColor = itemTypeColors[ItemType.ALARM_RULE]; readonly currentTbVersion: string = env.tbVersion; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html index 51d834e8ed..42f92fc3d1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html @@ -96,8 +96,6 @@
-

diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index e21582ea1a..ea2077e634 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -41,11 +41,13 @@ export const itemTypeIcons: Record = { export const getItemTypeIcon = (type?: string | null): string => type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category'; -// Canonical colour per item type - the IoT Hub home's type palette - for anything that marks an -// item's type with a colour: the hero's type cycle and the search popup's type label. +/** Colour for a type with no colour of its own. */ +export const DEFAULT_ITEM_TYPE_COLOR = '#5f6368'; + +/** Colour per item type, wherever an item's type is marked with one. */ export const itemTypeColors: Record = { [ItemType.WIDGET]: '#2c9755', - [ItemType.DASHBOARD]: '#5f6368', + [ItemType.DASHBOARD]: DEFAULT_ITEM_TYPE_COLOR, [ItemType.SOLUTION_TEMPLATE]: '#2b6bb4', [ItemType.CALCULATED_FIELD]: '#3cb4e0', [ItemType.RULE_CHAIN]: '#a95ae2', @@ -54,7 +56,7 @@ export const itemTypeColors: Record = { }; export const getItemTypeColor = (type?: string | null): string => - type && itemTypeColors[type] ? itemTypeColors[type] : '#5f6368'; + type && itemTypeColors[type] ? itemTypeColors[type] : DEFAULT_ITEM_TYPE_COLOR; /** * Item types discoverable to creators in the marketplace UI. @@ -71,11 +73,7 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; -/** - * Item types a surface that mixes them lays out, in the order they are shown. Distinct from - * CREATOR_VISIBLE_ITEM_TYPES, which is the same six as a membership test and carries the type - * tabs' own order: here DEVICE leads, matching the hero popup's sections and the website. - */ +/** Item types a cross-type surface (search page, popup) shows, in display order. */ export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, @@ -85,6 +83,10 @@ export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; +/** Types drawn as a coloured icon tile rather than a screenshot. */ +export const isCompactItemType = (type?: string | null): boolean => + type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE || type === ItemType.RULE_CHAIN; + /** Sort property served by relevance ranking. */ export const RELEVANCE_SORT_PROPERTY = 'relevance'; @@ -95,17 +97,8 @@ export interface SortOption { } /** - * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers - * them in: the first entry is the default each surface opens on. - * - * Relevance is that default with or without text. With text it ranks the answer; with none the - * backend serves the install count under the same key, so a surface opens on the order it opened - * on before and nothing here switches on the field state. The cost is a menu reading "Most - * relevant" over an install-ordered list until the user types; the alternative - flipping the - * selector once text appears - moves a control the user did not touch and reorders nothing. - * - * One list rather than one per surface: a new key must reach all of them, and the surface that - * missed it would keep a different default without failing. + * The sort menu of every IoT Hub surface with a search field; the first entry is the default. + * Relevance stays the default with an empty field, where it orders by install count. */ export const IOT_HUB_SORT_OPTIONS: SortOption[] = [ { value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 685fc27cb1..8ba587342c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -120,12 +120,7 @@ export interface ListingItemVersionNotFound { export interface MpItemVersionQueryOptions { /** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */ type?: string; - /** - * Several item types at once, for a cross-type surface whose Type facet is multi-select. - * Emitted as a repeated `type` parameter, which is the shape the backend reads - * (`@RequestParam List type`). Kept separate from `type` rather than widening it, - * so a caller that means "exactly this type" cannot be handed an array by accident. - */ + /** Several item types at once, sent as a repeated `type` parameter. */ types?: string[]; peOnly?: boolean; creatorId?: string; @@ -141,7 +136,7 @@ export interface MpItemVersionQueryOptions { scadaFirst?: boolean; } -/** Every filter, as `&name=value` pairs - shared by both query shapes below. */ +/** Every filter, as `&name=value` pairs. */ function filtersToQuery(o: MpItemVersionQueryOptions): string { let query = ''; if (o.type) { From 6fc35a4d0ede33a6d977ce2a82adfde02974f1b9 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 066/119] fix(iot-hub): offer no relevance sort on the widget picker's Installed list That list is sorted in the browser, and relevance is a score only the Hub computes: sortInstalledVersions read a 'relevance' field no row has, so "Most relevant" left the list unsorted under a label saying otherwise. The Installed list now offers the other three keys, and a relevance choice made on the IoT Hub list falls back to the first of them there. The sort is kept by value rather than by menu index, since the two lists differ in length. --- .../dashboard-widget-select.component.html | 6 ++-- .../dashboard-widget-select.component.ts | 32 ++++++++++++------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html index aa5c1deb90..c75165d122 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html @@ -80,12 +80,12 @@ } @if (selectWidgetMode === 'iotHub' && iotHubSubMode !== 'default') { - @for (option of iotHubSortOptions; track option.value; let i = $index) { - + @for (option of iotHubSortOptions; track option.value) { + } } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index 7cb0eddd2b..7132063ed2 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -25,8 +25,13 @@ import { FilterParamInfo, IOT_HUB_SORT_OPTIONS, ItemType, + RELEVANCE_SORT_PROPERTY, + SortOption, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; + +/** The Installed list is sorted locally, and only the Hub can rank by relevance. */ +const INSTALLED_SORT_OPTIONS = IOT_HUB_SORT_OPTIONS.filter(o => o.value !== RELEVANCE_SORT_PROPERTY); import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; @@ -87,12 +92,7 @@ export class DashboardWidgetSelectComponent { includeDeprecated = false; searchFocused = false; - /** - * scadaFirst is unaffected by the sort: the backend prepends it ahead of the caller's key AND - * ahead of relevance, so a SCADA context still lists SCADA widgets first. - */ - readonly iotHubSortOptions = IOT_HUB_SORT_OPTIONS; - iotHubSelectedSortIndex = 0; + private iotHubSelectedSortValue = IOT_HUB_SORT_OPTIONS[0].value; @Input() aliasController: IAliasController; @@ -302,7 +302,7 @@ export class DashboardWidgetSelectComponent { this.iotHubWidgetsFetchFunction = (pageSize, page, filter) => { const search = typeof filter === 'string' ? filter.split('|')[0] : filter; - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(pageSize, page, search || null, sortOrder); const effectiveCategories = this.iotHubSelectedCategory @@ -569,9 +569,19 @@ export class DashboardWidgetSelectComponent { this.reloadIotHubWidgets(); } - onIotHubSortChange(index: number): void { - if (this.iotHubSelectedSortIndex !== index) { - this.iotHubSelectedSortIndex = index; + get iotHubSortOptions(): SortOption[] { + return this.iotHubSubMode === 'installed' ? INSTALLED_SORT_OPTIONS : IOT_HUB_SORT_OPTIONS; + } + + /** The chosen sort, or the list's first option where the chosen one is not offered. */ + get iotHubSelectedSort(): SortOption { + const options = this.iotHubSortOptions; + return options.find(o => o.value === this.iotHubSelectedSortValue) ?? options[0]; + } + + onIotHubSortChange(option: SortOption): void { + if (this.iotHubSelectedSort.value !== option.value) { + this.iotHubSelectedSortValue = option.value; this.installedWidgetVersions = null; this.reloadIotHubWidgets(); } @@ -844,7 +854,7 @@ export class DashboardWidgetSelectComponent { } private sortInstalledVersions(versions: MpItemVersionView[]): MpItemVersionView[] { - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sign = sort.direction === Direction.ASC ? 1 : -1; const copy = [...versions]; copy.sort((a, b) => { From 3b4dc3198576a0c3c17807ced1c10d2b21e4d1c5 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 067/119] refactor(iot-hub): handle Enter in the popup on keydown, with no cross-event flag Enter in the field opens the search page unless the autocomplete has just used the press to select a highlighted row, which it marks with preventDefault in its own keydown handler, registered before the field's. The field now listens on keydown.enter and checks event.defaultPrevented, which replaces the enterHandledByRow flag, the four places that reset it, and the read of the trigger's activeOption at one exact moment. Checked in a browser: arrow + Enter on a row opens the row only, Enter in the field opens the search page, click a row / close the dialog / click the magnifier opens the search page, and arrow to the footer + Enter opens it once. Also from the review: - The popup asks for the six cross-type types rather than filtering dashboards out afterwards, so totalElements is exact and "See all N" needs no arithmetic. - Row and footer selection go through onRowSelected / onFooterSelected instead of a side-effecting predicate in the template. - isCompactType delegates to the shared isCompactItemType; comments trimmed. --- .../pages/iot-hub/iot-hub-home.component.html | 12 ++- .../pages/iot-hub/iot-hub-home.component.scss | 9 +-- .../pages/iot-hub/iot-hub-home.component.ts | 78 ++++++------------- 3 files changed, 32 insertions(+), 67 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 5963c9e536..d244bbe06a 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -54,13 +54,13 @@ [matAutocomplete]="searchAuto" (input)="onSearchInput()" (focus)="onSearchFocus()" - (keyup.enter)="onSearch()"> + (keydown.enter)="onSearchEnter($event)"> @if (searchText) { } - @@ -86,9 +86,8 @@ } @else { @for (item of searchResults; track item.id) { - + (onSelectionChange)="onRowSelected($event, item)"> +
@if (isCompactType(item.type)) {
@@ -102,7 +101,6 @@
{{ item.name }} - {{ getItemTypeIcon(item.type) }} @@ -124,7 +122,7 @@ } } + (onSelectionChange)="onFooterSelected($event)"> @if (searchText?.trim(); as query) { @if (searchTotal > searchResults.length) { {{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }} diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 157d6e1faf..7440403390 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,9 +220,7 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); - // Every row of the panel shares the flex line and the highlight; the boxes differ per kind - // below. Each kind is selected by its own class rather than by leaning on source order, since - // .mat-mdc-option. and .mat-mdc-option:not(...) tie on specificity. + // Shared by every row; each row kind below is selected by its own class. .mat-mdc-option { .mdc-list-item__primary-text { display: flex; @@ -357,8 +355,7 @@ min-width: 0; } - // Item type in its own colour, darkened so the paler ones (rule chain, calculated field) stay - // legible as text. + // Item type in its colour, darkened so the paler ones stay legible. .tb-search-popup-type { display: flex; align-items: center; @@ -368,7 +365,7 @@ font-weight: 500; line-height: 16px; letter-spacing: 0.25px; - color: color-mix(in srgb, var(--tb-search-popup-type-color, #5f6368) 75%, #000); + color: color-mix(in srgb, var(--tb-search-popup-type-color) 75%, #000); white-space: nowrap; tb-icon { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index c7c6a9ad07..8f44ec2c30 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -15,6 +15,7 @@ import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/io import { CROSS_TYPE_ITEM_TYPES, getItemTypeColor, + isCompactItemType, getItemTypeIcon, ItemType, itemTypeColors, @@ -42,10 +43,7 @@ interface HeroTypeConfig { icon: string; } -/** - * Rows the search popup shows: the first page of the search page's own request, so the popup is - * a preview of what "See results for ..." opens on. - */ +/** Rows the search popup shows: page 0 of the search page's own request. */ const SEARCH_POPUP_PAGE_SIZE = 10; @Component({ @@ -60,17 +58,12 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { searchText = ''; searchResults: MpItemVersionView[] = []; - /** - * What the footer's "See all N results" counts: the matches less the rows this page dropped, so - * a panel that shows everything it can open never claims more. Rows beyond this page that the - * panel could not show are still counted - only this page's drops are known. - */ + /** Everything the search matched, for the footer's "See all N results". */ searchTotal = 0; searchLoaded = false; searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef; - private enterHandledByRow = false; private searchSubject = new Subject(); private searchSubscription: Subscription; @@ -169,26 +162,19 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); - // One flat list ranked across every type, so the best match leads whatever its type. - // Relevance in both states, the same value every other IoT Hub surface sends: with an - // empty field the backend serves the install count under this key, so the panel opens on - // popularity without this component having to know it. + // One list ranked across every type the platform surfaces. With an empty field relevance + // is served as the install count. const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC }; const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); - // A failed request must not end the subscription: the interceptor reports it, and the - // panel goes back to an empty answer the next keystroke can replace. + const query = new MpItemVersionQuery(pageLink, { types: CROSS_TYPE_ITEM_TYPES }); + // A failure must not end the subscription; the next keystroke replaces the empty answer. return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe( catchError(() => of({ data: [], totalElements: 0 } as PageData)) ); }) ).subscribe(page => { - // The platform publishes no dashboards, so a type this panel has no layout for is dropped; - // the popup then shows fewer rows rather than asking for more. - const data = page.data ?? []; - this.searchResults = data.filter(item => CROSS_TYPE_ITEM_TYPES.includes(item.type)); - this.searchTotal = Math.max(this.searchResults.length, - (page.totalElements ?? 0) - (data.length - this.searchResults.length)); + this.searchResults = page.data ?? []; + this.searchTotal = page.totalElements ?? 0; this.searchLoaded = true; this.searchLoading = false; }); @@ -230,13 +216,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchInput(): void { - this.enterHandledByRow = false; this.searchLoading = true; this.searchSubject.next(this.searchText || ''); } onSearchFocus(): void { - this.enterHandledByRow = false; if (!this.searchLoaded) { this.searchLoading = true; this.searchSubject.next(this.searchText || ''); @@ -248,43 +232,30 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }; clearSearch(): void { - this.enterHandledByRow = false; this.searchText = ''; this.searchSubject.next(''); this.searchInputRef?.nativeElement?.focus(); setTimeout(() => this.searchAutoTrigger?.openPanel()); } - /** - * Gate on every row's selection: false for the panel's own bookkeeping, true when the user - * picked the row - and then it records whether a keyup is still coming for it. - * - * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own - * handler on keyup, and preventDefault on the first does not stop the second. Only the - * keyboard leaves that second half to deal with, so only the keyboard arms the flag: a pointer - * selection is finished when it returns, and a flag left standing there would swallow the next - * onSearch - which the magnifier button can raise with no keystroke at all. - * - * activeOption is what tells the two apart, and it is readable only here: the trigger holds it - * while it calls _selectViaInteraction and clears it on the next line of its own handler, so by - * keyup it reads empty either way. A pointer never sets it. - */ - rowSelectedByUser(event: MatOptionSelectionChange): boolean { - if (!event.isUserInput) { - return false; + onRowSelected(event: MatOptionSelectionChange, item: MpItemVersionView): void { + if (event.isUserInput) { + this.openItemDetail(item); + } + } + + onFooterSelected(event: MatOptionSelectionChange): void { + if (event.isUserInput) { + this.seeAllResults(); } - this.enterHandledByRow = !!this.searchAutoTrigger?.activeOption; - return true; } /** - * Enter in the field opens the search page, unless a row has just acted on this same press. - * Every path that re-enters the field clears the flag too, so nothing survives the keystroke - * it belongs to - including an arrow-then-click, the one selection that arms it by pointer. + * Enter in the field opens the search page - unless the autocomplete has just used this press + * to select a highlighted row, which it marks with preventDefault before this handler runs. */ - onSearch(): void { - if (this.enterHandledByRow) { - this.enterHandledByRow = false; + onSearchEnter(event: KeyboardEvent): void { + if (event.defaultPrevented || event.isComposing) { return; } this.seeAllResults(); @@ -297,11 +268,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; + return isCompactItemType(type); } + getCompactIcon(item: MpItemVersionView): string { return item.icon || getItemTypeIcon(item.type); } From a427a6a3d20cba5802896efbaa53b9a1bb33a664 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 068/119] fix(iot-hub): scope the search page to the cross-type types, and let a newer load win From the review of the search page: - No Type facet selected now sends the six types the platform surfaces, as the popup does, instead of every type the Hub holds: without the old grouping step a published dashboard would have rendered as a card and been counted. - Every reload goes through one Subject + switchMap, so a newer request cancels an older one; toggling two facets quickly can no longer leave the grid on the first answer. - The ResizeObserver callback runs inside NgZone.run, as in TbIotHubBrowseComponent; zone.js does not patch ResizeObserver, so a reload started from it did not render. Checked: widening the window reloads with the larger page size and renders it with no other event. - The facet list takes option keys (string[]) and computes its visible list once per change instead of on every change-detection pass; the Type facet's placeholder zero counts and the facet count summing are gone. - Shared in iot-hub-utils: filterByLabel (behind filterIotHubItemsBySearch), measureGridColumns (used by this component and the browse page), and IOT_HUB_FILTER_SCROLL_THRESHOLD in place of the literal 8 in both panels. - The page padding and the component's pull-out margin derive from one --tb-search-page-pad per breakpoint. Resize fields sit with the other state. - Comments trimmed to the non-obvious intent. --- .../iot-hub/iot-hub-browse.component.html | 24 +-- .../iot-hub/iot-hub-browse.component.ts | 21 ++- .../iot-hub/iot-hub-facet-list.component.html | 10 +- .../iot-hub/iot-hub-facet-list.component.scss | 10 +- .../iot-hub/iot-hub-facet-list.component.ts | 64 +++----- .../iot-hub/iot-hub-search.component.html | 8 +- .../iot-hub/iot-hub-search.component.scss | 33 ++-- .../iot-hub/iot-hub-search.component.ts | 147 +++++++----------- .../home/components/iot-hub/iot-hub-utils.ts | 24 ++- .../iot-hub-search-page.component.scss | 34 ++-- 10 files changed, 150 insertions(+), 225 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html index 40ffca34c8..dbc1c3c811 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html @@ -43,8 +43,8 @@ }
} -
@for (opt of getFilteredItems(subtypeOptions, 'subtype'); track opt.key) { } -
@for (group of getGroupedFilterItems(vendorOptions, 'vendor'); track group.label) { @if (group.label) { @@ -114,8 +114,8 @@ }
} -
@for (ht of getFilteredItems(hardwareTypeOptions, 'hardwareType'); track ht.key) { } -
@for (group of getFilteredConnectivityGroups('connectivity'); track group.group) {
{{ group.group }}
@@ -182,8 +182,8 @@ }
} -
@for (cat of getFilteredItems(categoryOptions, 'category'); track cat.key) { } -
@for (group of getGroupedFilterItems(useCaseOptions, 'useCase'); track group.label) { @if (group.label) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 2be0408826..40276cd769 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -19,7 +19,13 @@ import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; -import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils'; +import { + filterIotHubItemsBySearch, + groupIotHubFilterItems, + IOT_HUB_FILTER_SCROLL_THRESHOLD, + IotHubFilterGroup, + measureGridColumns +} from '@home/components/iot-hub/iot-hub-utils'; @Component({ selector: 'tb-iot-hub-browse', @@ -43,6 +49,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy } readonly ItemType = ItemType; + readonly scrollThreshold = IOT_HUB_FILTER_SCROLL_THRESHOLD; @Input() creatorId: string; @Input() embedded = false; @@ -212,17 +219,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (!el) { return this.probeCols; } - // Force layout so `grid-template-columns` resolves to pixel tracks, not `repeat(...)`. - void el.offsetWidth; - const tracks = getComputedStyle(el).gridTemplateColumns; - if (!tracks || tracks === 'none') { - return 1; - } - if (tracks.startsWith('repeat(')) { - const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); - return match ? parseInt(match[1], 10) : 1; - } - return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); + return measureGridColumns(el); } private adjustPageSize(): void { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html index 8468ddc04b..658ed108df 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -12,9 +12,9 @@ @if (searchable) {