Browse Source
Made AI features work on instances behind NAT or a firewall, with no public base URL requiredpull/16347/head
committed by
GitHub
58 changed files with 3523 additions and 679 deletions
@ -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()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -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()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
|
|||
} |
|||
@ -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; |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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,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) {} |
|||
@ -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()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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 -> {} |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue