From 149275ef2b79b61d11e6b2795a0b8c4c16fdc043 Mon Sep 17 00:00:00 2001 From: ViacheslavKlimov Date: Thu, 29 Sep 2022 15:29:29 +0300 Subject: [PATCH 1/5] Limits for JS script body, input args and invocation result size --- .../script/AbstractJsInvokeService.java | 65 +++++++++-- .../service/script/JsInvokeService.java | 2 +- .../script/NashornJsInvokeService.java | 31 ++--- .../service/script/RemoteJsInvokeService.java | 12 ++ .../script/RuleNodeJsScriptEngine.java | 4 +- .../src/main/resources/thingsboard.yml | 6 + .../service/script/JsInvokeServiceTest.java | 106 ++++++++++++++++++ .../service/script/MockJsInvokeService.java | 2 +- 8 files changed, 202 insertions(+), 26 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java index eef49ae518..c44fa2e335 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java @@ -17,6 +17,7 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import lombok.extern.slf4j.Slf4j; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.data.ApiUsageRecordKey; @@ -30,9 +31,10 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import static java.lang.String.format; + /** * Created by ashvayka on 26.09.18. */ @@ -65,33 +67,45 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { @Override public ListenableFuture eval(TenantId tenantId, JsScriptType scriptType, String scriptBody, String... argNames) { if (apiUsageStateService.getApiUsageState(tenantId).isJsExecEnabled()) { + if (scriptBodySizeExceeded(scriptBody)) { + return error(format("Script body exceeds maximum allowed size of %s symbols", getMaxScriptBodySize())); + } UUID scriptId = UUID.randomUUID(); String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); String jsScript = generateJsScript(scriptType, functionName, scriptBody, argNames); return doEval(scriptId, functionName, jsScript); } else { - return Futures.immediateFailedFuture(new RuntimeException("JS Execution is disabled due to API limits!")); + return error("JS Execution is disabled due to API limits!"); } } @Override - public ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args) { + public ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args) { if (apiUsageStateService.getApiUsageState(tenantId).isJsExecEnabled()) { String functionName = scriptIdToNameMap.get(scriptId); if (functionName == null) { - return Futures.immediateFailedFuture(new RuntimeException("No compiled script found for scriptId: [" + scriptId + "]!")); + return error("No compiled script found for scriptId: [" + scriptId + "]!"); } if (!isDisabled(scriptId)) { + if (argsSizeExceeded(args)) { + return scriptExecutionError(scriptId, format("Script input arguments exceed maximum allowed total args size of %s symbols", getMaxTotalArgsSize())); + } apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.JS_EXEC_COUNT, 1); - return doInvokeFunction(scriptId, functionName, args); + return Futures.transformAsync(doInvokeFunction(scriptId, functionName, args), output -> { + String result = output.toString(); + if (resultSizeExceeded(result)) { + return scriptExecutionError(scriptId, format("Script invocation result exceeds maximum allowed size of %s symbols", getMaxResultSize())); + } + return Futures.immediateFuture(result); + }, MoreExecutors.directExecutor()); } else { String message = "Script invocation is blocked due to maximum error count " + getMaxErrors() + ", scriptId " + scriptId + "!"; log.warn(message); - return Futures.immediateFailedFuture(new RuntimeException(message)); + return error(message); } } else { - return Futures.immediateFailedFuture(new RuntimeException("JS Execution is disabled due to API limits!")); + return error("JS Execution is disabled due to API limits!"); } } @@ -120,6 +134,12 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { protected abstract long getMaxBlacklistDuration(); + protected abstract long getMaxTotalArgsSize(); + + protected abstract long getMaxResultSize(); + + protected abstract long getMaxScriptBodySize(); + protected void onScriptExecutionError(UUID scriptId, Throwable t, String scriptBody) { DisableListInfo disableListInfo = disabledFunctions.computeIfAbsent(scriptId, key -> new DisableListInfo()); log.warn("Script has exception and will increment counter {} on disabledFunctions for id {}, exception {}, cause {}, scriptBody {}", @@ -127,6 +147,27 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { disableListInfo.incrementAndGet(); } + private boolean scriptBodySizeExceeded(String scriptBody) { + if (getMaxScriptBodySize() <= 0) return false; + return scriptBody.length() > getMaxScriptBodySize(); + } + + private boolean argsSizeExceeded(Object[] args) { + if (getMaxTotalArgsSize() <= 0) return false; + long totalArgsSize = 0; + for (Object arg : args) { + if (arg instanceof CharSequence) { + totalArgsSize += ((CharSequence) arg).length(); + } + } + return totalArgsSize > getMaxTotalArgsSize(); + } + + private boolean resultSizeExceeded(String result) { + if (getMaxResultSize() <= 0) return false; + return result.length() > getMaxResultSize(); + } + private String generateJsScript(JsScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == JsScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); @@ -148,6 +189,16 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { } } + private ListenableFuture error(String message) { + return Futures.immediateFailedFuture(new RuntimeException(message)); + } + + private ListenableFuture scriptExecutionError(UUID scriptId, String errorMsg) { + RuntimeException error = new RuntimeException(errorMsg); + onScriptExecutionError(scriptId, error, null); + return Futures.immediateFailedFuture(error); + } + private class DisableListInfo { private final AtomicInteger counter; private long expirationTime; diff --git a/application/src/main/java/org/thingsboard/server/service/script/JsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/JsInvokeService.java index 3e5d014bef..f9af2f83e4 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/JsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/JsInvokeService.java @@ -25,7 +25,7 @@ public interface JsInvokeService { ListenableFuture eval(TenantId tenantId, JsScriptType scriptType, String scriptBody, String... argNames); - ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args); + ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args); ListenableFuture release(UUID scriptId); diff --git a/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java index 5d64017f33..8d794ab24d 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.service.script; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -32,18 +33,33 @@ public class NashornJsInvokeService extends AbstractNashornJsInvokeService { @Value("${js.local.use_js_sandbox}") private boolean useJsSandbox; + @Getter @Value("${js.local.monitor_thread_pool_size}") private int monitorThreadPoolSize; + @Getter @Value("${js.local.max_cpu_time}") private long maxCpuTime; + @Getter @Value("${js.local.max_errors}") private int maxErrors; @Value("${js.local.max_black_list_duration_sec:60}") private int maxBlackListDurationSec; + @Getter + @Value("${js.local.max_total_args_size:100000}") + private long maxTotalArgsSize; + + @Getter + @Value("${js.local.max_result_size:300000}") + private long maxResultSize; + + @Getter + @Value("${js.local.max_script_body_size:50000}") + private long maxScriptBodySize; + public NashornJsInvokeService(TbApiUsageStateService apiUsageStateService, TbApiUsageClient apiUsageClient, JsExecutorService jsExecutor) { super(apiUsageStateService, apiUsageClient, jsExecutor); } @@ -53,21 +69,6 @@ public class NashornJsInvokeService extends AbstractNashornJsInvokeService { return useJsSandbox; } - @Override - protected int getMonitorThreadPoolSize() { - return monitorThreadPoolSize; - } - - @Override - protected long getMaxCpuTime() { - return maxCpuTime; - } - - @Override - protected int getMaxErrors() { - return maxErrors; - } - @Override protected long getMaxBlacklistDuration() { return TimeUnit.SECONDS.toMillis(maxBlackListDurationSec); diff --git a/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java index 86b364afd4..12f99b9e12 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java @@ -70,6 +70,18 @@ public class RemoteJsInvokeService extends AbstractJsInvokeService { @Value("${js.remote.stats.enabled:false}") private boolean statsEnabled; + @Getter + @Value("${js.remote.max_total_args_size:100000}") + private long maxTotalArgsSize; + + @Getter + @Value("${js.remote.max_result_size:300000}") + private long maxResultSize; + + @Getter + @Value("${js.remote.max_script_body_size:50000}") + private long maxScriptBodySize; + private final AtomicInteger queuePushedMsgs = new AtomicInteger(0); private final AtomicInteger queueInvokeMsgs = new AtomicInteger(0); private final AtomicInteger queueEvalMsgs = new AtomicInteger(0); diff --git a/application/src/main/java/org/thingsboard/server/service/script/RuleNodeJsScriptEngine.java b/application/src/main/java/org/thingsboard/server/service/script/RuleNodeJsScriptEngine.java index c90e104ff4..f1374711d5 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/RuleNodeJsScriptEngine.java +++ b/application/src/main/java/org/thingsboard/server/service/script/RuleNodeJsScriptEngine.java @@ -210,11 +210,11 @@ public class RuleNodeJsScriptEngine implements org.thingsboard.rule.engine.api.S return executeScriptAsync(msg.getCustomerId(), inArgs[0], inArgs[1], inArgs[2]); } - ListenableFuture executeScriptAsync(CustomerId customerId, Object... args) { + ListenableFuture executeScriptAsync(CustomerId customerId, String... args) { return Futures.transformAsync(sandboxService.invokeFunction(tenantId, customerId, this.scriptId, args), o -> { try { - return Futures.immediateFuture(mapper.readTree(o.toString())); + return Futures.immediateFuture(mapper.readTree(o)); } catch (Exception e) { if (e.getCause() instanceof ScriptException) { return Futures.immediateFailedFuture(e.getCause()); diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 9edd5d0ed5..3cbb2750a5 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -603,6 +603,9 @@ js: max_requests_timeout: "${LOCAL_JS_MAX_REQUEST_TIMEOUT:0}" # Maximum time in seconds for black listed function to stay in the list. max_black_list_duration_sec: "${LOCAL_JS_SANDBOX_MAX_BLACKLIST_DURATION_SEC:60}" + max_total_args_size: "${LOCAL_JS_SANDBOX_MAX_TOTAL_ARGS_SIZE:100000}" + max_result_size: "${LOCAL_JS_SANDBOX_MAX_RESULT_SIZE:300000}" + max_script_body_size: "${LOCAL_JS_SANDBOX_MAX_SCRIPT_BODY_SIZE:50000}" stats: enabled: "${TB_JS_LOCAL_STATS_ENABLED:false}" print_interval_ms: "${TB_JS_LOCAL_STATS_PRINT_INTERVAL_MS:10000}" @@ -612,6 +615,9 @@ js: max_errors: "${REMOTE_JS_SANDBOX_MAX_ERRORS:3}" # Maximum time in seconds for black listed function to stay in the list. max_black_list_duration_sec: "${REMOTE_JS_SANDBOX_MAX_BLACKLIST_DURATION_SEC:60}" + max_total_args_size: "${REMOTE_JS_SANDBOX_MAX_TOTAL_ARGS_SIZE:100000}" + max_result_size: "${REMOTE_JS_SANDBOX_MAX_RESULT_SIZE:300000}" + max_script_body_size: "${REMOTE_JS_SANDBOX_MAX_SCRIPT_BODY_SIZE:50000}" stats: enabled: "${TB_JS_REMOTE_STATS_ENABLED:false}" print_interval_ms: "${TB_JS_REMOTE_STATS_PRINT_INTERVAL_MS:10000}" diff --git a/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java new file mode 100644 index 0000000000..d382340a56 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java @@ -0,0 +1,106 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.script; + +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.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +@DaoSqlTest +@TestPropertySource(properties = { + "js.local.max_script_body_size=50", + "js.local.max_total_args_size=50", + "js.local.max_result_size=50", + "js.local.max_errors=2" +}) +class JsInvokeServiceTest extends AbstractControllerTest { + + @Autowired + private NashornJsInvokeService jsInvokeService; + + @Value("${js.local.max_errors}") + private int maxJsErrors; + + @Test + void givenTooBigScriptForEval_thenReturnError() { + String hugeScript = "var a = 'qwertyqwertywertyqwabababer'; return {a: a};"; + + assertThatThrownBy(() -> { + evalScript(hugeScript); + }).hasMessageContaining("body exceeds maximum allowed size"); + } + + @Test + void givenTooBigScriptForEval_whenMaxScriptBodySizeSetToZero_thenDoNothing() { + String script = "var a = 'a'; return { a: a };"; + + assertDoesNotThrow(() -> { + evalScript(script); + }); + } + + @Test + void givenTooBigScriptInputArgs_thenReturnErrorAndReportScriptExecutionError() throws Exception { + String script = "return { msg: msg };"; + String hugeMsg = "{\"input\":\"123456781234349\"}"; + UUID scriptId = evalScript(script); + + for (int i = 0; i < maxJsErrors; i++) { + assertThatThrownBy(() -> { + invokeScript(scriptId, hugeMsg); + }).hasMessageContaining("input arguments exceed maximum"); + } + assertThatScriptIsBlocked(scriptId); + } + + @Test + void whenScriptInvocationResultIsTooBig_thenReturnErrorAndReportScriptExecutionError() throws Exception { + String script = "var s = new Array(50).join('a'); return { s: s};"; + UUID scriptId = evalScript(script); + + for (int i = 0; i < maxJsErrors; i++) { + assertThatThrownBy(() -> { + invokeScript(scriptId, "{}"); + }).hasMessageContaining("result exceeds maximum allowed size"); + } + assertThatScriptIsBlocked(scriptId); + } + + private void assertThatScriptIsBlocked(UUID scriptId) { + assertThatThrownBy(() -> { + invokeScript(scriptId, "{}"); + }).hasMessageContaining("invocation is blocked due to maximum error"); + } + + private UUID evalScript(String script) throws ExecutionException, InterruptedException { + return jsInvokeService.eval(TenantId.SYS_TENANT_ID, JsScriptType.RULE_NODE_SCRIPT, script).get(); + } + + private String invokeScript(UUID scriptId, String msg) throws ExecutionException, InterruptedException { + return jsInvokeService.invokeFunction(TenantId.SYS_TENANT_ID, null, scriptId, msg, "{}", "POST_TELEMETRY_REQUEST").get(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java b/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java index 17803bac96..1d91f50131 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java +++ b/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java @@ -37,7 +37,7 @@ public class MockJsInvokeService implements JsInvokeService { } @Override - public ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args) { + public ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args) { log.warn("invokeFunction {} {} {} {}", tenantId, customerId, scriptId, args); return Futures.immediateFuture("{}"); } From f8b10fd587f8661a5f5c316515ff22b82e874a3b Mon Sep 17 00:00:00 2001 From: ViacheslavKlimov Date: Thu, 29 Sep 2022 17:42:55 +0300 Subject: [PATCH 2/5] Remove useless test from JsInvokeServiceTest --- .../server/service/script/JsInvokeServiceTest.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java index d382340a56..33d16531ac 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java @@ -53,15 +53,6 @@ class JsInvokeServiceTest extends AbstractControllerTest { }).hasMessageContaining("body exceeds maximum allowed size"); } - @Test - void givenTooBigScriptForEval_whenMaxScriptBodySizeSetToZero_thenDoNothing() { - String script = "var a = 'a'; return { a: a };"; - - assertDoesNotThrow(() -> { - evalScript(script); - }); - } - @Test void givenTooBigScriptInputArgs_thenReturnErrorAndReportScriptExecutionError() throws Exception { String script = "return { msg: msg };"; From a2c830ce8a17b85df0df6ad8f3c775ecbf788c16 Mon Sep 17 00:00:00 2001 From: ViacheslavKlimov Date: Mon, 3 Oct 2022 14:23:02 +0300 Subject: [PATCH 3/5] Refactoring for JS limit properties --- .../script/AbstractJsInvokeService.java | 18 ++++++++++++------ .../service/script/NashornJsInvokeService.java | 12 ------------ .../service/script/RemoteJsInvokeService.java | 12 ------------ application/src/main/resources/thingsboard.yml | 9 +++------ .../service/script/JsInvokeServiceTest.java | 7 +++---- 5 files changed, 18 insertions(+), 40 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java index c44fa2e335..0af1f4846b 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/AbstractJsInvokeService.java @@ -18,7 +18,9 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.data.ApiUsageRecordKey; import org.thingsboard.server.common.data.id.CustomerId; @@ -47,6 +49,16 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { protected Map scriptIdToNameMap = new ConcurrentHashMap<>(); protected Map disabledFunctions = new ConcurrentHashMap<>(); + @Getter + @Value("${js.max_total_args_size:100000}") + private long maxTotalArgsSize; + @Getter + @Value("${js.max_result_size:300000}") + private long maxResultSize; + @Getter + @Value("${js.max_script_body_size:50000}") + private long maxScriptBodySize; + protected AbstractJsInvokeService(TbApiUsageStateService apiUsageStateService, TbApiUsageClient apiUsageClient) { this.apiUsageStateService = apiUsageStateService; this.apiUsageClient = apiUsageClient; @@ -134,12 +146,6 @@ public abstract class AbstractJsInvokeService implements JsInvokeService { protected abstract long getMaxBlacklistDuration(); - protected abstract long getMaxTotalArgsSize(); - - protected abstract long getMaxResultSize(); - - protected abstract long getMaxScriptBodySize(); - protected void onScriptExecutionError(UUID scriptId, Throwable t, String scriptBody) { DisableListInfo disableListInfo = disabledFunctions.computeIfAbsent(scriptId, key -> new DisableListInfo()); log.warn("Script has exception and will increment counter {} on disabledFunctions for id {}, exception {}, cause {}, scriptBody {}", diff --git a/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java index 8d794ab24d..4b9e5dea57 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/NashornJsInvokeService.java @@ -48,18 +48,6 @@ public class NashornJsInvokeService extends AbstractNashornJsInvokeService { @Value("${js.local.max_black_list_duration_sec:60}") private int maxBlackListDurationSec; - @Getter - @Value("${js.local.max_total_args_size:100000}") - private long maxTotalArgsSize; - - @Getter - @Value("${js.local.max_result_size:300000}") - private long maxResultSize; - - @Getter - @Value("${js.local.max_script_body_size:50000}") - private long maxScriptBodySize; - public NashornJsInvokeService(TbApiUsageStateService apiUsageStateService, TbApiUsageClient apiUsageClient, JsExecutorService jsExecutor) { super(apiUsageStateService, apiUsageClient, jsExecutor); } diff --git a/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java b/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java index 12f99b9e12..86b364afd4 100644 --- a/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java +++ b/application/src/main/java/org/thingsboard/server/service/script/RemoteJsInvokeService.java @@ -70,18 +70,6 @@ public class RemoteJsInvokeService extends AbstractJsInvokeService { @Value("${js.remote.stats.enabled:false}") private boolean statsEnabled; - @Getter - @Value("${js.remote.max_total_args_size:100000}") - private long maxTotalArgsSize; - - @Getter - @Value("${js.remote.max_result_size:300000}") - private long maxResultSize; - - @Getter - @Value("${js.remote.max_script_body_size:50000}") - private long maxScriptBodySize; - private final AtomicInteger queuePushedMsgs = new AtomicInteger(0); private final AtomicInteger queueInvokeMsgs = new AtomicInteger(0); private final AtomicInteger queueEvalMsgs = new AtomicInteger(0); diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 3cbb2750a5..7b7fcfd774 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -589,6 +589,9 @@ state: js: evaluator: "${JS_EVALUATOR:local}" # local/remote + max_total_args_size: "${JS_MAX_TOTAL_ARGS_SIZE:100000}" + max_result_size: "${JS_MAX_RESULT_SIZE:300000}" + max_script_body_size: "${JS_MAX_SCRIPT_BODY_SIZE:50000}" # Built-in JVM JavaScript environment properties local: # Use Sandboxed (secured) JVM JavaScript environment @@ -603,9 +606,6 @@ js: max_requests_timeout: "${LOCAL_JS_MAX_REQUEST_TIMEOUT:0}" # Maximum time in seconds for black listed function to stay in the list. max_black_list_duration_sec: "${LOCAL_JS_SANDBOX_MAX_BLACKLIST_DURATION_SEC:60}" - max_total_args_size: "${LOCAL_JS_SANDBOX_MAX_TOTAL_ARGS_SIZE:100000}" - max_result_size: "${LOCAL_JS_SANDBOX_MAX_RESULT_SIZE:300000}" - max_script_body_size: "${LOCAL_JS_SANDBOX_MAX_SCRIPT_BODY_SIZE:50000}" stats: enabled: "${TB_JS_LOCAL_STATS_ENABLED:false}" print_interval_ms: "${TB_JS_LOCAL_STATS_PRINT_INTERVAL_MS:10000}" @@ -615,9 +615,6 @@ js: max_errors: "${REMOTE_JS_SANDBOX_MAX_ERRORS:3}" # Maximum time in seconds for black listed function to stay in the list. max_black_list_duration_sec: "${REMOTE_JS_SANDBOX_MAX_BLACKLIST_DURATION_SEC:60}" - max_total_args_size: "${REMOTE_JS_SANDBOX_MAX_TOTAL_ARGS_SIZE:100000}" - max_result_size: "${REMOTE_JS_SANDBOX_MAX_RESULT_SIZE:300000}" - max_script_body_size: "${REMOTE_JS_SANDBOX_MAX_SCRIPT_BODY_SIZE:50000}" stats: enabled: "${TB_JS_REMOTE_STATS_ENABLED:false}" print_interval_ms: "${TB_JS_REMOTE_STATS_PRINT_INTERVAL_MS:10000}" diff --git a/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java index 33d16531ac..8f0edd71c6 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/JsInvokeServiceTest.java @@ -27,13 +27,12 @@ import java.util.UUID; import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @DaoSqlTest @TestPropertySource(properties = { - "js.local.max_script_body_size=50", - "js.local.max_total_args_size=50", - "js.local.max_result_size=50", + "js.max_script_body_size=50", + "js.max_total_args_size=50", + "js.max_result_size=50", "js.local.max_errors=2" }) class JsInvokeServiceTest extends AbstractControllerTest { From 8d735f48868574cb3d5fe93431716de8f2008dab Mon Sep 17 00:00:00 2001 From: ViacheslavKlimov Date: Mon, 3 Oct 2022 15:22:11 +0300 Subject: [PATCH 4/5] Add script invocation result size check to remote JS executor --- msa/js-executor/api/jsInvokeMessageProcessor.ts | 17 ++++++++++++++--- .../config/custom-environment-variables.yml | 1 + msa/js-executor/config/default.yml | 1 + 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/msa/js-executor/api/jsInvokeMessageProcessor.ts b/msa/js-executor/api/jsInvokeMessageProcessor.ts index 0a101775e4..f1b60b6e07 100644 --- a/msa/js-executor/api/jsInvokeMessageProcessor.ts +++ b/msa/js-executor/api/jsInvokeMessageProcessor.ts @@ -43,6 +43,7 @@ const useSandbox = config.get('script.use_sandbox') === 'true'; const maxActiveScripts = Number(config.get('script.max_active_scripts')); const slowQueryLogMs = Number(config.get('script.slow_query_log_ms')); const slowQueryLogBody = config.get('script.slow_query_log_body') === 'true'; +const maxResultSize = Number(config.get('js.max_result_size')); export class JsInvokeMessageProcessor { @@ -164,9 +165,19 @@ export class JsInvokeMessageProcessor { (script) => { this.executor.executeScript(script, invokeRequest.args, invokeRequest.timeout).then( (result) => { - const invokeResponse = JsInvokeMessageProcessor.createInvokeResponse(result, true); - this.logger.debug('[%s] Sending success invoke response, scriptId: [%s]', requestId, scriptId); - this.sendResponse(requestId, responseTopic, headers, scriptId, undefined, invokeResponse); + if (result.length <= maxResultSize) { + const invokeResponse = JsInvokeMessageProcessor.createInvokeResponse(result, true); + this.logger.debug('[%s] Sending success invoke response, scriptId: [%s]', requestId, scriptId); + this.sendResponse(requestId, responseTopic, headers, scriptId, undefined, invokeResponse); + } else { + let err = { + name: 'Error', + message: 'script invocation result exceeds maximum allowed size of ' + maxResultSize + ' symbols' + } + const invokeResponse = JsInvokeMessageProcessor.createInvokeResponse("", false, RUNTIME_ERROR, err); + this.logger.debug('[%s] Script invocation result exceeds maximum allowed size of %s symbols, scriptId: [%s]', requestId, maxResultSize, scriptId); + this.sendResponse(requestId, responseTopic, headers, scriptId, undefined, invokeResponse); + } }, (err: any) => { let errorCode; diff --git a/msa/js-executor/config/custom-environment-variables.yml b/msa/js-executor/config/custom-environment-variables.yml index d408b14136..b9c24c8d8d 100644 --- a/msa/js-executor/config/custom-environment-variables.yml +++ b/msa/js-executor/config/custom-environment-variables.yml @@ -20,6 +20,7 @@ http_port: "HTTP_PORT" # /livenessProbe js: response_poll_interval: "REMOTE_JS_RESPONSE_POLL_INTERVAL_MS" + max_result_size: "JS_MAX_RESULT_SIZE" kafka: bootstrap: diff --git a/msa/js-executor/config/default.yml b/msa/js-executor/config/default.yml index 32163ea01e..64829ef792 100644 --- a/msa/js-executor/config/default.yml +++ b/msa/js-executor/config/default.yml @@ -20,6 +20,7 @@ http_port: "8888" # /livenessProbe js: response_poll_interval: "25" + max_result_size: "300000" kafka: bootstrap: From 65438c64e7ccbf56a026bdcecd11c6e1c5e4b6f5 Mon Sep 17 00:00:00 2001 From: Igor Kulikov Date: Fri, 7 Oct 2022 19:33:18 +0300 Subject: [PATCH 5/5] UI: add popover component to wiget context --- .../dashboard-page.component.html | 6 ++-- .../dashboard-page.component.ts | 18 +++++++--- .../layout/dashboard-layout.component.html | 3 +- .../layout/dashboard-layout.component.ts | 4 +++ .../dashboard/dashboard.component.ts | 9 ++++- .../components/widget/widget.component.ts | 25 ++++++++------ .../home/models/dashboard-component.models.ts | 19 ++++++----- .../home/models/widget-component.models.ts | 9 +++-- .../shared/components/popover.component.ts | 33 +++++++++++++++++++ .../app/shared/components/popover.service.ts | 22 +++++++++++-- 10 files changed, 116 insertions(+), 32 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html index 4caa27b0a2..db40fdc5d8 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html @@ -185,7 +185,8 @@ [isEditingWidget]="isEditingWidget" [isMobile]="forceDashboardMobileMode" [widgetEditMode]="widgetEditMode" - [parentDashboard]="parentDashboard"> + [parentDashboard]="parentDashboard" + [popoverComponent]="popoverComponent"> + [parentDashboard]="parentDashboard" + [popoverComponent]="popoverComponent"> diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts index c145794163..14e566411f 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts @@ -17,13 +17,18 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, EventEmitter, HostBinding, + Component, + ElementRef, + EventEmitter, + HostBinding, Inject, Injector, Input, NgZone, OnDestroy, - OnInit, Optional, Renderer2, + OnInit, + Optional, + Renderer2, StaticProvider, ViewChild, ViewContainerRef, @@ -48,7 +53,7 @@ import { } from '@app/shared/models/dashboard.models'; import { WINDOW } from '@core/services/window.service'; import { WindowMessage } from '@shared/models/window-message.model'; -import { deepClone, guid, hashCode, isDefined, isDefinedAndNotNull, isNotEmptyStr } from '@app/core/utils'; +import { deepClone, guid, isDefined, isDefinedAndNotNull, isNotEmptyStr } from '@app/core/utils'; import { DashboardContext, DashboardPageLayout, @@ -129,7 +134,8 @@ import { MobileService } from '@core/services/mobile.service'; import { DashboardImageDialogComponent, - DashboardImageDialogData, DashboardImageDialogResult + DashboardImageDialogData, + DashboardImageDialogResult } from '@home/components/dashboard-page/dashboard-image-dialog.component'; import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; import cssjs from '@core/css/css'; @@ -139,6 +145,7 @@ import { MatButton } from '@angular/material/button'; import { VersionControlComponent } from '@home/components/vc/version-control.component'; import { TbPopoverService } from '@shared/components/popover.service'; import { tap } from 'rxjs/operators'; +import { TbPopoverComponent } from '@shared/components/popover.component'; // @dynamic @Component({ @@ -184,6 +191,9 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC @Input() parentDashboard?: IDashboardComponent = null; + @Input() + popoverComponent?: TbPopoverComponent = null; + @Input() parentAliasController?: IAliasController = null; diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html index 4e7d11255b..0255ec8ade 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html @@ -58,6 +58,7 @@ [isRemoveActionEnabled]="isEdit && !widgetEditMode" [callbacks]="this" [ignoreLoading]="layoutCtx.ignoreLoading" - [parentDashboard]="parentDashboard"> + [parentDashboard]="parentDashboard" + [popoverComponent]="popoverComponent"> diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts index fcee0b2f0a..de3533d14e 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts @@ -33,6 +33,7 @@ import { TranslateService } from '@ngx-translate/core'; import { ItemBufferService } from '@app/core/services/item-buffer.service'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { TbCheatSheetComponent } from '@shared/components/cheatsheet.component'; +import { TbPopoverComponent } from '@shared/components/popover.component'; @Component({ selector: 'tb-dashboard-layout', @@ -81,6 +82,9 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo @Input() parentDashboard?: IDashboardComponent = null; + @Input() + popoverComponent?: TbPopoverComponent = null; + @ViewChild('dashboard', {static: true}) dashboard: IDashboardComponent; private rxSubscriptions = new Array(); diff --git a/ui-ngx/src/app/modules/home/components/dashboard/dashboard.component.ts b/ui-ngx/src/app/modules/home/components/dashboard/dashboard.component.ts index 62598ac1dd..627294b40f 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard/dashboard.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard/dashboard.component.ts @@ -15,7 +15,9 @@ /// import { - AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, + AfterViewInit, + ChangeDetectionStrategy, + ChangeDetectorRef, Component, DoCheck, Input, @@ -56,6 +58,7 @@ import { distinct } from 'rxjs/operators'; import { ResizeObserver } from '@juggle/resize-observer'; import { UtilsService } from '@core/services/utils.service'; import { WidgetComponentAction, WidgetComponentActionType } from '@home/components/widget/widget-container.component'; +import { TbPopoverComponent } from '@shared/components/popover.component'; @Component({ selector: 'tb-dashboard', @@ -136,6 +139,9 @@ export class DashboardComponent extends PageComponent implements IDashboardCompo @Input() parentDashboard?: IDashboardComponent = null; + @Input() + popoverComponent?: TbPopoverComponent = null; + dashboardTimewindowChangedSubject: Subject = new ReplaySubject(); dashboardTimewindowChanged = this.dashboardTimewindowChangedSubject.asObservable().pipe( @@ -191,6 +197,7 @@ export class DashboardComponent extends PageComponent implements IDashboardCompo ngOnInit(): void { this.dashboardWidgets.parentDashboard = this.parentDashboard; + this.dashboardWidgets.popoverComponent = this.popoverComponent; if (!this.dashboardTimewindow) { this.dashboardTimewindow = this.timeService.defaultTimewindow(); } diff --git a/ui-ngx/src/app/modules/home/components/widget/widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/widget.component.ts index 8826ff860f..790daf1a42 100644 --- a/ui-ngx/src/app/modules/home/components/widget/widget.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/widget.component.ts @@ -28,7 +28,8 @@ import { NgZone, OnChanges, OnDestroy, - OnInit, Renderer2, + OnInit, + Renderer2, SimpleChanges, ViewChild, ViewContainerRef, @@ -39,12 +40,14 @@ import { defaultLegendConfig, LegendConfig, LegendData, - LegendPosition, MobileActionResult, + LegendPosition, Widget, WidgetActionDescriptor, widgetActionSources, WidgetActionType, - WidgetComparisonSettings, WidgetMobileActionDescriptor, WidgetMobileActionType, + WidgetComparisonSettings, + WidgetMobileActionDescriptor, + WidgetMobileActionType, WidgetResource, widgetType, WidgetTypeParameters @@ -65,7 +68,9 @@ import { validateEntityId } from '@core/utils'; import { - IDynamicWidgetComponent, ShowWidgetHeaderActionFunction, updateEntityParams, + IDynamicWidgetComponent, + ShowWidgetHeaderActionFunction, + updateEntityParams, WidgetContext, WidgetHeaderAction, WidgetInfo, @@ -109,9 +114,7 @@ import { MobileService } from '@core/services/mobile.service'; import { DialogService } from '@core/services/dialog.service'; import { PopoverPlacement } from '@shared/components/popover.models'; import { TbPopoverService } from '@shared/components/popover.service'; -import { - DASHBOARD_PAGE_COMPONENT_TOKEN -} from '@home/components/tokens'; +import { DASHBOARD_PAGE_COMPONENT_TOKEN } from '@home/components/tokens'; @Component({ selector: 'tb-widget', @@ -1378,8 +1381,9 @@ export class WidgetComponent extends PageComponent implements OnInit, AfterViewI } ] }); - const component = this.popoverService.displayPopover(trigger, this.renderer, - this.widgetContentContainer, this.dashboardPageComponent, preferredPlacement, hideOnClickOutside, + const componentRef = this.popoverService.createPopoverRef(this.widgetContentContainer); + const component = this.popoverService.displayPopoverWithComponentRef(componentRef, trigger, this.renderer, + this.dashboardPageComponent, preferredPlacement, hideOnClickOutside, injector, { embedded: true, @@ -1388,7 +1392,8 @@ export class WidgetComponent extends PageComponent implements OnInit, AfterViewI currentState: objToBase64([stateObject]), dashboard, parentDashboard: this.widgetContext.parentDashboard ? - this.widgetContext.parentDashboard : this.widgetContext.dashboard + this.widgetContext.parentDashboard : this.widgetContext.dashboard, + popoverComponent: componentRef.instance }, {width: popoverWidth, height: popoverHeight}, popoverStyle, diff --git a/ui-ngx/src/app/modules/home/models/dashboard-component.models.ts b/ui-ngx/src/app/modules/home/models/dashboard-component.models.ts index 6721f7bc25..33fa5111c5 100644 --- a/ui-ngx/src/app/modules/home/models/dashboard-component.models.ts +++ b/ui-ngx/src/app/modules/home/models/dashboard-component.models.ts @@ -16,8 +16,8 @@ import { GridsterComponent, GridsterConfig, GridsterItem, GridsterItemComponentInterface } from 'angular-gridster2'; import { - Datasource, - datasourcesHasAggregation, datasourcesHasOnlyComparisonAggregation, + datasourcesHasAggregation, + datasourcesHasOnlyComparisonAggregation, FormattedData, Widget, WidgetPosition, @@ -25,14 +25,14 @@ import { } from '@app/shared/models/widget.models'; import { WidgetLayout, WidgetLayouts } from '@app/shared/models/dashboard.models'; import { IDashboardWidget, WidgetAction, WidgetContext, WidgetHeaderAction } from './widget-component.models'; -import { AggregationType, Timewindow } from '@shared/models/time/time.models'; +import { Timewindow } from '@shared/models/time/time.models'; import { Observable, of, Subject } from 'rxjs'; import { formattedDataFormDatasourceData, guid, isDefined, isEqual, isUndefined } from '@app/core/utils'; import { IterableDiffer, KeyValueDiffer } from '@angular/core'; import { IAliasController, IStateController } from '@app/core/api/widget-api.models'; import { enumerable } from '@shared/decorators/enumerable'; import { UtilsService } from '@core/services/utils.service'; -import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { TbPopoverComponent } from '@shared/components/popover.component'; export interface WidgetsData { widgets: Array; @@ -109,6 +109,8 @@ export class DashboardWidgets implements Iterable { parentDashboard?: IDashboardComponent; + popoverComponent?: TbPopoverComponent; + [Symbol.iterator](): Iterator { return this.activeDashboardWidgets[Symbol.iterator](); } @@ -174,7 +176,7 @@ export class DashboardWidgets implements Iterable { switch (record.operation) { case 'add': this.dashboardWidgets.push( - new DashboardWidget(this.dashboard, record.widget, record.widgetLayout, this.parentDashboard) + new DashboardWidget(this.dashboard, record.widget, record.widgetLayout, this.parentDashboard, this.popoverComponent) ); break; case 'remove': @@ -190,7 +192,7 @@ export class DashboardWidgets implements Iterable { if (!isEqual(prevDashboardWidget.widget, record.widget) || !isEqual(prevDashboardWidget.widgetLayout, record.widgetLayout)) { this.dashboardWidgets[index] = new DashboardWidget(this.dashboard, record.widget, record.widgetLayout, - this.parentDashboard); + this.parentDashboard, this.popoverComponent); this.dashboardWidgets[index].highlighted = prevDashboardWidget.highlighted; this.dashboardWidgets[index].selected = prevDashboardWidget.selected; } else { @@ -345,7 +347,7 @@ export class DashboardWidget implements GridsterItem, IDashboardWidget { customHeaderActions: Array; widgetActions: Array; - widgetContext = new WidgetContext(this.dashboard, this, this.widget, this.parentDashboard); + widgetContext = new WidgetContext(this.dashboard, this, this.widget, this.parentDashboard, this.popoverComponent); widgetId: string; @@ -388,7 +390,8 @@ export class DashboardWidget implements GridsterItem, IDashboardWidget { private dashboard: IDashboardComponent, public widget: Widget, public widgetLayout?: WidgetLayout, - private parentDashboard?: IDashboardComponent) { + private parentDashboard?: IDashboardComponent, + private popoverComponent?: TbPopoverComponent) { if (!widget.id) { widget.id = guid(); } diff --git a/ui-ngx/src/app/modules/home/models/widget-component.models.ts b/ui-ngx/src/app/modules/home/models/widget-component.models.ts index 4686fe88e6..0bcfa8fb01 100644 --- a/ui-ngx/src/app/modules/home/models/widget-component.models.ts +++ b/ui-ngx/src/app/modules/home/models/widget-component.models.ts @@ -18,7 +18,8 @@ import { IDashboardComponent } from '@home/models/dashboard-component.models'; import { DataSet, Datasource, - DatasourceData, FormattedData, + DatasourceData, + FormattedData, JsonSettingsSchema, Widget, WidgetActionDescriptor, @@ -37,7 +38,8 @@ import { IStateController, IWidgetSubscription, IWidgetUtils, - RpcApi, StateParams, + RpcApi, + StateParams, SubscriptionEntityInfo, TimewindowFunctions, WidgetActionsApi, @@ -113,7 +115,8 @@ export class WidgetContext { constructor(public dashboard: IDashboardComponent, private dashboardWidget: IDashboardWidget, private widget: Widget, - public parentDashboard?: IDashboardComponent) {} + public parentDashboard?: IDashboardComponent, + public popoverComponent?: TbPopoverComponent) {} get stateController(): IStateController { return this.parentDashboard ? this.parentDashboard.stateController : this.dashboard.stateController; diff --git a/ui-ngx/src/app/shared/components/popover.component.ts b/ui-ngx/src/app/shared/components/popover.component.ts index 99321974af..20815fd5fb 100644 --- a/ui-ngx/src/app/shared/components/popover.component.ts +++ b/ui-ngx/src/app/shared/components/popover.component.ts @@ -57,6 +57,7 @@ import { } from '@shared/components/popover.models'; import { distinctUntilChanged, take, takeUntil } from 'rxjs/operators'; import { isNotEmptyStr, onParentScrollOrWindowResize } from '@core/utils'; +import { animate, AnimationBuilder, AnimationMetadata, style } from '@angular/animations'; export type TbPopoverTrigger = 'click' | 'focus' | 'hover' | null; @@ -304,6 +305,7 @@ export class TbPopoverDirective implements OnChanges, OnDestroy, AfterViewInit {
; + @ViewChild('popover', { static: false }) popover!: ElementRef; tbContent: string | TemplateRef | null = null; tbComponentFactory: ComponentFactory | null = null; @@ -442,6 +445,7 @@ export class TbPopoverComponent implements OnDestroy, OnInit { constructor( public cdr: ChangeDetectorRef, private renderer: Renderer2, + private animationBuilder: AnimationBuilder, @Optional() private directionality: Directionality ) {} @@ -532,6 +536,35 @@ export class TbPopoverComponent implements OnDestroy, OnInit { }); } + resize(width: string, height: string, animationDurationMs?: number) { + if (animationDurationMs && animationDurationMs > 0) { + const prevWidth = this.popover.nativeElement.offsetWidth; + const prevHeight = this.popover.nativeElement.offsetHeight; + const animationMetadata: AnimationMetadata[] = [style({width: prevWidth + 'px', height: prevHeight + 'px'}), + animate(animationDurationMs + 'ms', style({width, height}))]; + const factory = this.animationBuilder.build(animationMetadata); + const player = factory.create(this.popover.nativeElement); + player.play(); + const resize$ = new ResizeObserver(() => { + this.updatePosition(); + }); + resize$.observe(this.popover.nativeElement); + player.onDone(() => { + player.destroy(); + resize$.disconnect(); + this.setSize(width, height); + }); + } else { + this.setSize(width, height); + } + } + + private setSize(width: string, height: string) { + this.renderer.setStyle(this.popover.nativeElement, 'width', width); + this.renderer.setStyle(this.popover.nativeElement, 'height', height); + this.updatePosition(); + } + updatePosition(): void { if (this.origin && this.overlay && this.overlay.overlayRef) { this.overlay.overlayRef.updatePosition(); diff --git a/ui-ngx/src/app/shared/components/popover.service.ts b/ui-ngx/src/app/shared/components/popover.service.ts index 713e8d337b..3f05ed02a6 100644 --- a/ui-ngx/src/app/shared/components/popover.service.ts +++ b/ui-ngx/src/app/shared/components/popover.service.ts @@ -16,8 +16,12 @@ import { ComponentFactory, - ComponentFactoryResolver, ElementRef, Inject, - Injectable, Injector, + ComponentFactoryResolver, + ComponentRef, + ElementRef, + Inject, + Injectable, + Injector, Renderer2, Type, ViewContainerRef @@ -53,11 +57,23 @@ export class TbPopoverService { } } + createPopoverRef(hostView: ViewContainerRef): ComponentRef { + return hostView.createComponent(this.componentFactory); + } + displayPopover(trigger: Element, renderer: Renderer2, hostView: ViewContainerRef, componentType: Type, preferredPlacement: PopoverPlacement = 'top', hideOnClickOutside = true, injector?: Injector, context?: any, overlayStyle: any = {}, popoverStyle: any = {}, style?: any, showCloseButton = true): TbPopoverComponent { - const componentRef = hostView.createComponent(this.componentFactory); + const componentRef = this.createPopoverRef(hostView); + return this.displayPopoverWithComponentRef(componentRef, trigger, renderer, componentType, preferredPlacement, hideOnClickOutside, + injector, context, overlayStyle, popoverStyle, style, showCloseButton); + } + + displayPopoverWithComponentRef(componentRef: ComponentRef, trigger: Element, renderer: Renderer2, + componentType: Type, preferredPlacement: PopoverPlacement = 'top', + hideOnClickOutside = true, injector?: Injector, context?: any, overlayStyle: any = {}, + popoverStyle: any = {}, style?: any, showCloseButton = true): TbPopoverComponent { const component = componentRef.instance; this.popoverWithTriggers.push({ trigger,