380 changed files with 6780 additions and 4405 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,130 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.service.edge.rpc.processor.ai; |
|||
|
|||
import com.google.common.util.concurrent.Futures; |
|||
import com.google.common.util.concurrent.ListenableFuture; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.data.util.Pair; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.EdgeUtils; |
|||
import org.thingsboard.server.common.data.ai.AiModel; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.edge.EdgeEvent; |
|||
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
|||
import org.thingsboard.server.common.data.edge.EdgeEventType; |
|||
import org.thingsboard.server.common.data.id.AiModelId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.msg.TbMsgType; |
|||
import org.thingsboard.server.common.msg.TbMsgMetaData; |
|||
import org.thingsboard.server.dao.exception.DataValidationException; |
|||
import org.thingsboard.server.gen.edge.v1.AiModelUpdateMsg; |
|||
import org.thingsboard.server.gen.edge.v1.DownlinkMsg; |
|||
import org.thingsboard.server.gen.edge.v1.EdgeVersion; |
|||
import org.thingsboard.server.gen.edge.v1.UpdateMsgType; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; |
|||
|
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
|
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
public class AiModelEdgeProcessor extends BaseAiModelProcessor implements AiModelProcessor { |
|||
|
|||
@Override |
|||
public ListenableFuture<Void> processAiModelMsgFromEdge(TenantId tenantId, Edge edge, AiModelUpdateMsg aiModelUpdateMsg) { |
|||
AiModelId aiModelId = new AiModelId(new UUID(aiModelUpdateMsg.getIdMSB(), aiModelUpdateMsg.getIdLSB())); |
|||
try { |
|||
edgeSynchronizationManager.getEdgeId().set(edge.getId()); |
|||
|
|||
switch (aiModelUpdateMsg.getMsgType()) { |
|||
case ENTITY_CREATED_RPC_MESSAGE: |
|||
case ENTITY_UPDATED_RPC_MESSAGE: |
|||
processAiModel(tenantId, aiModelId, aiModelUpdateMsg, edge); |
|||
return Futures.immediateFuture(null); |
|||
case UNRECOGNIZED: |
|||
default: |
|||
return handleUnsupportedMsgType(aiModelUpdateMsg.getMsgType()); |
|||
} |
|||
} catch (DataValidationException e) { |
|||
return Futures.immediateFailedFuture(e); |
|||
} finally { |
|||
edgeSynchronizationManager.getEdgeId().remove(); |
|||
} |
|||
} |
|||
|
|||
@Override |
|||
public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { |
|||
AiModelId aiModelId = new AiModelId(edgeEvent.getEntityId()); |
|||
switch (edgeEvent.getAction()) { |
|||
case ADDED, UPDATED -> { |
|||
Optional<AiModel> aiModel = edgeCtx.getAiModelService().findAiModelById(edgeEvent.getTenantId(), aiModelId); |
|||
if (aiModel.isPresent()) { |
|||
UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction()); |
|||
AiModelUpdateMsg aiModelUpdateMsg = EdgeMsgConstructorUtils.constructAiModelUpdatedMsg(msgType, aiModel.get()); |
|||
return DownlinkMsg.newBuilder() |
|||
.setDownlinkMsgId(EdgeUtils.nextPositiveInt()) |
|||
.addAiModelUpdateMsg(aiModelUpdateMsg) |
|||
.build(); |
|||
} |
|||
} |
|||
case DELETED -> { |
|||
AiModelUpdateMsg aiModelUpdateMsg = EdgeMsgConstructorUtils.constructAiModelDeleteMsg(aiModelId); |
|||
return DownlinkMsg.newBuilder() |
|||
.setDownlinkMsgId(EdgeUtils.nextPositiveInt()) |
|||
.addAiModelUpdateMsg(aiModelUpdateMsg) |
|||
.build(); |
|||
} |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
@Override |
|||
public EdgeEventType getEdgeEventType() { |
|||
return EdgeEventType.AI_MODEL; |
|||
} |
|||
|
|||
private void processAiModel(TenantId tenantId, AiModelId aiModelId, AiModelUpdateMsg aiModelUpdateMsg, Edge edge) { |
|||
Pair<Boolean, Boolean> resultPair = super.saveOrUpdateAiModel(tenantId, aiModelId, aiModelUpdateMsg); |
|||
Boolean wasCreated = resultPair.getFirst(); |
|||
if (wasCreated) { |
|||
pushAiModelCreatedEventToRuleEngine(tenantId, edge, aiModelId); |
|||
} |
|||
Boolean nameWasUpdated = resultPair.getSecond(); |
|||
if (nameWasUpdated) { |
|||
saveEdgeEvent(tenantId, edge.getId(), EdgeEventType.AI_MODEL, EdgeEventActionType.UPDATED, aiModelId, null); |
|||
} |
|||
} |
|||
|
|||
private void pushAiModelCreatedEventToRuleEngine(TenantId tenantId, Edge edge, AiModelId aiModelId) { |
|||
try { |
|||
Optional<AiModel> aiModel = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId); |
|||
if (aiModel.isPresent()) { |
|||
String aiModelAsString = JacksonUtil.toString(aiModel.get()); |
|||
TbMsgMetaData msgMetaData = getEdgeActionTbMsgMetaData(edge, edge.getCustomerId()); |
|||
pushEntityEventToRuleEngine(tenantId, aiModelId, edge.getCustomerId(), TbMsgType.ENTITY_CREATED, aiModelAsString, msgMetaData); |
|||
} else { |
|||
log.warn("[{}][{}] Failed to find aiModel", tenantId, aiModelId); |
|||
} |
|||
} catch (Exception e) { |
|||
log.warn("[{}][{}] Failed to push aiModel action to rule engine: {}", tenantId, aiModelId, TbMsgType.ENTITY_CREATED.name(), e); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,81 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.service.edge.rpc.processor.ai; |
|||
|
|||
import com.datastax.oss.driver.api.core.uuid.Uuids; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.data.util.Pair; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.StringUtils; |
|||
import org.thingsboard.server.common.data.ai.AiModel; |
|||
import org.thingsboard.server.common.data.id.AiModelId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.service.DataValidator; |
|||
import org.thingsboard.server.gen.edge.v1.AiModelUpdateMsg; |
|||
import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor; |
|||
|
|||
import java.util.Optional; |
|||
|
|||
@Slf4j |
|||
public abstract class BaseAiModelProcessor extends BaseEdgeProcessor { |
|||
|
|||
@Autowired |
|||
private DataValidator<AiModel> aiModelValidator; |
|||
|
|||
protected Pair<Boolean, Boolean> saveOrUpdateAiModel(TenantId tenantId, AiModelId aiModelId, AiModelUpdateMsg aiModelUpdateMsg) { |
|||
boolean isCreated = false; |
|||
boolean isNameUpdated = false; |
|||
try { |
|||
AiModel aiModel = JacksonUtil.fromString(aiModelUpdateMsg.getEntity(), AiModel.class, true); |
|||
if (aiModel == null) { |
|||
throw new RuntimeException("[{" + tenantId + "}] aiModelUpdateMsg {" + aiModelUpdateMsg + " } cannot be converted to aiModel"); |
|||
} |
|||
|
|||
Optional<AiModel> aiModelById = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId); |
|||
if (aiModelById.isEmpty()) { |
|||
aiModel.setCreatedTime(Uuids.unixTimestamp(aiModelId.getId())); |
|||
isCreated = true; |
|||
aiModel.setId(null); |
|||
} else { |
|||
aiModel.setId(aiModelId); |
|||
} |
|||
|
|||
String aiModelName = aiModel.getName(); |
|||
Optional<AiModel> aiModelByName = edgeCtx.getAiModelService().findAiModelByTenantIdAndName(aiModel.getTenantId(), aiModelName); |
|||
if (aiModelByName.isPresent() && !aiModelByName.get().getId().equals(aiModelId)) { |
|||
aiModelName = aiModelName + "_" + StringUtils.randomAlphabetic(15); |
|||
log.warn("[{}] aiModel with name {} already exists. Renaming aiModel name to {}", |
|||
tenantId, aiModel.getName(), aiModelByName.get().getName()); |
|||
isNameUpdated = true; |
|||
} |
|||
aiModel.setName(aiModelName); |
|||
|
|||
aiModelValidator.validate(aiModel, AiModel::getTenantId); |
|||
|
|||
if (isCreated) { |
|||
aiModel.setId(aiModelId); |
|||
} |
|||
|
|||
edgeCtx.getAiModelService().save(aiModel, false); |
|||
} catch (Exception e) { |
|||
log.error("[{}] Failed to process aiModel update msg [{}]", tenantId, aiModelUpdateMsg, e); |
|||
throw e; |
|||
} |
|||
return Pair.of(isCreated, isNameUpdated); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,196 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.edge; |
|||
|
|||
import com.datastax.oss.driver.api.core.uuid.Uuids; |
|||
import com.google.protobuf.AbstractMessage; |
|||
import com.google.protobuf.InvalidProtocolBufferException; |
|||
import org.junit.Assert; |
|||
import org.junit.Test; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.ai.AiModel; |
|||
import org.thingsboard.server.common.data.ai.model.chat.OpenAiChatModelConfig; |
|||
import org.thingsboard.server.common.data.ai.provider.OpenAiProviderConfig; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
import org.thingsboard.server.gen.edge.v1.AiModelUpdateMsg; |
|||
import org.thingsboard.server.gen.edge.v1.UpdateMsgType; |
|||
import org.thingsboard.server.gen.edge.v1.UplinkMsg; |
|||
import org.thingsboard.server.gen.edge.v1.UplinkResponseMsg; |
|||
|
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
|
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
|||
|
|||
@DaoSqlTest |
|||
public class AiModelEdgeTest extends AbstractEdgeTest { |
|||
|
|||
private static final String DEFAULT_AI_MODEL_NAME = "Edge Test AiModel"; |
|||
private static final String UPDATED_AI_MODEL_NAME = "Updated Edge Test AiModel"; |
|||
|
|||
@Test |
|||
public void testAiModel_create_update_delete() throws Exception { |
|||
// create AiModel
|
|||
AiModel aiModel = createSimpleAiModel(DEFAULT_AI_MODEL_NAME); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
AiModel savedAiModel = doPost("/api/ai/model", aiModel, AiModel.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
AbstractMessage latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AiModelUpdateMsg); |
|||
AiModelUpdateMsg aiModelUpdateMsg = (AiModelUpdateMsg) latestMessage; |
|||
Assert.assertEquals(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, aiModelUpdateMsg.getMsgType()); |
|||
Assert.assertEquals(savedAiModel.getUuidId().getMostSignificantBits(), aiModelUpdateMsg.getIdMSB()); |
|||
Assert.assertEquals(savedAiModel.getUuidId().getLeastSignificantBits(), aiModelUpdateMsg.getIdLSB()); |
|||
AiModel aiModelFromMsg = JacksonUtil.fromString(aiModelUpdateMsg.getEntity(), AiModel.class, true); |
|||
Assert.assertNotNull(aiModelFromMsg); |
|||
|
|||
Assert.assertEquals(DEFAULT_AI_MODEL_NAME, aiModelFromMsg.getName()); |
|||
Assert.assertEquals(savedAiModel.getTenantId(), aiModelFromMsg.getTenantId()); |
|||
|
|||
// update AiModel
|
|||
edgeImitator.expectMessageAmount(1); |
|||
savedAiModel.setName(UPDATED_AI_MODEL_NAME); |
|||
savedAiModel = doPost("/api/ai/model", savedAiModel, AiModel.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AiModelUpdateMsg); |
|||
aiModelUpdateMsg = (AiModelUpdateMsg) latestMessage; |
|||
aiModelFromMsg = JacksonUtil.fromString(aiModelUpdateMsg.getEntity(), AiModel.class, true); |
|||
Assert.assertNotNull(aiModelFromMsg); |
|||
Assert.assertEquals(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE, aiModelUpdateMsg.getMsgType()); |
|||
Assert.assertEquals(UPDATED_AI_MODEL_NAME, aiModelFromMsg.getName()); |
|||
|
|||
// delete AiModel
|
|||
edgeImitator.expectMessageAmount(1); |
|||
doDelete("/api/ai/model/" + savedAiModel.getUuidId()) |
|||
.andExpect(status().isOk()); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
latestMessage = edgeImitator.getLatestMessage(); |
|||
Assert.assertTrue(latestMessage instanceof AiModelUpdateMsg); |
|||
aiModelUpdateMsg = (AiModelUpdateMsg) latestMessage; |
|||
Assert.assertEquals(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, aiModelUpdateMsg.getMsgType()); |
|||
Assert.assertEquals(savedAiModel.getUuidId().getMostSignificantBits(), aiModelUpdateMsg.getIdMSB()); |
|||
Assert.assertEquals(savedAiModel.getUuidId().getLeastSignificantBits(), aiModelUpdateMsg.getIdLSB()); |
|||
} |
|||
|
|||
@Test |
|||
public void testSendAiModelToCloud() throws Exception { |
|||
AiModel aiModel = createSimpleAiModel(DEFAULT_AI_MODEL_NAME); |
|||
UUID uuid = Uuids.timeBased(); |
|||
UplinkMsg uplinkMsg = getUplinkMsg(uuid, aiModel, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); |
|||
|
|||
checkAiModelOnCloud(uplinkMsg, uuid, aiModel.getName()); |
|||
} |
|||
|
|||
@Test |
|||
public void testUpdateAiModelNameOnCloud() throws Exception { |
|||
AiModel aiModel = createSimpleAiModel(DEFAULT_AI_MODEL_NAME); |
|||
UUID uuid = Uuids.timeBased(); |
|||
UplinkMsg uplinkMsg = getUplinkMsg(uuid, aiModel, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); |
|||
|
|||
checkAiModelOnCloud(uplinkMsg, uuid, aiModel.getName()); |
|||
|
|||
aiModel.setName(UPDATED_AI_MODEL_NAME); |
|||
UplinkMsg updatedUplinkMsg = getUplinkMsg(uuid, aiModel, UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE); |
|||
|
|||
checkAiModelOnCloud(updatedUplinkMsg, uuid, aiModel.getName()); |
|||
} |
|||
|
|||
@Test |
|||
public void testAiModelToCloudWithNameThatAlreadyExistsOnCloud() throws Exception { |
|||
AiModel aiModel = createSimpleAiModel(DEFAULT_AI_MODEL_NAME); |
|||
|
|||
edgeImitator.expectMessageAmount(1); |
|||
AiModel savedAiModel = doPost("/api/ai/model", aiModel, AiModel.class); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
UUID uuid = Uuids.timeBased(); |
|||
|
|||
UplinkMsg uplinkMsg = getUplinkMsg(uuid, aiModel, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); |
|||
|
|||
edgeImitator.expectResponsesAmount(1); |
|||
edgeImitator.expectMessageAmount(1); |
|||
edgeImitator.sendUplinkMsg(uplinkMsg); |
|||
|
|||
Assert.assertTrue(edgeImitator.waitForResponses()); |
|||
Assert.assertTrue(edgeImitator.waitForMessages()); |
|||
|
|||
Optional<AiModelUpdateMsg> aiModelUpdateMsgOpt = edgeImitator.findMessageByType(AiModelUpdateMsg.class); |
|||
Assert.assertTrue(aiModelUpdateMsgOpt.isPresent()); |
|||
AiModelUpdateMsg latestAiModelUpdateMsg = aiModelUpdateMsgOpt.get(); |
|||
AiModel aiModelFromMsg = JacksonUtil.fromString(latestAiModelUpdateMsg.getEntity(), AiModel.class, true); |
|||
Assert.assertNotNull(aiModelFromMsg); |
|||
Assert.assertNotEquals(DEFAULT_AI_MODEL_NAME, aiModelFromMsg.getName()); |
|||
|
|||
Assert.assertNotEquals(savedAiModel.getUuidId(), uuid); |
|||
|
|||
AiModel aiModelFromCloud = doGet("/api/ai/model/" + uuid, AiModel.class); |
|||
Assert.assertNotNull(aiModelFromCloud); |
|||
Assert.assertNotEquals(DEFAULT_AI_MODEL_NAME, aiModelFromCloud.getName()); |
|||
} |
|||
|
|||
private AiModel createSimpleAiModel(String name) { |
|||
AiModel aiModel = new AiModel(); |
|||
aiModel.setTenantId(tenantId); |
|||
aiModel.setName(name); |
|||
aiModel.setConfiguration(OpenAiChatModelConfig.builder() |
|||
.providerConfig(new OpenAiProviderConfig(null, "test-api-key")) |
|||
.modelId("gpt-4o") |
|||
.temperature(0.5) |
|||
.topP(0.3) |
|||
.frequencyPenalty(0.1) |
|||
.presencePenalty(0.2) |
|||
.maxOutputTokens(1000) |
|||
.timeoutSeconds(60) |
|||
.maxRetries(2) |
|||
.build()); |
|||
return aiModel; |
|||
} |
|||
|
|||
private UplinkMsg getUplinkMsg(UUID uuid, AiModel aiModel, UpdateMsgType updateMsgType) throws InvalidProtocolBufferException { |
|||
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); |
|||
AiModelUpdateMsg.Builder aiModelUpdateMsgBuilder = AiModelUpdateMsg.newBuilder(); |
|||
aiModelUpdateMsgBuilder.setIdMSB(uuid.getMostSignificantBits()); |
|||
aiModelUpdateMsgBuilder.setIdLSB(uuid.getLeastSignificantBits()); |
|||
aiModelUpdateMsgBuilder.setEntity(JacksonUtil.toString(aiModel)); |
|||
aiModelUpdateMsgBuilder.setMsgType(updateMsgType); |
|||
testAutoGeneratedCodeByProtobuf(aiModelUpdateMsgBuilder); |
|||
uplinkMsgBuilder.addAiModelUpdateMsg(aiModelUpdateMsgBuilder.build()); |
|||
|
|||
testAutoGeneratedCodeByProtobuf(uplinkMsgBuilder); |
|||
|
|||
return uplinkMsgBuilder.build(); |
|||
} |
|||
|
|||
private void checkAiModelOnCloud(UplinkMsg uplinkMsg, UUID uuid, String resourceTitle) throws Exception { |
|||
edgeImitator.expectResponsesAmount(1); |
|||
edgeImitator.sendUplinkMsg(uplinkMsg); |
|||
|
|||
Assert.assertTrue(edgeImitator.waitForResponses()); |
|||
|
|||
UplinkResponseMsg latestResponseMsg = edgeImitator.getLatestResponseMsg(); |
|||
Assert.assertTrue(latestResponseMsg.getSuccess()); |
|||
|
|||
AiModel aiModel = doGet("/api/ai/model/" + uuid, AiModel.class); |
|||
Assert.assertNotNull(aiModel); |
|||
Assert.assertEquals(resourceTitle, aiModel.getName()); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,83 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.service.resource; |
|||
|
|||
import org.junit.Test; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.GeneralFileDescriptor; |
|||
import org.thingsboard.server.common.data.ResourceType; |
|||
import org.thingsboard.server.common.data.TbResource; |
|||
import org.thingsboard.server.common.data.TbResourceDataInfo; |
|||
import org.thingsboard.server.common.data.TbResourceInfo; |
|||
import org.thingsboard.server.controller.AbstractControllerTest; |
|||
import org.thingsboard.server.dao.resource.ResourceService; |
|||
import org.thingsboard.server.dao.resource.TbResourceDataCache; |
|||
import org.thingsboard.server.dao.service.DaoSqlTest; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.Mockito.clearInvocations; |
|||
import static org.mockito.Mockito.timeout; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoMoreInteractions; |
|||
|
|||
@DaoSqlTest |
|||
public class DefaultResourceDataCacheTest extends AbstractControllerTest { |
|||
|
|||
@MockitoSpyBean |
|||
private ResourceService resourceService; |
|||
@Autowired |
|||
private TbResourceService tbResourceService; |
|||
@MockitoSpyBean |
|||
private TbResourceDataCache resourceDataCache; |
|||
|
|||
@Test |
|||
public void testGetCachedResourceData() throws Exception { |
|||
loginTenantAdmin(); |
|||
|
|||
TbResource resource = new TbResource(); |
|||
resource.setTenantId(tenantId); |
|||
resource.setTitle("File for AI request"); |
|||
resource.setResourceType(ResourceType.GENERAL); |
|||
resource.setFileName("myTestJson.json"); |
|||
GeneralFileDescriptor descriptor = new GeneralFileDescriptor("application/json"); |
|||
resource.setDescriptorValue(descriptor); |
|||
byte[] data = "This is a test prompt for AI request.".getBytes(); |
|||
resource.setData(data); |
|||
TbResourceInfo savedResource = tbResourceService.save(resource); |
|||
verify(resourceDataCache, timeout(2000).times(1)).evictResourceData(tenantId, savedResource.getId()); |
|||
|
|||
TbResourceDataInfo cachedData = resourceDataCache.getResourceDataInfoAsync(tenantId, savedResource.getId()).get(); |
|||
assertThat(cachedData.getData()).isEqualTo(data); |
|||
assertThat(JacksonUtil.treeToValue(cachedData.getDescriptor(), GeneralFileDescriptor.class)).isEqualTo(descriptor); |
|||
verify(resourceService).getResourceDataInfo(tenantId, savedResource.getId()); |
|||
|
|||
// retrieve resource data second time
|
|||
clearInvocations(resourceService); |
|||
TbResourceDataInfo cachedData2 = resourceDataCache.getResourceDataInfoAsync(tenantId, savedResource.getId()).get(); |
|||
assertThat(cachedData2.getData()).isEqualTo(data); |
|||
verifyNoMoreInteractions(resourceService); |
|||
|
|||
// delete resource, check cache
|
|||
TbResource resourceById = resourceService.findResourceById(tenantId, savedResource.getId()); |
|||
tbResourceService.delete(resourceById, true, null); |
|||
verify(resourceDataCache, timeout(2000).times(2)).evictResourceData(tenantId, savedResource.getId()); |
|||
TbResourceDataInfo cachedDataAfterDeletion = resourceDataCache.getResourceDataInfoAsync(tenantId, savedResource.getId()).get(); |
|||
assertThat(cachedDataAfterDeletion).isEqualTo(null); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.EqualsAndHashCode; |
|||
import lombok.NoArgsConstructor; |
|||
|
|||
@Data |
|||
@EqualsAndHashCode |
|||
@AllArgsConstructor |
|||
@NoArgsConstructor |
|||
public class GeneralFileDescriptor { |
|||
private String mediaType; |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
public enum NameConflictPolicy { |
|||
|
|||
FAIL, |
|||
UNIQUIFY; |
|||
|
|||
} |
|||
@ -0,0 +1,25 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
import io.swagger.v3.oas.annotations.media.Schema; |
|||
|
|||
@Schema |
|||
public record NameConflictStrategy(NameConflictPolicy policy, String separator, UniquifyStrategy uniquifyStrategy) { |
|||
|
|||
public static final NameConflictStrategy DEFAULT = new NameConflictStrategy(NameConflictPolicy.FAIL, null, null); |
|||
|
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
|
|||
@Data |
|||
@AllArgsConstructor |
|||
@NoArgsConstructor |
|||
public class TbResourceDataInfo { |
|||
|
|||
private byte[] data; |
|||
private JsonNode descriptor; |
|||
|
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
/** |
|||
* Copyright © 2016-2025 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
public enum UniquifyStrategy { |
|||
|
|||
RANDOM, |
|||
INCREMENTAL; |
|||
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue