Browse Source

Merge pull request #16251 from thingsboard/feature/ai-websocket-channel

Made AI features work on instances behind NAT or a firewall, with no public base URL required
pull/16347/head
Viacheslav Klimov 2 months ago
committed by GitHub
parent
commit
c70d48a7aa
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 9
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  2. 8
      application/src/main/java/org/thingsboard/server/controller/AiDeviceDashboardController.java
  3. 13
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  4. 64
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  5. 8
      application/src/main/java/org/thingsboard/server/service/ai/LocalTbAiTokenProvider.java
  6. 44
      application/src/main/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProvider.java
  7. 8
      application/src/main/java/org/thingsboard/server/service/ai/TbAiConfiguration.java
  8. 2
      application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java
  9. 3
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  10. 41
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  11. 2
      application/src/main/java/org/thingsboard/server/service/ai/dashboard/AiDeviceDashboardService.java
  12. 13
      application/src/main/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardService.java
  13. 4
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  14. 65
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  15. 9
      application/src/main/java/org/thingsboard/server/service/ai/tool/DefaultAiToolService.java
  16. 204
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
  17. 240
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  18. 16
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelExchange.java
  19. 354
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
  20. 14
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
  21. 11
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelUnavailableException.java
  22. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperation.java
  23. 42
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
  24. 327
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  25. 260
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutor.java
  26. 15
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java
  27. 40
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnContext.java
  28. 14
      application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiDataDeletionTaskProcessor.java
  29. 14
      application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiTenantDataDeletionTaskProcessor.java
  30. 14
      application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiUserDataDeletionTaskProcessor.java
  31. 26
      application/src/main/resources/thingsboard.yml
  32. 53
      application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java
  33. 8
      application/src/test/java/org/thingsboard/server/controller/AbstractOnPremiseAiControllerTest.java
  34. 53
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerOnPremiseTest.java
  35. 64
      application/src/test/java/org/thingsboard/server/controller/AiChatControllerTest.java
  36. 19
      application/src/test/java/org/thingsboard/server/controller/AiDeviceDashboardControllerOnPremiseTest.java
  37. 39
      application/src/test/java/org/thingsboard/server/controller/AiDeviceDashboardControllerTest.java
  38. 89
      application/src/test/java/org/thingsboard/server/controller/AiSolutionControllerOnPremiseTest.java
  39. 90
      application/src/test/java/org/thingsboard/server/controller/AiSolutionControllerTest.java
  40. 16
      application/src/test/java/org/thingsboard/server/controller/AiToolControllerOnPremiseTest.java
  41. 29
      application/src/test/java/org/thingsboard/server/controller/AiToolControllerTest.java
  42. 135
      application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
  43. 86
      application/src/test/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProviderTest.java
  44. 69
      application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
  45. 43
      application/src/test/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardServiceTest.java
  46. 122
      application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
  47. 20
      application/src/test/java/org/thingsboard/server/service/ai/tool/DefaultAiToolServiceTest.java
  48. 310
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
  49. 200
      application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
  50. 135
      application/src/test/java/org/thingsboard/server/service/ai/transport/FakeTbAiServer.java
  51. 233
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java
  52. 91
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java
  53. 102
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java
  54. 209
      application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutorTest.java
  55. 34
      application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java
  56. 56
      application/src/test/java/org/thingsboard/server/service/housekeeper/processor/AiDataDeletionTaskProcessorsTest.java
  57. 3
      application/src/test/resources/application-test.properties
  58. 2
      pom.xml

9
application/src/main/java/org/thingsboard/server/controller/AiChatController.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@ -28,6 +29,7 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiSettings;
import org.thingsboard.server.service.ai.chat.AiChatService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import reactor.core.publisher.Flux;
import java.util.UUID;
@ -43,6 +45,7 @@ class AiChatController extends BaseController {
private final AiChatService aiChatService;
private final TbAiSettings aiSettings;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping
@ -97,11 +100,13 @@ class AiChatController extends BaseController {
@PathVariable UUID chatId,
@RequestBody JsonNode request,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage
@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage,
HttpServletRequest httpRequest
) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return withTraceLogging(chatId, aiChatService.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, user));
String clientOrigin = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest);
return withTraceLogging(chatId, aiChatService.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, clientOrigin, user));
}
private Flux<ServerSentEvent<String>> withTraceLogging(UUID chatId, Flux<ServerSentEvent<String>> events) {

8
application/src/main/java/org/thingsboard/server/controller/AiDeviceDashboardController.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
@ -19,6 +20,7 @@ import org.thingsboard.server.dao.service.validator.DashboardDataValidator;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.dashboard.AiDeviceDashboardService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.UUID;
@ -32,20 +34,22 @@ class AiDeviceDashboardController extends BaseController {
private final AiDeviceDashboardService aiDeviceDashboardService;
private final DashboardDataValidator dashboardDataValidator;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{deviceId}/dashboard")
JsonNode generateDashboard(
@PathVariable UUID deviceId,
@RequestBody JsonNode request,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest
) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
checkDeviceId(new DeviceId(deviceId), Operation.READ, Operation.READ_ATTRIBUTES, Operation.READ_TELEMETRY);
accessControlService.checkPermission(user, Resource.DASHBOARD, Operation.CREATE);
dashboardDataValidator.validateMaxDashboardsPerTenant(user.getTenantId());
return aiDeviceDashboardService.generateDashboard(deviceId, request, tbAccessToken, user);
return aiDeviceDashboardService.generateDashboard(deviceId, request, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
}
}

13
application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -21,6 +22,7 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.solution.AiSolutionService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.UUID;
@ -33,6 +35,7 @@ import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUT
public class AiSolutionController extends BaseController {
private final AiSolutionService aiSolutionService;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/start")
@ -97,19 +100,21 @@ public class AiSolutionController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/install")
public JsonNode installSolution(@PathVariable UUID solutionId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken) throws ThingsboardException {
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.installSolution(solutionId, tbAccessToken, user);
return aiSolutionService.installSolution(solutionId, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@DeleteMapping("/{solutionId}/uninstall")
public JsonNode uninstallSolution(@PathVariable UUID solutionId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken) throws ThingsboardException {
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.uninstallSolution(solutionId, tbAccessToken, user);
return aiSolutionService.uninstallSolution(solutionId, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")

64
application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java

@ -6,11 +6,9 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
@ -21,6 +19,10 @@ import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.stats.TbApiUsageReportClient;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
import org.thingsboard.server.service.ai.transport.TbAiChannelUnavailableException;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Flux;
@ -41,8 +43,8 @@ class DefaultTbAiService implements TbAiService {
private final TbApiUsageStateService apiUsageStateService;
private final TbApiUsageReportClient apiUsageReportClient;
private final Optional<TbAiTokenProvider> tokenProvider;
private final TbAiClient tbAiClient;
private final TbAiSettings aiSettings;
private final TbAiOperations operations;
@Override
public JsonNode process(TbAiCall<TbAiResponse> call, SecurityUser user, boolean checkCredits) {
@ -50,7 +52,7 @@ class DefaultTbAiService implements TbAiService {
if (checkCredits) {
checkApiUsage(user);
}
TbAiResponse response = call.apply(tbAiClient, createTokenProvider(user));
TbAiResponse response = call.apply(createCheckedTokenProvider(user));
return processResponse(response, user);
}
@ -58,11 +60,12 @@ class DefaultTbAiService implements TbAiService {
public Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> call, SecurityUser user) {
checkEnabled();
checkApiUsage(user);
TbAiClient.TokenProvider tokenProvider = createCheckedTokenProvider(user);
return Flux.defer(() -> {
// Eager subscribe so client cancel does not drop the trailing creditsUsed event.
Sinks.Many<ServerSentEvent<String>> clientSink = Sinks.many().unicast().onBackpressureBuffer();
call.apply(tbAiClient, createTokenProvider(user))
call.apply(tokenProvider)
.timeout(Duration.ofSeconds(aiSettings.getSseInactivityTimeoutSeconds()))
.subscribe(
event -> {
@ -98,7 +101,7 @@ class DefaultTbAiService implements TbAiService {
}
try {
return JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_AND_ENUMS_JSON_MAPPER.treeToValue(
process(TbAiClient::getApiUsageInfo, user, false), ApiUsageInfo.class);
process(tokenProvider -> operations.execute(new TbAiOperation(ChannelProtocol.USAGE_GET, null), user, tokenProvider), user, false), ApiUsageInfo.class);
} catch (Exception e) {
log.warn("[{}][{}] Couldn't get AI API usage info", user.getTenantId(), user.getId(), e);
return new ApiUsageInfo(Map.of(), 0);
@ -111,8 +114,14 @@ class DefaultTbAiService implements TbAiService {
}
}
private TbAiClient.TokenProvider createTokenProvider(SecurityUser user) {
/**
* Reads the token before the call reaches the channel pool, so a token the user may not have (e.g. AI is not in the
* subscription plan) fails the call with its own error rather than as a channel that cannot be opened, and is
* checked on every call rather than only when a channel opens.
*/
private TbAiClient.TokenProvider createCheckedTokenProvider(SecurityUser user) {
TbAiTokenProvider provider = tokenProvider.orElseThrow(() -> new ThingsboardRuntimeException("AI feature is not available", ThingsboardErrorCode.BAD_REQUEST_PARAMS));
provider.getToken(user);
return TbAiTokenProviderFactory.userScoped(provider, user);
}
@ -139,43 +148,10 @@ class DefaultTbAiService implements TbAiService {
private static String toUserFriendlyMessage(Throwable e) {
if (e instanceof TimeoutException) {
return "Request timed out";
} else if (e instanceof WebClientRequestException) {
return "Service unavailable";
} else if (e instanceof WebClientResponseException wcre) {
return toUserFriendlyMessage(wcre);
}
return "Internal error";
}
private static String toUserFriendlyMessage(WebClientResponseException wcre) {
var status = HttpStatus.resolve(wcre.getStatusCode().value());
if (status == null) {
return "Internal error";
}
if (status == HttpStatus.UNAUTHORIZED || status == HttpStatus.FORBIDDEN) {
return status.getReasonPhrase();
}
String errorMessage = null;
try {
JsonNode errorResponse = JacksonUtil.toJsonNode(wcre.getResponseBodyAsString());
if (errorResponse.hasNonNull("message")) {
errorMessage = errorResponse.get("message").asText();
}
} catch (IllegalArgumentException ignored) {}
if (errorMessage != null) {
return errorMessage;
}
// fallback
if (status.is4xxClientError()) {
return "Invalid request";
}
if (status.is5xxServerError()) {
} else if (e instanceof TbAiChannelUnavailableException) {
return "Service unavailable";
} else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) {
return e.getMessage();
}
return "Internal error";
}

8
application/src/main/java/org/thingsboard/server/service/ai/LocalTbAiTokenProvider.java

@ -37,7 +37,7 @@ import java.util.concurrent.TimeUnit;
@Component
@TbCoreComponent
@ConditionalOnExpression("'${TB_AI_JWT_SIGNING_KEY:}' != ''")
@ConditionalOnExpression("'${ai.jwt.signing_key:}' != ''")
class LocalTbAiTokenProvider implements TbAiTokenProvider {
private final TbAiTokenFactory tokenFactory;
@ -47,9 +47,9 @@ class LocalTbAiTokenProvider implements TbAiTokenProvider {
// AI-related settings are read directly from environment variables, not yaml properties: they are
// managed-service settings, not operator-tunable configuration.
public LocalTbAiTokenProvider(@Value("${TB_AI_JWT_ISSUER:local}") String issuer,
@Value("${TB_AI_JWT_SIGNING_KEY}") String signingKey,
@Value("${TB_AI_JWT_EXPIRATION_TIME_MINUTES:60}") int expirationTimeMinutes,
public LocalTbAiTokenProvider(@Value("${ai.jwt.issuer:local}") String issuer,
@Value("${ai.jwt.signing_key}") String signingKey,
@Value("${ai.jwt.expiration_time_minutes:60}") int expirationTimeMinutes,
@Value("${cache.tbAiAccessTokens.timeToLiveInMinutes:60}") int cacheTtlMinutes,
@Value("${cache.tbAiAccessTokens.maxSize:20000}") int cacheMaxSize,
SystemSecurityService systemSecurityService,

44
application/src/main/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProvider.java

@ -2,12 +2,10 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai;
import org.springframework.beans.factory.annotation.Value;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
@ -16,32 +14,20 @@ import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;
// The handshake carries no Origin: the origin TB AI uses comes from the channel's hello and start frames.
@Component
@TbCoreComponent
@ConditionalOnExpression("'${TB_AI_JWT_SIGNING_KEY:}' == ''")
@RequiredArgsConstructor
@ConditionalOnExpression("'${ai.jwt.signing_key:}' == ''")
class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
private final SubscriptionService subscriptionService;
private final SystemSecurityService systemSecurityService;
private final ProjectInfo projectInfo;
private final String coreBaseUrl;
OnPremiseTbAiTokenProvider(SubscriptionService subscriptionService,
SystemSecurityService systemSecurityService,
ProjectInfo projectInfo,
@Value("${TB_CORE_BASE_URL:}") String coreBaseUrl) {
this.subscriptionService = subscriptionService;
this.systemSecurityService = systemSecurityService;
this.projectInfo = projectInfo;
this.coreBaseUrl = coreBaseUrl;
}
@Override
public String getToken(SecurityUser user) {
@ -50,8 +36,7 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
@Override
public Map<String, String> getAdditionalInfo(SecurityUser user) {
String origin = StringUtils.isNotEmpty(coreBaseUrl) ? coreBaseUrl : resolveOrigin(user);
return additionalInfo(user.getUuidId(), user.getTenantId(), origin);
return additionalInfo(user.getUuidId(), user.getTenantId());
}
@Override
@ -66,11 +51,7 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
@Override
public Map<String, String> getAdditionalInfo(TenantId tenantId, UserId userId) {
// Background deletion tasks only need the Origin header to be present; the AI service never calls back
// to ThingsBoard for a delete. Skip TB_CORE_BASE_URL and the white-labeling chain (the tenant may already
// be gone by the time the task runs) and take the system-level general settings base URL instead.
String origin = systemSecurityService.getBaseUrl(tenantId, null, null);
return additionalInfo(userId.getId(), tenantId, origin);
return additionalInfo(userId.getId(), tenantId);
}
private String requireAiToken(Supplier<RuntimeException> onMissingToken) {
@ -81,20 +62,11 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
return token;
}
private String resolveOrigin(SecurityUser user) {
String origin = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null);
if ("localhost".equals(URI.create(origin).getHost())) {
throw new ThingsboardRuntimeException("Please configure the base URL under Login white labeling or General settings at the sysadmin level", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return origin;
}
private Map<String, String> additionalInfo(UUID userId, TenantId tenantId, String origin) {
private Map<String, String> additionalInfo(UUID userId, TenantId tenantId) {
return Map.of(
TbAiHeaders.USER_ID, userId.toString(),
TbAiHeaders.TENANT_ID, tenantId.getId().toString(),
TbAiHeaders.TB_VERSION, projectInfo.getProjectVersion(),
HttpHeaders.ORIGIN, origin
TbAiHeaders.TB_VERSION, projectInfo.getProjectVersion()
);
}

8
application/src/main/java/org/thingsboard/server/service/ai/TbAiConfiguration.java

@ -5,18 +5,16 @@ package org.thingsboard.server.service.ai;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.server.queue.util.TbCoreComponent;
@Configuration(proxyBeanMethods = false)
@TbCoreComponent
class TbAiConfiguration {
// TB_AI_BASE_URL is read directly from an environment variable, not a yaml property: it is a
// managed-service setting, not operator-tunable configuration.
@Bean
TbAiClient tbAiClient(@Value("${TB_AI_BASE_URL:https://ai.thingsboard.cloud}") String baseUrl) {
return new TbAiClient(baseUrl);
TbAiChannelClient tbAiChannelClient(@Value("${ai.base_url:https://ai.thingsboard.cloud}") String baseUrl) {
return new TbAiChannelClient(baseUrl);
}
}

2
application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java

@ -28,7 +28,7 @@ public interface TbAiService {
@FunctionalInterface
interface TbAiCall<T> {
T apply(TbAiClient client, TbAiClient.TokenProvider tokenProvider);
T apply(TbAiClient.TokenProvider tokenProvider);
}

3
application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java

@ -22,7 +22,8 @@ public interface AiChatService {
void deleteChat(UUID chatId, SecurityUser user);
Flux<ServerSentEvent<String>> sendChatMessage(
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, SecurityUser user
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
);
}

41
application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java

@ -6,8 +6,14 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Flux;
@ -19,48 +25,47 @@ import java.util.UUID;
class DefaultAiChatService implements AiChatService {
private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport;
private final TbAiOperations operations;
@Override
public JsonNode createChat(JsonNode request, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.createChat(request, tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false);
}
@Override
public void updateChat(UUID chatId, JsonNode request, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> {
return client.updateChat(chatId, request, tokenProvider);
}, user, false);
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request)), user, tokenProvider), user, false);
}
@Override
public JsonNode listChats(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.listChats(tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false);
}
@Override
public JsonNode getChatMessages(UUID chatId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.getChatMessages(chatId, tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
}
@Override
public void deleteChat(UUID chatId, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> {
return client.deleteChat(chatId, tokenProvider);
}, user, false);
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
}
@Override
public Flux<ServerSentEvent<String>> sendChatMessage(
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, SecurityUser user
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
) {
return tbAiService.processStream(chatId, (client, tokenProvider) -> {
return client.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, tokenProvider);
return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
return tbAiTransport.sendChatMessage(chatId, request, context);
}, user);
}

2
application/src/main/java/org/thingsboard/server/service/ai/dashboard/AiDeviceDashboardService.java

@ -9,6 +9,6 @@ import java.util.UUID;
public interface AiDeviceDashboardService {
JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, SecurityUser user);
JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, String clientOrigin, SecurityUser user);
}

13
application/src/main/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardService.java

@ -6,7 +6,12 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.DashboardOperationRequest;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
@ -17,11 +22,13 @@ import java.util.UUID;
class DefaultAiDeviceDashboardService implements AiDeviceDashboardService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override
public JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, SecurityUser user) {
return tbAiService.process((client, tokenProvider) ->
client.generateDashboard(deviceId, request, tbAccessToken, tokenProvider), user);
public JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(deviceId, request)),
new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user);
}
}

4
application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java

@ -24,9 +24,9 @@ public interface AiSolutionService {
void clearStep(UUID solutionId, SolutionStep step, SecurityUser user);
JsonNode installSolution(UUID solutionId, String tbAccessToken, SecurityUser user);
JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, SecurityUser user);
JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
void deleteSolution(UUID solutionId, SecurityUser user);

65
application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java

@ -7,7 +7,15 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
@ -18,75 +26,68 @@ import java.util.UUID;
public class DefaultAiSolutionService implements AiSolutionService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override
public JsonNode startNew(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.startNewSolution(tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false);
}
@Override
public JsonNode getSolution(UUID solutionId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.getSolution(solutionId, tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}
@Override
public JsonNode getSolutions(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.getSolutions(tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_LIST, null), user, tokenProvider), user, false);
}
@Override
public JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.sendSolutionMessage(solutionId, step, message, tokenProvider);
}, user);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message)), user, tokenProvider), user);
}
@Override
public JsonNode createSolution(UUID solutionId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.createSolution(solutionId, tokenProvider);
}, user);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user);
}
@Override
public JsonNode updateData(UUID solutionId, String dataKey, JsonNode value, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.updateData(solutionId, dataKey, value, tokenProvider);
}, user);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value)), user, tokenProvider), user);
}
@Override
public void clearStep(UUID solutionId, SolutionStep step, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> {
return client.clearStep(solutionId, step, tokenProvider);
}, user, false);
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false);
}
@Override
public JsonNode installSolution(UUID solutionId, String tbAccessToken, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.installSolution(solutionId, tbAccessToken, tokenProvider);
}, user, false);
public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId)),
new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user, false);
}
@Override
public JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.uninstallSolution(solutionId, tbAccessToken, tokenProvider);
}, user, false);
public JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId)),
new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user, false);
}
@Override
public void deleteSolution(UUID solutionId, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> {
return client.deleteSolution(solutionId, tokenProvider);
}, user, false);
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}
}

9
application/src/main/java/org/thingsboard/server/service/ai/tool/DefaultAiToolService.java

@ -5,8 +5,11 @@ package org.thingsboard.server.service.ai.tool;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser;
@Service
@ -15,12 +18,12 @@ import org.thingsboard.server.service.security.model.SecurityUser;
class DefaultAiToolService implements AiToolService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override
public JsonNode resolveToolApproval(JsonNode decision, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> {
return client.resolveToolApproval(decision, tokenProvider);
}, user, false);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, decision), user, tokenProvider), user, false);
}
}

204
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java

@ -0,0 +1,204 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.OperationResult;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Runs one operation on a pooled channel and waits for its {@code operation.result}. An operation the channel did not
* start (a {@code draining} or {@code too_many_operations} refusal, or a 1001 close before any frame for it: TB AI
* closes with 1001 only when nothing runs on the connection) is retried once on a new channel; any other failure after
* it was sent is an error, so an operation never runs twice. That includes
* {@link ChannelProtocol#CLOSE_EXCHANGES_ABORTED}, the close of a connection whose running operations were aborted.
*/
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
class ChannelTbAiOperations {
static final Duration OPERATION_TIMEOUT = Duration.ofMinutes(30);
private final TbAiChannelPool pool;
private final TbAiRequestExecutor requestExecutor;
TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) {
boolean fresh = false;
for (int attempt = 1; ; attempt++) {
TbAiPooledConnection connection = acquire(context, fresh);
var call = new OperationCall(operation, context, connection);
try {
return call.run();
} catch (NotStartedException e) {
if (attempt >= 2) {
log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage());
return failure("Service unavailable");
}
log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage());
fresh = true;
}
}
}
private TbAiPooledConnection acquire(TbAiTurnContext context, boolean fresh) {
try {
return pool.acquire(context, fresh).get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TbAiChannelUnavailableException("Interrupted while opening the AI channel", e);
} catch (TimeoutException e) {
throw new TbAiChannelUnavailableException("Timed out opening the AI channel", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof RuntimeException runtime) {
throw runtime;
}
throw new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(e), e);
}
}
static TbAiResponse failure(String message) {
return TbAiResponse.builder().success(false).error(message).build();
}
static TbAiResponse toResponse(OperationResult result) {
TbAiResponse response;
if (result.isSuccess()) {
response = TbAiResponse.builder().success(true).value(result.body()).build();
} else {
JsonNode message = result.body() != null ? result.body().get("message") : null;
String error = message != null && message.isTextual() ? message.asText() : reasonPhrase(result.status());
response = TbAiResponse.builder().success(false).error(error).build();
}
response.setCreditsUsed(result.creditsUsed());
return response;
}
private static String reasonPhrase(int status) {
HttpStatus resolved = HttpStatus.resolve(status);
return resolved != null ? resolved.getReasonPhrase() : "Internal error";
}
private static final class NotStartedException extends RuntimeException {
NotStartedException(String message) {
super(message, null, false, false);
}
}
private final class OperationCall implements TbAiChannelExchange {
private final TbAiOperation operation;
private final TbAiTurnContext context;
private final TbAiPooledConnection connection;
private final CompletableFuture<TbAiResponse> result = new CompletableFuture<>();
private final AtomicBoolean finished = new AtomicBoolean();
private volatile boolean frameSeen;
private volatile String op;
private OperationCall(TbAiOperation operation, TbAiTurnContext context, TbAiPooledConnection connection) {
this.operation = operation;
this.context = context;
this.connection = connection;
}
TbAiResponse run() {
ChannelFrame start = ChannelFrame.request(operation.type(), connection.codec().toPayload(operation.payload()))
.withOrigin(context.clientOrigin());
op = start.id();
try {
connection.start(this, start);
} catch (ChannelException e) {
finish();
throw new NotStartedException("channel closed before the operation was sent");
}
try {
return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return failure("Request interrupted");
} catch (TimeoutException e) {
return failure("Request timed out");
} catch (ExecutionException e) {
if (e.getCause() instanceof NotStartedException notStarted) {
throw notStarted;
}
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e));
return failure("Service unavailable");
} finally {
finish();
}
}
@Override
public void onFrame(TbAiPooledConnection frameConnection, ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.TB_REQUEST -> {
frameSeen = true;
requestExecutor.serve(frameConnection.session(), frame, frameConnection.codec(), context, frameConnection.maxFrameBytes());
}
case ChannelProtocol.OPERATION_RESULT -> result.complete(toResponse(
frameConnection.codec().fromPayload(frame.payload(), OperationResult.class)));
case ChannelProtocol.ERROR -> onError(frameConnection, frame);
default -> {
frameSeen = true;
log.debug("Ignoring AI channel frame '{}' during operation '{}'", frame.type(), operation.type());
}
}
} catch (ChannelException e) {
result.completeExceptionally(e);
}
}
@Override
public void onClose(int code, String reason) {
if (!frameSeen && code == ChannelProtocol.CLOSE_GOING_AWAY) {
result.completeExceptionally(new NotStartedException("channel closed [" + code + "] " + reason));
} else {
result.completeExceptionally(new ChannelException("AI channel closed [" + code + "] " + reason));
}
}
private void onError(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChannelError error = frameConnection.codec().fromPayload(frame.payload(), ChannelError.class);
if (ChannelError.DRAINING.equals(error.code())) {
frameConnection.retire();
result.completeExceptionally(new NotStartedException(error.message()));
} else if (ChannelError.TOO_MANY_OPERATIONS.equals(error.code())) {
result.completeExceptionally(new NotStartedException(error.message()));
} else {
log.warn("AI channel error during operation '{}' {}: {}", operation.type(), error.code(), error.message());
result.completeExceptionally(new CompletionException(new ChannelException(error.message())));
}
}
private void finish() {
if (finished.compareAndSet(false, true)) {
connection.finish(op, System.nanoTime());
}
}
}
}

