Browse Source
Phase 4 of the TB AI WebSocket channel. Operations run over the channel when TB AI advertises operations.v1 and fall back to the legacy HTTP calls otherwise. TbAiChannelAvailability shares the fallback back-off between chat and operations; TbAiClientRequestFactory resolves the client origin for all AI controllers.pull/16336/head
23 changed files with 785 additions and 69 deletions
@ -0,0 +1,199 @@ |
|||
// 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 io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException; |
|||
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.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.OperationResult; |
|||
import org.thingsboard.ai.common.channel.TbAiChannelClient; |
|||
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.time.Duration; |
|||
import java.util.List; |
|||
import java.util.concurrent.CompletableFuture; |
|||
import java.util.concurrent.ExecutionException; |
|||
import java.util.concurrent.TimeUnit; |
|||
import java.util.concurrent.TimeoutException; |
|||
import java.util.concurrent.atomic.AtomicBoolean; |
|||
|
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
class ChannelTbAiOperations { |
|||
|
|||
static final Duration OPERATION_TIMEOUT = Duration.ofMinutes(30); |
|||
|
|||
private final TbAiChannelClient channelClient; |
|||
private final TbAiRequestExecutor requestExecutor; |
|||
|
|||
TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) { |
|||
var call = new OperationCall(operation, context); |
|||
channelClient.connect(context.tokenProvider(), call).subscribe(call::opened, call::connectFailed); |
|||
try { |
|||
return call.result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); |
|||
} catch (InterruptedException e) { |
|||
Thread.currentThread().interrupt(); |
|||
call.abandon(); |
|||
return failure("Request interrupted"); |
|||
} catch (TimeoutException e) { |
|||
call.abandon(); |
|||
return failure("Request timed out"); |
|||
} catch (ExecutionException e) { |
|||
if (e.getCause() instanceof RuntimeException runtime |
|||
&& (runtime instanceof TbAiChannelUnavailableException || runtime instanceof TbAiOperationsUnsupportedException)) { |
|||
throw runtime; |
|||
} |
|||
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e)); |
|||
return failure("Service unavailable"); |
|||
} |
|||
} |
|||
|
|||
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 Integer handshakeStatus(Throwable error) { |
|||
for (Throwable cause : ExceptionUtils.getThrowableList(error)) { |
|||
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) { |
|||
return handshake.response().status().code(); |
|||
} |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
private final class OperationCall implements ChannelFrameListener { |
|||
|
|||
private final TbAiOperation operation; |
|||
private final TbAiTurnContext context; |
|||
private final ChannelFrameCodec codec = channelClient.codec(); |
|||
private final CompletableFuture<TbAiResponse> result = new CompletableFuture<>(); |
|||
private final AtomicBoolean sent = new AtomicBoolean(); |
|||
private volatile ChannelSession session; |
|||
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; |
|||
|
|||
private OperationCall(TbAiOperation operation, TbAiTurnContext context) { |
|||
this.operation = operation; |
|||
this.context = context; |
|||
} |
|||
|
|||
void opened(ChannelSession openedSession) { |
|||
session = openedSession; |
|||
if (result.isDone()) { |
|||
openedSession.close(ChannelProtocol.CLOSE_NORMAL, "Operation abandoned"); |
|||
return; |
|||
} |
|||
openedSession.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, |
|||
List.of(ChannelProtocol.CAPABILITY_REST, ChannelProtocol.CAPABILITY_OPERATIONS), |
|||
context.clientRequest().clientOrigin(), null)))); |
|||
} |
|||
|
|||
void connectFailed(Throwable error) { |
|||
Integer status = handshakeStatus(error); |
|||
if (status != null && (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value())) { |
|||
result.complete(failure(HttpStatus.valueOf(status).getReasonPhrase())); |
|||
return; |
|||
} |
|||
result.completeExceptionally(new TbAiChannelUnavailableException( |
|||
"Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(error), error)); |
|||
} |
|||
|
|||
void abandon() { |
|||
ChannelSession current = session; |
|||
if (current != null && current.isOpen()) { |
|||
current.close(ChannelProtocol.CLOSE_NORMAL, "Operation abandoned"); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void onFrame(ChannelSession frameSession, ChannelFrame frame) { |
|||
try { |
|||
switch (frame.type()) { |
|||
case ChannelProtocol.HELLO -> onHello(frameSession, frame); |
|||
case ChannelProtocol.TB_REQUEST -> requestExecutor.serve(frameSession, frame, codec, context, maxFrameBytes); |
|||
case ChannelProtocol.ERROR -> onError(frameSession, frame); |
|||
default -> log.debug("Ignoring AI channel frame '{}' during operation '{}'", frame.type(), operation.type()); |
|||
} |
|||
} catch (ChannelException e) { |
|||
log.warn("Malformed AI channel frame '{}': {}", frame.type(), e.getMessage()); |
|||
frameSession.close(ChannelProtocol.CLOSE_PROTOCOL_ERROR, e.getMessage()); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void onClose(ChannelSession closedSession, int code, String reason) { |
|||
if (!sent.get()) { |
|||
result.completeExceptionally(new TbAiChannelUnavailableException( |
|||
"AI channel closed before the operation started [" + code + "] " + reason, null)); |
|||
} |
|||
} |
|||
|
|||
private void onHello(ChannelSession helloSession, ChannelFrame frame) { |
|||
ChannelHello hello = codec.fromPayload(frame.payload(), ChannelHello.class); |
|||
if (hello.capabilities() == null || !hello.capabilities().contains(ChannelProtocol.CAPABILITY_OPERATIONS)) { |
|||
result.completeExceptionally(new TbAiOperationsUnsupportedException("TB AI does not support channel operations")); |
|||
helloSession.close(ChannelProtocol.CLOSE_NORMAL, "Operations not supported"); |
|||
return; |
|||
} |
|||
if (hello.maxFrameBytes() != null && hello.maxFrameBytes() > 0 && hello.maxFrameBytes() < Integer.MAX_VALUE) { |
|||
maxFrameBytes = hello.maxFrameBytes().intValue(); |
|||
} |
|||
sent.set(true); |
|||
helloSession.request(ChannelFrame.request(operation.type(), codec.toPayload(operation.payload())), OPERATION_TIMEOUT) |
|||
.whenComplete((reply, error) -> { |
|||
if (error != null) { |
|||
result.completeExceptionally(error); |
|||
} else if (ChannelProtocol.OPERATION_RESULT.equals(reply.type())) { |
|||
result.complete(toResponse(codec.fromPayload(reply.payload(), OperationResult.class))); |
|||
} else { |
|||
result.completeExceptionally(new ChannelException("Unexpected reply '" + reply.type() + "'")); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
private void onError(ChannelSession errorSession, ChannelFrame frame) { |
|||
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class); |
|||
log.warn("AI channel error during operation '{}' {}: {}", operation.type(), error.code(), error.message()); |
|||
if (!sent.get()) { |
|||
result.completeExceptionally(new TbAiChannelUnavailableException("AI channel refused: " + error.message(), null)); |
|||
} else { |
|||
result.completeExceptionally(new ChannelException(error.message())); |
|||
} |
|||
errorSession.close(ChannelProtocol.CLOSE_NORMAL, "Error received"); |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,47 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.beans.factory.annotation.Value; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.time.Clock; |
|||
import java.time.Duration; |
|||
|
|||
@Component |
|||
@TbCoreComponent |
|||
public class TbAiChannelAvailability { |
|||
|
|||
private final boolean enabled; |
|||
private final Duration fallbackBackoff; |
|||
private final Clock clock; |
|||
|
|||
private volatile long unavailableUntil; |
|||
|
|||
@Autowired |
|||
TbAiChannelAvailability(@Value("${TB_AI_CHANNEL_ENABLED:true}") boolean enabled, |
|||
@Value("${TB_AI_CHANNEL_FALLBACK_BACKOFF_MINUTES:10}") long fallbackBackoffMinutes) { |
|||
this(enabled, Duration.ofMinutes(fallbackBackoffMinutes), Clock.systemUTC()); |
|||
} |
|||
|
|||
TbAiChannelAvailability(boolean enabled, Duration fallbackBackoff, Clock clock) { |
|||
this.enabled = enabled; |
|||
this.fallbackBackoff = fallbackBackoff; |
|||
this.clock = clock; |
|||
} |
|||
|
|||
public boolean isUsable() { |
|||
return enabled && clock.millis() >= unavailableUntil; |
|||
} |
|||
|
|||
public void markUnavailable() { |
|||
unavailableUntil = clock.millis() + fallbackBackoff.toMillis(); |
|||
} |
|||
|
|||
public Duration fallbackBackoff() { |
|||
return fallbackBackoff; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
import jakarta.servlet.http.HttpServletRequest; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.security.system.SystemSecurityService; |
|||
|
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class TbAiClientRequestFactory { |
|||
|
|||
private final SystemSecurityService systemSecurityService; |
|||
|
|||
public TbAiClientRequest create(SecurityUser user, HttpServletRequest request) { |
|||
String clientOrigin = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request); |
|||
return TbAiClientRequest.of(clientOrigin, request); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
// 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 java.util.function.Supplier; |
|||
|
|||
public record TbAiOperation(String type, Object payload, Supplier<TbAiClient.TbAiResponse> httpCall) {} |
|||
@ -0,0 +1,37 @@ |
|||
// 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.TbAiResponse; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class TbAiOperations { |
|||
|
|||
private final ChannelTbAiOperations channelOperations; |
|||
private final TbAiChannelAvailability availability; |
|||
|
|||
public TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) { |
|||
if (!availability.isUsable()) { |
|||
return operation.httpCall().get(); |
|||
} |
|||
try { |
|||
return channelOperations.execute(operation, context); |
|||
} catch (TbAiChannelUnavailableException e) { |
|||
log.warn("AI channel unavailable, using HTTP for '{}' and backing off for {}: {}", |
|||
operation.type(), availability.fallbackBackoff(), e.getMessage()); |
|||
availability.markUnavailable(); |
|||
return operation.httpCall().get(); |
|||
} catch (TbAiOperationsUnsupportedException e) { |
|||
log.debug("TB AI has no channel operations, using HTTP for '{}'", operation.type()); |
|||
return operation.httpCall().get(); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
public class TbAiOperationsUnsupportedException extends RuntimeException { |
|||
|
|||
public TbAiOperationsUnsupportedException(String message) { |
|||
super(message); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,196 @@ |
|||
// 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.AfterEach; |
|||
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.OperationResult; |
|||
import org.thingsboard.ai.common.channel.SolutionOperationRequest; |
|||
import org.thingsboard.ai.common.channel.TbAiChannelClient; |
|||
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 reactor.core.publisher.Sinks; |
|||
import reactor.netty.DisposableServer; |
|||
import reactor.netty.http.server.HttpServer; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.CopyOnWriteArrayList; |
|||
import java.util.function.Function; |
|||
|
|||
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.ArgumentMatchers.same; |
|||
import static org.mockito.Mockito.doAnswer; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
class ChannelTbAiOperationsTest { |
|||
|
|||
UUID solutionId = UUID.randomUUID(); |
|||
ChannelFrameCodec codec = new ChannelFrameCodec(new ObjectMapper()); |
|||
List<ChannelFrame> receivedByAi = new CopyOnWriteArrayList<>(); |
|||
TbAiRequestExecutor requestExecutor = mock(TbAiRequestExecutor.class); |
|||
TbAiTurnContext context = new TbAiTurnContext(mock(SecurityUser.class), "Bearer user-jwt", null, () -> "ai-token", |
|||
new TbAiClientRequest("https://tb.example.com", Map.of())); |
|||
TbAiOperation operation = new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId), |
|||
() -> { throw new AssertionError("HTTP must not be used"); }); |
|||
DisposableServer aiServer; |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
if (aiServer != null) { |
|||
aiServer.disposeNow(); |
|||
} |
|||
} |
|||
|
|||
@Test |
|||
void shouldRunOperationAndServeThingsBoardRequests_whenServerSupportsOperations() { |
|||
// GIVEN
|
|||
startScriptedAi(List.of(ChannelProtocol.CAPABILITY_REST, ChannelProtocol.CAPABILITY_OPERATIONS), |
|||
request -> new OperationResult(200, JacksonUtil.newObjectNode().put("mainDashboardId", "d1"), 3)); |
|||
doAnswer(invocation -> { |
|||
ChannelSession session = invocation.getArgument(0); |
|||
ChannelFrame frame = invocation.getArgument(1); |
|||
session.send(ChannelFrame.reply(ChannelProtocol.TB_RESPONSE, frame, |
|||
codec.toPayload(new TbHttpResponse(200, Map.of(), "{}", "utf8")))); |
|||
return null; |
|||
}).when(requestExecutor).serve(any(), any(), any(), same(context), anyInt()); |
|||
|
|||
// WHEN
|
|||
TbAiResponse response = operations().execute(operation, context); |
|||
|
|||
// THEN
|
|||
assertThat(response.isSuccess()).isTrue(); |
|||
assertThat(response.getValue()).isEqualTo(JacksonUtil.newObjectNode().put("mainDashboardId", "d1")); |
|||
assertThat(response.getCreditsUsed()).isEqualTo(3); |
|||
ChannelHello hello = codec.fromPayload(frame(ChannelProtocol.HELLO).payload(), ChannelHello.class); |
|||
assertThat(hello.capabilities()).containsExactly(ChannelProtocol.CAPABILITY_REST, ChannelProtocol.CAPABILITY_OPERATIONS); |
|||
assertThat(hello.clientOrigin()).isEqualTo("https://tb.example.com"); |
|||
assertThat(codec.fromPayload(frame(ChannelProtocol.SOLUTION_INSTALL).payload(), SolutionOperationRequest.class)) |
|||
.isEqualTo(new SolutionOperationRequest(solutionId)); |
|||
assertThat(frame(ChannelProtocol.TB_RESPONSE)).isNotNull(); |
|||
} |
|||
|
|||
@Test |
|||
void shouldReturnErrorMessageFromBody_whenOperationFails() { |
|||
// GIVEN
|
|||
startScriptedAi(List.of(ChannelProtocol.CAPABILITY_REST, ChannelProtocol.CAPABILITY_OPERATIONS), |
|||
request -> new OperationResult(404, JacksonUtil.newObjectNode().put("message", "Solution not found"), 0)); |
|||
|
|||
// WHEN
|
|||
TbAiResponse response = operations().execute(operation, context); |
|||
|
|||
// THEN
|
|||
assertThat(response.isSuccess()).isFalse(); |
|||
assertThat(response.getError()).isEqualTo("Solution not found"); |
|||
} |
|||
|
|||
@Test |
|||
void shouldSignalOperationsUnsupported_whenServerLacksCapability() { |
|||
// GIVEN
|
|||
startScriptedAi(List.of(ChannelProtocol.CAPABILITY_REST), request -> { |
|||
throw new AssertionError("Operation must not be sent"); |
|||
}); |
|||
|
|||
// WHEN-THEN
|
|||
assertThatThrownBy(() -> operations().execute(operation, context)) |
|||
.isInstanceOf(TbAiOperationsUnsupportedException.class); |
|||
assertThat(receivedByAi).extracting(ChannelFrame::type).doesNotContain(ChannelProtocol.SOLUTION_INSTALL); |
|||
verify(requestExecutor, never()).serve(any(), any(), any(), any(), anyInt()); |
|||
} |
|||
|
|||
@Test |
|||
void shouldSignalChannelUnavailable_whenServerHasNoChannelEndpoint() { |
|||
// GIVEN
|
|||
aiServer = HttpServer.create().host("127.0.0.1").port(0) |
|||
.route(routes -> routes.get(ChannelProtocol.WS_PATH, (req, res) -> res.status(404).send())) |
|||
.bindNow(); |
|||
|
|||
// WHEN-THEN
|
|||
assertThatThrownBy(() -> operations().execute(operation, context)) |
|||
.isInstanceOf(TbAiChannelUnavailableException.class); |
|||
} |
|||
|
|||
@Test |
|||
void shouldReturnUnauthorized_whenServerRejectsToken() { |
|||
// GIVEN
|
|||
aiServer = HttpServer.create().host("127.0.0.1").port(0) |
|||
.route(routes -> routes.get(ChannelProtocol.WS_PATH, (req, res) -> res.status(401).send())) |
|||
.bindNow(); |
|||
|
|||
// WHEN
|
|||
TbAiResponse response = operations().execute(operation, context); |
|||
|
|||
// THEN
|
|||
assertThat(response.isSuccess()).isFalse(); |
|||
assertThat(response.getError()).isEqualTo("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() { |
|||
return new ChannelTbAiOperations(new TbAiChannelClient("http://127.0.0.1:" + aiServer.port()), requestExecutor); |
|||
} |
|||
|
|||
ChannelFrame frame(String type) { |
|||
return receivedByAi.stream().filter(frame -> type.equals(frame.type())).findFirst().orElseThrow(); |
|||
} |
|||
|
|||
void startScriptedAi(List<String> capabilities, Function<ChannelFrame, OperationResult> operationHandler) { |
|||
aiServer = HttpServer.create().host("127.0.0.1").port(0) |
|||
.route(routes -> routes.ws(ChannelProtocol.WS_PATH, (inbound, outbound) -> { |
|||
Sinks.Many<String> out = Sinks.many().unicast().onBackpressureBuffer(); |
|||
ChannelFrame[] pendingOperation = new ChannelFrame[1]; |
|||
inbound.receive().asString().subscribe(text -> { |
|||
ChannelFrame frame = codec.decode(text); |
|||
receivedByAi.add(frame); |
|||
switch (frame.type()) { |
|||
case ChannelProtocol.HELLO -> out.tryEmitNext(codec.encode(ChannelFrame.of(ChannelProtocol.HELLO, |
|||
codec.toPayload(new ChannelHello(1, capabilities, null, 10_485_760L))))); |
|||
case ChannelProtocol.SOLUTION_INSTALL -> { |
|||
OperationResult result = operationHandler.apply(frame); |
|||
if (result.status() == 200) { |
|||
pendingOperation[0] = frame; |
|||
out.tryEmitNext(codec.encode(new ChannelFrame(ChannelProtocol.TB_REQUEST, "r1", null, codec.toPayload( |
|||
new TbHttpRequest("POST", "/api/dashboard", null, Map.of(), "{}", "utf8", 5000L))))); |
|||
} else { |
|||
reply(out, frame, result); |
|||
} |
|||
} |
|||
case ChannelProtocol.TB_RESPONSE -> reply(out, pendingOperation[0], operationHandler.apply(pendingOperation[0])); |
|||
default -> {} |
|||
} |
|||
}); |
|||
return outbound.sendString(out.asFlux()).then().then(outbound.sendClose(1000, "Operation completed")); |
|||
})) |
|||
.bindNow(); |
|||
} |
|||
|
|||
void reply(Sinks.Many<String> out, ChannelFrame request, OperationResult result) { |
|||
out.tryEmitNext(codec.encode(ChannelFrame.reply(ChannelProtocol.OPERATION_RESULT, request, codec.toPayload(result)))); |
|||
out.tryEmitComplete(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,38 @@ |
|||
// 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 java.time.Clock; |
|||
import java.time.Duration; |
|||
import java.time.Instant; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
|
|||
class TbAiChannelAvailabilityTest { |
|||
|
|||
@Test |
|||
void shouldBeUnusable_whenDisabled() { |
|||
assertThat(new TbAiChannelAvailability(false, Duration.ofMinutes(10), Clock.systemUTC()).isUsable()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void shouldBackOffAndRecover_whenMarkedUnavailable() { |
|||
// GIVEN
|
|||
var clock = new TbAiTransportSelectorTest.MutableClock(Instant.parse("2026-10-01T10:00:00Z")); |
|||
var availability = new TbAiChannelAvailability(true, Duration.ofMinutes(10), clock); |
|||
assertThat(availability.isUsable()).isTrue(); |
|||
|
|||
// WHEN
|
|||
availability.markUnavailable(); |
|||
|
|||
// THEN
|
|||
assertThat(availability.isUsable()).isFalse(); |
|||
clock.advance(Duration.ofMinutes(9)); |
|||
assertThat(availability.isUsable()).isFalse(); |
|||
clock.advance(Duration.ofMinutes(2)); |
|||
assertThat(availability.isUsable()).isTrue(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
// 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.thingsboard.ai.common.channel.ChannelProtocol; |
|||
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.Map; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.BDDMockito.given; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
class TbAiOperationsTest { |
|||
|
|||
TbAiTurnContext context = new TbAiTurnContext(mock(SecurityUser.class), "Bearer jwt", null, () -> "token", |
|||
new TbAiClientRequest("https://tb.example.com", Map.of())); |
|||
TbAiResponse httpResponse = TbAiResponse.builder().success(true).build(); |
|||
TbAiResponse channelResponse = TbAiResponse.builder().success(true).build(); |
|||
TbAiOperation operation = new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, null, () -> httpResponse); |
|||
ChannelTbAiOperations channel = mock(ChannelTbAiOperations.class); |
|||
TbAiChannelAvailability availability = mock(TbAiChannelAvailability.class); |
|||
TbAiOperations operations = new TbAiOperations(channel, availability); |
|||
|
|||
@Test |
|||
void shouldUseChannel_whenUsable() { |
|||
// GIVEN
|
|||
given(availability.isUsable()).willReturn(true); |
|||
given(channel.execute(operation, context)).willReturn(channelResponse); |
|||
|
|||
// WHEN-THEN
|
|||
assertThat(operations.execute(operation, context)).isSameAs(channelResponse); |
|||
verify(availability, never()).markUnavailable(); |
|||
} |
|||
|
|||
@Test |
|||
void shouldUseHttp_whenChannelIsNotUsable() { |
|||
// GIVEN
|
|||
given(availability.isUsable()).willReturn(false); |
|||
|
|||
// WHEN-THEN
|
|||
assertThat(operations.execute(operation, context)).isSameAs(httpResponse); |
|||
verify(channel, never()).execute(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void shouldFallBackToHttpAndBackOff_whenChannelIsUnavailable() { |
|||
// GIVEN
|
|||
given(availability.isUsable()).willReturn(true); |
|||
given(channel.execute(operation, context)).willThrow(new TbAiChannelUnavailableException("404", null)); |
|||
|
|||
// WHEN-THEN
|
|||
assertThat(operations.execute(operation, context)).isSameAs(httpResponse); |
|||
verify(availability).markUnavailable(); |
|||
} |
|||
|
|||
@Test |
|||
void shouldFallBackToHttpWithoutBackOff_whenOperationsAreUnsupported() { |
|||
// GIVEN
|
|||
given(availability.isUsable()).willReturn(true); |
|||
given(channel.execute(operation, context)).willThrow(new TbAiOperationsUnsupportedException("old TB AI")); |
|||
|
|||
// WHEN-THEN
|
|||
assertThat(operations.execute(operation, context)).isSameAs(httpResponse); |
|||
verify(availability, never()).markUnavailable(); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue