diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index 90c2888a51..e973ee13dc 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -4,13 +4,17 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import delight.nashornsandbox.NashornSandbox; +import delight.nashornsandbox.NashornSandboxes; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.TbStopWatch; +import org.thingsboard.script.api.RuleNodeScriptFactory; import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.TbScriptException; import org.thingsboard.script.api.js.NashornJsInvokeService; @@ -18,6 +22,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; @@ -209,6 +214,87 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { }); } + @Test + void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { + UUID scriptId = evalScript("return msg;"); + String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(true); + + invokeService.release(scriptId).get(); + + // the property must be deleted, not just set to undefined: an abandoned binding keeps + // its slot in the Global's PropertyMap forever + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(false); + } + + @Test + void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception { + UUID scriptId = evalScript("return {doubled: msg.temperature * 2};"); + assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42"); + } + + @Test + void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception { + UUID writer = evalScript("compatSharedState = 777; return msg;"); + UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};"); + invokeScript(writer, "{}"); + assertThat(invokeScript(reader, "{}")).contains("\"seen\":777"); + } + + @Test + void givenIifeWrappedEval_thenCompilationErrorUnchanged() { + String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;"; + + String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript, + "msg", "metadata", "msgType"); + NashornSandbox legacySandbox = NashornSandboxes.create(); + legacySandbox.allowNoBraces(false); + legacySandbox.allowLoadFunctions(true); + legacySandbox.setMaxPreparedStatements(30); + int legacyErrorLine = -1; + try { + legacySandbox.eval(legacyScript); + } catch (ScriptException e) { + legacyErrorLine = e.getLineNumber(); + } + assertThat(legacyErrorLine).isGreaterThan(0); + final int expectedLine = legacyErrorLine; + + assertThatThrownBy(() -> evalScript(badScript)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION); + assertThat(ex.getBody()).contains(badScript); + assertThat(ex.getCause()).isInstanceOf(ScriptException.class); + // The IIFE wrapper shifts sandbox-reported line numbers by a constant +2 + // (the beautifier splits the wrapper prefix onto its own lines). Reported + // lines never matched the user's source anyway (the sandbox instrumentation + // already offsets them), so only the small constant shift is tolerated here. + assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2); + }); + } + + @Test + void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception { + UUID scriptId = evalScript("return msg;"); + invokeScript(scriptId, "{}"); + invokeService.release(scriptId).get(); + assertThatThrownBy(() -> invokeScript(scriptId, "{}")) + .isInstanceOf(ExecutionException.class) + .hasMessageContaining("No compiled script found"); + } + + private Object evalInEngine(String expression) throws Exception { + Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox"); + if (sandbox != null) { + return ((NashornSandbox) sandbox).eval(expression); + } + return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScript(scriptId, "{}"); diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index cbdd753346..8075e70fe4 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -127,14 +127,22 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { @Override protected ListenableFuture doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) { + // A top-level function declaration creates a non-configurable property on the Nashorn Global + // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap + // shape history forever. Declaring the function inside an IIFE and assigning it to a global + // property keeps the property configurable, allowing doRelease() to actually delete it. + // The prefix stays on the first line to preserve line numbering on the raw engine path; + // the sandbox beautifier reformats the wrapper and shifts reported error lines anyway. + String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { try { evalLock.lock(); try { if (useJsSandbox) { - sandbox.eval(jsScript); + sandbox.eval(wrappedScript); } else { - engine.eval(jsScript); + engine.eval(wrappedScript); } } finally { evalLock.unlock(); @@ -169,10 +177,16 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { } protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { - if (useJsSandbox) { - sandbox.eval(scriptInfo.getFunctionName() + " = undefined;"); - } else { - engine.eval(scriptInfo.getFunctionName() + " = undefined;"); + String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; + evalLock.lock(); + try { + if (useJsSandbox) { + sandbox.eval(deleteScript); + } else { + engine.eval(deleteScript); + } + } finally { + evalLock.unlock(); } } diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java new file mode 100644 index 0000000000..673e06d5a8 --- /dev/null +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.script.api.js; + +import delight.nashornsandbox.NashornSandbox; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.script.api.ScriptType; +import org.thingsboard.script.api.TbScriptException; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.stats.StatsFactory; + +import javax.script.ScriptEngine; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +/** + * Covers the JS global scope lifecycle against both backends the service can be configured with. + * The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since + * {@code js.local.use_js_sandbox} defaults to true. + */ +class NashornJsInvokeServiceLifecycleTest { + + private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; + + private NashornJsInvokeService service; + private boolean useJsSandbox; + + @AfterEach + void tearDown() { + if (service != null) { + service.stop(); + } + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID scriptId = UUID.randomUUID(); + + JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); + assertThat(hasGlobalProperty(scriptInfo)).isTrue(); + assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); + + service.doRelease(scriptId); + + assertThat(hasGlobalProperty(scriptInfo)).isFalse(); + assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class); + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID releasedId = UUID.randomUUID(); + UUID retainedId = UUID.randomUUID(); + + JsScriptInfo released = eval(releasedId, "return {v: 1};"); + JsScriptInfo retained = eval(retainedId, "return {v: 2};"); + + service.doRelease(releasedId); + + assertThat(hasGlobalProperty(released)).isFalse(); + assertThat(hasGlobalProperty(retained)).isTrue(); + assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); + } + + private void givenService(boolean useJsSandbox) { + this.useJsSandbox = useJsSandbox; + service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); + ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); + ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); + ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); + ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); + ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); + ReflectionTestUtils.setField(service, "maxMemory", 104857600L); + service.init(); + } + + private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { + service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); + return service.scriptInfoMap.get(scriptId); + } + + private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { + return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); + } + + private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { + String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; + Object result = useJsSandbox + ? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) + : ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); + return Boolean.TRUE.equals(result); + } + +} 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 dacb092d36..236a039473 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 @@ -95,6 +95,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -357,7 +363,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + /** + * Fired whenever an install, update or delete changed what this tenant has installed, so a host + * page showing its own installed-items counter can refresh it instead of waiting for a reload. + */ + @Output() installedItemsChanged = new EventEmitter(); @Input() set activeType(value: ItemType) { if (value && value !== this._activeType) { const wasInit = !!this._activeType; @@ -627,7 +632,11 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy }); } - private reloadInstalledItems(): void { + /** + * Re-reads what is installed for the active type and announces the change. Public so a host page + * that opens the item detail dialog itself can refresh this grid through the same path. + */ + reloadInstalledItems(): void { const config = {ignoreLoading: true}; const pageLink = new PageLink(10000, 0); if (this.activeType === ItemType.WIDGET) { @@ -643,6 +652,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.installedItemCounts = counts; }); } + this.installedItemsChanged.emit(); } private loadFilterInfo(): void { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss index 2a946348ad..c25c67e729 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss @@ -3,6 +3,10 @@ $text-color: rgba(0,0,0,0.76); $link-color: #2a7dec; $copy-button-color: #2a7dec; +// Geometry of the copy icon chip, shared by the chip itself and by the space table +// cells reserve for it, so the two cannot drift apart. +$copy-icon-width: 38px; +$copy-icon-offset: 3px; $code-block-border-color: rgba(42, 125, 236, .2); $code-default-color: #212529; @@ -169,10 +173,10 @@ $gallery-border-hover-color: #2a7dec; div { background-color: #fff; position: absolute; - width: 38px; + width: $copy-icon-width; height: 28px; - top: 3px; - right: 3px; + top: $copy-icon-offset; + right: $copy-icon-offset; padding: 8px 10px 0; img { @@ -204,9 +208,30 @@ $gallery-border-hover-color: #2a7dec; } th, td { + // Long unbreakable tokens (logins, e-mails, passwords) must never overflow their + // own column. `anywhere` also drops the cell min-content width down to a single + // character, so auto layout can always squeeze the table into the available + // width instead of overflowing (and getting clipped by `overflow: hidden`). + overflow-wrap: break-word; // fallback for engines without `anywhere` + overflow-wrap: anywhere; + + // Text is not the only thing that can outgrow a column: a preformatted block keeps + // its whole line as min-content width, which auto layout cannot shrink, so the table + // would push past its container and get cut off by a host that hides horizontal + // overflow (iot-hub-item-detail-dialog's .dlg-body). Wrap it inside the cell instead. + // Prism sets `white-space: pre` on both the block and the code inside it, so both + // have to be relaxed for the cell to shrink. + pre, pre > code { + white-space: pre-wrap; + } + div.code-wrapper { display: inline-block; width: 100%; + // Reserve room for the absolutely positioned copy icon, plus the same gap on its + // far side, so the cell text does not run underneath it and the reservation + // follows the chip if its geometry ever changes. + padding-right: $copy-icon-width + 2 * $copy-icon-offset; button.clipboard-btn { top: -6px; @@ -275,11 +300,10 @@ $gallery-border-hover-color: #2a7dec; margin-top: 20px; margin-bottom: 20px; overflow: hidden; - table-layout: fixed; - - &.auto { - table-layout: auto; - } + // Columns are sized to their content: with fixed layout every column got the + // same width, so cells with long values (e-mails, logins, tokens) had to wrap + // mid-word while short columns kept a lot of unused space. + table-layout: auto; > thead { background-color: $table-header-background-color; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html index 59a42eab29..5787b5ecf0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html @@ -35,7 +35,8 @@ + [hideTabs]="true" + (installedItemsChanged)="loadInstalledCount()"> diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts index b89448be3c..07beff5559 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { TbIotHubBrowseComponent } from '@home/components/iot-hub/iot-hub-browse.component'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { PageLink } from '@shared/models/page/page-link'; @@ -83,6 +84,8 @@ export class TbIotHubItemsPageComponent implements OnInit { config: ItemTypePageConfig; installedItemsCount = 0; + @ViewChild(TbIotHubBrowseComponent) private browse: TbIotHubBrowseComponent; + constructor( private route: ActivatedRoute, private router: Router, @@ -109,7 +112,7 @@ export class TbIotHubItemsPageComponent implements OnInit { window.open(this.iotHubApiService.baseUrl + '/signup', '_blank'); } - private loadInstalledCount(): void { + loadInstalledCount(): void { this.iotHubApiService.getInstalledItemsCount(this.config.type, { ignoreLoading: true }).subscribe(count => { this.installedItemsCount = count; }); @@ -147,7 +150,13 @@ export class TbIotHubItemsPageComponent implements OnInit { 'default', true, openItem.preview - ).subscribe(); + ).subscribe(result => { + // The deep-linked dialog is opened by this page rather than by the grid, so its outcome + // has to be fed back in by hand — the grid then refreshes and announces the new count. + if (result === 'installed' || result === 'updated' || result === 'deleted') { + this.browse?.reloadInstalledItems(); + } + }); }); }