Browse Source

IoT Hub installed items: after Check for updates only the items with an update, no server cache (PROD-9326)

pull/16657/head
dpinkevych 3 weeks ago
parent
commit
a1e4e33b2b
  1. 26
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 54
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  3. 15
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
  4. 12
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  5. 89
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  6. 6
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  7. 6
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  8. 19
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  9. 30
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  10. 10
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  11. 50
      dao/src/test/java/org/thingsboard/server/dao/service/IotHubInstalledItemServiceTest.java
  12. 45
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  13. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  14. 102
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  15. 45
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html
  16. 29
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss
  17. 23
      ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts
  18. 8
      ui-ngx/src/assets/locale/locale.constant-en_US.json

26
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<String> 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<IotHubInstalledItem> 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<String> itemTypes,
@RequestBody Map<UUID, UUID> 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

54
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<TenantId, Map<UUID, UUID>> 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<IotHubInstalledItem> findInstalledItemsUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
Map<UUID, UUID> 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<UUID, UUID> findPublishedVersionIds(TenantId tenantId) {
List<UUID> itemIds = iotHubInstalledItemService.findInstalledItemIdsByTenantId(tenantId);
Map<UUID, UUID> publishedVersionIds = new HashMap<>();
try {
for (List<UUID> 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<UUID, UUID> 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) {

15
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<UUID> 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);

12
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<IotHubInstalledItem> findInstalledItemsUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
InstallPlan resolveInstallPlan(SecurityUser user, String versionId);
InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request);

89
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<UUID> 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);
}
}

6
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java