240
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java

@ -0,0 +1,240 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatEventPayload;
import org.thingsboard.ai.common.channel.ChatTurnRequest;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.queue.util.TbCoreComponent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or
* closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails
* the turn with "Service unavailable".
*/
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
class ChannelTbAiTransport implements TbAiTransport {
private static final String HEARTBEAT = "heartbeat";
private final TbAiChannelPool pool;
private final TbAiRequestExecutor requestExecutor;
@Override
public Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context) {
return Flux.create(sink -> {
var turn = new ChannelTurn(chatId, request, context, sink);
sink.onDispose(turn::abandon);
turn.start(false);
});
}
private static ServerSentEvent<String> errorEvent(String message) {
return ServerSentEvent.<String>builder()
.event("error")
.data(JacksonUtil.toString(JacksonUtil.newObjectNode().put("message", message)))
.build();
}
private final class ChannelTurn implements TbAiChannelExchange {
private final UUID chatId;
private final JsonNode request;
private final TbAiTurnContext context;
private final FluxSink<ServerSentEvent<String>> sink;
private final AtomicBoolean finished = new AtomicBoolean();
private volatile TbAiPooledConnection connection;
private volatile String op;
private volatile boolean frameSeen;
private volatile boolean retried;
private ChannelTurn(UUID chatId, JsonNode request, TbAiTurnContext context, FluxSink<ServerSentEvent<String>> sink) {
this.chatId = chatId;
this.request = request;
this.context = context;
this.sink = sink;
}
void start(boolean fresh) {
pool.acquire(context, fresh).whenComplete((acquired, error) -> {
if (error != null) {
connectFailed(error instanceof CompletionException && error.getCause() != null ? error.getCause() : error);
} else {
attach(acquired);
}
});
}
void abandon() {
if (finished.get()) {
return;
}
TbAiPooledConnection current = connection;
if (current != null) {
try {
current.send(new ChannelFrame(ChannelProtocol.CANCEL, null, null, null, op));
} catch (ChannelException e) {
log.debug("[{}] Failed to cancel the AI turn: {}", chatId, e.getMessage());
}
}
end(null);
}
@Override
public void onFrame(TbAiPooledConnection frameConnection, ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.CHAT_EVENT -> {
frameSeen = true;
onChatEvent(frameConnection, frame);
}
case ChannelProtocol.TB_REQUEST -> {
frameSeen = true;
requestExecutor.serve(frameConnection.session(), frame, frameConnection.codec(), context, frameConnection.maxFrameBytes());
}
case ChannelProtocol.TURN_END -> end(null);
case ChannelProtocol.ERROR -> onError(frameConnection, frame);
default -> log.debug("[{}] Ignoring AI channel frame '{}'", chatId, frame.type());
}
} catch (ChannelException e) {
log.warn("[{}] Malformed AI channel frame '{}': {}", chatId, frame.type(), e.getMessage());
end(errorEvent("Internal error"));
}
}
@Override
public void onClose(int code, String reason) {
if (finished.get()) {
return;
}
if (!frameSeen && code == ChannelProtocol.CLOSE_GOING_AWAY && retry()) {
return;
}
if (!frameSeen) {
fail(new TbAiChannelUnavailableException("AI channel closed before the turn started [" + code + "] " + reason, null));
} else if (code == ChannelProtocol.CLOSE_NORMAL) {
end(null);
} else {
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason);
end(errorEvent("Service unavailable"));
}
}
private void connectFailed(Throwable error) {
if (error instanceof TbAiChannelRejectedException rejected) {
end(errorEvent(rejected.getMessage()));
} else if (error instanceof TbAiChannelUnavailableException unavailable) {
fail(unavailable);
} else {
fail(new TbAiChannelUnavailableException("Cannot open the AI channel: " + error.getMessage(), error));
}
}
private void attach(TbAiPooledConnection acquired) {
if (sink.isCancelled() || finished.get()) {
acquired.unreserve(System.nanoTime());
return;
}
ChannelFrame start = ChannelFrame.request(ChannelProtocol.CHAT_SEND,
acquired.codec().toPayload(new ChatTurnRequest(chatId, request, context.acceptLanguage())))
.withOrigin(context.clientOrigin());
op = start.id();
connection = acquired;
try {
acquired.start(this, start);
} catch (ChannelException e) {
connection = null;
acquired.finish(op, System.nanoTime());
if (!retry()) {
fail(new TbAiChannelUnavailableException("AI channel closed before the turn started", e));
}
}
}
private void onChatEvent(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChatEventPayload event = frameConnection.codec().fromPayload(frame.payload(), ChatEventPayload.class);
if (HEARTBEAT.equals(event.name())) {
sink.next(ServerSentEvent.<String>builder().comment(HEARTBEAT).build());
return;
}
sink.next(ServerSentEvent.<String>builder()
.event(event.name())
.data(event.data() != null ? event.data().toString() : null)
.build());
}
private void onError(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChannelError error = frameConnection.codec().fromPayload(frame.payload(), ChannelError.class);
boolean notStarted = ChannelError.DRAINING.equals(error.code()) || ChannelError.TOO_MANY_OPERATIONS.equals(error.code());
if (ChannelError.DRAINING.equals(error.code())) {
frameConnection.retire();
}
if (notStarted && !frameSeen) {
release();
if (retry()) {
return;
}
fail(new TbAiChannelUnavailableException("AI channel refused the turn: " + error.message(), null));
return;
}
log.warn("[{}] AI channel error {}: {}", chatId, error.code(), error.message());
end(errorEvent("Internal error"));
}
private boolean retry() {
if (retried || finished.get()) {
return false;
}
retried = true;
log.debug("[{}] AI turn was not started, retrying on a new channel", chatId);
connection = null;
start(true);
return true;
}
private void fail(RuntimeException error) {
if (finished.compareAndSet(false, true)) {
release();
sink.error(error);
}
}
private void end(ServerSentEvent<String> lastEvent) {
if (finished.compareAndSet(false, true)) {
release();
if (lastEvent != null) {
sink.next(lastEvent);
}
sink.complete();
}
}
private void release() {
TbAiPooledConnection current = connection;
if (current != null) {
connection = null;
current.finish(op, System.nanoTime());
}
}
}
}

16
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelExchange.java

@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.thingsboard.ai.common.channel.ChannelFrame;
/**
* One chat turn or operation on a pooled channel. Callbacks run on the channel's I/O thread and must not block.
*/
interface TbAiChannelExchange {
void onFrame(TbAiPooledConnection connection, ChannelFrame frame);
void onClose(int code, String reason);
}

354
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java

@ -0,0 +1,354 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.ThingsBoardThreadFactory;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.queue.util.TbCoreComponent;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.LongSupplier;
/**
* Channels to TB AI on this tb-core node, one per user in the common case: each call carries its own client origin.
* <ul>
* <li>Calls of one user share a channel; concurrent first calls share one handshake.</li>
* <li>At most {@code maxConnections} pooled channels per node. When full, the least recently used idle channel is
* closed; if none is idle the call gets a transient channel that closes after it, so a full pool never delays or
* refuses a call.</li>
* <li>One sweeper closes channels idle for {@code idleTimeout} and retires channels older than {@code maxAge}, which
* bounds how long a revoked token or changed subscription keeps working on an open channel.</li>
* <li>Background calls (housekeeper deletions) always use transient channels.</li>
* <li>After {@link #shutdown} no channel opens, so a call refused by the shutdown is not retried on a new one.</li>
* </ul>
*/
@Slf4j
@Component
@TbCoreComponent
class TbAiChannelPool {
record PoolKey(TenantId tenantId, UserId userId) {}
private static final Duration SWEEP_INTERVAL = Duration.ofSeconds(5);
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(15);
private static final int MAX_ACQUIRE_ATTEMPTS = 3;
private final TbAiChannelClient channelClient;
private final int maxConnections;
private final int maxOperationsPerConnection;
private final long idleTimeoutNanos;
private final long maxAgeNanos;
private final LongSupplier nanoClock;
private final ConcurrentMap<PoolKey, Group> groups = new ConcurrentHashMap<>();
private final AtomicInteger pooledConnections = new AtomicInteger();
private final ScheduledExecutorService sweeper;
private volatile boolean shutdown;
@Autowired
TbAiChannelPool(TbAiChannelClient channelClient,
@Value("${ai.channel.pool.max_connections:2000}") int maxConnections,
@Value("${ai.channel.pool.max_operations_per_connection:20}") int maxOperationsPerConnection,
@Value("${ai.channel.pool.idle_timeout_seconds:60}") long idleTimeoutSeconds,
@Value("${ai.channel.pool.max_age_minutes:10}") long maxAgeMinutes) {
this(channelClient, maxConnections, maxOperationsPerConnection, Duration.ofSeconds(idleTimeoutSeconds),
Duration.ofMinutes(maxAgeMinutes), System::nanoTime, true);
}
TbAiChannelPool(TbAiChannelClient channelClient, int maxConnections, int maxOperationsPerConnection,
Duration idleTimeout, Duration maxAge, LongSupplier nanoClock, boolean startSweeper) {
this.channelClient = channelClient;
this.maxConnections = maxConnections;
this.maxOperationsPerConnection = maxOperationsPerConnection;
this.idleTimeoutNanos = idleTimeout.toNanos();
this.maxAgeNanos = maxAge.toNanos();
this.nanoClock = nanoClock;
if (startSweeper) {
this.sweeper = Executors.newSingleThreadScheduledExecutor(ThingsBoardThreadFactory.forName("tb-ai-channel-pool"));
this.sweeper.scheduleWithFixedDelay(this::sweep, SWEEP_INTERVAL.toMillis(), SWEEP_INTERVAL.toMillis(), TimeUnit.MILLISECONDS);
} else {
this.sweeper = null;
}
}
/**
* A channel with one slot reserved for the caller, who must give it back through
* {@link TbAiPooledConnection#finish} or {@link TbAiPooledConnection#unreserve}. {@code fresh} skips the open
* channels, for a retry after a channel refused the call. Fails with {@link TbAiChannelUnavailableException} or
* {@link TbAiChannelRejectedException}.
*/
CompletableFuture<TbAiPooledConnection> acquire(TbAiTurnContext context, boolean fresh) {
return acquire(context, fresh, 1);
}
private CompletableFuture<TbAiPooledConnection> acquire(TbAiTurnContext context, boolean fresh, int attempt) {
if (shutdown) {
return CompletableFuture.failedFuture(new TbAiChannelUnavailableException("Server is shutting down", null));
}
if (context.isBackground()) {
return connect(context, null, false);
}
PoolKey key = new PoolKey(context.tenantId(), context.userId());
CompletableFuture<TbAiPooledConnection> pending = null;
if (!fresh) {
Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) {
long now = nanoClock.getAsLong();
for (int i = group.connections.size() - 1; i >= 0; i--) {
TbAiPooledConnection connection = group.connections.get(i);
if (connection.tryReserve(now)) {
return CompletableFuture.completedFuture(connection);
}
}
pending = group.connecting;
}
}
if (pending != null) {
return pending.thenCompose(connection -> connection.tryReserve(nanoClock.getAsLong())
? CompletableFuture.completedFuture(connection)
: retryAcquire(context, attempt));
}
boolean pooled = tryTakePoolSlot() || (evictIdleConnection() && tryTakePoolSlot());
if (!pooled) {
log.debug("[{}] AI channel pool is full ({}), using a transient channel", key, maxConnections);
return connect(context, key, false);
}
Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) {
if (!fresh) {
CompletableFuture<TbAiPooledConnection> started = group.connecting;
if (started != null) {
pooledConnections.decrementAndGet();
return started.thenCompose(connection -> connection.tryReserve(nanoClock.getAsLong())
? CompletableFuture.completedFuture(connection)
: retryAcquire(context, attempt));
}
}
CompletableFuture<TbAiPooledConnection> ready = connect(context, key, true);
group.connecting = ready;
ready.whenComplete((connection, error) -> {
synchronized (group) {
if (group.connecting == ready) {
group.connecting = null;
}
// A channel closed right after hello has already left the pool (removed() then found nothing).
if (connection != null && !connection.isRemoved()) {
group.connections.add(connection);
}
}
});
return ready;
}
}
private CompletableFuture<TbAiPooledConnection> retryAcquire(TbAiTurnContext context, int attempt) {
if (attempt >= MAX_ACQUIRE_ATTEMPTS) {
return CompletableFuture.failedFuture(new TbAiChannelUnavailableException("No AI channel with free capacity", null));
}
return acquire(context, true, attempt + 1);
}
/**
* Opens a channel; its hello carries the opening call's origin, which TB AI uses for start frames without one. One
* timer bounds the whole handshake: when it fires the connection leaves the pool at once, and a WebSocket upgrade
* that completes later is closed as soon as its session arrives (see {@link TbAiPooledConnection#opened}).
*/
private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) {
var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled,
maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong());
channelClient.connect(handshakeTokenProvider(context), connection)
.subscribeOn(Schedulers.boundedElastic())
.subscribe(connection::opened, error -> connection.failed(toConnectError(error)));
return connection.ready()
.orTimeout(CONNECT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)
.whenComplete((ready, error) -> {
if (error != null) {
connection.failed(error);
}
})
.exceptionallyCompose(error -> CompletableFuture.failedFuture(unwrap(error)));
}
void release(TbAiPooledConnection connection) {
if (connection.releasePoolSlot()) {
pooledConnections.decrementAndGet();
}
}
/**
* Called once when a channel closes or fails to open.
*/
void removed(TbAiPooledConnection connection) {
Group group = connection.key() != null ? groups.get(connection.key()) : null;
if (group != null) {
synchronized (group) {
group.connections.remove(connection);
}
}
release(connection);
}
int pooledConnections() {
return pooledConnections.get();
}
void sweep() {
try {
long now = nanoClock.getAsLong();
int closed = 0;
for (Map.Entry<PoolKey, Group> entry : groups.entrySet()) {
List<TbAiPooledConnection> snapshot;
synchronized (entry.getValue()) {
snapshot = new ArrayList<>(entry.getValue().connections);
}
for (TbAiPooledConnection connection : snapshot) {
if (connection.sweep(now, idleTimeoutNanos, maxAgeNanos)) {
closed++;
}
}
groups.computeIfPresent(entry.getKey(), (key, group) -> {
synchronized (group) {
return group.connections.isEmpty() && group.connecting == null ? null : group;
}
});
}
if (closed > 0 || log.isTraceEnabled()) {
log.debug("AI channel pool: {} pooled channel(s), {} user(s), {} closed as idle or aged",
pooledConnections.get(), groups.size(), closed);
}
} catch (Exception e) {
log.warn("Failed to sweep the AI channel pool", e);
}
}
@PreDestroy
void shutdown() {
shutdown = true;
if (sweeper != null) {
sweeper.shutdownNow();
}
groups.values().forEach(group -> {
List<TbAiPooledConnection> snapshot;
synchronized (group) {
snapshot = new ArrayList<>(group.connections);
}
snapshot.forEach(connection -> connection.close(ChannelProtocol.CLOSE_GOING_AWAY, "Server is shutting down"));
});
}
private boolean tryTakePoolSlot() {
while (true) {
int current = pooledConnections.get();
if (current >= maxConnections) {
return false;
}
if (pooledConnections.compareAndSet(current, current + 1)) {
return true;
}
}
}
private boolean evictIdleConnection() {
TbAiPooledConnection oldest = null;
long oldestUse = Long.MAX_VALUE;
for (Group group : groups.values()) {
synchronized (group) {
for (TbAiPooledConnection connection : group.connections) {
if (connection.isIdle() && connection.lastUsedNanos() < oldestUse) {
oldest = connection;
oldestUse = connection.lastUsedNanos();
}
}
}
}
if (oldest == null || !oldest.evictIfIdle()) {
return false;
}
// Free the evicted channel's slot now rather than when its close is reported, so the caller can take it.
release(oldest);
return true;
}
private static TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) {
TbAiClient.TokenProvider delegate = context.tokenProvider();
String acceptLanguage = context.acceptLanguage();
if (acceptLanguage == null || acceptLanguage.isBlank()) {
return delegate;
}
return new TbAiClient.TokenProvider() {
@Override
public String getToken() {
return delegate.getToken();
}
@Override
public Map<String, String> getAdditionalInfo() {
var headers = new HashMap<>(delegate.getAdditionalInfo());
headers.put(HttpHeaders.ACCEPT_LANGUAGE, acceptLanguage);
return headers;
}
};
}
private static Throwable toConnectError(Throwable error) {
for (Throwable cause : ExceptionUtils.getThrowableList(error)) {
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) {
int status = handshake.response().status().code();
if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) {
return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase());
}
}
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {
return cause;
}
}
return new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(error), error);
}
private static Throwable unwrap(Throwable error) {
Throwable cause = error;
while ((cause instanceof java.util.concurrent.CompletionException || cause instanceof java.util.concurrent.ExecutionException)
&& cause.getCause() != null) {
cause = cause.getCause();
}
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {
return cause;
}
if (cause instanceof java.util.concurrent.TimeoutException) {
return new TbAiChannelUnavailableException("AI channel handshake timed out", cause);
}
return new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(cause), cause);
}
private static final class Group {
private final List<TbAiPooledConnection> connections = new ArrayList<>();
private CompletableFuture<TbAiPooledConnection> connecting;
}
}

14
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java

@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user.
*/
public class TbAiChannelRejectedException extends RuntimeException {
public TbAiChannelRejectedException(String reason) {
super(reason);
}
}

11
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelUnavailableException.java

@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
public class TbAiChannelUnavailableException extends RuntimeException {
public TbAiChannelUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}

8
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperation.java

@ -0,0 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* A typed channel operation: its frame type (a {@code ChannelProtocol} constant) and its request payload DTO, or null.
*/
public record TbAiOperation(String type, Object payload) {}

42
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java

@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class TbAiOperations {
private final ChannelTbAiOperations channelOperations;
private final SystemSecurityService systemSecurityService;
/**
* For a call made on the user's behalf with no browser request at hand and no callback into ThingsBoard.
*/
public TbAiResponse execute(TbAiOperation operation, SecurityUser user, TbAiClient.TokenProvider tokenProvider) {
String clientOrigin = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null);
return execute(operation, new TbAiTurnContext(user, null, null, tokenProvider, clientOrigin));
}
public TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) {
try {
return channelOperations.execute(operation, context);
} catch (TbAiChannelUnavailableException e) {
log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage());
return ChannelTbAiOperations.failure("Service unavailable");
} catch (TbAiChannelRejectedException e) {
return ChannelTbAiOperations.failure(e.getMessage());
}
}
}

327
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java

