From 31dda2cf4153452fc722290c5a595b13fd447240 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:51:31 +0200 Subject: [PATCH] fix(iot-hub): a kept integration gets the step's metadata entries, one lookup of the packages' own default converters --- .../DefaultDevicePackageUpdateService.java | 27 ++++++ .../service/iot_hub/DeviceUpdateRequest.java | 3 + ...DefaultDevicePackageUpdateServiceTest.java | 51 +++++++++++ .../device-install-dialog.component.ts | 89 ++++++++++--------- .../iot-hub/iot-hub-default-converter.ts | 28 ++++-- ...iot-hub-installed-items-table.component.ts | 11 ++- .../iot-hub/iot-hub-installed-item.models.ts | 2 + 7 files changed, 159 insertions(+), 52 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java index c8dd0e69f8..399e46f6ac 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/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. diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java index c3f2f90f89..b8f31cef32 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/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; } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 2f7e4f57b0..76bad73451 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -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 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); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 195e5e0e3b..f049ee97b8 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/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 | null | undefined): Record { 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 | undefined { + this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + try { + return this.integrationMetadataOf(step); + } finally { + this.formValues = {}; + this.entityOutputs.clear(); + } + } + + private integrationMetadataOf(step: DeviceInstallStep): Record | 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 { + const entries: Record = {}; + 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 { const integration = await firstValueFrom(this.integrationService.getIntegration(existing.id, {ignoreErrors: true})); @@ -2138,7 +2159,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + let ownDefaultConverterIds: Set | 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 = {}; @@ -2442,19 +2470,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 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 { - let pageLink = new PageLink(100); - let page: PageData; - 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 !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 | undefined, formValues: Record): Record { - 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 { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts index 6af1073b93..68aeb0f832 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts +++ b/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> => { + const ids = new Set(); + let pageLink = new PageLink(100); + let page: PageData; + 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; +}; 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 d4cf0d4df0..a99fc65a66 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 @@ -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 { const updates = new Set(); + // Over all installed packages, not only this page's, as the update dialog decides + let ownDefaultConverterIds: Set | 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; diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index eb4776d107..882c97f9c5 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -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; // The step takes ThingsBoard's default converter: its install state says so, for the update check defaultConverter?: boolean; }