Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ public class CollectConfigDto implements Serializable {

private Boolean repeatRecord;

private Boolean autoGeneratorOn = false;

private Boolean repeatUntilStop;

private Integer repeatTimes;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.opentest.common.model.dto.dashboard;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opentest.common.config.DashboardConfigurationJson;
import com.opentest.common.utils.SnapshotJsonCodec;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CollectConfigAutoGeneratorJsonTest {
private final ObjectMapper json = new ObjectMapper();

@Test
void newAndLegacyConfigurationsDoNotOptIn() throws Exception {
assertEquals(Boolean.FALSE, new CollectConfigDto().getAutoGeneratorOn());
String legacy = "{\"collectConfig\":{\"inputChannels\":[\"Ch1\"]}}";
assertEquals(Boolean.FALSE, json.readValue(legacy, DashboardItemConfigDto.class)
.getCollectConfig().getAutoGeneratorOn());
assertEquals(Boolean.FALSE, DashboardConfigurationJson.read(legacy, DashboardItemConfigDto.class)
.getCollectConfig().getAutoGeneratorOn());
}

@Test
void checkedAndUncheckedPreferencesSurviveDashboardStorageAndResponse() throws Exception {
for (boolean enabled : new boolean[]{false, true}) {
String source = "{\"collectConfig\":{\"autoGeneratorOn\":" + enabled
+ "},\"signalAnalysisConfig\":{\"fftConfig\":{\"overlap\":50}}}";
DashboardItemConfigDto request = json.readValue(source, DashboardItemConfigDto.class);
String stored = DashboardConfigurationJson.write(request);
DashboardItemConfigDto loaded = DashboardConfigurationJson.read(stored, DashboardItemConfigDto.class);
var response = json.readTree(json.writeValueAsString(loaded));

assertEquals(enabled, loaded.getCollectConfig().getAutoGeneratorOn());
assertEquals(enabled, response.at("/collectConfig/autoGeneratorOn").booleanValue());
assertEquals(50, response.at("/signalAnalysisConfig/fftConfig/overlap").intValue());
assertFalse(response.at("/signalAnalysisConfig/fftConfig").has("autoGeneratorOn"));
}
}

@Test
void savedExecutionSnapshotsRetainThePreference() throws Exception {
String source = """
{"dashboardConfig":{"dashboardItemConfig":{"collectConfig":{"autoGeneratorOn":true}}}}
""";
var snapshot = SnapshotJsonCodec.deserializeSnapshot(source);
String saved = SnapshotJsonCodec.serializeSnapshot(snapshot);
assertTrue(json.readTree(saved)
.at("/dashboardConfig/dashboardItemConfig/collectConfig/autoGeneratorOn").booleanValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
import com.opentest.service.project.ProjectPackageChannelTopology;
import com.opentest.service.project.ProjectWordTemplateResourceService;
import com.opentest.service.support.GeneratorChannelConfigResolver;
import com.opentest.service.support.GeneratorCommandGate;
import com.opentest.service.support.GeneratorConfigRuntimeEquivalence;
import com.opentest.service.support.GeneratorPhaseChangePolicy;
import com.opentest.service.unit.BkFrfCurrentConfigNormalizer;
Expand Down Expand Up @@ -146,7 +147,6 @@
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
Expand Down Expand Up @@ -176,9 +176,7 @@ public class ProjectService extends BaseService<ProjectMapper, Project, ProjectQ

private static final String CRY576_PRODUCT_TYPE_ID = "BLUETOOTH-CRY576";

private static final int GENERATOR_MODIFY_LOCK_STRIPES = 64;

private final ReentrantLock[] generatorModifyLocks = createGeneratorModifyLocks();
private final GeneratorCommandGate generatorCommands = new GeneratorCommandGate();

private final GeneratorChannelConfigResolver generatorChannelConfigResolver = new GeneratorChannelConfigResolver();

Expand Down Expand Up @@ -735,13 +733,7 @@ private List<SequenceVariable> listProjectOwnedSequenceVariables(Long projectId)
}

public Boolean modifyGenerator(GeneratorConfigDto dto) {
ReentrantLock lock = generatorModifyLock(dto.getProjectId());
lock.lock();
try {
return modifyGeneratorLocked(dto);
} finally {
lock.unlock();
}
return generatorCommands.execute(dto.getProjectId(), () -> modifyGeneratorLocked(dto));
}

private Boolean modifyGeneratorLocked(GeneratorConfigDto dto) {
Expand Down Expand Up @@ -909,19 +901,6 @@ private <T> T executeGeneratorProjectionTransaction(Supplier<T> action) {
return transactionTemplate.execute(status -> action.get());
}

private static ReentrantLock[] createGeneratorModifyLocks() {
ReentrantLock[] locks = new ReentrantLock[GENERATOR_MODIFY_LOCK_STRIPES];
for (int index = 0; index < locks.length; index++) {
locks[index] = new ReentrantLock();
}
return locks;
}

private ReentrantLock generatorModifyLock(Long projectId) {
int hash = projectId == null ? 0 : projectId.hashCode();
return generatorModifyLocks[Math.floorMod(hash, generatorModifyLocks.length)];
}

private Integer businessErrorCode(Throwable throwable) {
return throwable instanceof CryBusinessException exception ? exception.getErrcode() : null;
}
Expand Down Expand Up @@ -1068,22 +1047,39 @@ private void checkChannelVersion(GeneratorConfigDto dto) {
*/
@Transactional(rollbackFor = Exception.class)
public Boolean startGeneratorPlayback(GeneratorConfigDto dto) {
Project project = this.findById(dto.getProjectId());
var permit = generatorCommands.requestStart(dto.getProjectId());
GeneratorConfigDto config = prepareGeneratorStart(dto.getProjectId(), false);
TransactionManagerUtil.afterCommit(() -> generatorCommands.start(permit, () -> startGenerator(config)));
return true;
}

public void ensureAutomaticGeneratorStarted(Long projectId) {
var permit = generatorCommands.requestStart(projectId);
generatorCommands.start(permit, () -> {
GeneratorConfigDto config = prepareGeneratorStart(projectId, true);
if (config != null) startGenerator(config);
});
}

private GeneratorConfigDto prepareGeneratorStart(Long projectId, boolean allowAlreadyStarted) {
Project project = this.findById(projectId);
Assert.notNull(project.getGeneratorConfig(), () -> new CryBusinessException(ErrorCode.GENERATOR_NOT_FOUND));
GeneratorConfigDto generatorConfigDto = JSONUtil.toBean(project.getGeneratorConfig(), GeneratorConfigDto.class);
checkChannelVersion(generatorConfigDto);
Assert.notNull(generatorConfigDto, () -> new CryBusinessException(ErrorCode.GENERATOR_NOT_FOUND));
generatorConfigDto.setProjectId(project.getId());
Assert.notEmpty(generatorConfigDto.getOutputChannels(), () -> new CryBusinessException(ErrorCode.GENERATOR_CHANEL_NOT_FOUND));
Assert.isFalse(BooleanUtil.isTrue(generatorConfigDto.getGeneratorEnabled()), () -> new CryBusinessException(ErrorCode.GENERATOR_IS_STARTED));
if (BooleanUtil.isTrue(generatorConfigDto.getGeneratorEnabled())) {
if (allowAlreadyStarted) return null;
throw new CryBusinessException(ErrorCode.GENERATOR_IS_STARTED);
}
// FILE 需要基于当前输出通道检查 separate 模式的幅度映射,因此提前加载通道信息。
loadChannels(project.getId(), generatorConfigDto, true);
generatorConfigValidationService.validateRunnable(generatorConfigDto);
if (requiresCalculatedAmplitude(generatorConfigDto)) {
audioJNIBridgeService.calculateAmplitudes(generatorConfigDto);
}
TransactionManagerUtil.afterCommit(() -> startGenerator(generatorConfigDto));
return true;
return generatorConfigDto;
}

/**
Expand Down Expand Up @@ -1270,13 +1266,41 @@ private void throwGeneratorStartFailure(GeneratorConfigDto generatorConfigDto, T
* @return 是否成功
*/
public Boolean stopGeneratorPlayback(GeneratorConfigDto dto) {
Project project = this.findById(dto.getProjectId());
return generatorCommands.execute(dto.getProjectId(), () -> stopGeneratorPlaybackLocked(dto.getProjectId(), false));
}

public void stopAutomaticGenerator(Long projectId, Consumer<RuntimeException> reportFailure) {
generatorCommands.automaticStop(projectId, () -> {
try {
stopGeneratorPlaybackLocked(projectId, false);
} catch (RuntimeException failure) {
reportAutomaticGeneratorFailure(reportFailure, failure);
try {
stopGeneratorPlaybackLocked(projectId, true);
} catch (RuntimeException retryFailure) {
reportAutomaticGeneratorFailure(reportFailure, retryFailure);
}
}
});
}

private void reportAutomaticGeneratorFailure(Consumer<RuntimeException> reporter, RuntimeException failure) {
log.error("Auto Generator shutdown failed", failure);
try {
reporter.accept(failure);
} catch (RuntimeException reportFailure) {
log.error("Auto Generator shutdown diagnostic could not be delivered", reportFailure);
}
}

private Boolean stopGeneratorPlaybackLocked(Long projectId, boolean force) {
Project project = this.findById(projectId);
Assert.notNull(project.getGeneratorConfig(), () -> new CryBusinessException(ErrorCode.GENERATOR_NOT_FOUND));
GeneratorConfigDto generatorConfigDto = JSONUtil.toBean(project.getGeneratorConfig(), GeneratorConfigDto.class);
Assert.notNull(generatorConfigDto, () -> new CryBusinessException(ErrorCode.GENERATOR_NOT_FOUND));
generatorConfigDto.setProjectId(project.getId());
audioJNIBridgeService.cancelGeneratorResume(project.getId());
if (!BooleanUtil.isTrue(generatorConfigDto.getGeneratorEnabled())) {
if (!force && !BooleanUtil.isTrue(generatorConfigDto.getGeneratorEnabled())) {
generatorConfigDto.recordLogChirpGeneratorStart(false);
generatorConfigDto.removeGeneratorEnabled();
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
import com.opentest.service.grpc.core.DashboardStreamSessionState;
import com.opentest.service.grpc.core.GrpcLogFormatter;
import com.opentest.service.grpc.core.sender.GrpcWriter;
import com.opentest.service.ProjectService;
import com.opentest.service.grpc.core.sync.AutomaticGeneratorSession;
import java.util.function.Consumer;
import com.opentest.service.grpc.core.sender.StreamObserverDashboardGrpcWriter;
import com.opentest.platform.mmap.MmapWriter;
import com.opentest.platform.mmap.MmapStorageException;
Expand Down Expand Up @@ -1223,7 +1226,7 @@ protected DashboardRecorder createSyncMeasurementRecorderManager(List<AbstractDa
GrpcWriter<CommonProto.Response> grpcWriter,
MmapWriter mmapWriter,
Locale locale) {
return new SyncMeasurementRecorderManager(
var recorder = new SyncMeasurementRecorderManager(
handlers,
SpringContextHolder.getBean(ContinueCaptureManager.class),
SpringContextHolder.getBean(ChannelListenerManagers.class),
Expand All @@ -1233,6 +1236,15 @@ protected DashboardRecorder createSyncMeasurementRecorderManager(List<AbstractDa
SpringContextHolder.getBean(SyncMeasurementHandlerFactory.class),
null,
executionStorageAdmission);
recorder.setAutomaticGeneratorCommands(new AutomaticGeneratorSession.Commands() {
@Override public void ensureStarted(Long projectId) {
SpringContextHolder.getBean(ProjectService.class).ensureAutomaticGeneratorStarted(projectId);
}
@Override public void stop(Long projectId, Consumer<RuntimeException> diagnostics) {
SpringContextHolder.getBean(ProjectService.class).stopAutomaticGenerator(projectId, diagnostics);
}
});
return recorder;
}

private DashboardMonitorExecutors getDashboardMonitorExecutors() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import com.opentest.service.proto.CommonProto;
import com.opentest.service.proto.WorkflowProto;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.google.protobuf.StringValue;
import io.grpc.stub.StreamObserver;
import lombok.Setter;
Expand Down Expand Up @@ -224,6 +226,30 @@ public Future<?> sendMathChannelError(Long dashboardId, Long requestId, String v
return sendCommonResponse(CommonProto.Response.newBuilder().setMathChannelErrorMsg(message).build());
}

public Future<?> sendAutomaticGeneratorStateChanged(Long projectId) {
var payload = Struct.newBuilder()
.putFields("kind", Value.newBuilder().setStringValue("autoGeneratorStateChanged").build())
.putFields("projectId", Value.newBuilder().setStringValue(projectId.toString()).build());
var message = CommonProto.ExecutionMessage.newBuilder().setSuccess(true).setPayload(payload);
return sendCommonResponse(CommonProto.Response.newBuilder().setExecutionMessage(message).build());
}

public Future<?> sendAutomaticGeneratorError(RuntimeException failure, String phase,
Long dashboardId, Long requestId, Locale locale) {
CryBusinessException business = resolveBusinessException(failure);
Struct payload = Struct.newBuilder()
.putFields("kind", Value.newBuilder().setStringValue("autoGeneratorError").build())
.putFields("phase", Value.newBuilder().setStringValue(phase).build())
.putFields("errorCode", Value.newBuilder().setNumberValue(SourceBusinessErrorCodes.externalCode(business)).build())
.putFields("errorMsg", Value.newBuilder().setStringValue(
"Auto Generator " + phase + ": " + business.resolveMessage(locale == null ? resolveLocale() : locale)).build())
.build();
var message = CommonProto.ExecutionMessage.newBuilder().setSuccess(true).setPayload(payload);
if (dashboardId != null) message.setDashboardId(dashboardId);
if (requestId != null) message.setRequestId(requestId);
return sendCommonResponse(CommonProto.Response.newBuilder().setExecutionMessage(message).build());
}

private CryBusinessException resolveBusinessException(Exception exception) {
JniBusinessException nativeFailure = JniBusinessException.find(exception);
if (nativeFailure != null) {
Expand Down
Loading
Loading