@ -0,0 +1,327 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelFrameListener;
import org.thingsboard.ai.common.channel.ChannelHello;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* One WebSocket to TB AI, shared by the turns and operations of one user. Capacity is reserved before an exchange
* starts ({@link #tryReserve}) and released when it ends ({@link #finish}); a retiring connection takes no new work
* and closes once its last exchange ends. Exchanges are told apart by their op, the id of their start frame.
* <p>
* Lock order: the pool's group lock may be held while calling into a connection, never the reverse, and a connection
* never closes its session while holding its own lock.
*/
@Slf4j
final class TbAiPooledConnection implements ChannelFrameListener {
// Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell
// before using it that this ThingsBoard understands it.
static final List<String> CLIENT_CAPABILITIES = List.of();
private final TbAiChannelPool.PoolKey key;
private final String origin;
private final boolean pooled;
private final int maxOperations;
private final ChannelFrameCodec codec;
private final TbAiChannelPool pool;
private final long createdNanos;
private final CompletableFuture<TbAiPooledConnection> ready = new CompletableFuture<>();
private final Map<String, TbAiChannelExchange> exchanges = new ConcurrentHashMap<>();
private final AtomicBoolean removed = new AtomicBoolean();
private final AtomicBoolean poolSlotHeld;
private final Object lock = new Object();
private int reserved;
private boolean retiring;
private long lastUsedNanos;
private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
/**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
* take its place.
*/
TbAiPooledConnection(TbAiChannelPool.PoolKey key, String origin, boolean pooled, int maxOperations,
ChannelFrameCodec codec, TbAiChannelPool pool, long nowNanos) {
this.key = key;
this.origin = origin;
this.pooled = pooled;
this.maxOperations = maxOperations;
this.codec = codec;
this.pool = pool;
this.createdNanos = nowNanos;
this.lastUsedNanos = nowNanos;
this.reserved = 1;
this.retiring = !pooled;
this.poolSlotHeld = new AtomicBoolean(pooled);
}
/**
* True exactly once for a pooled connection, when it gives its place in the pool's connection count back.
*/
boolean releasePoolSlot() {
return poolSlotHeld.compareAndSet(true, false);
}
boolean isRemoved() {
return removed.get();
}
TbAiChannelPool.PoolKey key() {
return key;
}
boolean isPooled() {
return pooled;
}
int maxFrameBytes() {
return maxFrameBytes;
}
ChannelSession session() {
return session;
}
ChannelFrameCodec codec() {
return codec;
}
CompletableFuture<TbAiPooledConnection> ready() {
return ready;
}
/**
* The session arrived. If the handshake already failed (the connect timed out), the session is closed: it is
* stored first and {@link #failed} closes whatever is stored after failing {@code ready}, so one of the two always
* sees the other and the channel never stays open outside the pool.
*/
void opened(ChannelSession openedSession) {
session = openedSession;
if (ready.isDone()) {
close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
return;
}
try {
openedSession.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(
new ChannelHello(ChannelProtocol.VERSION, CLIENT_CAPABILITIES, origin, null))));
} catch (ChannelException e) {
ready.completeExceptionally(new TbAiChannelUnavailableException("Cannot send hello: " + e.getMessage(), e));
}
}
/**
* The handshake failed or timed out: the connection leaves the pool now and its session, if it has one or gets
* one later, is closed.
*/
void failed(Throwable error) {
ready.completeExceptionally(error);
markRemoved();
close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
}
boolean tryReserve(long nowNanos) {
synchronized (lock) {
if (retiring || session == null || !session.isOpen() || reserved >= maxOperations) {
return false;
}
reserved++;
lastUsedNanos = nowNanos;
return true;
}
}
/**
* Starts an exchange on a reserved slot; its op is the id of {@code startFrame}.
*/
void start(TbAiChannelExchange exchange, ChannelFrame startFrame) {
exchanges.put(startFrame.id(), exchange);
try {
session.send(startFrame);
} catch (ChannelException e) {
exchanges.remove(startFrame.id());
throw e;
}
}
void send(ChannelFrame frame) {
session.send(frame);
}
/**
* Ends the exchange started with {@code op} and gives back its reservation; frames for it that still arrive are
* dropped.
*/
void finish(String op, long nowNanos) {
exchanges.remove(op);
unreserve(nowNanos);
}
/**
* Gives back a reservation that never started an exchange.
*/
void unreserve(long nowNanos) {
boolean close;
synchronized (lock) {
reserved = Math.max(0, reserved - 1);
lastUsedNanos = nowNanos;
close = retiring && reserved == 0;
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Done");
}
}
void retire() {
boolean close;
synchronized (lock) {
retiring = true;
close = reserved == 0;
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Retired");
}
}
/**
* Closes the connection when it has been idle for {@code idleNanos} or is older than {@code maxAgeNanos}; an old
* connection still in use stops taking work and closes after its last exchange.
*/
boolean sweep(long nowNanos, long idleNanos, long maxAgeNanos) {
boolean close = false;
synchronized (lock) {
boolean aged = nowNanos - createdNanos >= maxAgeNanos;
if (reserved == 0 && (aged || nowNanos - lastUsedNanos >= idleNanos)) {
retiring = true;
close = true;
} else if (aged) {
retiring = true;
}
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Idle");
}
return close;
}
/**
* Closes the connection if nothing runs on it, to make room in a full pool.
*/
boolean evictIfIdle() {
synchronized (lock) {
if (reserved != 0 || retiring) {
return false;
}
retiring = true;
}
close(ChannelProtocol.CLOSE_NORMAL, "Evicted");
return true;
}
long lastUsedNanos() {
synchronized (lock) {
return lastUsedNanos;
}
}
boolean isIdle() {
synchronized (lock) {
return reserved == 0 && !retiring;
}
}
void close(int code, String reason) {
ChannelSession current = session;
if (current != null && current.isOpen()) {
current.close(code, reason);
}
}
@Override
public void onFrame(ChannelSession frameSession, ChannelFrame frame) {
if (!ready.isDone()) {
onHandshakeFrame(frame);
return;
}
if (frame.op() == null) {
onConnectionFrame(frame);
return;
}
TbAiChannelExchange exchange = exchanges.get(frame.op());
if (exchange == null) {
log.debug("[{}] Dropping AI channel frame '{}' for finished operation '{}'", key, frame.type(), frame.op());
return;
}
exchange.onFrame(this, frame);
}
@Override
public void onClose(ChannelSession closedSession, int code, String reason) {
synchronized (lock) {
retiring = true;
}
ready.completeExceptionally(new TbAiChannelUnavailableException(
"AI channel closed before hello [" + code + "] " + reason, null));
markRemoved();
List<TbAiChannelExchange> running = List.copyOf(exchanges.values());
exchanges.clear();
running.forEach(exchange -> exchange.onClose(code, reason));
}
private void onHandshakeFrame(ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.HELLO -> {
ChannelHello hello = codec.fromPayload(frame.payload(), ChannelHello.class);
if (hello.maxFrameBytes() != null && hello.maxFrameBytes() > 0 && hello.maxFrameBytes() < Integer.MAX_VALUE) {
maxFrameBytes = hello.maxFrameBytes().intValue();
}
ready.complete(this);
}
case ChannelProtocol.ERROR -> {
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class);
ready.completeExceptionally(new TbAiChannelUnavailableException("AI channel refused: " + error.message(), null));
close(ChannelProtocol.CLOSE_NORMAL, "Error received");
}
default -> log.debug("[{}] Ignoring AI channel frame '{}' before hello", key, frame.type());
}
} catch (ChannelException e) {
ready.completeExceptionally(new TbAiChannelUnavailableException("Malformed AI channel hello: " + e.getMessage(), e));
close(ChannelProtocol.CLOSE_PROTOCOL_ERROR, e.getMessage());
}
}
private void onConnectionFrame(ChannelFrame frame) {
if (ChannelProtocol.ERROR.equals(frame.type())) {
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class);
log.warn("[{}] AI channel error {}: {}", key, error.code(), error.message());
close(ChannelProtocol.CLOSE_NORMAL, "Error received");
} else {
log.debug("[{}] Ignoring AI channel frame '{}' without op", key, frame.type());
}
}
private void markRemoved() {
if (removed.compareAndSet(false, true)) {
pool.removed(this);
}
}
}

260
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutor.java

@ -0,0 +1,260 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.thingsboard.ai.common.channel.ChannelBodies;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.channel.TbHttpRequest;
import org.thingsboard.ai.common.channel.TbHttpResponse;
import org.thingsboard.server.config.ThingsboardSecurityConfiguration;
import org.thingsboard.server.queue.util.TbCoreComponent;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import javax.net.ssl.SSLException;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
@Slf4j
@Component
@TbCoreComponent
public class TbAiRequestExecutor {
static final String INVALID_REQUEST = "invalid_request";
static final String REQUEST_FAILED = "request_failed";
static final String TIMEOUT = "timeout";
static final String TOO_LARGE = "too_large";
private static final String API_PREFIX = "/api/";
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(35);
private static final Set<HttpMethod> ALLOWED_METHODS = Set.of(
HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE);
private static final Set<String> DROPPED_REQUEST_HEADERS = Set.of(
"host", "authorization", "x-authorization", "cookie", "connection", "content-length", "transfer-encoding",
"x-forwarded-host", "x-forwarded-proto", "x-forwarded-port", "x-forwarded-for");
private static final Set<String> DROPPED_RESPONSE_HEADERS = Set.of(
"set-cookie", "content-length", "transfer-encoding", "connection");
private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
private static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
private static final String X_FORWARDED_PORT = "X-Forwarded-Port";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";
private final String baseUrl;
private final WebClient webClient;
@Autowired
public TbAiRequestExecutor(@Value("${server.address:0.0.0.0}") String address,
@Value("${server.port:8080}") int port,
@Value("${server.ssl.enabled:false}") boolean sslEnabled) {
this(loopbackUrl(address, port, sslEnabled), sslEnabled ? insecureLoopbackSslContext() : null);
}
TbAiRequestExecutor(String baseUrl, SslContext sslContext) {
this.baseUrl = baseUrl;
HttpClient httpClient = sslContext != null
? HttpClient.create().secure(spec -> spec.sslContext(sslContext))
: HttpClient.create();
this.webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES))
.build();
}
public Mono<ChannelFrame> execute(ChannelFrame frame, ChannelFrameCodec codec, TbAiTurnContext context, int maxBodyBytes) {
TbHttpRequest request;
try {
request = codec.fromPayload(frame.payload(), TbHttpRequest.class);
} catch (RuntimeException e) {
return Mono.just(error(frame, codec, INVALID_REQUEST, "Malformed tb.request payload"));
}
String invalidReason = context.tbAccessToken() == null
? "ThingsBoard access is not available for this operation"
: validate(request);
if (invalidReason != null) {
log.warn("[{}][{}] Rejected AI request {} {}: {}", context.tenantId(), context.userId(),
request.method(), request.path(), invalidReason);
return Mono.just(error(frame, codec, INVALID_REQUEST, invalidReason));
}
Duration timeout = request.timeoutMs() != null && request.timeoutMs() > 0 ? Duration.ofMillis(request.timeoutMs()) : DEFAULT_TIMEOUT;
String query = StringUtils.isEmpty(request.query()) ? "" : "?" + request.query();
byte[] body = ChannelBodies.decode(request.body(), request.bodyEncoding());
WebClient.RequestBodySpec spec = webClient.method(HttpMethod.valueOf(request.method().toUpperCase(Locale.ROOT)))
.uri(URI.create(baseUrl + request.path() + query))
.headers(headers -> {
copyRequestHeaders(request.headers(), headers);
forwardedHeaders(context).forEach(headers::set);
headers.set(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, context.tbAccessToken());
});
WebClient.RequestHeadersSpec<?> withBody = body.length > 0 ? spec.bodyValue(body) : spec;
return withBody.exchangeToMono(response -> response.bodyToMono(byte[].class)
.defaultIfEmpty(new byte[0])
.map(responseBody -> {
if (responseBody.length > maxBodyBytes) {
throw new DataBufferLimitException("Response body of " + responseBody.length + " bytes exceeds " + maxBodyBytes);
}
HttpHeaders responseHeaders = response.headers().asHttpHeaders();
String encoding = ChannelBodies.encoding(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE));
var reply = new TbHttpResponse(response.statusCode().value(), responseHeaders(responseHeaders),
ChannelBodies.encode(responseBody, encoding), encoding);
return ChannelFrame.reply(ChannelProtocol.TB_RESPONSE, frame, codec.toPayload(reply));
}))
.timeout(timeout)
.onErrorResume(e -> Mono.just(failure(frame, codec, request, e)));
}
public void serve(ChannelSession session, ChannelFrame frame, ChannelFrameCodec codec, TbAiTurnContext context, int maxBodyBytes) {
execute(frame, codec, context, maxBodyBytes).subscribe(reply -> {
try {
session.send(reply);
} catch (ChannelException e) {
log.debug("Dropped '{}' reply: {}", reply.type(), e.getMessage());
}
});
}
static String validate(TbHttpRequest request) {
if (request.method() == null || !ALLOWED_METHODS.contains(HttpMethod.valueOf(request.method().toUpperCase(Locale.ROOT)))) {
return "Method is not allowed: " + request.method();
}
String path = request.path();
if (path == null || !path.startsWith(API_PREFIX)) {
return "Path must start with " + API_PREFIX;
}
URI uri;
try {
uri = URI.create("http://loopback" + path);
} catch (IllegalArgumentException e) {
return "Path is not a valid URI path";
}
if (uri.getRawQuery() != null || uri.getRawFragment() != null || !uri.normalize().getRawPath().equals(path)
|| path.contains("//")) {
return "Path must be a normalized relative path";
}
if (request.query() != null) {
try {
URI withQuery = URI.create("http://loopback" + path + "?" + request.query());
if (withQuery.getRawFragment() != null) {
return "Query must not contain a fragment";
}
} catch (IllegalArgumentException e) {
return "Query is not a valid URI query";
}
}
return null;
}
/**
* Makes the loopback request look as if it came through the user's {@code clientOrigin} from the user's address,
* so ThingsBoard builds URLs (device connectivity commands) and records addresses as for the user's own request.
* The browser request's X-Forwarded-* headers cannot be copied: the forwarded-header filter consumes them.
*/
static Map<String, String> forwardedHeaders(TbAiTurnContext context) {
var headers = new LinkedHashMap<String, String>();
URI origin = parseOrigin(context.clientOrigin());
if (origin != null) {
String scheme = origin.getScheme().toLowerCase(Locale.ROOT);
int port = origin.getPort() != -1 ? origin.getPort() : "https".equals(scheme) ? 443 : 80;
headers.put(X_FORWARDED_PROTO, scheme);
headers.put(X_FORWARDED_HOST, origin.getHost());
headers.put(X_FORWARDED_PORT, String.valueOf(port));
}
if (context.user() != null && StringUtils.isNotBlank(context.user().getClientAddress())) {
headers.put(X_FORWARDED_FOR, context.user().getClientAddress());
}
return headers;
}
private static URI parseOrigin(String clientOrigin) {
if (StringUtils.isBlank(clientOrigin)) {
return null;
}
try {
URI uri = URI.create(clientOrigin.trim());
String scheme = uri.getScheme();
if (uri.getHost() == null || !("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme))) {
return null;
}
return uri;
} catch (IllegalArgumentException e) {
return null;
}
}
private static void copyRequestHeaders(Map<String, List<String>> source, HttpHeaders target) {
if (source == null) {
return;
}
source.forEach((name, values) -> {
if (!DROPPED_REQUEST_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
target.put(name, values);
}
});
}
private static Map<String, List<String>> responseHeaders(HttpHeaders headers) {
var result = new LinkedHashMap<String, List<String>>();
headers.forEach((name, values) -> {
if (!DROPPED_RESPONSE_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
result.put(name, List.copyOf(values));
}
});
return result;
}
private static ChannelFrame failure(ChannelFrame frame, ChannelFrameCodec codec, TbHttpRequest request, Throwable e) {
if (e instanceof TimeoutException) {
return error(frame, codec, TIMEOUT, "ThingsBoard did not answer " + request.method() + " " + request.path() + " in time");
}
if (e instanceof DataBufferLimitException) {
return error(frame, codec, TOO_LARGE, "Response is larger than the channel frame limit");
}
log.warn("AI request {} {} failed: {}", request.method(), request.path(), e.getMessage());
return error(frame, codec, REQUEST_FAILED, "ThingsBoard request failed");
}
private static ChannelFrame error(ChannelFrame frame, ChannelFrameCodec codec, String code, String message) {
return ChannelFrame.reply(ChannelProtocol.ERROR, frame, codec.toPayload(new ChannelError(code, message)));
}
private static String loopbackUrl(String address, int port, boolean sslEnabled) {
String host = StringUtils.isBlank(address) || "0.0.0.0".equals(address) || "::".equals(address) ? "127.0.0.1" : address;
if (host.contains(":") && !host.startsWith("[")) {
host = "[" + host + "]";
}
return (sslEnabled ? "https" : "http") + "://" + host + ":" + port;
}
private static SslContext insecureLoopbackSslContext() {
try {
return SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} catch (SSLException e) {
throw new IllegalStateException("Failed to create the loopback SSL context", e);
}
}
}

15
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java

@ -0,0 +1,15 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.codec.ServerSentEvent;
import reactor.core.publisher.Flux;
import java.util.UUID;
public interface TbAiTransport {
Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context);
}

40
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnContext.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.security.model.SecurityUser;
/**
* Everything one TB AI call needs on the TB side. {@code user} is null for background work (housekeeper deletions);
* {@code tbAccessToken} is null for calls during which TB AI never calls ThingsBoard back. {@code clientOrigin} is the
* ThingsBoard base URL the user reached for this call: TB AI shows it to the user (device connectivity commands) and
* audits it, and the calls back into ThingsBoard are forwarded as if made through it.
*/
public record TbAiTurnContext(
TenantId tenantId,
UserId userId,
SecurityUser user,
String tbAccessToken,
String acceptLanguage,
TbAiClient.TokenProvider tokenProvider,
String clientOrigin
) {
public TbAiTurnContext(SecurityUser user, String tbAccessToken, String acceptLanguage,
TbAiClient.TokenProvider tokenProvider, String clientOrigin) {
this(user.getTenantId(), user.getId(), user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
}
public static TbAiTurnContext background(TenantId tenantId, UserId userId, TbAiClient.TokenProvider tokenProvider,
String clientOrigin) {
return new TbAiTurnContext(tenantId, userId, null, null, null, tokenProvider, clientOrigin);
}
public boolean isBackground() {
return user == null;
}
}

14
application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiDataDeletionTaskProcessor.java

@ -10,6 +10,10 @@ import org.thingsboard.server.common.data.housekeeper.HousekeeperTask;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.ai.TbAiTokenProvider;
import org.thingsboard.server.service.ai.TbAiTokenProviderFactory;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.Optional;
@ -17,8 +21,9 @@ import java.util.Optional;
@RequiredArgsConstructor
public abstract class AiDataDeletionTaskProcessor extends HousekeeperTaskProcessor<HousekeeperTask> {
protected final TbAiClient tbAiClient;
private final Optional<TbAiTokenProvider> tokenProvider;
private final TbAiOperations operations;
private final SystemSecurityService systemSecurityService;
@Override
public void process(HousekeeperTask task) throws Exception {
@ -29,12 +34,15 @@ public abstract class AiDataDeletionTaskProcessor extends HousekeeperTaskProcess
return;
}
UserId userId = new UserId(task.getEntityId().getId());
TbAiResponse response = deleteData(TbAiTokenProviderFactory.idScoped(tokenProvider, task.getTenantId(), userId));
TbAiClient.TokenProvider scopedTokenProvider = TbAiTokenProviderFactory.idScoped(tokenProvider, task.getTenantId(), userId);
TbAiResponse response = operations.execute(
new TbAiOperation(operationType(), null),
TbAiTurnContext.background(task.getTenantId(), userId, scopedTokenProvider, systemSecurityService.getBaseUrl(task.getTenantId(), null, null)));
if (!response.isSuccess()) {
throw new RuntimeException(response.getError());
}
}
protected abstract TbAiResponse deleteData(TbAiClient.TokenProvider tokenProvider);
protected abstract String operationType();
}

14
application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiTenantDataDeletionTaskProcessor.java

