Browse Source
Phase 2 of the AI WebSocket channel: ChannelTbAiTransport over TbAiChannelClient, TbAiRequestExecutor running tb.request frames on loopback as the user, TbAiTransportSelector with SSE fallback and back-off (TB_AI_CHANNEL_ENABLED, TB_AI_CHANNEL_FALLBACK_BACKOFF_MINUTES), approvals over the channel via TbAiChannelRegistry, clientOrigin from SystemSecurityService. Uses thingsboard-ai common 2.1.8-SNAPSHOT.pull/16336/head
20 changed files with 1192 additions and 11 deletions
@ -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 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.HttpHeaders; |
|||
import org.springframework.http.HttpStatus; |
|||
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.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.ChatEventPayload; |
|||
import org.thingsboard.ai.common.channel.ChatTurnRequest; |
|||
import org.thingsboard.ai.common.channel.TbAiChannelClient; |
|||
import org.thingsboard.ai.common.client.TbAiClient; |
|||
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.HashMap; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.atomic.AtomicBoolean; |
|||
|
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
class ChannelTbAiTransport implements TbAiTransport { |
|||
|
|||
private static final String HEARTBEAT = "heartbeat"; |
|||
private static final String TOOL_EXECUTION_REQUESTED = "toolExecutionRequested"; |
|||
private static final String TOOL_EXECUTION_RESULT = "toolExecutionResult"; |
|||
|
|||
private final TbAiChannelClient channelClient; |
|||
private final TbAiRequestExecutor requestExecutor; |
|||
private final TbAiChannelRegistry registry; |
|||
|
|||
@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); |
|||
channelClient.connect(withAcceptLanguage(context), turn).subscribe(turn::opened, turn::connectFailed); |
|||
}); |
|||
} |
|||
|
|||
private static TbAiClient.TokenProvider withAcceptLanguage(TbAiTurnContext context) { |
|||
TbAiClient.TokenProvider delegate = context.tokenProvider(); |
|||
return new TbAiClient.TokenProvider() { |
|||
@Override |
|||
public String getToken() { |
|||
return delegate.getToken(); |
|||
} |
|||
|
|||
@Override |
|||
public Map<String, String> getAdditionalInfo() { |
|||
var headers = new HashMap<>(delegate.getAdditionalInfo()); |
|||
if (context.acceptLanguage() != null && !context.acceptLanguage().isBlank()) { |
|||
headers.put(HttpHeaders.ACCEPT_LANGUAGE, context.acceptLanguage()); |
|||
} |
|||
return headers; |
|||
} |
|||
}; |
|||
} |
|||
|
|||
private static ServerSentEvent<String> errorEvent(String message) { |
|||
return ServerSentEvent.<String>builder() |
|||
.event("error") |
|||
.data(JacksonUtil.toString(JacksonUtil.newObjectNode().put("message", message))) |
|||
.build(); |
|||
} |
|||
|
|||
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 ChannelTurn implements ChannelFrameListener { |
|||
|
|||
private final UUID chatId; |
|||
private final JsonNode request; |
|||
private final TbAiTurnContext context; |
|||
private final FluxSink<ServerSentEvent<String>> sink; |
|||
private final ChannelFrameCodec codec = channelClient.codec(); |
|||
private final AtomicBoolean finished = new AtomicBoolean(); |
|||
private volatile ChannelSession session; |
|||
private volatile boolean started; |
|||
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; |
|||
|
|||
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 opened(ChannelSession openedSession) { |
|||
session = openedSession; |
|||
if (sink.isCancelled()) { |
|||
openedSession.close(ChannelProtocol.CLOSE_NORMAL, "Turn abandoned"); |
|||
return; |
|||
} |
|||
openedSession.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(new ChannelHello( |
|||
ChannelProtocol.VERSION, List.of(ChannelProtocol.CAPABILITY_REST), context.clientRequest().clientOrigin(), null)))); |
|||
} |
|||
|
|||
void connectFailed(Throwable error) { |
|||
Integer status = handshakeStatus(error); |
|||
if (status != null && (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value())) { |
|||
finish(errorEvent(HttpStatus.valueOf(status).getReasonPhrase())); |
|||
return; |
|||
} |
|||
sink.error(new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(error), error)); |
|||
} |
|||
|
|||
void abandon() { |
|||
ChannelSession current = session; |
|||
if (current != null && current.isOpen() && !finished.get()) { |
|||
current.close(ChannelProtocol.CLOSE_NORMAL, "Turn abandoned"); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void onFrame(ChannelSession frameSession, ChannelFrame frame) { |
|||
try { |
|||
switch (frame.type()) { |
|||
case ChannelProtocol.HELLO -> onHello(frameSession, frame); |
|||
case ChannelProtocol.CHAT_EVENT -> onChatEvent(frameSession, frame); |
|||
case ChannelProtocol.TB_REQUEST -> requestExecutor.execute(frame, codec, context, maxFrameBytes) |
|||
.subscribe(reply -> sendQuietly(frameSession, reply)); |
|||
case ChannelProtocol.TURN_END -> finish(null); |
|||
case ChannelProtocol.ERROR -> onError(frameSession, 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()); |
|||
frameSession.close(ChannelProtocol.CLOSE_PROTOCOL_ERROR, e.getMessage()); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public void onClose(ChannelSession closedSession, int code, String reason) { |
|||
registry.unregisterSession(closedSession); |
|||
if (finished.get()) { |
|||
return; |
|||
} |
|||
if (!started) { |
|||
sink.error(new TbAiChannelUnavailableException("AI channel closed before the turn started [" + code + "] " + reason, null)); |
|||
} else if (code == ChannelProtocol.CLOSE_NORMAL) { |
|||
finish(null); |
|||
} else { |
|||
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason); |
|||
finish(errorEvent("Service unavailable")); |
|||
} |
|||
} |
|||
|
|||
private void onHello(ChannelSession helloSession, ChannelFrame frame) { |
|||
ChannelHello hello = codec.fromPayload(frame.payload(), ChannelHello.class); |
|||
if (hello.maxFrameBytes() != null && hello.maxFrameBytes() > 0 && hello.maxFrameBytes() < Integer.MAX_VALUE) { |
|||
maxFrameBytes = hello.maxFrameBytes().intValue(); |
|||
} |
|||
started = true; |
|||
helloSession.send(ChannelFrame.of(ChannelProtocol.CHAT_SEND, codec.toPayload(new ChatTurnRequest(chatId, request)))); |
|||
} |
|||
|
|||
private void onChatEvent(ChannelSession eventSession, ChannelFrame frame) { |
|||
ChatEventPayload event = codec.fromPayload(frame.payload(), ChatEventPayload.class); |
|||
if (HEARTBEAT.equals(event.name())) { |
|||
sink.next(ServerSentEvent.<String>builder().comment(HEARTBEAT).build()); |
|||
return; |
|||
} |
|||
trackApproval(eventSession, event); |
|||
sink.next(ServerSentEvent.<String>builder() |
|||
.event(event.name()) |
|||
.data(event.data() != null ? event.data().toString() : null) |
|||
.build()); |
|||
} |
|||
|
|||
private void trackApproval(ChannelSession eventSession, ChatEventPayload event) { |
|||
JsonNode executionId = event.data() != null ? event.data().get("executionId") : null; |
|||
if (executionId == null || !executionId.isTextual()) { |
|||
return; |
|||
} |
|||
UUID id = UUID.fromString(executionId.asText()); |
|||
if (TOOL_EXECUTION_REQUESTED.equals(event.name()) && event.data().path("needsApproval").asBoolean()) { |
|||
registry.registerApproval(id, eventSession); |
|||
} else if (TOOL_EXECUTION_RESULT.equals(event.name())) { |
|||
registry.unregisterApproval(id); |
|||
} |
|||
} |
|||
|
|||
private void onError(ChannelSession errorSession, ChannelFrame frame) { |
|||
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class); |
|||
log.warn("[{}] AI channel error {}: {}", chatId, error.code(), error.message()); |
|||
if (!started) { |
|||
finished.set(true); |
|||
sink.error(new TbAiChannelUnavailableException("AI channel refused: " + error.message(), null)); |
|||
} else { |
|||
finish(errorEvent("Internal error")); |
|||
} |
|||
errorSession.close(ChannelProtocol.CLOSE_NORMAL, "Error received"); |
|||
} |
|||
|
|||
private void finish(ServerSentEvent<String> lastEvent) { |
|||
if (finished.compareAndSet(false, true)) { |
|||
if (lastEvent != null) { |
|||
sink.next(lastEvent); |
|||
} |
|||
sink.complete(); |
|||
} |
|||
} |
|||
|
|||
private void sendQuietly(ChannelSession replySession, ChannelFrame reply) { |
|||
try { |
|||
replySession.send(reply); |
|||
} catch (ChannelException e) { |
|||
log.debug("[{}] Dropped '{}' reply: {}", chatId, reply.type(), e.getMessage()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,36 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.ai.common.channel.ChannelSession; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ConcurrentHashMap; |
|||
import java.util.concurrent.ConcurrentMap; |
|||
|
|||
@Component |
|||
@TbCoreComponent |
|||
public class TbAiChannelRegistry { |
|||
|
|||
private final ConcurrentMap<UUID, ChannelSession> pendingApprovals = new ConcurrentHashMap<>(); |
|||
|
|||
public void registerApproval(UUID executionId, ChannelSession session) { |
|||
pendingApprovals.put(executionId, session); |
|||
} |
|||
|
|||
public void unregisterApproval(UUID executionId) { |
|||
pendingApprovals.remove(executionId); |
|||
} |
|||
|
|||
public void unregisterSession(ChannelSession session) { |
|||
pendingApprovals.values().removeIf(registered -> registered == session); |
|||
} |
|||
|
|||
public Optional<ChannelSession> findApprovalSession(UUID executionId) { |
|||
return Optional.ofNullable(pendingApprovals.get(executionId)).filter(ChannelSession::isOpen); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.transport; |
|||
|
|||
import jakarta.servlet.http.HttpServletRequest; |
|||
import org.springframework.http.HttpHeaders; |
|||
|
|||
import java.util.LinkedHashMap; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
|
|||
public record TbAiClientRequest(String clientOrigin, Map<String, String> forwardedHeaders) { |
|||
|
|||
private static final List<String> FORWARDED_HEADERS = List.of( |
|||
HttpHeaders.HOST, "X-Forwarded-Host", "X-Forwarded-Proto", "X-Forwarded-Port", "X-Forwarded-For"); |
|||
|
|||
public static TbAiClientRequest of(String clientOrigin, HttpServletRequest request) { |
|||
var headers = new LinkedHashMap<String, String>(); |
|||
for (String name : FORWARDED_HEADERS) { |
|||
String value = request.getHeader(name); |
|||
if (value != null) { |
|||
headers.put(name, value); |
|||
} |
|||
} |
|||
return new TbAiClientRequest(clientOrigin, Map.copyOf(headers)); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,205 @@ |
|||
// 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.ChannelFrame; |
|||
import org.thingsboard.ai.common.channel.ChannelFrameCodec; |
|||
import org.thingsboard.ai.common.channel.ChannelProtocol; |
|||
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 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 = validate(request); |
|||
if (invalidReason != null) { |
|||
log.warn("[{}][{}] Rejected AI request {} {}: {}", context.user().getTenantId(), context.user().getId(), |
|||
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); |
|||
context.clientRequest().forwardedHeaders().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))); |
|||
} |
|||
|
|||
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; |
|||
} |
|||
|
|||
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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,63 @@ |
|||
// 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.extern.slf4j.Slf4j; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.beans.factory.annotation.Value; |
|||
import org.springframework.context.annotation.Primary; |
|||
import org.springframework.http.codec.ServerSentEvent; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import reactor.core.publisher.Flux; |
|||
|
|||
import java.time.Clock; |
|||
import java.time.Duration; |
|||
import java.util.UUID; |
|||
|
|||
@Slf4j |
|||
@Primary |
|||
@Component |
|||
@TbCoreComponent |
|||
class TbAiTransportSelector implements TbAiTransport { |
|||
|
|||
private final SseTbAiTransport sseTransport; |
|||
private final ChannelTbAiTransport channelTransport; |
|||
private final boolean channelEnabled; |
|||
private final Duration fallbackBackoff; |
|||
private final Clock clock; |
|||
|
|||
private volatile long channelUnavailableUntil; |
|||
|
|||
@Autowired |
|||
TbAiTransportSelector(SseTbAiTransport sseTransport, |
|||
ChannelTbAiTransport channelTransport, |
|||
@Value("${TB_AI_CHANNEL_ENABLED:true}") boolean channelEnabled, |
|||
@Value("${TB_AI_CHANNEL_FALLBACK_BACKOFF_MINUTES:10}") long fallbackBackoffMinutes) { |
|||
this(sseTransport, channelTransport, channelEnabled, Duration.ofMinutes(fallbackBackoffMinutes), Clock.systemUTC()); |
|||
} |
|||
|
|||
TbAiTransportSelector(SseTbAiTransport sseTransport, ChannelTbAiTransport channelTransport, |
|||
boolean channelEnabled, Duration fallbackBackoff, Clock clock) { |
|||
this.sseTransport = sseTransport; |
|||
this.channelTransport = channelTransport; |
|||
this.channelEnabled = channelEnabled; |
|||
this.fallbackBackoff = fallbackBackoff; |
|||
this.clock = clock; |
|||
} |
|||
|
|||
@Override |
|||
public Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context) { |
|||
if (!channelEnabled || clock.millis() < channelUnavailableUntil) { |
|||
return sseTransport.sendChatMessage(chatId, request, context); |
|||
} |
|||
return channelTransport.sendChatMessage(chatId, request, context) |
|||
.onErrorResume(TbAiChannelUnavailableException.class, e -> { |
|||
log.warn("[{}] AI channel unavailable, using SSE for {}: {}", chatId, fallbackBackoff, e.getMessage()); |
|||
channelUnavailableUntil = clock.millis() + fallbackBackoff.toMillis(); |
|||
return sseTransport.sendChatMessage(chatId, request, context); |
|||
}); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,175 @@ |
|||
// 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 com.fasterxml.jackson.databind.ObjectMapper; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.springframework.http.codec.ServerSentEvent; |
|||
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.ChatEventPayload; |
|||
import org.thingsboard.ai.common.channel.ChatTurnRequest; |
|||
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.channel.TurnEnd; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
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.Map; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.CopyOnWriteArrayList; |
|||
|
|||
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.mock; |
|||
import static org.mockito.Mockito.spy; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
class ChannelTbAiTransportTest { |
|||
|
|||
static final UUID EXECUTION_ID = UUID.fromString("33333333-3333-3333-3333-333333333333"); |
|||
|
|||
ChannelFrameCodec codec = new ChannelFrameCodec(new ObjectMapper()); |
|||
List<ChannelFrame> receivedByAi = new CopyOnWriteArrayList<>(); |
|||
TbAiRequestExecutor requestExecutor = mock(TbAiRequestExecutor.class); |
|||
TbAiChannelRegistry registry = spy(new TbAiChannelRegistry()); |
|||
TbAiTurnContext context = new TbAiTurnContext(mock(SecurityUser.class), "Bearer user-jwt", "de-DE", () -> "ai-token", |
|||
new TbAiClientRequest("https://tb.example.com", Map.of())); |
|||
DisposableServer aiServer; |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
if (aiServer != null) { |
|||
aiServer.disposeNow(); |
|||
} |
|||
} |
|||
|
|||
@Test |
|||
void shouldRelayEventsAndServeThingsBoardRequests_whenTurnRuns() { |
|||
// GIVEN
|
|||
startScriptedAi(); |
|||
UUID chatId = UUID.randomUUID(); |
|||
JsonNode request = JacksonUtil.newObjectNode().put("message", "Create a device"); |
|||
given(requestExecutor.execute(any(), any(), same(context), 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, codec.toPayload(response))); |
|||
}); |
|||
|
|||
// WHEN
|
|||
List<ServerSentEvent<String>> events = transport().sendChatMessage(chatId, request, context) |
|||
.collectList() |
|||
.block(Duration.ofSeconds(10)); |
|||
|
|||
// THEN
|
|||
assertThat(events).extracting(ServerSentEvent::event, ServerSentEvent::comment) |
|||
.containsExactly( |
|||
tuple(null, "heartbeat"), |
|||
tuple("assistantMessage", null), |
|||
tuple("toolExecutionRequested", null)); |
|||
assertThat(JacksonUtil.toJsonNode(events.get(1).data())).isEqualTo(JacksonUtil.toJsonNode("{\"message\":\"Working on it\"}")); |
|||
|
|||
ChannelHello hello = codec.fromPayload(frame(ChannelProtocol.HELLO).payload(), ChannelHello.class); |
|||
assertThat(hello).isEqualTo(new ChannelHello(1, List.of("rest.v1"), "https://tb.example.com", null)); |
|||
ChatTurnRequest turn = codec.fromPayload(frame(ChannelProtocol.CHAT_SEND).payload(), ChatTurnRequest.class); |
|||
assertThat(turn.chatId()).isEqualTo(chatId); |
|||
assertThat(turn.request()).isEqualTo(request); |
|||
TbHttpResponse tbResponse = codec.fromPayload(frame(ChannelProtocol.TB_RESPONSE).payload(), TbHttpResponse.class); |
|||
assertThat(tbResponse.body()).isEqualTo("{\"id\":\"d1\"}"); |
|||
verify(registry).registerApproval(any(), any()); |
|||
await().atMost(Duration.ofSeconds(5)).until(() -> registry.findApprovalSession(EXECUTION_ID).isEmpty()); |
|||
} |
|||
|
|||
@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(() -> transport().sendChatMessage(UUID.randomUUID(), JacksonUtil.newObjectNode(), context) |
|||
.collectList() |
|||
.block(Duration.ofSeconds(10))) |
|||
.isInstanceOf(TbAiChannelUnavailableException.class); |
|||
} |
|||
|
|||
@Test |
|||
void shouldEmitErrorEvent_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
|
|||
List<ServerSentEvent<String>> events = transport().sendChatMessage(UUID.randomUUID(), JacksonUtil.newObjectNode(), context) |
|||
.collectList() |
|||
.block(Duration.ofSeconds(10)); |
|||
|
|||
// THEN
|
|||
assertThat(events).hasSize(1); |
|||
assertThat(events.getFirst().event()).isEqualTo("error"); |
|||
assertThat(JacksonUtil.toJsonNode(events.getFirst().data())).isEqualTo(JacksonUtil.toJsonNode("{\"message\":\"Unauthorized\"}")); |
|||
} |
|||
|
|||
ChannelTbAiTransport transport() { |
|||
return new ChannelTbAiTransport(new TbAiChannelClient("http://127.0.0.1:" + aiServer.port()), requestExecutor, registry); |
|||
} |
|||
|
|||
ChannelFrame frame(String type) { |
|||
return receivedByAi.stream().filter(frame -> type.equals(frame.type())).findFirst().orElseThrow(); |
|||
} |
|||
|
|||
void startScriptedAi() { |
|||
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(); |
|||
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, List.of("rest.v1"), null, 10_485_760L))))); |
|||
case ChannelProtocol.CHAT_SEND -> { |
|||
out.tryEmitNext(event("heartbeat", null)); |
|||
out.tryEmitNext(event("assistantMessage", JacksonUtil.newObjectNode().put("message", "Working on it"))); |
|||
out.tryEmitNext(codec.encode(new ChannelFrame(ChannelProtocol.TB_REQUEST, "r1", null, codec.toPayload( |
|||
new TbHttpRequest("POST", "/api/device", null, Map.of(), "{}", "utf8", 5000L))))); |
|||
} |
|||
case ChannelProtocol.TB_RESPONSE -> { |
|||
out.tryEmitNext(event("toolExecutionRequested", JacksonUtil.newObjectNode() |
|||
.put("executionId", EXECUTION_ID.toString()).put("needsApproval", true).put("message", "Save device"))); |
|||
out.tryEmitNext(codec.encode(ChannelFrame.of(ChannelProtocol.TURN_END, |
|||
codec.toPayload(new TurnEnd(TurnEnd.Status.COMPLETED))))); |
|||
out.tryEmitComplete(); |
|||
} |
|||
default -> {} |
|||
} |
|||
}); |
|||
return outbound.sendString(out.asFlux()).then().then(outbound.sendClose(1000, "Turn completed")); |
|||
})) |
|||
.bindNow(); |
|||
} |
|||
|
|||
String event(String name, JsonNode data) { |
|||
return codec.encode(ChannelFrame.of(ChannelProtocol.CHAT_EVENT, codec.toPayload(new ChatEventPayload(name, data)))); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,164 @@ |
|||
// 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.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(mock(SecurityUser.class), "Bearer user-jwt", "en-US", () -> "ai-token", |
|||
new TbAiClientRequest("https://tb.example.com", Map.of("Host", "tb.example.com", "X-Forwarded-Proto", "https"))); |
|||
|
|||
@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("Host")).isEqualTo("tb.example.com"); |
|||
assertThat(headers.get("X-Forwarded-Proto")).isEqualTo("https"); |
|||
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(); |
|||
} |
|||
|
|||
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; |
|||
} |
|||
|
|||
} |
|||
@ -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.JsonNode; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.springframework.http.codec.ServerSentEvent; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import reactor.core.publisher.Flux; |
|||
|
|||
import java.time.Clock; |
|||
import java.time.Duration; |
|||
import java.time.Instant; |
|||
import java.time.ZoneId; |
|||
import java.time.ZoneOffset; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
|
|||
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.times; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
class TbAiTransportSelectorTest { |
|||
|
|||
UUID chatId = UUID.randomUUID(); |
|||
JsonNode request = JacksonUtil.newObjectNode().put("message", "Hi"); |
|||
TbAiTurnContext context = new TbAiTurnContext(mock(SecurityUser.class), "Bearer jwt", null, () -> "token", |
|||
new TbAiClientRequest("https://tb.example.com", Map.of())); |
|||
SseTbAiTransport sse = mock(SseTbAiTransport.class); |
|||
ChannelTbAiTransport channel = mock(ChannelTbAiTransport.class); |
|||
ServerSentEvent<String> sseEvent = ServerSentEvent.<String>builder().event("assistantMessage").data("{\"message\":\"sse\"}").build(); |
|||
ServerSentEvent<String> channelEvent = ServerSentEvent.<String>builder().event("assistantMessage").data("{\"message\":\"channel\"}").build(); |
|||
|
|||
@Test |
|||
void shouldUseChannel_whenEnabledAndAvailable() { |
|||
// GIVEN
|
|||
given(channel.sendChatMessage(chatId, request, context)).willReturn(Flux.just(channelEvent)); |
|||
|
|||
// WHEN
|
|||
List<ServerSentEvent<String>> events = selector(true, Clock.systemUTC()).sendChatMessage(chatId, request, context).collectList().block(); |
|||
|
|||
// THEN
|
|||
assertThat(events).containsExactly(channelEvent); |
|||
verify(sse, never()).sendChatMessage(any(), any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void shouldUseSse_whenChannelIsDisabled() { |
|||
// GIVEN
|
|||
given(sse.sendChatMessage(chatId, request, context)).willReturn(Flux.just(sseEvent)); |
|||
|
|||
// WHEN
|
|||
List<ServerSentEvent<String>> events = selector(false, Clock.systemUTC()).sendChatMessage(chatId, request, context).collectList().block(); |
|||
|
|||
// THEN
|
|||
assertThat(events).containsExactly(sseEvent); |
|||
verify(channel, never()).sendChatMessage(any(), any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void shouldFallBackToSseAndBackOff_whenChannelIsUnavailable() { |
|||
// GIVEN
|
|||
given(channel.sendChatMessage(chatId, request, context)) |
|||
.willReturn(Flux.error(new TbAiChannelUnavailableException("404", null))); |
|||
given(sse.sendChatMessage(chatId, request, context)).willReturn(Flux.just(sseEvent)); |
|||
var selector = selector(true, Clock.fixed(Instant.parse("2026-10-01T10:00:00Z"), ZoneOffset.UTC)); |
|||
|
|||
// WHEN
|
|||
List<ServerSentEvent<String>> first = selector.sendChatMessage(chatId, request, context).collectList().block(); |
|||
List<ServerSentEvent<String>> second = selector.sendChatMessage(chatId, request, context).collectList().block(); |
|||
|
|||
// THEN
|
|||
assertThat(first).containsExactly(sseEvent); |
|||
assertThat(second).containsExactly(sseEvent); |
|||
verify(channel, times(1)).sendChatMessage(chatId, request, context); |
|||
} |
|||
|
|||
@Test |
|||
void shouldRetryChannel_whenBackoffHasPassed() { |
|||
// GIVEN
|
|||
given(channel.sendChatMessage(chatId, request, context)) |
|||
.willReturn(Flux.error(new TbAiChannelUnavailableException("404", null))); |
|||
given(sse.sendChatMessage(chatId, request, context)).willReturn(Flux.just(sseEvent)); |
|||
var clock = new MutableClock(Instant.parse("2026-10-01T10:00:00Z")); |
|||
var selector = selector(true, clock); |
|||
selector.sendChatMessage(chatId, request, context).collectList().block(); |
|||
|
|||
// WHEN
|
|||
clock.advance(Duration.ofMinutes(11)); |
|||
selector.sendChatMessage(chatId, request, context).collectList().block(); |
|||
|
|||
// THEN
|
|||
verify(channel, times(2)).sendChatMessage(chatId, request, context); |
|||
} |
|||
|
|||
TbAiTransportSelector selector(boolean enabled, Clock clock) { |
|||
return new TbAiTransportSelector(sse, channel, enabled, Duration.ofMinutes(10), clock); |
|||
} |
|||
|
|||
static class MutableClock extends Clock { |
|||
|
|||
private Instant now; |
|||
|
|||
MutableClock(Instant now) { |
|||
this.now = now; |
|||
} |
|||
|
|||
void advance(Duration duration) { |
|||
now = now.plus(duration); |
|||
} |
|||
|
|||
@Override |
|||
public ZoneOffset getZone() { |
|||
return ZoneOffset.UTC; |
|||
} |
|||
|
|||
@Override |
|||
public Clock withZone(ZoneId zone) { |
|||
return this; |
|||
} |
|||
|
|||
@Override |
|||
public Instant instant() { |
|||
return now; |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue