From 5f5e3732e0fe679a63cca815612bb9885c977c4d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 13 Nov 2026 13:31:05 +0200 Subject: [PATCH 01/18] IoT Hub installed items: the items with an update come first after Check for updates (PROD-9326) --- .../server/controller/IotHubController.java | 7 +- .../service/iot_hub/DefaultIotHubService.java | 54 +++++++++ .../service/iot_hub/IotHubRestClient.java | 15 ++- .../server/service/iot_hub/IotHubService.java | 12 ++ .../iot_hub/DefaultIotHubServiceTest.java | 89 ++++++++++++++ .../dao/iot_hub/IotHubInstalledItemDao.java | 4 + .../iot_hub/IotHubInstalledItemService.java | 4 + .../IotHubInstalledItemServiceImpl.java | 7 ++ .../IotHubInstalledItemRepository.java | 31 +++++ .../iot_hub/JpaIotHubInstalledItemDao.java | 17 +++ .../IotHubInstalledItemServiceTest.java | 110 ++++++++++++++++++ .../src/app/core/http/iot-hub-api.service.ts | 9 +- ...iot-hub-installed-items-table.component.ts | 11 +- 13 files changed, 365 insertions(+), 5 deletions(-) create mode 100644 dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index b6d01d3342..56ed32b14e 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -140,9 +140,14 @@ public class IotHubController extends BaseController { @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder, @RequestParam(required = false) List itemTypes, - @RequestParam(required = false) UUID itemId) throws ThingsboardException { + @RequestParam(required = false) UUID itemId, + @RequestParam(required = false, defaultValue = "false") boolean updatesFirst) throws ThingsboardException { checkAllPermissions(); PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + if (updatesFirst) { + // The items installed in a version other than the one IoT Hub publishes now come first, sorted as asked + return iotHubService.findInstalledItemsUpdatesFirst(getTenantId(), itemTypes, itemId, pageLink); + } return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } 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 ddbe8ec5d7..60f2391544 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 @@ -5,6 +5,9 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -82,6 +85,7 @@ import org.thingsboard.server.service.security.permission.AccessControlService; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -138,6 +142,15 @@ public class DefaultIotHubService implements IotHubService { private final ProjectInfo projectInfo; private final DevicePackageEntities devicePackageEntities; + // How many item ids one request for their published versions takes + private static final int PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + // The installed items list asks for these on every page while it shows the updates first, so IoT Hub is asked once + // a minute per tenant at most; an answer it failed to give is kept too, so a slow IoT Hub doesn't slow down every page + private final Cache> publishedVersionIdsCache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMinutes(1)) + .maximumSize(10_000) + .build(); + // Field names of the marketplace version JSON payload. Both the install path and the // install-plan resolver parse the same shape, so the contract lives here in one place. private static final String FIELD_ID = "id"; @@ -803,6 +816,47 @@ public class DefaultIotHubService implements IotHubService { return keys; } + @Override + public PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { + Map publishedVersionIds = publishedVersionIdsCache.get(tenantId, this::findPublishedVersionIds); + return iotHubInstalledItemService.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + } + + /** + * IoT Hub's published version id by item id, of the items the tenant has installed. Asked in chunks, as IoT Hub may limit + * the ids of one request. Empty when IoT Hub doesn't answer: the list then shows in the page's sort only. + */ + private Map findPublishedVersionIds(TenantId tenantId) { + List itemIds = iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId); + Map publishedVersionIds = new HashMap<>(); + try { + for (List chunk : Lists.partition(itemIds, PUBLISHED_VERSIONS_CHUNK_SIZE)) { + JsonNode published = iotHubRestClient.getPublishedVersions(chunk); + if (published != null && published.isArray()) { + published.forEach(info -> putPublishedVersionId(tenantId, info, publishedVersionIds)); + } + } + } catch (RuntimeException e) { + log.warn("[{}] Failed to get the published versions of the installed items from IoT Hub", tenantId, e); + return Map.of(); + } + return publishedVersionIds; + } + + /** An entry of an item with no published version, or one that is not a pair of ids, adds nothing. */ + private static void putPublishedVersionId(TenantId tenantId, JsonNode info, Map publishedVersionIds) { + String itemId = info.path("itemId").asText(null); + String versionId = info.path("publishedVersionId").asText(null); + if (itemId == null || versionId == null) { + return; + } + try { + publishedVersionIds.put(UUID.fromString(itemId), UUID.fromString(versionId)); + } catch (IllegalArgumentException e) { + log.debug("[{}] Skipping a published version from IoT Hub that is not a pair of ids: {}", tenantId, info); + } + } + /** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */ @Override public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) { diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java index a12470271f..11950d86c4 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -18,6 +19,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; +import java.util.Collection; +import java.util.UUID; @Component @TbCoreComponent @@ -69,6 +72,16 @@ public class IotHubRestClient { } } + /** + * IoT Hub's published version of each item: {@code itemId}, {@code publishedVersionId} and {@code publishedVersion}, + * the last two null for an item with no published version. + */ + public JsonNode getPublishedVersions(Collection itemIds) { + String url = baseUrl + "/api/versions/publishedVersions"; + log.debug("Fetching IoT Hub published versions of {} items: {}", itemIds.size(), url); + return restTemplate.postForObject(url, itemIds, JsonNode.class); + } + public byte[] getVersionFileData(String versionId) { String url = baseUrl + "/api/versions/" + versionId + "/fileData"; log.debug("Fetching IoT Hub version file data: {}", url); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index e1d0cd666b..dfb9e068c4 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -9,8 +9,14 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.List; +import java.util.UUID; + public interface IotHubService { InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); @@ -23,6 +29,12 @@ public interface IotHubService { InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); + /** + * The tenant's installed items, those with an update in IoT Hub first: installed in a version other than the item's + * published one. Without an answer from IoT Hub, in the page's sort only. + */ + PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); 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 a81368450c..21b2f42c7d 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 @@ -4,6 +4,7 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -49,6 +51,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -744,4 +747,90 @@ class DefaultIotHubServiceTest { return item; } + @Test + void findInstalledItemsUpdatesFirst_passesThePublishedVersionOfEachInstalledItem() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + UUID unpublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker, unpublished)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()).put("publishedVersion", "1.0.1"); + // An item IoT Hub publishes no version of: nothing to update to + published.addObject().put("itemId", unpublished.toString()).putNull("publishedVersionId").putNull("publishedVersion"); + when(iotHubRestClient.getPublishedVersions(List.of(tracker, unpublished))).thenReturn(published); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, List.of("DEVICE"), null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, List.of("DEVICE"), null, Map.of(tracker, trackerPublished), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_withoutAnAnswerFromIotHub_listsInThePageSort() { + UUID tracker = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + when(iotHubRestClient.getPublishedVersions(any())).thenThrow(new RuntimeException("IoT Hub is down")); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_nothingInstalled_doesNotAskIotHub() { + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of()); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubRestClient, never()).getPublishedVersions(any()); + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); + } + + @Test + void findInstalledItemsUpdatesFirst_asksIotHubInChunksOf100() { + List itemIds = Stream.generate(UUID::randomUUID).limit(150).toList(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(itemIds); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(JacksonUtil.newArrayNode()); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); + + verify(iotHubRestClient).getPublishedVersions(itemIds.subList(0, 100)); + verify(iotHubRestClient).getPublishedVersions(itemIds.subList(100, 150)); + } + + @Test + void findInstalledItemsUpdatesFirst_nextPages_doNotAskIotHubAgain() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); + PageLink second = new PageLink(10, 1); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); + service.findInstalledItemsUpdatesFirst(tenantId, null, null, second); + + verify(iotHubRestClient).getPublishedVersions(any()); + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), second); + } + + @Test + void findInstalledItemsUpdatesFirst_skipsAnEntryThatIsNotAPairOfIds() { + UUID tracker = UUID.randomUUID(); + UUID trackerPublished = UUID.randomUUID(); + when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); + ArrayNode published = JacksonUtil.newArrayNode(); + published.addObject().put("itemId", "not-an-id").put("publishedVersionId", UUID.randomUUID().toString()); + published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); + when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); + PageLink pageLink = new PageLink(10); + + service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); + + verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), pageLink); + } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index b99cf18981..216f689b80 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first + PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 072506dfca..272d6ea6f1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,6 +25,10 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first + PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink); + List findInstalledItemIdsByTenantId(TenantId tenantId); List findInstalledItemIdsByTenantIdAndItemIdIn(TenantId tenantId, Collection itemIds); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index d69060cd94..86678f9acf 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -49,6 +49,13 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { return iotHubInstalledItemDao.findByTenantId(tenantId, itemTypes, itemId, pageLink); } + @Override + public PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); + return iotHubInstalledItemDao.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 693166b7e0..94f56a043f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -45,6 +45,37 @@ interface IotHubInstalledItemRepository extends JpaRepository findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); + /** + * As {@link #findByTenantId}, with the items that have an update first: an item of {@code publishedItemIds} whose + * installed version is not among {@code publishedVersionIds}. The page's sort applies within each of the two groups. + */ + @Query(value = """ + SELECT item FROM IotHubInstalledItemEntity item + WHERE item.tenantId = :tenantId + AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:textSearch IS NULL + OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) + ORDER BY CASE WHEN item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds THEN 0 ELSE 1 END + """, + countQuery = """ + SELECT COUNT(item) FROM IotHubInstalledItemEntity item + WHERE item.tenantId = :tenantId + AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:textSearch IS NULL + OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true + OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) + """) + Page findByTenantIdUpdatesFirst(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); + @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index d07d8f5dd4..40fbea4a7d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -57,6 +57,23 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + if (publishedVersionIds == null || publishedVersionIds.isEmpty()) { + return findByTenantId(tenantId, itemTypes, itemId, pageLink); + } + return DaoUtil.toPageData(repository.findByTenantIdUpdatesFirst( + tenantId.getId(), + itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, + itemId, + StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), + publishedVersionIds.keySet(), + publishedVersionIds.values(), + toPageRequest(pageLink)) + ); + } + @Override public List findInstalledItemIdsByTenantId(TenantId tenantId) { return repository.findInstalledItemIdsByTenantId(tenantId.getId()); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java new file mode 100644 index 0000000000..b024b5a29d --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.dao.service; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@DaoSqlTest +public class IotHubInstalledItemServiceTest extends AbstractServiceTest { + + @Autowired + IotHubInstalledItemService installedItemService; + + private final UUID trackerItemId = UUID.randomUUID(); + private final UUID sensorItemId = UUID.randomUUID(); + private final UUID unpublishedItemId = UUID.randomUUID(); + private final UUID trackerPublished = UUID.randomUUID(); + private final UUID sensorPublished = UUID.randomUUID(); + + private void install(String name, UUID itemId, UUID versionId) { + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setTenantId(tenantId); + item.setItemId(itemId); + item.setItemVersionId(versionId); + item.setItemName(name); + item.setItemType("WIDGET"); + item.setVersion("1.0.0"); + item.setDescriptor(new WidgetInstalledItemDescriptor()); + installedItemService.save(tenantId, item); + } + + /** a and c are up to date, b and d have an update (d is a second install of a's item in an older version), e has no published version. */ + private void installFive() { + install("a", sensorItemId, sensorPublished); + install("b", trackerItemId, UUID.randomUUID()); + install("c", sensorItemId, sensorPublished); + install("d", sensorItemId, UUID.randomUUID()); + install("e", unpublishedItemId, UUID.randomUUID()); + } + + private Map published() { + return Map.of(trackerItemId, trackerPublished, sensorItemId, sensorPublished); + } + + private static List names(PageData page) { + return page.getData().stream().map(IotHubInstalledItem::getItemName).toList(); + } + + @Test + public void updatesFirst_itemsWithAnUpdateComeFirst_eachGroupInThePageSort() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), byName); + + assertThat(names(page)).containsExactly("b", "d", "a", "c", "e"); + assertThat(page.getTotalElements()).isEqualTo(5); + } + + @Test + public void updatesFirst_pagesKeepTheOrderAndTheTotal() { + installFive(); + SortOrder byNameDesc = new SortOrder("itemName", SortOrder.Direction.DESC); + + PageData first = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), + new PageLink(2, 0, null, byNameDesc)); + PageData second = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), + new PageLink(2, 1, null, byNameDesc)); + + assertThat(names(first)).containsExactly("d", "b"); + assertThat(names(second)).containsExactly("e", "c"); + assertThat(first.getTotalElements()).isEqualTo(5); + assertThat(first.hasNext()).isTrue(); + } + + @Test + public void updatesFirst_keepsTheFilters() { + installFive(); + // "b" is in no item type or version, only in the name of b + PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, List.of("WIDGET"), null, published(), search); + + assertThat(names(page)).containsExactly("b"); + assertThat(page.getTotalElements()).isEqualTo(1); + } + + @Test + public void updatesFirst_withoutPublishedVersions_isThePageSortOnly() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), byName); + + assertThat(names(page)).containsExactly("a", "b", "c", "d", "e"); + } + +} 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 fa040e8632..b7f0f78287 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 @@ -238,8 +238,12 @@ export class IotHubApiService { ); } + /** + * updatesFirst: the items installed in a version other than the one IoT Hub publishes now come first, then the rest, + * each in the page's sort. + */ public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], - itemId?: string, config?: IotHubRequestConfig): Observable> { + itemId?: string, config?: IotHubRequestConfig, updatesFirst = false): Observable> { let query = pageLink.toQuery(); if (itemTypes) { const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; @@ -248,6 +252,9 @@ export class IotHubApiService { if (itemId) { query += `&itemId=${itemId}`; } + if (updatesFirst) { + query += '&updatesFirst=true'; + } return this.http.get>( `/api/iot-hub/installedItems${query}`, { params: this.buildParams(config) } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3c196cdb66..9202f5937f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -249,7 +249,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - void this.checkConverterUpdates(); + // From the first page: the items with an update come first now, wherever their install date put them + this.pageIndex = 0; + if (this.paginator) { + this.paginator.pageIndex = 0; + } + this.loadData(); }, error: () => { this.isCheckingUpdates = false; @@ -341,7 +346,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}).subscribe({ + // Once the updates are checked, the items with one come first; the page of one item's versions keeps its sort + const updatesFirst = this.updatesChecked && !this.itemVersion; + this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}, updatesFirst).subscribe({ next: (data) => { this.dataSource = data.data; this.totalElements = data.totalElements; From a1e4e33b2bfcc4a7ed9877e8fe1be6057f1063b0 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 10:49:56 +0200 Subject: [PATCH 02/18] IoT Hub installed items: after Check for updates only the items with an update, no server cache (PROD-9326) --- .../server/controller/IotHubController.java | 26 +++-- .../service/iot_hub/DefaultIotHubService.java | 54 ---------- .../service/iot_hub/IotHubRestClient.java | 15 +-- .../server/service/iot_hub/IotHubService.java | 12 --- .../iot_hub/DefaultIotHubServiceTest.java | 89 --------------- .../dao/iot_hub/IotHubInstalledItemDao.java | 6 +- .../iot_hub/IotHubInstalledItemService.java | 6 +- .../IotHubInstalledItemServiceImpl.java | 19 +++- .../IotHubInstalledItemRepository.java | 30 ++---- .../iot_hub/JpaIotHubInstalledItemDao.java | 10 +- .../IotHubInstalledItemServiceTest.java | 50 ++++----- .../src/app/core/http/iot-hub-api.service.ts | 45 +++++--- ...t-hub-installed-items-table.component.html | 12 ++- ...iot-hub-installed-items-table.component.ts | 102 +++++++++++++++--- .../iot-hub-installed-items.component.html | 45 ++++++-- .../iot-hub-installed-items.component.scss | 29 +++++ .../iot-hub-installed-items.component.ts | 23 +++- .../assets/locale/locale.constant-en_US.json | 8 ++ 18 files changed, 309 insertions(+), 272 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 56ed32b14e..332a95242b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -140,17 +140,31 @@ public class IotHubController extends BaseController { @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder, @RequestParam(required = false) List itemTypes, - @RequestParam(required = false) UUID itemId, - @RequestParam(required = false, defaultValue = "false") boolean updatesFirst) throws ThingsboardException { + @RequestParam(required = false) UUID itemId) throws ThingsboardException { checkAllPermissions(); PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); - if (updatesFirst) { - // The items installed in a version other than the one IoT Hub publishes now come first, sorted as asked - return iotHubService.findInstalledItemsUpdatesFirst(getTenantId(), itemTypes, itemId, pageLink); - } return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); } + /** + * The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates: + * the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL. + */ + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/installedItems/withUpdates") + @ResponseBody + public PageData getInstalledItemsWithUpdates(@RequestParam int pageSize, + @RequestParam int page, + @RequestParam(required = false) String textSearch, + @RequestParam(required = false) String sortProperty, + @RequestParam(required = false) String sortOrder, + @RequestParam(required = false) List itemTypes, + @RequestBody Map publishedVersionIds) throws ThingsboardException { + checkAllPermissions(); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/count") @ResponseBody 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 60f2391544..ddbe8ec5d7 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 @@ -5,9 +5,6 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -85,7 +82,6 @@ import org.thingsboard.server.service.security.permission.AccessControlService; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -142,15 +138,6 @@ public class DefaultIotHubService implements IotHubService { private final ProjectInfo projectInfo; private final DevicePackageEntities devicePackageEntities; - // How many item ids one request for their published versions takes - private static final int PUBLISHED_VERSIONS_CHUNK_SIZE = 100; - // The installed items list asks for these on every page while it shows the updates first, so IoT Hub is asked once - // a minute per tenant at most; an answer it failed to give is kept too, so a slow IoT Hub doesn't slow down every page - private final Cache> publishedVersionIdsCache = Caffeine.newBuilder() - .expireAfterWrite(Duration.ofMinutes(1)) - .maximumSize(10_000) - .build(); - // Field names of the marketplace version JSON payload. Both the install path and the // install-plan resolver parse the same shape, so the contract lives here in one place. private static final String FIELD_ID = "id"; @@ -816,47 +803,6 @@ public class DefaultIotHubService implements IotHubService { return keys; } - @Override - public PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { - Map publishedVersionIds = publishedVersionIdsCache.get(tenantId, this::findPublishedVersionIds); - return iotHubInstalledItemService.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); - } - - /** - * IoT Hub's published version id by item id, of the items the tenant has installed. Asked in chunks, as IoT Hub may limit - * the ids of one request. Empty when IoT Hub doesn't answer: the list then shows in the page's sort only. - */ - private Map findPublishedVersionIds(TenantId tenantId) { - List itemIds = iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId); - Map publishedVersionIds = new HashMap<>(); - try { - for (List chunk : Lists.partition(itemIds, PUBLISHED_VERSIONS_CHUNK_SIZE)) { - JsonNode published = iotHubRestClient.getPublishedVersions(chunk); - if (published != null && published.isArray()) { - published.forEach(info -> putPublishedVersionId(tenantId, info, publishedVersionIds)); - } - } - } catch (RuntimeException e) { - log.warn("[{}] Failed to get the published versions of the installed items from IoT Hub", tenantId, e); - return Map.of(); - } - return publishedVersionIds; - } - - /** An entry of an item with no published version, or one that is not a pair of ids, adds nothing. */ - private static void putPublishedVersionId(TenantId tenantId, JsonNode info, Map publishedVersionIds) { - String itemId = info.path("itemId").asText(null); - String versionId = info.path("publishedVersionId").asText(null); - if (itemId == null || versionId == null) { - return; - } - try { - publishedVersionIds.put(UUID.fromString(itemId), UUID.fromString(versionId)); - } catch (IllegalArgumentException e) { - log.debug("[{}] Skipping a published version from IoT Hub that is not a pair of ids: {}", tenantId, info); - } - } - /** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */ @Override public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) { diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java index 11950d86c4..a12470271f 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java @@ -1,6 +1,5 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -19,8 +18,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; -import java.util.Collection; -import java.util.UUID; @Component @TbCoreComponent @@ -72,16 +69,6 @@ public class IotHubRestClient { } } - /** - * IoT Hub's published version of each item: {@code itemId}, {@code publishedVersionId} and {@code publishedVersion}, - * the last two null for an item with no published version. - */ - public JsonNode getPublishedVersions(Collection itemIds) { - String url = baseUrl + "/api/versions/publishedVersions"; - log.debug("Fetching IoT Hub published versions of {} items: {}", itemIds.size(), url); - return restTemplate.postForObject(url, itemIds, JsonNode.class); - } - public byte[] getVersionFileData(String versionId) { String url = baseUrl + "/api/versions/" + versionId + "/fileData"; log.debug("Fetching IoT Hub version file data: {}", url); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index dfb9e068c4..e1d0cd666b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -9,14 +9,8 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; -import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; -import org.thingsboard.server.common.data.page.PageData; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.service.security.model.SecurityUser; -import java.util.List; -import java.util.UUID; - public interface IotHubService { InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); @@ -29,12 +23,6 @@ public interface IotHubService { InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); - /** - * The tenant's installed items, those with an update in IoT Hub first: installed in a version other than the item's - * published one. Without an answer from IoT Hub, in the page's sort only. - */ - PageData findInstalledItemsUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); 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 21b2f42c7d..a81368450c 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 @@ -4,7 +4,6 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; @@ -33,7 +32,6 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -51,7 +49,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -747,90 +744,4 @@ class DefaultIotHubServiceTest { return item; } - @Test - void findInstalledItemsUpdatesFirst_passesThePublishedVersionOfEachInstalledItem() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - UUID unpublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker, unpublished)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()).put("publishedVersion", "1.0.1"); - // An item IoT Hub publishes no version of: nothing to update to - published.addObject().put("itemId", unpublished.toString()).putNull("publishedVersionId").putNull("publishedVersion"); - when(iotHubRestClient.getPublishedVersions(List.of(tracker, unpublished))).thenReturn(published); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, List.of("DEVICE"), null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, List.of("DEVICE"), null, Map.of(tracker, trackerPublished), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_withoutAnAnswerFromIotHub_listsInThePageSort() { - UUID tracker = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - when(iotHubRestClient.getPublishedVersions(any())).thenThrow(new RuntimeException("IoT Hub is down")); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_nothingInstalled_doesNotAskIotHub() { - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of()); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubRestClient, never()).getPublishedVersions(any()); - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), pageLink); - } - - @Test - void findInstalledItemsUpdatesFirst_asksIotHubInChunksOf100() { - List itemIds = Stream.generate(UUID::randomUUID).limit(150).toList(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(itemIds); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(JacksonUtil.newArrayNode()); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); - - verify(iotHubRestClient).getPublishedVersions(itemIds.subList(0, 100)); - verify(iotHubRestClient).getPublishedVersions(itemIds.subList(100, 150)); - } - - @Test - void findInstalledItemsUpdatesFirst_nextPages_doNotAskIotHubAgain() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); - PageLink second = new PageLink(10, 1); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, new PageLink(10)); - service.findInstalledItemsUpdatesFirst(tenantId, null, null, second); - - verify(iotHubRestClient).getPublishedVersions(any()); - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), second); - } - - @Test - void findInstalledItemsUpdatesFirst_skipsAnEntryThatIsNotAPairOfIds() { - UUID tracker = UUID.randomUUID(); - UUID trackerPublished = UUID.randomUUID(); - when(iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId)).thenReturn(List.of(tracker)); - ArrayNode published = JacksonUtil.newArrayNode(); - published.addObject().put("itemId", "not-an-id").put("publishedVersionId", UUID.randomUUID().toString()); - published.addObject().put("itemId", tracker.toString()).put("publishedVersionId", trackerPublished.toString()); - when(iotHubRestClient.getPublishedVersions(any())).thenReturn(published); - PageLink pageLink = new PageLink(10); - - service.findInstalledItemsUpdatesFirst(tenantId, null, null, pageLink); - - verify(iotHubInstalledItemService).findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(tracker, trackerPublished), pageLink); - } - } diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index 216f689b80..7373a8fb81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java @@ -25,9 +25,9 @@ public interface IotHubInstalledItemDao extends Dao { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first - PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 272d6ea6f1..17f3361738 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java @@ -25,9 +25,9 @@ public interface IotHubInstalledItemService { PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); - // publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first - PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink); + // publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version + PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index 86678f9acf..89f7d636b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -14,6 +14,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.model.sql.IotHubInstalledItemEntity; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -50,10 +51,22 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { } @Override - public PageData findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink) { + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); - return iotHubInstalledItemDao.findByTenantIdUpdatesFirst(tenantId, itemTypes, itemId, publishedVersionIds, pageLink); + // An item IoT Hub publishes no version of has nothing to update to + Map published = new HashMap<>(); + if (publishedVersionIds != null) { + publishedVersionIds.forEach((itemId, versionId) -> { + if (itemId != null && versionId != null) { + published.put(itemId, versionId); + } + }); + } + if (published.isEmpty()) { + return PageData.emptyPageData(); + } + return iotHubInstalledItemDao.findByTenantIdWithUpdates(tenantId, itemTypes, published, pageLink); } @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 94f56a043f..c86f7edadf 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -46,35 +46,25 @@ interface IotHubInstalledItemRepository extends JpaRepository findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); /** - * As {@link #findByTenantId}, with the items that have an update first: an item of {@code publishedItemIds} whose - * installed version is not among {@code publishedVersionIds}. The page's sort applies within each of the two groups. + * As {@link #findByTenantId}, only the items with an update: an item of {@code publishedItemIds} whose installed version + * is not among {@code publishedVersionIds}. Version ids are unique, so this is "not the published version of its item". */ - @Query(value = """ + @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId + AND item.itemId IN :publishedItemIds + AND item.itemVersionId NOT IN :publishedVersionIds AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) - AND (:textSearch IS NULL - OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) - ORDER BY CASE WHEN item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds THEN 0 ELSE 1 END - """, - countQuery = """ - SELECT COUNT(item) FROM IotHubInstalledItemEntity item - WHERE item.tenantId = :tenantId - AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantIdUpdatesFirst(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, - @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, - @Param("publishedItemIds") Collection publishedItemIds, - @Param("publishedVersionIds") Collection publishedVersionIds, - Pageable pageable); + Page findByTenantIdWithUpdates(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("textSearch") String textSearch, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index 40fbea4a7d..1d05081d99 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -58,15 +58,11 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantIdUpdatesFirst(TenantId tenantId, List itemTypes, UUID itemId, - Map publishedVersionIds, PageLink pageLink) { - if (publishedVersionIds == null || publishedVersionIds.isEmpty()) { - return findByTenantId(tenantId, itemTypes, itemId, pageLink); - } - return DaoUtil.toPageData(repository.findByTenantIdUpdatesFirst( + public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, + Map publishedVersionIds, PageLink pageLink) { + return DaoUtil.toPageData(repository.findByTenantIdWithUpdates( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, - itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), publishedVersionIds.keySet(), publishedVersionIds.values(), diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index b024b5a29d..560b3cf0d0 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -11,6 +11,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -59,52 +60,53 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { } @Test - public void updatesFirst_itemsWithAnUpdateComeFirst_eachGroupInThePageSort() { + public void withUpdates_onlyTheItemsWithAnUpdate_inThePageSort() { installFive(); - PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.DESC)); - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), byName); + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), byName); - assertThat(names(page)).containsExactly("b", "d", "a", "c", "e"); - assertThat(page.getTotalElements()).isEqualTo(5); + assertThat(names(page)).containsExactly("d", "b"); + assertThat(page.getTotalElements()).isEqualTo(2); } @Test - public void updatesFirst_pagesKeepTheOrderAndTheTotal() { + public void withUpdates_pagesAndTotal() { installFive(); - SortOrder byNameDesc = new SortOrder("itemName", SortOrder.Direction.DESC); + SortOrder byName = new SortOrder("itemName", SortOrder.Direction.ASC); - PageData first = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), - new PageLink(2, 0, null, byNameDesc)); - PageData second = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), - new PageLink(2, 1, null, byNameDesc)); + PageData first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 0, null, byName)); + PageData second = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(), + new PageLink(1, 1, null, byName)); - assertThat(names(first)).containsExactly("d", "b"); - assertThat(names(second)).containsExactly("e", "c"); - assertThat(first.getTotalElements()).isEqualTo(5); + assertThat(names(first)).containsExactly("b"); + assertThat(names(second)).containsExactly("d"); + assertThat(first.getTotalElements()).isEqualTo(2); assertThat(first.hasNext()).isTrue(); + assertThat(second.hasNext()).isFalse(); } @Test - public void updatesFirst_keepsTheFilters() { + public void withUpdates_keepsTheSearchAndTheTypes() { installFive(); // "b" is in no item type or version, only in the name of b PageLink search = new PageLink(10, 0, "b", new SortOrder("itemName", SortOrder.Direction.ASC)); - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, List.of("WIDGET"), null, published(), search); - - assertThat(names(page)).containsExactly("b"); - assertThat(page.getTotalElements()).isEqualTo(1); + assertThat(names(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("WIDGET"), published(), search))) + .containsExactly("b"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, List.of("DEVICE"), published(), + new PageLink(10)).getData()).isEmpty(); } @Test - public void updatesFirst_withoutPublishedVersions_isThePageSortOnly() { + public void withUpdates_withoutPublishedVersions_isEmpty() { installFive(); - PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); - - PageData page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), byName); + Map unpublished = new HashMap<>(); + unpublished.put(unpublishedItemId, null); - assertThat(names(page)).containsExactly("a", "b", "c", "d", "e"); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, Map.of(), new PageLink(10)).getData()).isEmpty(); + assertThat(installedItemService.findByTenantIdWithUpdates(tenantId, null, unpublished, new PageLink(10)).getData()).isEmpty(); } } 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 b7f0f78287..b9674e232c 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 @@ -4,7 +4,8 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Store } from '@ngrx/store'; -import { Observable } from 'rxjs'; +import { forkJoin, Observable, of } from 'rxjs'; +import { map } from 'rxjs/operators'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { @@ -50,6 +51,8 @@ export function iotHubResourceUrl(baseUrl: string, path: string): string { return `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`; } +const PUBLISHED_VERSIONS_CHUNK_SIZE = 100; + export interface IotHubRequestConfig { ignoreLoading?: boolean; ignoreErrors?: boolean; @@ -238,12 +241,8 @@ export class IotHubApiService { ); } - /** - * updatesFirst: the items installed in a version other than the one IoT Hub publishes now come first, then the rest, - * each in the page's sort. - */ public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], - itemId?: string, config?: IotHubRequestConfig, updatesFirst = false): Observable> { + itemId?: string, config?: IotHubRequestConfig): Observable> { let query = pageLink.toQuery(); if (itemTypes) { const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; @@ -252,15 +251,29 @@ export class IotHubApiService { if (itemId) { query += `&itemId=${itemId}`; } - if (updatesFirst) { - query += '&updatesFirst=true'; - } return this.http.get>( `/api/iot-hub/installedItems${query}`, { params: this.buildParams(config) } ); } + /** + * The installed items with an update: publishedVersionIds is IoT Hub's published version id by item id, as Check for + * updates got it. The server keeps the items installed in another version, with the page's sort, search and types. + */ + public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, + config?: IotHubRequestConfig): Observable> { + let query = pageLink.toQuery(); + if (itemTypes?.length) { + query += itemTypes.map(t => `&itemTypes=${t}`).join(''); + } + return this.http.post>( + `/api/iot-hub/installedItems/withUpdates${query}`, + publishedVersionIds, + { params: this.buildParams(config) } + ); + } + public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable { let url = '/api/iot-hub/installedItems/count'; if (itemType) { @@ -300,12 +313,20 @@ export class IotHubApiService { ); } + /** Asked in requests of 100 item ids at most, so a tenant with many items doesn't send IoT Hub one huge request. */ public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { - return this.http.post( + if (!itemIds.length) { + return of([]); + } + const chunks: string[][] = []; + for (let i = 0; i < itemIds.length; i += PUBLISHED_VERSIONS_CHUNK_SIZE) { + chunks.push(itemIds.slice(i, i + PUBLISHED_VERSIONS_CHUNK_SIZE)); + } + return forkJoin(chunks.map(chunk => this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, - itemIds, + chunk, { params: this.buildParams(config) } - ); + ))).pipe(map(results => results.flat())); } public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 7f1dbac04e..3af83f064f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,7 +125,17 @@ - @if (!isLoading && dataSource.length === 0) { + @if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { + +
+
+

{{ 'iot-hub.all-items-up-to-date' | translate }}

+

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

+ +
+ } @else if (!isLoading && dataSource.length === 0) {

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

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 9202f5937f..f1bf82d05e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -44,7 +44,7 @@ import { loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, forkJoin } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -82,6 +82,15 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; + // IoT Hub didn't answer Check for updates: the page says so quietly, the list works without it + updatesCheckFailed = false; + // After Check for updates the list shows only the items with an update, until the user asks for all of them + onlyUpdates = false; + // How many installed items have an update, and how many there are, of all types and with no search; null while not known + updatesCount: number | null = null; + installedCount = 0; + // A later load (another page, mode, sort or search) wins over an earlier one that answers last + private loadRun = 0; private widgetResize$: ResizeObserver; @@ -161,7 +170,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, deleteItem(item: IotHubInstalledItem): void { this.iotHubActions.deleteItem(item).subscribe(deleted => { if (deleted) { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -191,7 +200,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { if (result === 'updated' || result === 'deleted') { - this.loadData(); + this.reloadAfterChange(); } }); }); @@ -241,31 +250,75 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true })) + // An IoT Hub that doesn't answer is not a page error: the page says so next to the button, the list works without it + switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - // From the first page: the items with an update come first now, wherever their install date put them - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } - this.loadData(); + this.showOnlyUpdates(true); + this.loadUpdatesCount(); }, error: () => { this.isCheckingUpdates = false; + this.updatesCheckFailed = true; + } + }); + } + + /** Only the items with an update, or all of them; from the first page, as the list changes. */ + showOnlyUpdates(onlyUpdates: boolean): void { + this.onlyUpdates = onlyUpdates; + this.pageIndex = 0; + if (this.paginator) { + this.paginator.pageIndex = 0; + } + this.loadData(); + } + + /** IoT Hub's published version id by item id, of the items it publishes a version of. */ + private publishedVersionIds(): Record { + const ids: Record = {}; + this.publishedVersionMap.forEach((info, itemId) => { + if (info.publishedVersionId) { + ids[itemId] = info.publishedVersionId; } }); + return ids; + } + + /** After an item is updated or removed: the list and, once the updates are checked, the counts in the header. */ + private reloadAfterChange(): void { + this.loadData(); + if (this.updatesChecked && !this.itemVersion) { + this.loadUpdatesCount(); + } + } + + private loadUpdatesCount(): void { + this.updatesCount = null; + forkJoin({ + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) + }).subscribe({ + next: ({ withUpdates, installed }) => { + this.updatesCount = withUpdates.totalElements; + this.installedCount = installed; + this.cd.markForCheck(); + }, + // The header then shows only the buttons + error: () => this.cd.markForCheck() + }); } updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { - this.loadData(); + this.reloadAfterChange(); } }); } @@ -346,18 +399,37 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // Once the updates are checked, the items with one come first; the page of one item's versions keeps its sort - const updatesFirst = this.updatesChecked && !this.itemVersion; - this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}, updatesFirst).subscribe({ + // The page of one item's versions has its own published version and lists all of them + const items$ = this.onlyUpdates && !this.itemVersion + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true}) + : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); + const run = ++this.loadRun; + items$.subscribe({ next: (data) => { + if (run !== this.loadRun) { + return; + } + // The last page emptied (its last item updated or removed): go to the page that is last now + if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { + this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; + if (this.paginator) { + this.paginator.pageIndex = this.pageIndex; + } + this.loadData(); + return; + } this.dataSource = data.data; this.totalElements = data.totalElements; this.isLoading = false; - if (this.updatesChecked && !this.itemVersion) { + // In the list of items with an update their version update shows, not the converter's + if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } }, error: () => { + if (run !== this.loadRun) { + return; + } this.dataSource = []; this.totalElements = 0; this.isLoading = false; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7591b1dc5a..f95bef69d7 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -1,7 +1,8 @@
@@ -15,14 +16,42 @@

{{ 'iot-hub.installed-items' | translate }}

@if (!updatesChecked) { - + +
+ } @else { + +
+ @if (updatesCount !== null) { + + @if (updatesCount > 0) { + arrow_circle_up + {{ (updatesCount === 1 ? 'iot-hub.item-with-update' : 'iot-hub.items-with-update') | translate:{ count: updatesCount, total: installedCount } }} + } @else { + check_circle + {{ 'iot-hub.all-items-up-to-date' | translate }} + } + + } + @if (onlyUpdates) { + + } @else if ((updatesCount ?? 0) > 0) { + + } +
}
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss index 1ade0222c5..eab61c2c2a 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss @@ -29,6 +29,35 @@ margin-bottom: 32px; } +// After Check for updates: "N items have an update" and Show all items / Show only updates +.tb-installed-updates-note { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 14px; + line-height: 20px; + letter-spacing: 0.2px; + color: rgba(0, 0, 0, 0.76); + + mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } + + .tb-installed-updates-available { + color: #f44336; + } + + .tb-installed-updates-none { + color: #198038; + } + + .tb-installed-updates-failed { + color: #f66716; + } +} + .tb-installed-title { font-size: 36px; font-weight: 500; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts index 1af2d5ed2c..47aa3e5080 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -107,4 +108,24 @@ export class TbIotHubInstalledItemsComponent implements OnInit, OnDestroy { get updatesChecked(): boolean { return this.tableComponent?.updatesChecked || false; } + + get updatesCheckFailed(): boolean { + return this.tableComponent?.updatesCheckFailed || false; + } + + get onlyUpdates(): boolean { + return this.tableComponent?.onlyUpdates || false; + } + + get updatesCount(): number | null { + return this.tableComponent?.updatesCount ?? null; + } + + get installedCount(): number { + return this.tableComponent?.installedCount || 0; + } + + showOnlyUpdates(onlyUpdates: boolean): void { + this.tableComponent?.showOnlyUpdates(onlyUpdates); + } } 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 88b545b9d2..c2c51b4632 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6494,6 +6494,14 @@ "install-partial-desc": "'{{name}}' was installed, but some required items were missing.", "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", + "check-for-updates-failed": "Couldn't check for updates", + "check-for-updates-try-again": "Try again", + "item-with-update": "1 of {{total}} items has an update", + "items-with-update": "{{count}} of {{total}} items have an update", + "all-items-up-to-date": "All items are up to date", + "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", + "show-all-items": "Show all items", + "show-only-updates": "Show only updates", "updates": "Updates", "up-to-date": "Up to date", "new-converter-available": "New converter available", From c1d8d73f2a6713d0ebaf07ac8d8837017b284a05 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 11:59:57 +0200 Subject: [PATCH 03/18] IoT Hub device package delete: a device profile devices use stays, with what it refers to, and the dialog says so (PROD-9340) --- .../service/iot_hub/DefaultIotHubService.java | 85 ++++++++++++++++++- .../iot_hub/InstalledItemKeptEntities.java | 10 ++- ...DefaultDevicePackageUpdateServiceTest.java | 2 +- .../iot_hub/DefaultIotHubServiceTest.java | 83 ++++++++++++++++++ .../iot-hub-delete-dialog.component.ts | 24 ++++-- .../iot-hub/iot-hub-installed-item.models.ts | 7 +- .../assets/locale/locale.constant-en_US.json | 1 + 7 files changed, 199 insertions(+), 13 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 ddbe8ec5d7..ff13b6378a 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 @@ -12,6 +12,7 @@ import org.springframework.stereotype.Service; import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.AssetProfile; @@ -91,8 +92,10 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.stream.Stream; @Service @TbCoreComponent @@ -720,7 +723,9 @@ public class DefaultIotHubService implements IotHubService { /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, - * and the ones the user had before and the package took as they were (use existing). + * and the ones the user had before and the package took as they were (use existing). A device profile that devices + * still use stays too, e.g. with the devices a LoRaWAN integration created, and so does what it refers to that the + * package created: TB deletes neither. * A kept integration loses the metadata entries the package added. */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, @@ -737,6 +742,8 @@ public class DefaultIotHubService implements IotHubService { List ordered = new ArrayList<>(createdEntityIds); Collections.reverse(ordered); ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size()))); + // What a kept profile refers to: its default rule chain and dashboard, which come after it in the order + Set referencedByKeptProfiles = new HashSet<>(); for (EntityId entityId : ordered) { if (usedExisting.contains(entityId.getId())) { log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); @@ -749,6 +756,17 @@ public class DefaultIotHubService implements IotHubService { removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); continue; } + if (referencedByKeptProfiles.contains(entityId.getId())) { + log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId()); + continue; + } + // The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration + long devices = countProfileDevices(tenantId, entityId, Set.of()); + if (devices > 0) { + log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); + continue; + } try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { @@ -811,16 +829,27 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item not found"); } List kept = new ArrayList<>(); + List keptForDevices = new ArrayList<>(); Set usedByItems = new HashSet<>(); int usedExistingCount = 0; + long devicesCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { Set usedExisting = usedExistingIds(dd); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); + // The delete removes these before the profiles, so they don't keep a profile; a kept device does + Set deletedDevices = new HashSet<>(); + dd.getCreatedEntityIds().stream() + .filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId())) + .forEach(id -> deletedDevices.add(id.getId())); + Set created = new HashSet<>(); + dd.getCreatedEntityIds().forEach(id -> created.add(id.getId())); + Set keptIds = new HashSet<>(); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId()); if (usedBy != null || taken) { - kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); + kept.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); } if (usedBy != null) { usedByItems.addAll(usedBy); @@ -829,8 +858,58 @@ public class DefaultIotHubService implements IotHubService { usedExistingCount++; } } + for (EntityId entityId : dd.getCreatedEntityIds()) { + long devices = keptIds.contains(entityId.getId()) ? 0 : countProfileDevices(tenantId, entityId, deletedDevices); + if (devices == 0) { + continue; + } + keptForDevices.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); + devicesCount += devices; + // What the profile refers to stays with it + for (EntityId reference : profileReferences(tenantId, entityId)) { + if (created.contains(reference.getId()) && keptIds.add(reference.getId())) { + keptForDevices.add(keptEntity(tenantId, reference)); + } + } + } + } + return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, keptForDevices, devicesCount); + } + + private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) { + return new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)); + } + + /** The default rule chains and dashboard of the device profile {@code profileId}: TB doesn't delete them while it refers to them. */ + private List profileReferences(TenantId tenantId, EntityId profileId) { + DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId())); + List references = new ArrayList<>(); + if (profile != null) { + Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId()) + .filter(Objects::nonNull) + .forEach(references::add); + } + return references; + } + + /** + * How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity. + * TB doesn't delete a profile that devices use. + */ + private long countProfileDevices(TenantId tenantId, EntityId entityId, Set excludedDevices) { + if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) { + return 0; + } + DeviceProfileId profileId = new DeviceProfileId(entityId.getId()); + long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements(); + for (UUID deviceId : excludedDevices) { + Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId)); + if (device != null && profileId.equals(device.getDeviceProfileId())) { + count--; + } } - return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount); + return Math.max(count, 0); } /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */ diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index ad517c5327..4d21db6b10 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; -/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ +/** + * What deleting an installed item keeps: what other installed items use too, what the user had before it, and the device + * profiles devices still use (a LoRaWAN integration creates its devices on the first uplink, not the package). + */ @Data @NoArgsConstructor @AllArgsConstructor @@ -20,6 +23,11 @@ public class InstalledItemKeptEntities { private int usedByItemsCount; // How many of the kept entities the user had before and the package took as they were (use existing) private int usedExistingCount; + // The package's device profiles that devices use and what they refer to (default rule chain, dashboard): TB deletes + // neither. Apart from entities, which an update reads as shared with other packages + private List keptForDevices; + // How many devices use those profiles + private long devicesCount; @Data @NoArgsConstructor diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 38595a0c71..82f5f6c1c9 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -308,7 +308,7 @@ class DefaultDevicePackageUpdateServiceTest { Dashboard shared = dashboard(9L); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); - when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0)); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of(), 0)); // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); 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 a81368450c..2ef9437115 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 @@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; @@ -39,10 +40,12 @@ import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService; import org.thingsboard.server.service.entitiy.converter.TbConverterService; import org.thingsboard.server.service.entitiy.device.TbDeviceService; import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService; +import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @@ -95,6 +98,10 @@ class DefaultIotHubServiceTest { private ConverterService converterService; @Mock private TbConverterService tbConverterService; + @Mock + private RuleChainService ruleChainService; + @Mock + private TbRuleChainService tbRuleChainService; @Spy @InjectMocks @@ -474,6 +481,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + noDevices(profile.getId()); when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); @@ -736,6 +744,81 @@ class DefaultIotHubServiceTest { return integration; } + @Test + void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndItsRuleChain_apartFromTheShared() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + Device packageDevice = new Device(new DeviceId(UUID.randomUUID())); + packageDevice.setDeviceProfileId(profile.getId()); + IotHubInstalledItem checked = devicePackage(ruleChainId, profile.getId(), packageDevice.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + // 3 devices on the profile: the package's own, which the delete removes first, and 2 the integration created + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(), 3, 3, true)); + when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr")); + when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + // An update reads entities as shared with other packages: the profile is not among them + assertThat(kept.getEntities()).isEmpty(); + assertThat(kept.getKeptForDevices()).containsExactly( + new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"), + new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR")); + assertThat(kept.getDevicesCount()).isEqualTo(2); + } + + @Test + void findKeptEntities_devicePackage_aKeptDeviceKeepsItsProfile() { + DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); + DeviceId sharedDeviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(profileId, sharedDeviceId); + IotHubInstalledItem other = devicePackage(sharedDeviceId); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + // The only device on the profile is the one another package uses: the delete keeps it, so it keeps the profile + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(sharedDeviceId), 1, 1, false)); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getKeptForDevices()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId); + assertThat(kept.getDevicesCount()).isEqualTo(1); + } + + @Test + void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndItsRuleChain() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())) + .thenReturn(new PageData<>(List.of(new DeviceId(UUID.randomUUID())), 1, 1, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(ruleChainService, never()).findRuleChainById(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + } + + private void noDevices(DeviceProfileId profileId) { + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any())) + .thenReturn(new PageData<>(List.of(), 0, 0, false)); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 88bdf96fff..5366e63dfc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -46,13 +46,23 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); - // Kept because other packages use them, because the user had them before the package, or both - const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : - !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; - this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length }); - this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length }); + const shared = kept?.entities ?? []; + const withDevices = kept?.keptForDevices ?? []; + if (shared.length || withDevices.length) { + this.keptReferences = [...shared, ...withDevices].map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); + const reasons: string[] = []; + if (shared.length) { + // Kept because other packages use them, because the user had them before the package, or both + const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : + !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; + reasons.push(this.translate.instant(reasonKey, { kept: shared.length })); + } + if (withDevices.length) { + const profiles = withDevices.filter(entity => entity.entityId.entityType === 'DEVICE_PROFILE').length; + reasons.push(this.translate.instant('iot-hub.remove-kept-devices', { profiles, devices: kept.devicesCount ?? 0 })); + } + this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + withDevices.length }); + this.keptReason = reasons.join(' '); } } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 07fac4bf63..5b7aad53b4 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -159,7 +159,7 @@ export interface ItemPublishedVersionInfo { publishedVersion: string; } -/** An entity that deleting an installed item keeps, because other installed items use it too. */ +/** An entity that deleting an installed item keeps. */ export interface IotHubKeptEntity { entityId: { id: string; entityType: string }; name: string; @@ -170,6 +170,11 @@ export interface IotHubInstalledItemKeptEntities { usedByItemsCount: number; // Of the kept entities, the ones the user had before and the package took as they were usedExistingCount: number; + // The package's device profiles that devices use (e.g. the ones a LoRaWAN integration created) and what they refer to: + // TB deletes neither. Absent from an older backend + keptForDevices?: IotHubKeptEntity[]; + // How many devices use those profiles + devicesCount?: number; } export interface IotHubInstalledItem extends BaseData<{id: string}> { 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 15ca6ed759..9d6c9e6726 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6449,6 +6449,7 @@ "remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }", "remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.", + "remove-kept-devices": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile} other {the device profiles} }, and ThingsBoard doesn't remove a profile in use. Delete the devices first to remove it.", "remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From b5d1210cae86d2b9f7d0946e8915657bccf512f6 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 12:19:58 +0200 Subject: [PATCH 04/18] IoT Hub installed items: one query for both lists, a failed load is not 'up to date', one ICU plural (PROD-9326 review) --- .../IotHubInstalledItemRepository.java | 33 +++++++------------ .../iot_hub/JpaIotHubInstalledItemDao.java | 26 +++++++++------ .../IotHubInstalledItemServiceTest.java | 9 +++++ ...t-hub-installed-items-table.component.html | 11 ++++++- ...iot-hub-installed-items-table.component.ts | 4 +++ .../iot-hub-installed-items.component.html | 2 +- .../assets/locale/locale.constant-en_US.json | 4 +-- 7 files changed, 54 insertions(+), 35 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index c86f7edadf..c09f8c12f5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java @@ -33,38 +33,29 @@ interface IotHubInstalledItemRepository extends JpaRepository findInstalledItemIdsByTenantIdAndItemIdIn(@Param("tenantId") UUID tenantId, @Param("itemIds") Collection itemIds); - @Query(""" - SELECT item FROM IotHubInstalledItemEntity item - WHERE item.tenantId = :tenantId - AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) - AND (:itemId IS NULL OR item.itemId = :itemId) - AND (:textSearch IS NULL - OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true - OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) - """) - Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, Pageable pageable); - /** - * As {@link #findByTenantId}, only the items with an update: an item of {@code publishedItemIds} whose installed version - * is not among {@code publishedVersionIds}. Version ids are unique, so this is "not the published version of its item". + * The tenant's installed items, by type, item and text. With {@code updatesOnly}, only the items with an update: an item + * of {@code publishedItemIds} whose installed version is not among {@code publishedVersionIds} (version ids are unique, + * so: not the published version of its item). A flag, as Hibernate can't type {@code :uuids IS NULL}. */ @Query(""" SELECT item FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId - AND item.itemId IN :publishedItemIds - AND item.itemVersionId NOT IN :publishedVersionIds AND (:itemTypes IS NULL OR item.itemType IN :itemTypes) + AND (:itemId IS NULL OR item.itemId = :itemId) + AND (:updatesOnly = false + OR (item.itemId IN :publishedItemIds AND item.itemVersionId NOT IN :publishedVersionIds)) AND (:textSearch IS NULL OR ilike(item.itemName, CONCAT('%', :textSearch, '%')) = true OR ilike(item.itemType, CONCAT('%', :textSearch, '%')) = true OR ilike(item.version, CONCAT('%', :textSearch, '%')) = true) """) - Page findByTenantIdWithUpdates(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, - @Param("textSearch") String textSearch, - @Param("publishedItemIds") Collection publishedItemIds, - @Param("publishedVersionIds") Collection publishedVersionIds, - Pageable pageable); + Page findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List itemTypes, + @Param("itemId") UUID itemId, @Param("textSearch") String textSearch, + @Param("updatesOnly") boolean updatesOnly, + @Param("publishedItemIds") Collection publishedItemIds, + @Param("publishedVersionIds") Collection publishedVersionIds, + Pageable pageable); @Query(""" SELECT COUNT(item) FROM IotHubInstalledItemEntity item diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index 1d05081d99..4c91e5137b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java @@ -48,24 +48,30 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { - return DaoUtil.toPageData(repository.findByTenantId( - tenantId.getId(), - itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, - itemId, - StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), - toPageRequest(pageLink)) - ); + return find(tenantId, itemTypes, itemId, null, pageLink); } @Override public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, Map publishedVersionIds, PageLink pageLink) { - return DaoUtil.toPageData(repository.findByTenantIdWithUpdates( + return find(tenantId, itemTypes, null, publishedVersionIds, pageLink); + } + + // Never matches: the query binds the published ids even when it doesn't filter by them + private static final Set NO_IDS = Set.of(new UUID(0, 0)); + + // One query for both lists, so the only-updates list filters and searches as the plain one does + private PageData find(TenantId tenantId, List itemTypes, UUID itemId, + Map publishedVersionIds, PageLink pageLink) { + boolean updatesOnly = publishedVersionIds != null; + return DaoUtil.toPageData(repository.findByTenantId( tenantId.getId(), itemTypes == null || itemTypes.isEmpty() ? null : itemTypes, + itemId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), - publishedVersionIds.keySet(), - publishedVersionIds.values(), + updatesOnly, + updatesOnly ? publishedVersionIds.keySet() : NO_IDS, + updatesOnly ? publishedVersionIds.values() : NO_IDS, toPageRequest(pageLink)) ); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index 560b3cf0d0..8d7698d2ce 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -99,6 +99,15 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { new PageLink(10)).getData()).isEmpty(); } + @Test + public void plainList_sameQuery_isNotFiltered() { + installFive(); + PageLink byName = new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC)); + + assertThat(names(installedItemService.findByTenantId(tenantId, null, null, byName))).containsExactly("a", "b", "c", "d", "e"); + assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); + } + @Test public void withUpdates_withoutPublishedVersions_isEmpty() { installFive(); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 3af83f064f..c871f0492e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,7 +125,16 @@ - @if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { + @if (!isLoading && loadFailed && onlyUpdates) { + +
+
+

{{ 'iot-hub.installed-items-load-failed' | translate }}

+ +
+ } @else if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) {
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index f1bf82d05e..073bbe8171 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -88,6 +88,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, onlyUpdates = false; // How many installed items have an update, and how many there are, of all types and with no search; null while not known updatesCount: number | null = null; + // The last load of the list failed: the list is empty, but not because nothing has an update + loadFailed = false; installedCount = 0; // A later load (another page, mode, sort or search) wins over an earlier one that answers last private loadRun = 0; @@ -420,6 +422,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.dataSource = data.data; this.totalElements = data.totalElements; + this.loadFailed = false; this.isLoading = false; // In the list of items with an update their version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { @@ -432,6 +435,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.dataSource = []; this.totalElements = 0; + this.loadFailed = true; this.isLoading = false; } }); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index f95bef69d7..456fcdbd1f 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -39,7 +39,7 @@ @if (updatesCount > 0) { arrow_circle_up - {{ (updatesCount === 1 ? 'iot-hub.item-with-update' : 'iot-hub.items-with-update') | translate:{ count: updatesCount, total: installedCount } }} + {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} } @else { check_circle {{ 'iot-hub.all-items-up-to-date' | translate }} 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 c2c51b4632..44d86bf476 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6496,8 +6496,8 @@ "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", "check-for-updates-try-again": "Try again", - "item-with-update": "1 of {{total}} items has an update", - "items-with-update": "{{count}} of {{total}} items have an update", + "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", + "installed-items-load-failed": "Couldn't load the items with an update", "all-items-up-to-date": "All items are up to date", "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", From f6067b469e7eb26df15b057093addcdd4dd979d7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 12:30:36 +0200 Subject: [PATCH 05/18] IoT Hub device package delete: the dialog says why a profile devices use stays, with no advice to delete the devices (PROD-9340 review) --- .../components/iot-hub/iot-hub-delete-dialog.component.ts | 4 +++- ui-ngx/src/assets/locale/locale.constant-en_US.json | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 5366e63dfc..f1910d662d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -58,8 +58,10 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent entity.entityId.entityType === 'DEVICE_PROFILE').length; - reasons.push(this.translate.instant('iot-hub.remove-kept-devices', { profiles, devices: kept.devicesCount ?? 0 })); + const key = withDevices.length > profiles ? 'iot-hub.remove-kept-devices-with-references' : 'iot-hub.remove-kept-devices'; + reasons.push(this.translate.instant(key, { profiles, devices: kept.devicesCount ?? 0 })); } this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + withDevices.length }); this.keptReason = reasons.join(' '); 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 9d6c9e6726..07d90f4b3a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6449,7 +6449,8 @@ "remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }", "remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.", - "remove-kept-devices": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile} other {the device profiles} }, and ThingsBoard doesn't remove a profile in use. Delete the devices first to remove it.", + "remove-kept-devices": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile, so it stays} other {the device profiles, so they stay} }.", + "remove-kept-devices-with-references": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile, so it stays with the entities it uses} other {the device profiles, so they stay with the entities they use} }.", "remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From f8b8fa18e5c826fcd82f8f9bdea14ed1bf70ca40 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 13:18:52 +0200 Subject: [PATCH 06/18] IoT Hub device package delete: kept entities in one list, a group per reason (PROD-9340 review) --- .../iot-hub-delete-dialog.component.html | 14 +++++-- .../iot-hub-delete-dialog.component.scss | 36 ++++++++++++++++++ .../iot-hub-delete-dialog.component.ts | 37 +++++++++---------- .../assets/locale/locale.constant-en_US.json | 3 +- 4 files changed, 65 insertions(+), 25 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index f7bcce1201..4b0d6fc93c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -8,13 +8,21 @@

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

{{ description }}

- @if (keptReferences) { + @if (keptGroups.length) {
info_outline
{{ keptTitle }}
-
{{ keptReason }}
- + +
+ @for (group of keptGroups; track group.reason; let first = $first) { + @if (!first) { +
+ } +
{{ group.reason }}
+ + } +
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 63fa684164..15bbef3f08 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -23,3 +23,39 @@ color: rgba(0, 0, 0, 0.54); margin: 0; } + +// The kept entities: one white list as tb-image-references draws it, a group per reason +.tb-iot-hub-kept-groups { + display: flex; + flex-direction: column; + gap: 4px; + padding: 8px 0; + border-radius: 4px; + background: #fff; + border: 1px solid color-mix(in srgb, var(--tb-primary-500) 40%, transparent); + + // The groups share the outer border: no border of its own around each group's list + ::ng-deep tb-image-references table.tb-entities-list-table { + padding: 0 10px 0 4px !important; + background: transparent !important; + + &:before { + display: none !important; + } + } +} + +.tb-iot-hub-kept-reason { + padding: 4px 12px 2px; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.4px; + color: rgba(0, 0, 0, 0.6); +} + +.tb-iot-hub-kept-divider { + height: 1px; + margin: 6px 12px 4px; + background: rgba(0, 0, 0, 0.08); +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index f1910d662d..2fe865940e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -7,7 +7,7 @@ import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; +import { IotHubInstalledItemKeptEntities, IotHubKeptEntity } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ResourceReferences } from '@shared/models/resource.models'; @@ -30,10 +30,10 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent, @@ -48,23 +48,20 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); - const reasons: string[] = []; - if (shared.length) { - // Kept because other packages use them, because the user had them before the package, or both - const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : - !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; - reasons.push(this.translate.instant(reasonKey, { kept: shared.length })); - } - if (withDevices.length) { - // The profiles devices use, and what they use (default rule chains, dashboard), which stays with them - const profiles = withDevices.filter(entity => entity.entityId.entityType === 'DEVICE_PROFILE').length; - const key = withDevices.length > profiles ? 'iot-hub.remove-kept-devices-with-references' : 'iot-hub.remove-kept-devices'; - reasons.push(this.translate.instant(key, { profiles, devices: kept.devicesCount ?? 0 })); - } + const references = (entities: IotHubKeptEntity[]): ResourceReferences => + entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); + if (shared.length) { + // Kept because other packages use them, because the user had them before the package, or both + const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : + !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; + this.keptGroups.push({ reason: this.translate.instant(reasonKey, { kept: shared.length }), references: references(shared) }); + } + if (withDevices.length) { + // The profiles devices use, and what those profiles use (default rule chains, dashboard) + this.keptGroups.push({ reason: this.translate.instant('iot-hub.remove-kept-referenced'), references: references(withDevices) }); + } + if (this.keptGroups.length) { this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + withDevices.length }); - this.keptReason = reasons.join(' '); } } 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 07d90f4b3a..944ab99022 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6449,8 +6449,7 @@ "remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }", "remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.", - "remove-kept-devices": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile, so it stays} other {the device profiles, so they stay} }.", - "remove-kept-devices-with-references": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile, so it stays with the entities it uses} other {the device profiles, so they stay with the entities they use} }.", + "remove-kept-referenced": "Referenced by other tenant entities.", "remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From 53aeba0875fd565cfa494cac91a22de75ee681fc Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 17:42:07 +0200 Subject: [PATCH 07/18] IoT Hub installed items: the full list when no newer versions, the map bounded by installed items, retry with the counts (PROD-9326 review) --- .../IotHubInstalledItemServiceImpl.java | 12 +++--- .../IotHubInstalledItemServiceTest.java | 15 +++++++ ...t-hub-installed-items-table.component.html | 41 +++++++------------ ...iot-hub-installed-items-table.component.ts | 38 +++++++++-------- .../iot-hub-installed-items.component.html | 28 ++++++------- .../iot-hub-installed-items.component.scss | 29 ------------- .../assets/locale/locale.constant-en_US.json | 3 +- 7 files changed, 72 insertions(+), 94 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index 89f7d636b2..90fe24e0d6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java @@ -54,14 +54,16 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService { public PageData findByTenantIdWithUpdates(TenantId tenantId, List itemTypes, Map publishedVersionIds, PageLink pageLink) { validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); - // An item IoT Hub publishes no version of has nothing to update to + // Only the tenant's installed items, so the map can't outgrow the query's bind parameter limit; an item IoT Hub + // publishes no version of has nothing to update to Map published = new HashMap<>(); - if (publishedVersionIds != null) { - publishedVersionIds.forEach((itemId, versionId) -> { - if (itemId != null && versionId != null) { + if (publishedVersionIds != null && !publishedVersionIds.isEmpty()) { + for (UUID itemId : iotHubInstalledItemDao.findInstalledItemIdsByTenantId(tenantId)) { + UUID versionId = publishedVersionIds.get(itemId); + if (versionId != null) { published.put(itemId, versionId); } - }); + } } if (published.isEmpty()) { return PageData.emptyPageData(); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java index 8d7698d2ce..65fe12ae2b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java @@ -108,6 +108,21 @@ public class IotHubInstalledItemServiceTest extends AbstractServiceTest { assertThat(names(installedItemService.findByTenantId(tenantId, null, sensorItemId, byName))).containsExactly("a", "c", "d"); } + @Test + public void withUpdates_ignoresItemsTheTenantHasNotInstalled() { + installFive(); + Map published = new HashMap<>(published()); + for (int i = 0; i < 20_000; i++) { + published.put(UUID.randomUUID(), UUID.randomUUID()); + } + + PageData page = installedItemService.findByTenantIdWithUpdates(tenantId, null, published, + new PageLink(10, 0, null, new SortOrder("itemName", SortOrder.Direction.ASC))); + + // 40k bind parameters would be over PostgreSQL's limit of 32767 + assertThat(names(page)).containsExactly("b", "d"); + } + @Test public void withUpdates_withoutPublishedVersions_isEmpty() { installFive(); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index c871f0492e..b24e8bb4cf 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -125,34 +125,23 @@ - @if (!isLoading && loadFailed && onlyUpdates) { - + @if (!isLoading && dataSource.length === 0) {
-

{{ 'iot-hub.installed-items-load-failed' | translate }}

- -
- } @else if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) { - -
-
-

{{ 'iot-hub.all-items-up-to-date' | translate }}

-

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

- -
- } @else if (!isLoading && dataSource.length === 0) { -
-
-

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

-

{{ 'iot-hub.no-installed-items-text' | translate }}

- @if (hasActiveFilters()) { - + @if (loadFailed) { +

{{ 'iot-hub.unable-to-load' | translate }}

+

{{ 'iot-hub.unable-to-load-text' | translate }}

+ + } @else if (onlyUpdates && !hasActiveFilters()) { +

{{ 'iot-hub.all-items-up-to-date' | translate }}

+

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

+ + } @else { +

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

+

{{ 'iot-hub.no-installed-items-text' | translate }}

+ @if (hasActiveFilters()) { + + } }
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 073bbe8171..3ada8afee5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -82,16 +82,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; - // IoT Hub didn't answer Check for updates: the page says so quietly, the list works without it updatesCheckFailed = false; - // After Check for updates the list shows only the items with an update, until the user asks for all of them onlyUpdates = false; - // How many installed items have an update, and how many there are, of all types and with no search; null while not known + // Of all types and with no search; null while not known updatesCount: number | null = null; - // The last load of the list failed: the list is empty, but not because nothing has an update - loadFailed = false; installedCount = 0; - // A later load (another page, mode, sort or search) wins over an earlier one that answers last + loadFailed = false; private loadRun = 0; private widgetResize$: ResizeObserver; @@ -262,8 +258,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; - this.showOnlyUpdates(true); - this.loadUpdatesCount(); + // No newer versions: the full list, where a new default converter still shows + this.loadUpdatesCount(() => this.showOnlyUpdates((this.updatesCount ?? 0) > 0)); }, error: () => { this.isCheckingUpdates = false; @@ -272,7 +268,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } - /** Only the items with an update, or all of them; from the first page, as the list changes. */ showOnlyUpdates(onlyUpdates: boolean): void { this.onlyUpdates = onlyUpdates; this.pageIndex = 0; @@ -282,7 +277,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); } - /** IoT Hub's published version id by item id, of the items it publishes a version of. */ private publishedVersionIds(): Record { const ids: Record = {}; this.publishedVersionMap.forEach((info, itemId) => { @@ -293,7 +287,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return ids; } - /** After an item is updated or removed: the list and, once the updates are checked, the counts in the header. */ + /** Retries a failed load, and the header counts if they failed with it. */ + retryLoad(): void { + this.loadData(); + if (this.updatesCount === null) { + this.loadUpdatesCount(); + } + } + private reloadAfterChange(): void { this.loadData(); if (this.updatesChecked && !this.itemVersion) { @@ -301,7 +302,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } } - private loadUpdatesCount(): void { + private loadUpdatesCount(then?: () => void): void { this.updatesCount = null; forkJoin({ withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), @@ -311,9 +312,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.cd.markForCheck(); + then?.(); }, - // The header then shows only the buttons - error: () => this.cd.markForCheck() + error: () => { + this.cd.markForCheck(); + then?.(); + } }); } @@ -401,7 +405,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // The page of one item's versions has its own published version and lists all of them + // One item's versions page lists them all const items$ = this.onlyUpdates && !this.itemVersion ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true}) : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); @@ -411,7 +415,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, if (run !== this.loadRun) { return; } - // The last page emptied (its last item updated or removed): go to the page that is last now + // The last page emptied after an update or a removal if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; if (this.paginator) { @@ -424,7 +428,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.totalElements = data.totalElements; this.loadFailed = false; this.isLoading = false; - // In the list of items with an update their version update shows, not the converter's + // In the only-updates list the version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 456fcdbd1f..e70619ab4b 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -15,11 +15,11 @@

{{ 'iot-hub.installed-items' | translate }}

- @if (!updatesChecked) { -
+
+ @if (!updatesChecked) { @if (updatesCheckFailed) { - - warning + + warning {{ 'iot-hub.check-for-updates-failed' | translate }} } @@ -29,20 +29,18 @@ } @else { update } - {{ (updatesCheckFailed ? 'iot-hub.check-for-updates-try-again' : 'iot-hub.check-for-updates') | translate }} + {{ (updatesCheckFailed ? 'iot-hub.try-again' : 'iot-hub.check-for-updates') | translate }} -
- } @else { - -
+ } @else { @if (updatesCount !== null) { - + @if (updatesCount > 0) { - arrow_circle_up + arrow_circle_up {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} } @else { - check_circle - {{ 'iot-hub.all-items-up-to-date' | translate }} + + check_circle + {{ 'iot-hub.no-newer-versions' | translate }} } } @@ -51,8 +49,8 @@ } @else if ((updatesCount ?? 0) > 0) { } -
- } + } +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss index eab61c2c2a..1ade0222c5 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss @@ -29,35 +29,6 @@ margin-bottom: 32px; } -// After Check for updates: "N items have an update" and Show all items / Show only updates -.tb-installed-updates-note { - display: inline-flex; - align-items: center; - gap: 8px; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - - mat-icon { - font-size: 20px; - width: 20px; - height: 20px; - } - - .tb-installed-updates-available { - color: #f44336; - } - - .tb-installed-updates-none { - color: #198038; - } - - .tb-installed-updates-failed { - color: #f66716; - } -} - .tb-installed-title { font-size: 36px; font-weight: 500; 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 44d86bf476..899486594c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6495,10 +6495,9 @@ "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", - "check-for-updates-try-again": "Try again", "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", - "installed-items-load-failed": "Couldn't load the items with an update", "all-items-up-to-date": "All items are up to date", + "no-newer-versions": "No newer versions in IoT Hub", "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", "show-only-updates": "Show only updates", From 4c960743c3819c1079a3aaa825ca98668ea93f7f Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 17:42:10 +0200 Subject: [PATCH 08/18] IoT Hub device package delete: any kept profile keeps what it refers to, devicesCount dropped (PROD-9340 review) --- .../service/iot_hub/DefaultIotHubService.java | 43 ++++++---- .../iot_hub/InstalledItemKeptEntities.java | 12 ++- ...DefaultDevicePackageUpdateServiceTest.java | 2 +- .../iot_hub/DefaultIotHubServiceTest.java | 83 ++++++++++++++++--- .../iot-hub-delete-dialog.component.html | 15 ++-- .../iot-hub-delete-dialog.component.scss | 30 ++----- .../iot-hub-delete-dialog.component.ts | 12 ++- .../iot-hub/iot-hub-installed-item.models.ts | 7 +- 8 files changed, 127 insertions(+), 77 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 ff13b6378a..b62cde9868 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 @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.stereotype.Service; import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; @@ -44,6 +45,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.subscription.SubscriptionException; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -724,8 +726,8 @@ public class DefaultIotHubService implements IotHubService { * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, * and the ones the user had before and the package took as they were (use existing). A device profile that devices - * still use stays too, e.g. with the devices a LoRaWAN integration created, and so does what it refers to that the - * package created: TB deletes neither. + * still use stays too, e.g. with the devices a LoRaWAN integration created, and any kept profile keeps what it refers + * to: TB deletes neither. * A kept integration loses the metadata entries the package added. */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, @@ -748,12 +750,14 @@ public class DefaultIotHubService implements IotHubService { if (usedExisting.contains(entityId.getId())) { log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } Set usedBy = usedByOtherPackages.get(entityId.getId()); if (usedBy != null) { log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); + profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId())); continue; } if (referencedByKeptProfiles.contains(entityId.getId())) { @@ -770,7 +774,12 @@ public class DefaultIotHubService implements IotHubService { try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { - log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + // A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain + if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) { + log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e)); + } else { + log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); + } } } } @@ -829,10 +838,9 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item not found"); } List kept = new ArrayList<>(); - List keptForDevices = new ArrayList<>(); + List referenced = new ArrayList<>(); Set usedByItems = new HashSet<>(); int usedExistingCount = 0; - long devicesCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { Set usedExisting = usedExistingIds(dd); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); @@ -859,32 +867,37 @@ public class DefaultIotHubService implements IotHubService { } } for (EntityId entityId : dd.getCreatedEntityIds()) { - long devices = keptIds.contains(entityId.getId()) ? 0 : countProfileDevices(tenantId, entityId, deletedDevices); - if (devices == 0) { + if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) { + referenced.add(keptEntity(tenantId, entityId)); + keptIds.add(entityId.getId()); + } + } + // A kept profile, for whatever reason, keeps what it refers to + for (EntityId entityId : dd.getCreatedEntityIds()) { + if (!keptIds.contains(entityId.getId())) { continue; } - keptForDevices.add(keptEntity(tenantId, entityId)); - keptIds.add(entityId.getId()); - devicesCount += devices; - // What the profile refers to stays with it for (EntityId reference : profileReferences(tenantId, entityId)) { if (created.contains(reference.getId()) && keptIds.add(reference.getId())) { - keptForDevices.add(keptEntity(tenantId, reference)); + referenced.add(keptEntity(tenantId, reference)); } } } } - return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, keptForDevices, devicesCount); + return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced); } private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) { return new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)); } - /** The default rule chains and dashboard of the device profile {@code profileId}: TB doesn't delete them while it refers to them. */ + /** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */ private List profileReferences(TenantId tenantId, EntityId profileId) { - DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId())); List references = new ArrayList<>(); + if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) { + return references; + } + DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId())); if (profile != null) { Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId()) .filter(Objects::nonNull) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index 4d21db6b10..7c3cfdbeb7 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -10,8 +10,8 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; /** - * What deleting an installed item keeps: what other installed items use too, what the user had before it, and the device - * profiles devices still use (a LoRaWAN integration creates its devices on the first uplink, not the package). + * What deleting an installed item keeps: what other installed items use too, what the user had before it, and what other + * tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package). */ @Data @NoArgsConstructor @@ -23,11 +23,9 @@ public class InstalledItemKeptEntities { private int usedByItemsCount; // How many of the kept entities the user had before and the package took as they were (use existing) private int usedExistingCount; - // The package's device profiles that devices use and what they refer to (default rule chain, dashboard): TB deletes - // neither. Apart from entities, which an update reads as shared with other packages - private List keptForDevices; - // How many devices use those profiles - private long devicesCount; + // What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and + // dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages + private List referencedEntities; @Data @NoArgsConstructor diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 82f5f6c1c9..a90bef69df 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -308,7 +308,7 @@ class DefaultDevicePackageUpdateServiceTest { Dashboard shared = dashboard(9L); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); - when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of(), 0)); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of())); // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); 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 2ef9437115..f21dd20726 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 @@ -23,6 +23,8 @@ import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; @@ -745,13 +747,17 @@ class DefaultIotHubServiceTest { } @Test - void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndItsRuleChain_apartFromTheShared() { + void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() { DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + DashboardId dashboardId = new DashboardId(UUID.randomUUID()); profile.setDefaultRuleChainId(ruleChainId); + profile.setDefaultDashboardId(dashboardId); + // The user's, not the package's: not listed + profile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.randomUUID())); Device packageDevice = new Device(new DeviceId(UUID.randomUUID())); packageDevice.setDeviceProfileId(profile.getId()); - IotHubInstalledItem checked = devicePackage(ruleChainId, profile.getId(), packageDevice.getId()); + IotHubInstalledItem checked = devicePackage(ruleChainId, dashboardId, profile.getId(), packageDevice.getId()); when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); @@ -762,15 +768,16 @@ class DefaultIotHubServiceTest { when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr")); when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR")); + when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet")); InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); // An update reads entities as shared with other packages: the profile is not among them assertThat(kept.getEntities()).isEmpty(); - assertThat(kept.getKeptForDevices()).containsExactly( + assertThat(kept.getReferencedEntities()).containsExactly( new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"), - new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR")); - assertThat(kept.getDevicesCount()).isEqualTo(2); + new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"), + new InstalledItemKeptEntities.KeptEntity(dashboardId, "Smartico L2-LR Fleet")); } @Test @@ -788,17 +795,36 @@ class DefaultIotHubServiceTest { InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); - assertThat(kept.getKeptForDevices()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId); - assertThat(kept.getDevicesCount()).isEqualTo(1); + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId); } @Test - void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndItsRuleChain() throws Exception { + void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() { + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + IotHubInstalledItem checked = devicePackage(ruleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId()); + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(ruleChainId); + } + + @Test + void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndWhatItRefersTo() throws Exception { mockTenant(); DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + DashboardId dashboardId = new DashboardId(UUID.randomUUID()); profile.setDefaultRuleChainId(ruleChainId); - IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId()); + profile.setDefaultDashboardId(dashboardId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, dashboardId, profile.getId()); when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); @@ -809,8 +835,45 @@ class DefaultIotHubServiceTest { service.deleteInstalledItem(user, deleted.getId()); verify(tbDeviceProfileService, never()).delete(any(), any()); - verify(ruleChainService, never()).findRuleChainById(any(), any()); verify(tbRuleChainService, never()).delete(any(), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + } + + @Test + void deleteInstalledItem_devicePackage_aSharedProfileKeepsItsRuleChain() throws Exception { + mockTenant(); + DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + profile.setDefaultRuleChainId(ruleChainId); + IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId()); + IotHubInstalledItem other = devicePackage(profile.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); + when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceProfileService, never()).delete(any(), any()); + verify(tbRuleChainService, never()).delete(any(), any()); + } + + @Test + void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays() throws Exception { + mockTenant(); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + IotHubInstalledItem deleted = devicePackage(ruleChain.getId()); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain); + // A profile the user made after the install uses the package's rule chain + doThrow(new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!")) + .when(tbRuleChainService).delete(ruleChain, user); + + service.deleteInstalledItem(user, deleted.getId()); + verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 4b0d6fc93c..9ee22d6bc7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -13,14 +13,13 @@ info_outline
{{ keptTitle }}
- -
- @for (group of keptGroups; track group.reason; let first = $first) { - @if (!first) { -
- } -
{{ group.reason }}
- +
+ @for (group of keptGroups; track group.reason; let i = $index; let first = $first) { +
+
{{ group.reason }}
+ +
}
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 15bbef3f08..95dcd79e2d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -24,38 +24,20 @@ margin: 0; } -// The kept entities: one white list as tb-image-references draws it, a group per reason .tb-iot-hub-kept-groups { - display: flex; - flex-direction: column; - gap: 4px; - padding: 8px 0; - border-radius: 4px; - background: #fff; border: 1px solid color-mix(in srgb, var(--tb-primary-500) 40%, transparent); - // The groups share the outer border: no border of its own around each group's list + // Groups share the outer border; hide tb-image-references' own ::ng-deep tb-image-references table.tb-entities-list-table { - padding: 0 10px 0 4px !important; - background: transparent !important; + padding: 0 10px 0 4px; + background: transparent; &:before { - display: none !important; + display: none; } } } -.tb-iot-hub-kept-reason { - padding: 4px 12px 2px; - font-size: 12px; - font-weight: 500; - line-height: 16px; - letter-spacing: 0.4px; - color: rgba(0, 0, 0, 0.6); -} - -.tb-iot-hub-kept-divider { - height: 1px; - margin: 6px 12px 4px; - background: rgba(0, 0, 0, 0.08); +.tb-iot-hub-kept-group-next { + border-top: 1px solid rgba(0, 0, 0, 0.08); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 2fe865940e..ee010f52d5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -30,8 +30,7 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); if (shared.length) { @@ -56,12 +55,11 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent { From b03f29e5bec7b892655b4f5b7808c5bdfedd42c8 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 18:07:32 +0200 Subject: [PATCH 09/18] IoT Hub installed items: checked once the counts are in, counts keep the last value, one status note (PROD-9326 review) --- ...t-hub-installed-items-table.component.html | 4 -- ...iot-hub-installed-items-table.component.ts | 43 +++++++++++++------ .../iot-hub-installed-items.component.html | 30 ++++++------- .../assets/locale/locale.constant-en_US.json | 2 - 4 files changed, 45 insertions(+), 34 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index b24e8bb4cf..282e4a0f23 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -132,10 +132,6 @@

{{ 'iot-hub.unable-to-load' | translate }}

{{ 'iot-hub.unable-to-load-text' | translate }}

- } @else if (onlyUpdates && !hasActiveFilters()) { -

{{ 'iot-hub.all-items-up-to-date' | translate }}

-

{{ 'iot-hub.all-items-up-to-date-text' | translate }}

- } @else {

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

{{ 'iot-hub.no-installed-items-text' | translate }}

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 3ada8afee5..330fd635ef 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -89,6 +89,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, installedCount = 0; loadFailed = false; private loadRun = 0; + private countRun = 0; private widgetResize$: ResizeObserver; @@ -256,10 +257,16 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - this.updatesChecked = true; - this.isCheckingUpdates = false; - // No newer versions: the full list, where a new default converter still shows - this.loadUpdatesCount(() => this.showOnlyUpdates((this.updatesCount ?? 0) > 0)); + // Checked once the counts are in: the header shows them + this.loadUpdatesCount(() => { + this.updatesChecked = true; + this.isCheckingUpdates = false; + // No newer versions: the full list, where a new default converter still shows + this.showOnlyUpdates(this.updatesCount > 0); + }, () => { + this.isCheckingUpdates = false; + this.updatesCheckFailed = true; + }); }, error: () => { this.isCheckingUpdates = false; @@ -290,33 +297,45 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, /** Retries a failed load, and the header counts if they failed with it. */ retryLoad(): void { this.loadData(); - if (this.updatesCount === null) { + if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { this.loadUpdatesCount(); } } private reloadAfterChange(): void { - this.loadData(); - if (this.updatesChecked && !this.itemVersion) { - this.loadUpdatesCount(); + if (!this.updatesChecked || this.itemVersion) { + this.loadData(); + return; } + // The last update done: the full list, as after Check for updates + this.loadUpdatesCount( + () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), + () => this.loadData()); } - private loadUpdatesCount(then?: () => void): void { - this.updatesCount = null; + /** The header counts; the previous ones stay until the new ones arrive, and a later call wins. */ + private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { + const run = ++this.countRun; forkJoin({ withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) }).subscribe({ next: ({ withUpdates, installed }) => { + if (run !== this.countRun) { + return; + } this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.cd.markForCheck(); - then?.(); + onCounts?.(); }, error: () => { + if (run !== this.countRun) { + return; + } + this.updatesCount = null; this.cd.markForCheck(); - then?.(); + onError?.(); } }); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index e70619ab4b..7d4bbe52d0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -16,13 +16,23 @@

{{ 'iot-hub.installed-items' | translate }}

- @if (!updatesChecked) { - @if (updatesCheckFailed) { - + + + @if (!updatesChecked) { + @if (updatesCheckFailed) { warning {{ 'iot-hub.check-for-updates-failed' | translate }} - + } + } @else if (updatesCount > 0) { + arrow_circle_up + {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} + } @else if (updatesCount === 0) { + + check_circle + {{ 'iot-hub.no-newer-versions' | translate }} } + + @if (!updatesChecked) { } @else { - @if (updatesCount !== null) { - - @if (updatesCount > 0) { - arrow_circle_up - {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} - } @else { - - check_circle - {{ 'iot-hub.no-newer-versions' | translate }} - } - - } @if (onlyUpdates) { } @else if ((updatesCount ?? 0) > 0) { 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 899486594c..217b2e7919 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6496,9 +6496,7 @@ "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", - "all-items-up-to-date": "All items are up to date", "no-newer-versions": "No newer versions in IoT Hub", - "all-items-up-to-date-text": "No installed item has a newer version in IoT Hub.", "show-all-items": "Show all items", "show-only-updates": "Show only updates", "updates": "Updates", From 9cee5b499a72136faa2e55f26418e7c1f3cf5e9c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 18:23:06 +0200 Subject: [PATCH 10/18] IoT Hub device package delete: the dialog scrolls and keeps long names in the box, log level checked in tests (PROD-9340 review) --- .../iot_hub/DefaultIotHubServiceTest.java | 58 ++++++++++++++++--- .../iot-hub-delete-dialog.component.html | 7 ++- .../iot-hub-delete-dialog.component.scss | 6 ++ 3 files changed, 59 insertions(+), 12 deletions(-) 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 f21dd20726..fe42513490 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 @@ -3,6 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; @@ -14,6 +18,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.DashboardId; @@ -802,8 +807,10 @@ class DefaultIotHubServiceTest { void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() { DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainId edgeRuleChainId = new RuleChainId(UUID.randomUUID()); profile.setDefaultRuleChainId(ruleChainId); - IotHubInstalledItem checked = devicePackage(ruleChainId, profile.getId()); + profile.setDefaultEdgeRuleChainId(edgeRuleChainId); + IotHubInstalledItem checked = devicePackage(ruleChainId, edgeRuleChainId, profile.getId()); IotHubInstalledItem other = devicePackage(profile.getId()); when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) @@ -813,7 +820,8 @@ class DefaultIotHubServiceTest { InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId()); - assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(ruleChainId); + assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId) + .containsExactly(ruleChainId, edgeRuleChainId); } @Test @@ -860,7 +868,30 @@ class DefaultIotHubServiceTest { } @Test - void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays() throws Exception { + void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays_loggedAsKept() throws Exception { + // A profile the user made after the install uses the package's rule chain + List logs = deleteRuleChainFailingWith( + new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.INFO); + assertThat(event.getFormattedMessage()).contains("Kept RULE_CHAIN").contains("referenced by the device profiles"); + }); + assertThat(logs).noneMatch(event -> event.getLevel() == Level.ERROR); + } + + @Test + void deleteInstalledItem_devicePackage_aFailedDelete_staysAnError() throws Exception { + List logs = deleteRuleChainFailingWith(new RuntimeException("Database is down")); + + assertThat(logs).anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + assertThat(event.getFormattedMessage()).contains("Failed to delete device package entity"); + }); + } + + /** Deletes a package whose only entity is a rule chain that fails to delete with {@code failure}; the service's logs. */ + private List deleteRuleChainFailingWith(Exception failure) throws Exception { mockTenant(); RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); IotHubInstalledItem deleted = devicePackage(ruleChain.getId()); @@ -868,13 +899,22 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain); - // A profile the user made after the install uses the package's rule chain - doThrow(new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!")) - .when(tbRuleChainService).delete(ruleChain, user); - - service.deleteInstalledItem(user, deleted.getId()); - + doThrow(failure).when(tbRuleChainService).delete(ruleChain, user); + Logger logger = (Logger) LoggerFactory.getLogger(DefaultIotHubService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + Level level = logger.getLevel(); + logger.setLevel(Level.INFO); + try { + service.deleteInstalledItem(user, deleted.getId()); + } finally { + logger.setLevel(level); + logger.detachAppender(appender); + } + // The delete goes on either way verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId()); + return appender.list; } private void noDevices(DeviceProfileId profileId) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 9ee22d6bc7..be62922e11 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -5,15 +5,16 @@ SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --> -
+ +

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

{{ description }}

@if (keptGroups.length) {
info_outline -
+
{{ keptTitle }}
-
+
@for (group of keptGroups; track group.reason; let i = $index; let first = $first) {
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 95dcd79e2d..ab3f9b9ebc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -35,9 +35,15 @@ &:before { display: none; } + + // A long name breaks inside the box instead of running past its border + td.tb-entity-name { + overflow-wrap: anywhere; + } } } +// Not divide-y: with preflight off, divide-solid draws the side borders of the groups too .tb-iot-hub-kept-group-next { border-top: 1px solid rgba(0, 0, 0, 0.08); } From d67da9487c7d0ff1a0b483432f23c9c2cb836ded Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 17 Nov 2026 11:13:00 +0200 Subject: [PATCH 11/18] IoT Hub installed items: a failed count shows in the header with Try again, only-updates empty state, no double error toast, cleanup (PROD-9326 review) --- .../src/app/core/http/iot-hub-api.service.ts | 23 +++----- ...t-hub-installed-items-table.component.html | 2 +- ...iot-hub-installed-items-table.component.ts | 52 ++++++++----------- .../iot-hub-installed-items.component.html | 18 +++---- .../assets/locale/locale.constant-en_US.json | 3 +- 5 files changed, 42 insertions(+), 56 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 b9674e232c..fe8c2800e6 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 @@ -243,11 +243,7 @@ export class IotHubApiService { public getInstalledItems(pageLink: PageLink, itemTypes?: string | string[], itemId?: string, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes) { - const types = Array.isArray(itemTypes) ? itemTypes : [itemTypes]; - types.forEach(t => query += `&itemTypes=${t}`); - } + let query = this.installedItemsQuery(pageLink, itemTypes); if (itemId) { query += `&itemId=${itemId}`; } @@ -257,18 +253,11 @@ export class IotHubApiService { ); } - /** - * The installed items with an update: publishedVersionIds is IoT Hub's published version id by item id, as Check for - * updates got it. The server keeps the items installed in another version, with the page's sort, search and types. - */ + /** publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come back. */ public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, config?: IotHubRequestConfig): Observable> { - let query = pageLink.toQuery(); - if (itemTypes?.length) { - query += itemTypes.map(t => `&itemTypes=${t}`).join(''); - } return this.http.post>( - `/api/iot-hub/installedItems/withUpdates${query}`, + `/api/iot-hub/installedItems/withUpdates${this.installedItemsQuery(pageLink, itemTypes)}`, publishedVersionIds, { params: this.buildParams(config) } ); @@ -313,7 +302,6 @@ export class IotHubApiService { ); } - /** Asked in requests of 100 item ids at most, so a tenant with many items doesn't send IoT Hub one huge request. */ public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { if (!itemIds.length) { return of([]); @@ -336,6 +324,11 @@ export class IotHubApiService { ); } + private installedItemsQuery(pageLink: PageLink, itemTypes?: string | string[] | null): string { + const types = !itemTypes ? [] : Array.isArray(itemTypes) ? itemTypes : [itemTypes]; + return pageLink.toQuery() + types.map(t => `&itemTypes=${t}`).join(''); + } + private buildParams(config?: IotHubRequestConfig): HttpParams { return new InterceptorHttpParams( new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 282e4a0f23..a5a013b68d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -133,7 +133,7 @@

{{ 'iot-hub.unable-to-load-text' | translate }}

} @else { -

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

+

{{ (onlyUpdates ? 'iot-hub.no-items-with-updates' : 'iot-hub.no-installed-items') | translate }}

{{ 'iot-hub.no-installed-items-text' | translate }}

@if (hasActiveFilters()) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 330fd635ef..8204a42584 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -84,7 +84,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isCheckingUpdates = false; updatesCheckFailed = false; onlyUpdates = false; - // Of all types and with no search; null while not known + // Of all types and with no search updatesCount: number | null = null; installedCount = 0; loadFailed = false; @@ -135,10 +135,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngOnChanges(changes: SimpleChanges): void { if (changes.textSearch || changes.typeFilters) { if (!changes.textSearch?.firstChange || !changes.typeFilters?.firstChange) { - this.pageIndex = 0; - if (this.paginator) { - this.paginator.pageIndex = 0; - } + this.setPageIndex(0); this.loadData(); } } @@ -146,8 +143,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, ngAfterViewInit(): void { this.sort.sortChange.subscribe(() => { - this.pageIndex = 0; - this.paginator.pageIndex = 0; + this.setPageIndex(0); this.loadData(); }); } @@ -257,16 +253,12 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, next: (infos) => { this.publishedVersionMap.clear(); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); - // Checked once the counts are in: the header shows them this.loadUpdatesCount(() => { this.updatesChecked = true; this.isCheckingUpdates = false; - // No newer versions: the full list, where a new default converter still shows + // The full list shows a new default converter, the only-updates list doesn't this.showOnlyUpdates(this.updatesCount > 0); - }, () => { - this.isCheckingUpdates = false; - this.updatesCheckFailed = true; - }); + }, () => this.isCheckingUpdates = false); }, error: () => { this.isCheckingUpdates = false; @@ -277,11 +269,15 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, showOnlyUpdates(onlyUpdates: boolean): void { this.onlyUpdates = onlyUpdates; - this.pageIndex = 0; + this.setPageIndex(0); + this.loadData(); + } + + private setPageIndex(pageIndex: number): void { + this.pageIndex = pageIndex; if (this.paginator) { - this.paginator.pageIndex = 0; + this.paginator.pageIndex = pageIndex; } - this.loadData(); } private publishedVersionIds(): Record { @@ -294,7 +290,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return ids; } - /** Retries a failed load, and the header counts if they failed with it. */ retryLoad(): void { this.loadData(); if (this.updatesChecked && !this.itemVersion && this.updatesCount === null) { @@ -307,18 +302,19 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); return; } - // The last update done: the full list, as after Check for updates + // Without counts the only-updates list can't be trusted, so the full list this.loadUpdatesCount( () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), - () => this.loadData()); + () => this.onlyUpdates ? this.showOnlyUpdates(false) : this.loadData()); } - /** The header counts; the previous ones stay until the new ones arrive, and a later call wins. */ + /** The previous counts stay until the new ones arrive, and a later call wins. A failure shows in the header with Try again. */ private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { const run = ++this.countRun; + const config = { ignoreLoading: true, ignoreErrors: true }; forkJoin({ - withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), { ignoreLoading: true }), - installed: this.iotHubApiService.getInstalledItemsCount(undefined, { ignoreLoading: true }) + withUpdates: this.iotHubApiService.getInstalledItemsWithUpdates(new PageLink(1), null, this.publishedVersionIds(), config), + installed: this.iotHubApiService.getInstalledItemsCount(undefined, config) }).subscribe({ next: ({ withUpdates, installed }) => { if (run !== this.countRun) { @@ -326,6 +322,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.updatesCount = withUpdates.totalElements; this.installedCount = installed; + this.updatesCheckFailed = false; this.cd.markForCheck(); onCounts?.(); }, @@ -334,6 +331,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, return; } this.updatesCount = null; + this.updatesCheckFailed = true; this.cd.markForCheck(); onError?.(); } @@ -424,9 +422,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }; const pageLink = new PageLink(this.pageSize, this.pageIndex, this.textSearch || null, sortOrder); const typeFilters = this.typeFilters?.length ? this.typeFilters : null; - // One item's versions page lists them all + // The empty state shows a failure of the only-updates list; one item's versions page lists them all const items$ = this.onlyUpdates && !this.itemVersion - ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true}) + ? this.iotHubApiService.getInstalledItemsWithUpdates(pageLink, typeFilters, this.publishedVersionIds(), {ignoreLoading: true, ignoreErrors: true}) : this.iotHubApiService.getInstalledItems(pageLink, typeFilters, this.itemVersion?.itemId, {ignoreLoading: true}); const run = ++this.loadRun; items$.subscribe({ @@ -436,10 +434,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } // The last page emptied after an update or a removal if (!data.data.length && this.pageIndex > 0 && data.totalElements > 0) { - this.pageIndex = Math.ceil(data.totalElements / this.pageSize) - 1; - if (this.paginator) { - this.paginator.pageIndex = this.pageIndex; - } + this.setPageIndex(Math.ceil(data.totalElements / this.pageSize) - 1); this.loadData(); return; } @@ -447,7 +442,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.totalElements = data.totalElements; this.loadFailed = false; this.isLoading = false; - // In the only-updates list the version update shows, not the converter's if (this.updatesChecked && !this.itemVersion && !this.onlyUpdates) { void this.checkConverterUpdates(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7d4bbe52d0..7a46195fa5 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -18,21 +18,18 @@
- @if (!updatesChecked) { - @if (updatesCheckFailed) { - warning - {{ 'iot-hub.check-for-updates-failed' | translate }} - } - } @else if (updatesCount > 0) { + @if (updatesCheckFailed) { + warning + {{ 'iot-hub.check-for-updates-failed' | translate }} + } @else if (updatesChecked && updatesCount > 0) { arrow_circle_up {{ 'iot-hub.items-with-update' | translate:{ count: updatesCount, total: installedCount } }} - } @else if (updatesCount === 0) { - + } @else if (updatesChecked && updatesCount === 0) { check_circle {{ 'iot-hub.no-newer-versions' | translate }} } - @if (!updatesChecked) { + @if (!updatesChecked || updatesCheckFailed) { - } @else { + } + @if (updatesChecked) { @if (onlyUpdates) { } @else if ((updatesCount ?? 0) > 0) { 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 217b2e7919..05b9d80811 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6495,7 +6495,7 @@ "install-rollback-partial": "Some of the items installed before the failure could not be removed automatically and may need to be deleted manually.", "check-for-updates": "Check for updates", "check-for-updates-failed": "Couldn't check for updates", - "items-with-update": "{ count, plural, =1 {1 of {total} items has an update} other {# of {total} items have an update} }", + "items-with-update": "Updates available for {{count}} of {{total}}", "no-newer-versions": "No newer versions in IoT Hub", "show-all-items": "Show all items", "show-only-updates": "Show only updates", @@ -6530,6 +6530,7 @@ "installed-date": "Installed", "no-installed-items": "No installed items found", "no-installed-items-text": "Try adjusting your search or filters.", + "no-items-with-updates": "No items with updates match your filters", "remove-installed-item-title": "Remove Installed Item", "remove-installed-item-text": "Are you sure you want to remove '{{name}}'? The installed entity will also be removed.", "installed-item-removed": "'{{name}}' has been removed", From 14415d27b68c22da7b374526dc4d2923bd7ed68b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 17 Nov 2026 11:27:59 +0200 Subject: [PATCH 12/18] IoT Hub device package delete: the hint doesn't shrink so the dialog scrolls, the type column wraps in a narrow dialog, cleanup (PROD-9340 review) --- .../iot-hub/iot-hub-delete-dialog.component.html | 11 ++++++----- .../iot-hub/iot-hub-delete-dialog.component.scss | 6 +++++- .../iot-hub/iot-hub-delete-dialog.component.ts | 1 - .../models/iot-hub/iot-hub-installed-item.models.ts | 2 +- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index be62922e11..29af8760a4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -10,15 +10,16 @@

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

{{ description }}

@if (keptGroups.length) { -
+ +
info_outline
{{ keptTitle }}
-
- @for (group of keptGroups; track group.reason; let i = $index; let first = $first) { +
+ @for (group of keptGroups; track group.reason; let first = $first) {
-
{{ group.reason }}
+ [attr.aria-labelledby]="'tb-iot-hub-kept-reason-' + $index"> +
{{ group.reason }}
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index ab3f9b9ebc..692c86d143 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -36,7 +36,11 @@ display: none; } - // A long name breaks inside the box instead of running past its border + // In a narrow dialog the type wraps, so the name keeps room; a long name breaks inside the box + td.tb-entity-type { + white-space: normal; + } + td.tb-entity-name { overflow-wrap: anywhere; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index ee010f52d5..32cd6324c6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -30,7 +30,6 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent Date: Tue, 17 Nov 2026 11:49:20 +0200 Subject: [PATCH 13/18] IoT Hub installed items: Try again after a failed count only recounts When updates were already checked and only the count failed, Try again now recounts instead of re-running the whole check: the header keeps the note with a spinner on the button, the user's list mode and page stay, and the checking state is cleared by whichever count finishes last, so a newer count from a reload can't leave the button spinning. Shorter comments and plain if/else in reloadAfterChange. --- .../src/app/core/http/iot-hub-api.service.ts | 2 +- ...iot-hub-installed-items-table.component.ts | 36 +++++++++++++------ .../iot-hub-installed-items.component.html | 2 +- 3 files changed, 28 insertions(+), 12 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 fe8c2800e6..e162ba1357 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 @@ -253,7 +253,7 @@ export class IotHubApiService { ); } - /** publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come back. */ + /** Body: published version id by item id; returns items installed in a different version. */ public getInstalledItemsWithUpdates(pageLink: PageLink, itemTypes: string[] | null, publishedVersionIds: Record, config?: IotHubRequestConfig): Observable> { return this.http.post>( diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 8204a42584..4b50ad533a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -84,7 +84,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isCheckingUpdates = false; updatesCheckFailed = false; onlyUpdates = false; - // Of all types and with no search + // Totals, ignoring type filters and search updatesCount: number | null = null; installedCount = 0; loadFailed = false; @@ -245,9 +245,14 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, checkForUpdates(): void { this.isCheckingUpdates = true; + if (this.updatesChecked) { + // Only the count failed: recount, keeping the list as it is + this.loadUpdatesCount(); + return; + } this.updatesCheckFailed = false; this.iotHubApiService.getInstalledItemIds({ ignoreLoading: true }).pipe( - // An IoT Hub that doesn't answer is not a page error: the page says so next to the button, the list works without it + // Failure is shown next to the button, not as an error toast switchMap(itemIds => this.iotHubApiService.getItemsPublishedVersions(itemIds, { ignoreLoading: true, ignoreErrors: true })) ).subscribe({ next: (infos) => { @@ -255,10 +260,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.loadUpdatesCount(() => { this.updatesChecked = true; - this.isCheckingUpdates = false; - // The full list shows a new default converter, the only-updates list doesn't + // No updates: stay on the full list (it also shows converter updates) this.showOnlyUpdates(this.updatesCount > 0); - }, () => this.isCheckingUpdates = false); + }); }, error: () => { this.isCheckingUpdates = false; @@ -302,13 +306,23 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.loadData(); return; } - // Without counts the only-updates list can't be trusted, so the full list - this.loadUpdatesCount( - () => this.onlyUpdates && this.updatesCount === 0 ? this.showOnlyUpdates(false) : this.loadData(), - () => this.onlyUpdates ? this.showOnlyUpdates(false) : this.loadData()); + this.loadUpdatesCount(() => { + if (this.onlyUpdates && this.updatesCount === 0) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }, () => { + // Count failed: fall back to the full list + if (this.onlyUpdates) { + this.showOnlyUpdates(false); + } else { + this.loadData(); + } + }); } - /** The previous counts stay until the new ones arrive, and a later call wins. A failure shows in the header with Try again. */ + // Latest call wins; previous counts stay until it returns private loadUpdatesCount(onCounts?: () => void, onError?: () => void): void { const run = ++this.countRun; const config = { ignoreLoading: true, ignoreErrors: true }; @@ -323,6 +337,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.updatesCount = withUpdates.totalElements; this.installedCount = installed; this.updatesCheckFailed = false; + this.isCheckingUpdates = false; this.cd.markForCheck(); onCounts?.(); }, @@ -332,6 +347,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, } this.updatesCount = null; this.updatesCheckFailed = true; + this.isCheckingUpdates = false; this.cd.markForCheck(); onError?.(); } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html index 7a46195fa5..8702709c3e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html @@ -42,7 +42,7 @@ @if (updatesChecked) { @if (onlyUpdates) { - } @else if ((updatesCount ?? 0) > 0) { + } @else if (updatesCount > 0) { } } From fd30267aa5b46672b6fc25ef3a0c66b715249935 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Tue, 17 Nov 2026 11:06:42 +0100 Subject: [PATCH 14/18] White labeling: fixed horizontal scrollbar in the Custom menu table (#16715) * Port of fix/custom-menu-width onto master * Custom menu table: names wrap and columns fit, no horizontal scrollbar --------- Co-authored-by: Vladyslav_Prykhodko --- .../entity/entities-table.component.ts | 3 +-- .../custom-menu-table.component.scss | 1 - .../custom-menu-table.component.ts | 20 ++++++++++++------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 05f6608ae5..15a710d325 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -787,9 +787,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa res = column.cellTooltipFunction(entity, column.key); res = isDefined(res) ? res : null; this.cellTooltipCache[index] = res; - } else { - return res !== null ? res : undefined; } + return res !== null ? res : undefined; } else { return undefined; } diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss index 3e91fc24ac..32b040769c 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.scss @@ -15,7 +15,6 @@ padding: 0; } mat-cell.mat-column-name { - white-space: nowrap; .mat-mdc-icon-button { vertical-align: middle; margin-left: 8px; diff --git a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts index 4da08170a7..280fbfad07 100644 --- a/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts +++ b/ui-ngx/src/app/modules/home/pages/custom-menu/custom-menu-table.component.ts @@ -95,22 +95,28 @@ export class CustomMenuTableComponent implements OnInit { this.customMenuTableConfig.entitiesDeleteEnabled = !readonly && authUser.authority !== Authority.SYS_ADMIN; this.customMenuTableConfig.addEntity = () => this.addCustomMenu(); - let mainColumnsWidth: string; + let nameColumnWidth: string; + let scopeColumnWidth: string; + let assigneeTypeColumnWidth: string; switch (authUser.authority) { case Authority.SYS_ADMIN: - mainColumnsWidth = '50%'; + nameColumnWidth = '60%'; + scopeColumnWidth = '20%'; break; case Authority.TENANT_ADMIN: - mainColumnsWidth = '33%'; + nameColumnWidth = '50%'; + scopeColumnWidth = '15%'; + assigneeTypeColumnWidth = '15%'; break; case Authority.CUSTOMER_USER: - mainColumnsWidth = '50%'; + nameColumnWidth = '60%'; + assigneeTypeColumnWidth = '20%'; break; } this.customMenuTableConfig.columns.push( new DateEntityTableColumn('createdTime', 'common.created-time', this.datePipe, '150px'), - new EntityTableColumn('name', 'custom-menu.name', mainColumnsWidth, + new EntityTableColumn('name', 'custom-menu.name', nameColumnWidth, entity => entity.name, _entity => ({}), true, () => ({}), () => undefined, false, { name: this.translate.instant('custom-menu.edit-name'), @@ -120,12 +126,12 @@ export class CustomMenuTableComponent implements OnInit { }) ); if (authUser.authority !== Authority.CUSTOMER_USER) { - this.customMenuTableConfig.columns.push(new EntityTableColumn('scope', 'custom-menu.scope', mainColumnsWidth, + this.customMenuTableConfig.columns.push(new EntityTableColumn('scope', 'custom-menu.scope', scopeColumnWidth, (menu) => this.translate.instant(cmScopeTranslations.get(menu.scope)))); } if (authUser.authority !== Authority.SYS_ADMIN) { this.customMenuTableConfig.columns.push(new EntityTableColumn('assigneeType', - 'custom-menu.assignee-type', mainColumnsWidth, + 'custom-menu.assignee-type', assigneeTypeColumnWidth, (menu) => this.translate.instant(cmAssigneeTypeTranslations(menu.assigneeType, menu.scope)))); } if (authUser.authority !== Authority.SYS_ADMIN) { From 62264f5d81ac9624d3aed37a72e16ce45f20d818 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Tue, 17 Nov 2026 12:36:05 +0200 Subject: [PATCH 15/18] IoT Hub device package delete: the type column wraps in a narrow dialog, standard dialog layout On phones the entity type now wraps so the name gets more room; the override did not apply before. The dialog uses mat-dialog-content and mat-dialog-actions, so Material handles scrolling. The group divider uses Tailwind. --- .../iot-hub/iot-hub-actions.service.ts | 2 +- .../iot-hub-delete-dialog.component.html | 46 +++++++++---------- .../iot-hub-delete-dialog.component.scss | 13 +++--- 3 files changed, 30 insertions(+), 31 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 9c5d995c10..f17c4cb7d4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -212,7 +212,7 @@ export class IotHubActionsService { if (!installedItem) { return of(false); } - // A device package keeps what other installed packages use: the dialog opens with that already known + // A device package keeps some entities: the dialog opens with them already known const keptEntities$: Observable = installedItem.itemType === 'DEVICE' ? this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) : of(null); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 29af8760a4..d8adb56606 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -5,30 +5,30 @@ SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --> - -
-

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

-

{{ description }}

- @if (keptGroups.length) { - -
- info_outline -
-
{{ keptTitle }}
-
- @for (group of keptGroups; track group.reason; let first = $first) { -
-
{{ group.reason }}
- -
- } + +
+

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

+

{{ description }}

+ @if (keptGroups.length) { +
+ info_outline +
+
{{ keptTitle }}
+
+ @for (group of keptGroups; track group.reason) { +
+
{{ group.reason }}
+ +
+ } +
-
- } -
-
+ } +
+ + -
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 692c86d143..0168b2bb51 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +@import "../../../../../scss/constants"; + :host { display: block; max-width: 600px; @@ -36,9 +38,11 @@ display: none; } - // In a narrow dialog the type wraps, so the name keeps room; a long name breaks inside the box + // Narrow dialog: let type and name wrap td.tb-entity-type { - white-space: normal; + @media #{$mat-xs} { + white-space: normal !important; + } } td.tb-entity-name { @@ -46,8 +50,3 @@ } } } - -// Not divide-y: with preflight off, divide-solid draws the side borders of the groups too -.tb-iot-hub-kept-group-next { - border-top: 1px solid rgba(0, 0, 0, 0.08); -} From aa7085f410286ad169840402dbcd2ac57abd3c7f Mon Sep 17 00:00:00 2001 From: Shvaika Dmytro Date: Tue, 17 Nov 2026 12:42:13 +0200 Subject: [PATCH 16/18] IoT Hub: fixed device package installs leaving entities behind after an error or cancel (#16724) * IoT Hub device packages: the update service becomes DevicePackageService, ready to install too * IoT Hub device packages: an install saves its entities and the installed item in one transaction * IoT Hub device packages: an install keeps only entities the user chose, and its errors read for install too * IoT Hub device packages: an install from a customer or a device group puts its device and dashboard there, in the same transaction * IoT Hub device packages: an install never moves an overwritten device to another owner * IoT Hub device install: the wizard checks every step first, asks about all conflicts at once and installs in one request * IoT Hub device install: an overwritten device takes the package's credentials, a cancelled check installs nothing, one install is one request * IoT Hub device install: no second check or install from the step header, Retry checks the package again, messages and comments fit install and update * IoT Hub device packages: install and update share one plan, review and result path, with neutral names * IoT Hub device install: the plan looks like the update review, with a footer to confirm warnings and no jump to Verify * IoT Hub device install: the rows after an install say Created, Used existing, Overwritten or Created copy * IoT Hub device install: no overwrite of a device or gateway, Use existing keeps the step attributes, Try again asks again about the failed choice - At install a name conflict on a device or gateway offers only Use existing; the server rejects an install that overwrites one. An overwrite keeps the device's credentials, which are applied only to a created device. - Use existing at install writes the step's server and shared attributes after commit, as the browser install did. - Try again at install keeps the conflict choices except the one of the failed step. - The provisioning step label is translated; ca_ES and ar_AE get the install texts. - Tests check that the audit log, the Hub install report and the attributes run after commit. * IoT Hub device packages: a test pins that an overwrite keeps the device's credentials * IoT Hub device install dialog: cleanup after review * IoT Hub device install: the conflict check resolves names from the plan, an install overwrite sends the version - The pre-check resolves each step's template with the names the plan gives the entities of earlier steps (alias -> name, in step order), not with outputs left from a failed attempt, so a dashboard titled ${device.name} is checked under the device's planned name and the first check and Try again agree. Placeholders known only after the install, e.g. ${device.id}, stay. An update still resolves with the installed entities. The request sent to the server is unchanged. - The pre-check keeps the version of the entity it found (rule chain, dashboard, converter, integration), and an install overwrite sends it as expectedVersion, so the server rejects an entity changed between the check and the install. - The conflict message names the existing entity, as a step's name can differ from it. - The duplicate-key comment says the check runs before the plan is sent, and the server checks too. * IoT Hub device install: a device profile overwrite sends the profile's version The names lookup has no version, so the pre-check reads the matched profile once and keeps its version for expectedVersion. * IoT Hub device install: a device overwrite sends the device's version The device lookup of the pre-check now keeps the version, as the other lookups do, and the state key comment says the duplicate check runs before the plan is sent. * IoT Hub device install: pass the preview outputs instead of swapping entityOutputs preCheckTemplates passes its preview outputs to resolveTemplateJson instead of temporarily replacing entityOutputs. Drops duplicated comments and redundant optional chaining in templateNameOf. --------- Co-authored-by: Viacheslav Klimov Co-authored-by: Vladyslav_Prykhodko --- .../server/controller/IotHubController.java | 24 +- ....java => DefaultDevicePackageService.java} | 375 +++++-- .../service/iot_hub/DefaultIotHubService.java | 2 +- ...Request.java => DevicePackageRequest.java} | 30 +- ...teResult.java => DevicePackageResult.java} | 10 +- ...Service.java => DevicePackageService.java} | 9 +- ...a => DefaultDevicePackageServiceTest.java} | 600 +++++++++-- .../src/app/core/http/iot-hub-api.service.ts | 27 +- .../device-install-dialog.component.html | 169 +-- .../device-install-dialog.component.scss | 16 +- .../device-install-dialog.component.ts | 992 ++++++------------ .../iot-hub/iot-hub-default-converter.ts | 4 +- .../models/iot-hub/device-package.models.ts | 8 +- .../iot-hub/iot-hub-installed-item.models.ts | 21 +- .../assets/locale/locale.constant-ar_AE.json | 21 +- .../assets/locale/locale.constant-ca_ES.json | 21 +- .../assets/locale/locale.constant-da_DK.json | 3 - .../assets/locale/locale.constant-de_DE.json | 3 - .../assets/locale/locale.constant-el_GR.json | 3 - .../assets/locale/locale.constant-en_US.json | 18 +- .../assets/locale/locale.constant-es_ES.json | 3 - .../assets/locale/locale.constant-fr_FR.json | 3 - .../assets/locale/locale.constant-hi_IN.json | 3 - .../assets/locale/locale.constant-it_IT.json | 3 - .../assets/locale/locale.constant-ja_JP.json | 3 - .../assets/locale/locale.constant-ko_KR.json | 3 - .../assets/locale/locale.constant-lt_LT.json | 3 - .../assets/locale/locale.constant-nl_BE.json | 3 - .../assets/locale/locale.constant-nl_NL.json | 3 - .../assets/locale/locale.constant-no_NO.json | 3 - .../assets/locale/locale.constant-pl_PL.json | 3 - .../assets/locale/locale.constant-pt_BR.json | 3 - .../assets/locale/locale.constant-sl_SI.json | 3 - .../assets/locale/locale.constant-tr_TR.json | 3 - .../assets/locale/locale.constant-uk_UA.json | 3 - .../assets/locale/locale.constant-zh_CN.json | 3 - .../assets/locale/locale.constant-zh_TW.json | 3 - 37 files changed, 1257 insertions(+), 1150 deletions(-) rename application/src/main/java/org/thingsboard/server/service/iot_hub/{DefaultDevicePackageUpdateService.java => DefaultDevicePackageService.java} (72%) rename application/src/main/java/org/thingsboard/server/service/iot_hub/{DeviceUpdateRequest.java => DevicePackageRequest.java} (67%) rename application/src/main/java/org/thingsboard/server/service/iot_hub/{DeviceUpdateResult.java => DevicePackageResult.java} (70%) rename application/src/main/java/org/thingsboard/server/service/iot_hub/{DevicePackageUpdateService.java => DevicePackageService.java} (59%) rename application/src/test/java/org/thingsboard/server/service/iot_hub/{DefaultDevicePackageUpdateServiceTest.java => DefaultDevicePackageServiceTest.java} (60%) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 332a95242b..287c50b84d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -39,9 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; -import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; -import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; -import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; +import org.thingsboard.server.service.iot_hub.DevicePackageService; +import org.thingsboard.server.service.iot_hub.DevicePackageRequest; +import org.thingsboard.server.service.iot_hub.DevicePackageResult; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; @@ -58,7 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService; public class IotHubController extends BaseController { private final IotHubService iotHubService; - private final DevicePackageUpdateService devicePackageUpdateService; + private final DevicePackageService devicePackageService; private final IotHubInstalledItemService iotHubInstalledItemService; private final DeviceConnectivityService deviceConnectivityService; private final SystemSecurityService systemSecurityService; @@ -103,21 +103,29 @@ public class IotHubController extends BaseController { return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/device/install") + @ResponseBody + public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException { + checkAllPermissions(); + return devicePackageService.install(getCurrentUser(), request); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @ResponseBody public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); + return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/installedItems/{installedItemId}/deviceUpdate") @ResponseBody - public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, - @RequestBody DeviceUpdateRequest request) throws ThingsboardException { + public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId, + @RequestBody DevicePackageRequest request) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); + return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java similarity index 72% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java index f4604beea4..ac998aae5a 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java @@ -16,10 +16,13 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.GroupEntity; +import org.thingsboard.server.common.data.HasCustomerId; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasVersion; @@ -30,14 +33,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; @@ -66,6 +72,7 @@ import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -86,18 +93,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Applies an update of an installed device package in one transaction. The install wizard resolves the templates - * of the new version (the same way it installs them) and sends the entity of each step; this service checks the - * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a - * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a - * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, - * are written after commit too. + * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the + * templates of the version and sends the entity of each step; this service checks the plan, saves every entity + * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors, + * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control + * and the attributes, which aren't transactional, are written after commit too. */ @Service @TbCoreComponent @Slf4j @RequiredArgsConstructor -public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { +public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService { // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} private static final Map STEP_ALIASES = Map.of( @@ -110,7 +116,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i "DOWNLINK_CONVERTER", "downlinkConverter", "INTEGRATION", "integration"); private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); - private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + private static final String UNEXPECTED_ERROR = "Failed to save the device package"; private final IotHubInstalledItemService installedItemService; private final IotHubRestClient iotHubRestClient; @@ -129,6 +135,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private final AttributesService attributesService; private final TelemetrySubscriptionService telemetryService; private final TransactionTemplate transactionTemplate; + private final ProjectInfo projectInfo; @Override public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { @@ -162,33 +169,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } @Override - public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Installing device package version {}", tenantId, request.getVersionId()); + DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> { + if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) { + throw new IllegalArgumentException("Invalid install request"); + } + Placement placement = placement(tenantId, request); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + // The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation + DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor(); + validateInstallSteps(request); + validate(tenantId, previous, request); + return transactionTemplate.execute(status -> { + Applied applied = applySteps(tenantId, previous, request, null, placement); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); + installedItem.setTenantId(tenantId); + installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText())); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setItemType("DEVICE"); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + reportInstall(user, request.getVersionId()); + log.info("[{}] Installed device package version {}", tenantId, request.getVersionId()); + } + return result; + } + + @Override + public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - Applied applied; - try { + DevicePackageResult result = apply(user, "update of " + installedItemId, () -> { DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { throw new IllegalArgumentException("The version belongs to another item"); } - validatePlan(devicePackage, request); - checkFeatures(tenantId, request); - validateIntegrations(tenantId, request); - applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + validate(tenantId, devicePackage.descriptor(), request); + return transactionTemplate.execute(status -> { + IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); + Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + } + return result; + } + + /** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */ + private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) { + TenantId tenantId = user.getTenantId(); + Applied applied; + try { + applied = change.apply(); } catch (StepFailure e) { - log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); - return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); + log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); + return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey); } catch (RestClientException e) { - log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); - return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); + return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); } catch (Exception e) { - log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); - return DeviceUpdateResult.error(userMessage(e), null); + log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e); + return DevicePackageResult.error(userMessage(e), null); } afterCommit(user, tenantId, applied); - log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + return DevicePackageResult.success(applied.descriptor(), applied.outputs()); + } + + /** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */ + private void reportInstall(SecurityUser user, String versionId) { + TenantId tenantId = user.getTenantId(); + try { + InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(), + projectInfo.getProjectVersion(), projectInfo.getProductType()); + iotHubRestClient.reportVersionInstalled(versionId, report); + } catch (Exception e) { + log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage()); + } + } + + /** + * At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or + * gateway is never overwritten: its credentials are what its firmware uses. + */ + private static void validateInstallSteps(DevicePackageRequest request) { + if (request.getSteps() == null) { + return; + } + for (DevicePackageRequest.Step step : request.getSteps()) { + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) + || (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) { + throw new IllegalArgumentException("Invalid install step: " + step.getName()); + } + } + } + + /** + * The customer and the device group the install was opened from; each must be the tenant's. The group's own + * permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources. + */ + private Placement placement(TenantId tenantId, DevicePackageRequest request) { + CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId()) + ? new CustomerId(request.getCustomerId()) : null; + if (customerId != null && !isTenantsCustomer(tenantId, customerId)) { + throw new IllegalArgumentException("Invalid install request"); + } + if (request.getEntityGroupId() == null) { + return new Placement(customerId, customerId, null); + } + EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId())); + EntityId owner = group != null ? group.getOwnerId() : null; + boolean tenants = owner != null && (tenantId.equals(owner) + || (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId())))); + if (group == null || group.getType() != EntityType.DEVICE || !tenants) { + throw new IllegalArgumentException("Invalid install request"); + } + // As a device saved into a group: with no customer given, a new one goes to the group's customer + CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId; + return new Placement(customerId, deviceCustomerId, group); + } + + private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) { + Customer customer = customerService.findCustomerById(tenantId, customerId); + return customer != null && tenantId.equals(customer.getTenantId()); + } + + /** + * Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without + * a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale. + */ + private static void assignCustomer(GroupEntity entity, CustomerId customerId, GroupEntity current, DevicePackageRequest.Step step) { + if (customerId != null) { + entity.setOwnerId(customerId); + } + if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) { + throw new IllegalArgumentException(step.getName() + " belongs to another owner"); + } + } + + /** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */ + private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception { + validatePlan(ownedIds(previous), request); + checkFeatures(tenantId, request); + validateIntegrations(tenantId, request); } private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -201,50 +343,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * The device package may only change what it owns, or what the user confirmed. Its own device and gateway, * whose credentials the firmware uses, are never changed. */ - private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + private void validatePlan(Set ownedIds, DevicePackageRequest request) { if (request.getSteps() == null || request.getSteps().isEmpty()) { - throw new IllegalArgumentException("The update has no steps"); + throw new IllegalArgumentException("The device package has no steps"); } - Set ownedIds = ownedIds(devicePackage.descriptor()); // A form's values are saved under its key too, so an entity step may not share it Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { - throw new IllegalArgumentException("Invalid update step: " + step.getName()); + throw new IllegalArgumentException("Invalid step: " + step.getName()); } if (!stateKeys.add(step.stateKey())) { - throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); + throw new IllegalArgumentException("Duplicate step: " + step.stateKey()); } boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); switch (step.getAction()) { case KEEP, OVERWRITE -> { if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { - throw new IllegalArgumentException("No entity for update step: " + step.getName()); + throw new IllegalArgumentException("No entity for step: " + step.getName()); } boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed() && !"GATEWAY_CONNECTOR".equals(step.getType())) { throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) { throw new IllegalArgumentException("The device and its credentials don't change on update"); } } case CREATE -> { } } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { - throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for step: " + step.getName()); } } } /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ - private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { - boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP + private void checkFeatures(TenantId tenantId, DevicePackageRequest request) { + boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); if (savesIntegrations) { subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); @@ -252,13 +393,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** The configuration of an integration is checked by a remote call, so before the transaction. */ - private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { - for (DeviceUpdateRequest.Step step : request.getSteps()) { - if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception { + for (DevicePackageRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) { continue; } ObjectNode body = step.getEntity().deepCopy(); - // Converters this update creates have no id yet; the configuration doesn't depend on them + // Converters the request creates have no id yet; the configuration doesn't depend on them body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); Integration integration = JacksonUtil.treeToValue(body, Integration.class); integration.setTenantId(tenantId); @@ -274,9 +415,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { - IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); - DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + /** + * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the + * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null. + */ + private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId, + Placement placement) { Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); @@ -291,21 +435,22 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List stepEntityIds = new ArrayList<>(); Map usedExistingIds = usedExistingIds(previous); List saved = new ArrayList<>(); - List connectorSteps = new ArrayList<>(); + List grouped = new ArrayList<>(); + List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); DashboardId dashboardId = null; - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { try { if ("GATEWAY_CONNECTOR".equals(step.getType())) { // A connector lives in the gateway's attributes, which aren't transactional: saved after commit - if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() != DevicePackageRequest.Action.KEEP) { connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); } continue; } JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; - StepResult result = applyStep(tenantId, step, entity); + StepResult result = applyStep(tenantId, step, entity, placement); ObjectNode output = result.output(); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); outputs.put(step.stateKey(), output); @@ -317,7 +462,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("resolution", resolution); // A kept entity keeps the checksum of what the package left: the current one would take the // user's changes for the package's, and the next update would overwrite them without a warning - String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); + String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); if (checksum != null) { state.put("checksum", checksum); } @@ -343,8 +488,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { - // As at install, the step's attributes go with the entity it saved; written after commit + if (placement.entityGroup() != null && result.saved() != null && result.saved().created() + && result.entityId().getEntityType() == EntityType.DEVICE) { + entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId()); + grouped.add(result.saved()); + } + // The step's attributes go with the entity it saved; at install also onto an entity the user chose to + // use, as the install always did. Written after commit + boolean install = installedVersionId == null; + if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) { attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); } } catch (StepFailure e) { @@ -356,7 +508,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps // it changes: the other steps and the forms keep their install state - if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { + if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) { previous.getInstallState().forEach((key, value) -> { if (value instanceof ObjectNode state) { installState.putIfAbsent(key, state); @@ -376,15 +528,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i carryMetadataStates(previous, tracked, state); descriptor.setInstallState(state); - installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - installedItemService.save(tenantId, installedItem); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); - return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); + return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped); } /** The checksums the installed device packages recorded, by entity. */ @@ -422,7 +569,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * fails: the plan was made for the version installed before. Without it both would create the new entities. */ - private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { + private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) { IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) @@ -432,11 +579,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return installedItem; } - private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException { return switch (step.getType()) { case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); - case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); - case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "INTEGRATION" -> saveIntegration(tenantId, step, entity); @@ -444,16 +591,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }; } - private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); profile.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(profile, id, current, step); // The tenant's default profile stays the default one @@ -466,31 +613,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; Device device; boolean created = false; - if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + if (step.getAction() == DevicePackageRequest.Action.CREATE) { Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); template.setId(null); template.setVersion(null); + assignCustomer(template, placement.deviceCustomerId(), null, step); device = deviceService.saveDevice(template); created = true; } else { Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; device = existing(tenantId, current, step); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { - // Another device the user chose to overwrite; the package's own device never changes + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { + // On update, another device the user chose to overwrite; it keeps its credentials. The package's own + // device never changes, and an install never overwrites one Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); prepareOverwrite(template, id, current, step); + assignCustomer(template, placement.customerId(), current, step); device = deviceService.saveDevice(template); created = true; } } DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); - if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) { credentials = applyCredentials(tenantId, credentials, step.getCredentials()); } ObjectNode output = output(device.getId(), device.getName()); @@ -500,7 +650,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if ("GATEWAY".equals(step.getType())) { output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); } - SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null; return new StepResult(device.getId(), output, null, saved); } @@ -520,16 +670,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); } - private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getTitle()); } Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); dashboard.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(dashboard, id, current, step); // The dashboard keeps its owner and the customers it is assigned to @@ -537,25 +687,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i dashboard.setCustomerId(current.getCustomerId()); } dashboard.setAssignedCustomers(current.getAssignedCustomers()); + assignCustomer(dashboard, placement.customerId(), current, step); } else { dashboard.setId(null); dashboard.setVersion(null); + assignCustomer(dashboard, placement.customerId(), null, step); } Dashboard result = dashboardService.saveDashboard(dashboard); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); } - private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException { RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); ruleChain.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(ruleChain, id, current, step); // A rule chain the tenant made its root one stays the root @@ -578,17 +730,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } Converter converter = JacksonUtil.treeToValue(entity, Converter.class); converter.setTenantId(tenantId); converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(converter, id, current, step); } else { @@ -599,10 +751,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); Integration merged = withMergedMetadata(current, step.getMetadata()); if (merged != null) { @@ -613,7 +765,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } Integration integration = JacksonUtil.treeToValue(entity, Integration.class); integration.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(integration, id, current, step); // The devices keep sending to the same endpoint @@ -668,7 +820,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i /** * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. - * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change. */ private static Integration withMergedMetadata(Integration integration, JsonNode entries) { if (entries == null || !entries.isObject() || entries.isEmpty()) { @@ -698,7 +850,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the * user reviewed makes the save fail if someone changed the entity since. */ - private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) { switch (entity) { case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } @@ -715,9 +867,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i ((HasVersion) entity).setVersion(currentVersion); } - private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + private T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) { if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { - throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again."); } return current; } @@ -745,9 +897,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with * its metadata, which isn't cached. */ - private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) { String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); - return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE)); } private static ObjectNode output(EntityId id, String name) { @@ -775,7 +927,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + /** Replaces ${.} of entities the request has saved, e.g. the id of a converter it created. */ static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { if (node == null) { return null; @@ -834,17 +986,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; } - /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + /** + * What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install + * or update. + */ private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { for (SavedEntity saved : applied.saved()) { try { - logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null; + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId, saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); if (saved.id().getEntityType() != EntityType.DEVICE) { autoCommit(user, saved.id()); } } catch (Exception e) { - log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e); + } + } + for (SavedEntity saved : applied.grouped()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(), + ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName()); + } catch (Exception e) { + log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e); } } for (StepAttributes step : applied.attributes()) { @@ -855,7 +1019,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); } } - for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { + for (DevicePackageRequest.Step step : applied.connectorSteps()) { try { saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); } catch (Exception e) { @@ -905,7 +1069,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i */ static String userMessage(Throwable e) { if (e instanceof EntityVersionMismatchException) { - return "Someone changed it while you were reviewing the update. Check the update again."; + return "Someone changed it meanwhile. Check the package again."; } if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException || e instanceof SubscriptionException) { @@ -961,8 +1125,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return ids; } - private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { - DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) { + DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class); if (entity != null) { copy.setEntity(entity); } @@ -972,6 +1136,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { } + @FunctionalInterface + private interface PackageChange { + Applied apply() throws Exception; + } + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { } @@ -982,8 +1151,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, - List connectorSteps, List attributes, - Map aliasOutputs) { + List connectorSteps, List attributes, + Map aliasOutputs, EntityGroup entityGroup, List grouped) { + } + + /** + * Where an install opened from a customer's or a device group's page puts its entities. A new device follows the + * group's customer when no customer is given, as a device saved into a group does; an update has none. + */ + private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) { + static final Placement NONE = new Placement(null, null, null); } /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ 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 ddbe8ec5d7..b950ecbd86 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 @@ -421,7 +421,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService + // Updated in one transaction from the install wizard of the new version, see DevicePackageService throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java similarity index 67% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java index a62f556c57..f79f023672 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java @@ -10,28 +10,33 @@ import java.util.Map; import java.util.UUID; /** - * The update of an installed device package as the install wizard planned it: the entity of each install step - * of the new version, already resolved from its template, and what to do with it. The server applies all of it - * in one transaction, together with the new version of the installed item, or nothing. + * The install or update of a device package as the install wizard planned it: the entity of each install step + * of the version being installed, already resolved from its template, and what to do with it. The server applies + * all of it in one transaction, together with the installed item, or nothing. */ @Data -public class DeviceUpdateRequest { +public class DevicePackageRequest { private String versionId; - // The version installed when the wizard planned the update; the update fails if the package changed since + // Update only: the version installed when the wizard planned the update, which fails if the package changed since private UUID fromVersionId; - // The install method of the new version's steps; the installed one when not set + // The install method of the steps; an update without it keeps the installed one private String selectedInstallMethod; // The form values of the install state, by step: the server adds the entities to it private Map installState; + // Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard + // go to, and the group the created device or gateway is added to. An update ignores them + private UUID customerId; + private UUID entityGroupId; private List steps; public enum Action { - // Taken as it is: the new version doesn't change it, or the user kept an entity they had + // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had KEEP, // Takes the entity from the step OVERWRITE, - // A new entity: new in this version, deleted since install, or a copy next to one with the same name + // A new entity: one the package installs, a step new in this version or deleted since install, or a copy + // next to one with the same name CREATE } @@ -51,13 +56,13 @@ public class DeviceUpdateRequest { private Long expectedVersion; // The user confirmed overwriting an entity of another package or one they didn't install with this package private boolean confirmed; - // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this - // update creates is left for the server, which knows its id only once it is created. + // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity the + // request creates is left for the server, which knows its id only once it is created. private JsonNode entity; // DEVICE and GATEWAY: the credentials template, if any private JsonNode credentials; // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, - // they may keep ${.} of an entity this update creates. + // they may keep ${.} of an entity the request creates. private JsonNode serverAttributes; private JsonNode sharedAttributes; // The resolution the install state records for it @@ -65,7 +70,8 @@ public class DeviceUpdateRequest { // INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the // integration, e.g. one the package took as it was; null removes an entry private JsonNode metadata; - // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check + // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later + // update checks that converter against ThingsBoard's default one private boolean defaultConverter; /** diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java similarity index 70% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java index 5c8ec6e8d7..d07a51d839 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java @@ -17,7 +17,7 @@ import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor -public class DeviceUpdateResult { +public class DevicePackageResult { private boolean success; private String errorMessage; @@ -26,12 +26,12 @@ public class DeviceUpdateResult { // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; - public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { - return new DeviceUpdateResult(true, null, null, descriptor, outputs); + public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { + return new DevicePackageResult(true, null, null, descriptor, outputs); } - public static DeviceUpdateResult error(String errorMessage, String failedStep) { - return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); + public static DevicePackageResult error(String errorMessage, String failedStep) { + return new DevicePackageResult(false, errorMessage, failedStep, null, null); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java similarity index 59% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java index 5688056c98..60103c6e01 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java @@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; -/** Updates an installed device package to another version of its item. */ -public interface DevicePackageUpdateService { +/** Installs a device package, or updates an installed one to another version of its item. */ +public interface DevicePackageService { /** The package's entities as they are now: whether they still exist, changed since, or are shared. */ List check(SecurityUser user, IotHubInstalledItemId installedItemId); + /** Installs the version in one transaction, together with its installed item, or nothing. */ + DevicePackageResult install(SecurityUser user, DevicePackageRequest request); + /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ - DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); + DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java similarity index 60% rename from application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java index 38595a0c71..5a75ddc997 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -16,12 +17,17 @@ import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; @@ -30,23 +36,29 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.subscription.PlatformFeature; @@ -54,6 +66,7 @@ import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -62,20 +75,25 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class DefaultDevicePackageUpdateServiceTest { +class DefaultDevicePackageServiceTest { private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); private final SecurityUser user = mock(SecurityUser.class); @@ -119,18 +137,30 @@ class DefaultDevicePackageUpdateServiceTest { private TelemetrySubscriptionService telemetryService; @Mock private IotHubService iotHubService; + @Mock + private ProjectInfo projectInfo; + @Mock + private CustomerService customerService; + @Mock + private EntityGroupService entityGroupService; @InjectMocks - private DefaultDevicePackageUpdateService service; + private DefaultDevicePackageService service; private IotHubInstalledItem installedItem; // Set when the transaction callback threw, so the transaction would roll back private final List rolledBack = new ArrayList<>(); + private boolean inTransaction; + private final List savedInTransaction = new ArrayList<>(); + // What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside + private final List afterCommitCalls = new ArrayList<>(); @BeforeEach void setUp() { ReflectionTestUtils.setField(service, "entityService", entityService); ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); + ReflectionTestUtils.setField(service, "customerService", customerService); + ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService); when(user.getTenantId()).thenReturn(tenantId); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -158,11 +188,14 @@ class DefaultDevicePackageUpdateServiceTest { when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + inTransaction = true; try { return invocation.>getArgument(0).doInTransaction(null); } catch (RuntimeException e) { rolledBack.add(e); throw e; + } finally { + inTransaction = false; } }); when(packageEntities.checksum(any(), any())).thenReturn("checksum"); @@ -184,7 +217,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), keep("AM308", "DEVICE", deviceId), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); @@ -218,10 +251,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); + DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -237,10 +270,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); overview.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(overview)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -256,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -266,10 +299,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void useExistingOfAPackageEntity_staysThePackages() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -282,10 +315,10 @@ class DefaultDevicePackageUpdateServiceTest { // At install the user picked their own dashboard: the install adds it to createdEntityIds too ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -295,9 +328,9 @@ class DefaultDevicePackageUpdateServiceTest { @Test void overwritingAnEntityUsedAtInstall_needsAConfirmation() { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -327,10 +360,10 @@ class DefaultDevicePackageUpdateServiceTest { // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -343,9 +376,9 @@ class DefaultDevicePackageUpdateServiceTest { DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); installed.setUsedExistingEntityIds(List.of(dashboardId)); installed.setInstallState(Map.of()); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -358,7 +391,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); @@ -377,13 +410,13 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setResolution("use-existing"); ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); entries.putNull("profile.milesight-iot-am308"); step.setMetadata(entries); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); @@ -411,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest { integration.setId(integrationId); when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -438,11 +471,11 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); step.setResolution("use-existing"); step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -465,10 +498,10 @@ class DefaultDevicePackageUpdateServiceTest { configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); verify(integrationService, never()).saveIntegration(any()); @@ -476,12 +509,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsWithOneKey_areRejected() { - DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); first.setId("main-dashboard"); - DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); + DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId); second.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -489,25 +522,25 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsOfOneTypeAndName_areRejected() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard"); verify(transactionTemplate, never()).execute(any()); } @Test void stepWithTheKeyOfAForm_isRejected() { - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setId("Settings"); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10)))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings"); verify(transactionTemplate, never()).execute(any()); } @@ -532,14 +565,14 @@ class DefaultDevicePackageUpdateServiceTest { legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), "Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); - DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); + DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); uplink.setDefaultConverter(true); - DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); + DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateRequest request = request(uplink, ttn); + DevicePackageRequest request = request(uplink, ttn); request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration"))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -563,7 +596,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); @@ -580,12 +613,12 @@ class DefaultDevicePackageUpdateServiceTest { void entityChangedSinceTheCheck_isAVersionConflict() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); - assertThat(result.getErrorMessage()).contains("Check the update again"); + assertThat(result.getErrorMessage()).contains("Check the package again"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -608,7 +641,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); @@ -640,12 +673,12 @@ class DefaultDevicePackageUpdateServiceTest { IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); when(installedItemService.findByTenantId(any(), any(), any(), any())) .thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); - DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setConfirmed(true); step.setDefaultConverter(true); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); @@ -672,14 +705,14 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0"); when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); // ThingsBoard's default converter changed: only the converter step is sent - DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setId("uplink"); step.setDefaultConverter(true); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setVersionId(installedVersionId.toString()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -697,7 +730,7 @@ class DefaultDevicePackageUpdateServiceTest { void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); @@ -707,7 +740,7 @@ class DefaultDevicePackageUpdateServiceTest { void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -716,7 +749,7 @@ class DefaultDevicePackageUpdateServiceTest { @Test void theDeviceIsNeverOverwritten() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -729,7 +762,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isFalse(); verify(transactionTemplate, never()).execute(any()); @@ -743,7 +776,7 @@ class DefaultDevicePackageUpdateServiceTest { updated.setItemVersionId(UUID.fromString(versionId)); when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -754,10 +787,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void planOfAnotherInstalledVersion_isRejected() { - DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); + DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId)); request.setFromVersionId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -768,7 +801,7 @@ class DefaultDevicePackageUpdateServiceTest { doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) .when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -780,10 +813,10 @@ class DefaultDevicePackageUpdateServiceTest { void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); @@ -829,12 +862,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void userMessage_showsValidationMessagesAndHidesInternalOnes() { - assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) + assertThat(DefaultDevicePackageService.userMessage(new DataValidationException("Rule chains limit reached"))) .isEqualTo("Rule chains limit reached"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) - .contains("Check the update again"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) - .isEqualTo("Failed to update the device package"); + assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) + .contains("Check the package again"); + assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) + .isEqualTo("Failed to save the device package"); } @Test @@ -842,12 +875,431 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); - ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); + ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device)); assertThat(resolved.get("a").asText()).isEqualTo("123"); assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); } + @Test + void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("use-existing"); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + integrationStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + verify(transactionTemplate).execute(any()); + assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM"); + ArgumentCaptor saved = ArgumentCaptor.forClass(IotHubInstalledItem.class); + verify(installedItemService).save(eq(tenantId), saved.capture()); + IotHubInstalledItem item = saved.getValue(); + assertThat(item.getTenantId()).isEqualTo(tenantId); + assertThat(item.getItemId()).isEqualTo(itemId); + assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(item.getVersion()).isEqualTo("1.0.1"); + assertThat(item.getItemName()).isEqualTo("AM308"); + assertThat(item.getItemType()).isEqualTo("DEVICE"); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor(); + assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId); + assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId); + assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId); + Map state = descriptor.getInstallState(); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString()); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue(); + assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString()); + assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue(); + assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString()); + assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing"); + assertThat(result.getDescriptor()).isSameAs(descriptor); + assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard"); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installFailureOnALaterStepSavesNothing() { + mockInstall(); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); + assertThat(rolledBack).hasSize(1); + verify(installedItemService, never()).save(any(), any()); + verifyNoInteractions(logEntityActionService, telemetryService); + verify(iotHubRestClient, never()).reportVersionInstalled(any(), any()); + } + + @Test + void installOverwriteOfAnExistingEntityNeedsAConfirmation() { + mockInstall(); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + + DevicePackageResult result = service.install(user, request( + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard"); + verify(transactionTemplate, never()).execute(any()); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWithBadIntegrationCredentialsSavesNothing() throws Exception { + mockInstall(); + doThrow(new ExecutionException(new IllegalStateException("Wrong API key"))) + .when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any()); + + DevicePackageResult result = service.install(user, request( + create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN"); + assertThat(result.getErrorMessage()).isEqualTo("Wrong API key"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWhenHubIsUnavailableSavesNothing() { + mockInstall(); + when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused")); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later."); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() { + mockInstall(); + doAnswer(i -> { + recordAfterCommit("REPORT"); + throw new RestClientException("Connection refused"); + }).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient); + order.verify(installedItemService).save(eq(tenantId), any()); + order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user)); + order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT"); + } + + @Test + void installRejectsAFromVersion() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setFromVersionId(installedVersionId); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installKeepStepMustUseExisting() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("created"); + + DevicePackageResult result = service.install(user, request(integrationStep)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installRejectsAMalformedVersionId() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setVersionId("not-a-uuid"); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(iotHubRestClient, never()).getVersionInfo(any()); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void installAssignsTheCustomerToTheDeviceAndTheDashboard() { + mockInstall(); + CustomerId customerId = customerOf(tenantId); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(customerId); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId); + } + + @Test + void installAddsTheDeviceToTheEntityGroup() { + mockInstall(); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Warehouse sensors"); + group.setOwnerId(tenantId); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId)); + assertThat(savedInTransaction).contains("ENTITY_GROUP"); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP), + eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors")); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installRejectsACustomerOfAnotherTenant() { + mockInstall(); + CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID())); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateIgnoresCustomerAndEntityGroup() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); + DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(UUID.randomUUID()); + request.setEntityGroupId(UUID.randomUUID()); + + DevicePackageResult result = service.update(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isNull(); + verifyNoInteractions(customerService, entityGroupService); + } + + @Test + void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + current.setCustomerId(customerOf(tenantId)); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare"); + assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner"); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateOverwriteOfAnotherDeviceKeepsItsCredentials() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0)); + DeviceCredentials credentials = new DeviceCredentials(); + credentials.setDeviceId(otherId); + credentials.setCredentialsId("existing-token"); + when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token")); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isTrue(); + verify(deviceService).saveDevice(any(Device.class)); + verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any()); + assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token"); + } + + @Test + void installRejectsAnOverwriteOfADeviceOrGateway() { + mockInstall(); + for (String type : new String[]{"DEVICE", "GATEWAY"}) { + DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308")); + step.setConfirmed(true); + + DevicePackageResult result = service.install(user, request(step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308"); + } + verify(transactionTemplate, never()).execute(any()); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() { + mockInstall(); + DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId); + deviceStep.setResolution("use-existing"); + deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308")); + deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); + + DevicePackageResult result = service.install(user, request(deviceStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); + verify(telemetryService, times(2)).saveAttributes(saved.capture()); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE); + assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308"); + assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); + // The kept device isn't saved, so only the dashboard is audited + assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT"); + } + + @Test + void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() { + mockInstall(); + CustomerId groupCustomer = customerOf(tenantId); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Customer sensors"); + group.setOwnerId(groupCustomer); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user)); + } + + private CustomerId customerOf(TenantId owner) { + Customer customer = new Customer(new CustomerId(UUID.randomUUID())); + customer.setTenantId(owner); + when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer); + return customer.getId(); + } + + /** The new entities get these ids; each save records that it ran inside the transaction. */ + private void mockInstall() { + when(user.getId()).thenReturn(new UserId(UUID.randomUUID())); + when(projectInfo.getProjectVersion()).thenReturn("4.4.1"); + when(projectInfo.getProductType()).thenReturn("PE"); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> { + recordSave("DEVICE_PROFILE"); + DeviceProfile profile = i.getArgument(0); + profile.setId(profileId); + return profile; + }); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> { + recordSave("DASHBOARD"); + Dashboard dashboard = i.getArgument(0); + dashboard.setId(dashboardId); + return dashboard; + }); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> { + recordSave("DEVICE"); + Device device = i.getArgument(0); + device.setId(deviceId); + return device; + }); + doAnswer(i -> { + recordSave("ENTITY_GROUP"); + return null; + }).when(entityGroupService).addEntityToEntityGroup(any(), any(), any()); + when(installedItemService.save(any(), any())).thenAnswer(i -> { + recordSave("INSTALLED_ITEM"); + return i.getArgument(1); + }); + Integration integration = new Integration(); + integration.setId(integrationId); + integration.setTenantId(tenantId); + integration.setName("TTN my-app"); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration); + doAnswer(i -> { + recordAfterCommit("AUDIT"); + return null; + }).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class), + any(ActionType.class), any(User.class), any(Object[].class)); + doAnswer(i -> { + recordAfterCommit("REPORT"); + return null; + }).when(iotHubRestClient).reportVersionInstalled(any(), any()); + doAnswer(i -> { + recordAfterCommit("ATTRIBUTES"); + return null; + }).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class)); + } + + private void recordSave(String what) { + if (inTransaction) { + savedInTransaction.add(what); + } + } + + private void recordAfterCommit(String what) { + afterCommitCalls.add(inTransaction ? what + " in transaction" : what); + } + private IotHubInstalledItem otherPackage(Map installState) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setInstallState(installState); @@ -875,35 +1327,35 @@ class DefaultDevicePackageUpdateServiceTest { return dashboard; } - private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { - DeviceUpdateRequest request = new DeviceUpdateRequest(); + private DevicePackageRequest request(DevicePackageRequest.Step... steps) { + DevicePackageRequest request = new DevicePackageRequest(); request.setVersionId(versionId); request.setSteps(List.of(steps)); return request; } - private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); + private static DevicePackageRequest.Step keep(String name, String type, EntityId id) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP); step.setEntityId(id.getId()); return step; } - private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); + private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE); step.setEntityId(id.getId()); step.setExpectedVersion(version); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); + private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { - DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); + private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) { + DevicePackageRequest.Step step = new DevicePackageRequest.Step(); step.setName(name); step.setType(type); step.setAction(action); 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 e162ba1357..b9af2299f2 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 @@ -14,7 +14,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DevicePackageEntityState, DevicePackageRequest, DevicePackageResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, 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'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; @@ -180,18 +180,6 @@ export class IotHubApiService { ); } - public registerDeviceInstall( - versionId: string, - descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig - ): Observable { - return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, - { type: 'DEVICE', ...descriptor }, - { params: this.buildParams(config) } - ); - } - public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable { return this.http.post( `/api/iot-hub/versions/${versionId}/install`, @@ -287,14 +275,23 @@ export class IotHubApiService { } /** Applies a device package update in one transaction: all of it, or nothing. */ - public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable { - return this.http.post( + public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, request, { params: this.buildParams(config) } ); } + /** Installs a device package in one transaction: all of its entities and the installed item, or nothing. */ + public installDevicePackage(request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/device/install`, + request, + { params: this.buildParams(config) } + ); + } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { return this.http.get( `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 23578f5490..cf6e9d0cca 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -62,93 +62,7 @@ } @case ('progress') { - @if (data.update) { - - } @else { -
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { - @if (i > 0) { -
- } - @if (ep.status === 'conflict' || ep.status === 'error') { -
-
-
- warning -
-
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - @if (ep.status === 'conflict') { - - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} - - } - @if (ep.status === 'error' && ep.errorMessage) { - {{ ep.errorMessage }} - } -
-
-
- @if (ep.status === 'conflict') { - @if (ep.conflictType === 'use-or-overwrite') { - - - } @else { - - - } - } - @if (ep.status === 'error') { - - } -
-
- } @else { -
-
- @switch (ep.status) { - @case ('pending') { -
{{ i + 1 }}
- } - @case ('running') { - - } - @case ('success') { - check_circle - } - } -
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - - @if (ep.status === 'success') { - {{ 'iot-hub.done' | translate }} - } - @if (ep.status === 'running') { - {{ 'iot-hub.in-progress' | translate }} - } - -
- } - } -
- } + } }
@@ -156,18 +70,17 @@ - @let hint = textWithLink('iot-hub.device-update-modified'); - {{ hint.before }}{{ hint.link }}{{ hint.after }} + {{ modifiedHintText.before }}{{ modifiedHintText.link }}{{ modifiedHintText.after }} - - + +
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @for (ep of ws.entitySteps; track ep.step; let i = $index) { @if (i > 0) {
} - @let plan = updatePlanOf(ep); + @let plan = planOf(ep); @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name); @if (ws.reviewing && plan && !plan.confirmed) {
@@ -182,7 +95,7 @@ } @if (plan.existing) { - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate), name: plan.existing.name } }} } @if (plan.shared) { @@ -198,19 +111,21 @@
@if (plan.existing) { @if (ep.step.type === 'DASHBOARD') { - } @else { - } - + @if (canOverwriteExisting(ep)) { + + } } @else { - } @@ -237,7 +152,7 @@ } @case ('success') { - check_circle + check_circle } @default {
{{ i + 1 }}
@@ -249,7 +164,8 @@ {{ label }} - @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + + @if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') { {{ 'iot-hub.device-update-new' | translate }} }
@@ -274,10 +190,10 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ updateOutcomeOf(plan) | translate }} + {{ appliedOutcomeOf(plan) | translate }} } @case ('skipped') { - {{ 'iot-hub.device-update-skipped' | translate }} + {{ 'iot-hub.device-package-skipped' | translate }} } @default { @@ -335,7 +251,7 @@
- @for (ws of wizardSteps; track ws.label) { + @for (ws of wizardSteps; track ws) { @@ -359,8 +275,8 @@ done - @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -378,24 +294,24 @@ } - @if (data.update && currentWizardStep?.type === 'progress') { + @if (currentWizardStep?.type === 'progress') { @let step = currentWizardStep; - @if (hasUpdateError(step)) { -
+ @if (hasPackageError(step)) { +
error {{ step.progressError }}
- } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { -
+ } @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) { +
warning - {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} + {{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}
} } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -432,13 +348,13 @@ } @case ('progress') { - @if (data.update && (step.reviewing || step.updating || step.progressError)) { - @if (step.progressError && !step.updating) { - - + - } @else if (step.updating) { + } @else if (step.applying) { } - } @else if (step.progressError) { - - } @else if (step.progressDone && isLastWizardStep) { - } @else if (!step.progressError) { + } @else {