Browse Source

address the second PE review pass on the install report

- rename the cap to MAX_LISTED_NAMES_PER_TYPE: it shortens the printed
  list, it does not limit what is validated
- say how many conflicts a type has in total, and add a note when names
  were left out, so the "rename or delete them" instruction stays true
- keep only the names in the conflict map, the entities were never read
  for anything else
- one way of saying "there are no details" in the dialog, and one comment
  instead of two that open the same way
- cover the whole branch of the cap (10, 11 and 12 names) and the profile
  name that comes from both the json file and the directory
pull/16109/head
dpinkevych 2 months ago
parent
commit
79e1a9ff77
Failed to extract signature
  1. 36
      application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
  2. 71
      application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java
  3. 17
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts

36
application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java

@ -182,7 +182,9 @@ public class DefaultSolutionService implements SolutionService {
private static final String CONFLICTS_INTRO =
"Some entities of the solution template already exist. Rename or delete them and install the template again:";
private static final String RANDOM_PLACEHOLDER = "$random";
private static final int MAX_REPORTED_CONFLICTS = 10;
private static final int MAX_LISTED_NAMES_PER_TYPE = 10;
private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE
+ " names of each type are listed. The rest are reported the next time the template is installed.";
@Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}")
private String docsBaseUrl;
@ -321,7 +323,7 @@ public class DefaultSolutionService implements SolutionService {
});
// Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
Map<EntityType, List<HasName>> conflicts = new LinkedHashMap<>();
Map<EntityType, List<String>> conflicts = new LinkedHashMap<>();
collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains);
collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName,
name -> deviceProfileService.findDeviceProfileByName(tenantId, name));
@ -338,8 +340,11 @@ public class DefaultSolutionService implements SolutionService {
return null;
}
StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE);
conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType,
entities.stream().map(entity -> "'" + entity.getName() + "'").toList()));
conflicts.forEach((entityType, names) -> appendConflicts(details, entityType,
names.stream().map(name -> "'" + name + "'").toList()));
if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) {
details.append(System.lineSeparator()).append(TRUNCATION_NOTE);
}
SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse();
solutionInstallResponse.setSuccess(false);
@ -351,7 +356,7 @@ public class DefaultSolutionService implements SolutionService {
* The entity type and the name both come from the definition, so a list can not end up checked against the
* wrong type by mistake.
*/
private void collectConflicts(Map<EntityType, List<HasName>> conflicts, List<? extends EntityDefinition> definitions,
private void collectConflicts(Map<EntityType, List<String>> conflicts, List<? extends EntityDefinition> definitions,
Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (EntityDefinition definition : definitions) {
@ -361,7 +366,7 @@ public class DefaultSolutionService implements SolutionService {
}
}
private <T> void collectConflicts(Map<EntityType, List<HasName>> conflicts, EntityType entityType, List<T> definitions,
private <T> void collectConflicts(Map<EntityType, List<String>> conflicts, EntityType entityType, List<T> definitions,
Function<T, String> nameExtractor, Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (T definition : definitions) {
@ -372,14 +377,14 @@ public class DefaultSolutionService implements SolutionService {
}
}
private void collectConflict(Map<EntityType, List<HasName>> conflicts, EntityType entityType, String name,
private void collectConflict(Map<EntityType, List<String>> conflicts, EntityType entityType, String name,
Function<String, ? extends HasName> lookup) {
if (StringUtils.isEmpty(name)) {
return;
}
HasName existing = lookup.apply(name);
if (existing != null) {
conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing);
conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName());
}
}
@ -387,7 +392,7 @@ public class DefaultSolutionService implements SolutionService {
* A rule chain is created from the rule chain file, so both the name and the type of the chain the install will
* produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE.
*/
private void collectRuleChainConflicts(Map<EntityType, List<HasName>> conflicts, TenantId tenantId, Path tempDir,
private void collectRuleChainConflicts(Map<EntityType, List<String>> conflicts, TenantId tenantId, Path tempDir,
List<ReferenceableEntityDefinition> definitions) {
Set<String> checked = new HashSet<>();
for (ReferenceableEntityDefinition definition : definitions) {
@ -426,13 +431,16 @@ public class DefaultSolutionService implements SolutionService {
/**
* One markdown list item per entity type, so that the names of the conflicting entities are what the user reads,
* instead of the same sentence repeated for every type.
* instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE}
* names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of
* that type is not complete.
*/
private void appendConflicts(StringBuilder details, EntityType entityType, List<String> conflictDescriptions) {
private static void appendConflicts(StringBuilder details, EntityType entityType, List<String> conflictDescriptions) {
details.append("- **").append(entityType.getNormalName()).append("**: ")
.append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", ")));
if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) {
details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more");
.append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", ")));
if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) {
details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE)
.append(" more (").append(conflictDescriptions.size()).append(" in total)");
}
details.append(System.lineSeparator());
}

71
application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java

@ -18,6 +18,8 @@ package org.thingsboard.server.service.solutions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -61,6 +63,10 @@ class DefaultSolutionServiceTest {
private static final String CONFLICTS_INTRO =
"Some entities of the solution template already exist. Rename or delete them and install the template again:";
// mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it
private static final int LISTED_NAMES_PER_TYPE = 10;
private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE
+ " names of each type are listed. The rest are reported the next time the template is installed.";
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
@ -95,15 +101,14 @@ class DefaultSolutionServiceTest {
Customer customer = new Customer();
customer.setTitle("Existing customer");
Device device = new Device();
device.setName("Existing device");
when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer));
Asset asset = new Asset();
asset.setName("Existing asset");
when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset);
when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null);
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device);
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device"))
.thenReturn(existingDevice("Existing device"));
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null);
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
@ -184,9 +189,7 @@ class DefaultSolutionServiceTest {
void testValidateSolutionLooksTheSameNameUpOnce() throws IOException {
writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]");
Device device = new Device();
device.setName("Sensor");
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device);
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor"));
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
@ -227,23 +230,47 @@ class DefaultSolutionServiceTest {
verifyNoInteractions(deviceService);
}
@Test
void testValidateSolutionCapsTheNamesItLists() throws IOException {
String definitions = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}")
.collect(Collectors.joining(","));
writeEntitiesFile("devices.json", "[" + definitions + "]");
for (int i = 1; i <= 12; i++) {
Device device = new Device();
device.setName("Sensor " + i);
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device);
@ParameterizedTest
@ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2})
void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException {
List<String> names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList();
writeEntitiesFile("devices.json", names.stream()
.map(name -> "{\"name\": \"" + name + "\"}")
.collect(Collectors.joining(",", "[", "]")));
names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name))
.thenReturn(existingDevice(name)));
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
int hidden = conflictCount - LISTED_NAMES_PER_TYPE;
String listed = names.stream().limit(LISTED_NAMES_PER_TYPE)
.map(name -> "'" + name + "'").collect(Collectors.joining(", "));
assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed
+ (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : ""));
if (hidden > 0) {
assertThat(result.getDetails()).contains(TRUNCATION_NOTE);
} else {
assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE);
}
}
/**
* The profile lists are the json file plus every file in the directory of the same name merged into one list, so
* this is where the same name genuinely can appear twice.
*/
@Test
void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException {
writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]");
writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}");
DeviceProfile profile = new DeviceProfile();
profile.setName("Sensor profile");
when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile);
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
assertThat(result.getDetails().lines().toList())
.contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', "
+ "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more");
assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'");
verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile");
}
@Test
@ -261,6 +288,12 @@ class DefaultSolutionServiceTest {
deviceProfileService, assetProfileService, edgeService);
}
private static Device existingDevice(String name) {
Device device = new Device();
device.setName(name);
return device;
}
private void writeFile(String relativePath, String content) throws IOException {
Path file = tempDir.resolve(relativePath);
Files.createDirectories(file.getParent());

17
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts

@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent<TbIotHubInst
next: (result) => {
if (!result.success) {
this.state = 'error';
this.errorMessage = result.errorMessage ?? '';
this.errorMessage = result.errorMessage || '';
return;
}
this.handleInstalledDescriptor(result.descriptor);
@ -338,12 +338,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent<TbIotHubInst
if (!result.success) {
this.state = 'error';
const serverError = result.errorMessage;
// The description above the details already names the item, so nothing is rendered here when the server
// reported no message of its own.
let message = serverError ?? '';
// The description above already names the item being installed, so only a failing dependency has to be
// named here, and only when the server reported the failure. A missing entry carries an error message of
// its own, so the failing one is the entry the cascade actually tried to install.
// The description above the details already names the item being installed, so nothing is rendered here when
// the server reported no message of its own, and only a failing dependency has to be named - and only when the
// server reported the failure. A missing entry carries an error message of its own, so the failing one is the
// entry the cascade actually tried to install.
let message = serverError || '';
const failedDependency = serverError ? (result.entries ?? []).find(
entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined;
if (failedDependency) {
@ -355,8 +354,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent<TbIotHubInst
// behind — tell the admin so they know manual cleanup may be needed. The willInstall guard
// avoids the misleading warning on the "empty plan" failure, where nothing was installed.
if (!result.rolledBack && this.planSummary.willInstall > 0) {
const warning = this.translate.instant('iot-hub.install-rollback-partial');
message = message ? message + '\n\n' + warning : warning;
message = [message, this.translate.instant('iot-hub.install-rollback-partial')]
.filter(Boolean).join('\n\n');
}
this.errorMessage = message;
return;

Loading…
Cancel
Save