From d53982905a1f2e2a4c76274e3e9af2bb5543092b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 12:58:29 +0200 Subject: [PATCH 01/24] fix(iot-hub): update a device package in place instead of deleting its entities Updating an installed device package deleted everything the package created, the device included, so its telemetry and attributes were lost, and nothing was installed again. Now the update opens the install wizard of the new version over the installed package. It keeps the install method and the form values, finds the entities by the ids in the install state (so a renamed profile is still found), keeps the device and gateway as they are (id, credentials, history) and overwrites the device profile, converters, integration, dashboard and rule chain with the new templates under their current names. The installed item then takes the new version through registerDeviceUpdate. The server no longer updates a device package by itself. PROD-9096 --- .../server/controller/IotHubController.java | 4 + .../service/iot_hub/DefaultIotHubService.java | 45 ++++- .../server/service/iot_hub/IotHubService.java | 2 + .../iot_hub/DefaultIotHubServiceTest.java | 55 ++++++ .../src/app/core/http/iot-hub-api.service.ts | 7 +- .../device-install-dialog.component.ts | 166 +++++++++++++++--- .../iot-hub/iot-hub-actions.service.ts | 20 ++- 7 files changed, 265 insertions(+), 34 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 1645505c00..e5388bd28b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -92,9 +92,13 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, + @RequestParam(required = false) UUID installedItemId, @RequestBody JsonNode body) throws ThingsboardException { checkAllPermissions(); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); + if (installedItemId != null) { + return iotHubService.registerDeviceUpdate(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, descriptor); + } return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index a3cf0599fa..6f0f9db86f 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -416,6 +416,10 @@ public class DefaultIotHubService implements IotHubService { } String itemType = installedItem.getItemType(); + if ("DEVICE".equals(itemType)) { + // The install wizard of the new version changes the package's entities in place, see registerDeviceUpdate + throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); + } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); // Skip checksum validation for solution templates @@ -460,12 +464,6 @@ public class DefaultIotHubService implements IotHubService { case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData); case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData); case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); - case "DEVICE" -> { - DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor; - deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); - dd.setCreatedEntityIds(null); - dd.setDashboardId(null); - } case "SOLUTION_TEMPLATE" -> { SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor; solutionService.deleteSolution(tenantId, stDescriptor, user); @@ -710,6 +708,41 @@ public class DefaultIotHubService implements IotHubService { } } + @Override + public InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, + DeviceInstalledItemDescriptor descriptor) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Registering device package update of {} to version: {}", tenantId, installedItemId, versionId); + + try { + IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); + if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())) { + throw new IllegalArgumentException("Installed device package not found"); + } + + JsonNode versionInfo = iotHubRestClient.getVersionInfo(versionId); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + if (!installedItem.getItemId().toString().equals(versionInfo.get("itemId").asText())) { + throw new IllegalArgumentException("The version belongs to another item"); + } + + // The wizard has already changed the entities in place: a failure here must not delete them + installedItem.setItemVersionId(UUID.fromString(versionId)); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(descriptor); + iotHubInstalledItemService.save(tenantId, installedItem); + log.info("[{}] Registered device package update: {} (version {})", tenantId, installedItem.getItemName(), installedItem.getVersion()); + + return InstallItemVersionResult.success(descriptor); + } catch (Exception e) { + log.error("[{}] Failed to register device package update of {} to version: {}", tenantId, installedItemId, versionId, e); + return InstallItemVersionResult.error(e.getMessage()); + } + } + /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index e1d0cd666b..3a3fd372b0 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -19,6 +19,8 @@ public interface IotHubService { InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor); + InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, DeviceInstalledItemDescriptor descriptor); + void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 0f0068872c..cf4f25bfd7 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -495,6 +495,61 @@ class DefaultIotHubServiceTest { assertThat(kept.getUsedByItemsCount()).isZero(); } + @Test + void updateItemVersion_devicePackage_deletesNothing() { + mockTenant(); + IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID()), new DashboardId(UUID.randomUUID())); + installed.setItemType("DEVICE"); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + + UpdateItemVersionResult result = service.updateItemVersion(user, installed.getId(), UUID.randomUUID().toString(), true, null); + + assertThat(result.isSuccess()).isFalse(); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void registerDeviceUpdate_keepsTheInstalledItemAndRecordsTheNewVersion() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem installed = devicePackage(deviceId); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + installed.setVersion("1.0"); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, installed.getItemId().toString(), "DEVICE", "AM308", "1.1")); + DeviceInstalledItemDescriptor updated = new DeviceInstalledItemDescriptor(); + updated.setCreatedEntityIds(List.of(deviceId)); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, updated); + + assertThat(result.isSuccess()).isTrue(); + verify(iotHubInstalledItemService).save(tenantId, installed); + assertThat(installed.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(installed.getVersion()).isEqualTo("1.1"); + assertThat(installed.getDescriptor()).isSameAs(updated); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + } + + @Test + void registerDeviceUpdate_versionOfAnotherItem_isRejected() { + mockTenant(); + IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID())); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Other", "1.0")); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, new DeviceInstalledItemDescriptor()); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 49da0f4e6a..639127e075 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -180,10 +180,13 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig + config?: IotHubRequestConfig, + // Set for an update: the installed item takes the version and the descriptor + installedItemId?: string ): Observable { + const installedItemParam = installedItemId ? `&installedItemId=${installedItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, + `/api/iot-hub/device/register?versionId=${versionId}${installedItemParam}`, { type: 'DEVICE', ...descriptor }, { params: this.buildParams(config) } ); 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 0f2a99df36..ea37b3bbe5 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 @@ -14,6 +14,7 @@ import { firstValueFrom, Subscription } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { DeviceInstalledItemDescriptor } 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'; import { DeviceService } from '@core/http/device.service'; @@ -57,6 +58,17 @@ export interface DeviceInstallDialogData { installState?: Record; entityGroupId?: string; customerId?: string; + // Set when the wizard updates an installed package to the item version + update?: DeviceInstallUpdate; +} + +/** + * The installed package an update changes. The steps of the new version change the entities + * the package created in place, so the device keeps its id, credentials and history. + */ +export interface DeviceInstallUpdate { + installedItemId: string; + descriptor: DeviceInstalledItemDescriptor; } export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress'; @@ -318,6 +330,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field); ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; - // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; + // In review mode, use stored values; an update starts from the values of the installed version; otherwise use defaults + const storedState = this.reviewMode ? this.data.installState : this.data.update?.descriptor.installState; + const storedValues = storedState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -1250,17 +1259,26 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + /** keepName: the entity keeps its current name instead of the template's, e.g. a device profile the user renamed. */ + private async overwriteEntity(step: DeviceInstallStep, existing: EntityStepOutput, keepName = false): Promise { const raw = this.zipFiles.get(step.template); if (!raw) throw new Error(`Template file not found: ${step.template}`); // Overwriting an existing integration reuses its routingKey, so resolve @@ -1563,6 +1583,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (step.type !== InstallStepType.DEVICE && step.type !== InstallStepType.GATEWAY) { + return existing; + } + const creds = await firstValueFrom(this.deviceService.getDeviceCredentials(existing.id, false, {ignoreErrors: true})); + const output: EntityStepOutput = { ...existing, token: creds.credentialsId }; + if (step.type === InstallStepType.GATEWAY) { + output.dockerComposeUrl = `/api/device-connectivity/gateway-launch/${output.id}/docker-compose/download`; + // As createEntity does: the docker-compose template resolves ${gateway.token} + this.entityOutputs.set('gateway', output); + if (step.dockerCompose) { + const dcRaw = this.zipFiles.get(step.dockerCompose); + if (dcRaw) this.gatewayDockerComposeContent = this.resolveVariables(dcRaw); + } + } + return output; + } + + /** + * Update: the entity the installed version created for this step. It is found by the id kept in + * the install state, not by name, so an entity the user renamed is still found. Null when this + * is not an update, when the installed version had no such step, or when the entity was deleted since. + */ + private async findPreviousEntity(step: DeviceInstallStep): Promise { + const installState = this.data.update?.descriptor.installState; + // A connector lives in the gateway's attributes: its step runs again over the same gateway + if (!installState || step.type === InstallStepType.GATEWAY_CONNECTOR) { + return null; + } + const id: string = (installState[step.name] || installState[this.resolveVariables(step.name)])?.entityOutput?.id; + if (!id) { + return null; + } + const config = {ignoreErrors: true}; + try { + switch (step.type) { + case InstallStepType.DEVICE_PROFILE: { + const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); + return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; + } + case InstallStepType.DEVICE: { + const device = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: device.name, url: `/entities/devices/all/${id}` }; + } + case InstallStepType.GATEWAY: { + const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: gateway.name, url: '/entities/gateways' }; + } + case InstallStepType.DASHBOARD: { + const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); + return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; + } + case InstallStepType.RULE_CHAIN: { + const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); + return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; + } + case InstallStepType.UPLINK_CONVERTER: + case InstallStepType.DOWNLINK_CONVERTER: { + const converter = await firstValueFrom(this.converterService.getConverter(id, config)); + const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; + return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; + } + case InstallStepType.INTEGRATION: { + const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); + return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; + } + default: + return null; + } + } catch (_e) { + // Deleted since: the step creates it again + return null; + } + } + + /** + * Update: a device or gateway is kept as it is, so its credentials, which the firmware uses, don't change. + * Other entities take the new version's template and keep their id and current name. + */ + private updatePreviousEntity(step: DeviceInstallStep, previous: EntityStepOutput): Promise { + if (step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + return this.useExistingEntity(step, previous); + } + return this.overwriteEntity(step, previous, true); + } + private async preCheckEntity(step: DeviceInstallStep): Promise { const raw = this.zipFiles.get(step.template); if (!raw) return null; @@ -1711,6 +1822,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousId.id)) { + ids.push(previousId); + } + } return ids; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index b04932040d..fb5c9125d0 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -17,7 +17,7 @@ import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubIt import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component'; import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component'; import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component'; -import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; +import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallUpdate } from './device-install-dialog/device-install-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; import { IotHubBuiltInService } from './iot-hub-built-in.service'; import { isBuiltInItem } from './iot-hub-utils'; @@ -150,6 +150,9 @@ export class IotHubActionsService { if (!installedItem) { return of(false); } + if (installedItem.itemType === ItemType.DEVICE) { + return this.updateDevice(installedItem, versionId); + } return this.dialog.open(TbIotHubUpdateDialogComponent, { panelClass: ['tb-dialog'], disableClose: true, @@ -199,9 +202,22 @@ export class IotHubActionsService { }); } + /** + * A device package is updated by the install wizard of the new version: its steps change what + * the package created in place, so the device and its history stay. + */ + private updateDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + return this.iotHubApiService.getVersionInfo(versionId).pipe( + switchMap(item => this.openDeviceInstallDialog(item, { + update: { installedItemId: installedItem.id.id, descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor } + })), + map(result => result === 'installed' ? 'updated' : result) + ); + } + private openDeviceInstallDialog(item: MpItemVersionView, options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; - entityGroupId?: string; customerId?: string}): Observable { + entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], disableClose: true, From 12deaf57287f78cadc2ac47aed9a5a523a7d66e3 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 13:41:41 +0200 Subject: [PATCH 02/24] fix(iot-hub): keep what the user chose at install when updating a device package - An entity the user took with "Use existing" at install is kept as it is on update instead of being overwritten with the package's template. - Only a 404 counts as "deleted since"; any other failure to load a previous entity fails the step, so a transient error can't create a second device with new credentials. - A rejected update registration (success=false) is shown on the step and can be retried instead of closing as updated. - An overwritten dashboard keeps its owner. - Ids of entities deleted since are no longer re-tracked. - The transport fields take the current Device connectivity settings. - A version without a dashboard step keeps the installed dashboardId. - A failed version lookup on update no longer errors unhandled. PROD-9096 --- .../device-install-dialog.component.ts | 141 +++++++++++------- .../iot-hub/iot-hub-actions.service.ts | 4 +- 2 files changed, 93 insertions(+), 52 deletions(-) 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 ea37b3bbe5..3daae22f31 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 @@ -66,6 +66,12 @@ export interface DeviceInstallDialogData { * The installed package an update changes. The steps of the new version change the entities * the package created in place, so the device keeps its id, credentials and history. */ +/** Update: an entity the installed version has for a step, and whether the user kept it as it was at install. */ +interface PreviousEntity { + output: EntityStepOutput; + useExisting: boolean; +} + export interface DeviceInstallUpdate { installedItemId: string; descriptor: DeviceInstalledItemDescriptor; @@ -236,6 +242,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); // Variable resolution state formValues: Record = {}; @@ -1093,8 +1101,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field); ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; - // In review mode, use stored values; an update starts from the values of the installed version; otherwise use defaults - const storedState = this.reviewMode ? this.data.installState : this.data.update?.descriptor.installState; + // In review mode, use stored values; an update starts from the values of the installed version, + // except the transport fields, which take the current Device connectivity settings; otherwise use defaults + const storedState = this.reviewMode ? this.data.installState : + ws.stateKey !== TRANSPORT_STEP_STATE_KEY ? this.data.update?.descriptor.installState : undefined; const storedValues = storedState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); @@ -1265,7 +1275,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousDashboardId) ? { entityType: 'DASHBOARD', id: previousDashboardId } : undefined); + const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, { createdEntityIds, dashboardId, selectedInstallMethod: this.selectedInstallMethod, installState: this.buildInstallState() }, @@ -1310,10 +1324,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + private async findPreviousEntity(step: DeviceInstallStep): Promise { const installState = this.data.update?.descriptor.installState; // A connector lives in the gateway's attributes: its step runs again over the same gateway if (!installState || step.type === InstallStepType.GATEWAY_CONNECTOR) { return null; } - const id: string = (installState[step.name] || installState[this.resolveVariables(step.name)])?.entityOutput?.id; + const stored = installState[step.name] || installState[this.resolveVariables(step.name)]; + const id: string = stored?.entityOutput?.id; if (!id) { return null; } - const config = {ignoreErrors: true}; try { - switch (step.type) { - case InstallStepType.DEVICE_PROFILE: { - const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); - return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; - } - case InstallStepType.DEVICE: { - const device = await firstValueFrom(this.deviceService.getDevice(id, config)); - return { id, name: device.name, url: `/entities/devices/all/${id}` }; - } - case InstallStepType.GATEWAY: { - const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); - return { id, name: gateway.name, url: '/entities/gateways' }; - } - case InstallStepType.DASHBOARD: { - const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); - return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; - } - case InstallStepType.RULE_CHAIN: { - const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); - return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; - } - case InstallStepType.UPLINK_CONVERTER: - case InstallStepType.DOWNLINK_CONVERTER: { - const converter = await firstValueFrom(this.converterService.getConverter(id, config)); - const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; - return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; - } - case InstallStepType.INTEGRATION: { - const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); - return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; - } - default: - return null; + const output = await this.loadPreviousEntity(step, id); + // The user chose to keep an entity they already had: the update doesn't overwrite it either + return output ? { output, useExisting: stored.resolution === 'use-existing' } : null; + } catch (e: any) { + if (e?.status === 404) { + // Deleted since: the step creates it again, and the package no longer tracks the old id + this.deletedPreviousIds.add(id); + return null; } - } catch (_e) { - // Deleted since: the step creates it again - return null; + throw e; + } + } + + private async loadPreviousEntity(step: DeviceInstallStep, id: string): Promise { + const config = {ignoreErrors: true}; + switch (step.type) { + case InstallStepType.DEVICE_PROFILE: { + const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); + return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; + } + case InstallStepType.DEVICE: { + const device = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: device.name, url: `/entities/devices/all/${id}` }; + } + case InstallStepType.GATEWAY: { + const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: gateway.name, url: '/entities/gateways' }; + } + case InstallStepType.DASHBOARD: { + const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); + return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; + } + case InstallStepType.RULE_CHAIN: { + const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); + return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; + } + case InstallStepType.UPLINK_CONVERTER: + case InstallStepType.DOWNLINK_CONVERTER: { + const converter = await firstValueFrom(this.converterService.getConverter(id, config)); + const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; + return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; + } + case InstallStepType.INTEGRATION: { + const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); + return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; + } + default: + return null; } } @@ -1753,11 +1792,11 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { - return this.useExistingEntity(step, previous); + private updatePreviousEntity(step: DeviceInstallStep, previous: PreviousEntity): Promise { + if (previous.useExisting || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + return this.useExistingEntity(step, previous.output); } - return this.overwriteEntity(step, previous, true); + return this.overwriteEntity(step, previous.output, true); } private async preCheckEntity(step: DeviceInstallStep): Promise { @@ -1825,7 +1864,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousId.id)) { + if (!this.deletedPreviousIds.has(previousId.id) && !ids.some(id => id.id === previousId.id)) { ids.push(previousId); } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index fb5c9125d0..4c6fa566e8 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -211,7 +211,9 @@ export class IotHubActionsService { switchMap(item => this.openDeviceInstallDialog(item, { update: { installedItemId: installedItem.id.id, descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor } })), - map(result => result === 'installed' ? 'updated' : result) + map(result => result === 'installed' ? 'updated' : result), + // The request has already shown the error + catchError(() => of(false)) ); } From 7351515978fee4a807bcc52907c472ef25496a56 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 14:03:06 +0200 Subject: [PATCH 03/24] fix(iot-hub): keep entities other packages use and report a failed registration on device update - Entities other installed device packages use are kept as they are on update, as deleting the package already does, instead of being overwritten with this package's templates. - A version without a dashboard step keeps the installed dashboard only if it still exists; a deleted one is no longer tracked. - On update, Close reports the update as done only once the new version is registered. - A kept integration keeps httpEndpoint and baseUrl for the instructions. - The gateway output and docker-compose resolution are in one helper. PROD-9096 --- .../device-install-dialog.component.ts | 116 ++++++++++++------ 1 file changed, 79 insertions(+), 37 deletions(-) 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 3daae22f31..c400003c26 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 @@ -62,16 +62,19 @@ export interface DeviceInstallDialogData { update?: DeviceInstallUpdate; } -/** - * The installed package an update changes. The steps of the new version change the entities - * the package created in place, so the device keeps its id, credentials and history. - */ -/** Update: an entity the installed version has for a step, and whether the user kept it as it was at install. */ +/** Update: an entity the installed version has for a step. */ interface PreviousEntity { output: EntityStepOutput; - useExisting: boolean; + // Taken as it is instead of overwritten: the user kept it at install, or another installed package uses it + keepAsIs: boolean; + // What the install state records for it, so that the next update decides again + resolution: string; } +/** + * The installed package an update changes. The steps of the new version change the entities + * the package created in place, so the device keeps its id, credentials and history. + */ export interface DeviceInstallUpdate { installedItemId: string; descriptor: DeviceInstalledItemDescriptor; @@ -244,6 +247,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + // Update: ids of the package's entities that other installed device packages use, loaded once + private sharedEntityIds: Promise> | null = null; // Variable resolution state formValues: Record = {}; @@ -666,7 +671,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousDashboardId) ? { entityType: 'DASHBOARD', id: previousDashboardId } : undefined); const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, @@ -1390,15 +1392,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent> { + if (!this.sharedEntityIds) { + this.sharedEntityIds = firstValueFrom( + this.iotHubApiService.getInstalledItemKeptEntities(this.data.update.installedItemId, {ignoreLoading: true}) + ).then(kept => new Set(kept.entities.map(e => e.entityId.id))); + // A failed request is asked again on retry instead of being remembered + this.sharedEntityIds.catch(() => this.sharedEntityIds = null); + } + return this.sharedEntityIds; + } + private async loadPreviousEntity(step: DeviceInstallStep, id: string): Promise { const config = {ignoreErrors: true}; switch (step.type) { @@ -1780,8 +1801,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (previous.useExisting || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + if (previous.keepAsIs || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { return this.useExistingEntity(step, previous.output); } return this.overwriteEntity(step, previous.output, true); @@ -1871,6 +1892,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const previousDashboardId = this.data.update?.descriptor.dashboardId?.id; + if (!previousDashboardId || this.deletedPreviousIds.has(previousDashboardId)) { + return undefined; + } + try { + await firstValueFrom(this.dashboardService.getDashboardInfo(previousDashboardId, {ignoreErrors: true})); + return { entityType: 'DASHBOARD', id: previousDashboardId }; + } catch (e: any) { + if (e?.status === 404) { + this.deletedPreviousIds.add(previousDashboardId); + return undefined; + } + throw e; + } + } + private findCreatedDashboardId(): { entityType: string; id: string } | undefined { for (const ws of this.wizardSteps) { if (ws.type === 'progress' && ws.entitySteps) { From 15a7222f2567e689a8182f01a368a052a81a4eb1 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 29 Oct 2026 13:51:36 +0200 Subject: [PATCH 04/24] fix(iot-hub): apply a device package update in one transaction on the server The wizard no longer saves the entities itself and reverts them from snapshots on a failure. It plans the update and the server applies it. - POST /api/iot-hub/installedItems/{id}/deviceUpdate takes the entity of each step, resolved from the new version's template, and saves all of them with the new version of the installed item in one transaction. Any failure rolls everything back. The audit log, version control and attributes are written after commit. - The server checks the plan: only the package's entities or confirmed conflicts are overwritten, the device and its credentials never change, and an entity changed since the check fails the update (version). - GET .../deviceUpdate/check reports for each entity whether it still exists, is shared with other packages, or was changed since install, by a checksum the server keeps in the install state at install and on update. Packages installed before keep the comparison with the template. - An entity changed since install is overwritten only after a warning, with a link to download its current version. A shared one shows the shared warning. - Only texts changed: the version is recorded without the wizard. - Try again checks the update again. Errors show validation messages and a common message for anything else. --- .../server/controller/IotHubController.java | 26 +- .../DefaultDevicePackageUpdateService.java | 789 +++++++++++++++++ .../service/iot_hub/DefaultIotHubService.java | 40 +- .../iot_hub/DevicePackageEntities.java | 119 +++ .../iot_hub/DevicePackageEntityState.java | 27 + .../iot_hub/DevicePackageUpdateService.java | 19 + .../service/iot_hub/DeviceUpdateRequest.java | 61 ++ .../service/iot_hub/DeviceUpdateResult.java | 37 + .../service/iot_hub/EntityChecksum.java | 110 +++ .../server/service/iot_hub/IotHubService.java | 2 - ...DefaultDevicePackageUpdateServiceTest.java | 376 ++++++++ .../iot_hub/DefaultIotHubServiceTest.java | 40 - .../src/app/core/http/iot-hub-api.service.ts | 26 +- .../device-install-dialog.component.html | 186 +++- .../device-install-dialog.component.scss | 84 ++ .../device-install-dialog.component.ts | 808 +++++++++++++++--- .../iot-hub/iot-hub-actions.service.ts | 10 +- .../models/iot-hub/device-package.models.ts | 3 +- .../iot-hub/iot-hub-installed-item.models.ts | 43 + .../assets/locale/locale.constant-en_US.json | 14 + 20 files changed, 2591 insertions(+), 229 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java create mode 100644 application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index e5388bd28b..b6d01d3342 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -38,6 +38,10 @@ import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; +import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; +import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; +import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; +import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; @@ -54,6 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService; public class IotHubController extends BaseController { private final IotHubService iotHubService; + private final DevicePackageUpdateService devicePackageUpdateService; private final IotHubInstalledItemService iotHubInstalledItemService; private final DeviceConnectivityService deviceConnectivityService; private final SystemSecurityService systemSecurityService; @@ -92,16 +97,29 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, - @RequestParam(required = false) UUID installedItemId, @RequestBody JsonNode body) throws ThingsboardException { checkAllPermissions(); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); - if (installedItemId != null) { - return iotHubService.registerDeviceUpdate(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, descriptor); - } return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") + @ResponseBody + public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { + checkAllPermissions(); + return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); + } + + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/installedItems/{installedItemId}/deviceUpdate") + @ResponseBody + public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, + @RequestBody DeviceUpdateRequest request) throws ThingsboardException { + checkAllPermissions(); + return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/installedItems/{installedItemId}/update/{versionId}") @ResponseBody 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 new file mode 100644 index 0000000000..1e6d3f776d --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java @@ -0,0 +1,789 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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 com.fasterxml.jackson.databind.node.TextNode; +import com.google.gson.JsonParser; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.AttributesSaveRequest; +import org.thingsboard.server.common.adaptor.JsonConverter; +import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.HasTenantId; +import org.thingsboard.server.common.data.HasVersion; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.converter.Converter; +import org.thingsboard.server.common.data.converter.ConverterType; +import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.common.data.security.DeviceCredentials; +import org.thingsboard.server.common.data.security.DeviceCredentialsType; +import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceCredentialsService; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.integration.IntegrationService; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.dao.rule.RuleChainService; +import org.thingsboard.server.dao.secret.SecretConfigurationService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.exception.EntitiesLimitExceededException; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; +import org.thingsboard.server.service.integration.IntegrationManagerService; +import org.thingsboard.server.service.rule.TbRuleChainService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Applies an update of an installed device package in one transaction. The install wizard resolves the templates + * of the new version (the same way it installs them) and sends the entity of each step; this service checks the + * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a + * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a + * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, + * are written after commit too. + */ +@Service +@TbCoreComponent +@Slf4j +@RequiredArgsConstructor +public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { + + // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} + private static final Map STEP_ALIASES = Map.of( + "DEVICE_PROFILE", "deviceProfile", + "DEVICE", "device", + "GATEWAY", "gateway", + "DASHBOARD", "dashboard", + "RULE_CHAIN", "ruleChain", + "UPLINK_CONVERTER", "uplinkConverter", + "DOWNLINK_CONVERTER", "downlinkConverter", + "INTEGRATION", "integration"); + private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); + private static final int INTEGRATION_VALIDATION_TIMEOUT_SEC = 20; + private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + + private final IotHubInstalledItemService installedItemService; + private final IotHubRestClient iotHubRestClient; + private final IotHubService iotHubService; + private final DevicePackageEntities packageEntities; + private final DeviceProfileService deviceProfileService; + private final DeviceService deviceService; + private final DeviceCredentialsService deviceCredentialsService; + private final DashboardService dashboardService; + private final RuleChainService ruleChainService; + private final TbRuleChainService tbRuleChainService; + private final ConverterService converterService; + private final IntegrationService integrationService; + private final IntegrationManagerService integrationManagerService; + private final SecretConfigurationService secretConfigurationService; + private final AttributesService attributesService; + private final TelemetrySubscriptionService telemetryService; + private final TransactionTemplate transactionTemplate; + + @Override + public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { + TenantId tenantId = user.getTenantId(); + DeviceInstalledItemDescriptor descriptor = findDevicePackage(tenantId, installedItemId).descriptor(); + Set sharedIds = new HashSet<>(); + iotHubService.findKeptEntities(tenantId, installedItemId).getEntities().forEach(e -> sharedIds.add(e.getEntityId().getId())); + Map createdIds = createdIds(descriptor); + + List states = new ArrayList<>(); + if (descriptor.getInstallState() == null) { + return states; + } + descriptor.getInstallState().forEach((stepName, state) -> { + EntityId entityId = DevicePackageEntities.entityIdOf(state, createdIds); + if (entityId == null || !DevicePackageEntities.CHECKSUM_TYPES.contains(entityId.getEntityType())) { + return; + } + DevicePackageEntities.Snapshot snapshot = packageEntities.load(tenantId, entityId); + JsonNode storedChecksum = state.get("checksum"); + Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null : + !storedChecksum.asText().equals(snapshot.checksum()); + states.add(new DevicePackageEntityState(stepName, entityId, snapshot != null, + snapshot != null ? snapshot.version() : null, modified, sharedIds.contains(entityId.getId()))); + }); + return states; + } + + @Override + public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + Applied applied; + try { + DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { + throw new IllegalArgumentException("The version belongs to another item"); + } + validatePlan(devicePackage, request); + validateIntegrations(tenantId, request); + applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + } catch (StepFailure e) { + log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause()); + return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName); + } catch (RestClientException e) { + log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); + return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + } catch (Exception e) { + log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); + return DeviceUpdateResult.error(userMessage(e), null); + } + afterCommit(user, tenantId, applied); + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + } + + private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { + IotHubInstalledItem installedItem = installedItemService.findById(tenantId, installedItemId); + if (installedItem == null || !"DEVICE".equals(installedItem.getItemType()) + || !(installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor)) { + throw new IllegalArgumentException("Installed device package not found"); + } + return new DevicePackage(installedItem, descriptor); + } + + /** + * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * whose credentials the firmware uses, are never changed. + */ + private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + if (request.getSteps() == null || request.getSteps().isEmpty()) { + throw new IllegalArgumentException("The update has no steps"); + } + Set ownedIds = createdIds(devicePackage.descriptor()).keySet(); + for (DeviceUpdateRequest.Step step : request.getSteps()) { + if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { + throw new IllegalArgumentException("Invalid update step: " + step.getName()); + } + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + switch (step.getAction()) { + case KEEP, OVERWRITE -> { + if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { + throw new IllegalArgumentException("No entity for update step: " + step.getName()); + } + boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + && !"GATEWAY_CONNECTOR".equals(step.getType())) { + throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); + } + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + throw new IllegalArgumentException("The device and its credentials don't change on update"); + } + } + case CREATE -> { + } + } + if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + } + } + } + + /** The configuration of an integration is checked by a remote call, so before the transaction. */ + private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { + for (DeviceUpdateRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + continue; + } + ObjectNode body = step.getEntity().deepCopy(); + // Converters this update creates have no id yet; the configuration doesn't depend on them + body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); + Integration integration = JacksonUtil.treeToValue(body, Integration.class); + integration.setTenantId(tenantId); + if (integration.isEdgeTemplate()) { + continue; + } + try { + secretConfigurationService.replaceSecretUsages(tenantId, integration.getConfiguration()); + integrationManagerService.validateIntegrationConfiguration(integration).get(INTEGRATION_VALIDATION_TIMEOUT_SEC, TimeUnit.SECONDS); + } catch (ExecutionException e) { + // What the integration reports, e.g. wrong credentials, is what the user has to fix + Throwable cause = e.getCause() != null ? e.getCause() : e; + throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause)); + } catch (TimeoutException e) { + throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration")); + } + } + } + + private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { + DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + Map aliasOutputs = new HashMap<>(); + Map outputs = new LinkedHashMap<>(); + Map installState = new LinkedHashMap<>(); + if (request.getInstallState() != null) { + request.getInstallState().forEach((key, value) -> { + if (value != null && value.has("formValues")) { + installState.put(key, JacksonUtil.newObjectNode().set("formValues", value.get("formValues"))); + } + }); + } + List stepEntityIds = new ArrayList<>(); + List saved = new ArrayList<>(); + List afterCommitSteps = new ArrayList<>(); + DashboardId dashboardId = null; + + for (DeviceUpdateRequest.Step step : request.getSteps()) { + try { + if ("GATEWAY_CONNECTOR".equals(step.getType())) { + // A connector lives in the gateway's attributes, which aren't transactional: saved after commit + if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + DeviceUpdateRequest.Step resolved = copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs)); + afterCommitSteps.add(resolved); + } + continue; + } + JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; + StepResult result = applyStep(tenantId, step, entity); + ObjectNode output = result.output(); + aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); + outputs.put(step.getName(), output); + ObjectNode state = JacksonUtil.newObjectNode(); + state.set("entityOutput", output); + state.put("resolution", step.getResolution() != null ? step.getResolution() : "created"); + // A kept entity keeps the checksum of what the package left: the current one would take the + // user's changes for the package's, and the next update would overwrite them without a warning + String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getName()) : result.checksum(); + if (checksum != null) { + state.put("checksum", checksum); + } + installState.put(step.getName(), state); + if (!"use-existing".equals(step.getResolution())) { + stepEntityIds.add(result.entityId()); + } + if (result.entityId() instanceof DashboardId id) { + dashboardId = id; + } + if (result.saved() != null) { + saved.add(result.saved()); + } + if (step.getAction() == DeviceUpdateRequest.Action.CREATE && ("DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()))) { + // Its attributes are saved after commit, once the device exists + DeviceUpdateRequest.Step created = copyWithEntity(step, null); + created.setEntityId(result.entityId().getId()); + afterCommitSteps.add(created); + } + } catch (StepFailure e) { + throw e; + } catch (Exception e) { + throw new StepFailure(step.getName(), e); + } + } + + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + // The new version may not offer the method the package was installed with + descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod()); + descriptor.setCreatedEntityIds(createdEntityIds(tenantId, previous, stepEntityIds)); + descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous)); + Map state = new LinkedHashMap<>(installState); + descriptor.setInstallState(state); + + IotHubInstalledItem installedItem = devicePackage.installedItem(); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(descriptor); + installedItemService.save(tenantId, installedItem); + return new Applied(descriptor, outputs, saved, afterCommitSteps, aliasOutputs); + } + + private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + return switch (step.getType()) { + case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); + case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); + case "INTEGRATION" -> saveIntegration(tenantId, step, entity); + default -> throw new IllegalArgumentException("Unsupported step type: " + step.getType()); + }; + } + + private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; + DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); + profile.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(profile, id, current, step); + // The tenant's default profile stays the default one + profile.setDefault(current.isDefault()); + } else { + profile.setId(null); + profile.setVersion(null); + } + DeviceProfile result = deviceProfileService.saveDeviceProfile(profile); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; + Device device; + boolean created = false; + if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + Device template = JacksonUtil.treeToValue(entity, Device.class); + template.setTenantId(tenantId); + template.setId(null); + template.setVersion(null); + device = deviceService.saveDevice(template); + created = true; + } else { + Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; + device = existing(tenantId, current, step); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + // Another device the user chose to overwrite; the package's own device never changes + Device template = JacksonUtil.treeToValue(entity, Device.class); + template.setTenantId(tenantId); + prepareOverwrite(template, id, current, step); + device = deviceService.saveDevice(template); + created = true; + } + } + DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); + if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + credentials = applyCredentials(tenantId, credentials, step.getCredentials()); + } + ObjectNode output = output(device.getId(), device.getName()); + if (credentials != null) { + output.put("token", credentials.getCredentialsId()); + } + if ("GATEWAY".equals(step.getType())) { + output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); + } + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + return new StepResult(device.getId(), output, null, saved); + } + + private DeviceCredentials applyCredentials(TenantId tenantId, DeviceCredentials credentials, JsonNode template) { + JsonNode type = template.get("credentialsType"); + if (type != null && type.isTextual()) { + credentials.setCredentialsType(DeviceCredentialsType.valueOf(type.asText())); + } + JsonNode value = template.get("credentialsValue"); + if (value != null && !value.isNull()) { + credentials.setCredentialsValue(value.isTextual() ? value.asText() : value.toString()); + } + JsonNode credentialsId = template.get("credentialsId"); + if (credentialsId != null && credentialsId.isTextual()) { + credentials.setCredentialsId(credentialsId.asText()); + } + return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); + } + + private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; + Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getTitle()); + } + Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); + dashboard.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(dashboard, id, current, step); + // The dashboard keeps its owner and the customers it is assigned to + if (dashboard.getCustomerId() == null) { + dashboard.setCustomerId(current.getCustomerId()); + } + dashboard.setAssignedCustomers(current.getAssignedCustomers()); + } else { + dashboard.setId(null); + dashboard.setVersion(null); + } + Dashboard result = dashboardService.saveDashboard(dashboard); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); + } + + private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; + RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; + RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); + ruleChain.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(ruleChain, id, current, step); + // A rule chain the tenant made its root one stays the root + ruleChain.setRoot(current.isRoot()); + } else { + ruleChain.setId(null); + ruleChain.setVersion(null); + ruleChain.setRoot(false); + } + RuleChain result = ruleChainService.saveRuleChain(ruleChain); + if (entity.has("metadata") && entity.get("metadata").isObject()) { + RuleChainMetaData metadata = JacksonUtil.treeToValue(entity.get("metadata"), RuleChainMetaData.class); + metadata.setRuleChainId(result.getId()); + metadata.setVersion(result.getVersion()); + if (!ruleChainService.saveRuleChainMetaData(tenantId, metadata, tbRuleChainService::updateRuleNodeConfiguration).isSuccess()) { + throw new IllegalStateException("Failed to save the rule chain metadata"); + } + result = ruleChainService.findRuleChainById(tenantId, result.getId()); + } + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; + Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + Converter converter = JacksonUtil.treeToValue(entity, Converter.class); + converter.setTenantId(tenantId); + converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(converter, id, current, step); + } else { + converter.setId(null); + converter.setVersion(null); + } + Converter result = converterService.saveConverter(converter); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; + Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return new StepResult(id, integrationOutput(current), null, null); + } + Integration integration = JacksonUtil.treeToValue(entity, Integration.class); + integration.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(integration, id, current, step); + // The devices keep sending to the same endpoint + integration.setRoutingKey(current.getRoutingKey()); + } else { + integration.setId(null); + integration.setVersion(null); + if (integration.getRoutingKey() == null) { + integration.setRoutingKey(UUID.randomUUID().toString()); + } + } + Integration result = integrationService.saveIntegration(integration); + return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); + } + + /** + * 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. + */ + private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + switch (entity) { + case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } + case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } + case Dashboard d -> { d.setId((DashboardId) id); d.setTitle(((Dashboard) current).getTitle()); } + case RuleChain r -> { r.setId((RuleChainId) id); r.setName(((RuleChain) current).getName()); } + case Converter c -> { c.setId((ConverterId) id); c.setName(((Converter) current).getName()); } + case Integration i -> { i.setId((IntegrationId) id); i.setName(((Integration) current).getName()); } + default -> throw new IllegalArgumentException("Unsupported entity: " + entity.getClass().getSimpleName()); + } + Long currentVersion = ((HasVersion) current).getVersion(); + if (step.getExpectedVersion() != null && !step.getExpectedVersion().equals(currentVersion)) { + throw new EntityVersionMismatchException(id.getEntityType(), null); + } + ((HasVersion) entity).setVersion(currentVersion); + } + + private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { + throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + } + return current; + } + + private StepResult kept(EntityId id, String name) { + return new StepResult(id, output(id, name), null, null); + } + + private static String previousChecksum(DeviceInstalledItemDescriptor previous, String stepName) { + JsonNode checksum = previous.getInstallState() != null && previous.getInstallState().get(stepName) != null ? + previous.getInstallState().get(stepName).get("checksum") : null; + return checksum != null && checksum.isTextual() ? checksum.asText() : null; + } + + /** + * The checksum is of the entity the save returned: a profile or an integration read back by id inside the + * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with + * its metadata, which isn't cached. + */ + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + } + + private static ObjectNode output(EntityId id, String name) { + ObjectNode output = JacksonUtil.newObjectNode(); + output.put("id", id.getId().toString()); + output.put("name", name); + return output; + } + + /** With what the install instructions resolve: ${integration.routingKey}, ${integration.httpEndpoint}, ${integration.baseUrl}. */ + private static ObjectNode integrationOutput(Integration integration) { + ObjectNode output = output(integration.getId(), integration.getName()); + output.put("routingKey", integration.getRoutingKey()); + JsonNode configuration = integration.getConfiguration() != null ? integration.getConfiguration() : JacksonUtil.newObjectNode(); + JsonNode client = configuration.path("clientConfiguration"); + putText(output, "httpEndpoint", client.path("httpEndpoint"), configuration.path("httpEndpoint")); + putText(output, "baseUrl", client.path("baseUrl"), configuration.path("baseUrl")); + return output; + } + + private static void putText(ObjectNode output, String key, JsonNode first, JsonNode second) { + JsonNode value = first.isTextual() ? first : second; + if (value.isTextual()) { + output.put(key, value.asText()); + } + } + + /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { + if (node == null) { + return null; + } + if (node.isTextual()) { + String text = node.asText(); + Matcher matcher = ENTITY_PLACEHOLDER.matcher(text); + StringBuilder resolved = new StringBuilder(); + boolean changed = false; + while (matcher.find()) { + ObjectNode output = aliasOutputs.get(matcher.group(1)); + JsonNode value = output != null ? output.get(matcher.group(2)) : null; + String replacement = value != null && !value.isNull() ? value.asText() : matcher.group(); + changed |= value != null && !value.isNull(); + matcher.appendReplacement(resolved, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(resolved); + return changed ? TextNode.valueOf(resolved.toString()) : node; + } + if (node.isObject()) { + ObjectNode copy = JacksonUtil.newObjectNode(); + for (Iterator> it = node.fields(); it.hasNext(); ) { + Map.Entry field = it.next(); + copy.set(field.getKey(), resolvePlaceholders(field.getValue(), aliasOutputs)); + } + return copy; + } + if (node.isArray()) { + ArrayNode copy = JacksonUtil.newArrayNode(); + node.forEach(item -> copy.add(resolvePlaceholders(item, aliasOutputs))); + return copy; + } + return node; + } + + /** + * The ids the package tracks: the entities of this version's steps, and those of the installed version this one + * no longer uses, so deleting the package still deletes them. Entities deleted since are dropped. + */ + private List createdEntityIds(TenantId tenantId, DeviceInstalledItemDescriptor previous, List stepEntityIds) { + List ids = new ArrayList<>(stepEntityIds); + Set known = new HashSet<>(); + ids.forEach(id -> known.add(id.getId())); + if (previous.getCreatedEntityIds() != null) { + for (EntityId id : previous.getCreatedEntityIds()) { + if (known.add(id.getId()) && entityService.fetchEntity(tenantId, id).isPresent()) { + ids.add(id); + } + } + } + return ids; + } + + private DashboardId existingDashboard(TenantId tenantId, DeviceInstalledItemDescriptor previous) { + DashboardId id = previous.getDashboardId(); + return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; + } + + /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { + for (SavedEntity saved : applied.saved()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); + if (saved.id().getEntityType() != EntityType.DEVICE) { + autoCommit(user, saved.id()); + } + } catch (Exception e) { + log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + } + } + for (DeviceUpdateRequest.Step step : applied.afterCommitSteps()) { + try { + if ("GATEWAY_CONNECTOR".equals(step.getType())) { + saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); + } else { + DeviceId deviceId = new DeviceId(step.getEntityId()); + saveAttributes(tenantId, deviceId, AttributeScope.SERVER_SCOPE, step.getServerAttributes()); + saveAttributes(tenantId, deviceId, AttributeScope.SHARED_SCOPE, step.getSharedAttributes()); + } + } catch (Exception e) { + log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.getName(), e); + } + } + } + + private void saveConnector(TenantId tenantId, ObjectNode gateway, JsonNode connector) throws Exception { + if (gateway == null || connector == null || !connector.has("name")) { + return; + } + DeviceId gatewayId = new DeviceId(UUID.fromString(gateway.get("id").asText())); + String name = connector.get("name").asText(); + List active = new ArrayList<>(); + for (AttributeKvEntry entry : attributesService.find(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, List.of("active_connectors")).get()) { + JsonNode value = JacksonUtil.toJsonNode(entry.getValueAsString()); + if (value != null && value.isArray()) { + value.forEach(v -> active.add(v.asText())); + } + } + if (!active.contains(name)) { + active.add(name); + } + ObjectNode attributes = JacksonUtil.newObjectNode(); + attributes.set("active_connectors", JacksonUtil.valueToTree(active)); + attributes.set(name, connector); + saveAttributes(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, attributes); + } + + private void saveAttributes(TenantId tenantId, EntityId entityId, AttributeScope scope, JsonNode attributes) { + if (attributes == null || !attributes.isObject() || attributes.isEmpty()) { + return; + } + List entries = JsonConverter.convertToAttributes(JsonParser.parseString(attributes.toString())); + telemetryService.saveAttributes(AttributesSaveRequest.builder() + .tenantId(tenantId) + .entityId(entityId) + .scope(scope) + .entries(entries) + .build()); + } + + /** + * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database + * error, as a common message, with the details in the log. + */ + static String userMessage(Throwable e) { + if (e instanceof EntityVersionMismatchException) { + return "Someone changed it while you were reviewing the update. Check the update again."; + } + if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException) { + return e.getMessage(); + } + if (e instanceof ThingsboardException te && te.getErrorCode() != ThingsboardErrorCode.GENERAL) { + return te.getMessage(); + } + return UNEXPECTED_ERROR; + } + + private static boolean isKnownType(String type) { + return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type)); + } + + private static Map createdIds(DeviceInstalledItemDescriptor descriptor) { + Map ids = new HashMap<>(); + if (descriptor.getCreatedEntityIds() != null) { + descriptor.getCreatedEntityIds().forEach(id -> ids.put(id.getId(), id)); + } + return ids; + } + + private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + if (entity != null) { + copy.setEntity(entity); + } + return copy; + } + + private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { + } + + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { + } + + private record SavedEntity(EntityId id, Object entity, boolean created) { + } + + private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, + List afterCommitSteps, Map aliasOutputs) { + } + + /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ + private static class StepFailure extends RuntimeException { + + private final String stepName; + + StepFailure(String stepName, Throwable cause) { + super(cause.getMessage(), cause); + this.stepName = stepName; + } + + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 6f0f9db86f..dcc569b481 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -133,6 +133,7 @@ public class DefaultIotHubService implements IotHubService { private final ConverterService converterService; private final TbConverterService tbConverterService; private final ProjectInfo projectInfo; + private final DevicePackageEntities devicePackageEntities; // 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. @@ -417,7 +418,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // The install wizard of the new version changes the package's entities in place, see registerDeviceUpdate + // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); @@ -677,6 +678,8 @@ public class DefaultIotHubService implements IotHubService { installedItem.setItemName(itemName); installedItem.setItemType("DEVICE"); installedItem.setVersion(version); + // So that an update can tell whether someone changed an entity since + devicePackageEntities.addChecksums(tenantId, descriptor); installedItem.setDescriptor(descriptor); try { iotHubInstalledItemService.save(tenantId, installedItem); @@ -708,41 +711,6 @@ public class DefaultIotHubService implements IotHubService { } } - @Override - public InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, - DeviceInstalledItemDescriptor descriptor) { - TenantId tenantId = user.getTenantId(); - log.info("[{}] Registering device package update of {} to version: {}", tenantId, installedItemId, versionId); - - try { - IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); - if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())) { - throw new IllegalArgumentException("Installed device package not found"); - } - - JsonNode versionInfo = iotHubRestClient.getVersionInfo(versionId); - if (versionInfo == null) { - throw new IllegalArgumentException("Failed to get version info from IoT Hub"); - } - if (!installedItem.getItemId().toString().equals(versionInfo.get("itemId").asText())) { - throw new IllegalArgumentException("The version belongs to another item"); - } - - // The wizard has already changed the entities in place: a failure here must not delete them - installedItem.setItemVersionId(UUID.fromString(versionId)); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - iotHubInstalledItemService.save(tenantId, installedItem); - log.info("[{}] Registered device package update: {} (version {})", tenantId, installedItem.getItemName(), installedItem.getVersion()); - - return InstallItemVersionResult.success(descriptor); - } catch (Exception e) { - log.error("[{}] Failed to register device package update of {} to version: {}", tenantId, installedItemId, versionId, e); - return InstallItemVersionResult.error(e.getMessage()); - } - } - /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java new file mode 100644 index 0000000000..37cc999822 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasTenantId; +import org.thingsboard.server.common.data.HasVersion; +import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.integration.IntegrationService; +import org.thingsboard.server.dao.rule.RuleChainService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway + * and a gateway connector don't have one: an update never changes them. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class DevicePackageEntities { + + static final Set CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD, + EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION); + + private final DeviceProfileService deviceProfileService; + private final DashboardService dashboardService; + private final RuleChainService ruleChainService; + private final ConverterService converterService; + private final IntegrationService integrationService; + + /** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */ + public Snapshot load(TenantId tenantId, EntityId entityId) { + Object entity = switch (entityId.getEntityType()) { + case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId); + case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId); + case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId); + case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId); + case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId); + default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType()); + }; + if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) { + return null; + } + Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null; + return new Snapshot(entity, metadata); + } + + public String checksum(TenantId tenantId, EntityId entityId) { + Snapshot snapshot = load(tenantId, entityId); + return snapshot != null ? snapshot.checksum() : null; + } + + /** + * Adds the checksum of each entity the install state names, so that an update can tell whether someone changed + * it since. Entities the user kept at install are left out: an update never overwrites them. + */ + public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { + if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) { + return; + } + Map createdIds = new HashMap<>(); + descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id)); + descriptor.getInstallState().forEach((stepName, state) -> { + EntityId entityId = entityIdOf(state, createdIds); + if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) { + String checksum = checksum(tenantId, entityId); + if (checksum != null) { + ((ObjectNode) state).put("checksum", checksum); + } + } + }); + } + + /** The package entity an install-state step recorded, with its type from the ids the package created. */ + static EntityId entityIdOf(JsonNode state, Map createdIds) { + JsonNode id = state != null ? state.path("entityOutput").path("id") : null; + if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) { + return null; + } + try { + return createdIds.get(UUID.fromString(id.asText())); + } catch (IllegalArgumentException e) { + return null; + } + } + + public record Snapshot(Object entity, Object metadata) { + + public Long version() { + return ((HasVersion) entity).getVersion(); + } + + public String checksum() { + return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity); + } + + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java new file mode 100644 index 0000000000..005727da77 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.id.EntityId; + +/** An entity of an installed device package as an update finds it, before it changes anything. */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DevicePackageEntityState { + + private String stepName; + private EntityId entityId; + private boolean exists; + // Sent back with the update, which fails if someone changed the entity in between + private Long version; + // Changed since the package installed or last updated it; null when the install state has no checksum of it + // (installed before checksums were kept) + private Boolean modified; + // Other installed device packages use it, so overwriting it affects them + private boolean shared; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java new file mode 100644 index 0000000000..25a0cdb6ef --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.util.List; + +/** Updates an installed device package to another version of its item. */ +public interface DevicePackageUpdateService { + + /** The package's entities as they are now: whether they still exist, changed since, or are shared. */ + List check(SecurityUser user, IotHubInstalledItemId installedItemId); + + /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ + DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); + +} 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 new file mode 100644 index 0000000000..6e47841e91 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.Data; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * The update of an installed device package as the install wizard planned it: the entity of each install step + * of the new version, already resolved from its template, and what to do with it. The server applies all of it + * in one transaction, together with the new version of the installed item, or nothing. + */ +@Data +public class DeviceUpdateRequest { + + private String versionId; + // The install method of the new version's steps; the installed one when not set + private String selectedInstallMethod; + // The form values of the install state, by step: the server adds the entities to it + private Map installState; + private List steps; + + public enum Action { + // Taken as it is: the new version doesn't change it, or the user kept an entity they had + KEEP, + // Takes the entity from the step + OVERWRITE, + // A new entity: new in this version, deleted since install, or a copy next to one with the same name + CREATE + } + + @Data + public static class Step { + private String name; + // InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN, + // UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION + private String type; + private Action action; + // KEEP and OVERWRITE: the entity + private UUID entityId; + // OVERWRITE: the version the user reviewed; a different one means someone changed the entity since + private Long expectedVersion; + // The user confirmed overwriting an entity of another package or one they didn't install with this package + private boolean confirmed; + // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this + // update creates is left for the server, which knows its id only once it is created. + private JsonNode entity; + // DEVICE and GATEWAY: the credentials template, if any + private JsonNode credentials; + // DEVICE and GATEWAY created by this update: attributes, saved after the transaction + private JsonNode serverAttributes; + private JsonNode sharedAttributes; + // The resolution the install state records for it + private String resolution; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java new file mode 100644 index 0000000000..da73d5de80 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; + +import java.util.Map; + +/** + * Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep + * names the step that failed, if one did. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DeviceUpdateResult { + + private boolean success; + private String errorMessage; + private String failedStep; + private DeviceInstalledItemDescriptor descriptor; + // By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} + private Map outputs; + + public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { + return new DeviceUpdateResult(true, null, null, descriptor, outputs); + } + + public static DeviceUpdateResult error(String errorMessage, String failedStep) { + return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java new file mode 100644 index 0000000000..898a222f05 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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 org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.common.data.rule.RuleNode; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +/** + * The checksum of an entity as the server stores it, kept in the install state of a device package. A different + * checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name, + * which an update keeps, don't count. + */ +final class EntityChecksum { + + private static final Set SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId", + "customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources"); + + private EntityChecksum() { + } + + /** A rule chain is checked with its metadata: pass both. */ + static String of(Object... parts) { + StringBuilder canonical = new StringBuilder(); + for (Object part : parts) { + JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part); + appendCanonical(canonical, node, true); + canonical.append('|'); + } + try { + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(hash); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** + * What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and + * configuration, and the connections. Node ids, layout and debug settings change without the user changing + * what the rule chain does, e.g. when it is saved again. + */ + private static JsonNode ruleChainContent(RuleChainMetaData metadata) { + ObjectNode content = JacksonUtil.newObjectNode(); + ArrayNode nodes = content.putArray("nodes"); + if (metadata.getNodes() != null) { + for (RuleNode node : metadata.getNodes()) { + ObjectNode n = nodes.addObject(); + n.put("type", node.getType()); + n.put("name", node.getName()); + n.set("configuration", node.getConfiguration()); + n.put("singletonMode", node.isSingletonMode()); + n.put("queueName", node.getQueueName()); + } + } + content.set("connections", JacksonUtil.valueToTree(metadata.getConnections())); + content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections())); + content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex())); + return content; + } + + /** JSON with the keys sorted, so the same entity always gives the same text. */ + private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) { + if (node == null || node.isNull() || node.isMissingNode()) { + out.append("null"); + } else if (node.isObject()) { + List keys = new ArrayList<>(); + for (Iterator it = node.fieldNames(); it.hasNext(); ) { + String key = it.next(); + if (!topLevel || !SKIPPED_KEYS.contains(key)) { + keys.add(key); + } + } + keys.sort(null); + out.append('{'); + for (int i = 0; i < keys.size(); i++) { + if (i > 0) { + out.append(','); + } + out.append(JacksonUtil.toString(keys.get(i))).append(':'); + appendCanonical(out, node.get(keys.get(i)), false); + } + out.append('}'); + } else if (node.isArray()) { + out.append('['); + for (int i = 0; i < node.size(); i++) { + if (i > 0) { + out.append(','); + } + appendCanonical(out, node.get(i), false); + } + out.append(']'); + } else { + out.append(node.toString()); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index 3a3fd372b0..e1d0cd666b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -19,8 +19,6 @@ public interface IotHubService { InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor); - InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, DeviceInstalledItemDescriptor descriptor); - void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); 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 new file mode 100644 index 0000000000..736e6c790d --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -0,0 +1,376 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.converter.Converter; +import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; +import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.IotHubInstalledItemId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceCredentialsService; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.integration.IntegrationService; +import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.service.entitiy.TbLogEntityActionService; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DefaultDevicePackageUpdateServiceTest { + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + private final SecurityUser user = mock(SecurityUser.class); + private final UUID itemId = UUID.randomUUID(); + private final String versionId = UUID.randomUUID().toString(); + private final DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); + private final DashboardId dashboardId = new DashboardId(UUID.randomUUID()); + private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); + private final IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); + + @Mock + private IotHubInstalledItemService installedItemService; + @Mock + private IotHubRestClient iotHubRestClient; + @Mock + private DevicePackageEntities packageEntities; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private DashboardService dashboardService; + @Mock + private DeviceService deviceService; + @Mock + private DeviceCredentialsService deviceCredentialsService; + @Mock + private ConverterService converterService; + @Mock + private IntegrationService integrationService; + @Mock + private TransactionTemplate transactionTemplate; + @Mock + private EntityService entityService; + @Mock + private TbLogEntityActionService logEntityActionService; + + @InjectMocks + private DefaultDevicePackageUpdateService service; + + private IotHubInstalledItem installedItem; + // Set when the transaction callback threw, so the transaction would roll back + private final List rolledBack = new ArrayList<>(); + + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(service, "entityService", entityService); + ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); + when(user.getTenantId()).thenReturn(tenantId); + + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setSelectedInstallMethod("INTEGRATION_TTN"); + descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId)); + descriptor.setDashboardId(dashboardId); + descriptor.setInstallState(Map.of()); + installedItem = new IotHubInstalledItem(); + installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID())); + installedItem.setTenantId(tenantId); + installedItem.setItemId(itemId); + installedItem.setItemType("DEVICE"); + installedItem.setVersion("1.0.0"); + installedItem.setDescriptor(descriptor); + when(installedItemService.findById(tenantId, installedItem.getId())).thenReturn(installedItem); + + ObjectNode versionInfo = JacksonUtil.newObjectNode(); + versionInfo.put("itemId", itemId.toString()); + versionInfo.put("name", "AM308"); + versionInfo.put("version", "1.0.1"); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); + + when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + try { + return invocation.>getArgument(0).doInTransaction(null); + } catch (RuntimeException e) { + rolledBack.add(e); + throw e; + } + }); + when(packageEntities.checksum(any(), any())).thenReturn("checksum"); + when(entityService.fetchEntity(any(), any())).thenReturn(Optional.empty()); + Device device = new Device(deviceId); + device.setTenantId(tenantId); + device.setName("AM308"); + when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + } + + @Test + void overwritesTheEntitiesAndRecordsTheNewVersionInOneTransaction() { + DeviceProfile profile = profile(3L, "AM308 renamed"); + when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); + Dashboard dashboard = dashboard(7L); + dashboard.setCustomerId(new CustomerId(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), + keep("AM308", "DEVICE", deviceId), + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor savedProfile = ArgumentCaptor.forClass(DeviceProfile.class); + verify(deviceProfileService).saveDeviceProfile(savedProfile.capture()); + // Same id, the name the user gave it, the version they reviewed + assertThat(savedProfile.getValue().getId()).isEqualTo(profileId); + assertThat(savedProfile.getValue().getName()).isEqualTo("AM308 renamed"); + assertThat(savedProfile.getValue().getDescription()).isEqualTo("new"); + assertThat(savedProfile.getValue().getVersion()).isEqualTo(3L); + ArgumentCaptor savedDashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(savedDashboard.capture()); + assertThat(savedDashboard.getValue().getCustomerId()).isEqualTo(dashboard.getCustomerId()); + + verify(installedItemService).save(tenantId, installedItem); + assertThat(installedItem.getVersion()).isEqualTo("1.0.1"); + assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + // Of the saved dashboard, not read back by id: inside the transaction that may come from the cache + assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()) + .isEqualTo(EntityChecksum.of(savedDashboard.getValue())); + assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId); + } + + @Test + void keptEntity_keepsTheChecksumThePackageLeft() { + // The user changed the dashboard since: its current checksum must not become the package's + ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created"); + dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); + DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); + request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed"); + assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK"); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + } + + @Test + void failedStep_rollsBackAndReportsTheStep() { + when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308")); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); + assertThat(rolledBack).hasSize(1); + verify(installedItemService, never()).save(any(), any()); + verifyNoInteractions(logEntityActionService); + assertThat(installedItem.getVersion()).isEqualTo("1.0.0"); + } + + @Test + void entityChangedSinceTheCheck_isAVersionConflict() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("Dashboard"); + assertThat(result.getErrorMessage()).contains("Check the update again"); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + } + + @Test + void integrationGetsTheIdOfTheConverterCreatedInTheSameUpdate() throws Exception { + ConverterId converterId = new ConverterId(UUID.randomUUID()); + when(converterService.saveConverter(any())).thenAnswer(i -> { + Converter converter = i.getArgument(0); + converter.setId(converterId); + return converter; + }); + Integration current = new Integration(); + current.setId(integrationId); + current.setTenantId(tenantId); + current.setName("TTN my-app"); + current.setRoutingKey("routing-key"); + current.setVersion(2L); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); + when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); + ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); + integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), + overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); + verify(integrationService).saveIntegration(saved.capture()); + assertThat(saved.getValue().getDefaultConverterId()).isEqualTo(converterId); + // The devices keep sending to the same endpoint + assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key"); + assertThat(saved.getValue().getName()).isEqualTo("TTN my-app"); + assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); + } + + @Test + void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { + DashboardId foreign = new DashboardId(UUID.randomUUID()); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void theDeviceIsNeverOverwritten() { + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("The device and its credentials don't change on update"); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void versionOfAnotherItem_isRejected() { + ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + + assertThat(result.isSuccess()).isFalse(); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void userMessage_showsValidationMessagesAndHidesInternalOnes() { + assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) + .isEqualTo("Rule chains limit reached"); + assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) + .contains("Check the update again"); + assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) + .isEqualTo("Failed to update the device package"); + } + + @Test + void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() { + ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); + ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); + + ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); + + assertThat(resolved.get("a").asText()).isEqualTo("123"); + assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); + } + + private DeviceProfile profile(Long version, String name) { + DeviceProfile profile = new DeviceProfile(profileId); + profile.setTenantId(tenantId); + profile.setName(name); + profile.setVersion(version); + return profile; + } + + private Dashboard dashboard(Long version) { + Dashboard dashboard = new Dashboard(dashboardId); + dashboard.setTenantId(tenantId); + dashboard.setTitle("AM308 dashboard"); + dashboard.setVersion(version); + return dashboard; + } + + private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { + DeviceUpdateRequest request = new DeviceUpdateRequest(); + request.setVersionId(versionId); + request.setSteps(List.of(steps)); + return request; + } + + private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { + DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); + step.setEntityId(id.getId()); + return step; + } + + private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { + DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); + step.setEntityId(id.getId()); + step.setExpectedVersion(version); + step.setEntity(entity); + return step; + } + + private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { + DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); + step.setEntity(entity); + return step; + } + + private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { + DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); + step.setName(name); + step.setType(type); + step.setAction(action); + return step; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index cf4f25bfd7..8cc1848797 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -510,46 +510,6 @@ class DefaultIotHubServiceTest { verify(iotHubInstalledItemService, never()).save(any(), any()); } - @Test - void registerDeviceUpdate_keepsTheInstalledItemAndRecordsTheNewVersion() { - mockTenant(); - DeviceId deviceId = new DeviceId(UUID.randomUUID()); - IotHubInstalledItem installed = devicePackage(deviceId); - installed.setItemType("DEVICE"); - installed.setItemId(UUID.randomUUID()); - installed.setVersion("1.0"); - when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); - String versionId = UUID.randomUUID().toString(); - when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, installed.getItemId().toString(), "DEVICE", "AM308", "1.1")); - DeviceInstalledItemDescriptor updated = new DeviceInstalledItemDescriptor(); - updated.setCreatedEntityIds(List.of(deviceId)); - - InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, updated); - - assertThat(result.isSuccess()).isTrue(); - verify(iotHubInstalledItemService).save(tenantId, installed); - assertThat(installed.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); - assertThat(installed.getVersion()).isEqualTo("1.1"); - assertThat(installed.getDescriptor()).isSameAs(updated); - verify(tbDeviceService, never()).delete(any(Device.class), any()); - } - - @Test - void registerDeviceUpdate_versionOfAnotherItem_isRejected() { - mockTenant(); - IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID())); - installed.setItemType("DEVICE"); - installed.setItemId(UUID.randomUUID()); - when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); - String versionId = UUID.randomUUID().toString(); - when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Other", "1.0")); - - InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, new DeviceInstalledItemDescriptor()); - - assertThat(result.isSuccess()).isFalse(); - verify(iotHubInstalledItemService, never()).save(any(), any()); - } - private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 639127e075..1bf462ce35 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -13,7 +13,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; @@ -180,13 +180,10 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig, - // Set for an update: the installed item takes the version and the descriptor - installedItemId?: string + config?: IotHubRequestConfig ): Observable { - const installedItemParam = installedItemId ? `&installedItemId=${installedItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}${installedItemParam}`, + `/api/iot-hub/device/register?versionId=${versionId}`, { type: 'DEVICE', ...descriptor }, { params: this.buildParams(config) } ); @@ -272,6 +269,23 @@ export class IotHubApiService { ); } + /** The entities of an installed device package as they are now: whether they exist, changed since, or are shared. */ + public checkDeviceUpdate(installedItemId: string, config?: IotHubRequestConfig): Observable { + return this.http.get( + `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate/check`, + { params: this.buildParams(config) } + ); + } + + /** Applies a device package update in one transaction: all of it, or nothing. */ + public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, + request, + { params: this.buildParams(config) } + ); + } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { return this.http.get( `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 11499fe154..d13e0221d9 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -61,6 +61,9 @@ } @case ('progress') { + @if (data.update) { + + } @else {
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) { @if (i > 0) { @@ -144,6 +147,142 @@ } }
+ } + } + } + + + + + + {{ 'iot-hub.device-update-modified' | translate }} + {{ 'iot-hub.device-update-here' | translate }}. + + + + +
+ @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @if (i > 0) { +
+ } + @let plan = updatePlanOf(ep); + @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name); + @if (ws.reviewing && plan && !plan.confirmed) { +
+
+
+ warning +
+
+ {{ label }} + @if (plan.existing) { + + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + + } + @if (plan.shared) { + {{ 'iot-hub.device-update-shared' | translate }} + } + @if (plan.modified) { + + + + } +
+
+
+ @if (plan.existing) { + @if (ep.step.type === 'DASHBOARD') { + + } @else { + + } + + } @else { + + } +
+
+ } @else if (ep.status === 'error') { +
+
+ error +
+
+ {{ label }} + @if (ep.errorMessage) { + {{ ep.errorMessage }} + } +
+ {{ 'iot-hub.device-install-step-error' | translate }} +
+ } @else { +
+
+ @switch (ep.status) { + @case ('running') { + + } + @case ('success') { + check_circle + } + @default { +
{{ i + 1 }}
+ } + } +
+
+
+ {{ label }} + @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + {{ 'iot-hub.device-update-new' | translate }} + } +
+ + @if (ws.reviewing && plan?.confirmed) { + @if (plan.existing) { + {{ 'iot-hub.device-update-existing-' + plan.resolution | translate }} + } + @if (plan.shared) { + {{ 'iot-hub.device-update-shared' | translate }} + } + @if (plan.modified) { + + + + } + } +
+ + @switch (ep.status) { + @case ('running') { + {{ 'iot-hub.in-progress' | translate }} + } + @case ('success') { + {{ 'iot-hub.done' | translate }} + } + @case ('skipped') { + {{ 'iot-hub.device-update-skipped' | translate }} + } + @default { + @if (ws.reviewing && plan) { + {{ 'iot-hub.device-update-no-conflicts' | translate }} + } + } + } + +
} }
@@ -171,7 +310,14 @@ } @else {
-

{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}

+

+ @if (data.update) { + {{ 'iot-hub.device-update-title' | translate:{ name: packageInfo?.name || data.item.name } }} + {{ data.update.fromVersion }} → {{ data.item.version }} + } @else { + {{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }} + } +

@@ -225,9 +371,24 @@ } + @if (data.update && currentWizardStep?.type === 'progress') { + @let step = currentWizardStep; + @if (hasUpdateError(step)) { +
+ error + {{ step.progressError }} +
+ } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { +
+ warning + {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} +
+ } + } + @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -264,7 +425,26 @@ } @case ('progress') { - @if (step.progressError) { + @if (data.update && (step.reviewing || step.updating || step.progressError)) { + @if (step.progressError && !step.updating) { + + + } @else if (step.updating) { + + + } @else { + + + } + } @else if (step.progressError) {
} @@ -270,7 +271,7 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ 'iot-hub.done' | translate }} + {{ updateOutcomeOf(plan) | translate }} } @case ('skipped') { {{ 'iot-hub.device-update-skipped' | translate }} 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 39e97081c4..34b25e66c5 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 @@ -200,6 +200,8 @@ export interface WizardStep { extraFormFields?: FormFieldDefinition[]; // Key of the step's form values in the install state; the label when not set stateKey?: string; + // Update: the keys of the form's fields the installed version didn't have + newFieldKeys?: Set; formGroup?: UntypedFormGroup; // Connection check of the integration the form configures; null when the form configures none connectionCheck?: ConnectionCheck | null; @@ -1230,6 +1232,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent…, which the translation may put anywhere in it, split around the link. */ + /** Update: what the update did with the entity of a row, once it succeeded. */ + updateOutcomeOf(plan: EntityStepPlan | undefined): string { + if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') { + return 'iot-hub.device-update-not-changed'; + } + return plan.action === 'overwrite' || plan.resolution === 'overwrite' ? 'iot-hub.device-update-updated' : 'iot-hub.device-update-created'; + } + textWithLink(key: string): { before: string; link: string; after: string } { const text: string = this.translate.instant(key); const match = /^([\s\S]*)([\s\S]*)<\/a>([\s\S]*)$/.exec(text); @@ -2295,6 +2306,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent s.type === step.type && (s.id && step.id ? s.id === step.id : s.name === step.name)); } + /** Update: the fields of a form step the installed version's form didn't have; all of them for a new form step. */ + private newFieldKeysOf(step: DeviceInstallStep, fields: FormFieldDefinition[]): Set { + if (!this.previousPackageInfo) { + return new Set(); + } + const previousStep = this.findPreviousStep(step); + let previousKeys = new Set(); + try { + const previousForm = previousStep ? JSON.parse(this.previousFiles.get(previousStep.file) || '[]') as FormFieldDefinition[] : []; + previousKeys = new Set(previousForm.map(field => field.key)); + } catch { + return new Set(); + } + return new Set(fields.map(field => field.key).filter(key => !previousKeys.has(key))); + } + /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ private stateKeysOf(step: DeviceInstallStep): string[] { return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)]; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index a94a41cff0..ab1314f65d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -36,7 +36,10 @@ @for (row of rows; track row.fields[0].key) { -
+
+ @if (isNewRow(row)) { + {{ 'iot-hub.device-update-new' | translate }} + } @if (row.fields.length > 1) {
@for (field of row.fields; track field.key) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss index f99f29ebca..10711348cc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss @@ -14,3 +14,23 @@ max-width: 100%; margin-top: 8px; } + +// Update: a field the installed version didn't have +.tb-install-form-row-new { + padding: 8px 12px; + border-left: 3px solid #305680; + border-radius: 4px; + background: rgba(48, 86, 128, 0.04); +} + +.tb-install-form-new { + align-self: flex-start; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.4px; + color: #305680; + background: rgba(48, 86, 128, 0.08); + border-radius: 4px; + padding: 2px 8px; +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index 6965009871..4633a41afd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts @@ -49,6 +49,8 @@ export class InstallFormRendererComponent implements OnChanges { @Input() resolveImagePath?: (path: string) => string; /** When true, PASSWORD inputs render unmasked by default (used by review mode). */ @Input() reviewMode = false; + /** Update: the fields the installed version's form didn't have, highlighted as new. */ + @Input() newFieldKeys?: Set; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields @@ -170,4 +172,8 @@ export class InstallFormRendererComponent implements OnChanges { imagePath(path: string): string { return this.resolveImagePath ? this.resolveImagePath(path) : path; } + + isNewRow(row: { fields: FormFieldDefinition[] }): boolean { + return !!this.newFieldKeys?.size && row.fields.some(field => this.newFieldKeys.has(field.key)); + } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 7e587600c9..36c91f24ab 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6538,13 +6538,16 @@ "device-update-no-conflicts": "No conflicts", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", - "device-update-modified": "Changed by someone else. You can download the current version here.", + "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", "device-update-existing-use-existing": "Already exists. The existing one will be used.", "device-update-existing-overwrite": "Already exists. It will be overwritten.", "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", + "device-update-not-changed": "Not changed", + "device-update-updated": "Updated", + "device-update-created": "Created", "device-update-try-again": "Try again", "done": "Done", "in-progress": "In progress", From 109c13a5e2f64c6612b0502c008cae7b3f7d2677 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:15:10 +0200 Subject: [PATCH 09/24] feat(iot-hub): mark a new form field by its outline, label and hint; show Done for kept entities --- .../device-install-dialog.component.html | 3 +- .../device-install-dialog.component.ts | 2 +- .../install-form-renderer.component.html | 60 +++++++++++++------ .../install-form-renderer.component.scss | 28 ++++----- .../install-form-renderer.component.ts | 6 +- .../assets/locale/locale.constant-en_US.json | 2 +- 6 files changed, 62 insertions(+), 39 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 7fb651678e..964a50bd0d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -56,7 +56,8 @@ [formGroup]="ws.formGroup" [resolveImagePath]="resolveImagePathFn" [reviewMode]="reviewMode" - [newFieldKeys]="ws.newFieldKeys"> + [newFieldKeys]="ws.newFieldKeys" + [newFieldHint]="'iot-hub.device-update-new-field' | translate: { version: data.item.version }">
} 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 34b25e66c5..ca88fa519e 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 @@ -1946,7 +1946,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent @for (row of rows; track row.fields[0].key) { -
- @if (isNewRow(row)) { - {{ 'iot-hub.device-update-new' | translate }} - } +
@if (row.fields.length > 1) {
@for (field of row.fields; track field.key) { @@ -96,7 +93,7 @@
} @case (FormFieldType.SELECT) { - {{ field.label }} @@ -104,8 +101,13 @@ {{ opt.label }} } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -113,7 +115,7 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }} {{ opt.label }} } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -139,7 +146,7 @@ } @case (FormFieldType.PASSWORD) { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -173,14 +185,19 @@ } @case (FormFieldType.INTEGER) { - {{ field.label }} - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -194,7 +211,7 @@ } @default { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss index 10711348cc..b19765a280 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss @@ -15,22 +15,20 @@ margin-top: 8px; } -// Update: a field the installed version didn't have -.tb-install-form-row-new { - padding: 8px 12px; - border-left: 3px solid #305680; - border-radius: 4px; - background: rgba(48, 86, 128, 0.04); +// Update: a field the installed version didn't have: outline, label and hint in the primary color +:host ::ng-deep .mat-mdc-form-field.tb-install-form-field-new { + .mdc-notched-outline__leading, + .mdc-notched-outline__notch, + .mdc-notched-outline__trailing { + border-color: var(--tb-primary-500); + } + .mdc-floating-label, + .mat-mdc-floating-label { + color: var(--tb-primary-500); + } } -.tb-install-form-new { - align-self: flex-start; - font-size: 12px; +.tb-install-form-new-hint { + color: var(--tb-primary-500); font-weight: 500; - line-height: 16px; - letter-spacing: 0.4px; - color: #305680; - background: rgba(48, 86, 128, 0.08); - border-radius: 4px; - padding: 2px 8px; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index 4633a41afd..16a1298ae2 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts @@ -51,6 +51,8 @@ export class InstallFormRendererComponent implements OnChanges { @Input() reviewMode = false; /** Update: the fields the installed version's form didn't have, highlighted as new. */ @Input() newFieldKeys?: Set; + /** Update: the text the hint of a new field starts with. */ + @Input() newFieldHint = ''; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields @@ -173,7 +175,7 @@ export class InstallFormRendererComponent implements OnChanges { return this.resolveImagePath ? this.resolveImagePath(path) : path; } - isNewRow(row: { fields: FormFieldDefinition[] }): boolean { - return !!this.newFieldKeys?.size && row.fields.some(field => this.newFieldKeys.has(field.key)); + isNewField(field: FormFieldDefinition): boolean { + return !!this.newFieldKeys?.has(field.key); } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 36c91f24ab..78db1e922c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6545,7 +6545,7 @@ "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", - "device-update-not-changed": "Not changed", + "device-update-new-field": "New in {{version}}.", "device-update-updated": "Updated", "device-update-created": "Created", "device-update-try-again": "Try again", From 25692d6ab0faca2c22ad4cb9030907c0cb5798ba Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:24:57 +0200 Subject: [PATCH 10/24] feat(iot-hub): mark a new form field by a primary outline and a New label --- .../device-install-dialog.component.html | 3 +- .../install-form-renderer.component.html | 55 +++++-------------- .../install-form-renderer.component.scss | 13 +++-- .../install-form-renderer.component.ts | 2 - .../assets/locale/locale.constant-en_US.json | 1 - 5 files changed, 23 insertions(+), 51 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 964a50bd0d..7fb651678e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -56,8 +56,7 @@ [formGroup]="ws.formGroup" [resolveImagePath]="resolveImagePathFn" [reviewMode]="reviewMode" - [newFieldKeys]="ws.newFieldKeys" - [newFieldHint]="'iot-hub.device-update-new-field' | translate: { version: data.item.version }"> + [newFieldKeys]="ws.newFieldKeys">
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index f8fd99411e..965f6ffefe 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -95,19 +95,14 @@ @case (FormFieldType.SELECT) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -117,7 +112,7 @@ @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -126,13 +121,8 @@ {{ opt.label }} } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -148,7 +138,7 @@ @case (FormFieldType.PASSWORD) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} autorenew } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -187,17 +172,12 @@ @case (FormFieldType.INTEGER) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -213,7 +193,7 @@ @default { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -225,13 +205,8 @@ autorenew } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss index b19765a280..492e9be76d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss @@ -15,20 +15,21 @@ margin-top: 8px; } -// Update: a field the installed version didn't have: outline, label and hint in the primary color +// Update: a field the installed version didn't have: a thicker outline, a tint and the label in the primary color :host ::ng-deep .mat-mdc-form-field.tb-install-form-field-new { .mdc-notched-outline__leading, .mdc-notched-outline__notch, .mdc-notched-outline__trailing { border-color: var(--tb-primary-500); + border-width: 2px; + } + .mat-mdc-text-field-wrapper { + border-radius: 4px; + background: color-mix(in srgb, var(--tb-primary-500) 4%, transparent); } .mdc-floating-label, .mat-mdc-floating-label { color: var(--tb-primary-500); + font-weight: 500; } } - -.tb-install-form-new-hint { - color: var(--tb-primary-500); - font-weight: 500; -} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index 16a1298ae2..a87c734094 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts @@ -51,8 +51,6 @@ export class InstallFormRendererComponent implements OnChanges { @Input() reviewMode = false; /** Update: the fields the installed version's form didn't have, highlighted as new. */ @Input() newFieldKeys?: Set; - /** Update: the text the hint of a new field starts with. */ - @Input() newFieldHint = ''; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 78db1e922c..4d52160b91 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6545,7 +6545,6 @@ "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", - "device-update-new-field": "New in {{version}}.", "device-update-updated": "Updated", "device-update-created": "Created", "device-update-try-again": "Try again", From 83ab5ec8147d8b12d77c11c1e7935bf0c01258d9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:28:30 +0200 Subject: [PATCH 11/24] feat(iot-hub): installed items offer an update through the new version's details --- .../iot-hub-installed-items-table.component.html | 12 +++++------- .../iot-hub-installed-items-table.component.scss | 6 +++--- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index ab41384640..8e4d9b57c5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -45,19 +45,17 @@ @if (getPublishedVersionInfo(item); as pubInfo) { @if (pubInfo.publishedVersionId !== item.itemVersionId) {
+ @if (!itemVersion) { - } - + + }
} @else { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index 9f304d2751..7d511670b9 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -126,9 +126,9 @@ font-weight: 500; line-height: 20px; letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); + color: var(--tb-primary-500); background: none; - border: 1px solid rgba(0, 0, 0, 0.12); + border: 1px solid var(--tb-primary-500); border-radius: 4px; padding: 6px 12px; cursor: pointer; @@ -143,7 +143,7 @@ } &:hover { - background: rgba(0, 0, 0, 0.04); + background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); } } From f410611ed690d3a877e9dfb05283b1e7f770f216 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:28:46 +0200 Subject: [PATCH 12/24] fix(iot-hub): lowercase available after the version --- ui-ngx/src/assets/locale/locale.constant-en_US.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 4d52160b91..eb84ed9a84 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6325,7 +6325,7 @@ "items-per-page": "Items per page", "filter": "Filter", "clear-filters": "Clear filters", - "available": "Available", + "available": "available", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", "items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.", "items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.", From a25a4563933fbe6e7d30e8e8695e1f13d0900563 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:32:02 +0200 Subject: [PATCH 13/24] fix(iot-hub): keep the update button red --- ...t-hub-installed-items-table.component.html | 2 +- ...t-hub-installed-items-table.component.scss | 32 +------------------ 2 files changed, 2 insertions(+), 32 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 8e4d9b57c5..6926a0ba41 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -47,7 +47,7 @@
@if (!itemVersion) { - diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index 7d511670b9..e390164cd5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -117,37 +117,7 @@ .tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); } .tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); } -// "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8 -.tb-installed-version-btn { - display: inline-flex; - align-items: center; - gap: 8px; - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: var(--tb-primary-500); - background: none; - border: 1px solid var(--tb-primary-500); - border-radius: 4px; - padding: 6px 12px; - cursor: pointer; - font-family: inherit; - - mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - color: inherit !important; - --mat-icon-color: currentColor; - } - - &:hover { - background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); - } -} - -// "Update" button — Design: same height as available btn, border matches text color +// "vX.X.X available" and "Update to" buttons: border matches the text color .tb-installed-update-btn.mat-mdc-outlined-button { font-size: 14px; font-weight: 500; From cd95b67b8c931b1a1ebe57845c783526cff43656 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:34:42 +0200 Subject: [PATCH 14/24] feat(iot-hub): the available version button opens the update --- .../iot-hub-installed-items-table.component.html | 3 +-- .../iot-hub-installed-items-table.component.scss | 5 +++++ .../iot-hub/iot-hub-installed-items-table.component.ts | 10 ---------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 6926a0ba41..08195cac7a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -45,9 +45,8 @@ @if (getPublishedVersionInfo(item); as pubInfo) { @if (pubInfo.publishedVersionId !== item.itemVersionId) {
- @if (!itemVersion) { - diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index e390164cd5..e943f76f46 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -126,6 +126,11 @@ padding: 6px 12px; height: auto; --mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color); + + mat-icon { + color: inherit !important; + --mat-icon-color: currentColor; + } } // "Up to date" — Design: 14px Medium, #198038, gap-8, py-6 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 0e332b9d45..27a2215c48 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 @@ -242,16 +242,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } - viewUpdateDetails(publishedInfo: ItemPublishedVersionInfo, installedItem: IotHubInstalledItem): void { - this.iotHubApiService.getVersionInfo(publishedInfo.publishedVersionId, {ignoreLoading: true}).subscribe(versionView => { - this.iotHubActions.openItemDetail(versionView, installedItem).subscribe(result => { - if (result === 'updated' || result === 'deleted') { - this.loadData(); - } - }); - }); - } - updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { From 341fd5d3cd247bf4adaf3b22cb0a361b6a9a8149 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Mon, 2 Nov 2026 10:20:01 +0200 Subject: [PATCH 15/24] feat(iot-hub): a device package step takes the default converter, a new default converter shows as an update, and the profile name is set at install - UPLINK_CONVERTER step with "default": true and no template: the wizard builds the converter ThingsBoard creates for a new integration of the method's type (INTEGRATION_TTN: TTN) from the UI assets, and installs, overwrites and updates it like a template of the package. - Installed items: a device package whose default converter differs from ThingsBoard's default converter now shows "New converter available". It opens the update of the installed version, which brings the converter to the default one. A package that took another package's converter overwrites it with the shared-entity warning. - After an update overwrites an entity, the other packages that recorded its checksum record the new one. - INTEGRATION step "metadata": its entries are added to the integration's metadata at create, overwrite, use existing and update; the entries the integration has stay. An entry that maps a name to itself (profile.: ) isn't added. The checksum of an integration leaves out its metadata. - The default TTN and TTI converters take the profile name from the integration metadata entry profile.- when there is one. - Form field "resettable": a field the user changed shows a button that puts its default value back. --- .../DefaultDevicePackageUpdateService.java | 53 +++++++ .../service/iot_hub/DeviceUpdateRequest.java | 2 + .../service/iot_hub/EntityChecksum.java | 5 + .../controller/ConverterControllerTest.java | 29 +++- ...DefaultDevicePackageUpdateServiceTest.java | 64 ++++++++ .../device-install-dialog.component.html | 6 + .../device-install-dialog.component.ts | 138 ++++++++++++++++-- .../install-form-renderer.component.html | 8 + .../install-form-renderer.component.ts | 12 ++ .../iot-hub/iot-hub-default-converter.ts | 57 ++++++++ ...t-hub-installed-items-table.component.html | 40 ++--- ...iot-hub-installed-items-table.component.ts | 52 ++++++- .../models/iot-hub/device-package.models.ts | 6 + .../iot-hub/iot-hub-installed-item.models.ts | 2 + .../src/assets/converters/js-tti-decoder.raw | 12 +- .../src/assets/converters/js-ttn-decoder.raw | 12 +- .../assets/converters/tbel-tti-decoder.raw | 12 +- .../assets/converters/tbel-ttn-decoder.raw | 12 +- .../assets/locale/locale.constant-en_US.json | 2 + 19 files changed, 465 insertions(+), 59 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts 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 6b8445d16e..1f452c3792 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 @@ -42,6 +42,8 @@ import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.security.DeviceCredentials; @@ -285,6 +287,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List saved = new ArrayList<>(); List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); + // The checksums of the entities this update overwrote, which other packages may record too + Map overwrittenChecksums = new HashMap<>(); DashboardId dashboardId = null; for (DeviceUpdateRequest.Step step : request.getSteps()) { @@ -310,6 +314,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (checksum != null) { state.put("checksum", checksum); } + if (step.isDefaultConverter()) { + state.put("defaultConverter", true); + } + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && result.checksum() != null) { + overwrittenChecksums.put(result.entityId().getId(), result.checksum()); + } installState.put(step.getId() != null ? step.getId() : step.getName(), state); if (!"use-existing".equals(step.getResolution())) { stepEntityIds.add(result.entityId()); @@ -344,12 +354,55 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i installedItem.setVersion(versionInfo.get("version").asText()); installedItem.setDescriptor(descriptor); installedItemService.save(tenantId, installedItem); + refreshChecksumsOfOtherPackages(tenantId, installedItem.getId(), overwrittenChecksums); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); } + /** + * Another package that recorded the checksum of an entity this update overwrote, e.g. a shared converter, records the + * new one: the update was confirmed for all packages using the entity, so their next update sees no change by someone else. + */ + private void refreshChecksumsOfOtherPackages(TenantId tenantId, IotHubInstalledItemId installedItemId, Map checksums) { + if (checksums.isEmpty()) { + return; + } + PageLink pageLink = new PageLink(100); + PageData page; + do { + page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); + for (IotHubInstalledItem item : page.getData()) { + if (!item.getId().equals(installedItemId) && item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor + && descriptor.getInstallState() != null && refreshChecksums(descriptor.getInstallState(), checksums)) { + installedItemService.save(tenantId, item); + } + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + } + + private static boolean refreshChecksums(Map installState, Map checksums) { + boolean changed = false; + for (JsonNode state : installState.values()) { + String checksum = checksums.get(toUuid(state.path("entityOutput").path("id").asText())); + if (checksum != null && state.has("checksum") && state instanceof ObjectNode objectState) { + objectState.put("checksum", checksum); + changed = true; + } + } + return changed; + } + + private static UUID toUuid(String id) { + try { + return UUID.fromString(id); + } catch (IllegalArgumentException e) { + return null; + } + } + /** * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * fails: the plan was made for the version installed before. Without it both would create the new entities. 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 28118ed018..c3f2f90f89 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,8 @@ public class DeviceUpdateRequest { private JsonNode sharedAttributes; // The resolution the install state records for it private String resolution; + // 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/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java index 4cd2f25d02..1f8c8887e5 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.rule.RuleNode; @@ -37,6 +38,10 @@ final class EntityChecksum { StringBuilder canonical = new StringBuilder(); for (Object part : parts) { JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part); + if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) { + // Device packages on one integration add their entries to its metadata: that is no change to the integration + configuration.remove("metadata"); + } appendCanonical(canonical, node, true); canonical.append('|'); } diff --git a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java index 8ab6727c04..023397bf0b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -686,9 +686,7 @@ public class ConverterControllerTest extends AbstractControllerTest { testDecoder(TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); } - @Test - public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + + private static final String THINGS_STACK_REPOSITORY_DEVICE_RESULT = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560," + "\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + "\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," + @@ -696,7 +694,17 @@ public class ConverterControllerTest extends AbstractControllerTest { "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + "\"clusterAddress\":\"eu1.cloud.thethings.network\"}}"; - testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, expectedDecodedMessage); + @Test + public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { + testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, Map.of(), THINGS_STACK_REPOSITORY_DEVICE_RESULT); + } + + @Test + public void testThingsStackDefaultConvertersTakeProfileNameFromIntegrationMetadata() throws IOException { + String expectedDecodedMessage = THINGS_STACK_REPOSITORY_DEVICE_RESULT.replace("\"profile\":\"milesight-iot-am308\"", "\"profile\":\"AM308\""); + Map integrationMetadata = Map.of("profile.milesight-iot-am308", "AM308", "profile.milesight-iot-ws202", "WS202"); + + testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, integrationMetadata, expectedDecodedMessage); } @Test @@ -706,18 +714,18 @@ public class ConverterControllerTest extends AbstractControllerTest { "\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," + "\"spreadingFactor\":9,\"frequency\":\"868300000\"}}"; - testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, expectedDecodedMessage); + testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, Map.of("profile.milesight-iot-am308", "AM308"), expectedDecodedMessage); } // The TBEL and JS defaults are two copies of one script, so each of them must give this result for TTN and TTI - private void testThingsStackDefaultConverters(String payloadFile, String expectedResult) throws IOException { + private void testThingsStackDefaultConverters(String payloadFile, Map integrationMetadata, String expectedResult) throws IOException { JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); String payload = readResource(payloadFile); for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); for (ScriptLanguage scriptLang : ScriptLanguage.values()) { String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; - assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang))) + assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang, integrationMetadata))) .as("%s %s", integrationType, scriptLang) .isEqualTo(JacksonUtil.toJsonNode(expectedResult)); } @@ -896,6 +904,12 @@ public class ConverterControllerTest extends AbstractControllerTest { } private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException { + return decode(decoderFileName, payloadExample, converter, scriptLang, Map.of()); + } + + // integrationMetadata: what the integration adds to the metadata of every uplink, from its configuration + private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang, + Map integrationMetadata) throws IOException { byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName)); String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8)); @@ -917,6 +931,7 @@ public class ConverterControllerTest extends AbstractControllerTest { inputParams.set("payload", unwrapped.get("payload")); } inputParams.set("metadata",unwrapped.get("metadata")); + integrationMetadata.forEach(((ObjectNode) inputParams.get("metadata"))::put); } else { inputParams.set("payload", new TextNode(base64Payload)); } 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 6fbf49587c..e0281891aa 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 @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.iot_hub; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,6 +35,7 @@ import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; @@ -165,6 +167,7 @@ class DefaultDevicePackageUpdateServiceTest { device.setTenantId(tenantId); device.setName("AM308"); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>()); } @Test @@ -335,6 +338,40 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); } + @Test + void overwrittenSharedConverter_isRecordedAsDefaultAndOtherPackagesTakeItsChecksum() { + ConverterId converterId = new ConverterId(UUID.randomUUID()); + Converter current = new Converter(converterId); + current.setTenantId(tenantId); + current.setName("Uplink data converter for TTN my-app"); + current.setVersion(4L); + when(converterService.findConverterById(tenantId, converterId)).thenReturn(current); + when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0)); + // The package that created the converter records its checksum; one that took it as it was records none + ObjectNode created = JacksonUtil.newObjectNode().put("checksum", "before").put("resolution", "created"); + created.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); + ObjectNode usedExisting = JacksonUtil.newObjectNode().put("resolution", "use-existing"); + usedExisting.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); + IotHubInstalledItem creator = otherPackage(Map.of("Uplink", created)); + IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); + when(installedItemService.findByTenantId(any(), any(), any(), any())) + .thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); + DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, + JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); + step.setConfirmed(true); + step.setDefaultConverter(true); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isTrue(); + JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); + assertThat(state.get("defaultConverter").asBoolean()).isTrue(); + assertThat(created.get("checksum").asText()).isEqualTo(state.get("checksum").asText()); + assertThat(usedExisting.has("checksum")).isFalse(); + verify(installedItemService).save(tenantId, creator); + verify(installedItemService, never()).save(tenantId, taker); + } + @Test void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); @@ -443,6 +480,22 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(EntityChecksum.of(profile)).isEqualTo(profileChecksum); } + @Test + void checksum_ignoresTheMetadataOfAnIntegration() { + Integration integration = new Integration(); + integration.setName("TTN my-app"); + ObjectNode configuration = JacksonUtil.newObjectNode().put("host", "eu1.cloud.thethings.network"); + configuration.set("metadata", JacksonUtil.newObjectNode()); + integration.setConfiguration(configuration); + String installed = EntityChecksum.of(integration); + // Another package on the integration adds its profile name + ((ObjectNode) configuration.get("metadata")).put("profile.milesight-iot-am308", "AM308"); + assertThat(EntityChecksum.of(integration)).isEqualTo(installed); + assertThat(integration.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue(); + configuration.put("host", "nam1.cloud.thethings.network"); + assertThat(EntityChecksum.of(integration)).isNotEqualTo(installed); + } + @Test void userMessage_showsValidationMessagesAndHidesInternalOnes() { assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) @@ -464,6 +517,17 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); } + private IotHubInstalledItem otherPackage(Map installState) { + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setInstallState(installState); + IotHubInstalledItem item = new IotHubInstalledItem(); + item.setId(new IotHubInstalledItemId(UUID.randomUUID())); + item.setTenantId(tenantId); + item.setItemType("DEVICE"); + item.setDescriptor(descriptor); + return item; + } + private DeviceProfile profile(Long version, String name) { DeviceProfile profile = new DeviceProfile(profileId); profile.setTenantId(tenantId); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 7fb651678e..695df118b5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -177,6 +177,9 @@
{{ label }} + @if (plan.newDefaultConverter) { + {{ 'iot-hub.device-update-new-default-converter' | translate }} + } @if (plan.existing) { {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} @@ -252,6 +255,9 @@
@if (ws.reviewing && plan?.confirmed) { + @if (plan.newDefaultConverter) { + {{ 'iot-hub.device-update-new-default-converter' | translate }} + } @if (plan.existing) { {{ 'iot-hub.device-update-existing-' + plan.resolution | translate }} } 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 ca88fa519e..e515186140 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 @@ -35,6 +35,11 @@ import { IntegrationService } from '@core/http/integration.service'; import { DialogService } from '@core/services/dialog.service'; import { Converter, ConverterType } from '@shared/models/converter.models'; import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service'; +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, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; import { cleanFormFieldValue, DeviceInstallStep, @@ -98,6 +103,8 @@ interface EntityStepPlan { version?: number; // Modified: the entity as the check found it, which the user can download before it is overwritten current?: any; + // A step with "default": true whose converter differs from ThingsBoard's default converter now + newDefaultConverter?: boolean; } /** @@ -225,6 +232,8 @@ export interface ConnectionCheck { } const ENTITY_STEP_MIN_DELAY = 2000; +// Where the wizard keeps the converter it builds for a step with "default": true, as if the package had that file +const DEFAULT_CONVERTER_PATH = 'tb-default-converter/'; const DEFAULT_RANDOM_SIZE = 20; const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost'; const TRANSPORT_PORT_FIELD_KEY = 'tbTransportPort'; @@ -359,6 +368,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); private previousPackageInfo: DevicePackageInfo | null = null; private entityPlans = new WeakMap(); + // Update: for each step with "default": true, whether its converter differs from ThingsBoard's default one now + private defaultConverterChanges = new Map(); // Variable resolution state formValues: Record = {}; @@ -397,7 +408,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.packageInfo.installSteps[ct]?.length > 0 ); @@ -440,6 +453,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (step.type === InstallStepType.INTEGRATION && step.metadata) { + return this.addStepMetadata(step, existing); + } if (step.type !== InstallStepType.DEVICE && step.type !== InstallStepType.GATEWAY) { return existing; } @@ -1814,6 +1833,35 @@ export class TbDeviceInstallDialogComponent extends DialogComponent: does when the + * user kept the default profile name, isn't added. + */ + private withStepMetadata(step: DeviceInstallStep, metadata: Record | 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('${') && value !== key.substring(key.indexOf('.') + 1)) { + merged[key] = value; + } + } + return merged; + } + + /** 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})); + const metadata = this.withStepMetadata(step, integration.configuration?.metadata); + if (isEqual(metadata, integration.configuration?.metadata ?? {})) { + return existing; + } + integration.configuration = { ...integration.configuration, metadata }; + const result = await firstValueFrom(this.integrationService.saveIntegration(integration, {ignoreErrors: true})); + return this.buildIntegrationOutput(result); + } + /** Stores the gateway output early, so the custom docker-compose template, if any, resolves ${gateway.token} etc. */ private setGatewayOutput(step: DeviceInstallStep, output: EntityStepOutput): void { this.entityOutputs.set('gateway', output); @@ -2001,7 +2049,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { for (const ep of ws.entitySteps) { const plan = this.entityPlans.get(ep); const alias = stepTypeAliasMap[ep.step.type]; @@ -2068,16 +2116,21 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.buildUpdateStep(ws, ep.step, this.entityPlans.get(ep))); + const steps: DeviceUpdateStep[] = []; + for (const ep of ws.entitySteps) { + steps.push(await this.buildUpdateStep(ws, ep.step, this.entityPlans.get(ep))); + } + return steps; } - private buildUpdateStep(ws: WizardStep, step: DeviceInstallStep, plan: EntityStepPlan): DeviceUpdateStep { + private async buildUpdateStep(ws: WizardStep, step: DeviceInstallStep, plan: EntityStepPlan): Promise { const base: DeviceUpdateStep = { name: step.name, id: step.id, type: step.type, action: 'KEEP', - resolution: plan.previous?.resolution ?? plan.resolution ?? 'created' + resolution: plan.previous?.resolution ?? plan.resolution ?? 'created', + defaultConverter: step.default || undefined }; if (step.type === InstallStepType.GATEWAY_CONNECTOR) { return plan.action === 'keep' ? base : { ...base, action: 'OVERWRITE', entity: this.resolveTemplateJson(this.zipFiles.get(step.template)) }; @@ -2090,6 +2143,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const scriptLang = getCurrentAuthState(this.store).tbelEnabled ? ScriptLanguage.TBEL : ScriptLanguage.JS; + for (const [method, steps] of Object.entries(this.packageInfo.installSteps ?? {})) { + for (const step of steps) { + if (step.type !== InstallStepType.UPLINK_CONVERTER || !step.default) { + continue; + } + const integrationType = method.replace(/^INTEGRATION_/, '') as IntegrationType; + const converter = await loadDefaultUplinkConverter(this.resourcesService, integrationType, scriptLang, step.name); + if (!converter) { + throw new Error(`ThingsBoard has no default converter for ${integrationType}`); + } + step.template = `${DEFAULT_CONVERTER_PATH}${integrationType}.json`; + this.zipFiles.set(step.template, JSON.stringify(converter)); + } + } + } + + /** + * Update: ThingsBoard's default converter changes with ThingsBoard, not with the package, so a step with "default": true + * changed when the package's converter differs from the default one now. A converter the user changed differs too: + * the update shows that someone changed it. + */ + private async checkDefaultConverters(): Promise { + this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + try { + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { + const id = step.default ? this.storedStateOf(step)?.state?.entityOutput?.id : undefined; + const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true})).catch(() => null) : null; + if (converter) { + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + this.defaultConverterChanges.set(step, !!defaultConverter && differsFromDefaultConverter(converter, defaultConverter)); + } + } + } finally { + this.formValues = {}; + this.entityOutputs.clear(); + } + } + /** Update: loads the installed version. Without it, every form and entity of the new version counts as changed. */ private async loadPreviousVersion(): Promise { try { @@ -2343,12 +2447,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual( this.resolvePackageFile(this.zipFiles, step[file], this.formValues), this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues) @@ -2418,6 +2525,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponentautorenew } + @if (canResetToDefault(field)) { + + } @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index a87c734094..5c2b03d162 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts @@ -138,6 +138,18 @@ export class InstallFormRendererComponent implements OnChanges { control.markAsDirty(); } + /** A resettable field the user changed shows a button that puts its defaultValue back. */ + canResetToDefault(field: FormFieldDefinition): boolean { + const control = this.formGroup.controls[field.key]; + return !!field.resettable && !!control?.enabled && control.value !== (field.defaultValue ?? ''); + } + + resetToDefault(field: FormFieldDefinition): void { + const control = this.formGroup.controls[field.key]; + control.setValue(field.defaultValue ?? ''); + control.markAsDirty(); + } + onFocus(field: FormFieldDefinition): void { const control = this.formGroup.controls[field.key]; this.focusedControl = control ?? null; 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 new file mode 100644 index 0000000000..b90a362da3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +import { firstValueFrom } from 'rxjs'; +import { ResourcesService } from '@core/services/resources.service'; +import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models'; +import { IntegrationType } from '@shared/models/integration.models'; +import { ScriptLanguage } from '@shared/models/rule-node.models'; +import { isEqual } from '@core/utils'; + +const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json'; + +// The settings of a default converter that decide what it does: the script is compared on its own +const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] = + ['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys']; + +/** + * The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with + * "default": true installs it. Null when ThingsBoard has no default converter settings for the type. + */ +export const loadDefaultUplinkConverter = async (resourcesService: ResourcesService, integrationType: IntegrationType, + scriptLang: ScriptLanguage, name: string): Promise | null> => { + const configurations = await firstValueFrom( + resourcesService.loadJsonResource>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL)); + const configuration = configurations?.[integrationType]; + if (!configuration) { + return null; + } + const script = await firstValueFrom(resourcesService.loadJsonResource( + getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2))); + return { + name, + type: ConverterType.UPLINK, + integrationType, + converterVersion: 2, + edgeTemplate: false, + // As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing + debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 }, + configuration: { + ...configuration, + scriptLang, + decoder: null, + tbelDecoder: null, + encoder: null, + tbelEncoder: null, + [getTargetField(ConverterType.UPLINK, scriptLang)]: script + }, + additionalInfo: { description: '' } + }; +}; + +/** True when the converter does something else than the default one: another script or other settings. */ +export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial): boolean => { + const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang); + const script = (value: string) => (value ?? '').trimEnd(); + return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) || + V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); +}; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index 08195cac7a..db7ad21423 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -42,26 +42,26 @@ @if (updatesChecked) { {{ 'iot-hub.updates' | translate }} } @if (updatesChecked) { - @if (getPublishedVersionInfo(item); as pubInfo) { - @if (pubInfo.publishedVersionId !== item.itemVersionId) { -
- @if (!itemVersion) { - - } @else { - - } -
- } @else { - - check - {{ 'iot-hub.up-to-date' | translate }} - - } + @let pubInfo = getPublishedVersionInfo(item); + @if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) { +
+ @if (!itemVersion) { + + } @else { + + } +
+ } @else if (hasConverterUpdate(item)) { + + } @else { check 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 27a2215c48..765f563898 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 @@ -36,6 +36,10 @@ import { entityTypeTranslations } from '@shared/models/entity-type.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.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, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { firstValueFrom } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -68,6 +72,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isLoading = false; publishedVersionMap = new Map(); + // Installed device packages whose default converter differs from ThingsBoard's default converter now + converterUpdates = new Set(); updatesChecked = false; isCheckingUpdates = false; @@ -83,7 +89,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private iotHubActions: IotHubActionsService, private elementRef: ElementRef, private zone: NgZone, - private cd: ChangeDetectorRef + private cd: ChangeDetectorRef, + private converterService: ConverterService, + private resourcesService: ResourcesService ) { this.widgetResize$ = new ResizeObserver(() => { this.zone.run(() => { @@ -235,6 +243,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; + void this.checkConverterUpdates(); }, error: () => { this.isCheckingUpdates = false; @@ -250,6 +259,44 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } + hasConverterUpdate(item: IotHubInstalledItem): boolean { + return this.converterUpdates.has(item.id.id); + } + + /** The update to the installed version itself brings the converter to ThingsBoard's default one. */ + updateConverter(item: IotHubInstalledItem): void { + this.iotHubActions.updateItem(item, item.version, item.itemVersionId).subscribe(result => { + if (result === 'updated') { + this.loadData(); + } + }); + } + + /** + * The device packages on this page whose step with "default": true installed a converter that differs from + * ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it. + */ + private async checkConverterUpdates(): Promise { + const updates = new Set(); + for (const item of this.dataSource) { + const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; + for (const state of states) { + const id = state?.defaultConverter ? state.entityOutput?.id : undefined; + const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) + .catch(() => null) : null; + if (converter) { + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + if (defaultConverter && differsFromDefaultConverter(converter, defaultConverter)) { + updates.add(item.id.id); + } + } + } + } + this.converterUpdates = updates; + this.cd.markForCheck(); + } + getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { return this.publishedVersionMap.get(item.itemId); } @@ -267,6 +314,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.dataSource = data.data; this.totalElements = data.totalElements; this.isLoading = false; + if (this.updatesChecked && !this.itemVersion) { + void this.checkConverterUpdates(); + } }, error: () => { this.dataSource = []; diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index 62e38c0541..088f787440 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -226,6 +226,10 @@ export interface DeviceInstallStep { dockerCompose?: string; // INTEGRATION step references the integration-form.json artifact alongside the template. form?: string; + // UPLINK_CONVERTER: ThingsBoard's default converter for the method's integration instead of a template + default?: boolean; + // INTEGRATION: entries added to the integration's metadata, which keeps the entries it has + metadata?: Record; } export interface DevicePackageInfo { @@ -285,6 +289,8 @@ export interface FormFieldDefinition { // Consecutive fields with the same group are shown in one panel titled with the group group?: string; readOnly?: boolean; + // A STRING field the user changed shows a button that puts defaultValue back + resettable?: boolean; // Shown inside the empty field; the label then always stays above it placeholder?: string; // Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it. 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 fbdd9867c3..494605caf4 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 @@ -62,6 +62,8 @@ export interface DeviceUpdateStep { resolution?: string; // The package step's id, which keys its install state; the name when not set id?: string; + // The step takes ThingsBoard's default converter: its install state says so, for the update check + defaultConverter?: boolean; } export interface DeviceUpdateRequest { diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index 5cb10f8db1..ee4314679b 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -1,6 +1,7 @@ // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. -// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == 'JSON') { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') { var profile = 'LoRaWAN Device'; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + '-' + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata['profile.' + profile]; + if (customProfile != null && customProfile != '') { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == 'milesight-iot-am308') { -// profile = 'AM308'; -// } if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index 5cb10f8db1..ee4314679b 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -1,6 +1,7 @@ // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. -// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == 'JSON') { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') { var profile = 'LoRaWAN Device'; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + '-' + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata['profile.' + profile]; + if (customProfile != null && customProfile != '') { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == 'milesight-iot-am308') { -// profile = 'AM308'; -// } if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 09c75b5aed..1cfef4546d 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -1,6 +1,7 @@ // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. -// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == "JSON") { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") { var profile = "LoRaWAN Device"; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + "-" + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata["profile." + profile]; + if (customProfile != null && customProfile != "") { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == "milesight-iot-am308") { -// profile = "AM308"; -// } if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 09c75b5aed..1cfef4546d 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -1,6 +1,7 @@ // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. -// Such a device gets the profile -, so all devices of one model share it. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == "JSON") { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") { var profile = "LoRaWAN Device"; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + "-" + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata["profile." + profile]; + if (customProfile != null && customProfile != "") { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == "milesight-iot-am308") { -// profile = "AM308"; -// } if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index eb84ed9a84..68a0906635 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6452,6 +6452,7 @@ "check-for-updates": "Check for updates", "updates": "Updates", "up-to-date": "Up to date", + "new-converter-available": "New converter available", "update": "Update", "update-to-version": "Update to v {{ version }}", "update-item-title": "Update Item", @@ -6538,6 +6539,7 @@ "device-update-no-conflicts": "No conflicts", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", + "device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.", "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", "device-update-existing-use-existing": "Already exists. The existing one will be used.", From 4bfa5d91153ae83dd9c7f4faede9f4a7593cdf0f Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 10:20:54 +0200 Subject: [PATCH 16/24] fix(iot-hub): keep the package's own entity on use-existing, find a step that gained an id by its name --- .../device-install-dialog.component.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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 ca88fa519e..327590d41c 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 @@ -2086,7 +2086,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } + /** Update: true when the entity is one the installed package created. */ + private isPackageEntity(id: string): boolean { + return !!this.data.update?.descriptor.createdEntityIds?.some(created => created.id === id); + } + /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ private stateKeysOf(step: DeviceInstallStep): string[] { return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)]; } - /** Update: the install state of a step of the new version, under the key of the installed step it replaces. */ + /** + * Update: the install state of a step of the new version, under the key of the installed step it replaces. + * Without the installed version's steps (e.g. it can't be downloaded any more), a step that has gained an id + * is also looked up under its own name, which the installed version keyed it by. + */ private storedStateOf(step: DeviceInstallStep): { key: string; state: any } | undefined { const installState = this.data.update?.descriptor.installState ?? {}; const previousStep = this.findPreviousStep(step); const keys = [...(previousStep ? this.stateKeysOf(previousStep) : []), ...this.stateKeysOf(step)]; + if (!previousStep && step.id) { + keys.push(step.name, this.resolveVariables(step.name)); + } const key = keys.find(k => k && installState[k]); return key ? { key, state: installState[key] } : undefined; } From f536a08e21117c49ba42e7dac70dfc80c5675bd7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 10:45:51 +0200 Subject: [PATCH 17/24] fix(iot-hub): the server keeps the package's own entities, the name fallback only without the installed version --- .../iot_hub/DefaultDevicePackageUpdateService.java | 10 +++++++--- .../DefaultDevicePackageUpdateServiceTest.java | 14 ++++++++++++++ .../device-install-dialog.component.ts | 2 +- 3 files changed, 22 insertions(+), 4 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 6b8445d16e..380f372ea7 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 @@ -271,6 +271,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + Set ownedIds = createdIds(previous).keySet(); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); Map installState = new LinkedHashMap<>(); @@ -303,7 +304,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i outputs.put(step.getName(), output); ObjectNode state = JacksonUtil.newObjectNode(); state.set("entityOutput", output); - state.put("resolution", step.getResolution() != null ? step.getResolution() : "created"); + // The package's own entity stays the package's, whatever the request says, so later versions update it + boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); + String resolution = step.getResolution() == null || (owned && "use-existing".equals(step.getResolution())) ? "created" : step.getResolution(); + state.put("resolution", resolution); // A kept entity keeps the checksum of what the package left: the current one would take the // user's changes for the package's, and the next update would overwrite them without a warning String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); @@ -311,7 +315,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("checksum", checksum); } installState.put(step.getId() != null ? step.getId() : step.getName(), state); - if (!"use-existing".equals(step.getResolution())) { + if (!"use-existing".equals(resolution)) { stepEntityIds.add(result.entityId()); } if (result.entityId() instanceof DashboardId id) { @@ -320,7 +324,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) { + if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { // As at install, the step's attributes go with the entity it saved; written after commit attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); } 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 6fbf49587c..0d6bed9f0f 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 @@ -256,6 +256,20 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse(); } + @Test + void useExistingOfAPackageEntity_staysThePackages() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); + DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); + step.setResolution("use-existing"); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isTrue(); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created"); + assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId); + } + @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 327590d41c..fc1718b108 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 @@ -2344,7 +2344,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent k && installState[k]); From 464147b6f7eda98484ac6721784ba689a695dd29 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:04:41 +0200 Subject: [PATCH 18/24] fix(iot-hub): a package owns the entities its install state records, except use-existing ones --- .../DefaultDevicePackageUpdateService.java | 24 +++++++++++- ...DefaultDevicePackageUpdateServiceTest.java | 37 ++++++++++++++++++- .../device-install-dialog.component.ts | 8 +++- 3 files changed, 64 insertions(+), 5 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 db5dc64379..5ab98c932e 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 @@ -204,7 +204,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (request.getSteps() == null || request.getSteps().isEmpty()) { throw new IllegalArgumentException("The update has no steps"); } - Set ownedIds = createdIds(devicePackage.descriptor()).keySet(); + Set ownedIds = ownedIds(devicePackage.descriptor()); Set stateKeys = new HashSet<>(); for (DeviceUpdateRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { @@ -273,7 +273,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); - Set ownedIds = createdIds(previous).keySet(); + Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); Map installState = new LinkedHashMap<>(); @@ -840,6 +840,26 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type)); } + /** + * The entities the package owns: those its install state records, except the ones the user chose to use as they + * were. Not createdEntityIds: the install adds the use-existing ones to it too. + */ + private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) { + Set ids = new HashSet<>(); + if (descriptor.getInstallState() != null) { + descriptor.getInstallState().values().forEach(state -> { + JsonNode id = state.path("entityOutput").path("id"); + if (id.isTextual() && !"use-existing".equals(state.path("resolution").asText())) { + try { + ids.add(UUID.fromString(id.asText())); + } catch (IllegalArgumentException ignored) { + } + } + }); + } + return ids; + } + private static Map createdIds(DeviceInstalledItemDescriptor descriptor) { Map ids = new HashMap<>(); if (descriptor.getCreatedEntityIds() != null) { 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 7b02a966fa..06d0109b82 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 @@ -135,7 +135,9 @@ class DefaultDevicePackageUpdateServiceTest { descriptor.setSelectedInstallMethod("INTEGRATION_TTN"); descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId)); descriptor.setDashboardId(dashboardId); - descriptor.setInstallState(Map.of()); + // The package created these entities + descriptor.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"), + "Dashboard", stateOf(dashboardId, "created"), "Integration", stateOf(integrationId, "created"))); installedItem = new IotHubInstalledItem(); installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID())); installedItem.setTenantId(tenantId); @@ -273,6 +275,32 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId); } + @Test + void useExistingAtInstall_staysUseExisting() { + // At install the user picked their own dashboard: the install adds it to createdEntityIds too + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); + DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + step.setResolution("use-existing"); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isTrue(); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing"); + } + + @Test + void overwritingAnEntityUsedAtInstall_needsAConfirmation() { + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); + DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isFalse(); + verify(installedItemService, never()).save(any(), any()); + } + @Test void twoStepsWithOneKey_areRejected() { DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); @@ -593,4 +621,11 @@ class DefaultDevicePackageUpdateServiceTest { return step; } + + private static ObjectNode stateOf(EntityId id, String resolution) { + ObjectNode state = JacksonUtil.newObjectNode().put("resolution", resolution); + state.set("entityOutput", JacksonUtil.newObjectNode().put("id", id.getId().toString())); + return state; + } + } 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 77fef10a5e..5085d7fc96 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 @@ -2429,9 +2429,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } - /** Update: true when the entity is one the installed package created. */ + /** + * Update: true when the entity is one the installed package owns: its install state records it, and not as one + * the user chose to use as it was. Not createdEntityIds: the install adds the use-existing ones to it too. + */ private isPackageEntity(id: string): boolean { - return !!this.data.update?.descriptor.createdEntityIds?.some(created => created.id === id); + return Object.values(this.data.update?.descriptor.installState ?? {}) + .some(state => state?.entityOutput?.id === id && state.resolution !== 'use-existing'); } /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ From 50eff0dd15667da9e07eafa2086d7bce9052e6d9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:37:10 +0200 Subject: [PATCH 19/24] fix(iot-hub): keep the used-existing ids, check shared entities against every package's checksums, fix the default converter review --- .../DefaultDevicePackageUpdateService.java | 82 +++++++++--------- ...DefaultDevicePackageUpdateServiceTest.java | 71 +++++++++++++++- .../DeviceInstalledItemDescriptor.java | 2 + .../src/app/core/http/iot-hub-api.service.ts | 2 +- .../device-install-dialog.component.ts | 84 ++++++++++++++++--- .../iot-hub/iot-hub-default-converter.ts | 9 ++ ...iot-hub-installed-items-table.component.ts | 8 +- .../iot-hub/iot-hub-installed-item.models.ts | 2 + 8 files changed, 203 insertions(+), 57 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 5ab98c932e..c8dd0e69f8 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 @@ -137,6 +137,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i Set sharedIds = new HashSet<>(); iotHubService.findKeptEntities(tenantId, installedItemId).getEntities().forEach(e -> sharedIds.add(e.getEntityId().getId())); Map createdIds = createdIds(descriptor); + Map> recordedChecksums = recordedChecksums(tenantId); List states = new ArrayList<>(); if (descriptor.getInstallState() == null) { @@ -149,8 +150,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } DevicePackageEntities.Snapshot snapshot = packageEntities.load(tenantId, entityId); JsonNode storedChecksum = state.get("checksum"); + // Changed by someone else only when no installed package recorded the current checksum: an update of another + // package that shares the entity, e.g. a converter, records it only in its own row Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null : - !storedChecksum.asText().equals(snapshot.checksum()); + !storedChecksum.asText().equals(snapshot.checksum()) + && !recordedChecksums.getOrDefault(entityId.getId(), Set.of()).contains(snapshot.checksum()); states.add(new DevicePackageEntityState(stepName, entityId, snapshot != null, snapshot != null ? snapshot.version() : null, modified, sharedIds.contains(entityId.getId()))); }); @@ -285,11 +289,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }); } List stepEntityIds = new ArrayList<>(); + Map usedExistingIds = usedExistingIds(previous); List saved = new ArrayList<>(); List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); // The checksums of the entities this update overwrote, which other packages may record too - Map overwrittenChecksums = new HashMap<>(); DashboardId dashboardId = null; for (DeviceUpdateRequest.Step step : request.getSteps()) { @@ -321,12 +325,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (step.isDefaultConverter()) { state.put("defaultConverter", true); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && result.checksum() != null) { - overwrittenChecksums.put(result.entityId().getId(), result.checksum()); - } installState.put(step.getId() != null ? step.getId() : step.getName(), state); if (!"use-existing".equals(resolution)) { stepEntityIds.add(result.entityId()); + } else { + usedExistingIds.putIfAbsent(result.entityId().getId(), result.entityId()); } if (result.entityId() instanceof DashboardId id) { dashboardId = id; @@ -349,6 +352,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // The new version may not offer the method the package was installed with descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod()); descriptor.setCreatedEntityIds(createdEntityIds(tenantId, previous, stepEntityIds)); + // Carried over like createdEntityIds, so an entity the user chose to use stays theirs after a version drops its step + Set tracked = createdIds(descriptor).keySet(); + descriptor.setUsedExistingEntityIds(usedExistingIds.values().stream().filter(id -> tracked.contains(id.getId())).toList()); descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous)); Map state = new LinkedHashMap<>(installState); descriptor.setInstallState(state); @@ -358,45 +364,33 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i installedItem.setVersion(versionInfo.get("version").asText()); installedItem.setDescriptor(descriptor); installedItemService.save(tenantId, installedItem); - refreshChecksumsOfOtherPackages(tenantId, installedItem.getId(), overwrittenChecksums); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); } - /** - * Another package that recorded the checksum of an entity this update overwrote, e.g. a shared converter, records the - * new one: the update was confirmed for all packages using the entity, so their next update sees no change by someone else. - */ - private void refreshChecksumsOfOtherPackages(TenantId tenantId, IotHubInstalledItemId installedItemId, Map checksums) { - if (checksums.isEmpty()) { - return; - } + /** The checksums the installed device packages recorded, by entity. */ + private Map> recordedChecksums(TenantId tenantId) { + Map> checksums = new HashMap<>(); PageLink pageLink = new PageLink(100); PageData page; do { page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); for (IotHubInstalledItem item : page.getData()) { - if (!item.getId().equals(installedItemId) && item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor - && descriptor.getInstallState() != null && refreshChecksums(descriptor.getInstallState(), checksums)) { - installedItemService.save(tenantId, item); + if (item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor && descriptor.getInstallState() != null) { + descriptor.getInstallState().values().forEach(state -> { + UUID id = toUuid(state.path("entityOutput").path("id").asText()); + JsonNode checksum = state.get("checksum"); + if (id != null && checksum != null && checksum.isTextual()) { + checksums.computeIfAbsent(id, k -> new HashSet<>()).add(checksum.asText()); + } + }); } } pageLink = pageLink.nextPageLink(); } while (page.hasNext()); - } - - private static boolean refreshChecksums(Map installState, Map checksums) { - boolean changed = false; - for (JsonNode state : installState.values()) { - String checksum = checksums.get(toUuid(state.path("entityOutput").path("id").asText())); - if (checksum != null && state.has("checksum") && state instanceof ObjectNode objectState) { - objectState.put("checksum", checksum); - changed = true; - } - } - return changed; + return checksums; } private static UUID toUuid(String id) { @@ -841,19 +835,31 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The entities the package owns: those its install state records, except the ones the user chose to use as they - * were. Not createdEntityIds: the install adds the use-existing ones to it too. + * The entities the package owns: those it created, not the ones the user chose to use as they were. The install adds + * those to createdEntityIds too, so they are subtracted; an entity of a step a later version dropped stays owned. */ private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) { - Set ids = new HashSet<>(); + Set ids = new HashSet<>(createdIds(descriptor).keySet()); + ids.removeAll(usedExistingIds(descriptor).keySet()); + return ids; + } + + /** + * The entities the user chose to use as they were. An install made before the descriptor kept them has them only in + * its install state, which the first update carries over into the descriptor. + */ + private static Map usedExistingIds(DeviceInstalledItemDescriptor descriptor) { + Map ids = new LinkedHashMap<>(); + if (descriptor.getUsedExistingEntityIds() != null) { + descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id)); + return ids; + } + Map createdIds = createdIds(descriptor); if (descriptor.getInstallState() != null) { descriptor.getInstallState().values().forEach(state -> { - JsonNode id = state.path("entityOutput").path("id"); - if (id.isTextual() && !"use-existing".equals(state.path("resolution").asText())) { - try { - ids.add(UUID.fromString(id.asText())); - } catch (IllegalArgumentException ignored) { - } + UUID id = toUuid(state.path("entityOutput").path("id").asText()); + if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) { + ids.put(id, createdIds.get(id)); } }); } 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 06d0109b82..2f7e4f57b0 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 @@ -117,6 +117,8 @@ class DefaultDevicePackageUpdateServiceTest { private SubscriptionService subscriptionService; @Mock private TelemetrySubscriptionService telemetryService; + @Mock + private IotHubService iotHubService; @InjectMocks private DefaultDevicePackageUpdateService service; @@ -301,6 +303,67 @@ class DefaultDevicePackageUpdateServiceTest { verify(installedItemService, never()).save(any(), any()); } + @Test + void sharedEntityOverwrittenByAnotherPackage_isNotChangedBySomeoneElse() { + Dashboard shared = dashboard(9L); + DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); + when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0)); + // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one + ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); + IotHubInstalledItem other = otherPackage(Map.of("Dashboard", stateOf(dashboardId, "created").put("checksum", snapshot.checksum()))); + when(installedItemService.findByTenantId(any(), any(), any(), any())) + .thenReturn(new PageData<>(List.of(installedItem, other), 1, 2, false)); + + assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isFalse(); + + shared.setConfiguration(JacksonUtil.newObjectNode().put("description", "Changed by hand")); + assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isTrue(); + } + + @Test + void entityOfAStepAVersionDropped_staysThePackages() { + // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); + DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + step.setResolution("use-existing"); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isTrue(); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created"); + } + + @Test + void entityUsedAtInstall_staysTheUsersAfterAVersionDropsItsStep() { + // Recorded at install; the step is gone from the install state since + DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + installed.setUsedExistingEntityIds(List.of(dashboardId)); + installed.setInstallState(Map.of()); + DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + + assertThat(result.isSuccess()).isFalse(); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void entitiesUsedAtInstall_areCarriedIntoTheDescriptor() { + // Installed before the descriptor kept them: the install state has them + ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); + when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + + assertThat(result.isSuccess()).isTrue(); + assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); + } + @Test void twoStepsWithOneKey_areRejected() { DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); @@ -381,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest { } @Test - void overwrittenSharedConverter_isRecordedAsDefaultAndOtherPackagesTakeItsChecksum() { + void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() { ConverterId converterId = new ConverterId(UUID.randomUUID()); Converter current = new Converter(converterId); current.setTenantId(tenantId); @@ -408,9 +471,9 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); assertThat(state.get("defaultConverter").asBoolean()).isTrue(); - assertThat(created.get("checksum").asText()).isEqualTo(state.get("checksum").asText()); - assertThat(usedExisting.has("checksum")).isFalse(); - verify(installedItemService).save(tenantId, creator); + // The other packages keep what they recorded: check() takes the checksum of any installed package + assertThat(created.get("checksum").asText()).isEqualTo("before"); + verify(installedItemService, never()).save(tenantId, creator); verify(installedItemService, never()).save(tenantId, taker); } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java index c7f5583291..25734fae2d 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java @@ -14,6 +14,8 @@ import java.util.Map; public class DeviceInstalledItemDescriptor implements IotHubInstalledItemDescriptor { private List createdEntityIds; + // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them + private List usedExistingEntityIds; private DashboardId dashboardId; private String selectedInstallMethod; private Map installState; diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 1bf462ce35..fa040e8632 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -179,7 +179,7 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, - descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, + descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, config?: IotHubRequestConfig ): Observable { return this.http.post( 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 5085d7fc96..195e5e0e3b 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,7 +18,8 @@ import { DeviceInstalledItemDescriptor, DevicePackageEntityState, DeviceUpdateResult, - DeviceUpdateStep + DeviceUpdateStep, + IotHubInstalledItem } 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'; @@ -39,7 +40,8 @@ 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, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { PageData } from '@shared/models/page/page-data'; import { cleanFormFieldValue, DeviceInstallStep, @@ -1462,7 +1464,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent: does when the - * user kept the default profile name, isn't added. + * user kept the default profile name, isn't added, and an earlier value of it is removed: the name is the default again. */ private withStepMetadata(step: DeviceInstallStep, metadata: Record | 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('${') && value !== key.substring(key.indexOf('.') + 1)) { + if (!value || value.includes('${')) { + continue; + } + if (value === key.substring(key.indexOf('.') + 1)) { + delete merged[key]; + } else { merged[key] = value; } } @@ -2282,7 +2290,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent null) : null; if (converter) { const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, @@ -2348,7 +2361,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -2429,13 +2442,30 @@ 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: its install state records it, and not as one - * the user chose to use as it was. Not createdEntityIds: the install adds the use-existing ones to it too. + * Update: true when the entity is one the installed package owns: it created it, not the user chose to use it as it was. + * The same rule as the server's: createdEntityIds without usedExistingEntityIds, which an install made before the + * descriptor kept them has only in its install state. */ private isPackageEntity(id: string): boolean { - return Object.values(this.data.update?.descriptor.installState ?? {}) - .some(state => state?.entityOutput?.id === id && state.resolution !== 'use-existing'); + const descriptor = this.data.update?.descriptor; + const usedExisting = descriptor?.usedExistingEntityIds?.some(used => used.id === id) ?? + Object.values(descriptor?.installState ?? {}).some(state => state?.entityOutput?.id === id && state.resolution === 'use-existing'); + return !!descriptor?.createdEntityIds?.some(created => created.id === id) && !usedExisting; } /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ @@ -2478,7 +2508,23 @@ 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. */ @@ -2708,6 +2754,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); }; + +/** + * 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. + */ +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'); 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 765f563898..d4cf0d4df0 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, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; import { firstValueFrom } from 'rxjs'; @Component({ @@ -281,7 +281,11 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, for (const item of this.dataSource) { const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; for (const state of states) { - const id = state?.defaultConverter ? state.entityOutput?.id : undefined; + 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; + } const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) .catch(() => null) : null; if (converter) { 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 494605caf4..eb4776d107 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 @@ -30,6 +30,8 @@ export interface RuleChainInstalledItemDescriptor { export interface DeviceInstalledItemDescriptor { type: 'DEVICE'; createdEntityIds?: { entityType: string; id: string }[]; + // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them + usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { id: string }; selectedInstallMethod?: string; installState?: Record; From 31dda2cf4153452fc722290c5a595b13fd447240 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:51:31 +0200 Subject: [PATCH 20/24] 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; } From de40a36f125de4600887274018e31f8f8c589e71 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:53:41 +0200 Subject: [PATCH 21/24] fix(iot-hub): a kept integration gets the step's metadata, one default converter lookup, uninstall keeps use-existing entities --- .../service/iot_hub/DefaultIotHubService.java | 34 ++++++++++++++--- .../iot_hub/InstalledItemKeptEntities.java | 4 +- ...DefaultDevicePackageUpdateServiceTest.java | 2 +- .../iot_hub/DefaultIotHubServiceTest.java | 37 +++++++++++++++++++ .../iot-hub-delete-dialog.component.ts | 6 ++- .../iot-hub/iot-hub-installed-item.models.ts | 2 + .../assets/locale/locale.constant-en_US.json | 2 + 7 files changed, 78 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index dcc569b481..6968cbd00f 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -713,17 +713,24 @@ public class DefaultIotHubService implements IotHubService { /** * Deletes what a device package created, except the entities another installed device package - * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. + * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, + * and the ones the user had before and the package took as they were (use existing). */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, - List createdEntityIds, SecurityUser user) { + DeviceInstalledItemDescriptor descriptor, SecurityUser user) { + List createdEntityIds = descriptor.getCreatedEntityIds(); if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } + Set usedExisting = usedExistingIds(descriptor); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); List reversed = new ArrayList<>(createdEntityIds); Collections.reverse(reversed); for (EntityId entityId : reversed) { + if (usedExisting.contains(entityId.getId())) { + log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); + continue; + } Set usedBy = usedByOtherPackages.get(entityId.getId()); if (usedBy != null) { log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); @@ -746,17 +753,34 @@ public class DefaultIotHubService implements IotHubService { } List kept = new ArrayList<>(); Set usedByItems = new HashSet<>(); + int usedExistingCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { + Set usedExisting = usedExistingIds(dd); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); - if (usedBy != null) { + boolean taken = usedExisting.contains(entityId.getId()); + if (usedBy != null || taken) { kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); + } + if (usedBy != null) { usedByItems.addAll(usedBy); } + if (taken) { + usedExistingCount++; + } } } - return new InstalledItemKeptEntities(kept, usedByItems.size()); + return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount); + } + + /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */ + private static Set usedExistingIds(DeviceInstalledItemDescriptor descriptor) { + Set ids = new HashSet<>(); + if (descriptor.getUsedExistingEntityIds() != null) { + descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId())); + } + return ids; } private Map> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -854,7 +878,7 @@ public class DefaultIotHubService implements IotHubService { } } } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { - deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); + deleteDevicePackageEntities(tenantId, installedItemId, dd, user); } else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) { try { solutionService.deleteSolution(tenantId, st, user); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index 021cfe5be5..ad517c5327 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -9,7 +9,7 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; -/** What deleting an installed item keeps, because other installed items use it too. */ +/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ @Data @NoArgsConstructor @AllArgsConstructor @@ -18,6 +18,8 @@ public class InstalledItemKeptEntities { private List entities; // How many other installed items use at least one of the kept entities private int usedByItemsCount; + // How many of the kept entities the user had before and the package took as they were (use existing) + private int usedExistingCount; @Data @NoArgsConstructor 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 76bad73451..316732253c 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 @@ -308,7 +308,7 @@ class DefaultDevicePackageUpdateServiceTest { Dashboard shared = dashboard(9L); DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); - when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0)); + when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0)); // This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 8cc1848797..938c816ed7 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -481,6 +481,43 @@ class DefaultIotHubServiceTest { assertThat(kept.getUsedByItemsCount()).isEqualTo(2); } + @Test + void deleteInstalledItem_devicePackage_keepsEntitiesTheUserHadBefore() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId usersDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem deleted = devicePackage(deviceId, usersDashboardId); + ((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId)); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + Device device = new Device(deviceId); + when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(tbDeviceService).delete(device, user); + verify(tbDashboardService, never()).delete(any(), any()); + } + + @Test + void findKeptEntities_devicePackage_namesTheEntitiesTheUserHadBefore() { + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + DashboardId usersDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(deviceId, usersDashboardId); + ((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId)); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard")); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(usersDashboardId, "My dashboard")); + assertThat(kept.getUsedByItemsCount()).isZero(); + assertThat(kept.getUsedExistingCount()).isEqualTo(1); + } + @Test void findKeptEntities_devicePackageSharingNothing_keepsNothing() { IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID())); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 81d13800d3..08ae924eb6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -45,8 +45,10 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); - this.description = this.translate.instant('iot-hub.remove-desc-kept', - { count: kept.usedByItemsCount, kept: kept.entities.length }); + // Kept because other packages use them, because the user had them before the package, or both + const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' : + !kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used'; + this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length }); } else { this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); } 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 882c97f9c5..2ca0603a37 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 @@ -166,6 +166,8 @@ export interface IotHubKeptEntity { export interface IotHubInstalledItemKeptEntities { entities: IotHubKeptEntity[]; usedByItemsCount: number; + // Of the kept entities, the ones the user had before and the package took as they were + usedExistingCount: number; } export interface IotHubInstalledItem extends BaseData<{id: string}> { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 68a0906635..ca933a9b36 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6405,6 +6405,8 @@ "remove": "Remove", "remove-confirm-title": "Remove '{{name}}'?", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", + "remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:", + "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity} other {entities} } will not be removed, because you had them before the package was installed or { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } them:", "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From f2d4872688e0a1f91b524885867b3f00603b4e99 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 12:08:30 +0200 Subject: [PATCH 22/24] fix(iot-hub): merge metadata into a copy of the integration, lock the metadata fields on update, plural of the kept text --- .../DefaultDevicePackageUpdateService.java | 30 +++++++++++-------- ...DefaultDevicePackageUpdateServiceTest.java | 3 ++ .../device-install-dialog.component.ts | 20 +++++++++++++ .../assets/locale/locale.constant-en_US.json | 2 +- 4 files changed, 42 insertions(+), 13 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 399e46f6ac..2bbed29280 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,8 +587,9 @@ 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); + Integration merged = withMergedMetadata(current, step.getMetadata()); + if (merged != null) { + Integration result = integrationService.saveIntegration(merged); return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); } return new StepResult(id, integrationOutput(current), null, null); @@ -611,14 +612,18 @@ 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) { + /** + * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. + * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + */ + private static Integration withMergedMetadata(Integration integration, JsonNode entries) { if (entries == null || !entries.isObject() || entries.isEmpty()) { - return false; + return null; } - 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(); + Integration copy = new Integration(integration); + ObjectNode configuration = copy.getConfiguration() instanceof ObjectNode current ? current : JacksonUtil.newObjectNode(); + JsonNode before = configuration.get("metadata"); + ObjectNode metadata = before instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode(); entries.fields().forEachRemaining(entry -> { if (entry.getValue() == null || entry.getValue().isNull()) { metadata.remove(entry.getKey()); @@ -626,14 +631,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i metadata.put(entry.getKey(), entry.getValue().asText()); } }); - if (metadata.equals(configuration.get("metadata")) || (metadata.isEmpty() && configuration.get("metadata") == null)) { - return false; + if (metadata.equals(before) || (metadata.isEmpty() && before == null)) { + return null; } configuration.set("metadata", metadata); - integration.setConfiguration(configuration); - return true; + copy.setConfiguration(configuration); + return copy; } + /** * 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/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 316732253c..062eabf80f 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 @@ -392,6 +392,9 @@ class DefaultDevicePackageUpdateServiceTest { 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(); + // A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit + assertThat(saved.getValue()).isNotSameAs(current); + assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText()) .isEqualTo("use-existing"); } 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 f049ee97b8..ca92919b5b 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 @@ -1247,6 +1247,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent locked.has(field.key) ? { ...field, readOnly: true, resettable: false } : field); } for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); @@ -1862,6 +1866,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const keys = new Set(); + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { + if (step.type !== InstallStepType.INTEGRATION) { + continue; + } + for (const [key, value] of Object.entries(step.metadata ?? {})) { + for (const match of `${key} ${value ?? ''}`.matchAll(/\$\{([^}.]+)}/g)) { + keys.add(match[1]); + } + } + } + return keys; + } + private integrationMetadataOf(step: DeviceInstallStep): Record | undefined { return step.type === InstallStepType.INTEGRATION && step.metadata ? this.stepMetadataEntries(step) : undefined; } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index ca933a9b36..598b051e0e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6406,7 +6406,7 @@ "remove-confirm-title": "Remove '{{name}}'?", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", "remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:", - "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity} other {entities} } will not be removed, because you had them before the package was installed or { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } them:", + "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From 4f0151542fbfb30c9a37df4063293d4ac0bcc027 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 12:33:46 +0200 Subject: [PATCH 23/24] fix(iot-hub): check the update again after any way back, check default converters in parallel and keep the latest run --- .../device-install-dialog.component.ts | 20 ++++++--- ...iot-hub-installed-items-table.component.ts | 41 ++++++++++++------- 2 files changed, 41 insertions(+), 20 deletions(-) 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 ca92919b5b..54dfc3e218 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 @@ -555,6 +555,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.resetUpdatePlan(ws)); + } return; } // Forward moves can come from the stepper header, which bypasses nextStep(), 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 a99fc65a66..2677ec1cbe 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 @@ -74,6 +74,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, publishedVersionMap = new Map(); // Installed device packages whose default converter differs from ThingsBoard's default converter now converterUpdates = new Set(); + private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; @@ -277,35 +278,47 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, * ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it. */ private async checkConverterUpdates(): Promise { - const updates = new Set(); + // A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win + const run = ++this.converterCheckRun; + // The package's default converter of each DEVICE package on the page + const checks: { itemId: string; converterId: string }[] = []; // 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; + const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; + if (!id) { + continue; + } // A converter taken as it was counts only when a package installed it as its default converter - if (id && state.resolution === 'use-existing') { + if (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; - if (converter) { - const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, - converter.configuration.scriptLang, converter.name); - if (defaultConverter && differsFromDefaultConverter(converter, defaultConverter)) { - updates.add(item.id.id); + continue; } } + checks.push({ itemId: item.id.id, converterId: id }); } } - this.converterUpdates = updates; + const changed = await Promise.all(checks.map(async ({ itemId, converterId }) => { + const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true})) + .catch(() => null); + if (!converter) { + return null; + } + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ? itemId : null; + })); + if (run !== this.converterCheckRun) { + return; + } + this.converterUpdates = new Set(changed.filter(itemId => !!itemId)); this.cd.markForCheck(); } + getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { return this.publishedVersionMap.get(item.itemId); } From af75897c2530f388cf5178b22d7b08c4ba4ff599 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 13:37:39 +0200 Subject: [PATCH 24/24] fix(iot-hub): drop the result of an update check the user went back from --- .../device-install-dialog.component.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) 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 54dfc3e218..9f79cbb59d 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 @@ -370,6 +370,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); // Update: for each step with "default": true, whether its converter differs from ThingsBoard's default one now private defaultConverterChanges = new Map(); + // Update: the check of the update in progress; a way back meanwhile starts a new one, which drops this one's result + private updateCheckRun = 0; // Variable resolution state formValues: Record = {}; @@ -557,7 +559,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const run = ++this.updateCheckRun; // Templates refer to the package's entities, e.g. ${deviceProfile.id}: until the steps run, the installed ones this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false); ws.entitySteps = ws.rawSteps.map(s => ({ @@ -2600,9 +2608,16 @@ export class TbDeviceInstallDialogComponent extends DialogComponent [state.stepName, state])); const plans = await Promise.all(ws.entitySteps.map(ep => this.planEntityStep(ep))); + if (run !== this.updateCheckRun) { + // The user went back meanwhile: the plan is of the form values before + return; + } ws.entitySteps.forEach((ep, i) => this.entityPlans.set(ep, plans[i])); this.overwriteReferencesToCreated(ws); } catch (e: any) { + if (run !== this.updateCheckRun) { + return; + } ws.progressError = this.failureMessage(e); } ws.checking = false;