@ -3,11 +3,12 @@
package org.thingsboard.server.service.housekeeper.processor;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.server.common.data.housekeeper.HousekeeperTaskType;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiTokenProvider;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.Optional;
@ -15,13 +16,14 @@ import java.util.Optional;
@TbCoreComponent
public class AiTenantDataDeletionTaskProcessor extends AiDataDeletionTaskProcessor {
public AiTenantDataDeletionTaskProcessor(TbAiClient tbAiClient, Optional<TbAiTokenProvider> tokenProvider) {
super(tbAiClient, tokenProvider);
public AiTenantDataDeletionTaskProcessor(Optional<TbAiTokenProvider> tokenProvider, TbAiOperations operations,
SystemSecurityService systemSecurityService) {
super(tokenProvider, operations, systemSecurityService);
}
@Override
protected TbAiResponse deleteData(TbAiClient.TokenProvider tokenProvider) {
return tbAiClient.deleteTenantData(tokenProvider);
protected String operationType() {
return ChannelProtocol.TENANT_DATA_DELETE;
}
@Override

14
application/src/main/java/org/thingsboard/server/service/housekeeper/processor/AiUserDataDeletionTaskProcessor.java

@ -3,11 +3,12 @@
package org.thingsboard.server.service.housekeeper.processor;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.server.common.data.housekeeper.HousekeeperTaskType;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiTokenProvider;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.Optional;
@ -15,13 +16,14 @@ import java.util.Optional;
@TbCoreComponent
public class AiUserDataDeletionTaskProcessor extends AiDataDeletionTaskProcessor {
public AiUserDataDeletionTaskProcessor(TbAiClient tbAiClient, Optional<TbAiTokenProvider> tokenProvider) {
super(tbAiClient, tokenProvider);
public AiUserDataDeletionTaskProcessor(Optional<TbAiTokenProvider> tokenProvider, TbAiOperations operations,
SystemSecurityService systemSecurityService) {
super(tokenProvider, operations, systemSecurityService);
}
@Override
protected TbAiResponse deleteData(TbAiClient.TokenProvider tokenProvider) {
return tbAiClient.deleteUserData(tokenProvider);
protected String operationType() {
return ChannelProtocol.USER_DATA_DELETE;
}
@Override

26
application/src/main/resources/thingsboard.yml

@ -2754,6 +2754,32 @@ ai:
inactivity_timeout: "${TB_AI_SSE_INACTIVITY_TIMEOUT:600}"
# Maximum number of characters of event data to include in trace logs
log_max_data_length: "${TB_AI_SSE_LOG_MAX_DATA_LENGTH:150}"
# Base URL of the ThingsBoard AI service; TB opens the AI WebSocket channel at wss://<host>/api/ws/v1
base_url: "${TB_AI_BASE_URL:https://ai.thingsboard.cloud}"
# Tokens this instance signs for the AI service itself (ThingsBoard Cloud). When the signing key is empty, the
# instance uses the AI token of its subscription instead (on-premise)
jwt:
# Base64-encoded HMAC key shared with the AI service; leave empty on-premise
signing_key: "${TB_AI_JWT_SIGNING_KEY:}"
# Issuer claim of the signed tokens
issuer: "${TB_AI_JWT_ISSUER:local}"
# Lifetime of a signed token in minutes
expiration_time_minutes: "${TB_AI_JWT_EXPIRATION_TIME_MINUTES:60}"
# WebSocket channel to the AI service: chat turns and all other AI calls run over it, and the AI service calls this
# instance back through it, so no public base URL is needed
channel:
# Channels are shared by the calls of one user on this node
pool:
# Maximum pooled channels on this node; when full, the least recently used idle channel is closed, or a call
# gets a channel of its own that closes after it
max_connections: "${TB_AI_CHANNEL_POOL_MAX_CONNECTIONS:2000}"
# Maximum chat turns and operations running at once on one channel; further calls open another channel
max_operations_per_connection: "${TB_AI_CHANNEL_MAX_OPERATIONS_PER_CONNECTION:20}"
# Seconds a channel with nothing running stays open; keep it below the proxy's tunnel timeout
idle_timeout_seconds: "${TB_AI_CHANNEL_IDLE_TIMEOUT_SECONDS:60}"
# Minutes after which a channel takes no new calls and closes once idle, so a revoked token or a changed
# subscription is picked up by the next handshake
max_age_minutes: "${TB_AI_CHANNEL_MAX_AGE_MINUTES:10}"
iot-hub:
base-url: "${IOT_HUB_BASE_URL:https://iot-hub.thingsboard.io}" # IoT Hub base URL for fetching published items, resources, etc.

53
application/src/test/java/org/thingsboard/server/controller/AbstractAiControllerTest.java

@ -5,6 +5,8 @@ package org.thingsboard.server.controller;
import com.auth0.jwt.JWT;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
@ -18,18 +20,28 @@ import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.ApiUsageState;
import org.thingsboard.server.common.data.ApiUsageStateValue;
import org.thingsboard.server.service.ai.TbAiSettings;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import java.util.Objects;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@TestPropertySource(properties = {
// base64-encoded ASCII "shared-test-jwt-signing-key-for-ai-controller-tests-not-secret!!"
// (64 bytes — required minimum for HS512; tests only JWT.decode(), never verify the signature)
"TB_AI_JWT_SIGNING_KEY=c2hhcmVkLXRlc3Qtand0LXNpZ25pbmcta2V5LWZvci1haS1jb250cm9sbGVyLXRlc3RzLW5vdC1zZWNyZXQhIQ=="
"ai.jwt.signing_key=c2hhcmVkLXRlc3Qtand0LXNpZ25pbmcta2V5LWZvci1haS1jb250cm9sbGVyLXRlc3RzLW5vdC1zZWNyZXQhIQ=="
})
public abstract class AbstractAiControllerTest extends AbstractControllerTest {
@ -37,8 +49,12 @@ public abstract class AbstractAiControllerTest extends AbstractControllerTest {
protected static final String MSG_AI_DISABLED = "AI feature is disabled";
protected static final String MSG_OUT_OF_CREDITS = "Out of AI credits";
// Every TB AI call goes through these two seams: operations (spied, so the per-user overload still builds the
// real context) and the chat turn transport.
@MockitoSpyBean
protected TbAiOperations tbAiOperations;
@MockitoBean
protected TbAiClient tbAiClient;
protected TbAiTransport tbAiTransport;
@MockitoSpyBean
protected TbAiSettings aiSettings;
@MockitoSpyBean
@ -60,6 +76,39 @@ public abstract class AbstractAiControllerTest extends AbstractControllerTest {
assertThat(tokenProvider.getAdditionalInfo()).isEmpty();
}
protected void givenOperation(String type, Object payload, TbAiClient.TbAiResponse response) {
doReturn(response).when(tbAiOperations).execute(argThat(operation(type, payload)), any(TbAiTurnContext.class));
}
protected void givenOperation(String type, TbAiClient.TbAiResponse response) {
doReturn(response).when(tbAiOperations).execute(argThat(operation -> operation != null && type.equals(operation.type())),
any(TbAiTurnContext.class));
}
/**
* Verifies the operation ran once and returns the context it ran with (user, TB access token, token provider).
*/
protected TbAiTurnContext verifyOperation(String type, Object payload) {
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiOperations).execute(argThat(operation(type, payload)), context.capture());
return context.getValue();
}
protected TbAiTurnContext verifyOperation(String type) {
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiOperations).execute(argThat(operation -> operation != null && type.equals(operation.type())), context.capture());
return context.getValue();
}
protected void verifyNoAiCalls() {
verify(tbAiOperations, never()).execute(any(TbAiOperation.class), any(TbAiTurnContext.class));
verifyNoInteractions(tbAiTransport);
}
private static ArgumentMatcher<TbAiOperation> operation(String type, Object payload) {
return operation -> operation != null && type.equals(operation.type()) && Objects.equals(payload, operation.payload());
}
protected static TbAiClient.TbAiResponse success(JsonNode value) {
return TbAiClient.TbAiResponse.builder().success(true).value(value).build();
}

8
application/src/test/java/org/thingsboard/server/controller/AbstractOnPremiseAiControllerTest.java

@ -3,7 +3,6 @@
package org.thingsboard.server.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.thingsboard.ai.common.client.TbAiClient;
@ -17,13 +16,11 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
@TestPropertySource(properties = {
"TB_AI_JWT_SIGNING_KEY=",
"TB_CORE_BASE_URL=" + AbstractOnPremiseAiControllerTest.ORIGIN
"ai.jwt.signing_key="
})
public abstract class AbstractOnPremiseAiControllerTest extends AbstractAiControllerTest {
protected static final String AI_TOKEN = "on-premise-ai-token";
protected static final String ORIGIN = "https://tb.example.org";
@MockitoSpyBean
protected SubscriptionService subscriptionService;
@ -40,8 +37,7 @@ public abstract class AbstractOnPremiseAiControllerTest extends AbstractAiContro
assertThat(tokenProvider.getAdditionalInfo()).containsExactlyInAnyOrderEntriesOf(Map.of(
TbAiHeaders.USER_ID, tenantAdminUserId.getId().toString(),
TbAiHeaders.TENANT_ID, tenantId.getId().toString(),
TbAiHeaders.TB_VERSION, projectInfo.getProjectVersion(),
HttpHeaders.ORIGIN, ORIGIN
TbAiHeaders.TB_VERSION, projectInfo.getProjectVersion()
));
}

53
application/src/test/java/org/thingsboard/server/controller/AiChatControllerOnPremiseTest.java

@ -2,19 +2,22 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.test.web.servlet.MvcResult;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.dao.service.DaoSqlTest;
import reactor.core.publisher.Flux;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -32,16 +35,14 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
ObjectNode request = createChatRequest("Energy assistant chat");
given(tbAiClient.createChat(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(success(TextNode.valueOf(UUID.randomUUID().toString())));
givenOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request), success(TextNode.valueOf(UUID.randomUUID().toString())));
// WHEN
doPost("/api/ai/chats", request).andExpect(status().isCreated());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).createChat(eq(request), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -51,15 +52,14 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
givenSubscriptionProvidesAiToken();
UUID chatId = UUID.randomUUID();
ObjectNode request = JacksonUtil.newObjectNode().put("title", "Renamed chat");
given(tbAiClient.updateChat(eq(chatId), eq(request), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request), success());
// WHEN
doPatch("/api/ai/chats/" + chatId, request).andExpect(status().isNoContent());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).updateChat(eq(chatId), eq(request), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -67,16 +67,14 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
// GIVEN
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
given(tbAiClient.listChats(any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newArrayNode()));
givenOperation(ChannelProtocol.CHAT_LIST, null, success(JacksonUtil.newArrayNode()));
// WHEN
doGet("/api/ai/chats").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).listChats(tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_LIST, null);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -85,16 +83,14 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID chatId = UUID.randomUUID();
given(tbAiClient.getChatMessages(eq(chatId), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newArrayNode()));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), success(JacksonUtil.newArrayNode()));
// WHEN
doGet("/api/ai/chats/" + chatId + "/messages").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).getChatMessages(eq(chatId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -103,15 +99,14 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID chatId = UUID.randomUUID();
given(tbAiClient.deleteChat(eq(chatId), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null), success());
// WHEN
doDelete("/api/ai/chats/" + chatId).andExpect(status().isNoContent());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).deleteChat(eq(chatId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -122,7 +117,7 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
UUID chatId = UUID.randomUUID();
ObjectNode requestBody = sendMessageBody("What is the device status?", null);
String acceptLanguage = "es-ES";
given(tbAiClient.sendChatMessage(eq(chatId), eq(requestBody), eq("Bearer " + token), eq(acceptLanguage), any(TbAiClient.TokenProvider.class)))
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class)))
.willReturn(Flux.just(ServerSentEvent.<String>builder().event("message").data("Checking device status...").build()));
// WHEN
@ -132,9 +127,11 @@ public class AiChatControllerOnPremiseTest extends AbstractOnPremiseAiController
mockMvc.perform(asyncDispatch(asyncStart)).andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).sendChatMessage(eq(chatId), eq(requestBody), eq("Bearer " + token), eq(acceptLanguage), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture());
assertThat(context.getValue().tbAccessToken()).isEqualTo("Bearer " + token);
assertThat(context.getValue().acceptLanguage()).isEqualTo(acceptLanguage);
assertTokenProviderBelongsToTenantAdmin(context.getValue().tokenProvider());
}
}

64
application/src/test/java/org/thingsboard/server/controller/AiChatControllerTest.java

@ -2,6 +2,9 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@ -11,7 +14,6 @@ import org.mockito.ArgumentCaptor;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MvcResult;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.ApiUsageRecordKey;
import org.thingsboard.server.common.data.permission.Operation;
@ -31,7 +33,6 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -52,8 +53,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
ObjectNode request = createChatRequest("Energy assistant chat");
UUID newChatId = UUID.randomUUID();
given(tbAiClient.createChat(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(success(TextNode.valueOf(newChatId.toString())));
givenOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request), success(TextNode.valueOf(newChatId.toString())));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/chats", request).andExpect(status().isCreated()), JsonNode.class);
@ -62,9 +62,8 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
assertThat(result.isTextual()).isTrue();
assertThat(result.asText()).isEqualTo(newChatId.toString());
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).createChat(eq(request), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -73,15 +72,14 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
ObjectNode request = JacksonUtil.newObjectNode().put("title", "Renamed chat");
given(tbAiClient.updateChat(eq(chatId), eq(request), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request), success());
// WHEN
doPatch("/api/ai/chats/" + chatId, request).andExpect(status().isNoContent());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).updateChat(eq(chatId), eq(request), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -89,14 +87,14 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
// GIVEN
loginTenantAdmin();
ArrayNode summaries = chatSummaries(UUID.randomUUID(), "Energy assistant chat");
given(tbAiClient.listChats(any(TbAiClient.TokenProvider.class))).willReturn(success(summaries));
givenOperation(ChannelProtocol.CHAT_LIST, null, success(summaries));
// WHEN
JsonNode result = doGet("/api/ai/chats", JsonNode.class);
// THEN
assertThat(result).isEqualTo(summaries);
verify(tbAiClient).listChats(any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.CHAT_LIST, null);
}
@Test
@ -105,14 +103,14 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
ArrayNode messages = chatMessages();
given(tbAiClient.getChatMessages(eq(chatId), any(TbAiClient.TokenProvider.class))).willReturn(success(messages));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), success(messages));
// WHEN
JsonNode result = doGet("/api/ai/chats/" + chatId + "/messages", JsonNode.class);
// THEN
assertThat(result).isEqualTo(messages);
verify(tbAiClient).getChatMessages(eq(chatId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
}
@Test
@ -120,13 +118,13 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
// GIVEN
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
given(tbAiClient.deleteChat(eq(chatId), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null), success());
// WHEN
doDelete("/api/ai/chats/" + chatId).andExpect(status().isNoContent());
// THEN
verify(tbAiClient).deleteChat(eq(chatId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null));
}
@Test
@ -140,8 +138,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
ServerSentEvent.<String>builder().event("message").data("Creating a high-temperature alarm rule...").build(),
ServerSentEvent.<String>builder().event("creditsUsed").data("{\"creditsUsed\":5}").build()
);
given(tbAiClient.sendChatMessage(eq(chatId), eq(requestBody), eq("Bearer " + token), eq(acceptLanguage), any(TbAiClient.TokenProvider.class)))
.willReturn(upstream);
given(tbAiTransport.sendChatMessage(eq(chatId), eq(requestBody), any(TbAiTurnContext.class))).willReturn(upstream);
// WHEN
MvcResult asyncStart = mockMvc.perform(sendMessageRequest(chatId, requestBody, acceptLanguage))
@ -158,9 +155,11 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
verify(apiUsageReportClient).report(any(), any(), eq(ApiUsageRecordKey.AI_CREDITS_COUNT), eq(5L));
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).sendChatMessage(eq(chatId), eq(requestBody), eq("Bearer " + token), eq(acceptLanguage), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiTransport).sendChatMessage(eq(chatId), eq(requestBody), context.capture());
assertThat(context.getValue().tbAccessToken()).isEqualTo("Bearer " + token);
assertThat(context.getValue().acceptLanguage()).isEqualTo(acceptLanguage);
assertTokenProviderBelongsToTenantAdmin(context.getValue().tokenProvider());
}
// ------------------------------------------------------------------------
@ -180,7 +179,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(MSG_OUT_OF_CREDITS)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -190,15 +189,14 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
givenAiCreditsExhausted();
ObjectNode request = createChatRequest("Energy assistant chat");
UUID newChatId = UUID.randomUUID();
given(tbAiClient.createChat(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(success(TextNode.valueOf(newChatId.toString())));
givenOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request), success(TextNode.valueOf(newChatId.toString())));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/chats", request).andExpect(status().isCreated()), JsonNode.class);
// THEN
assertThat(result.asText()).isEqualTo(newChatId.toString());
verify(tbAiClient).createChat(eq(request), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request));
}
// ------------------------------------------------------------------------
@ -217,7 +215,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(MSG_AI_DISABLED)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -226,7 +224,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID chatId = UUID.randomUUID();
String error = "Chat service unavailable";
given(tbAiClient.getChatMessages(eq(chatId), any(TbAiClient.TokenProvider.class))).willReturn(failure(error));
givenOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null), failure(error));
// WHEN
doGet("/api/ai/chats/" + chatId + "/messages")
@ -234,7 +232,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(error)));
// THEN
verify(tbAiClient).getChatMessages(eq(chatId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, null));
}
// ------------------------------------------------------------------------
@ -252,7 +250,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermission)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -266,7 +264,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermission)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -283,7 +281,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermissionWrite + AI_RESOURCE)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -300,7 +298,7 @@ public class AiChatControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermissionRead + AI_RESOURCE)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
// ------------------------------------------------------------------------

19
application/src/test/java/org/thingsboard/server/controller/AiDeviceDashboardControllerOnPremiseTest.java

@ -2,22 +2,20 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.DashboardOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.assertj.core.api.Assertions.assertThat;
@DaoSqlTest
public class AiDeviceDashboardControllerOnPremiseTest extends AbstractOnPremiseAiControllerTest {
@ -39,16 +37,15 @@ public class AiDeviceDashboardControllerOnPremiseTest extends AbstractOnPremiseA
// GIVEN
givenSubscriptionProvidesAiToken();
ObjectNode request = JacksonUtil.newObjectNode();
given(tbAiClient.generateDashboard(eq(device.getUuidId()), eq(request), eq("Bearer " + token), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newObjectNode().put("dashboardId", UUID.randomUUID().toString())));
givenOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(device.getUuidId(), request), success(JacksonUtil.newObjectNode().put("dashboardId", UUID.randomUUID().toString())));
// WHEN
doPost("/api/ai/devices/" + device.getUuidId() + "/dashboard", request, JsonNode.class);
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).generateDashboard(eq(device.getUuidId()), eq(request), eq("Bearer " + token), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(device.getUuidId(), request));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
}

39
application/src/test/java/org/thingsboard/server/controller/AiDeviceDashboardControllerTest.java

