Browse Source

fix(iot-hub): a kept integration gets the step's metadata entries, one lookup of the packages' own default converters

pull/16466/head
dpinkevych 1 month ago
parent
commit
31dda2cf41
Failed to extract signature
  1. 27
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  2. 3
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  3. 51
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  4. 89
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  5. 28
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  6. 11
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  7. 2
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

27
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

@ -587,6 +587,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
existing(tenantId, current, step);
if (mergeMetadata(current, step.getMetadata())) {
Integration result = integrationService.saveIntegration(current);
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result));
}
return new StepResult(id, integrationOutput(current), null, null);
}
Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
@ -607,6 +611,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result));
}
/** Merges the step's metadata entries into the integration's; true when that changed it. */
private static boolean mergeMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) {
return false;
}
ObjectNode configuration = integration.getConfiguration() != null && integration.getConfiguration().isObject() ?
(ObjectNode) integration.getConfiguration() : JacksonUtil.newObjectNode();
ObjectNode metadata = configuration.get("metadata") instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode();
entries.fields().forEachRemaining(entry -> {
if (entry.getValue() == null || entry.getValue().isNull()) {
metadata.remove(entry.getKey());
} else {
metadata.put(entry.getKey(), entry.getValue().asText());
}
});
if (metadata.equals(configuration.get("metadata")) || (metadata.isEmpty() && configuration.get("metadata") == null)) {
return false;
}
configuration.set("metadata", metadata);
integration.setConfiguration(configuration);
return true;
}
/**
* The overwritten entity keeps its id and its current name (the user may have renamed it). The version the
* user reviewed makes the save fail if someone changed the entity since.

3
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -61,6 +61,9 @@ public class DeviceUpdateRequest {
private JsonNode sharedAttributes;
// The resolution the install state records for it
private String resolution;
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
// integration, e.g. one the package took as it was; null removes an entry
private JsonNode metadata;
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
private boolean defaultConverter;
}

51
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -364,6 +364,57 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
}
@Test
void keptIntegration_getsTheStepsMetadataEntries() {
// Taken as it was at install: other packages' entries stay, the step's are merged, a null one is removed
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", stateOf(integrationId, "use-existing")));
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other").put("profile.milesight-iot-am308", "AM308"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setResolution("use-existing");
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge");
entries.putNull("profile.milesight-iot-am308");
step.setMetadata(entries);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.get("profile.other-model").asText()).isEqualTo("Other");
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText())
.isEqualTo("use-existing");
}
@Test
void keptIntegrationWithTheEntriesItHas_isNotSaved() {
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any());
}
@Test
void twoStepsWithOneKey_areRejected() {
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);

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

@ -18,8 +18,7 @@ import {
DeviceInstalledItemDescriptor,
DevicePackageEntityState,
DeviceUpdateResult,
DeviceUpdateStep,
IotHubInstalledItem
DeviceUpdateStep
} from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DeviceProfileService } from '@core/http/device-profile.service';
@ -40,8 +39,7 @@ import { ResourcesService } from '@core/services/resources.service';
import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { IntegrationType } from '@shared/models/integration.models';
import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter';
import { PageData } from '@shared/models/page/page-data';
import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter';
import {
cleanFormFieldValue,
DeviceInstallStep,
@ -1843,13 +1841,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
*/
private withStepMetadata(step: DeviceInstallStep, metadata: Record<string, string> | null | undefined): Record<string, string> {
const merged = { ...(metadata ?? {}) };
for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) {
const key = this.resolveVariables(rawKey);
const value = this.resolveVariables(String(rawValue ?? ''));
if (!value || value.includes('${')) {
continue;
}
if (value === key.substring(key.indexOf('.') + 1)) {
for (const [key, value] of Object.entries(this.stepMetadataEntries(step))) {
if (value === null) {
delete merged[key];
} else {
merged[key] = value;
@ -1858,6 +1851,34 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return merged;
}
/** The metadata entries resolved with the form values the package was installed with, as the text-only update has no forms. */
private metadataWithInstalledValues(step: DeviceInstallStep): Record<string, string | null> | undefined {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
try {
return this.integrationMetadataOf(step);
} finally {
this.formValues = {};
this.entityOutputs.clear();
}
}
private integrationMetadataOf(step: DeviceInstallStep): Record<string, string | null> | undefined {
return step.type === InstallStepType.INTEGRATION && step.metadata ? this.stepMetadataEntries(step) : undefined;
}
/** The INTEGRATION step's metadata entries, resolved: null for a self-mapping, whose earlier value is removed. */
private stepMetadataEntries(step: DeviceInstallStep): Record<string, string | null> {
const entries: Record<string, string | null> = {};
for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) {
const key = this.resolveVariables(rawKey);
const value = this.resolveVariables(String(rawValue ?? ''));
if (value && !value.includes('${')) {
entries[key] = value === key.substring(key.indexOf('.') + 1) ? null : value;
}
}
return entries;
}
/** An integration taken as it is still gets the step's metadata: the package's converter reads it. */
private async addStepMetadata(step: DeviceInstallStep, existing: EntityStepOutput): Promise<EntityStepOutput> {
const integration = await firstValueFrom(this.integrationService.getIntegration(existing.id, {ignoreErrors: true}));
@ -2138,7 +2159,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
type: step.type,
action: 'KEEP',
resolution: plan.previous?.resolution ?? plan.resolution ?? 'created',
defaultConverter: step.default || undefined
defaultConverter: step.default || undefined,
// A kept integration, e.g. one the package took as it was, gets them merged by the server: the converter reads them
metadata: this.integrationMetadataOf(step)
};
if (step.type === InstallStepType.GATEWAY_CONNECTOR) {
return plan.action === 'keep' ? base : { ...base, action: 'OVERWRITE', entity: this.resolveTemplateJson(this.zipFiles.get(step.template)) };
@ -2288,13 +2311,17 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
*/
private async checkDefaultConverters(): Promise<void> {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
let ownDefaultConverterIds: Set<string> | undefined;
try {
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
const stored = step.default ? this.storedStateOf(step)?.state : undefined;
let id: string = stored?.entityOutput?.id;
// A converter taken as it was may be any converter with that name: only another package's default one is checked
if (id && stored.resolution === 'use-existing' && !(await this.isInstalledDefaultConverter(id))) {
id = undefined;
if (id && stored.resolution === 'use-existing') {
ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService);
if (!ownDefaultConverterIds.has(id)) {
id = undefined;
}
}
const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true})).catch(() => null) : null;
if (converter) {
@ -2361,7 +2388,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return false;
}
steps.push({ name: step.name, id: step.id, type: step.type, action: 'KEEP', entityId: stored?.entityOutput?.id,
resolution: stored?.resolution ?? 'created', confirmed: true, defaultConverter: step.default || undefined });
resolution: stored?.resolution ?? 'created', confirmed: true, defaultConverter: step.default || undefined,
metadata: this.metadataWithInstalledValues(step) });
}
// Under the new version's keys, as the wizard would store them
const formState: Record<string, any> = {};
@ -2442,19 +2470,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return new Set(fields.map(field => field.key).filter(key => !previousKeys.has(key)));
}
/** True when a device package installed the converter itself, as its default converter. */
private async isInstalledDefaultConverter(id: string): Promise<boolean> {
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(this.iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
if (page.data.some(item => isOwnDefaultConverter(item, id))) {
return true;
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
return false;
}
/**
* Update: true when the entity is one the installed package owns: it created it, not the user chose to use it as it was.
@ -2508,24 +2524,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return files.some(file => !isEqual(
this.resolvePackageFile(this.zipFiles, step[file], this.formValues),
this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues)
)) || !isEqual(
// An INTEGRATION step's metadata entries, which the package's converter reads, are written when it is overwritten
this.resolveStepMetadata(step.metadata, this.formValues),
this.resolveStepMetadata(previousStep.metadata, previousFormValues)
);
));
}
/** The metadata entries of a step, resolved with the given form values. */
private resolveStepMetadata(metadata: Record<string, any> | undefined, formValues: Record<string, any>): Record<string, string> {
const committedValues = this.formValues;
this.formValues = formValues;
try {
return Object.fromEntries(Object.entries(metadata ?? {})
.map(([key, value]) => [this.resolveVariables(key), this.resolveVariables(String(value ?? ''))]));
} finally {
this.formValues = committedValues;
}
}
/** Update: the form values the installed version was installed with. */
private previousFormValues(): Record<string, any> {

28
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -7,6 +7,9 @@ import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data';
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json';
@ -58,9 +61,24 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert
};
/**
* True when the device package installed the converter itself as its default converter, not one it took as it was:
* only such a converter is ThingsBoard's default one, which a new ThingsBoard version may change.
* The converters device packages installed themselves as their default converter, not ones they took as they were, of
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version
* may change. The installed items table and the update dialog both decide by it.
*/
export const isOwnDefaultConverter = (item: IotHubInstalledItem, converterId: string): boolean =>
item.itemType === 'DEVICE' && Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})
.some(state => state?.defaultConverter && state.entityOutput?.id === converterId && state.resolution !== 'use-existing');
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => {
const ids = new Set<string>();
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
for (const item of page.data) {
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) {
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') {
ids.add(state.entityOutput.id);
}
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
return ids;
};

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

