committed by
GitHub
91 changed files with 7027 additions and 7200 deletions
@ -0,0 +1,41 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
/** |
|||
* Connects the browser end of an AI chat stream to its turn on TB AI. ThingsBoard keeps listening to a turn after the |
|||
* browser leaves (the turn bills its credits at its end), so leaving is reported separately: TB AI then knows nobody |
|||
* follows the turn, and a pending approval expires soon instead of waiting its full timeout for a user who left. |
|||
*/ |
|||
public final class TbAiTurnLink { |
|||
|
|||
private final Object lock = new Object(); |
|||
private Runnable onClientLeft; |
|||
private boolean clientLeft; |
|||
|
|||
public void onClientLeft(Runnable listener) { |
|||
boolean leftAlready; |
|||
synchronized (lock) { |
|||
onClientLeft = listener; |
|||
leftAlready = clientLeft; |
|||
} |
|||
if (leftAlready) { |
|||
listener.run(); |
|||
} |
|||
} |
|||
|
|||
public void clientLeft() { |
|||
Runnable listener; |
|||
synchronized (lock) { |
|||
if (clientLeft) { |
|||
return; |
|||
} |
|||
clientLeft = true; |
|||
listener = onClientLeft; |
|||
} |
|||
if (listener != null) { |
|||
listener.run(); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.mail; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.rule.engine.api.TbEmail; |
|||
import org.thingsboard.server.common.data.ApiFeature; |
|||
import org.thingsboard.server.common.data.ApiUsageRecordState; |
|||
import org.thingsboard.server.common.data.ApiUsageStateValue; |
|||
|
|||
/** |
|||
* Describes a mail send that the Edge delegates to the Cloud. On the Edge, a mail send that depends |
|||
* on admin-configured (tenant/system) mail settings is packaged into this request and enqueued as a |
|||
* SEND_EMAIL cloud event. On the Cloud, {@code method} selects the matching {@code MailService} call |
|||
* so the Cloud resolves the config, renders the template and transmits via its own SMTP. |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeMailRequest { |
|||
|
|||
public enum MailMethod { |
|||
SEND_BASIC, // sendEmail(to, subject, message)
|
|||
SEND_TB_EMAIL, // send(TbEmail)
|
|||
ACTIVATION, // sendActivationEmail(activationLink, ttlMs, to)
|
|||
ACCOUNT_ACTIVATED, // sendAccountActivatedEmail(loginLink, to)
|
|||
RESET_PASSWORD, // sendResetPasswordEmail(passwordResetLink, ttlMs, to)
|
|||
PASSWORD_WAS_RESET,// sendPasswordWasResetEmail(loginLink, to)
|
|||
TWO_FA, // sendTwoFaVerificationEmail(to, verificationCode, expirationTimeSeconds)
|
|||
ACCOUNT_LOCKOUT, // sendAccountLockoutEmail(lockoutEmail, to, maxFailedLoginAttempts)
|
|||
API_USAGE_STATE, // sendApiFeatureStateEmail(apiFeature, stateValue, to, recordState)
|
|||
TEST_MAIL // sendTestMail(config, to)
|
|||
} |
|||
|
|||
private MailMethod method; |
|||
|
|||
private String to; |
|||
private String subject; |
|||
private String message; |
|||
|
|||
private TbEmail tbEmail; |
|||
|
|||
private String activationLink; |
|||
private String loginLink; |
|||
private String passwordResetLink; |
|||
private Long ttlMs; |
|||
|
|||
private String verificationCode; |
|||
private Integer expirationTimeSeconds; |
|||
|
|||
private String lockoutEmail; |
|||
private Integer maxFailedLoginAttempts; |
|||
|
|||
private ApiFeature apiFeature; |
|||
private ApiUsageStateValue stateValue; |
|||
private ApiUsageRecordState recordState; |
|||
|
|||
private JsonNode testConfig; |
|||
|
|||
} |
|||
@ -0,0 +1,63 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.notification; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* Describes a notification delivery that the Edge delegates to the Cloud, for channels whose credentials |
|||
* live only on the Cloud (they are stored in the {@code notifications} admin settings that no longer sync |
|||
* to the Edge). {@code method} selects the channel: |
|||
* <ul> |
|||
* <li>{@code SEND_SLACK} - the Cloud resolves the Slack bot token and posts {@code message} (plus any |
|||
* {@code files}) to {@code conversationId}. The whole send is delegated.</li> |
|||
* <li>{@code SEND_MOBILE_PUSH} - the Edge keeps the notification record, device-token lookup and unread |
|||
* count locally and delegates only the FCM push: the Cloud resolves the Firebase credentials and pushes |
|||
* the already-built payload ({@code subject}/{@code body}/{@code data}/{@code badge}) to every |
|||
* {@code fcmToken}.</li> |
|||
* </ul> |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeNotificationRequest { |
|||
|
|||
public enum NotificationMethod { |
|||
SEND_SLACK, |
|||
SEND_MOBILE_PUSH |
|||
} |
|||
|
|||
private NotificationMethod method; |
|||
|
|||
// SEND_SLACK
|
|||
private String conversationId; |
|||
private String message; |
|||
private List<SlackFileData> files; |
|||
|
|||
// SEND_MOBILE_PUSH
|
|||
private Set<String> fcmTokens; |
|||
private String subject; |
|||
private String body; |
|||
private Map<String, String> data; |
|||
private Integer badge; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public static class SlackFileData { |
|||
private String name; |
|||
private String type; |
|||
private byte[] data; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,38 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.sms; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonInclude; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Builder; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.sms.config.TestSmsRequest; |
|||
|
|||
/** |
|||
* Describes an SMS send that the Edge delegates to the Cloud. On the Edge, a send that depends on |
|||
* admin-configured (tenant/system) SMS provider settings cannot be resolved locally, so the call is |
|||
* packaged into this request and enqueued as a SEND_SMS cloud event; on the Cloud, {@code method} |
|||
* selects the matching {@code SmsService} call so the Cloud resolves the config and transmits via its |
|||
* own provider. |
|||
*/ |
|||
@Data |
|||
@Builder |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
@JsonInclude(JsonInclude.Include.NON_NULL) |
|||
public class EdgeSmsRequest { |
|||
|
|||
public enum SmsMethod { |
|||
SEND_SMS, // sendSms(customerId, numbersTo, message)
|
|||
SEND_TEST_SMS // sendTestSms(testSmsRequest)
|
|||
} |
|||
|
|||
private SmsMethod method; |
|||
|
|||
private String[] numbers; |
|||
private String message; |
|||
|
|||
private TestSmsRequest testSmsRequest; |
|||
|
|||
} |
|||
@ -1,109 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import com.google.protobuf.AbstractMessage; |
|||
import org.junit.Assert; |
|||
import org.junit.Test; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; |
|||
|
|||
@DaoSqlTest |
|||
public class AdminSettingsEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@Autowired |
|||
private AdminSettingsService adminSettingsService; |
|||
|
|||
@Test |
|||
public void testAdminSettings_sysAdmin() throws Exception { |
|||
loginSysAdmin(); |
|||
|
|||
AdminSettings adminSettings = new AdminSettings(); |
|||
adminSettings.setKey("edgeTest"); |
|||
ObjectNode jsonValue = JacksonUtil.newObjectNode(); |
|||
jsonValue.put("key1", "value1"); |
|||
adminSettings.setJsonValue(jsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
AdminSettings savedAdminSettings = doPost("/api/admin/settings", adminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
AbstractMessage latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); |
|||
|
|||
ObjectNode updatedJsonValue = (ObjectNode) savedAdminSettings.getJsonValue(); |
|||
updatedJsonValue.put("key2", "value2"); |
|||
savedAdminSettings.setJsonValue(updatedJsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
doPost("/api/admin/settings", savedAdminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); |
|||
Assert.assertEquals("value2", adminSettingsMsg.getJsonValue().get("key2").asText()); |
|||
|
|||
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedAdminSettings.getTenantId(), "edgeTest"); |
|||
} |
|||
|
|||
@Test |
|||
public void testAdminSettings_tenant() throws Exception { |
|||
loginTenantAdmin(); |
|||
|
|||
AdminSettings tenantAdminSettings = new AdminSettings(); |
|||
tenantAdminSettings.setTenantId(tenantId); |
|||
tenantAdminSettings.setKey("tenantEdgeTest"); |
|||
ObjectNode tenantJsonValue = JacksonUtil.newObjectNode(); |
|||
tenantJsonValue.put("tenantKey1", "tenantValue1"); |
|||
tenantAdminSettings.setJsonValue(tenantJsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
AdminSettings savedTenantAdminSettings = doPost("/api/admin/settings", tenantAdminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
AbstractMessage latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("tenantEdgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("tenantValue1", adminSettingsMsg.getJsonValue().get("tenantKey1").asText()); |
|||
|
|||
// TENANT update
|
|||
ObjectNode updatedTenantJsonValue = (ObjectNode) savedTenantAdminSettings.getJsonValue(); |
|||
updatedTenantJsonValue.put("tenantKey2", "tenantValue2"); |
|||
savedTenantAdminSettings.setJsonValue(updatedTenantJsonValue); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
doPost("/api/admin/settings", savedTenantAdminSettings, AdminSettings.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); |
|||
adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; |
|||
adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); |
|||
Assert.assertNotNull(adminSettingsMsg); |
|||
Assert.assertEquals("tenantEdgeTest", adminSettingsMsg.getKey()); |
|||
Assert.assertEquals("tenantValue1", adminSettingsMsg.getJsonValue().get("tenantKey1").asText()); |
|||
Assert.assertEquals("tenantValue2", adminSettingsMsg.getJsonValue().get("tenantKey2").asText()); |
|||
|
|||
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedTenantAdminSettings.getTenantId(), "tenantEdgeTest"); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,198 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import org.junit.Test; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.MailService; |
|||
import org.thingsboard.rule.engine.api.TbEmail; |
|||
import org.thingsboard.server.common.data.ApiFeature; |
|||
import org.thingsboard.server.common.data.ApiUsageStateValue; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; |
|||
import org.thingsboard.server.service.mail.EdgeMailRequest; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.ArgumentMatchers.isNull; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-email uplink: when the Edge delegates a mail send, the Cloud receives the |
|||
* SendEmailUplinkMsg and invokes its MailService (which resolves the config, renders and transmits). Here |
|||
* the EdgeImitator plays the Edge and sends the uplink; the Cloud's MailService is mocked so we can assert |
|||
* the delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of |
|||
* the connected edge). |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendEmailEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private MailService mailService; |
|||
|
|||
@Test |
|||
public void testSendBasicEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.SEND_BASIC) |
|||
.to("recipient@thingsboard.io") |
|||
.subject("Edge test subject") |
|||
.message("<b>Edge test body</b>") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("<b>Edge test body</b>")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTbEmailFromEdgeProcessedByCloud() throws Exception { |
|||
TbEmail tbEmail = TbEmail.builder() |
|||
.from("noreply@thingsboard.io") |
|||
.to("recipient@thingsboard.io") |
|||
.subject("Rule chain email") |
|||
.body("Alarm!") |
|||
.html(false) |
|||
.build(); |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.SEND_TB_EMAIL) |
|||
.tbEmail(tbEmail) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendActivationEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACTIVATION) |
|||
.activationLink("http://localhost/activate?token=abc") |
|||
.ttlMs(60000L) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendActivationEmail(eq(tenantId), eq("http://localhost/activate?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendAccountActivatedEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACCOUNT_ACTIVATED) |
|||
.loginLink("http://localhost/login") |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendAccountActivatedEmail(eq(tenantId), eq("http://localhost/login"), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendResetPasswordEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.RESET_PASSWORD) |
|||
.passwordResetLink("http://localhost/reset?token=abc") |
|||
.ttlMs(60000L) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendResetPasswordEmail(eq(tenantId), eq("http://localhost/reset?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendPasswordWasResetEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.PASSWORD_WAS_RESET) |
|||
.loginLink("http://localhost/login") |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendPasswordWasResetEmail(eq(tenantId), eq("http://localhost/login"), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTwoFaVerificationEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.TWO_FA) |
|||
.to("recipient@thingsboard.io") |
|||
.verificationCode("123456") |
|||
.expirationTimeSeconds(120) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendTwoFaVerificationEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("123456"), eq(120)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendAccountLockoutEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.ACCOUNT_LOCKOUT) |
|||
.lockoutEmail("locked@thingsboard.io") |
|||
.to("recipient@thingsboard.io") |
|||
.maxFailedLoginAttempts(5) |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendAccountLockoutEmail(eq(tenantId), eq("locked@thingsboard.io"), eq("recipient@thingsboard.io"), eq(5)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendApiUsageStateEmailFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.API_USAGE_STATE) |
|||
.apiFeature(ApiFeature.EMAIL) |
|||
.stateValue(ApiUsageStateValue.DISABLED) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendApiFeatureStateEmail(eq(tenantId), eq(ApiFeature.EMAIL), eq(ApiUsageStateValue.DISABLED), eq("recipient@thingsboard.io"), isNull()); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTestMailFromEdgeProcessedByCloud() throws Exception { |
|||
JsonNode testConfig = JacksonUtil.newObjectNode().put("smtpHost", "localhost"); |
|||
EdgeMailRequest request = EdgeMailRequest.builder() |
|||
.method(EdgeMailRequest.MailMethod.TEST_MAIL) |
|||
.testConfig(testConfig) |
|||
.to("recipient@thingsboard.io") |
|||
.build(); |
|||
|
|||
sendEmailUplink(request); |
|||
|
|||
verify(mailService, timeout(30000)) |
|||
.sendTestMail(eq(tenantId), any(JsonNode.class), eq("recipient@thingsboard.io")); |
|||
} |
|||
|
|||
private void sendEmailUplink(EdgeMailRequest request) throws Exception { |
|||
SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendEmailUplinkMsg(sendEmailUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,106 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import org.junit.Test; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.notification.FirebaseService; |
|||
import org.thingsboard.rule.engine.api.notification.SlackService; |
|||
import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; |
|||
import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; |
|||
import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig; |
|||
import org.thingsboard.server.common.data.notification.settings.NotificationSettings; |
|||
import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig; |
|||
import org.thingsboard.server.dao.notification.NotificationSettingsService; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; |
|||
import org.thingsboard.server.service.notification.EdgeNotificationRequest; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.anyString; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-notification uplink: when the Edge delegates a Slack or mobile-push notification, the |
|||
* Cloud receives the SendNotificationUplinkMsg, resolves the channel credentials from its own notification |
|||
* settings and delivers. The EdgeImitator plays the Edge and sends the uplink; the Cloud's SlackService and |
|||
* FirebaseService are mocked so we can assert the delegated call arrives with the expected arguments. |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendNotificationEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private SlackService slackService; |
|||
|
|||
@MockitoBean |
|||
private FirebaseService firebaseService; |
|||
|
|||
@Autowired |
|||
private NotificationSettingsService notificationSettingsService; |
|||
|
|||
private void prepareNotificationSettings() { |
|||
SlackNotificationDeliveryMethodConfig slack = new SlackNotificationDeliveryMethodConfig(); |
|||
slack.setBotToken("xoxb-edge-test-token"); |
|||
MobileAppNotificationDeliveryMethodConfig mobile = new MobileAppNotificationDeliveryMethodConfig(); |
|||
mobile.setUseSystemSettings(false); |
|||
mobile.setFirebaseServiceAccountCredentials("{\"type\":\"service_account\"}"); |
|||
|
|||
NotificationSettings settings = new NotificationSettings(); |
|||
Map<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> configs = new HashMap<>(); |
|||
configs.put(NotificationDeliveryMethod.SLACK, slack); |
|||
configs.put(NotificationDeliveryMethod.MOBILE_APP, mobile); |
|||
settings.setDeliveryMethodsConfigs(configs); |
|||
notificationSettingsService.saveNotificationSettings(tenantId, settings); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendSlackNotificationFromEdgeProcessedByCloud() throws Exception { |
|||
prepareNotificationSettings(); |
|||
EdgeNotificationRequest request = EdgeNotificationRequest.builder() |
|||
.method(EdgeNotificationRequest.NotificationMethod.SEND_SLACK) |
|||
.conversationId("C0123456789") |
|||
.message("Edge Slack notification") |
|||
.build(); |
|||
|
|||
sendNotificationUplink(request); |
|||
|
|||
verify(slackService, timeout(30000)) |
|||
.sendMessage(eq(tenantId), anyString(), eq("C0123456789"), eq("Edge Slack notification"), any()); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendMobilePushFromEdgeProcessedByCloud() throws Exception { |
|||
prepareNotificationSettings(); |
|||
EdgeNotificationRequest request = EdgeNotificationRequest.builder() |
|||
.method(EdgeNotificationRequest.NotificationMethod.SEND_MOBILE_PUSH) |
|||
.fcmTokens(Set.of("fcm-token-1")) |
|||
.subject("Edge subject") |
|||
.body("Edge body") |
|||
.badge(3) |
|||
.build(); |
|||
|
|||
sendNotificationUplink(request); |
|||
|
|||
verify(firebaseService, timeout(30000)) |
|||
.sendMessage(eq(tenantId), anyString(), eq("fcm-token-1"), eq("Edge subject"), eq("Edge body"), any(), eq(3)); |
|||
} |
|||
|
|||
private void sendNotificationUplink(EdgeNotificationRequest request) throws Exception { |
|||
SendNotificationUplinkMsg sendNotificationUplinkMsg = SendNotificationUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,72 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.edge; |
|||
|
|||
import org.junit.Test; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.SmsService; |
|||
import org.thingsboard.server.common.data.sms.config.TestSmsRequest; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; |
|||
import org.thingsboard.server.service.sms.EdgeSmsRequest; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.ArgumentMatchers.isNull; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
/** |
|||
* Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the |
|||
* SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the |
|||
* EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the |
|||
* delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the |
|||
* connected edge). |
|||
*/ |
|||
@DaoSqlTest |
|||
public class SendSmsEdgeTest extends AbstractEdgeTest { |
|||
|
|||
@MockitoBean |
|||
private SmsService smsService; |
|||
|
|||
@Test |
|||
public void testSendSmsFromEdgeProcessedByCloud() throws Exception { |
|||
EdgeSmsRequest request = EdgeSmsRequest.builder() |
|||
.method(EdgeSmsRequest.SmsMethod.SEND_SMS) |
|||
.numbers(new String[]{"+15551234567"}) |
|||
.message("Edge test message") |
|||
.build(); |
|||
|
|||
sendSmsUplink(request); |
|||
|
|||
verify(smsService, timeout(30000)) |
|||
.sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message")); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception { |
|||
TestSmsRequest testSmsRequest = new TestSmsRequest(); |
|||
testSmsRequest.setNumberTo("+15551234567"); |
|||
testSmsRequest.setMessage("Test message"); |
|||
EdgeSmsRequest request = EdgeSmsRequest.builder() |
|||
.method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS) |
|||
.testSmsRequest(testSmsRequest) |
|||
.build(); |
|||
|
|||
sendSmsUplink(request); |
|||
|
|||
verify(smsService, timeout(30000)).sendTestSms(eq(tenantId), any(TestSmsRequest.class)); |
|||
} |
|||
|
|||
private void sendSmsUplink(EdgeSmsRequest request) throws Exception { |
|||
SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder() |
|||
.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) |
|||
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) |
|||
.setRequest(JacksonUtil.toString(request)) |
|||
.build(); |
|||
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendSmsUplinkMsg(sendSmsUplinkMsg)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,112 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge.rpc.processor.settings; |
|||
|
|||
import org.junit.jupiter.api.Assertions; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.common.data.edge.EdgeEvent; |
|||
import org.thingsboard.server.common.data.id.AdminSettingsId; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
import org.thingsboard.server.gen.edge.v1.DownlinkMsg; |
|||
import org.thingsboard.server.gen.edge.v1.EdgeVersion; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
|
|||
import java.util.UUID; |
|||
|
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.lenient; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class AdminSettingsEdgeProcessorTest { |
|||
|
|||
@Mock |
|||
private EdgeContextComponent edgeCtx; |
|||
@Mock |
|||
private AdminSettingsService adminSettingsService; |
|||
|
|||
private final TenantId tenantId = new TenantId(UUID.randomUUID()); |
|||
private AdminSettingsEdgeProcessor processor; |
|||
|
|||
@BeforeEach |
|||
public void setUp() { |
|||
processor = new AdminSettingsEdgeProcessor(); |
|||
ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx); |
|||
lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService); |
|||
} |
|||
|
|||
@Test |
|||
public void testTenantScopedAllowListedKeyIsSyncedToEdge() { |
|||
AdminSettings general = adminSettings(tenantId, "general"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNotNull(downlink); |
|||
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); |
|||
AdminSettings synced = JacksonUtil.fromString(downlink.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true); |
|||
Assertions.assertNotNull(synced); |
|||
Assertions.assertEquals("general", synced.getKey()); |
|||
} |
|||
|
|||
@Test |
|||
public void testTenantScopedNonAllowListedKeyIsNotSyncedToEdge() { |
|||
AdminSettings mail = adminSettings(tenantId, "mail"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(mail); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNull(downlink); |
|||
} |
|||
|
|||
@Test |
|||
public void testSystemScopedAllowListedKeyIsSyncedToEdge() { |
|||
AdminSettings connectivity = adminSettings(TenantId.SYS_TENANT_ID, "connectivity"); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(connectivity); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNotNull(downlink); |
|||
Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); |
|||
} |
|||
|
|||
@ParameterizedTest |
|||
@ValueSource(strings = {"mail", "jwt", "sms", "notifications"}) |
|||
public void testSystemScopedNonAllowListedKeyIsNotSyncedToEdge(String key) { |
|||
AdminSettings settings = adminSettings(TenantId.SYS_TENANT_ID, key); |
|||
when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(settings); |
|||
|
|||
DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); |
|||
|
|||
Assertions.assertNull(downlink); |
|||
} |
|||
|
|||
private EdgeEvent edgeEvent(TenantId eventTenantId) { |
|||
EdgeEvent edgeEvent = new EdgeEvent(); |
|||
edgeEvent.setTenantId(eventTenantId); |
|||
edgeEvent.setEdgeId(new EdgeId(UUID.randomUUID())); |
|||
edgeEvent.setEntityId(UUID.randomUUID()); |
|||
return edgeEvent; |
|||
} |
|||
|
|||
private AdminSettings adminSettings(TenantId settingsTenantId, String key) { |
|||
AdminSettings adminSettings = new AdminSettings(); |
|||
adminSettings.setId(new AdminSettingsId(UUID.randomUUID())); |
|||
adminSettings.setTenantId(settingsTenantId); |
|||
adminSettings.setKey(key); |
|||
adminSettings.setJsonValue(JacksonUtil.newObjectNode()); |
|||
return adminSettings; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,40 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.edge.rpc.processor.wl; |
|||
|
|||
import org.junit.jupiter.api.Assertions; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.wl.WhiteLabelingType; |
|||
|
|||
import java.util.UUID; |
|||
|
|||
public class WhiteLabelingEdgeProcessorTest { |
|||
|
|||
private final WhiteLabelingEdgeProcessor processor = new WhiteLabelingEdgeProcessor(); |
|||
private final TenantId tenantId = new TenantId(UUID.randomUUID()); |
|||
|
|||
@Test |
|||
public void testSystemMailTemplatesAreNotSyncedToEdge() { |
|||
// System mail templates are rendered on the cloud, so they must never be pushed to the edge.
|
|||
Assertions.assertTrue(isSystemMailTemplates(WhiteLabelingType.MAIL_TEMPLATES, TenantId.SYS_TENANT_ID)); |
|||
} |
|||
|
|||
@Test |
|||
public void testTenantMailTemplatesAreStillSyncedToEdge() { |
|||
// Only system-scoped mail templates are skipped; tenant-scoped ones keep syncing.
|
|||
Assertions.assertFalse(isSystemMailTemplates(WhiteLabelingType.MAIL_TEMPLATES, tenantId)); |
|||
} |
|||
|
|||
@Test |
|||
public void testSystemNonMailTemplatesAreStillSyncedToEdge() { |
|||
// Other system white-labeling (e.g. GENERAL) is not affected by the mail-templates skip.
|
|||
Assertions.assertFalse(isSystemMailTemplates(WhiteLabelingType.GENERAL, TenantId.SYS_TENANT_ID)); |
|||
} |
|||
|
|||
private boolean isSystemMailTemplates(WhiteLabelingType type, TenantId tenantId) { |
|||
return Boolean.TRUE.equals(ReflectionTestUtils.invokeMethod(processor, "isSystemMailTemplates", type, tenantId)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,250 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.edge.rpc.service; |
|||
|
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentMatcher; |
|||
import org.mockito.InOrder; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.springframework.context.ApplicationContext; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.rule.engine.api.AttributesSaveRequest; |
|||
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; |
|||
import org.thingsboard.server.cache.TbTransactionalCache; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.msg.TbMsgType; |
|||
import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; |
|||
import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; |
|||
import org.thingsboard.server.common.msg.queue.ServiceType; |
|||
import org.thingsboard.server.queue.discovery.PartitionService; |
|||
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
import org.thingsboard.server.service.edge.rpc.EdgeSessionState; |
|||
import org.thingsboard.server.service.edge.rpc.session.EdgeSessionsHolder; |
|||
import org.thingsboard.server.service.edge.rpc.session.manager.EdgeGrpcSessionManager; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.atomic.AtomicBoolean; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.argThat; |
|||
import static org.mockito.ArgumentMatchers.isNull; |
|||
import static org.mockito.Mockito.doAnswer; |
|||
import static org.mockito.Mockito.inOrder; |
|||
import static org.mockito.Mockito.lenient; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; |
|||
import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_DISCONNECT_TIME; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
class EdgeGrpcServiceTest { |
|||
|
|||
private static final String THIS_NODE = "tb-core-1"; |
|||
private static final String OTHER_NODE = "tb-core-2"; |
|||
|
|||
@Mock |
|||
private ApplicationContext applicationContext; |
|||
@Mock |
|||
private TbClusterService clusterService; |
|||
@Mock |
|||
private TbServiceInfoProvider serviceInfoProvider; |
|||
@Mock |
|||
private TelemetrySubscriptionService tsSubService; |
|||
@Mock |
|||
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache; |
|||
@Mock |
|||
private PartitionService partitionService; |
|||
@Mock |
|||
private EdgeContextComponent ctx; |
|||
@Mock |
|||
private NotificationRuleProcessor ruleProcessor; |
|||
|
|||
private EdgeSessionsHolder sessions; |
|||
private EdgeGrpcService edgeGrpcService; |
|||
private Edge edge; |
|||
private EdgeId edgeId; |
|||
|
|||
@BeforeEach |
|||
void setUp() { |
|||
sessions = new EdgeSessionsHolder(); |
|||
edgeGrpcService = new EdgeGrpcService(sessions, applicationContext, clusterService, serviceInfoProvider, |
|||
tsSubService, edgeIdServiceIdCache, partitionService); |
|||
ReflectionTestUtils.setField(edgeGrpcService, "ctx", ctx); |
|||
edgeId = new EdgeId(UUID.randomUUID()); |
|||
edge = new Edge(edgeId); |
|||
edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); |
|||
edge.setName("test-edge"); |
|||
lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); |
|||
} |
|||
|
|||
@Test |
|||
void givenNoCacheEntry_whenDisconnect_thenAllDisconnectSideEffectsRun() { |
|||
EdgeGrpcSessionManager session = registerSession(); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
verify(tsSubService, times(1)).saveAttributes(argThat(activeStateWrite(false))); |
|||
verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite())); |
|||
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); |
|||
verify(ruleProcessor, times(1)).process(argThat(disconnectTrigger())); |
|||
} |
|||
|
|||
@Test |
|||
void givenEdgeOwnedByAnotherLiveNode_whenDisconnect_thenNoDisconnectSideEffects() { |
|||
EdgeGrpcSessionManager session = registerSession(); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); |
|||
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
verifyNoDisconnectSideEffects(); |
|||
} |
|||
|
|||
@Test |
|||
void givenOwnerNodeLeftCluster_whenDisconnect_thenInactiveStateIsPersisted() { |
|||
// the cache has no TTL by default, so a dead owner's claim must not keep the edge active forever
|
|||
EdgeGrpcSessionManager session = registerSession(); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); |
|||
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE)); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
verify(tsSubService, times(1)).saveAttributes(argThat(activeStateWrite(false))); |
|||
} |
|||
|
|||
@Test |
|||
void givenSameNodeReconnectDuringOwnershipCheck_whenDisconnect_thenNoDisconnectSideEffects() { |
|||
// the edge reconnects to this node after the stale session was removed, so the cache names this node
|
|||
EdgeGrpcSessionManager session = registerSession(); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenAnswer(invocation -> { |
|||
sessions.put(newSession()); |
|||
return SimpleTbCacheValueWrapper.wrap(THIS_NODE); |
|||
}); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
verifyNoDisconnectSideEffects(); |
|||
} |
|||
|
|||
@Test |
|||
void givenReconnectDuringInactiveWrite_whenDisconnect_thenReconnectWaitsForTheWrite() throws Exception { |
|||
// a same-node reconnect racing the guard must be ordered after the inactive write, so its active=true wins
|
|||
EdgeGrpcSessionManager session = registerSession(); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); |
|||
EdgeGrpcSessionManager replacement = newSession(); |
|||
Thread reconnect = new Thread(() -> sessions.put(replacement)); |
|||
AtomicBoolean reconnectBlockedDuringWrite = new AtomicBoolean(); |
|||
lenient().doAnswer(invocation -> { |
|||
reconnect.start(); |
|||
reconnect.join(200); |
|||
reconnectBlockedDuringWrite.set(reconnect.isAlive()); |
|||
return null; |
|||
}).when(tsSubService).saveAttributes(argThat(activeStateWrite(false))); |
|||
|
|||
onEdgeDisconnect(session); |
|||
reconnect.join(5000); |
|||
|
|||
assertThat(reconnectBlockedDuringWrite).isTrue(); |
|||
assertThat(sessions.getByEdgeId(edgeId)).isSameAs(replacement); |
|||
} |
|||
|
|||
@Test |
|||
void givenReplacedSessionDisconnectsDuringItsTeardown_whenConnect_thenNoDisconnectSideEffects() { |
|||
// the edge reconnects before its old stream is noticed dead; the old session's close fires while it is destroyed
|
|||
EdgeGrpcSessionManager old = registerSession(); |
|||
doAnswer(invocation -> { |
|||
onEdgeDisconnect(old); |
|||
return null; |
|||
}).when(old).destroyAndMarkAsZombieIfFailed(); |
|||
EdgeGrpcSessionManager replacement = newSession(); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
|
|||
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, replacement); |
|||
|
|||
verify(tsSubService, never()).saveAttributes(argThat(activeStateWrite(false))); |
|||
verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite())); |
|||
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), |
|||
argThat(msg -> TbMsgType.DISCONNECT_EVENT.equals(msg.getInternalType())), isNull()); |
|||
verify(ruleProcessor, never()).process(argThat(disconnectTrigger())); |
|||
verify(edgeIdServiceIdCache, never()).evict(edgeId); |
|||
assertThat(sessions.getByEdgeId(edgeId)).isSameAs(replacement); |
|||
assertThat(sessions.getSessionsById()).doesNotContainKey(old.getState().getSessionId()); |
|||
} |
|||
|
|||
@Test |
|||
void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() { |
|||
// the previous node reads this cache entry on disconnect, so the claim must be visible before active=true
|
|||
EdgeGrpcSessionManager session = newSession(); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
|
|||
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, session); |
|||
|
|||
InOrder inOrder = inOrder(edgeIdServiceIdCache, tsSubService); |
|||
inOrder.verify(edgeIdServiceIdCache).put(edgeId, THIS_NODE); |
|||
inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite(true))); |
|||
} |
|||
|
|||
private void verifyNoDisconnectSideEffects() { |
|||
verify(tsSubService, never()).saveAttributes(argThat(activeStateWrite(false))); |
|||
verify(tsSubService, never()).saveAttributes(argThat(lastDisconnectTimeWrite())); |
|||
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); |
|||
verify(ruleProcessor, never()).process(argThat(disconnectTrigger())); |
|||
} |
|||
|
|||
private void onEdgeDisconnect(EdgeGrpcSessionManager session) { |
|||
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, session.getState().getSessionId()); |
|||
} |
|||
|
|||
private EdgeGrpcSessionManager registerSession() { |
|||
EdgeGrpcSessionManager session = newSession(); |
|||
sessions.put(session); |
|||
return session; |
|||
} |
|||
|
|||
private EdgeGrpcSessionManager newSession() { |
|||
EdgeSessionState state = new EdgeSessionState(); |
|||
state.setEdge(edge); |
|||
EdgeGrpcSessionManager session = mock(EdgeGrpcSessionManager.class); |
|||
lenient().when(session.getState()).thenReturn(state); |
|||
return session; |
|||
} |
|||
|
|||
private ArgumentMatcher<AttributesSaveRequest> activeStateWrite(boolean active) { |
|||
return request -> request != null |
|||
&& edgeId.equals(request.getEntityId()) |
|||
&& request.getEntries().stream().anyMatch(entry -> |
|||
ACTIVITY_STATE.equals(entry.getKey()) |
|||
&& Boolean.valueOf(active).equals(entry.getBooleanValue().orElse(null))); |
|||
} |
|||
|
|||
private ArgumentMatcher<AttributesSaveRequest> lastDisconnectTimeWrite() { |
|||
return request -> request != null |
|||
&& edgeId.equals(request.getEntityId()) |
|||
&& request.getEntries().stream().anyMatch(entry -> LAST_DISCONNECT_TIME.equals(entry.getKey())); |
|||
} |
|||
|
|||
private ArgumentMatcher<NotificationRuleTrigger> disconnectTrigger() { |
|||
return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger && !edgeTrigger.isConnected(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { JsExecutor } from '../api/jsExecutor'; |
|||
|
|||
// Runs one probe as the first sandbox execution of a fresh process and reports
|
|||
// whether any error caught on stack overflow came from outside the sandbox realm.
|
|||
const call = process.argv[2]; |
|||
|
|||
(async () => { |
|||
const exec = new JsExecutor(true); |
|||
const script = await exec.compileScript(`function(msg, metadata, msgType){
|
|||
var foreign; |
|||
function attempt() { |
|||
if (foreign) return; |
|||
try { ${call}; } catch (e) { |
|||
if (e === null || typeof e !== 'object' || (e.constructor !== RangeError && e.constructor !== TypeError && e.constructor !== Error)) { |
|||
foreign = String(e && e.name); |
|||
} |
|||
} |
|||
} |
|||
function recurse() { try { recurse(); } catch (e) {} attempt(); } |
|||
recurse(); |
|||
return foreign ? 'foreign error: ' + foreign : 'isolated'; |
|||
}`);
|
|||
const out = await exec.executeScript(script, ['{}', '{}', 'X'], 20000); |
|||
process.stdout.write(String(out)); |
|||
})().catch((err) => { |
|||
process.stdout.write('probe failed: ' + String(err && err.message)); |
|||
}); |
|||
File diff suppressed because it is too large
File diff suppressed because it is too large
File diff suppressed because it is too large
File diff suppressed because it is too large
@ -0,0 +1,33 @@ |
|||
#### RPC parameters function |
|||
|
|||
<div class="divider"></div> |
|||
<br/> |
|||
|
|||
*function (): any* |
|||
|
|||
A JavaScript function returning the parameters (payload) of the RPC command used to get the value. |
|||
|
|||
**Returns:** |
|||
|
|||
Payload object or primitive to be used as the parameters of the RPC get value command. |
|||
|
|||
<div class="divider"></div> |
|||
|
|||
##### Examples |
|||
|
|||
* Request the state of a specific pin: |
|||
|
|||
```javascript |
|||
return { pin: 5 }; |
|||
{:copy-code} |
|||
``` |
|||
|
|||
* Request several values with a single RPC call: |
|||
|
|||
```javascript |
|||
return { keys: ['temperature', 'humidity'] }; |
|||
{:copy-code} |
|||
``` |
|||
|
|||
<br> |
|||
<br> |
|||
@ -1,8 +1,8 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
@import 'flag-icons/sass/_variables'; |
|||
$flag-icons-path: '/assets/flags'; |
|||
$flag-icons-rect-path: ''; |
|||
$flag-icons-use-square: false; |
|||
@import 'flag-icons/sass/_flag-icons-base'; |
|||
@import 'flag-icons/sass/_flag-icons-list'; |
|||
@use 'flag-icons/sass/variables' with ( |
|||
$flag-icons-path: '/assets/flags', |
|||
$flag-icons-rect-path: '', |
|||
$flag-icons-use-square: false |
|||
); |
|||
@use 'flag-icons/sass/flag-icons-list'; |
|||
|
|||
File diff suppressed because it is too large
Loading…
Reference in new issue