@ -2,11 +2,13 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.DashboardOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.ResultActions;
import org.thingsboard.ai.common.client.TbAiClient;
@ -26,10 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -101,7 +100,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermission)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -116,7 +115,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermission)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -147,7 +146,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermissionWrite + AI_RESOURCE)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -163,7 +162,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermissionRead + "DEVICE '" + device.getName() + "'!")));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -179,7 +178,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo("You don't have permission to perform 'READ_ATTRIBUTES' operation with DEVICE '" + device.getName() + "'!")));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -195,7 +194,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo("You don't have permission to perform 'READ_TELEMETRY' operation with DEVICE '" + device.getName() + "'!")));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -211,7 +210,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermissionCreate + "'DASHBOARD' resource!")));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -229,15 +228,14 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
.andExpect(jsonPath("$.entityType", equalTo("DASHBOARD")))
.andExpect(jsonPath("$.limit", equalTo(1)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
public void shouldPropagateAiServiceErrorMessage_whenAiClientReturnsFailure() throws Exception {
// GIVEN
String aiServiceError = "Failed to save dashboard: dashboards limit reached";
given(tbAiClient.generateDashboard(eq(device.getUuidId()), any(JsonNode.class), any(String.class), any(TbAiClient.TokenProvider.class)))
.willReturn(failure(aiServiceError));
givenOperation(ChannelProtocol.DASHBOARD_GENERATE, failure(aiServiceError));
// WHEN
ResultActions result = doPost("/api/ai/devices/" + device.getUuidId() + "/dashboard", JacksonUtil.newObjectNode());
@ -246,7 +244,7 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.message", equalTo(aiServiceError)));
verify(tbAiClient).generateDashboard(eq(device.getUuidId()), any(JsonNode.class), any(String.class), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.DASHBOARD_GENERATE);
}
private void givenDashboardLimitReached(long limit) {
@ -255,15 +253,14 @@ public class AiDeviceDashboardControllerTest extends AbstractAiControllerTest {
}
private void givenAiClientGeneratesDashboard(JsonNode request, JsonNode response) {
given(tbAiClient.generateDashboard(eq(device.getUuidId()), eq(request), any(String.class), any(TbAiClient.TokenProvider.class)))
.willReturn(success(response));
givenOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(device.getUuidId(), request), success(response));
}
private TbAiClient.TokenProvider verifyAiClientGeneratedDashboard(JsonNode request) {
ArgumentCaptor<TbAiClient.TokenProvider> tokenProviderCaptor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).generateDashboard(eq(device.getUuidId()), eq(request), eq("Bearer " + token), tokenProviderCaptor.capture());
verifyNoMoreInteractions(tbAiClient);
return tokenProviderCaptor.getValue();
TbAiTurnContext context = verifyOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(device.getUuidId(), request));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
verifyNoMoreInteractions(tbAiTransport);
return context.tokenProvider();
}
private static ObjectNode generatedDashboardResponse() {

89
application/src/test/java/org/thingsboard/server/controller/AiSolutionControllerOnPremiseTest.java

@ -2,20 +2,21 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
@ -26,15 +27,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
// GIVEN
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
given(tbAiClient.startNewSolution(any(TbAiClient.TokenProvider.class))).willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_START, null, success(JacksonUtil.newObjectNode()));
// WHEN
doPost("/api/ai/solution/start").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).startNewSolution(tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_START, null);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -43,15 +43,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.getSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId), success(JacksonUtil.newObjectNode()));
// WHEN
doGet("/api/ai/solution/" + solutionId).andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).getSolution(eq(solutionId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -59,15 +58,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
// GIVEN
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
given(tbAiClient.getSolutions(any(TbAiClient.TokenProvider.class))).willReturn(success(JacksonUtil.newArrayNode()));
givenOperation(ChannelProtocol.SOLUTION_LIST, null, success(JacksonUtil.newArrayNode()));
// WHEN
doGet("/api/ai/solution/infos").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).getSolutions(tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_LIST, null);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -78,16 +76,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
UUID solutionId = UUID.randomUUID();
SolutionStep step = SolutionStep.INITIAL_CONFIGURATION;
String message = "Add humidity monitoring to the solution.";
given(tbAiClient.sendSolutionMessage(eq(solutionId), eq(step), eq(message), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message), success(JacksonUtil.newObjectNode()));
// WHEN
performChat(solutionId, step, message).andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).sendSolutionMessage(eq(solutionId), eq(step), eq(message), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -96,15 +92,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.createSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId), success(JacksonUtil.newObjectNode()));
// WHEN
doPost("/api/ai/solution/" + solutionId + "/create").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).createSolution(eq(solutionId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -116,16 +111,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
String dataKey = "entities";
ObjectNode value = JacksonUtil.newObjectNode();
value.putArray("devices").add("Thermostat");
given(tbAiClient.updateData(eq(solutionId), eq(dataKey), eq(value), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value), success(JacksonUtil.newObjectNode()));
// WHEN
doPut("/api/ai/solution/" + solutionId + "/" + dataKey, value).andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).updateData(eq(solutionId), eq(dataKey), eq(value), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -135,15 +128,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
SolutionStep step = SolutionStep.DASHBOARDS_CONFIGURATION;
given(tbAiClient.clearStep(eq(solutionId), eq(step), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step), success());
// WHEN
doDelete("/api/ai/solution/" + solutionId + "/" + step + "/clear").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).clearStep(eq(solutionId), eq(step), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -152,16 +144,15 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.installSolution(eq(solutionId), eq("Bearer " + token), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId), success(JacksonUtil.newObjectNode()));
// WHEN
doPost("/api/ai/solution/" + solutionId + "/install").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).installSolution(eq(solutionId), eq("Bearer " + token), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -170,16 +161,15 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.uninstallSolution(eq(solutionId), eq("Bearer " + token), any(TbAiClient.TokenProvider.class)))
.willReturn(success(JacksonUtil.newObjectNode()));
givenOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId), success(JacksonUtil.newObjectNode()));
// WHEN
doDelete("/api/ai/solution/" + solutionId + "/uninstall").andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).uninstallSolution(eq(solutionId), eq("Bearer " + token), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -188,15 +178,14 @@ public class AiSolutionControllerOnPremiseTest extends AbstractOnPremiseAiContro
loginTenantAdmin();
givenSubscriptionProvidesAiToken();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.deleteSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId), success());
// WHEN
doDelete("/api/ai/solution/" + solutionId).andExpect(status().isOk());
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).deleteSolution(eq(solutionId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
}

90
application/src/test/java/org/thingsboard/server/controller/AiSolutionControllerTest.java

@ -2,11 +2,16 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
@ -20,12 +25,7 @@ import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
@ -40,7 +40,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
// GIVEN
loginTenantAdmin();
ObjectNode solution = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false);
given(tbAiClient.startNewSolution(any(TbAiClient.TokenProvider.class))).willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_START, null, success(solution));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/solution/start").andExpect(status().isOk()), JsonNode.class);
@ -56,16 +56,15 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
ObjectNode solution = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiClient.getSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId), success(solution));
// WHEN
JsonNode result = doGet("/api/ai/solution/" + solutionId, JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).getSolution(eq(solutionId), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -73,14 +72,14 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
// GIVEN
loginTenantAdmin();
ArrayNode infos = solutionInfosResponse(UUID.randomUUID(), "Energy Monitoring");
given(tbAiClient.getSolutions(any(TbAiClient.TokenProvider.class))).willReturn(success(infos));
givenOperation(ChannelProtocol.SOLUTION_LIST, null, success(infos));
// WHEN
JsonNode result = doGet("/api/ai/solution/infos", JsonNode.class);
// THEN
assertThat(result).isEqualTo(infos);
verify(tbAiClient).getSolutions(any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_LIST, null);
}
@Test
@ -91,17 +90,15 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
SolutionStep step = SolutionStep.INITIAL_CONFIGURATION;
String message = "Add humidity monitoring to the solution.";
ObjectNode solution = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiClient.sendSolutionMessage(eq(solutionId), eq(step), eq(message), any(TbAiClient.TokenProvider.class)))
.willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message), success(solution));
// WHEN
JsonNode result = readResponse(performChat(solutionId, step, message).andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).sendSolutionMessage(eq(solutionId), eq(step), eq(message), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, message));
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -110,14 +107,14 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
ObjectNode solution = solutionResponse(solutionId, "Energy Monitoring", true, false);
given(tbAiClient.createSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId), success(solution));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/solution/" + solutionId + "/create").andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
verify(tbAiClient).createSolution(eq(solutionId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId));
}
@Test
@ -129,15 +126,14 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
ObjectNode value = JacksonUtil.newObjectNode();
value.putArray("devices").add("Thermostat");
ObjectNode solution = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiClient.updateData(eq(solutionId), eq(dataKey), eq(value), any(TbAiClient.TokenProvider.class)))
.willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value), success(solution));
// WHEN
JsonNode result = doPut("/api/ai/solution/" + solutionId + "/" + dataKey, value, JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
verify(tbAiClient).updateData(eq(solutionId), eq(dataKey), eq(value), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value));
}
@Test
@ -146,13 +142,13 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
SolutionStep step = SolutionStep.DASHBOARDS_CONFIGURATION;
given(tbAiClient.clearStep(eq(solutionId), eq(step), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step), success());
// WHEN
doDelete("/api/ai/solution/" + solutionId + "/" + step + "/clear").andExpect(status().isOk());
// THEN
verify(tbAiClient).clearStep(eq(solutionId), eq(step), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step));
}
@Test
@ -161,17 +157,16 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
ObjectNode installResult = solutionInstallResultResponse(UUID.randomUUID());
given(tbAiClient.installSolution(eq(solutionId), eq("Bearer " + token), any(TbAiClient.TokenProvider.class)))
.willReturn(success(installResult));
givenOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId), success(installResult));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/solution/" + solutionId + "/install").andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(installResult);
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).installSolution(eq(solutionId), eq("Bearer " + token), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
@Test
@ -180,15 +175,15 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
ObjectNode solution = solutionResponse(solutionId, "Energy Monitoring", true, false);
given(tbAiClient.uninstallSolution(eq(solutionId), eq("Bearer " + token), any(TbAiClient.TokenProvider.class)))
.willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId), success(solution));
// WHEN
JsonNode result = readResponse(doDelete("/api/ai/solution/" + solutionId + "/uninstall").andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
verify(tbAiClient).uninstallSolution(eq(solutionId), eq("Bearer " + token), any(TbAiClient.TokenProvider.class));
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId));
assertThat(context.tbAccessToken()).isEqualTo("Bearer " + token);
}
@Test
@ -196,13 +191,13 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
// GIVEN
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
given(tbAiClient.deleteSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(success());
givenOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId), success());
// WHEN
doDelete("/api/ai/solution/" + solutionId).andExpect(status().isOk());
// THEN
verify(tbAiClient).deleteSolution(eq(solutionId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId));
}
// ------------------------------------------------------------------------
@ -221,7 +216,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(MSG_OUT_OF_CREDITS)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -230,14 +225,14 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
givenAiCreditsExhausted();
ObjectNode solution = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false);
given(tbAiClient.startNewSolution(any(TbAiClient.TokenProvider.class))).willReturn(success(solution));
givenOperation(ChannelProtocol.SOLUTION_START, null, success(solution));
// WHEN
JsonNode result = readResponse(doPost("/api/ai/solution/start").andExpect(status().isOk()), JsonNode.class);
// THEN
assertThat(result).isEqualTo(solution);
verify(tbAiClient).startNewSolution(any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_START, null);
}
// ------------------------------------------------------------------------
@ -256,7 +251,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(MSG_AI_DISABLED)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -265,7 +260,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
loginTenantAdmin();
UUID solutionId = UUID.randomUUID();
String error = "Solution service unavailable";
given(tbAiClient.getSolution(eq(solutionId), any(TbAiClient.TokenProvider.class))).willReturn(failure(error));
givenOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId), failure(error));
// WHEN
doGet("/api/ai/solution/" + solutionId)
@ -273,7 +268,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(error)));
// THEN
verify(tbAiClient).getSolution(eq(solutionId), any(TbAiClient.TokenProvider.class));
verifyOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId));
}
// ------------------------------------------------------------------------
@ -291,7 +286,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermission)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -305,7 +300,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermission)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -322,7 +317,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermissionWrite + AI_RESOURCE)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -339,7 +334,7 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
.andExpect(statusReason(equalTo(msgErrorPermissionRead + AI_RESOURCE)));
// THEN
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
// ------------------------------------------------------------------------
@ -347,9 +342,8 @@ public class AiSolutionControllerTest extends AbstractAiControllerTest {
// ------------------------------------------------------------------------
private TbAiClient.TokenProvider captureStartNewTokenProvider() {
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).startNewSolution(tokenProvider.capture());
return tokenProvider.getValue();
TbAiTurnContext context = verifyOperation(ChannelProtocol.SOLUTION_START, null);
return context.tokenProvider();
}
private static ObjectNode solutionResponse(UUID solutionId, String solutionTitle, boolean built, boolean installed) {

16
application/src/test/java/org/thingsboard/server/controller/AiToolControllerOnPremiseTest.java

@ -2,21 +2,17 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@DaoSqlTest
public class AiToolControllerOnPremiseTest extends AbstractOnPremiseAiControllerTest {
@ -29,8 +25,7 @@ public class AiToolControllerOnPremiseTest extends AbstractOnPremiseAiController
ObjectNode request = decision(true);
ObjectNode response = approvedResponse();
given(tbAiClient.resolveToolApproval(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(success(response));
givenOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, request, success(response));
// WHEN
JsonNode result = doPost("/api/ai/tools/resolve-approval", request, JsonNode.class);
@ -38,9 +33,8 @@ public class AiToolControllerOnPremiseTest extends AbstractOnPremiseAiController
// THEN
assertThat(result).isEqualTo(response);
ArgumentCaptor<TbAiClient.TokenProvider> tokenProvider = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).resolveToolApproval(eq(request), tokenProvider.capture());
assertTokenProviderBelongsToTenantAdmin(tokenProvider.getValue());
TbAiTurnContext context = verifyOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, request);
assertTokenProviderBelongsToTenantAdmin(context.tokenProvider());
}
private static ObjectNode decision(boolean approved) {

29
application/src/test/java/org/thingsboard/server/controller/AiToolControllerTest.java

@ -2,10 +2,11 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.web.servlet.ResultActions;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
@ -19,12 +20,7 @@ import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -103,7 +99,7 @@ public class AiToolControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(MSG_AI_DISABLED)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -118,7 +114,7 @@ public class AiToolControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermission)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -133,7 +129,7 @@ public class AiToolControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermission)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
@Test
@ -151,24 +147,21 @@ public class AiToolControllerTest extends AbstractAiControllerTest {
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo(msgErrorPermissionWrite + AI_RESOURCE)));
verifyNoInteractions(tbAiClient);
verifyNoAiCalls();
}
private void givenAiClientResolvesToolApproval(ObjectNode request, ObjectNode response) {
given(tbAiClient.resolveToolApproval(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(success(response));
givenOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, request, success(response));
}
private void givenAiClientRejectsToolApproval(ObjectNode request, String error) {
given(tbAiClient.resolveToolApproval(eq(request), any(TbAiClient.TokenProvider.class)))
.willReturn(failure(error));
givenOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, request, failure(error));
}
private TbAiClient.TokenProvider verifyAiClientResolvedToolApproval(ObjectNode request) {
ArgumentCaptor<TbAiClient.TokenProvider> tokenProviderCaptor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).resolveToolApproval(eq(request), tokenProviderCaptor.capture());
verifyNoMoreInteractions(tbAiClient);
return tokenProviderCaptor.getValue();
TbAiTurnContext context = verifyOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, request);
verifyNoMoreInteractions(tbAiTransport);
return context.tokenProvider();
}
private static ObjectNode anyDecision() {

135
application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java

@ -13,11 +13,8 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
@ -32,15 +29,16 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.stats.TbApiUsageReportClient;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
import org.thingsboard.server.service.ai.transport.TbAiChannelUnavailableException;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -52,15 +50,20 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@ExtendWith(MockitoExtension.class)
class DefaultTbAiServiceTest {
@Mock
TbAiOperations operations;
@Mock
TbApiUsageStateService apiUsageStateService;
@Mock
@ -68,8 +71,6 @@ class DefaultTbAiServiceTest {
@Mock
TbAiTokenProvider tbAiTokenProvider;
@Mock
TbAiClient tbAiClient;
@Mock
TbAiService.TbAiCall<TbAiResponse> call;
final int sseInactivityTimeoutSeconds = 600;
@ -100,19 +101,18 @@ class DefaultTbAiServiceTest {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
JsonNode value = JacksonUtil.newObjectNode().put("answer", 42);
given(call.apply(any(), any())).willReturn(TbAiResponse.builder().success(true).value(value).creditsUsed(150).build());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(true).value(value).creditsUsed(150).build());
// WHEN
JsonNode returned = service.process(call, user, true);
// THEN
assertThat(returned).isSameAs(value);
then(call).should().apply(same(tbAiClient), notNull()); // invoked with the real client and a user-scoped provider
then(call).should().apply(notNull()); // invoked with a user-scoped token provider
then(apiUsageStateService).should().getApiUsageState(tenantId);
then(apiUsageReportClient).should().report(tenantId, customerId, ApiUsageRecordKey.AI_CREDITS_COUNT, 150L);
then(apiUsageReportClient).shouldHaveNoMoreInteractions();
then(tbAiClient).shouldHaveNoInteractions();
}
@Test
@ -120,14 +120,14 @@ class DefaultTbAiServiceTest {
// GIVEN: checkCredits=false only skips the pre-request availability check; credits actually
// consumed by the call must still be reported
JsonNode value = JacksonUtil.newObjectNode().put("ok", true);
given(call.apply(any(), any())).willReturn(TbAiResponse.builder().success(true).value(value).creditsUsed(75).build());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(true).value(value).creditsUsed(75).build());
// WHEN
JsonNode returned = service.process(call, user, false);
// THEN
assertThat(returned).isSameAs(value);
then(call).should().apply(same(tbAiClient), notNull());
then(call).should().apply(notNull());
then(apiUsageStateService).shouldHaveNoInteractions(); // pre-request credit check skipped
then(apiUsageReportClient).should().report(tenantId, customerId, ApiUsageRecordKey.AI_CREDITS_COUNT, 75L);
@ -145,9 +145,8 @@ class DefaultTbAiServiceTest {
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Out of AI credits");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS);
then(call).should(never()).apply(any(), any());
then(call).should(never()).apply(any());
then(apiUsageReportClient).shouldHaveNoInteractions();
then(tbAiClient).shouldHaveNoInteractions();
}
@Test
@ -161,17 +160,16 @@ class DefaultTbAiServiceTest {
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("AI feature is disabled");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.PERMISSION_DENIED);
then(call).should(never()).apply(any(), any());
then(call).should(never()).apply(any());
then(apiUsageStateService).shouldHaveNoInteractions();
then(apiUsageReportClient).shouldHaveNoInteractions();
then(tbAiClient).shouldHaveNoInteractions();
}
@Test
void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
given(call.apply(any(), any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build());
// WHEN
Throwable thrown = catchThrowable(() -> service.process(call, user, true));
@ -195,9 +193,8 @@ class DefaultTbAiServiceTest {
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("AI feature is not available");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS);
then(call).should(never()).apply(any(), any());
then(call).should(never()).apply(any());
then(apiUsageStateService).shouldHaveNoInteractions();
then(tbAiClient).shouldHaveNoInteractions();
}
@Test
@ -205,24 +202,40 @@ class DefaultTbAiServiceTest {
// GIVEN
given(tbAiTokenProvider.getToken(user)).willReturn("jwt-token");
given(tbAiTokenProvider.getAdditionalInfo(user)).willReturn(Map.of("X-Forwarded-For", "198.51.100.10"));
given(call.apply(any(), any())).willReturn(TbAiResponse.builder().success(true).value(JacksonUtil.newObjectNode()).build());
given(call.apply(any())).willReturn(TbAiResponse.builder().success(true).value(JacksonUtil.newObjectNode()).build());
// WHEN
service.process(call, user, false);
// THEN the provider handed to the call is scoped to the calling user
ArgumentCaptor<TbAiClient.TokenProvider> tokenProviderCaptor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
then(call).should().apply(same(tbAiClient), tokenProviderCaptor.capture());
then(call).should().apply(tokenProviderCaptor.capture());
TbAiClient.TokenProvider tokenProvider = tokenProviderCaptor.getValue();
assertThat(tokenProvider.getToken()).isEqualTo("jwt-token");
assertThat(tokenProvider.getAdditionalInfo()).containsExactlyInAnyOrderEntriesOf(Map.of("X-Forwarded-For", "198.51.100.10"));
then(tbAiTokenProvider).should().getToken(user);
// once before the call, to fail it early, and once through the scoped provider
then(tbAiTokenProvider).should(times(2)).getToken(user);
then(tbAiTokenProvider).should().getAdditionalInfo(user);
then(tbAiTokenProvider).shouldHaveNoMoreInteractions();
}
@Test
void shouldThrowTokenErrorAndSkipCall_whenProcessAndUserHasNoAiToken() {
// GIVEN
given(tbAiTokenProvider.getToken(user)).willThrow(new ThingsboardRuntimeException(
"AI is not available for the current subscription plan", ThingsboardErrorCode.PERMISSION_DENIED));
// WHEN
Throwable thrown = catchThrowable(() -> service.process(call, user, false));
// THEN — the plan error reaches the controller as a 403, not as an unavailable channel
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("AI is not available for the current subscription plan");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.PERMISSION_DENIED);
then(call).should(never()).apply(any());
}
// ---------------------------------------------------------------------------------------------
// isEnabled()
// ---------------------------------------------------------------------------------------------
@ -248,7 +261,6 @@ class DefaultTbAiServiceTest {
// THEN
assertThat(usageInfo.usage()).isEmpty();
assertThat(usageInfo.periodStartTs()).isZero();
then(tbAiClient).shouldHaveNoInteractions();
}
@Test
@ -267,7 +279,7 @@ class DefaultTbAiServiceTest {
response.set("usage", usage);
response.put("periodStartTs", 1716460800000L);
response.put("unexpectedTopLevelField", "ignored");
given(tbAiClient.getApiUsageInfo(any()))
given(operations.execute(any(TbAiOperation.class), same(user), any(TbAiClient.TokenProvider.class)))
.willReturn(TbAiResponse.builder().success(true).value(response).build());
// WHEN
@ -277,13 +289,13 @@ class DefaultTbAiServiceTest {
assertThat(usageInfo.periodStartTs()).isEqualTo(1716460800000L);
assertThat(usageInfo.usage()).containsEntry(Resource.AI_CREDITS, new ApiUsageInfo.ResourceUsage(250L, 1000));
then(apiUsageStateService).shouldHaveNoInteractions(); // usage is fetched without a credit check
then(tbAiClient).should().getApiUsageInfo(any());
then(operations).should().execute(argThat(operation -> ChannelProtocol.USAGE_GET.equals(operation.type())), same(user), any());
}
@Test
void shouldReturnEmptyUsage_whenClientResponseIsFailure() {
// GIVEN
given(tbAiClient.getApiUsageInfo(any()))
given(operations.execute(any(TbAiOperation.class), same(user), any(TbAiClient.TokenProvider.class)))
.willReturn(TbAiResponse.builder().success(false).error("AI service down").build());
// WHEN
@ -292,7 +304,6 @@ class DefaultTbAiServiceTest {
// THEN
assertThat(usageInfo.usage()).isEmpty();
assertThat(usageInfo.periodStartTs()).isZero();
then(tbAiClient).should().getApiUsageInfo(any());
}
// ---------------------------------------------------------------------------------------------
@ -306,7 +317,7 @@ class DefaultTbAiServiceTest {
// WHEN
Throwable thrown = catchThrowable(() ->
disabledService.processStream(chatId, (client, tokenProvider) -> Flux.empty(), user));
disabledService.processStream(chatId, tokenProvider -> Flux.empty(), user));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("AI feature is disabled");
@ -322,7 +333,7 @@ class DefaultTbAiServiceTest {
// WHEN
Throwable thrown = catchThrowable(() ->
service.processStream(chatId, (client, tokenProvider) -> Flux.empty(), user));
service.processStream(chatId, tokenProvider -> Flux.empty(), user));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Out of AI credits");
@ -330,6 +341,23 @@ class DefaultTbAiServiceTest {
then(apiUsageReportClient).shouldHaveNoInteractions();
}
@Test
void shouldThrowTokenError_whenProcessStreamAndUserHasNoAiToken() {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
given(tbAiTokenProvider.getToken(user)).willThrow(new ThingsboardRuntimeException(
"AI is not available for the current subscription plan", ThingsboardErrorCode.PERMISSION_DENIED));
// WHEN
Throwable thrown = catchThrowable(() ->
service.processStream(chatId, tokenProvider -> Flux.empty(), user));
// THEN
assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("AI is not available for the current subscription plan");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.PERMISSION_DENIED);
then(apiUsageReportClient).shouldHaveNoInteractions();
}
@Test
void shouldReportCredits_whenClientCancelsMidStream() {
// GIVEN
@ -446,22 +474,11 @@ class DefaultTbAiServiceTest {
return List.of(
// PE-side inactivity timeout from the .timeout(...) operator
arguments(new TimeoutException("inactivity"), "Request timed out"),
// AI service unreachable (e.g. connection refused / DNS failure)
arguments(connectError(), "Service unavailable"),
// auth failures: the response body is ignored and the status reason phrase is used
arguments(aiError(401, "Unauthorized", "Authentication required"), "Unauthorized"),
arguments(aiError(403, "Forbidden", "Access denied"), "Forbidden"),
// the AI service always wraps errors in an {"message": ...} body, which is surfaced verbatim
arguments(aiError(400, "Bad Request", "message: must not be blank"), "message: must not be blank"),
arguments(aiError(404, "Not Found", "Chat not found"), "Chat not found"),
arguments(aiError(429, "Too Many Requests", "Rate limit exceeded. Please try again later."), "Rate limit exceeded. Please try again later."),
arguments(aiError(500, "Internal Server Error", "Unexpected error"), "Unexpected error"),
// infrastructure in front of the AI service (proxy/gateway/CDN) returns non-JSON bodies,
// so the status-class fallback message is used
arguments(gatewayError(502, "Bad Gateway"), "Service unavailable"),
arguments(gatewayError(413, "Payload Too Large"), "Invalid request"),
// non-standard / unresolvable status code -> generic message
arguments(gatewayError(520, "Web Server Returned an Unknown Error"), "Internal error"),
// the AI channel cannot be opened or closed before the turn started
arguments(new TbAiChannelUnavailableException("Connection refused", null), "Service unavailable"),
// the channel handshake was refused: the reason phrase is shown
arguments(new TbAiChannelRejectedException("Unauthorized"), "Unauthorized"),
arguments(new TbAiChannelRejectedException("Forbidden"), "Forbidden"),
// any other unexpected throwable
arguments(new RuntimeException("boom"), "Internal error")
);
@ -473,7 +490,7 @@ class DefaultTbAiServiceTest {
private DefaultTbAiService newService(boolean enabled, Optional<TbAiTokenProvider> tokenProvider) {
return new DefaultTbAiService(apiUsageStateService, apiUsageReportClient, tokenProvider,
tbAiClient, new TbAiSettings(enabled, sseInactivityTimeoutSeconds, sseLogMaxDataLength));
new TbAiSettings(enabled, sseInactivityTimeoutSeconds, sseLogMaxDataLength), operations);
}
private SecurityUser newUser(TenantId tenant) {
@ -487,7 +504,7 @@ class DefaultTbAiServiceTest {
private Flux<ServerSentEvent<String>> startStream() {
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
upstream = Sinks.many().unicast().onBackpressureBuffer();
return service.processStream(chatId, (client, tokenProvider) -> upstream.asFlux(), user);
return service.processStream(chatId, tokenProvider -> upstream.asFlux(), user);
}
private static ApiUsageState enabledApiUsageState() {
@ -502,26 +519,6 @@ class DefaultTbAiServiceTest {
return state;
}
private static WebClientRequestException connectError() {
return new WebClientRequestException(new IOException("Connection refused"), HttpMethod.POST,
URI.create("https://ai.example.test/api/chats/x/messages"), HttpHeaders.EMPTY);
}
// mirrors the AI service ErrorHandler, which always responds with an {"message": ...} body
private static WebClientResponseException aiError(int status, String reasonPhrase, String message) {
return wcre(status, reasonPhrase, JacksonUtil.toString(JacksonUtil.newObjectNode().put("message", message)));
}
// mirrors an infrastructure error in front of the AI service: a non-JSON (e.g. HTML) body
private static WebClientResponseException gatewayError(int status, String reasonPhrase) {
return wcre(status, reasonPhrase, "<html><body><h1>" + status + " " + reasonPhrase + "</h1></body></html>");
}
private static WebClientResponseException wcre(int status, String reasonPhrase, String body) {
return new WebClientResponseException(status, reasonPhrase, HttpHeaders.EMPTY,
body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private static String errorMessageOf(ServerSentEvent<String> event) {
return JacksonUtil.toJsonNode(event.data()).get("message").asText();
}

86
application/src/test/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProviderTest.java

@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.id.CustomerId;
@ -19,39 +18,29 @@ import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
@ExtendWith(MockitoExtension.class)
class OnPremiseTbAiTokenProviderTest {
private final String aiToken = "on-premise-ai-token";
private final String coreBaseUrl = "https://tb.example.org";
private final String resolvedBaseUrl = "https://resolved.example.org";
private final String localhostBaseUrl = "http://localhost:8080";
private final String tbVersion = "4.3.0-AI-TEST";
@Mock
SubscriptionService subscriptionService;
@Mock
SystemSecurityService systemSecurityService;
@Mock
ProjectInfo projectInfo;
UUID userId;
TenantId tenantId;
SecurityUser user;
// Default provider: a configured core base URL, so origin resolution does not touch SystemSecurityService.
OnPremiseTbAiTokenProvider provider;
@BeforeEach
@ -59,7 +48,7 @@ class OnPremiseTbAiTokenProviderTest {
userId = UUID.randomUUID();
tenantId = TenantId.fromUUID(UUID.randomUUID());
user = user(userId, tenantId);
provider = newProvider(coreBaseUrl);
provider = new OnPremiseTbAiTokenProvider(subscriptionService, projectInfo);
}
// ---------------------------------------------------------------------------------------------
@ -99,52 +88,15 @@ class OnPremiseTbAiTokenProviderTest {
// ---------------------------------------------------------------------------------------------
@Test
void shouldBuildHeadersWithConfiguredCoreBaseUrlAsOrigin_whenCoreBaseUrlIsSet() {
void shouldBuildHeadersWithoutOrigin_whenCalledForUser() {
// GIVEN
given(projectInfo.getProjectVersion()).willReturn(tbVersion);
// WHEN
Map<String, String> additionalInfo = provider.getAdditionalInfo(user);
// THEN
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders(coreBaseUrl));
// Origin came from the configured core base URL, so the security service must not be consulted.
then(systemSecurityService).shouldHaveNoInteractions();
}
@Test
void shouldResolveOriginViaSecurityService_whenCoreBaseUrlIsBlank() {
// GIVEN
OnPremiseTbAiTokenProvider providerWithoutCoreUrl = newProvider("");
given(projectInfo.getProjectVersion()).willReturn(tbVersion);
given(systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null))
.willReturn(resolvedBaseUrl);
// WHEN
Map<String, String> additionalInfo = providerWithoutCoreUrl.getAdditionalInfo(user);
// THEN
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders(resolvedBaseUrl));
}
@Test
void shouldThrowBadRequest_whenCoreBaseUrlIsBlankAndResolvedOriginIsLocalhost() {
// GIVEN — no configured core URL and the security service falls back to a localhost base URL.
OnPremiseTbAiTokenProvider providerWithoutCoreUrl = newProvider("");
given(systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null))
.willReturn(localhostBaseUrl);
// WHEN
Throwable thrown = catchThrowable(() -> providerWithoutCoreUrl.getAdditionalInfo(user));
// THEN
assertThat(thrown)
.isInstanceOf(ThingsboardRuntimeException.class)
.hasMessageContaining("Please configure the base URL");
assertThat(((ThingsboardRuntimeException) thrown).getErrorCode())
.isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS);
// The version header is never assembled once origin resolution fails.
then(projectInfo).shouldHaveNoInteractions();
// THEN — TB AI takes the origin from the channel's hello and start frames, never from the handshake.
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders());
}
// ---------------------------------------------------------------------------------------------
@ -196,49 +148,29 @@ class OnPremiseTbAiTokenProviderTest {
}
@Test
void shouldResolveIdBasedOriginFromGeneralSettings_whenCoreBaseUrlIsSet() {
// GIVEN — the configured core base URL and the white-labeling chain are both ignored for background tasks.
given(projectInfo.getProjectVersion()).willReturn(tbVersion);
given(systemSecurityService.getBaseUrl(tenantId, null, null)).willReturn(resolvedBaseUrl);
// WHEN
Map<String, String> additionalInfo = provider.getAdditionalInfo(tenantId, new UserId(userId));
// THEN
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders(resolvedBaseUrl));
then(systemSecurityService).should(never()).getBaseUrl(any(Authority.class), any(), any(), any());
}
@Test
void shouldAcceptLocalhostOrigin_whenBuildingIdBasedHeaders() {
// GIVEN — unlike the user-facing path, background deletion must not fail on an unconfigured base URL.
void shouldBuildHeadersWithoutOrigin_whenCalledWithRawIds() {
// GIVEN
given(projectInfo.getProjectVersion()).willReturn(tbVersion);
given(systemSecurityService.getBaseUrl(tenantId, null, null)).willReturn(localhostBaseUrl);
// WHEN
Map<String, String> additionalInfo = provider.getAdditionalInfo(tenantId, new UserId(userId));
// THEN
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders(localhostBaseUrl));
assertThat(additionalInfo).containsExactlyInAnyOrderEntriesOf(expectedHeaders());
}
// ---------------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------------
private Map<String, String> expectedHeaders(String origin) {
private Map<String, String> expectedHeaders() {
return Map.of(
TbAiHeaders.USER_ID, userId.toString(),
TbAiHeaders.TENANT_ID, tenantId.getId().toString(),
TbAiHeaders.TB_VERSION, tbVersion,
HttpHeaders.ORIGIN, origin
TbAiHeaders.TB_VERSION, tbVersion
);
}
private OnPremiseTbAiTokenProvider newProvider(String coreBaseUrl) {
return new OnPremiseTbAiTokenProvider(subscriptionService, systemSecurityService, projectInfo, coreBaseUrl);
}
private static SecurityUser user(UUID userId, TenantId tenantId) {
SecurityUser user = new SecurityUser(new UserId(userId));
user.setTenantId(tenantId);

69
application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java

@ -13,20 +13,29 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.codec.ServerSentEvent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Flux;
import java.util.Objects;
import java.util.UUID;
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.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
class DefaultAiChatServiceTest {
@ -34,19 +43,23 @@ class DefaultAiChatServiceTest {
@Mock
TbAiService tbAiService;
@Mock
TbAiClient tbAiClient;
@Mock
TbAiClient.TokenProvider tokenProvider;
@Mock
TbAiClient.TbAiResponse tbAiResponse;
@Mock
SecurityUser user;
@Mock
TbAiOperations operations;
@Mock
TbAiTransport tbAiTransport;
DefaultAiChatService service;
@BeforeEach
void setUp() {
service = new DefaultAiChatService(tbAiService);
service = new DefaultAiChatService(tbAiService, tbAiTransport, operations);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse);
}
@Test
@ -56,7 +69,6 @@ class DefaultAiChatServiceTest {
UUID chatId = UUID.randomUUID();
JsonNode expectedResponse = TextNode.valueOf(chatId.toString());
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.createChat(same(request), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.createChat(request, user);
@ -64,9 +76,9 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().createChat(same(request), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_CREATE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(null, request), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -76,15 +88,14 @@ class DefaultAiChatServiceTest {
UUID chatId = UUID.randomUUID();
JsonNode request = updateChatRequest("Updated chat");
given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
given(tbAiClient.updateChat(eq(chatId), same(request), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
service.updateChat(chatId, request, user);
// THEN
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().updateChat(eq(chatId), same(request), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_UPDATE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, request), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -94,7 +105,6 @@ class DefaultAiChatServiceTest {
UUID chatId = UUID.randomUUID();
JsonNode expectedResponse = chatSummariesResponse(chatId, 1716460800000L, "My Test Chat");
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.listChats(same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.listChats(user);
@ -102,9 +112,9 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().listChats(same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_LIST.equals(operation.type())
&& Objects.equals(null, operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -114,7 +124,6 @@ class DefaultAiChatServiceTest {
UUID chatId = UUID.randomUUID();
JsonNode expectedResponse = chatMessagesResponse("Hello", "Hi there!");
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.getChatMessages(eq(chatId), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.getChatMessages(chatId, user);
@ -122,9 +131,9 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().getChatMessages(eq(chatId), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -133,20 +142,19 @@ class DefaultAiChatServiceTest {
// GIVEN
UUID chatId = UUID.randomUUID();
given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
given(tbAiClient.deleteChat(eq(chatId), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
service.deleteChat(chatId, user);
// THEN
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().deleteChat(eq(chatId), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_DELETE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@Test
void shouldProcessStreamAndDelegateToClientWithAcceptLanguage_whenSendChatMessageWithClientContextCalled() {
void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() {
// GIVEN
UUID chatId = UUID.randomUUID();
JsonNode request = sendMessageBody("Generate a dashboard", "DASHBOARD_LIST");
@ -157,18 +165,19 @@ class DefaultAiChatServiceTest {
.data("{\"message\":\"ok\"}")
.build());
given(tbAiService.processStream(eq(chatId), any(), same(user))).willReturn(expectedStream);
given(tbAiClient.sendChatMessage(eq(chatId), same(request), eq(tbAccessToken), eq(acceptLanguage), same(tokenProvider)))
.willReturn(expectedStream);
var clientOrigin = "https://tb.example.com";
var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
given(tbAiTransport.sendChatMessage(eq(chatId), same(request), eq(expectedContext))).willReturn(expectedStream);
// WHEN
Flux<ServerSentEvent<String>> result = service.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, user);
Flux<ServerSentEvent<String>> result = service.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, clientOrigin, user);
// THEN
assertThat(result).isSameAs(expectedStream);
assertThat(captureProcessStreamCall(chatId).apply(tbAiClient, tokenProvider)).isSameAs(expectedStream);
then(tbAiClient).should().sendChatMessage(eq(chatId), same(request), eq(tbAccessToken), eq(acceptLanguage), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessStreamCall(chatId).apply(tokenProvider)).isSameAs(expectedStream);
then(tbAiTransport).should().sendChatMessage(eq(chatId), same(request), eq(expectedContext));
then(tbAiTransport).shouldHaveNoMoreInteractions();
then(tbAiService).shouldHaveNoMoreInteractions();
}

43
application/src/test/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardServiceTest.java

@ -11,16 +11,21 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.DashboardOperationRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
@ -31,19 +36,21 @@ class DefaultAiDeviceDashboardServiceTest {
@Mock
TbAiService tbAiService;
@Mock
TbAiClient tbAiClient;
@Mock
TbAiClient.TokenProvider tokenProvider;
@Mock
TbAiClient.TbAiResponse tbAiResponse;
@Mock
TbAiOperations operations;
@Mock
SecurityUser user;
String clientOrigin = "https://tb.example.com";
DefaultAiDeviceDashboardService service;
@BeforeEach
void setUp() {
service = new DefaultAiDeviceDashboardService(tbAiService);
service = new DefaultAiDeviceDashboardService(tbAiService, operations);
}
@Test
@ -55,18 +62,22 @@ class DefaultAiDeviceDashboardServiceTest {
String tbAccessToken = "tb-access-token";
JsonNode expectedResponse = TextNode.valueOf(dashboardId.toString());
given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
given(tbAiClient.generateDashboard(eq(deviceId), same(request), eq(tbAccessToken), same(tokenProvider)))
.willReturn(tbAiResponse);
stubOperations();
// WHEN
JsonNode result = service.generateDashboard(deviceId, request, tbAccessToken, user);
JsonNode result = service.generateDashboard(deviceId, request, tbAccessToken, clientOrigin, user);
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().generateDashboard(eq(deviceId), same(request), eq(tbAccessToken), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
TbAiTurnContext[] context = new TbAiTurnContext[1];
TbAiOperation operation = captureOperation(context);
assertThat(operation.type()).isEqualTo(ChannelProtocol.DASHBOARD_GENERATE);
assertThat(operation.payload()).isEqualTo(new DashboardOperationRequest(deviceId, request));
assertThat(context[0].clientOrigin()).isEqualTo(clientOrigin);
assertThat(context[0].tbAccessToken()).isEqualTo(tbAccessToken);
assertThat(context[0].tokenProvider()).isSameAs(tokenProvider);
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -77,6 +88,18 @@ class DefaultAiDeviceDashboardServiceTest {
return callCaptor.getValue();
}
private void stubOperations() {
given(operations.execute(any(), any())).willReturn(tbAiResponse);
}
private TbAiOperation captureOperation(TbAiTurnContext[] context) {
ArgumentCaptor<TbAiOperation> operationCaptor = ArgumentCaptor.forClass(TbAiOperation.class);
ArgumentCaptor<TbAiTurnContext> contextCaptor = ArgumentCaptor.forClass(TbAiTurnContext.class);
then(operations).should().execute(operationCaptor.capture(), contextCaptor.capture());
context[0] = contextCaptor.getValue();
return operationCaptor.getValue();
}
private static ObjectNode generateDashboardRequest(String... timeseriesKeys) {
ObjectNode request = JacksonUtil.newObjectNode();
for (String key : timeseriesKeys) {

122
application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java

@ -14,20 +14,32 @@ import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.Objects;
import java.util.UUID;
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.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
class DefaultAiSolutionServiceTest {
@ -35,19 +47,23 @@ class DefaultAiSolutionServiceTest {
@Mock
TbAiService tbAiService;
@Mock
TbAiClient tbAiClient;
@Mock
TbAiClient.TokenProvider tokenProvider;
@Mock
TbAiClient.TbAiResponse tbAiResponse;
@Mock
TbAiOperations operations;
@Mock
SecurityUser user;
String clientOrigin = "https://tb.example.com";
DefaultAiSolutionService service;
@BeforeEach
void setUp() {
service = new DefaultAiSolutionService(tbAiService);
service = new DefaultAiSolutionService(tbAiService, operations);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse);
}
@Test
@ -55,7 +71,6 @@ class DefaultAiSolutionServiceTest {
// GIVEN
JsonNode expectedResponse = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false);
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.startNewSolution(same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.startNew(user);
@ -63,9 +78,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().startNewSolution(same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_START.equals(operation.type())
&& Objects.equals(null, operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -75,7 +90,6 @@ class DefaultAiSolutionServiceTest {
UUID solutionId = UUID.randomUUID();
JsonNode expectedResponse = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.getSolution(eq(solutionId), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.getSolution(solutionId, user);
@ -83,9 +97,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().getSolution(eq(solutionId), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_GET.equals(operation.type())
&& Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -94,7 +108,6 @@ class DefaultAiSolutionServiceTest {
// GIVEN
JsonNode expectedResponse = solutionInfosResponse(UUID.randomUUID(), "Energy Monitoring");
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.getSolutions(same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.getSolutions(user);
@ -102,9 +115,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().getSolutions(same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_LIST.equals(operation.type())
&& Objects.equals(null, operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -116,8 +129,6 @@ class DefaultAiSolutionServiceTest {
String message = "Add humidity monitoring to the solution.";
JsonNode expectedResponse = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
given(tbAiClient.sendSolutionMessage(eq(solutionId), eq(step), eq(message), same(tokenProvider)))
.willReturn(tbAiResponse);
// WHEN
JsonNode result = service.chat(solutionId, step, message, user);
@ -125,9 +136,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().sendSolutionMessage(eq(solutionId), eq(step), eq(message), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_CHAT.equals(operation.type())
&& Objects.equals(new SolutionChatRequest(solutionId, step, message), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -137,7 +148,6 @@ class DefaultAiSolutionServiceTest {
UUID solutionId = UUID.randomUUID();
JsonNode expectedResponse = solutionResponse(solutionId, "Energy Monitoring", true, false);
given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
given(tbAiClient.createSolution(eq(solutionId), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.createSolution(solutionId, user);
@ -145,9 +155,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().createSolution(eq(solutionId), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_CREATE.equals(operation.type())
&& Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -159,7 +169,6 @@ class DefaultAiSolutionServiceTest {
JsonNode value = TextNode.valueOf("Energy Monitoring");
JsonNode expectedResponse = solutionResponse(solutionId, "Energy Monitoring", false, false);
given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
given(tbAiClient.updateData(eq(solutionId), eq(dataKey), same(value), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.updateData(solutionId, dataKey, value, user);
@ -167,9 +176,9 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().updateData(eq(solutionId), eq(dataKey), same(value), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_DATA_UPDATE.equals(operation.type())
&& Objects.equals(new SolutionDataRequest(solutionId, dataKey, value), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -179,16 +188,14 @@ class DefaultAiSolutionServiceTest {
// GIVEN
UUID solutionId = UUID.randomUUID();
given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
given(tbAiClient.clearStep(eq(solutionId), eq(step), same(tokenProvider)))
.willReturn(tbAiResponse);
// WHEN
service.clearStep(solutionId, step, user);
// THEN
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().clearStep(eq(solutionId), eq(step), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_STEP_CLEAR.equals(operation.type())
&& Objects.equals(new SolutionStepRequest(solutionId, step), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -199,17 +206,22 @@ class DefaultAiSolutionServiceTest {
String tbAccessToken = "tb-access-token";
JsonNode expectedResponse = solutionInstallResultResponse(UUID.randomUUID());
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.installSolution(eq(solutionId), eq(tbAccessToken), same(tokenProvider))).willReturn(tbAiResponse);
stubOperations();
// WHEN
JsonNode result = service.installSolution(solutionId, tbAccessToken, user);
JsonNode result = service.installSolution(solutionId, tbAccessToken, clientOrigin, user);
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().installSolution(eq(solutionId), eq(tbAccessToken), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
TbAiTurnContext[] context = new TbAiTurnContext[1];
TbAiOperation operation = captureOperation(context);
assertThat(operation.type()).isEqualTo(ChannelProtocol.SOLUTION_INSTALL);
assertThat(operation.payload()).isEqualTo(new SolutionOperationRequest(solutionId));
assertThat(context[0].clientOrigin()).isEqualTo(clientOrigin);
assertThat(context[0].tbAccessToken()).isEqualTo(tbAccessToken);
assertThat(context[0].tokenProvider()).isSameAs(tokenProvider);
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -220,17 +232,22 @@ class DefaultAiSolutionServiceTest {
String tbAccessToken = "tb-access-token";
JsonNode expectedResponse = solutionResponse(solutionId, "Energy Monitoring", true, false);
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.uninstallSolution(eq(solutionId), eq(tbAccessToken), same(tokenProvider))).willReturn(tbAiResponse);
stubOperations();
// WHEN
JsonNode result = service.uninstallSolution(solutionId, tbAccessToken, user);
JsonNode result = service.uninstallSolution(solutionId, tbAccessToken, clientOrigin, user);
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().uninstallSolution(eq(solutionId), eq(tbAccessToken), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
TbAiTurnContext[] context = new TbAiTurnContext[1];
TbAiOperation operation = captureOperation(context);
assertThat(operation.type()).isEqualTo(ChannelProtocol.SOLUTION_UNINSTALL);
assertThat(operation.payload()).isEqualTo(new SolutionOperationRequest(solutionId));
assertThat(context[0].clientOrigin()).isEqualTo(clientOrigin);
assertThat(context[0].tbAccessToken()).isEqualTo(tbAccessToken);
assertThat(context[0].tokenProvider()).isSameAs(tokenProvider);
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -239,15 +256,14 @@ class DefaultAiSolutionServiceTest {
// GIVEN
UUID solutionId = UUID.randomUUID();
given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
given(tbAiClient.deleteSolution(eq(solutionId), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
service.deleteSolution(solutionId, user);
// THEN
assertThat(captureProcessCallWithoutCreditCheck().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().deleteSolution(eq(solutionId), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_DELETE.equals(operation.type())
&& Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
@ -265,6 +281,18 @@ class DefaultAiSolutionServiceTest {
return callCaptor.getValue();
}
private void stubOperations() {
given(operations.execute(any(), any())).willReturn(tbAiResponse);
}
private TbAiOperation captureOperation(TbAiTurnContext[] context) {
ArgumentCaptor<TbAiOperation> operationCaptor = ArgumentCaptor.forClass(TbAiOperation.class);
ArgumentCaptor<TbAiTurnContext> contextCaptor = ArgumentCaptor.forClass(TbAiTurnContext.class);
then(operations).should().execute(operationCaptor.capture(), contextCaptor.capture());
context[0] = contextCaptor.getValue();
return operationCaptor.getValue();
}
private static ObjectNode solutionResponse(UUID solutionId, String solutionTitle, boolean built, boolean installed) {
ObjectNode response = JacksonUtil.newObjectNode()
.put("id", solutionId.toString())

20
application/src/test/java/org/thingsboard/server/service/ai/tool/DefaultAiToolServiceTest.java

@ -11,15 +11,19 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
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.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
@ -31,28 +35,28 @@ class DefaultAiToolServiceTest {
@Mock
TbAiService tbAiService;
@Mock
TbAiClient tbAiClient;
@Mock
TbAiClient.TokenProvider tokenProvider;
@Mock
TbAiClient.TbAiResponse tbAiResponse;
@Mock
SecurityUser user;
@Mock
TbAiOperations operations;
DefaultAiToolService service;
@BeforeEach
void setUp() {
service = new DefaultAiToolService(tbAiService);
service = new DefaultAiToolService(tbAiService, operations);
}
@Test
void shouldProcessWithoutCreditCheckAndDelegateToClient_whenResolveToolApprovalCalled() {
void shouldResolveThroughToolApprovalResolveOperation() {
// GIVEN
JsonNode decision = toolApprovalDecision(UUID.randomUUID(), true);
JsonNode expectedResponse = TextNode.valueOf("APPROVED");
given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
given(tbAiClient.resolveToolApproval(same(decision), same(tokenProvider))).willReturn(tbAiResponse);
given(operations.execute(any(TbAiOperation.class), same(user), same(tokenProvider))).willReturn(tbAiResponse);
// WHEN
JsonNode result = service.resolveToolApproval(decision, user);
@ -60,9 +64,9 @@ class DefaultAiToolServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
assertThat(captureProcessCall().apply(tbAiClient, tokenProvider)).isSameAs(tbAiResponse);
then(tbAiClient).should().resolveToolApproval(same(decision), same(tokenProvider));
then(tbAiClient).shouldHaveNoMoreInteractions();
assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.TOOL_APPROVAL_RESOLVE.equals(operation.type())
&& operation.payload() == decision), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}

310
application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java

@ -0,0 +1,310 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.OperationResult;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.TbHttpRequest;
import org.thingsboard.ai.common.channel.TbHttpResponse;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
class ChannelTbAiOperationsTest {
UUID solutionId = UUID.randomUUID();
TbAiRequestExecutor requestExecutor = mock(TbAiRequestExecutor.class);
TbAiTurnContext context = TbAiChannelPoolTest.context(TbAiChannelPoolTest.user(), "https://tb.example.com");
TbAiOperation install = new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId));
FakeTbAiServer server;
TbAiChannelPool pool;
int maxConnections = 10;
@AfterEach
void tearDown() {
if (pool != null) {
pool.shutdown();
}
if (server != null) {
server.close();
}
}
@Test
void shouldRunOperationAndServeThingsBoardRequests() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> {
switch (frame.type()) {
case ChannelProtocol.SOLUTION_INSTALL -> connection.request(frame, ChannelProtocol.TB_REQUEST, "r1",
new TbHttpRequest("POST", "/api/dashboard", null, Map.of(), "{}", "utf8", 5000L));
case ChannelProtocol.TB_RESPONSE -> connection.result(server.received(ChannelProtocol.SOLUTION_INSTALL).getFirst(),
new OperationResult(200, JacksonUtil.newObjectNode().put("mainDashboardId", "d1"), 3));
default -> {}
}
});
doAnswer(invocation -> {
ChannelSession session = invocation.getArgument(0);
ChannelFrame frame = invocation.getArgument(1);
session.send(ChannelFrame.reply(ChannelProtocol.TB_RESPONSE, frame, server.codec.toPayload(new TbHttpResponse(200, Map.of(), "{}", "utf8"))));
return null;
}).when(requestExecutor).serve(any(), any(), any(), any(), anyInt());
// WHEN
TbAiResponse first = operations().execute(install, context);
// THEN
assertThat(first.isSuccess()).isTrue();
assertThat(first.getValue()).isEqualTo(JacksonUtil.newObjectNode().put("mainDashboardId", "d1"));
assertThat(first.getCreditsUsed()).isEqualTo(3);
ChannelFrame start = server.received(ChannelProtocol.SOLUTION_INSTALL).getFirst();
assertThat(server.received(ChannelProtocol.TB_RESPONSE).getFirst().op()).isEqualTo(start.id());
assertThat(server.codec.fromPayload(start.payload(), SolutionOperationRequest.class)).isEqualTo(new SolutionOperationRequest(solutionId));
assertThat(server.connections.get()).isEqualTo(1);
assertThat(server.openConnections.get()).isEqualTo(1);
}
@Test
void shouldRunConcurrentOperationsOnOneChannel() throws Exception {
// GIVEN
CountDownLatch bothStarted = new CountDownLatch(2);
server = FakeTbAiServer.start((connection, frame) -> {
bothStarted.countDown();
CompletableFuture.runAsync(() -> {
await(bothStarted);
connection.result(frame, new OperationResult(200, JacksonUtil.toJsonNode("[]"), 0));
});
});
ChannelTbAiOperations operations = operations();
TbAiOperation list = new TbAiOperation(ChannelProtocol.CHAT_LIST, null);
// WHEN
CompletableFuture<TbAiResponse> first = CompletableFuture.supplyAsync(() -> operations.execute(list, context));
CompletableFuture<TbAiResponse> second = CompletableFuture.supplyAsync(() -> operations.execute(list, context));
// THEN
assertThat(first.get(10, TimeUnit.SECONDS).isSuccess()).isTrue();
assertThat(second.get(10, TimeUnit.SECONDS).isSuccess()).isTrue();
assertThat(server.connections.get()).isEqualTo(1);
}
@Test
void shouldServeManyUsersConcurrently_withOneChannelPerUser() throws Exception {
// GIVEN
maxConnections = 100;
server = FakeTbAiServer.start((connection, frame) -> CompletableFuture.runAsync(() ->
connection.result(frame, new OperationResult(200, JacksonUtil.toJsonNode("[]"), 0))));
ChannelTbAiOperations operations = operations();
TbAiOperation list = new TbAiOperation(ChannelProtocol.CHAT_LIST, null);
List<TbAiTurnContext> users = java.util.stream.IntStream.range(0, 50)
.mapToObj(i -> TbAiChannelPoolTest.context(TbAiChannelPoolTest.user(), "https://tb.example.com"))
.toList();
var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor();
// WHEN
List<CompletableFuture<TbAiResponse>> calls = java.util.stream.IntStream.range(0, 400)
.mapToObj(i -> CompletableFuture.supplyAsync(() -> operations.execute(list, users.get(i % users.size())), executor))
.toList();
CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new)).get(30, TimeUnit.SECONDS);
// THEN
assertThat(calls).allSatisfy(call -> assertThat(call.join().isSuccess()).isTrue());
assertThat(server.connections.get()).isEqualTo(users.size());
assertThat(pool.pooledConnections()).isEqualTo(users.size());
executor.close();
}
@Test
void shouldServeEveryCall_whenUsersOutnumberThePool() throws Exception {
// GIVEN
maxConnections = 5;
server = FakeTbAiServer.start((connection, frame) -> CompletableFuture.runAsync(() ->
connection.result(frame, new OperationResult(200, JacksonUtil.toJsonNode("[]"), 0))));
ChannelTbAiOperations operations = operations();
TbAiOperation list = new TbAiOperation(ChannelProtocol.CHAT_LIST, null);
var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor();
// WHEN
List<CompletableFuture<TbAiResponse>> calls = java.util.stream.IntStream.range(0, 100)
.mapToObj(i -> CompletableFuture.supplyAsync(() -> operations.execute(list,
TbAiChannelPoolTest.context(TbAiChannelPoolTest.user(), "https://tb.example.com")), executor))
.toList();
CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new)).get(30, TimeUnit.SECONDS);
// THEN
assertThat(calls).allSatisfy(call -> assertThat(call.join().isSuccess()).isTrue());
assertThat(pool.pooledConnections()).isLessThanOrEqualTo(maxConnections);
executor.close();
}
@Test
void shouldRetryOnNewChannel_whenServerHasTooManyOperations() {
// GIVEN
AtomicBoolean refused = new AtomicBoolean();
server = FakeTbAiServer.start((connection, frame) -> {
if (refused.compareAndSet(false, true)) {
connection.refuse(frame, ChannelError.TOO_MANY_OPERATIONS);
} else {
connection.result(frame, new OperationResult(200, JacksonUtil.toJsonNode("[]"), 0));
}
});
// WHEN
TbAiResponse response = operations().execute(new TbAiOperation(ChannelProtocol.CHAT_LIST, null), context);
// THEN
assertThat(response.isSuccess()).isTrue();
assertThat(server.connections.get()).isEqualTo(2);
}
@Test
void shouldFailWithoutRetry_whenChannelDropsAfterOperationWasSent() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> connection.close(1011, "Crashed"));
// WHEN
TbAiResponse response = operations().execute(install, context);
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable");
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
}
@Test
void shouldRetryOnNewChannel_whenChannelGoesAwayBeforeAnyFrame() {
// GIVEN
AtomicBoolean wentAway = new AtomicBoolean();
server = FakeTbAiServer.start((connection, frame) -> {
if (wentAway.compareAndSet(false, true)) {
connection.close(ChannelProtocol.CLOSE_GOING_AWAY, "Server is shutting down");
} else {
connection.result(frame, new OperationResult(200, null, 0));
}
});
// WHEN
TbAiResponse response = operations().execute(install, context);
// THEN
assertThat(response.isSuccess()).isTrue();
assertThat(server.connections.get()).isEqualTo(2);
}
@Test
void shouldReturnErrorMessageFromBody_whenOperationFails() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> connection.result(frame,
new OperationResult(404, JacksonUtil.newObjectNode().put("message", "Solution not found"), 0)));
// WHEN
TbAiResponse response = operations().execute(install, context);
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Solution not found");
}
@Test
void shouldFailWithoutRetry_whenServerAbortsRunningOperations() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) ->
connection.close(ChannelProtocol.CLOSE_EXCHANGES_ABORTED, "Server is shutting down"));
// WHEN
TbAiResponse response = operations().execute(install, context);
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable");
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
assertThat(server.connections.get()).isEqualTo(1);
}
@Test
void shouldSendCallOrigin_whenChannelWasOpenedWithAnother() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> connection.result(frame, new OperationResult(200, null, 0)));
TbAiChannelPool sharedPool = new TbAiChannelPool(server.client(), 10, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), System::nanoTime, false);
SecurityUser user = TbAiChannelPoolTest.user();
var channelOperations = new ChannelTbAiOperations(sharedPool, requestExecutor);
// WHEN
channelOperations.execute(new TbAiOperation(ChannelProtocol.CHAT_LIST, null), TbAiChannelPoolTest.context(user, "https://tb.example.com"));
channelOperations.execute(new TbAiOperation(ChannelProtocol.CHAT_LIST, null), TbAiChannelPoolTest.context(user, "https://other.example.com"));
// THEN
assertThat(server.connections.get()).isEqualTo(1);
assertThat(server.received(ChannelProtocol.CHAT_LIST)).extracting(ChannelFrame::origin)
.containsExactly("https://tb.example.com", "https://other.example.com");
sharedPool.shutdown();
}
@Test
void shouldSignalChannelUnavailable_whenServerHasNoChannelEndpoint() {
// GIVEN
server = FakeTbAiServer.rejecting(404);
// WHEN-THEN
assertThatThrownBy(() -> operations().execute(install, context)).isInstanceOf(TbAiChannelUnavailableException.class);
}
@Test
void shouldSignalRejection_whenServerRejectsToken() {
// GIVEN
server = FakeTbAiServer.rejecting(401);
// WHEN-THEN
assertThatThrownBy(() -> operations().execute(install, context))
.isInstanceOf(TbAiChannelRejectedException.class)
.hasMessage("Unauthorized");
}
@Test
void shouldMapResultWithoutMessage_toReasonPhrase() {
// WHEN
TbAiResponse response = ChannelTbAiOperations.toResponse(new OperationResult(403, null, 0));
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Forbidden");
}
ChannelTbAiOperations operations() {
if (pool == null) {
pool = new TbAiChannelPool(server.client(), maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), System::nanoTime, false);
}
return new ChannelTbAiOperations(pool, requestExecutor);
}
static void await(CountDownLatch latch) {
try {
latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

200
application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java

@ -0,0 +1,200 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.codec.ServerSentEvent;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelHello;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatEventPayload;
import org.thingsboard.ai.common.channel.ChatTurnRequest;
import org.thingsboard.ai.common.channel.TbHttpRequest;
import org.thingsboard.ai.common.channel.TbHttpResponse;
import org.thingsboard.ai.common.channel.TurnEnd;
import org.thingsboard.common.util.JacksonUtil;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
class ChannelTbAiTransportTest {
static final UUID EXECUTION_ID = UUID.fromString("33333333-3333-3333-3333-333333333333");
TbAiRequestExecutor requestExecutor = mock(TbAiRequestExecutor.class);
TbAiTurnContext context = TbAiChannelPoolTest.context(TbAiChannelPoolTest.user(), "https://tb.example.com");
JsonNode request = JacksonUtil.newObjectNode().put("message", "Create a device");
FakeTbAiServer server;
TbAiChannelPool pool;
@AfterEach
void tearDown() {
if (pool != null) {
pool.shutdown();
}
if (server != null) {
server.close();
}
}
@Test
void shouldRelayEventsServeRequestsAndKeepChannel() {
// GIVEN
server = FakeTbAiServer.start(this::assistantWithToolCall);
stubExecutor();
// WHEN
List<ServerSentEvent<String>> first = turn();
List<ServerSentEvent<String>> second = turn();
// THEN
assertThat(first).extracting(ServerSentEvent::event, ServerSentEvent::comment).containsExactly(
tuple(null, "heartbeat"), tuple("assistantMessage", null), tuple("toolExecutionRequested", null));
assertThat(second).hasSize(3);
assertThat(server.connections.get()).isEqualTo(1);
ChannelHello hello = server.codec.fromPayload(server.received(ChannelProtocol.HELLO).getFirst().payload(), ChannelHello.class);
assertThat(hello).isEqualTo(new ChannelHello(1, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null));
ChannelFrame send = server.received(ChannelProtocol.CHAT_SEND).getFirst();
ChatTurnRequest turnRequest = server.codec.fromPayload(send.payload(), ChatTurnRequest.class);
assertThat(turnRequest.request()).isEqualTo(request);
assertThat(turnRequest.acceptLanguage()).isEqualTo("de-DE");
assertThat(server.received(ChannelProtocol.TB_RESPONSE)).extracting(ChannelFrame::op)
.containsExactlyElementsOf(server.received(ChannelProtocol.CHAT_SEND).stream().map(ChannelFrame::id).toList());
}
@Test
void shouldRetryOnNewChannel_whenServerIsDraining() {
// GIVEN
AtomicBoolean drained = new AtomicBoolean();
server = FakeTbAiServer.start((connection, frame) -> {
if (ChannelProtocol.CHAT_SEND.equals(frame.type())) {
if (drained.compareAndSet(false, true)) {
connection.refuse(frame, ChannelError.DRAINING);
} else {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("assistantMessage",
JacksonUtil.newObjectNode().put("message", "Hi")));
connection.sendFor(frame, ChannelProtocol.TURN_END, new TurnEnd(TurnEnd.Status.COMPLETED));
}
}
});
// WHEN
List<ServerSentEvent<String>> events = turn();
// THEN
assertThat(events).extracting(ServerSentEvent::event).containsExactly("assistantMessage");
assertThat(server.connections.get()).isEqualTo(2);
}
@Test
void shouldCancelOnlyItsTurn_whenBrowserLeaves() {
// GIVEN
server = FakeTbAiServer.start((connection, frame) -> {
if (ChannelProtocol.CHAT_SEND.equals(frame.type())) {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("heartbeat", null));
}
});
pool = pool();
var transport = new ChannelTbAiTransport(pool, requestExecutor);
AtomicBoolean heartbeat = new AtomicBoolean();
// WHEN
Disposable subscription = transport.sendChatMessage(UUID.randomUUID(), request, context).subscribe(event -> heartbeat.set(true));
await().atMost(Duration.ofSeconds(5)).untilTrue(heartbeat);
subscription.dispose();
// THEN
await().atMost(Duration.ofSeconds(5)).until(() -> !server.received(ChannelProtocol.CANCEL).isEmpty());
ChannelFrame cancel = server.received(ChannelProtocol.CANCEL).getFirst();
assertThat(cancel.op()).isEqualTo(server.received(ChannelProtocol.CHAT_SEND).getFirst().id());
assertThat(server.openConnections.get()).isEqualTo(1);
}
@Test
void shouldSignalChannelUnavailable_whenServerHasNoChannelEndpoint() {
// GIVEN
server = FakeTbAiServer.rejecting(404);
// WHEN-THEN
assertThatThrownBy(this::turn).isInstanceOf(TbAiChannelUnavailableException.class);
}
@Test
void shouldEmitErrorEvent_whenServerRejectsToken() {
// GIVEN
server = FakeTbAiServer.rejecting(401);
// WHEN
List<ServerSentEvent<String>> events = turn();
// THEN
assertThat(events).hasSize(1);
assertThat(events.getFirst().event()).isEqualTo("error");
assertThat(JacksonUtil.toJsonNode(events.getFirst().data())).isEqualTo(JacksonUtil.toJsonNode("{\"message\":\"Unauthorized\"}"));
}
List<ServerSentEvent<String>> turn() {
if (pool == null) {
pool = pool();
}
TbAiTurnContext turnContext = new TbAiTurnContext(context.tenantId(), context.userId(), context.user(), "Bearer user-jwt",
"de-DE", context.tokenProvider(), "https://tb.example.com");
return new ChannelTbAiTransport(pool, requestExecutor)
.sendChatMessage(UUID.randomUUID(), request, turnContext)
.collectList()
.block(Duration.ofSeconds(10));
}
TbAiChannelPool pool() {
return new TbAiChannelPool(server.client(), 10, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), System::nanoTime, false);
}
void stubExecutor() {
given(requestExecutor.execute(any(), any(), any(), anyInt())).willAnswer(invocation -> {
ChannelFrame frame = invocation.getArgument(0);
var response = new TbHttpResponse(200, Map.of("Content-Type", List.of("application/json")), "{\"id\":\"d1\"}", "utf8");
return Mono.just(ChannelFrame.reply(ChannelProtocol.TB_RESPONSE, frame, server.codec.toPayload(response)));
});
doCallRealMethod().when(requestExecutor).serve(any(), any(), any(), any(), anyInt());
}
void assistantWithToolCall(FakeTbAiServer.Connection connection, ChannelFrame frame) {
switch (frame.type()) {
case ChannelProtocol.CHAT_SEND -> {
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("heartbeat", null));
connection.sendFor(frame, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("assistantMessage",
JacksonUtil.newObjectNode().put("message", "Working on it")));
connection.request(frame, ChannelProtocol.TB_REQUEST, "r-" + frame.id(),
new TbHttpRequest("POST", "/api/device", null, Map.of(), "{}", "utf8", 5000L));
}
case ChannelProtocol.TB_RESPONSE -> {
ChannelFrame start = server.received(ChannelProtocol.CHAT_SEND).stream()
.filter(send -> frame.replyTo().equals("r-" + send.id())).findFirst().orElseThrow();
connection.sendFor(start, ChannelProtocol.CHAT_EVENT, new ChatEventPayload("toolExecutionRequested",
JacksonUtil.newObjectNode().put("executionId", EXECUTION_ID.toString()).put("needsApproval", true)));
connection.sendFor(start, ChannelProtocol.TURN_END, new TurnEnd(TurnEnd.Status.COMPLETED));
}
default -> {}
}
}
}

135
application/src/test/java/org/thingsboard/server/service/ai/transport/FakeTbAiServer.java

@ -0,0 +1,135 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelHello;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.OperationResult;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A scripted TB AI channel endpoint. It answers {@code hello} with the protocol version and frame limit and hands every other frame
* to the script, which replies through {@link Connection}: tagged with the op of the operation it belongs to, as TB AI
* does.
*/
class FakeTbAiServer implements AutoCloseable {
@FunctionalInterface
interface Script {
void onFrame(Connection connection, ChannelFrame frame);
}
final ChannelFrameCodec codec = new ChannelFrameCodec(new ObjectMapper());
final List<ChannelFrame> received = new CopyOnWriteArrayList<>();
final AtomicInteger connections = new AtomicInteger();
final AtomicInteger openConnections = new AtomicInteger();
private final DisposableServer server;
private FakeTbAiServer(Script script) {
server = HttpServer.create().host("127.0.0.1").port(0)
.route(routes -> routes.ws(ChannelProtocol.WS_PATH, (inbound, outbound) -> {
connections.incrementAndGet();
openConnections.incrementAndGet();
var connection = new Connection();
inbound.receive().asString().subscribe(text -> {
ChannelFrame frame = codec.decode(text);
received.add(frame);
if (ChannelProtocol.HELLO.equals(frame.type())) {
connection.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(
new ChannelHello(1, null, null, (long) TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES))));
} else {
script.onFrame(connection, frame);
}
});
return outbound.sendString(connection.out.asFlux())
.then()
.then(Mono.defer(() -> outbound.sendClose(connection.closeCode, connection.closeReason)))
.doFinally(signal -> openConnections.decrementAndGet());
}))
.bindNow();
}
static FakeTbAiServer start(Script script) {
return new FakeTbAiServer(script);
}
static FakeTbAiServer rejecting(int status) {
return new FakeTbAiServer(status);
}
private FakeTbAiServer(int status) {
server = HttpServer.create().host("127.0.0.1").port(0)
.route(routes -> routes.get(ChannelProtocol.WS_PATH, (req, res) -> res.status(status).send()))
.bindNow();
}
String baseUrl() {
return "http://127.0.0.1:" + server.port();
}
TbAiChannelClient client() {
return new TbAiChannelClient(baseUrl());
}
List<ChannelFrame> received(String type) {
return received.stream().filter(frame -> type.equals(frame.type())).toList();
}
@Override
public void close() {
server.disposeNow(Duration.ofSeconds(5));
}
final class Connection {
private final Sinks.Many<String> out = Sinks.many().unicast().onBackpressureBuffer();
private volatile int closeCode = ChannelProtocol.CLOSE_NORMAL;
private volatile String closeReason = "Done";
// A unicast sink drops concurrent emissions, so frames sent from several threads are serialized here.
synchronized void send(ChannelFrame frame) {
out.tryEmitNext(codec.encode(frame));
}
/**
* A frame that belongs to the operation started by {@code start}.
*/
void sendFor(ChannelFrame start, String type, Object payload) {
send(new ChannelFrame(type, null, null, codec.toPayload(payload), start.id()));
}
void request(ChannelFrame start, String type, String id, Object payload) {
send(new ChannelFrame(type, id, null, codec.toPayload(payload), start.id()));
}
void result(ChannelFrame start, OperationResult result) {
send(new ChannelFrame(ChannelProtocol.OPERATION_RESULT, null, start.id(), codec.toPayload(result), start.id()));
}
void refuse(ChannelFrame start, String code) {
send(new ChannelFrame(ChannelProtocol.ERROR, null, start.id(), codec.toPayload(new ChannelError(code, code)),
start.id()));
}
synchronized void close(int code, String reason) {
closeCode = code;
closeReason = reason;
out.tryEmitComplete();
}
}
}

233
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java

@ -0,0 +1,233 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class TbAiChannelPoolTest {
AtomicLong now = new AtomicLong(1_000_000_000L);
FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {});
TbAiChannelPool pool;
@AfterEach
void tearDown() {
if (pool != null) {
pool.shutdown();
}
server.close();
}
@Test
void shouldShareOneHandshake_whenUserMakesConcurrentFirstCalls() {
// GIVEN
pool = pool(10);
TbAiTurnContext context = context(user(), "https://tb.example.com");
// WHEN
CompletableFuture<TbAiPooledConnection> first = pool.acquire(context, false);
CompletableFuture<TbAiPooledConnection> second = pool.acquire(context, false);
// THEN
assertThat(join(first)).isSameAs(join(second));
assertThat(server.connections.get()).isEqualTo(1);
assertThat(pool.pooledConnections()).isEqualTo(1);
}
@Test
void shouldReuseChannel_whenSameUserCallsAgain() {
// GIVEN
pool = pool(10);
TbAiTurnContext context = context(user(), "https://tb.example.com");
TbAiPooledConnection connection = join(pool.acquire(context, false));
connection.unreserve(now.get());
// WHEN
TbAiPooledConnection again = join(pool.acquire(context, false));
// THEN
assertThat(again).isSameAs(connection);
assertThat(server.connections.get()).isEqualTo(1);
}
@Test
void shouldShareChannel_whenUserComesThroughDifferentOrigins() {
// GIVEN
pool = pool(10);
SecurityUser user = user();
TbAiPooledConnection mainOrigin = join(pool.acquire(context(user, "https://tb.example.com"), false));
// WHEN
TbAiPooledConnection otherOrigin = join(pool.acquire(context(user, "https://other.example.com"), false));
TbAiPooledConnection otherUser = join(pool.acquire(context(user(), "https://tb.example.com"), false));
// THEN
assertThat(otherOrigin).isSameAs(mainOrigin);
assertThat(otherUser).isNotSameAs(mainOrigin);
assertThat(server.connections.get()).isEqualTo(2);
}
@Test
void shouldOpenNoChannel_whenPoolIsShutDown() {
// GIVEN
pool = pool(10);
pool.shutdown();
// WHEN-THEN
assertThatThrownBy(() -> join(pool.acquire(context(user(), "https://tb.example.com"), false)))
.hasCauseInstanceOf(TbAiChannelUnavailableException.class)
.hasMessageEndingWith("Server is shutting down");
assertThat(server.connections.get()).isZero();
}
@Test
void shouldCloseChannel_whenIdleLongerThanTimeout() {
// GIVEN
pool = pool(10);
TbAiPooledConnection connection = join(pool.acquire(context(user(), "https://tb.example.com"), false));
connection.unreserve(now.get());
// WHEN
now.addAndGet(Duration.ofSeconds(30).toNanos());
pool.sweep();
int openAfterHalfTimeout = server.openConnections.get();
now.addAndGet(Duration.ofSeconds(31).toNanos());
pool.sweep();
// THEN
assertThat(openAfterHalfTimeout).isEqualTo(1);
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 0);
await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0);
}
@Test
void shouldRetireBusyChannel_whenOlderThanMaxAge() {
// GIVEN
pool = pool(10);
TbAiTurnContext context = context(user(), "https://tb.example.com");
TbAiPooledConnection busy = join(pool.acquire(context, false));
// WHEN
now.addAndGet(Duration.ofMinutes(11).toNanos());
pool.sweep();
TbAiPooledConnection next = join(pool.acquire(context, false));
busy.unreserve(now.get());
// THEN
assertThat(next).isNotSameAs(busy);
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
}
@Test
void shouldEvictIdleChannel_whenPoolIsFull() {
// GIVEN
pool = pool(1);
TbAiPooledConnection idle = join(pool.acquire(context(user(), "https://tb.example.com"), false));
idle.unreserve(now.get());
// WHEN
TbAiPooledConnection next = join(pool.acquire(context(user(), "https://tb.example.com"), false));
// THEN
assertThat(next.isPooled()).isTrue();
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
}
@Test
void shouldUseTransientChannel_whenPoolIsFullOfBusyChannels() {
// GIVEN
pool = pool(1);
join(pool.acquire(context(user(), "https://tb.example.com"), false));
// WHEN
TbAiPooledConnection overflow = join(pool.acquire(context(user(), "https://tb.example.com"), false));
overflow.unreserve(now.get());
// THEN
assertThat(overflow.isPooled()).isFalse();
assertThat(pool.pooledConnections()).isEqualTo(1);
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
}
@Test
void shouldUseTransientChannel_whenCallIsBackgroundWork() {
// GIVEN
pool = pool(10);
TbAiTurnContext context = TbAiTurnContext.background(TenantId.fromUUID(UUID.randomUUID()), new UserId(UUID.randomUUID()),
() -> "token", "https://tb.example.com");
// WHEN
TbAiPooledConnection connection = join(pool.acquire(context, false));
connection.unreserve(now.get());
// THEN
assertThat(connection.isPooled()).isFalse();
assertThat(pool.pooledConnections()).isZero();
await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 0);
}
@Test
void shouldFailWithRejection_whenTokenIsRefused() {
// GIVEN
server.close();
server = FakeTbAiServer.rejecting(401);
pool = pool(10);
// WHEN-THEN
assertThatThrownBy(() -> join(pool.acquire(context(user(), "https://tb.example.com"), false)))
.hasCauseInstanceOf(TbAiChannelRejectedException.class);
await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0);
}
@Test
void shouldFailAsUnavailable_whenServerHasNoChannelEndpoint() {
// GIVEN
server.close();
server = FakeTbAiServer.rejecting(404);
pool = pool(10);
// WHEN-THEN
assertThatThrownBy(() -> join(pool.acquire(context(user(), "https://tb.example.com"), false)))
.hasCauseInstanceOf(TbAiChannelUnavailableException.class);
await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0);
}
TbAiChannelPool pool(int maxConnections) {
return new TbAiChannelPool(server.client(), maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false);
}
static TbAiPooledConnection join(CompletableFuture<TbAiPooledConnection> future) {
return future.orTimeout(10, TimeUnit.SECONDS).join();
}
static SecurityUser user() {
SecurityUser user = mock(SecurityUser.class);
given(user.getTenantId()).willReturn(TenantId.fromUUID(UUID.randomUUID()));
given(user.getId()).willReturn(new UserId(UUID.randomUUID()));
return user;
}
static TbAiTurnContext context(SecurityUser user, String origin) {
return new TbAiTurnContext(user, null, null, () -> "token", origin);
}
}

91
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java

@ -0,0 +1,91 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class TbAiOperationsTest {
TbAiTurnContext context = new TbAiTurnContext(mock(SecurityUser.class), "Bearer jwt", null, () -> "token",
"https://tb.example.com");
TbAiResponse channelResponse = TbAiResponse.builder().success(true).build();
TbAiOperation operation = new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, null);
ChannelTbAiOperations channel = mock(ChannelTbAiOperations.class);
SystemSecurityService systemSecurityService = mock(SystemSecurityService.class);
TbAiOperations operations = new TbAiOperations(channel, systemSecurityService);
@Test
void shouldReturnChannelResponse_whenChannelAnswers() {
// GIVEN
given(channel.execute(operation, context)).willReturn(channelResponse);
// WHEN-THEN
assertThat(operations.execute(operation, context)).isSameAs(channelResponse);
}
@Test
void shouldReturnServiceUnavailable_whenChannelCannotBeOpened() {
// GIVEN
given(channel.execute(operation, context)).willThrow(new TbAiChannelUnavailableException("404", null));
// WHEN
TbAiResponse response = operations.execute(operation, context);
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Service unavailable");
}
@Test
void shouldReturnRejection_whenChannelHandshakeIsRefused() {
// GIVEN
given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException("Unauthorized"));
// WHEN
TbAiResponse response = operations.execute(operation, context);
// THEN
assertThat(response.isSuccess()).isFalse();
assertThat(response.getError()).isEqualTo("Unauthorized");
}
@Test
void shouldUseSettingsBaseUrlAsOrigin_whenCalledForUser() {
// GIVEN
SecurityUser user = mock(SecurityUser.class);
TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
CustomerId customerId = new CustomerId(UUID.randomUUID());
given(user.getAuthority()).willReturn(Authority.TENANT_ADMIN);
given(user.getTenantId()).willReturn(tenantId);
given(user.getCustomerId()).willReturn(customerId);
given(systemSecurityService.getBaseUrl(Authority.TENANT_ADMIN, tenantId, customerId, null)).willReturn("https://tb.example.com");
given(channel.execute(any(), any())).willReturn(channelResponse);
// WHEN
operations.execute(operation, user, () -> "token");
// THEN
ArgumentCaptor<TbAiTurnContext> captured = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(channel).execute(same(operation), captured.capture());
assertThat(captured.getValue().clientOrigin()).isEqualTo("https://tb.example.com");
assertThat(captured.getValue().tbAccessToken()).isNull();
}
}

102
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java

@ -0,0 +1,102 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelHello;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
class TbAiPooledConnectionTest {
ChannelFrameCodec codec = new ChannelFrameCodec(new ObjectMapper());
TbAiChannelPool pool = new TbAiChannelPool(mock(TbAiChannelClient.class), 10, 20, Duration.ofSeconds(60),
Duration.ofMinutes(10), System::nanoTime, false);
TbAiChannelPool.PoolKey key = new TbAiChannelPool.PoolKey(TenantId.fromUUID(UUID.randomUUID()), new UserId(UUID.randomUUID()));
@Test
void shouldCloseSessionWithoutHello_whenSessionArrivesAfterHandshakeTimedOut() {
// GIVEN
TbAiPooledConnection connection = connection();
ChannelSession session = openSession();
connection.failed(new TimeoutException());
// WHEN
connection.opened(session);
// THEN
then(session).should(never()).send(any());
then(session).should().close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
assertThat(connection.isRemoved()).isTrue();
assertThat(pool.pooledConnections()).isZero();
}
@Test
void shouldCloseOpenedSession_whenHandshakeTimesOutBeforeHelloReply() {
// GIVEN
TbAiPooledConnection connection = connection();
ChannelSession session = openSession();
connection.opened(session);
// WHEN
connection.failed(new TimeoutException());
connection.onFrame(session, ChannelFrame.of(ChannelProtocol.HELLO,
codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, null, null, null))));
// THEN
then(session).should().close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
assertThat(connection.ready()).isCompletedExceptionally();
assertThat(connection.isRemoved()).isTrue();
assertThat(pool.pooledConnections()).isZero();
}
@Test
void shouldSendHelloWithoutCapabilities_whenSessionOpens() {
// GIVEN
TbAiPooledConnection connection = connection();
ChannelSession session = openSession();
// WHEN
connection.opened(session);
connection.onFrame(session, ChannelFrame.of(ChannelProtocol.HELLO,
codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, null, null, 1024L))));
// THEN
then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO,
codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, List.of(), "https://tb.example.com", null))));
then(session).should(never()).close(anyInt(), anyString());
assertThat(connection.ready()).isCompletedWithValue(connection);
assertThat(connection.maxFrameBytes()).isEqualTo(1024);
}
TbAiPooledConnection connection() {
return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime());
}
static ChannelSession openSession() {
ChannelSession session = mock(ChannelSession.class);
given(session.isOpen()).willReturn(true);
return session;
}
}

209
application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutorTest.java

@ -0,0 +1,209 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.handler.codec.http.HttpHeaders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbHttpRequest;
import org.thingsboard.ai.common.channel.TbHttpResponse;
import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class TbAiRequestExecutorTest {
ChannelFrameCodec codec = new ChannelFrameCodec(new ObjectMapper());
AtomicReference<HttpHeaders> receivedHeaders = new AtomicReference<>();
AtomicReference<String> receivedUri = new AtomicReference<>();
AtomicReference<String> receivedBody = new AtomicReference<>();
DisposableServer tbServer;
TbAiRequestExecutor executor;
TbAiTurnContext context = new TbAiTurnContext(user("203.0.113.7"), "Bearer user-jwt", "en-US", () -> "ai-token",
"https://tb.example.com");
@BeforeEach
void setUp() {
tbServer = HttpServer.create().host("127.0.0.1").port(0).route(routes -> routes
.get("/api/tenant/devices", (request, response) -> {
receivedHeaders.set(request.requestHeaders());
receivedUri.set(request.uri());
return response.header("Content-Type", "application/json").sendString(Mono.just("{\"data\":[]}"));
})
.post("/api/device", (request, response) -> request.receive().aggregate().asString()
.flatMap(body -> {
receivedBody.set(body);
return response.status(201).header("Content-Type", "application/json")
.sendString(Mono.just("{\"id\":\"saved\"}")).then();
}))
.get("/api/large", (request, response) -> response.header("Content-Type", "application/json")
.sendString(Mono.just("{\"payload\":\"" + "x".repeat(200) + "\"}"))))
.bindNow();
executor = new TbAiRequestExecutor("http://127.0.0.1:" + tbServer.port(), null);
}
@AfterEach
void tearDown() {
tbServer.disposeNow();
}
@Test
void shouldCallThingsBoardAsUserWithForwardedHeaders_whenRequestIsValid() {
// GIVEN
var request = new TbHttpRequest("GET", "/api/tenant/devices", "pageSize=10&page=0",
Map.of("Accept", List.of("application/json"), "Authorization", List.of("Bearer ai-token")), null, "base64", 5000L);
// WHEN
ChannelFrame reply = execute(request, 10_000);
// THEN
assertThat(reply.type()).isEqualTo(ChannelProtocol.TB_RESPONSE);
TbHttpResponse response = codec.fromPayload(reply.payload(), TbHttpResponse.class);
assertThat(response.status()).isEqualTo(200);
assertThat(response.body()).isEqualTo("{\"data\":[]}");
assertThat(response.bodyEncoding()).isEqualTo("utf8");
assertThat(receivedUri.get()).isEqualTo("/api/tenant/devices?pageSize=10&page=0");
HttpHeaders headers = receivedHeaders.get();
assertThat(headers.get("X-Authorization")).isEqualTo("Bearer user-jwt");
assertThat(headers.get("X-Forwarded-Host")).isEqualTo("tb.example.com");
assertThat(headers.get("X-Forwarded-Proto")).isEqualTo("https");
assertThat(headers.get("X-Forwarded-Port")).isEqualTo("443");
assertThat(headers.get("X-Forwarded-For")).isEqualTo("203.0.113.7");
assertThat(headers.get("Accept")).isEqualTo("application/json");
assertThat(headers.contains("Authorization")).isFalse();
}
@Test
void shouldForwardBodyAndStatus_whenRequestHasBody() {
// GIVEN
var request = new TbHttpRequest("POST", "/api/device", null,
Map.of("Content-Type", List.of("application/json")), "{\"name\":\"Pump\"}", "utf8", 5000L);
// WHEN
ChannelFrame reply = execute(request, 10_000);
// THEN
TbHttpResponse response = codec.fromPayload(reply.payload(), TbHttpResponse.class);
assertThat(response.status()).isEqualTo(201);
assertThat(response.body()).isEqualTo("{\"id\":\"saved\"}");
assertThat(receivedBody.get()).isEqualTo("{\"name\":\"Pump\"}");
}
@Test
void shouldPassThroughErrorStatus_whenThingsBoardRejectsRequest() {
// GIVEN
var request = new TbHttpRequest("GET", "/api/missing", null, Map.of(), null, "base64", 5000L);
// WHEN
ChannelFrame reply = execute(request, 10_000);
// THEN
assertThat(reply.type()).isEqualTo(ChannelProtocol.TB_RESPONSE);
assertThat(codec.fromPayload(reply.payload(), TbHttpResponse.class).status()).isEqualTo(404);
}
@Test
void shouldReplyWithError_whenResponseExceedsFrameLimit() {
// GIVEN
var request = new TbHttpRequest("GET", "/api/large", null, Map.of(), null, "base64", 5000L);
// WHEN
ChannelFrame reply = execute(request, 100);
// THEN
assertThat(reply.type()).isEqualTo(ChannelProtocol.ERROR);
assertThat(codec.fromPayload(reply.payload(), ChannelError.class))
.isEqualTo(new ChannelError("too_large", "Response is larger than the channel frame limit"));
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
GET | /oauth2/authorization | Path must start with /api/
GET | http://evil/api/x | Path must start with /api/
GET | /api/../admin | Path must be a normalized relative path
GET | /api//device | Path must be a normalized relative path
GET | /api/device?x=1 | Path must be a normalized relative path
TRACE | /api/device | Method is not allowed: TRACE
""")
void shouldRejectRequest_whenMethodOrPathIsNotAllowed(String method, String path, String expectedMessage) {
// GIVEN
var request = new TbHttpRequest(method, path, null, Map.of(), null, "base64", 5000L);
// WHEN
ChannelFrame reply = execute(request, 10_000);
// THEN
assertThat(reply.type()).isEqualTo(ChannelProtocol.ERROR);
assertThat(codec.fromPayload(reply.payload(), ChannelError.class)).isEqualTo(new ChannelError("invalid_request", expectedMessage));
assertThat(receivedUri.get()).isNull();
}
@ParameterizedTest
@CsvSource(delimiter = '|', nullValues = "null", textBlock = """
https://tb.example.com | 203.0.113.7 | https | tb.example.com | 443 | 203.0.113.7
http://tb.example.com | null | http | tb.example.com | 80 | null
http://10.0.0.5:8080/ | 10.0.0.9 | http | 10.0.0.5 | 8080 | 10.0.0.9
https://[2001:db8::1]:8443 | null | https | [2001:db8::1] | 8443 | null
""")
void shouldBuildForwardedHeadersFromClientOrigin(String clientOrigin, String clientAddress, String proto, String host,
String port, String forwardedFor) {
// GIVEN
var turn = new TbAiTurnContext(user(clientAddress), "Bearer user-jwt", null, () -> "ai-token", clientOrigin);
// WHEN
Map<String, String> headers = TbAiRequestExecutor.forwardedHeaders(turn);
// THEN
assertThat(headers).containsEntry("X-Forwarded-Proto", proto)
.containsEntry("X-Forwarded-Host", host)
.containsEntry("X-Forwarded-Port", port);
if (forwardedFor != null) {
assertThat(headers).containsEntry("X-Forwarded-For", forwardedFor);
} else {
assertThat(headers).doesNotContainKey("X-Forwarded-For");
}
}
@ParameterizedTest
@CsvSource(nullValues = "null", value = {"null", "not a url", "ftp://tb.example.com", "/relative"})
void shouldForwardNoOrigin_whenClientOriginIsNotAnHttpUrl(String clientOrigin) {
// GIVEN
var turn = new TbAiTurnContext(user(null), "Bearer user-jwt", null, () -> "ai-token", clientOrigin);
// WHEN-THEN
assertThat(TbAiRequestExecutor.forwardedHeaders(turn)).isEmpty();
}
static SecurityUser user(String clientAddress) {
SecurityUser user = mock(SecurityUser.class);
given(user.getClientAddress()).willReturn(clientAddress);
return user;
}
ChannelFrame execute(TbHttpRequest request, int maxBodyBytes) {
var frame = new ChannelFrame(ChannelProtocol.TB_REQUEST, UUID.randomUUID().toString(), null, codec.toPayload(request));
ChannelFrame reply = executor.execute(frame, codec, context, maxBodyBytes).block(Duration.ofSeconds(10));
assertThat(reply.replyTo()).isEqualTo(frame.id());
return reply;
}
}

34
application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java

@ -16,6 +16,7 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.common.util.JacksonUtil;
@ -94,6 +95,9 @@ import org.thingsboard.server.dao.usagerecord.ApiUsageStateDao;
import org.thingsboard.server.gen.transport.TransportProtos.HousekeeperTaskProto;
import org.thingsboard.server.gen.transport.TransportProtos.ToHousekeeperServiceMsg;
import org.thingsboard.server.service.ai.TbAiTokenProvider;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.housekeeper.processor.EntitiesCleanupTaskProcessor;
import org.thingsboard.server.service.housekeeper.processor.TsHistoryDeletionTaskProcessor;
@ -144,7 +148,7 @@ public class HousekeeperServiceTest extends AbstractControllerTest {
@MockitoSpyBean
private EntitiesCleanupTaskProcessor cleanupTaskProcessor;
@MockitoBean
private TbAiClient tbAiClient;
private TbAiOperations tbAiOperations;
@MockitoBean
private TbAiTokenProvider tbAiTokenProvider;
@Autowired
@ -187,8 +191,7 @@ public class HousekeeperServiceTest extends AbstractControllerTest {
loginTenantAdmin();
this.tenantId = super.tenantId;
doReturn(true).when(tbAiTokenProvider).isTokenAvailable();
doReturn(TbAiResponse.builder().success(true).build()).when(tbAiClient).deleteUserData(any());
doReturn(TbAiResponse.builder().success(true).build()).when(tbAiClient).deleteTenantData(any());
doReturn(TbAiResponse.builder().success(true).build()).when(tbAiOperations).execute(any(TbAiOperation.class), any(TbAiTurnContext.class));
}
@After
@ -257,12 +260,10 @@ public class HousekeeperServiceTest extends AbstractControllerTest {
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
verifyNoRelatedData(userId);
assertThat(alarmService.findAlarmRefsByAssigneeId(tenantId, userId, 0, null, 5000)).size().isZero();
verify(tbAiClient).deleteUserData(any());
verify(tbAiOperations).execute(argThat(operation -> ChannelProtocol.USER_DATA_DELETE.equals(operation.type())), any());
});
ArgumentCaptor<TbAiClient.TokenProvider> captor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).deleteUserData(captor.capture());
assertIdScopedToken(captor.getValue(), userId);
assertIdScopedToken(deletionContext(ChannelProtocol.USER_DATA_DELETE).tokenProvider(), userId);
}
@Test
@ -516,17 +517,12 @@ public class HousekeeperServiceTest extends AbstractControllerTest {
verifyNoRelatedData(oAuth2ClientId);
verifyNoRelatedData(appBundleId);
verifyNoRelatedData(tenantId);
verify(tbAiClient).deleteTenantData(any());
verify(tbAiClient).deleteUserData(any());
verify(tbAiOperations).execute(argThat(operation -> ChannelProtocol.TENANT_DATA_DELETE.equals(operation.type())), any());
verify(tbAiOperations).execute(argThat(operation -> ChannelProtocol.USER_DATA_DELETE.equals(operation.type())), any());
});
ArgumentCaptor<TbAiClient.TokenProvider> tenantDataCaptor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).deleteTenantData(tenantDataCaptor.capture());
assertIdScopedToken(tenantDataCaptor.getValue(), new UserId(tenantId.getId()));
ArgumentCaptor<TbAiClient.TokenProvider> userDataCaptor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
verify(tbAiClient).deleteUserData(userDataCaptor.capture());
assertIdScopedToken(userDataCaptor.getValue(), userId);
assertIdScopedToken(deletionContext(ChannelProtocol.TENANT_DATA_DELETE).tokenProvider(), new UserId(tenantId.getId()));
assertIdScopedToken(deletionContext(ChannelProtocol.USER_DATA_DELETE).tokenProvider(), userId);
}
@Test
@ -648,6 +644,12 @@ public class HousekeeperServiceTest extends AbstractControllerTest {
verify(housekeeperService, never()).processTask(argThat(getTaskMatcher(tenantId, HousekeeperTaskType.DELETE_ENTITIES, null)));
}
private TbAiTurnContext deletionContext(String type) {
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
verify(tbAiOperations).execute(argThat(operation -> type.equals(operation.type())), context.capture());
return context.getValue();
}
private void assertIdScopedToken(TbAiClient.TokenProvider tokenProvider, UserId expectedUserId) {
tokenProvider.getToken();
verify(tbAiTokenProvider).getToken(tenantId, expectedUserId);

56
application/src/test/java/org/thingsboard/server/service/housekeeper/processor/AiDataDeletionTaskProcessorsTest.java

@ -8,13 +8,17 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.common.data.housekeeper.HousekeeperTask;
import org.thingsboard.server.common.data.housekeeper.HousekeeperTaskType;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.ai.TbAiTokenProvider;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.Map;
import java.util.Optional;
@ -25,14 +29,17 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
class AiDataDeletionTaskProcessorsTest {
@Mock
TbAiClient tbAiClient;
@Mock
TbAiTokenProvider tokenProvider;
@Mock
TbAiOperations operations;
@Mock
SystemSecurityService systemSecurityService;
TenantId tenantId;
UserId userId;
@ -44,8 +51,11 @@ class AiDataDeletionTaskProcessorsTest {
void setUp() {
tenantId = TenantId.fromUUID(UUID.randomUUID());
userId = new UserId(UUID.randomUUID());
userDataProcessor = new AiUserDataDeletionTaskProcessor(tbAiClient, Optional.of(tokenProvider));
tenantDataProcessor = new AiTenantDataDeletionTaskProcessor(tbAiClient, Optional.of(tokenProvider));
userDataProcessor = new AiUserDataDeletionTaskProcessor(Optional.of(tokenProvider), operations, systemSecurityService);
tenantDataProcessor = new AiTenantDataDeletionTaskProcessor(Optional.of(tokenProvider), operations, systemSecurityService);
lenient().when(systemSecurityService.getBaseUrl(any(TenantId.class), any(), any())).thenReturn("https://tb.example.com");
lenient().when(operations.execute(any(TbAiOperation.class), any(TbAiTurnContext.class)))
.thenReturn(TbAiResponse.builder().success(true).build());
}
@Test
@ -57,7 +67,6 @@ class AiDataDeletionTaskProcessorsTest {
@Test
void shouldCallUserDataDeletionWithIdScopedToken_whenProcessingUserDataTask() throws Exception {
// GIVEN
given(tbAiClient.deleteUserData(any())).willReturn(TbAiResponse.builder().success(true).build());
given(tokenProvider.isTokenAvailable()).willReturn(true);
given(tokenProvider.getToken(tenantId, userId)).willReturn("id-scoped-token");
given(tokenProvider.getAdditionalInfo(tenantId, userId)).willReturn(Map.of("X-User-Id", userId.toString()));
@ -65,17 +74,22 @@ class AiDataDeletionTaskProcessorsTest {
// WHEN
userDataProcessor.process(HousekeeperTask.deleteAiUserData(tenantId, userId));
// THEN — the client is called once with a token provider that resolves identity from the task's raw ids.
ArgumentCaptor<TbAiClient.TokenProvider> captor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
then(tbAiClient).should().deleteUserData(captor.capture());
assertThat(captor.getValue().getToken()).isEqualTo("id-scoped-token");
assertThat(captor.getValue().getAdditionalInfo()).isEqualTo(Map.of("X-User-Id", userId.toString()));
// THEN — one background operation, with a token provider that resolves identity from the task's raw ids.
ArgumentCaptor<TbAiOperation> operation = ArgumentCaptor.forClass(TbAiOperation.class);
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
then(operations).should().execute(operation.capture(), context.capture());
assertThat(context.getValue().tokenProvider().getToken()).isEqualTo("id-scoped-token");
assertThat(context.getValue().tokenProvider().getAdditionalInfo()).isEqualTo(Map.of("X-User-Id", userId.toString()));
assertThat(operation.getValue().type()).isEqualTo(ChannelProtocol.USER_DATA_DELETE);
assertThat(context.getValue().isBackground()).isTrue();
assertThat(context.getValue().tenantId()).isEqualTo(tenantId);
assertThat(context.getValue().userId()).isEqualTo(userId);
assertThat(context.getValue().tbAccessToken()).isNull();
}
@Test
void shouldCallTenantDataDeletionWithIdScopedToken_whenProcessingTenantDataTask() throws Exception {
// GIVEN — for a tenant task the tenant id doubles as the token's user identity.
given(tbAiClient.deleteTenantData(any())).willReturn(TbAiResponse.builder().success(true).build());
given(tokenProvider.isTokenAvailable()).willReturn(true);
given(tokenProvider.getToken(tenantId, new UserId(tenantId.getId()))).willReturn("id-scoped-token");
@ -83,16 +97,18 @@ class AiDataDeletionTaskProcessorsTest {
tenantDataProcessor.process(HousekeeperTask.deleteAiTenantData(tenantId));
// THEN
ArgumentCaptor<TbAiClient.TokenProvider> captor = ArgumentCaptor.forClass(TbAiClient.TokenProvider.class);
then(tbAiClient).should().deleteTenantData(captor.capture());
assertThat(captor.getValue().getToken()).isEqualTo("id-scoped-token");
ArgumentCaptor<TbAiOperation> operation = ArgumentCaptor.forClass(TbAiOperation.class);
ArgumentCaptor<TbAiTurnContext> context = ArgumentCaptor.forClass(TbAiTurnContext.class);
then(operations).should().execute(operation.capture(), context.capture());
assertThat(operation.getValue().type()).isEqualTo(ChannelProtocol.TENANT_DATA_DELETE);
assertThat(context.getValue().tokenProvider().getToken()).isEqualTo("id-scoped-token");
}
@Test
void shouldThrow_whenAiServiceReportsFailure() {
// GIVEN
given(tokenProvider.isTokenAvailable()).willReturn(true);
given(tbAiClient.deleteUserData(any()))
given(operations.execute(any(TbAiOperation.class), any(TbAiTurnContext.class)))
.willReturn(TbAiResponse.builder().success(false).error("Service unavailable").build());
// WHEN
@ -112,14 +128,14 @@ class AiDataDeletionTaskProcessorsTest {
tenantDataProcessor.process(HousekeeperTask.deleteAiTenantData(tenantId));
// THEN
then(tbAiClient).shouldHaveNoInteractions();
then(operations).shouldHaveNoInteractions();
}
@Test
void shouldThrowWithoutCallingAiService_whenNoTokenProviderIsConfigured() {
// GIVEN
userDataProcessor = new AiUserDataDeletionTaskProcessor(tbAiClient, Optional.empty());
tenantDataProcessor = new AiTenantDataDeletionTaskProcessor(tbAiClient, Optional.empty());
userDataProcessor = new AiUserDataDeletionTaskProcessor(Optional.empty(), operations, systemSecurityService);
tenantDataProcessor = new AiTenantDataDeletionTaskProcessor(Optional.empty(), operations, systemSecurityService);
// WHEN
Throwable userTaskThrown = catchThrowable(() -> userDataProcessor.process(HousekeeperTask.deleteAiUserData(tenantId, userId)));
@ -128,7 +144,7 @@ class AiDataDeletionTaskProcessorsTest {
// THEN — a missing provider is a misconfiguration, not a no-op: fail so Housekeeper reprocessing kicks in.
assertThat(userTaskThrown).isInstanceOf(IllegalStateException.class).hasMessage("AI token provider is not configured");
assertThat(tenantTaskThrown).isInstanceOf(IllegalStateException.class).hasMessage("AI token provider is not configured");
then(tbAiClient).shouldHaveNoInteractions();
then(operations).shouldHaveNoInteractions();
}
}

3
application/src/test/resources/application-test.properties

@ -72,3 +72,6 @@ queue.edqs.sync.enabled=false
queue.edqs.api.supported=false
trendz.enabled=false
# Tests never reach a real AI service: the channel handshake is refused at once
ai.base_url=http://127.0.0.1:1

2
pom.xml

@ -63,7 +63,7 @@
<pkg.unixLogFolder>/var/log/${pkg.name}</pkg.unixLogFolder>
<pkg.installFolder>/usr/share/${pkg.name}</pkg.installFolder>
<pkg.controlScriptsFolder>control</pkg.controlScriptsFolder>
<thingsboard.ai.version>2.1.6</thingsboard.ai.version>
<thingsboard.ai.version>2.1.9-SNAPSHOT</thingsboard.ai.version>
<thingsboard.client.version>4.4.0</thingsboard.client.version>
<spring-boot.version>3.5.15</spring-boot.version>
<!-- Pins spring-boot-test to 3.5.13: the ImportsContextCustomizer change in 3.5.14 causes "Duplicate spy

Loading…
Cancel
Save