@ -25,9 +25,9 @@ public interface IotHubInstalledItemDao extends Dao<IotHubInstalledItem> {
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
// publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first
PageData<IotHubInstalledItem> findByTenantIdUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
// publishedVersionIds: IoT Hub's published version id by item id, not empty; only the items installed in another version
PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

6
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java

@ -25,9 +25,9 @@ public interface IotHubInstalledItemService {
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
// publishedVersionIds: IoT Hub's published version id by item id; the items installed in another version come first
PageData<IotHubInstalledItem> findByTenantIdUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
// publishedVersionIds: IoT Hub's published version id by item id; only the items installed in another version
PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

19
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<IotHubInstalledItem> findByTenantIdUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
public PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> 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<UUID, UUID> 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

30
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java

@ -46,35 +46,25 @@ interface IotHubInstalledItemRepository extends JpaRepository<IotHubInstalledIte
Page<IotHubInstalledItemEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> 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<IotHubInstalledItemEntity> findByTenantIdUpdatesFirst(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes,
@Param("itemId") UUID itemId, @Param("textSearch") String textSearch,
@Param("publishedItemIds") Collection<UUID> publishedItemIds,
@Param("publishedVersionIds") Collection<UUID> publishedVersionIds,
Pageable pageable);
Page<IotHubInstalledItemEntity> findByTenantIdWithUpdates(@Param("tenantId") UUID tenantId, @Param("itemTypes") List<String> itemTypes,
@Param("textSearch") String textSearch,
@Param("publishedItemIds") Collection<UUID> publishedItemIds,
@Param("publishedVersionIds") Collection<UUID> publishedVersionIds,
Pageable pageable);
@Query("""
SELECT COUNT(item) FROM IotHubInstalledItemEntity item

10
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java

@ -58,15 +58,11 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao<IotHubInstalledItemEntity
}
@Override
public PageData<IotHubInstalledItem> findByTenantIdUpdatesFirst(TenantId tenantId, List<String> itemTypes, UUID itemId,
Map<UUID, UUID> publishedVersionIds, PageLink pageLink) {
if (publishedVersionIds == null || publishedVersionIds.isEmpty()) {
return findByTenantId(tenantId, itemTypes, itemId, pageLink);
}
return DaoUtil.toPageData(repository.findByTenantIdUpdatesFirst(
public PageData<IotHubInstalledItem> findByTenantIdWithUpdates(TenantId tenantId, List<String> itemTypes,
Map<UUID, UUID> 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(),

50
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<IotHubInstalledItem> page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(), byName);
PageData<IotHubInstalledItem> 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<IotHubInstalledItem> first = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(),
new PageLink(2, 0, null, byNameDesc));
PageData<IotHubInstalledItem> second = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, published(),
new PageLink(2, 1, null, byNameDesc));
PageData<IotHubInstalledItem> first = installedItemService.findByTenantIdWithUpdates(tenantId, null, published(),
new PageLink(1, 0, null, byName));
PageData<IotHubInstalledItem> 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<IotHubInstalledItem> 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<IotHubInstalledItem> page = installedItemService.findByTenantIdUpdatesFirst(tenantId, null, null, Map.of(), byName);
Map<UUID, UUID> 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();
}
}

45
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<PageData<IotHubInstalledItem>> {
itemId?: string, config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> {
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<PageData<IotHubInstalledItem>>(
`/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<string, string>,
config?: IotHubRequestConfig): Observable<PageData<IotHubInstalledItem>> {
let query = pageLink.toQuery();
if (itemTypes?.length) {
query += itemTypes.map(t => `&itemTypes=${t}`).join('');
}
return this.http.post<PageData<IotHubInstalledItem>>(
`/api/iot-hub/installedItems/withUpdates${query}`,
publishedVersionIds,
{ params: this.buildParams(config) }
);
}
public getInstalledItemsCount(itemType?: string, config?: IotHubRequestConfig): Observable<number> {
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<ItemPublishedVersionInfo[]> {
return this.http.post<ItemPublishedVersionInfo[]>(
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<ItemPublishedVersionInfo[]>(
`${this.baseUrl}/api/versions/publishedVersions`,
itemIds,
chunk,
{ params: this.buildParams(config) }
);
))).pipe(map(results => results.flat()));
}
public getCreatorProfile(creatorId: string, config?: IotHubRequestConfig): Observable<CreatorView> {

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html

@ -125,7 +125,17 @@
<tr mat-row *matRowDef="let _row; columns: displayedColumns;"></tr>
</table>
@if (!isLoading && dataSource.length === 0) {
@if (!isLoading && dataSource.length === 0 && onlyUpdates && !hasActiveFilters()) {
<!-- Only the items with an update, and none has one -->
<div class="tb-iot-hub-empty-state flex flex-1 flex-col items-center justify-center text-center">
<div class="tb-no-data-bg"></div>
<h3>{{ 'iot-hub.all-items-up-to-date' | translate }}</h3>
<p>{{ 'iot-hub.all-items-up-to-date-text' | translate }}</p>
<button mat-flat-button color="primary" (click)="showOnlyUpdates(false)">
{{ 'iot-hub.show-all-items' | translate }}
</button>
</div>
} @else if (!isLoading && dataSource.length === 0) {
<div class="tb-iot-hub-empty-state flex flex-1 flex-col items-center justify-center text-center">
<div class="tb-no-data-bg"></div>
<h3>{{ 'iot-hub.no-installed-items' | translate }}</h3>

102
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<string, string> {
const ids: Record<string, string> = {};
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;

45
ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.html

@ -1,7 +1,8 @@
<!--
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
-->
<div class="tb-installed-items-page flex h-full flex-col">
@ -15,14 +16,42 @@
<div class="tb-installed-header">
<h1 class="tb-installed-title">{{ 'iot-hub.installed-items' | translate }}</h1>
@if (!updatesChecked) {
<button mat-flat-button color="primary" (click)="checkForUpdates()" [disabled]="isCheckingUpdates">
@if (isCheckingUpdates) {
<mat-spinner matButtonIcon class="mr-2" diameter="18"></mat-spinner>
} @else {
<mat-icon matButtonIcon>update</mat-icon>
<div class="tb-installed-updates flex items-center gap-4">
@if (updatesCheckFailed) {
<span class="tb-installed-updates-note">
<mat-icon class="tb-installed-updates-failed">warning</mat-icon>
{{ 'iot-hub.check-for-updates-failed' | translate }}
</span>
}
{{ 'iot-hub.check-for-updates' | translate }}
</button>
<button mat-flat-button color="primary" (click)="checkForUpdates()" [disabled]="isCheckingUpdates">
@if (isCheckingUpdates) {
<mat-spinner matButtonIcon class="mr-2" diameter="18"></mat-spinner>
} @else {
<mat-icon matButtonIcon>update</mat-icon>
}
{{ (updatesCheckFailed ? 'iot-hub.check-for-updates-try-again' : 'iot-hub.check-for-updates') | translate }}
</button>
</div>
} @else {
<!-- After Check for updates: how many items have one, and the switch between them and all items -->
<div class="tb-installed-updates flex items-center gap-4">
@if (updatesCount !== null) {
<span class="tb-installed-updates-note">
@if (updatesCount > 0) {
<mat-icon class="tb-installed-updates-available">arrow_circle_up</mat-icon>
{{ (updatesCount === 1 ? 'iot-hub.item-with-update' : 'iot-hub.items-with-update') | translate:{ count: updatesCount, total: installedCount } }}
} @else {
<mat-icon class="tb-installed-updates-none">check_circle</mat-icon>
{{ 'iot-hub.all-items-up-to-date' | translate }}
}
</span>
}
@if (onlyUpdates) {
<button mat-stroked-button color="primary" (click)="showOnlyUpdates(false)">{{ 'iot-hub.show-all-items' | translate }}</button>
} @else if ((updatesCount ?? 0) > 0) {
<button mat-stroked-button color="primary" (click)="showOnlyUpdates(true)">{{ 'iot-hub.show-only-updates' | translate }}</button>
}
</div>
}
</div>

29
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;

23
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);
}
}

8
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",

Loading…
Cancel
Save