1172 changed files with 139892 additions and 54878 deletions
@ -0,0 +1,2 @@ |
|||||
|
# Shipped as committed: its SBOM records the SHA-256 of these exact bytes |
||||
|
application/src/main/data/resources/js_extensions/gateway-management-extension.js -text |
||||
@ -0,0 +1,14 @@ |
|||||
|
# Maintainers |
||||
|
|
||||
|
This file lists the maintainers of the ThingsBoard project. |
||||
|
Maintainers review and merge pull requests, triage issues, and drive project releases. |
||||
|
|
||||
|
| Name | GitHub | Email | |
||||
|
|---------------------|--------------------------------------------------------|---------------------------| |
||||
|
| Andrii Shvaika | [@ashvayka](https://github.com/ashvayka) | ashvayka@thingsboard.io | |
||||
|
| Igor Kulikov | [@ikulikov](https://github.com/ikulikov) | ikulikov@thingsboard.io | |
||||
|
| Viacheslav Klimov | [@ViacheslavKlimov](https://github.com/ViacheslavKlimov) | vklimov@thingsboard.io | |
||||
|
| Vladyslav Prykhodko | [@vvlladd28](https://github.com/vvlladd28) | vprykhodko@thingsboard.io | |
||||
|
| Sergey Matvienko | [@smatvienko-tb](https://github.com/smatvienko-tb) | smatvienko@thingsboard.io | |
||||
|
|
||||
|
For security issues, please follow the process described in [security.md](security.md) instead of contacting maintainers directly. |
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1,10 +0,0 @@ |
|||||
-- |
|
||||
-- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|
||||
-- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|
||||
-- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|
||||
-- |
|
||||
|
|
||||
-- Intentionally empty. The offline upgrade path is now fully bean-driven: every schema/data change lives in |
|
||||
-- an LtsMigration bean and its data/upgrade/lts/<version>/schema_update.sql (4.4 baseline DDL is in |
|
||||
-- V4_4_0_0Migration / lts/4.4.0.0/schema_update.sql). This file is kept present only so loadSql does not fail. |
|
||||
|
|
||||
@ -0,0 +1,10 @@ |
|||||
|
-- |
||||
|
-- SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
-- SPDX-License-Identifier: BUSL-1.1 |
||||
|
-- |
||||
|
|
||||
|
-- Tenant-scoped paging over calculated fields (WHERE tenant_id = ? ORDER BY id LIMIT ?), issued for every tenant |
||||
|
-- when the calculated field actors initialize, otherwise scans the whole table and sorts on each call. |
||||
|
CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id); |
||||
|
|
||||
|
ALTER TABLE ai_model ADD COLUMN IF NOT EXISTS customer_access_enabled BOOLEAN NOT NULL DEFAULT FALSE; |
||||
@ -0,0 +1,88 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.http.CacheControl; |
||||
|
import org.springframework.http.ContentDisposition; |
||||
|
import org.springframework.http.HttpHeaders; |
||||
|
import org.springframework.http.HttpStatus; |
||||
|
import org.springframework.http.MediaType; |
||||
|
import org.springframework.http.ResponseEntity; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.DeleteMapping; |
||||
|
import org.springframework.web.bind.annotation.GetMapping; |
||||
|
import org.springframework.web.bind.annotation.PathVariable; |
||||
|
import org.springframework.web.bind.annotation.PostMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestPart; |
||||
|
import org.springframework.web.bind.annotation.ResponseStatus; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.permission.Operation; |
||||
|
import org.thingsboard.server.common.data.permission.Resource; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.ai.resource.AiResourceService; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.time.Duration; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
@RequiredArgsConstructor |
||||
|
@RestController |
||||
|
@TbCoreComponent |
||||
|
@RequestMapping("/api/ai/resources") |
||||
|
class AiResourceController extends BaseController { |
||||
|
|
||||
|
private final AiResourceService aiResourceService; |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@GetMapping("/config") |
||||
|
public JsonNode getAiResourcesConfig() throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
||||
|
return aiResourceService.getConfig(user); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) |
||||
|
@ResponseStatus(HttpStatus.CREATED) |
||||
|
public JsonNode uploadAiResource(@RequestPart("file") MultipartFile file) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
||||
|
return aiResourceService.upload(file, user); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@GetMapping("/{resourceId}") |
||||
|
public ResponseEntity<byte[]> downloadAiResource(@PathVariable UUID resourceId) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
||||
|
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user); |
||||
|
return ResponseEntity.ok() |
||||
|
.contentType(MediaType.parseMediaType(content.mediaType())) |
||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name())) |
||||
|
.header("X-Content-Type-Options", "nosniff") |
||||
|
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate()) |
||||
|
.body(content.data()); |
||||
|
} |
||||
|
|
||||
|
private static String disposition(String name) { |
||||
|
ContentDisposition.Builder builder = ContentDisposition.attachment(); |
||||
|
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name); |
||||
|
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString(); |
||||
|
} |
||||
|
|
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@DeleteMapping("/{resourceId}") |
||||
|
@ResponseStatus(HttpStatus.NO_CONTENT) |
||||
|
public void deleteAiResource(@PathVariable UUID resourceId) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
||||
|
aiResourceService.delete(resourceId, user); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,32 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.agent.template; |
||||
|
|
||||
|
import org.thingsboard.common.util.TbVersionUtils; |
||||
|
|
||||
|
import java.util.Collection; |
||||
|
import java.util.List; |
||||
|
import java.util.regex.Pattern; |
||||
|
|
||||
|
/** |
||||
|
* Version-named folders of the templates repo (e.g. {@code templates/since/4.4.1}, {@code compose/edge/4.4}): a |
||||
|
* folder applies to its own version and every later one, until a newer folder exists. |
||||
|
*/ |
||||
|
final class VersionFolders { |
||||
|
|
||||
|
private static final Pattern VERSION = Pattern.compile("\\d+(\\.\\d+)*"); |
||||
|
|
||||
|
private VersionFolders() { |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* The folder names that are plain versions not above {@code version}, newest first; other names are ignored. |
||||
|
*/ |
||||
|
static List<String> applicableTo(Collection<String> folders, String version) { |
||||
|
return folders.stream() |
||||
|
.filter(folder -> VERSION.matcher(folder).matches()) |
||||
|
.filter(folder -> TbVersionUtils.compare(folder, version) <= 0) |
||||
|
.sorted((a, b) -> TbVersionUtils.compare(b, a)) |
||||
|
.toList(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,24 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.ai.resource; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.util.UUID; |
||||
|
|
||||
|
public interface AiResourceService { |
||||
|
|
||||
|
JsonNode getConfig(SecurityUser user); |
||||
|
|
||||
|
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException; |
||||
|
|
||||
|
AiResourceContent download(UUID resourceId, SecurityUser user); |
||||
|
|
||||
|
void delete(UUID resourceId, SecurityUser user); |
||||
|
|
||||
|
record AiResourceContent(String name, String mediaType, byte[] data) {} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,84 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.ai.resource; |
||||
|
|
||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.springframework.web.multipart.MultipartFile; |
||||
|
import org.thingsboard.ai.common.channel.ChannelProtocol; |
||||
|
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
||||
|
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.ai.TbAiService; |
||||
|
import org.thingsboard.server.service.ai.transport.TbAiOperation; |
||||
|
import org.thingsboard.server.service.ai.transport.TbAiOperations; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.io.ByteArrayOutputStream; |
||||
|
import java.io.IOException; |
||||
|
import java.io.InputStream; |
||||
|
import java.io.OutputStream; |
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.util.Base64; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
@Service |
||||
|
@TbCoreComponent |
||||
|
@RequiredArgsConstructor |
||||
|
class DefaultAiResourceService implements AiResourceService { |
||||
|
|
||||
|
private final TbAiService tbAiService; |
||||
|
private final TbAiOperations operations; |
||||
|
|
||||
|
@Override |
||||
|
public JsonNode getConfig(SecurityUser user) { |
||||
|
return tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException { |
||||
|
if (file == null || file.isEmpty()) { |
||||
|
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
} |
||||
|
long maxSize = getConfig(user).path("maxSize").asLong(0); |
||||
|
if (maxSize > 0 && file.getSize() > maxSize) { |
||||
|
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
} |
||||
|
String data; |
||||
|
try { |
||||
|
data = base64(file); |
||||
|
} catch (IOException e) { |
||||
|
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL); |
||||
|
} |
||||
|
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data); |
||||
|
return tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
private static String base64(MultipartFile file) throws IOException { |
||||
|
var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4)); |
||||
|
try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) { |
||||
|
in.transferTo(encoder); |
||||
|
} |
||||
|
return encoded.toString(StandardCharsets.ISO_8859_1); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public AiResourceContent download(UUID resourceId, SecurityUser user) { |
||||
|
JsonNode content = tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
||||
|
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(), |
||||
|
Base64.getDecoder().decode(content.path("data").asText())); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void delete(UUID resourceId, SecurityUser user) { |
||||
|
tbAiService.process(tokenProvider -> operations.execute( |
||||
|
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -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).status(result.status()).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).status(result.status()).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,280 @@ |
|||||
|
// 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, TbAiTurnLink link) { |
||||
|
return turn(ChannelProtocol.CHAT_SEND, chatId, request, context, link); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link) { |
||||
|
return turn(ChannelProtocol.CHAT_RESUME, chatId, null, context, link); |
||||
|
} |
||||
|
|
||||
|
private Flux<ServerSentEvent<String>> turn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link) { |
||||
|
return Flux.create(sink -> { |
||||
|
var turn = new ChannelTurn(type, chatId, request, context, sink); |
||||
|
sink.onDispose(turn::abandon); |
||||
|
if (link != null) { |
||||
|
link.onClientLeft(turn::detach); |
||||
|
} |
||||
|
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 String type; |
||||
|
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 volatile boolean detached; |
||||
|
|
||||
|
private ChannelTurn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, FluxSink<ServerSentEvent<String>> sink) { |
||||
|
this.type = type; |
||||
|
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); |
||||
|
} |
||||
|
|
||||
|
void detach() { |
||||
|
detached = true; |
||||
|
sendDetach(); |
||||
|
} |
||||
|
|
||||
|
private void sendDetach() { |
||||
|
TbAiPooledConnection current = connection; |
||||
|
if (finished.get() || current == null || !current.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) { |
||||
|
return; |
||||
|
} |
||||
|
try { |
||||
|
current.send(new ChannelFrame(ChannelProtocol.CHAT_DETACH, null, null, null, op)); |
||||
|
} catch (ChannelException e) { |
||||
|
log.debug("[{}] Failed to detach from the AI turn: {}", chatId, e.getMessage()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@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; |
||||
|
} |
||||
|
if (ChannelProtocol.CHAT_RESUME.equals(type) && !acquired.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) { |
||||
|
acquired.unreserve(System.nanoTime()); |
||||
|
end(null); |
||||
|
return; |
||||
|
} |
||||
|
ChannelFrame start = ChannelFrame.request(type, |
||||
|
acquired.codec().toPayload(new ChatTurnRequest(chatId, request, context.acceptLanguage()))) |
||||
|
.withOrigin(context.clientOrigin()); |
||||
|
op = start.id(); |
||||
|
connection = acquired; |
||||
|
try { |
||||
|
acquired.start(this, start); |
||||
|
if (detached) { |
||||
|
sendDetach(); |
||||
|
} |
||||
|
} 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,359 @@ |
|||||
|
// 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.ai.common.client.TbAiHeaders; |
||||
|
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 org.thingsboard.server.service.install.ProjectInfo; |
||||
|
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 String tbVersion; |
||||
|
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, |
||||
|
ProjectInfo projectInfo, |
||||
|
@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, projectInfo.getProjectVersion(), maxConnections, maxOperationsPerConnection, |
||||
|
Duration.ofSeconds(idleTimeoutSeconds), Duration.ofMinutes(maxAgeMinutes), System::nanoTime, true); |
||||
|
} |
||||
|
|
||||
|
TbAiChannelPool(TbAiChannelClient channelClient, String tbVersion, int maxConnections, int maxOperationsPerConnection, |
||||
|
Duration idleTimeout, Duration maxAge, LongSupplier nanoClock, boolean startSweeper) { |
||||
|
this.channelClient = channelClient; |
||||
|
this.tbVersion = tbVersion; |
||||
|
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 TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) { |
||||
|
TbAiClient.TokenProvider delegate = context.tokenProvider(); |
||||
|
String acceptLanguage = context.acceptLanguage(); |
||||
|
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(TbAiHeaders.TB_VERSION, tbVersion); |
||||
|
if (acceptLanguage != null && !acceptLanguage.isBlank()) { |
||||
|
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,339 @@ |
|||||
|
// 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; |
||||
|
private volatile List<String> serverCapabilities = List.of(); |
||||
|
|
||||
|
/** |
||||
|
* 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; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Whether TB AI listed {@code capability} in its hello. Frames a capability adds must not be sent without it: an |
||||
|
* older TB AI closes the connection on a frame type it does not know. |
||||
|
*/ |
||||
|
boolean supports(String capability) { |
||||
|
return serverCapabilities.contains(capability); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 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(); |
||||
|
} |
||||
|
if (hello.capabilities() != null) { |
||||
|
serverCapabilities = List.copyOf(hello.capabilities()); |
||||
|
} |
||||
|
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,21 @@ |
|||||
|
// 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, TbAiTurnLink link); |
||||
|
|
||||
|
/** |
||||
|
* Follows the turn running in the chat: a {@code turnResumed} event, every event of the turn so far, then the live |
||||
|
* ones. Completes at once when no turn is running or when TB AI cannot resume turns. |
||||
|
*/ |
||||
|
Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link); |
||||
|
|
||||
|
} |
||||
@ -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,41 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.ai.transport; |
||||
|
|
||||
|
/** |
||||
|
* Connects the browser end of an AI chat stream to its turn on TB AI. ThingsBoard keeps listening to a turn after the |
||||
|
* browser leaves (the turn bills its credits at its end), so leaving is reported separately: TB AI then knows nobody |
||||
|
* follows the turn, and a pending approval expires soon instead of waiting its full timeout for a user who left. |
||||
|
*/ |
||||
|
public final class TbAiTurnLink { |
||||
|
|
||||
|
private final Object lock = new Object(); |
||||
|
private Runnable onClientLeft; |
||||
|
private boolean clientLeft; |
||||
|
|
||||
|
public void onClientLeft(Runnable listener) { |
||||
|
boolean leftAlready; |
||||
|
synchronized (lock) { |
||||
|
onClientLeft = listener; |
||||
|
leftAlready = clientLeft; |
||||
|
} |
||||
|
if (leftAlready) { |
||||
|
listener.run(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public void clientLeft() { |
||||
|
Runnable listener; |
||||
|
synchronized (lock) { |
||||
|
if (clientLeft) { |
||||
|
return; |
||||
|
} |
||||
|
clientLeft = true; |
||||
|
listener = onClientLeft; |
||||
|
} |
||||
|
if (listener != null) { |
||||
|
listener.run(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,20 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.converter; |
||||
|
|
||||
|
import org.thingsboard.server.common.data.converter.ConverterType; |
||||
|
import org.thingsboard.server.common.data.integration.IntegrationType; |
||||
|
|
||||
|
import java.util.Optional; |
||||
|
|
||||
|
public interface ConverterDefaultsService { |
||||
|
|
||||
|
Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType); |
||||
|
|
||||
|
Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType); |
||||
|
|
||||
|
Optional<String> getIntegrationName(IntegrationType integrationType); |
||||
|
|
||||
|
Optional<String> getDownlinkMsgType(IntegrationType integrationType); |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,66 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.service.converter; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.thingsboard.common.util.JacksonUtil; |
||||
|
import org.thingsboard.server.common.data.converter.ConverterType; |
||||
|
import org.thingsboard.server.common.data.integration.IntegrationType; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
|
||||
|
import java.io.IOException; |
||||
|
import java.io.InputStream; |
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.util.Optional; |
||||
|
|
||||
|
@TbCoreComponent |
||||
|
@Service |
||||
|
@Slf4j |
||||
|
public class DefaultConverterDefaultsService implements ConverterDefaultsService { |
||||
|
|
||||
|
private static final String CONVERTERS_DIR = "converters"; |
||||
|
private static final String PAYLOAD_FILE = "payload.json"; |
||||
|
private static final String METADATA_FILE = "metadata.json"; |
||||
|
private static final String INTEGRATION_FILE = "integration.json"; |
||||
|
private static final String MSG_TYPE_FILE = "msgType.txt"; |
||||
|
|
||||
|
@Override |
||||
|
public Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType) { |
||||
|
return getFileContent(integrationType, converterType.getDirectory() + "/" + PAYLOAD_FILE); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType) { |
||||
|
return getFileContent(integrationType, converterType.getDirectory() + "/" + METADATA_FILE); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Optional<String> getIntegrationName(IntegrationType integrationType) { |
||||
|
return getFileContent(integrationType, INTEGRATION_FILE) |
||||
|
.map(content -> JacksonUtil.toJsonNode(content).get("name").asText()); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Optional<String> getDownlinkMsgType(IntegrationType integrationType) { |
||||
|
return getFileContent(integrationType, ConverterType.DOWNLINK.getDirectory() + "/" + MSG_TYPE_FILE) |
||||
|
.map(String::trim); |
||||
|
} |
||||
|
|
||||
|
private Optional<String> getFileContent(IntegrationType integrationType, String relativePath) { |
||||
|
if (integrationType.getDirectory() == null) { |
||||
|
return Optional.empty(); |
||||
|
} |
||||
|
String path = String.join("/", CONVERTERS_DIR, integrationType.getDirectory(), relativePath); |
||||
|
try (InputStream in = getClass().getClassLoader().getResourceAsStream(path)) { |
||||
|
if (in == null) { |
||||
|
return Optional.empty(); |
||||
|
} |
||||
|
return Optional.of(new String(in.readAllBytes(), StandardCharsets.UTF_8)); |
||||
|
} catch (IOException e) { |
||||
|
log.warn("Failed to read converter defaults file {}", path, e); |
||||
|
return Optional.empty(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue