From a1e4e33b2bfcc4a7ed9877e8fe1be6057f1063b0 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 16 Nov 2026 10:49:56 +0200 Subject: [PATCH] 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",