@ -38,7 +38,7 @@ import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { ConverterService } from '@core/http/converter.service';
import { ResourcesService } from '@core/services/resources.service';
import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter';
import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter';
import { firstValueFrom } from 'rxjs';
@Component({
@ -278,13 +278,18 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
*/
private async checkConverterUpdates(): Promise<void> {
const updates = new Set<string>();
// Over all installed packages, not only this page's, as the update dialog decides
let ownDefaultConverterIds: Set<string> | undefined;
for (const item of this.dataSource) {
const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : [];
for (const state of states) {
let id: string = state?.defaultConverter ? state.entityOutput?.id : undefined;
// A converter taken as it was counts only when a package installed it as its default converter
if (id && state.resolution === 'use-existing' && !this.dataSource.some(other => isOwnDefaultConverter(other, id))) {
id = undefined;
if (id && state.resolution === 'use-existing') {
ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService);
if (!ownDefaultConverterIds.has(id)) {
id = undefined;
}
}
const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true}))
.catch(() => null) : null;

2
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -64,6 +64,8 @@ export interface DeviceUpdateStep {
resolution?: string;
// The package step's id, which keys its install state; the name when not set
id?: string;
// INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry
metadata?: Record<string, string | null>;
// The step takes ThingsBoard's default converter: its install state says so, for the update check
defaultConverter?: boolean;
}

Loading…
Cancel
Save