From 831627e5759ecc2ea78948449f6a0f2318b29f19 Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Thu, 19 Nov 2026 18:48:50 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(measure):=20=E5=A2=9E=E5=8A=A0=20Auto?= =?UTF-8?q?=20Generator=20On?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #42 --- .../model/dto/dashboard/CollectConfigDto.java | 2 + .../CollectConfigAutoGeneratorJsonTest.java | 52 ++++ .../com/opentest/service/ProjectService.java | 84 ++++--- .../service/grpc/DashboardGrpcImpl.java | 14 +- .../service/grpc/core/sender/GrpcWriter.java | 26 ++ .../core/sync/AutomaticGeneratorSession.java | 154 ++++++++++++ .../sync/SyncMeasurementRecorderManager.java | 58 +++++ .../ProviderPipelineDashboardHandler.java | 77 ++++-- .../service/support/GeneratorCommandGate.java | 83 ++++++ .../ProjectServiceAutomaticGeneratorTest.java | 77 ++++++ .../AutomaticGeneratorMeasurementTest.java | 236 ++++++++++++++++++ ...roviderAutomaticGeneratorPipelineTest.java | 131 ++++++++++ .../support/GeneratorCommandGateTest.java | 87 +++++++ .../use-dashboard-grpc-runtime.test.ts | 49 ++++ .../dashboard/use-dashboard-grpc-runtime.ts | 25 +- .../__tests__/config-dashboard.test.ts | 7 + .../src/constants/dashboard/colllect.ts | 3 + .../__tests__/dashboard-locale.test.ts | 11 +- apps/frontend/src/locales/de-DE.ts | 1 + apps/frontend/src/locales/en.ts | 1 + apps/frontend/src/locales/es-ES.ts | 1 + apps/frontend/src/locales/fr-FR.ts | 1 + apps/frontend/src/locales/ja-JP.ts | 1 + apps/frontend/src/locales/ko-KR.ts | 1 + apps/frontend/src/locales/ru-RU.ts | 1 + apps/frontend/src/locales/tr-TR.ts | 1 + apps/frontend/src/locales/zh-CN.ts | 1 + apps/frontend/src/locales/zh-TW.ts | 1 + .../__tests__/measurement-control.test.ts | 71 +++++- .../shared/dashboard/measurement-control.vue | 21 ++ .../src/plugin-host/measure-settings.ts | 10 + .../tests/measure-settings.test.ts | 41 ++- .../src/stores/__tests__/generator.test.ts | 19 ++ apps/frontend/src/stores/generator.ts | 10 + .../v1/http/models/dashboard.types.ts | 1 + .../packages/generated/src/index.ts | 2 +- .../generated/src/models/dashboard.types.ts | 1 + 37 files changed, 1306 insertions(+), 56 deletions(-) create mode 100644 apps/backend/crydaq-common/src/test/java/com/opentest/common/model/dto/dashboard/CollectConfigAutoGeneratorJsonTest.java create mode 100644 apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorSession.java create mode 100644 apps/backend/crydaq-service/src/main/java/com/opentest/service/support/GeneratorCommandGate.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/ProjectServiceAutomaticGeneratorTest.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorMeasurementTest.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/provider/ProviderAutomaticGeneratorPipelineTest.java create mode 100644 apps/backend/crydaq-service/src/test/java/com/opentest/service/support/GeneratorCommandGateTest.java diff --git a/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/dashboard/CollectConfigDto.java b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/dashboard/CollectConfigDto.java index 87cfadc8..902bfdb4 100644 --- a/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/dashboard/CollectConfigDto.java +++ b/apps/backend/crydaq-common/src/main/java/com/opentest/common/model/dto/dashboard/CollectConfigDto.java @@ -155,6 +155,8 @@ public class CollectConfigDto implements Serializable { private Boolean repeatRecord; + private Boolean autoGeneratorOn = false; + private Boolean repeatUntilStop; private Integer repeatTimes; diff --git a/apps/backend/crydaq-common/src/test/java/com/opentest/common/model/dto/dashboard/CollectConfigAutoGeneratorJsonTest.java b/apps/backend/crydaq-common/src/test/java/com/opentest/common/model/dto/dashboard/CollectConfigAutoGeneratorJsonTest.java new file mode 100644 index 00000000..5cf10db8 --- /dev/null +++ b/apps/backend/crydaq-common/src/test/java/com/opentest/common/model/dto/dashboard/CollectConfigAutoGeneratorJsonTest.java @@ -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()); + } +} diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/ProjectService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/ProjectService.java index 36afcb39..f060c139 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/ProjectService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/ProjectService.java @@ -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; @@ -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; @@ -176,9 +176,7 @@ public class ProjectService extends BaseService 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) { @@ -909,19 +901,6 @@ private T executeGeneratorProjectionTransaction(Supplier 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; } @@ -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; } /** @@ -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 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 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; diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/DashboardGrpcImpl.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/DashboardGrpcImpl.java index a92ac729..78187a16 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/DashboardGrpcImpl.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/DashboardGrpcImpl.java @@ -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; @@ -1223,7 +1226,7 @@ protected DashboardRecorder createSyncMeasurementRecorderManager(List grpcWriter, MmapWriter mmapWriter, Locale locale) { - return new SyncMeasurementRecorderManager( + var recorder = new SyncMeasurementRecorderManager( handlers, SpringContextHolder.getBean(ContinueCaptureManager.class), SpringContextHolder.getBean(ChannelListenerManagers.class), @@ -1233,6 +1236,15 @@ protected DashboardRecorder createSyncMeasurementRecorderManager(List diagnostics) { + SpringContextHolder.getBean(ProjectService.class).stopAutomaticGenerator(projectId, diagnostics); + } + }); + return recorder; } private DashboardMonitorExecutors getDashboardMonitorExecutors() { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sender/GrpcWriter.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sender/GrpcWriter.java index 2da43a7d..f20d6e37 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sender/GrpcWriter.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sender/GrpcWriter.java @@ -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; @@ -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) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorSession.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorSession.java new file mode 100644 index 00000000..b6705e55 --- /dev/null +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorSession.java @@ -0,0 +1,154 @@ +package com.opentest.service.grpc.core.sync; + +import lombok.extern.slf4j.Slf4j; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.function.Consumer; +import java.util.function.BiConsumer; + +@Slf4j +public final class AutomaticGeneratorSession implements AutoCloseable { + public interface Commands { + void ensureStarted(Long projectId); + void stop(Long projectId, Consumer diagnostics); + } + + public static final class AdmissionCancelledException extends CancellationException { + private AdmissionCancelledException() { super("Automatic Generator acquisition was cancelled"); } + } + + private enum State { NEW, STARTING, ACTIVE, RELEASED } + + private final Long projectId; + private final Commands commands; + private final Consumer startFailure; + private final Runnable outputChanged; + private final Object stateLock = new Object(); + private final Object commandLock = new Object(); + private final Set rounds = Collections.newSetFromMap(new IdentityHashMap<>()); + private boolean admissionsClosed; + private RuntimeException failure; + private boolean outputNeedsStop; + private Consumer lastDiagnostics; + + public AutomaticGeneratorSession(Long projectId, Commands commands, Consumer startFailure, + Runnable outputChanged) { + this.projectId = projectId; + this.commands = commands; + this.startFailure = startFailure; + this.outputChanged = outputChanged; + } + + public Round newRound(BiConsumer diagnostics) { + synchronized (stateLock) { + var round = new Round(diagnostics); + if (admissionsClosed) round.state = State.RELEASED; + else rounds.add(round); + return round; + } + } + + /** Publish cancellation without shutting output off before input drain. */ + public void cancelAdmissions() { + synchronized (stateLock) { admissionsClosed = true; } + } + + @Override public void close() { + synchronized (stateLock) { + admissionsClosed = true; + rounds.forEach(round -> round.state = State.RELEASED); + rounds.clear(); + } + synchronized (commandLock) { stopIfUnused(lastDiagnostics); } + } + + private void stopIfUnused(Consumer diagnostics) { + synchronized (stateLock) { + if (!outputNeedsStop || rounds.stream().anyMatch(round -> round.state == State.ACTIVE || round.state == State.STARTING)) return; + outputNeedsStop = false; + } + try { commands.stop(projectId, error -> report(diagnostics, error)); } + catch (RuntimeException error) { report(diagnostics, error); } + finally { notifyOutputChanged(); } + } + + private void notifyOutputChanged() { + try { + outputChanged.run(); + } catch (RuntimeException error) { + log.warn("Automatic Generator status notification failed, projectId={}", projectId, error); + } + } + + private void report(Consumer diagnostics, RuntimeException error) { + try { + if (diagnostics != null) diagnostics.accept(error); + else log.error("Automatic Generator cleanup failed, projectId={}", projectId, error); + } catch (RuntimeException reportingFailure) { + log.error("Automatic Generator cleanup failed, projectId={}", projectId, error); + log.warn("Automatic Generator diagnostic delivery failed, projectId={}", projectId, reportingFailure); + } + } + + public final class Round implements AutoCloseable { + private final BiConsumer diagnostics; + private State state = State.NEW; + + private Round(BiConsumer diagnostics) { this.diagnostics = diagnostics; } + + public void start() { + RuntimeException rejected = null; + boolean notifyFailure = false; + synchronized (commandLock) { + synchronized (stateLock) { + if (failure != null) throw failure; + if (admissionsClosed || state == State.RELEASED) + throw new AdmissionCancelledException(); + if (state == State.ACTIVE) return; + state = State.STARTING; + outputNeedsStop = true; + lastDiagnostics = error -> diagnostics.accept("stop", error); + } + try { + commands.ensureStarted(projectId); + notifyOutputChanged(); + synchronized (stateLock) { + if (admissionsClosed || state == State.RELEASED) + throw new AdmissionCancelledException(); + state = State.ACTIVE; + } + } catch (RuntimeException error) { + synchronized (stateLock) { + state = State.RELEASED; + rounds.remove(this); + if (!(error instanceof AdmissionCancelledException)) { + failure = error; + admissionsClosed = true; + notifyFailure = true; + } + } + rejected = error; + } + } + if (notifyFailure) { + report(error -> diagnostics.accept("start", error), rejected); + try { startFailure.accept(rejected); } + catch (RuntimeException notificationFailure) { + if (notificationFailure != rejected) rejected.addSuppressed(notificationFailure); + } + } + if (rejected != null) throw rejected; + } + + @Override public void close() { + synchronized (stateLock) { + state = State.RELEASED; + rounds.remove(this); + } + synchronized (commandLock) { stopIfUnused(error -> diagnostics.accept("stop", error)); } + } + } +} diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/SyncMeasurementRecorderManager.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/SyncMeasurementRecorderManager.java index e4fead15..6591f366 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/SyncMeasurementRecorderManager.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/core/sync/SyncMeasurementRecorderManager.java @@ -7,6 +7,7 @@ import com.opentest.common.exception.CryBusinessException; import com.opentest.common.exception.ErrorCode; import com.opentest.common.enums.ChannelSourceEnum; +import com.opentest.common.enums.BuiltinDashboardProvider; import com.opentest.common.model.dto.ChannelDto; import com.opentest.common.model.dto.ContinueCaptureFuture; import com.opentest.common.model.dto.dashboard.CollectConfigDto; @@ -124,6 +125,18 @@ public class SyncMeasurementRecorderManager implements DashboardRecorder { private final Set admittedRepeatActivationRoundIndexes = new LinkedHashSet<>(); + private AutomaticGeneratorSession.Commands automaticGeneratorCommands; + private volatile AutomaticGeneratorSession automaticGeneratorSession; + private static final Set AUTOMATIC_GENERATOR_PROVIDERS = Set.of( + BuiltinDashboardProvider.FFT.getProviderId(), BuiltinDashboardProvider.OCTAVE.getProviderId(), + BuiltinDashboardProvider.SOUND_QUALITY.getProviderId(), BuiltinDashboardProvider.SOUND_LEVEL_METER.getProviderId(), + BuiltinDashboardProvider.VIBRATION.getProviderId()); + + public synchronized void setAutomaticGeneratorCommands(AutomaticGeneratorSession.Commands commands) { + if (startRequested) throw new IllegalStateException("Generator commands must be configured before capture starts"); + automaticGeneratorCommands = commands; + } + private volatile boolean stageOwned; private boolean startRequested; @@ -372,6 +385,7 @@ public void start(Executor startExecutor, var recorder = new SyncMeasurementRecorderManager(List.of(child), continueCaptureManager, channelListenerManagers, postProcessService, sequenceExecutionGraphRuntimeCache, projectDashboardComponent, handlerFactory, delayController, executionStorageAdmission); + recorder.setAutomaticGeneratorCommands(automaticGeneratorCommands); recorder.setStageOwned(true); return recorder; }, startExecutor, nativeStartExecutor, timeoutScheduler, nativeStartTimeoutMs); @@ -465,6 +479,8 @@ public boolean requestOperatorStop() { } } } + var generatorSession = automaticGeneratorSession; + if (generatorSession != null) generatorSession.cancelAdmissions(); // Plugin callbacks are dispatched after the group transition releases its monitor. executions.forEach(ProviderExecutionSession::requestOperatorStop); if (!deferred) { @@ -506,6 +522,8 @@ public void stop(Exception e, DashboardCompletionDisposition disposition) { if (!completion.isDone() && distinct.add(handler)) stopTargets.add(handler); }); } + var generatorSession = automaticGeneratorSession; + if (generatorSession != null) generatorSession.cancelAdmissions(); signalMeasurementPrewarms(); if (!firstStop) { dispatchFinalization(() -> broadcastStopIntent(stopTargets)); @@ -600,6 +618,8 @@ private void finishSessionStop(Exception e, DashboardCompletionDisposition dispo } catch (Throwable failure) { failureCollector.add(failure); } finally { + var generatorSession = automaticGeneratorSession; + if (generatorSession != null) generatorSession.close(); // All worker/resource waits are over. Publish the terminal outcome atomically with // stop-intent admission so a concurrent failure cannot follow a successful message. synchronized (this) { @@ -2210,6 +2230,7 @@ private void notifyStopCompleted() { private void prepareHandlerForRun(SyncMeasurementMemberRuntime runtime, AbstractDashboardHandler handler, ScheduledExecutorService timeoutScheduler) { + bindAutomaticGeneratorRound(runtime, handler); handler.setProcessingFailureCallback(handlerProcessingFailureCallback); handler.setRecordCreate(true); handler.setStopTriggerFunc(() -> onHandlerNaturalStop(runtime, handler, timeoutScheduler)); @@ -2226,6 +2247,43 @@ private void prepareHandlerForRun(SyncMeasurementMemberRuntime runtime, } } + private synchronized void bindAutomaticGeneratorRound(SyncMeasurementMemberRuntime runtime, + AbstractDashboardHandler handler) { + if (!(handler instanceof ProviderPipelineDashboardHandler provider) + || !handler.hasExecutionRecord() || handler.getDashboard() == null + || runtime.getCollectConfig() == null + || !Boolean.TRUE.equals(runtime.getCollectConfig().getAutoGeneratorOn()) + || handler.getDashboard().getProviderId() == null + || !AUTOMATIC_GENERATOR_PROVIDERS.contains(handler.getDashboard().getProviderId())) return; + if (automaticGeneratorCommands == null) + throw new IllegalStateException("Automatic Generator commands are not configured"); + if (automaticGeneratorSession == null) { + automaticGeneratorSession = new AutomaticGeneratorSession(handler.getDashboard().getProjectId(), + automaticGeneratorCommands, + failure -> dispatchFinalization(() -> stop(failure, DashboardCompletionDisposition.FAILURE)), + () -> { + if (handler.getGrpcWriter() != null) + handler.getGrpcWriter().sendAutomaticGeneratorStateChanged(handler.getDashboard().getProjectId()); + }); + if (hasStop || stopRequested) automaticGeneratorSession.cancelAdmissions(); + } + provider.bindAutomaticGeneratorRound(automaticGeneratorSession.newRound( + (phase, failure) -> reportAutomaticGeneratorFailure(handler, failure, phase))); + } + + private void reportAutomaticGeneratorFailure(AbstractDashboardHandler handler, RuntimeException failure, String phase) { + try { + if (handler.getGrpcWriter() != null) + handler.getGrpcWriter().sendAutomaticGeneratorError(failure, phase, handler.getDashboardId(), + handler.getRequestId(), handler.getLocale()); + } catch (RuntimeException reportingFailure) { + log.warn("Automatic Generator diagnostic delivery failed, dashboardId={}, requestId={}", + handler.getDashboardId(), handler.getRequestId(), reportingFailure); + } + log.error("Automatic Generator {} failed, dashboardId={}, requestId={}", phase, + handler.getDashboardId(), handler.getRequestId(), failure); + } + private MeasurementPrewarm startMeasurementPrewarm(SyncMeasurementMemberRuntime runtime) { MeasurementPrewarm slot; synchronized (this) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/provider/ProviderPipelineDashboardHandler.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/provider/ProviderPipelineDashboardHandler.java index 87361b42..8b28f957 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/provider/ProviderPipelineDashboardHandler.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/grpc/provider/ProviderPipelineDashboardHandler.java @@ -78,6 +78,8 @@ import com.opentest.common.model.dto.dashboard.TriggerConfigDto; import com.opentest.service.grpc.plan.DashboardExecutionMode; import com.opentest.service.grpc.core.sync.RecordingStorageOutput; +import com.opentest.service.grpc.core.sync.AutomaticGeneratorSession; +import com.opentest.service.grpc.core.sync.AutomaticGeneratorSession.AdmissionCancelledException; import com.opentest.common.enums.ExportTypeEnum; import com.opentest.common.enums.ResultStorageModeEnum; import com.opentest.common.enums.BuiltinDashboardProvider; @@ -973,20 +975,23 @@ private void observe(CompletedResultCurve curve, long generation, boolean append preparationFailure = failure; throw failure; } - pipeline.completion().whenComplete((ignored, error) -> { - inputControl.requestClose(); - var stagesReleased = captureStages == null ? CompletableFuture.completedFuture(null) - : captureStages.closeAsync().toCompletableFuture(); - var canReleased = canInputs == null ? CompletableFuture.completedFuture(null) : canInputs.released(); - CompletableFuture.allOf(pipeline.resourcesReleased().toCompletableFuture(), inputControl.closed(), stagesReleased, canReleased) - .whenComplete((closed, closeFailure) -> { - if (closeFailure == null) resourcesReleased.complete(null); else resourcesReleased.completeExceptionally(closeFailure); - }); - if (closing.get()) return; - if (error == null) requestNaturalStop(); else notifyProviderFailure(new IllegalStateException("Measurement pipeline failed", error)); - }); + bindPipelineCompletion(); } } + private CompletionStage bindPipelineCompletion() { + return pipeline.completion().whenComplete((ignored, error) -> { + inputControl.requestClose(); + var stagesReleased = captureStages == null ? CompletableFuture.completedFuture(null) + : captureStages.closeAsync().toCompletableFuture(); + var canReleased = canInputs == null ? CompletableFuture.completedFuture(null) : canInputs.released(); + CompletableFuture.allOf(pipeline.resourcesReleased().toCompletableFuture(), inputControl.closed(), stagesReleased, canReleased) + .whenComplete((closed, closeFailure) -> { + if (closeFailure == null) resourcesReleased.complete(null); else resourcesReleased.completeExceptionally(closeFailure); + }); + if (closing.get()) return; + if (error == null) requestNaturalStop(); else notifyProviderFailure(new IllegalStateException("Measurement pipeline failed", error)); + }); + } void publishMeasurementCompleted(List curves) { publishMeasurementCompleted(curves, null); } void publishMeasurementCompleted(List curves, ProviderRuntimeLimitFrames.CompletedBatch prepared) { @@ -1541,12 +1546,12 @@ private void requestPackageStop() { } @Override public void recordStartFunc(String vchId) { if (captureAdmission != null && !captureAdmissionOpened) return; - recordingLifecycle.started(); + if (automaticGeneratorRound == null) recordingLifecycle.started(); if (captureStageInput && (captureAdmission == null || captureAdmissionOpened)) startFormalMeasurement(); } @Override public void recordStartFunc(String vchId, java.time.LocalDateTime time) { if (captureAdmission != null && !captureAdmissionOpened) return; - recordingLifecycle.started(); + if (automaticGeneratorRound == null) recordingLifecycle.started(); if (captureStageInput && (captureAdmission == null || captureAdmissionOpened)) startFormalMeasurement(); } /** 共享 reader 已就绪;所有 Provider 都收到同一资源事实,不决定业务停止策略。 */ @@ -1589,6 +1594,19 @@ private double formalRecordingElapsedMillis() { public Long getExpectedCompletionDurationMs() { return recordingLifecycle.expectedDuration(); } @Override public void afterSharedCaptureStopped(boolean successful) { recordingLifecycle.stopped(successful); } private final AtomicBoolean formalMeasurementStarted = new AtomicBoolean(); + private final CompletableFuture formalMeasurementReady = new CompletableFuture<>(); + private AutomaticGeneratorSession.Round automaticGeneratorRound; + + public void bindAutomaticGeneratorRound(AutomaticGeneratorSession.Round round) { + if (automaticGeneratorRound != null || formalMeasurementStarted.get()) + throw new IllegalStateException("Automatic Generator round must be bound once before acquisition"); + automaticGeneratorRound = Objects.requireNonNull(round); + } + + @Override public DashboardHandlerStopPreparation beginStop() { + try { return super.beginStop(); } + finally { if (automaticGeneratorRound != null) automaticGeneratorRound.close(); } + } private void attachCanRecording() { if (canInputs == null || canInputs.channels().channels().isEmpty() @@ -1686,8 +1704,35 @@ private void persist(CompletedResultCurve curve) { } private void startFormalMeasurement() { - if (closing.get() || captureAdmission != null && !captureAdmissionOpened - || !formalMeasurementStarted.compareAndSet(false, true)) return; + if (closing.get() || captureAdmission != null && !captureAdmissionOpened) return; + if (!formalMeasurementStarted.compareAndSet(false, true)) { + if (automaticGeneratorRound == null) return; + try { formalMeasurementReady.join(); } + catch (CompletionException error) { + if (error.getCause() instanceof RuntimeException failure) throw failure; + if (error.getCause() instanceof Error failure) throw failure; + throw error; + } + return; + } + try { + if (automaticGeneratorRound != null) { + try { automaticGeneratorRound.start(); } + catch (AdmissionCancelledException cancelled) { + // Recorder cancellation owns finalization; pipeline completion must not report it as a new failure. + closing.set(true); + throw cancelled; + } + } + publishFormalMeasurementStart(); + formalMeasurementReady.complete(null); + } catch (RuntimeException | Error failure) { + formalMeasurementReady.completeExceptionally(failure); + throw failure; + } + } + + private void publishFormalMeasurementStart() { if (measurementSession != null) measurementSession.captureStarted(); recordingLifecycle.started(); String anchor = input.isEmpty() ? measurementInputs.selected().getFirst().getVchId() : input.getFirst().vchId(); diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/support/GeneratorCommandGate.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/support/GeneratorCommandGate.java new file mode 100644 index 00000000..b1203af4 --- /dev/null +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/support/GeneratorCommandGate.java @@ -0,0 +1,83 @@ +package com.opentest.service.support; + +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +public final class GeneratorCommandGate { + private final ConcurrentHashMap lanes = new ConcurrentHashMap<>(); + + private static final class Lane { + final ReentrantLock commands = new ReentrantLock(); + long generation; + int closing; + } + + public static final class StartPermit { + private final Lane lane; + private final long generation; + private final boolean admitted; + + private StartPermit(Lane lane) { + this.lane = lane; + synchronized (lane) { + generation = lane.generation; + admitted = lane.closing == 0; + } + } + } + + public StartPermit requestStart(Long projectId) { + return new StartPermit(lane(projectId)); + } + + public void start(StartPermit permit, Runnable command) { + Lane lane = permit.lane; + lane.commands.lock(); + try { + synchronized (lane) { + if (!permit.admitted || lane.closing != 0 || permit.generation != lane.generation) { + throw new CryBusinessException(ErrorCode.GENERATOR_PLAYBACK_START_FAILED, + new IllegalStateException("Auto Generator shutdown superseded this start request")); + } + } + command.run(); + } finally { + lane.commands.unlock(); + } + } + + public T execute(Long projectId, Supplier command) { + Lane lane = lane(projectId); + lane.commands.lock(); + try { + return command.get(); + } finally { + lane.commands.unlock(); + } + } + + public void automaticStop(Long projectId, Runnable command) { + Lane lane = lane(projectId); + synchronized (lane) { + lane.generation++; + lane.closing++; + } + lane.commands.lock(); + try { + command.run(); + } finally { + synchronized (lane) { + lane.closing--; + } + lane.commands.unlock(); + } + } + + private Lane lane(Long projectId) { + return lanes.computeIfAbsent(projectId, ignored -> new Lane()); + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/ProjectServiceAutomaticGeneratorTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/ProjectServiceAutomaticGeneratorTest.java new file mode 100644 index 00000000..4438bb34 --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/ProjectServiceAutomaticGeneratorTest.java @@ -0,0 +1,77 @@ +package com.opentest.service; + +import cn.hutool.json.JSONUtil; +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; +import com.opentest.common.model.dto.dashboard.GeneratorConfigDto; +import com.opentest.common.model.entity.Project; +import com.opentest.service.jni.AudioJNIBridgeService; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ProjectServiceAutomaticGeneratorTest { + @Test + void shutdownFailureRetriesEvenIfRuntimeAlreadyReportsOff() { + var service = spy(new ProjectService()); + var audio = mock(AudioJNIBridgeService.class); + ReflectionTestUtils.setField(service, "audioJNIBridgeService", audio); + var config = new GeneratorConfigDto(); + config.setProjectId(90871L); + config.setOutputChannels(List.of("Ch1")); + var project = new Project(); + project.setId(config.getProjectId()); + project.setGeneratorConfig(JSONUtil.toJsonStr(config)); + doReturn(project).when(service).findById(project.getId()); + var failure = new CryBusinessException(ErrorCode.GENERATOR_PLAYBACK_STOP_FAILED); + var diagnostics = new ArrayList(); + when(audio.stopActiveGeneratorPlayback(project.getId(), false)).thenAnswer(invocation -> { + config.removeGeneratorEnabled(); + throw failure; + }).thenReturn(true); + config.recordGeneratorStart(); + try { + assertDoesNotThrow(() -> service.stopAutomaticGenerator(project.getId(), diagnostics::add)); + verify(audio, times(2)).stopActiveGeneratorPlayback(project.getId(), false); + assertEquals(List.of(failure), diagnostics); + } finally { + config.removeGeneratorEnabled(); + } + } + + @Test + void retryAndDiagnosticFailuresDoNotEscapeCleanupOrCauseFurtherRetries() { + var service = spy(new ProjectService()); + var audio = mock(AudioJNIBridgeService.class); + ReflectionTestUtils.setField(service, "audioJNIBridgeService", audio); + var config = new GeneratorConfigDto(); + config.setProjectId(90872L); + config.setOutputChannels(List.of("Ch1")); + var project = new Project(); + project.setId(config.getProjectId()); + project.setGeneratorConfig(JSONUtil.toJsonStr(config)); + doReturn(project).when(service).findById(project.getId()); + when(audio.stopActiveGeneratorPlayback(project.getId(), false)) + .thenThrow(new CryBusinessException(ErrorCode.GENERATOR_PLAYBACK_STOP_FAILED)); + config.recordGeneratorStart(); + try { + assertDoesNotThrow(() -> service.stopAutomaticGenerator(project.getId(), failure -> { + throw new IllegalStateException("stream closed"); + })); + verify(audio, times(2)).stopActiveGeneratorPlayback(project.getId(), false); + } finally { + config.removeGeneratorEnabled(); + } + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorMeasurementTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorMeasurementTest.java new file mode 100644 index 00000000..25ef64de --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/core/sync/AutomaticGeneratorMeasurementTest.java @@ -0,0 +1,236 @@ +package com.opentest.service.grpc.core.sync; + +import com.opentest.common.enums.BuiltinDashboardProvider; +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; +import com.opentest.common.model.dto.DashboardConfigDto; +import com.opentest.common.model.dto.dashboard.CollectConfigDto; +import com.opentest.common.model.dto.dashboard.DashboardItemConfigDto; +import com.opentest.dashboard.api.channel.ChannelMetadata; +import com.opentest.dashboard.api.channel.SignalType; +import com.opentest.dashboard.api.pipeline.PipelineInputMode; +import com.opentest.service.grpc.core.ChannelListenerManagers; +import com.opentest.service.grpc.core.DashboardCompletionDisposition; +import com.opentest.service.grpc.core.DashboardHandlerStopPreparation; +import com.opentest.service.grpc.core.sender.GrpcWriter; +import com.opentest.service.grpc.provider.ProviderPipelineDashboardHandler; +import com.opentest.service.helper.SequenceExecutionGraphRuntimeCache; +import com.opentest.service.jni.ContinueCaptureManager; +import com.opentest.service.proto.CommonProto; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.springframework.test.util.ReflectionTestUtils.invokeMethod; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +class AutomaticGeneratorMeasurementTest { + @Test void missingOptionAndUnsupportedProvidersNeverControlGenerator() { + var generator = new Generator(); + var legacy = new Handler(1, false); + legacy.getDashboard().getDashboardItemConfig().getCollectConfig().setAutoGeneratorOn(null); + legacy.getDashboard().setProviderId(null); + var unsupported = new Handler(2, true); + unsupported.getDashboard().setProviderId(BuiltinDashboardProvider.SWEEP.getProviderId()); + var fixture = new Fixture(generator, legacy, unsupported); + fixture.prepare(legacy); fixture.prepare(unsupported); + legacy.acquire(); unsupported.acquire(); + assertNull(legacy.beginStop().getCloseFailure()); + assertNull(unsupported.beginStop().getCloseFailure()); + assertEquals(0, generator.starts); + assertEquals(0, generator.stops); + } + + @Test void scheduledPreparationDoesNotStartAndEachRepeatedRoundOwnsItsOutput() { + var generator = new Generator(); + var first = new Handler(1, true); + var fixture = new Fixture(generator, first); + fixture.prepare(first); + assertEquals(0, generator.starts); + first.acquire(); + assertEquals(1, generator.starts); + first.beginStop(); + assertEquals(1, generator.stops); + var repeated = new Handler(2, true); + fixture.prepare(repeated); + assertEquals(1, generator.starts); + repeated.acquire(); + assertEquals(2, generator.starts); + first.beginStop(); + assertTrue(generator.on, "An old round must not stop its successor"); + repeated.beginStop(); + assertEquals(2, generator.stops); + } + + @Test void overlappingOptedInRoundsKeepOutputUntilTheLastInputDrains() { + var generator = new Generator(); + var first = new Handler(1, true); + var second = new Handler(2, true); + var unchecked = new Handler(3, false); + var fixture = new Fixture(generator, first, second, unchecked); + fixture.prepare(first); fixture.prepare(second); fixture.prepare(unchecked); + first.acquire(); second.acquire(); unchecked.acquire(); + assertEquals(1, generator.starts); + first.beforeDrain = () -> assertTrue(generator.on); + second.beforeDrain = () -> assertTrue(generator.on); + first.beginStop(); + assertTrue(generator.on); + second.beginStop(); + assertFalse(generator.on); + unchecked.beginStop(); + assertEquals(1, generator.stops); + } + + @Test void manualOffDoesNotCancelCurrentRoundAndTheNextAdmissionRestartsOutput() { + var generator = new Generator(); + var first = new Handler(1, true); + var next = new Handler(2, true); + var fixture = new Fixture(generator, first, next); + fixture.prepare(first); fixture.prepare(next); + first.acquire(); generator.on = false; + assertEquals(Boolean.FALSE, first.getFinished()); + next.acquire(); + assertEquals(2, generator.starts); + first.beginStop(); next.beginStop(); + } + + @Test void cleanupDiagnosticDoesNotInvalidateTheAcquiredMeasurement() throws Exception { + var generator = new Generator(); + var error = new CryBusinessException(ErrorCode.FAILED); + generator.stopFailure = error; + var handler = new Handler(1, true); + var fixture = new Fixture(generator, handler); + fixture.prepare(handler); handler.acquire(); + fixture.manager.stop(null, DashboardCompletionDisposition.NORMAL_COMPLETE); + fixture.manager.stopCompletion().toCompletableFuture().get(3, TimeUnit.SECONDS); + assertNull(handler.finalFailure); + verify(handler.writer).sendAutomaticGeneratorError(eq(error), eq("stop"), eq(1L), eq(101L), eq(Locale.ROOT)); + } + + @Test void generatorStartFailureStopsEverySynchronizedMemberBeforeFormalAdmission() throws Exception { + var generator = new Generator(); + var error = new CryBusinessException(ErrorCode.FAILED); + generator.startFailure = error; + var first = new Handler(1, true); + var peer = new Handler(2, false); + var fixture = new Fixture(generator, first, peer); + fixture.prepare(first); fixture.prepare(peer); + assertSame(error, assertThrows(CryBusinessException.class, first::acquire)); + assertThrows(ExecutionException.class, () -> fixture.manager.stopCompletion().toCompletableFuture().get(3, TimeUnit.SECONDS)); + assertSame(error, first.finalFailure); + assertSame(error, peer.finalFailure); + assertEquals(0, first.formalStarts.get()); + assertEquals(0, peer.formalStarts.get()); + } + + @Test void concurrentFormalCallbacksWaitForGeneratorReadiness() throws Exception { + var generator = new Generator(); + generator.startEntered = new CountDownLatch(1); generator.releaseStart = new CountDownLatch(1); + var handler = new Handler(1, true); + var fixture = new Fixture(generator, handler); fixture.prepare(handler); + var first = CompletableFuture.runAsync(handler::acquire); + assertTrue(generator.startEntered.await(2, TimeUnit.SECONDS)); + var secondEntered = new CountDownLatch(1); + var second = CompletableFuture.runAsync(() -> { secondEntered.countDown(); handler.acquire(); }); + assertTrue(secondEntered.await(2, TimeUnit.SECONDS)); + try { + assertThrows(TimeoutException.class, () -> second.get(100, TimeUnit.MILLISECONDS)); + assertEquals(0, handler.formalStarts.get()); + } finally { generator.releaseStart.countDown(); } + first.get(2, TimeUnit.SECONDS); second.get(2, TimeUnit.SECONDS); + assertEquals(1, handler.formalStarts.get()); + handler.beginStop(); + } + + @Test void globalStopDuringGeneratorStartFencesLateAdmissionAndThenStopsOutput() throws Exception { + var generator = new Generator(); + generator.startEntered = new CountDownLatch(1); generator.releaseStart = new CountDownLatch(1); + var handler = new Handler(1, true); + var fixture = new Fixture(generator, handler); fixture.prepare(handler); + var starting = CompletableFuture.runAsync(handler::acquire); + assertTrue(generator.startEntered.await(2, TimeUnit.SECONDS)); + fixture.manager.stop(null, DashboardCompletionDisposition.CANCEL); + generator.releaseStart.countDown(); + assertThrows(ExecutionException.class, () -> starting.get(2, TimeUnit.SECONDS)); + fixture.manager.stopCompletion().toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(0, handler.formalStarts.get()); + assertEquals(1, generator.stops); + assertFalse(generator.on); + } + + private static final class Fixture { + final SyncMeasurementRecorderManager manager; + Fixture(Generator generator, Handler... handlers) { + manager = new SyncMeasurementRecorderManager(List.of(handlers), mock(ContinueCaptureManager.class), + mock(ChannelListenerManagers.class), null, mock(SequenceExecutionGraphRuntimeCache.class), null, null, null); + manager.setAutomaticGeneratorCommands(generator); + } + void prepare(Handler handler) { + invokeMethod(manager, "prepareHandlerForRun", new SyncMeasurementMemberRuntime(handler), handler, null); + handler.setRecordStartedFunc(handler.formalStarts::incrementAndGet); + } + } + + private static final class Handler extends ProviderPipelineDashboardHandler { + final GrpcWriter writer = mock(GrpcWriter.class); + final AtomicInteger formalStarts = new AtomicInteger(); + CryBusinessException finalFailure; + Runnable beforeDrain = () -> { }; + Handler(long id, boolean automatic) { + var collect = new CollectConfigDto(); collect.setAutoGeneratorOn(automatic); collect.setStopMethod("MANUAL"); + collect.setChannels(List.of()); collect.setExecutionChannels(List.of()); + var item = new DashboardItemConfigDto(); item.setCollectConfig(collect); + var dashboard = new DashboardConfigDto(); dashboard.setId(id); dashboard.setProjectId(7L); + dashboard.setProviderId(BuiltinDashboardProvider.FFT.getProviderId()); dashboard.setDashboardItemConfig(item); + setField(this, "channelListenerManagers", mock(ChannelListenerManagers.class)); + setDashboard(dashboard); setDashboardId(id); setRequestId(id + 100); setLocale(Locale.ROOT); setGrpcWriter(writer); + setField(this, "input", List.of(new ChannelMetadata("Ch1", SignalType.AUDIO, 48000, "FS", 1000D, 1D, null))); + setField(this, "inputMode", PipelineInputMode.DIRECT); + } + void acquire() { startFileInput(Map.of()); } + @Override public void initBaseMeasureNum() { } + @Override public void prepareStartConfiguration() { } + @Override public boolean requiresAsyncStopFinalization() { return true; } + @Override protected void closeRuntimeResourcesForStop() { beforeDrain.run(); super.closeRuntimeResourcesForStop(); } + @Override public void finishStop(DashboardHandlerStopPreparation preparation, CryBusinessException failure) { + finalFailure = failure; + } + } + + private static final class Generator implements AutomaticGeneratorSession.Commands { + volatile boolean on; + int starts, stops; + RuntimeException startFailure, stopFailure; + CountDownLatch startEntered, releaseStart; + @Override public void ensureStarted(Long projectId) { + if (startEntered != null) { + startEntered.countDown(); + try { assertTrue(releaseStart.await(3, TimeUnit.SECONDS)); } + catch (InterruptedException failure) { Thread.currentThread().interrupt(); throw new IllegalStateException(failure); } + } + if (startFailure != null) throw startFailure; + if (!on) { starts++; on = true; } + } + @Override public void stop(Long projectId, Consumer diagnostics) { + stops++; on = false; + if (stopFailure != null) diagnostics.accept(stopFailure); + } + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/provider/ProviderAutomaticGeneratorPipelineTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/provider/ProviderAutomaticGeneratorPipelineTest.java new file mode 100644 index 00000000..310e838f --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/grpc/provider/ProviderAutomaticGeneratorPipelineTest.java @@ -0,0 +1,131 @@ +package com.opentest.service.grpc.provider; + +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; +import com.opentest.dashboard.api.channel.ChannelMetadata; +import com.opentest.dashboard.api.channel.SignalType; +import com.opentest.dashboard.api.frame.ChannelFrame; +import com.opentest.dashboard.api.frame.SourceSampleRange; +import com.opentest.dashboard.api.pipeline.PipelineInputMode; +import com.opentest.dashboard.api.pipeline.ProcessorPipeline; +import com.opentest.dashboard.api.pipeline.ProcessorPipelineBuilder; +import com.opentest.dashboard.api.pipeline.ProcessorPipelineCompiler; +import com.opentest.dashboard.api.pipeline.QueueOverflowPolicy; +import com.opentest.dashboard.api.pipeline.SinkProcessor; +import com.opentest.dashboard.api.pipeline.StartControlProcessor; +import com.opentest.dashboard.api.pipeline.StopControlProcessor; +import com.opentest.service.grpc.core.sync.AutomaticGeneratorSession; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +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; +import static org.springframework.test.util.ReflectionTestUtils.invokeMethod; +import static org.springframework.test.util.ReflectionTestUtils.setField; + +class ProviderAutomaticGeneratorPipelineTest { + @Test void cancelledGeneratorAdmissionDoesNotBecomeAMeasurementFailure() throws Exception { + try (var fixture = new Fixture()) { + fixture.accept(); + assertTrue(fixture.startEntered.await(2, TimeUnit.SECONDS)); + fixture.session.cancelAdmissions(); + fixture.releaseStart.countDown(); + fixture.finished.get(3, TimeUnit.SECONDS); + assertEquals(0, fixture.measurementFailures.get()); + assertEquals(0, fixture.automaticStartFailures.get()); + assertEquals(0, fixture.formalFrames.get()); + assertFalse(fixture.handler.recordingLifecycle.startTriggered().toCompletableFuture().isDone()); + } + } + + @Test void actualGeneratorStartFailureStillFailsTheMeasurementPipeline() throws Exception { + try (var fixture = new Fixture()) { + fixture.startFailure = new CryBusinessException(ErrorCode.FAILED); + fixture.accept(); + assertTrue(fixture.startEntered.await(2, TimeUnit.SECONDS)); + fixture.releaseStart.countDown(); + fixture.finished.get(3, TimeUnit.SECONDS); + assertEquals(1, fixture.measurementFailures.get()); + assertEquals(1, fixture.automaticStartFailures.get()); + assertEquals(0, fixture.formalFrames.get()); + } + } + + @Test void nativeStartCancellationStillAbortsTheSession() throws Exception { + try (var fixture = new Fixture()) { + fixture.startFailure = new CancellationException("Native readiness was interrupted"); + fixture.accept(); + assertTrue(fixture.startEntered.await(2, TimeUnit.SECONDS)); + fixture.releaseStart.countDown(); + fixture.finished.get(3, TimeUnit.SECONDS); + assertEquals(1, fixture.measurementFailures.get()); + assertEquals(1, fixture.automaticStartFailures.get()); + assertEquals(0, fixture.formalFrames.get()); + } + } + + private static final class Fixture implements AutoCloseable { + final ProviderPipelineDashboardHandler handler = new ProviderPipelineDashboardHandler(); + final AtomicInteger measurementFailures = new AtomicInteger(); + final AtomicInteger automaticStartFailures = new AtomicInteger(); + final AtomicInteger formalFrames = new AtomicInteger(); + final CountDownLatch startEntered = new CountDownLatch(1), releaseStart = new CountDownLatch(1); + final ChannelMetadata channel = new ChannelMetadata("input", SignalType.AUDIO, 48000, "FS", 1000D, 1D, null); + final AutomaticGeneratorSession session; + final ProcessorPipeline pipeline; + final CompletableFuture finished; + volatile RuntimeException startFailure; + + Fixture() { + handler.setProcessingFailureCallback(error -> measurementFailures.incrementAndGet()); + session = new AutomaticGeneratorSession(7L, new AutomaticGeneratorSession.Commands() { + @Override public void ensureStarted(Long projectId) { + startEntered.countDown(); + try { assertTrue(releaseStart.await(3, TimeUnit.SECONDS)); } + catch (InterruptedException failure) { Thread.currentThread().interrupt(); throw new IllegalStateException(failure); } + if (startFailure != null) throw startFailure; + } + @Override public void stop(Long projectId, Consumer diagnostics) { } + }, error -> automaticStartFailures.incrementAndGet(), () -> { }); + handler.bindAutomaticGeneratorRound(session.newRound((phase, error) -> { })); + var start = new StartControlProcessor() { + @Override public void onFrame(ChannelFrame frame) { startMeasure(); context().emit(frame.retain()); } + }; + var stop = new StopControlProcessor() { + @Override public void onFrame(ChannelFrame frame) { context().emit(frame.retain()); } + }; + var sink = new SinkProcessor() { + @Override public void onFrame(ChannelFrame frame) { formalFrames.incrementAndGet(); } + }; + pipeline = ProcessorPipelineCompiler.create().compile(ProcessorPipelineBuilder.create() + .startControl(start, 2, QueueOverflowPolicy.WAIT_FOR_CAPACITY) + .stopControl(stop, 2, QueueOverflowPolicy.WAIT_FOR_CAPACITY) + .addProcessor("observed", sink).connectInput("input", sink, 2, QueueOverflowPolicy.WAIT_FOR_CAPACITY), + Set.of("input"), PipelineInputMode.CONTROLLED_REALTIME, Map.of(), + () -> invokeMethod(handler, "startFormalMeasurement")); + setField(handler, "pipeline", pipeline); + setField(handler, "inputControl", new ProviderMeasurementInputControl(List.of(), null, armed -> { })); + CompletionStage hostCompletion = invokeMethod(handler, "bindPipelineCompletion"); + finished = hostCompletion.handle((value, error) -> (Void) null).toCompletableFuture(); + } + void accept() { + pipeline.accept(ChannelFrame.of(channel, new double[]{1}, 0, new SourceSampleRange(0, 1), 48000, Optional.empty())); + } + @Override public void close() throws Exception { + releaseStart.countDown(); pipeline.stop(); + pipeline.resourcesReleased().toCompletableFuture().get(3, TimeUnit.SECONDS); + session.close(); + } + } +} diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/support/GeneratorCommandGateTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/support/GeneratorCommandGateTest.java new file mode 100644 index 00000000..39f26706 --- /dev/null +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/support/GeneratorCommandGateTest.java @@ -0,0 +1,87 @@ +package com.opentest.service.support; + +import com.opentest.common.exception.CryBusinessException; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GeneratorCommandGateTest { + @Test + void shutdownSupersedesDeferredStartsButAllowsNewStartsAfterCompletion() { + var gate = new GeneratorCommandGate(); + var commands = new ArrayList(); + var beforeCommit = gate.requestStart(1L); + gate.automaticStop(1L, () -> { + var duringStop = gate.requestStart(1L); + assertThrows(CryBusinessException.class, () -> gate.start(duringStop, () -> commands.add("on"))); + commands.add("off"); + }); + assertThrows(CryBusinessException.class, () -> gate.start(beforeCommit, () -> commands.add("stale on"))); + gate.start(gate.requestStart(1L), () -> commands.add("new on")); + assertEquals(List.of("off", "new on"), commands); + } + + @Test + void shutdownWaitsForAnAdmittedStartAndClosesAfterIt() throws Exception { + var gate = new GeneratorCommandGate(); + var starting = new CountDownLatch(1); + var finishStart = new CountDownLatch(1); + var commands = new ArrayList(); + try (var workers = Executors.newFixedThreadPool(2)) { + var start = workers.submit(() -> gate.start(gate.requestStart(1L), () -> { + starting.countDown(); + await(finishStart); + commands.add("on"); + })); + assertTrue(starting.await(3, TimeUnit.SECONDS)); + var stop = workers.submit(() -> gate.automaticStop(1L, () -> commands.add("off"))); + finishStart.countDown(); + start.get(3, TimeUnit.SECONDS); + stop.get(3, TimeUnit.SECONDS); + } finally { + finishStart.countDown(); + } + assertEquals(List.of("on", "off"), commands); + } + + @Test + void manualOffAndParameterEditsRemainAllowedAndProjectsAreIndependent() { + var gate = new GeneratorCommandGate(); + var commands = new ArrayList(); + var otherProject = gate.requestStart(2L); + gate.automaticStop(1L, () -> { + gate.execute(1L, () -> commands.add("manual off")); + gate.execute(1L, () -> commands.add("edit")); + gate.start(otherProject, () -> commands.add("other on")); + }); + assertEquals(List.of("manual off", "edit", "other on"), commands); + } + + @Test + void failedStopDoesNotPermanentlyBlockManualCommands() { + var gate = new GeneratorCommandGate(); + assertThrows(IllegalStateException.class, () -> gate.automaticStop(1L, () -> { + throw new IllegalStateException("stop failed"); + })); + var commands = new ArrayList(); + gate.start(gate.requestStart(1L), () -> commands.add("on")); + assertEquals(List.of("on"), commands); + } + + private static void await(CountDownLatch latch) { + try { + assertTrue(latch.await(3, TimeUnit.SECONDS)); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(failure); + } + } +} diff --git a/apps/frontend/src/composables/dashboard/__tests__/use-dashboard-grpc-runtime.test.ts b/apps/frontend/src/composables/dashboard/__tests__/use-dashboard-grpc-runtime.test.ts index 6f418ec2..e7ad7126 100644 --- a/apps/frontend/src/composables/dashboard/__tests__/use-dashboard-grpc-runtime.test.ts +++ b/apps/frontend/src/composables/dashboard/__tests__/use-dashboard-grpc-runtime.test.ts @@ -1,4 +1,5 @@ import { flushPromises, mount } from '@vue/test-utils' +import { jsonToStruct } from '@/libs/grpc/struct' import type { GrpcStreamLifecycleCallbacks } from '@/composables/grpc/types' import { defineComponent, nextTick, ref } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -16,6 +17,8 @@ const mocks = vi.hoisted(() => { } return { + notification: vi.fn(), + refreshGeneratorState: vi.fn(), capturedOptions: null as Record | null, grpcState, logger: { @@ -38,6 +41,12 @@ vi.mock('@/composables/grpc/use-grpc-stream', () => ({ } })) +vi.mock('@/stores/generator', () => ({ + useGeneratorStore: () => ({ refreshAutomaticGeneratorRuntimeState: mocks.refreshGeneratorState }) +})) + +vi.mock('element-plus', () => ({ ElNotification: mocks.notification })) + vi.mock('@/utils/logger', () => ({ default: mocks.logger })) @@ -104,6 +113,46 @@ describe('useDashboardGrpcRuntime', () => { wrapper.unmount() }) + it('refreshes the project Generator state on an automatic output change', async () => { + const onExecutionMessage = vi.fn() + const { api, wrapper } = await createHarness({ onExecutionMessage }) + await api.handleGrpcMessage({ response: 'executionMessage', executionMessage: { + success: true, payload: jsonToStruct({ kind: 'autoGeneratorStateChanged', projectId: 'project-1' }) + } }) + expect(mocks.refreshGeneratorState).toHaveBeenCalledWith('project-1') + expect(onExecutionMessage).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it('reports Generator cleanup errors without failing completed Measurement results or closing the stream', async () => { + const onTaskFailed = vi.fn(), onExecFinish = vi.fn(), onExecutionMessage = vi.fn() + const { api, wrapper } = await createHarness({ onTaskFailed, onExecFinish, onExecutionMessage }) + await api.handleGrpcMessage({ response: 'executionMessage', executionMessage: { + dashboardId: 'dashboard-1', requestId: 'request-1', success: true, + payload: jsonToStruct({ kind: 'autoGeneratorError', phase: 'stop', errorCode: 123, errorMsg: 'Auto Generator stop: device unavailable' }) + } }) + expect(mocks.notification).toHaveBeenCalledWith(expect.objectContaining({ message: 'Auto Generator stop: device unavailable (123)', type: 'error' })) + expect(onTaskFailed).not.toHaveBeenCalled() + expect(onExecFinish).not.toHaveBeenCalled() + expect(onExecutionMessage).not.toHaveBeenCalled() + expect(mocks.grpcState.stopAndDisconnect).not.toHaveBeenCalled() + await api.handleGrpcMessage({ response: 'taskOperationMsg', taskOperationMsg: { + operationType: 'TOTAL_TASK_STOP', success: true, dashboardId: 'dashboard-1', requestId: 'request-1' + } }) + expect(onExecFinish).toHaveBeenCalled() + wrapper.unmount() + }) + + it('ignores Generator diagnostics belonging to another execution', async () => { + const { api, wrapper } = await createHarness() + await api.handleGrpcMessage({ response: 'executionMessage', executionMessage: { + dashboardId: 'dashboard-1', requestId: 'old-request', success: true, + payload: { kind: 'autoGeneratorError', errorMsg: 'old stop failure' } + } }) + expect(mocks.notification).not.toHaveBeenCalled() + wrapper.unmount() + }) + it('does not start execution or recording callbacks for a scheduled waiting confirmation', async () => { const onExecStart = vi.fn(), onTaskStart = vi.fn(), onExecFinish = vi.fn(), onTaskFailed = vi.fn() const { wrapper } = await createHarness({ onExecStart, onTaskStart, onExecFinish, onTaskFailed }) diff --git a/apps/frontend/src/composables/dashboard/use-dashboard-grpc-runtime.ts b/apps/frontend/src/composables/dashboard/use-dashboard-grpc-runtime.ts index cf6cc6e4..6a00bdd0 100644 --- a/apps/frontend/src/composables/dashboard/use-dashboard-grpc-runtime.ts +++ b/apps/frontend/src/composables/dashboard/use-dashboard-grpc-runtime.ts @@ -1,3 +1,7 @@ +import { ElNotification } from 'element-plus' +import { getEventErrorMessage } from '@/utils/error' +import { structToJson } from '@/libs/grpc/struct' +import { useGeneratorStore } from '@/stores/generator' import { computed, getCurrentInstance, onUnmounted, toValue, watch, type Ref } from 'vue' import { useGrpcStream, GRPC_SUCCESS_OPERATION_TYPE } from '@/composables/grpc/use-grpc-stream' import type { GrpcBatchContext, GrpcStartOptions } from '@/composables/grpc/types' @@ -309,9 +313,26 @@ export function useDashboardGrpcRuntime) + case 'executionMessage': { + const payload = data.payload && typeof data.payload === 'object' ? structToJson(data.payload) : undefined + if (payload && 'kind' in payload && payload.kind === 'autoGeneratorStateChanged') { + if ('projectId' in payload && typeof payload.projectId === 'string' && payload.projectId) { + useGeneratorStore().refreshAutomaticGeneratorRuntimeState(payload.projectId) + } + break + } + if (payload && 'kind' in payload && payload.kind === 'autoGeneratorError') { + if (!matchesCurrentDashboard(data) || !matchesCurrentRequest(data)) break + if (!('errorMsg' in payload) || typeof payload.errorMsg !== 'string') break + const code = 'errorCode' in payload && (typeof payload.errorCode === 'number' || typeof payload.errorCode === 'string') + ? payload.errorCode + : undefined + ElNotification({ type: 'error', title: 'Auto Generator', message: getEventErrorMessage(code, payload.errorMsg) }) + break + } + await options.onExecutionMessage?.(data) break + } case 'taskOperationMsg': await processTaskOperation(data as TaskOperationMessage) break diff --git a/apps/frontend/src/constants/__tests__/config-dashboard.test.ts b/apps/frontend/src/constants/__tests__/config-dashboard.test.ts index 15670bce..ce903e0e 100644 --- a/apps/frontend/src/constants/__tests__/config-dashboard.test.ts +++ b/apps/frontend/src/constants/__tests__/config-dashboard.test.ts @@ -123,11 +123,18 @@ describe('config and dashboard constants', () => { expect(getDefaultRecordConfig()).toMatchObject({ startMethod: START_METHOD.MANUAL, stopMethod: STOP_METHOD.TIME, + autoGeneratorOn: false, repeatUntilStop: false, testIntervalTimeUnit: TIME_UNIT_TYPE.S }) }) + it.each([undefined, null, false, true])('defaults automatic Generator control without opting in legacy value %s', value => { + const config: Parameters[0] = { autoGeneratorOn: value } + ensureMeasurementControlDefaults(config) + expect(config.autoGeneratorOn).toBe(value === true) + }) + it('normalizes legacy free-run start method to time', () => { const config: Parameters[0] = { startMethod: 'FREE_RUN' diff --git a/apps/frontend/src/constants/dashboard/colllect.ts b/apps/frontend/src/constants/dashboard/colllect.ts index 4b0907d4..72414144 100644 --- a/apps/frontend/src/constants/dashboard/colllect.ts +++ b/apps/frontend/src/constants/dashboard/colllect.ts @@ -147,6 +147,7 @@ type MeasurementCollectConfig = { recordMode?: string recordStartTime?: string repeatRecord?: boolean + autoGeneratorOn?: boolean | null repeatUntilStop?: boolean repeatTimes?: number testInterval?: number | null @@ -359,6 +360,7 @@ export function getDefaultRecordConfig() { recordMode: RECORD_MODE_ENUM.MANUAL, recordStartTime: '00:00:00', repeatRecord: false, + autoGeneratorOn: false, repeatUntilStop: false, repeatTimes: 1, testInterval: 0, @@ -596,6 +598,7 @@ export function ensureMeasurementControlDefaults( : RECORD_MODE_ENUM.MANUAL config.recordStartTime ||= '00:00:00' config.repeatRecord ??= false + config.autoGeneratorOn ??= false config.repeatUntilStop ??= false config.repeatTimes ??= 1 config.testInterval ??= 0 diff --git a/apps/frontend/src/locales/__tests__/dashboard-locale.test.ts b/apps/frontend/src/locales/__tests__/dashboard-locale.test.ts index 3cfcbfeb..0ea8648a 100644 --- a/apps/frontend/src/locales/__tests__/dashboard-locale.test.ts +++ b/apps/frontend/src/locales/__tests__/dashboard-locale.test.ts @@ -7,6 +7,7 @@ import frMessages from '../fr-FR' import jaMessages from '../ja-JP' import koMessages from '../ko-KR' import ruMessages from '../ru-RU' +import trMessages from '../tr-TR' import zhCnMessages from '../zh-CN' import zhTwMessages from '../zh-TW' @@ -19,7 +20,8 @@ const localeCases = [ ['fr-FR', frMessages], ['ja-JP', jaMessages], ['ko-KR', koMessages], - ['ru-RU', ruMessages] + ['ru-RU', ruMessages], + ['tr-TR', trMessages] ] as const const startMethodOptionKeys = ['MANUAL', 'TIME', 'TRIGGER'] as const @@ -100,6 +102,13 @@ function getBkFftWindowTypeOptions(messages: { } describe('dashboard locale resources', () => { + it('provides the automatic Generator setting label in every locale', () => { + expect(clientEnMessages.fft.setting.autoGeneratorOn).toBe('Auto Generator On') + localeCases.forEach(([localeName, messages]) => { + expect(messages.fft.setting.autoGeneratorOn.trim(), `${localeName} fft.setting.autoGeneratorOn`).not.toBe('') + }) + }) + it('provides Scope Cycle Reference labels in every locale', () => { expect(clientEnMessages.chart?.config?.cycleReference).toBe('Cycle Reference') expect(clientEnMessages.chart?.config?.auto).toBe('Auto') diff --git a/apps/frontend/src/locales/de-DE.ts b/apps/frontend/src/locales/de-DE.ts index 456058d1..ebca1244 100644 --- a/apps/frontend/src/locales/de-DE.ts +++ b/apps/frontend/src/locales/de-DE.ts @@ -4173,6 +4173,7 @@ guidance: { triggerName: 'Triggername', scheduledStartTime: 'Geplante Startzeit', scheduledTime: 'Geplante Zeit', + autoGeneratorOn: 'Generator automatisch einschalten', repeat: 'Wiederholen', channelLevelFiltering: 'Kanalbasierte Filterung', channelFilters: 'Kanalfilter', diff --git a/apps/frontend/src/locales/en.ts b/apps/frontend/src/locales/en.ts index 362b88d5..ae642564 100644 --- a/apps/frontend/src/locales/en.ts +++ b/apps/frontend/src/locales/en.ts @@ -4162,6 +4162,7 @@ guidance: { triggerName: 'Trigger Name', scheduledStartTime: 'Scheduled Start Time', scheduledTime: 'Scheduled Time', + autoGeneratorOn: 'Auto Generator On', repeat: 'Repeat', channelLevelFiltering: 'Channel-level filtering', channelFilters: 'Channel Filters', diff --git a/apps/frontend/src/locales/es-ES.ts b/apps/frontend/src/locales/es-ES.ts index 9aaed74b..e3d0fe93 100644 --- a/apps/frontend/src/locales/es-ES.ts +++ b/apps/frontend/src/locales/es-ES.ts @@ -4172,6 +4172,7 @@ guidance: { triggerName: 'Nombre del Disparo', scheduledStartTime: 'Hora de Inicio Programada', scheduledTime: 'Hora Programada', + autoGeneratorOn: 'Activar generador automáticamente', repeat: 'Repetir', channelLevelFiltering: 'Filtrado a nivel de canal', channelFilters: 'Filtros de Canal', diff --git a/apps/frontend/src/locales/fr-FR.ts b/apps/frontend/src/locales/fr-FR.ts index b4e35c35..8859e739 100644 --- a/apps/frontend/src/locales/fr-FR.ts +++ b/apps/frontend/src/locales/fr-FR.ts @@ -4176,6 +4176,7 @@ guidance: { triggerName: 'Nom du déclencheur', scheduledStartTime: 'Heure de début programmée', scheduledTime: 'Heure programmée', + autoGeneratorOn: 'Activer automatiquement le générateur', repeat: 'Répéter', channelLevelFiltering: 'Filtrage au niveau du canal', channelFilters: 'Filtres de canal', diff --git a/apps/frontend/src/locales/ja-JP.ts b/apps/frontend/src/locales/ja-JP.ts index 82cb05ff..5b27b2ed 100644 --- a/apps/frontend/src/locales/ja-JP.ts +++ b/apps/frontend/src/locales/ja-JP.ts @@ -4140,6 +4140,7 @@ guidance: { triggerName: 'トリガー名', scheduledStartTime: '定時開始時刻', scheduledTime: '予約時刻', + autoGeneratorOn: '信号発生器を自動でオン', repeat: '繰り返し', channelLevelFiltering: 'チャンネルレベルフィルタリング', channelFilters: 'チャンネルフィルター', diff --git a/apps/frontend/src/locales/ko-KR.ts b/apps/frontend/src/locales/ko-KR.ts index 04d79508..c5936f12 100644 --- a/apps/frontend/src/locales/ko-KR.ts +++ b/apps/frontend/src/locales/ko-KR.ts @@ -4124,6 +4124,7 @@ guidance: { triggerName: '트리거 이름', scheduledStartTime: '예약 시작 시간', scheduledTime: '예약 시간', + autoGeneratorOn: '신호 발생기 자동 켜기', repeat: '반복', channelLevelFiltering: '채널 레벨 필터링', channelFilters: '채널 필터', diff --git a/apps/frontend/src/locales/ru-RU.ts b/apps/frontend/src/locales/ru-RU.ts index b3cb461f..34d7af98 100644 --- a/apps/frontend/src/locales/ru-RU.ts +++ b/apps/frontend/src/locales/ru-RU.ts @@ -4152,6 +4152,7 @@ guidance: { triggerName: 'Имя триггера', scheduledStartTime: 'Время начала по расписанию', scheduledTime: 'Время по расписанию', + autoGeneratorOn: 'Автоматическое включение генератора', repeat: 'Повтор', channelLevelFiltering: 'Фильтрация на уровне канала', channelFilters: 'Фильтры каналов', diff --git a/apps/frontend/src/locales/tr-TR.ts b/apps/frontend/src/locales/tr-TR.ts index a1a933f1..3c397510 100644 --- a/apps/frontend/src/locales/tr-TR.ts +++ b/apps/frontend/src/locales/tr-TR.ts @@ -4165,6 +4165,7 @@ averagingMode: 'Ortalama Alma Modu', triggerName: 'Tetikleme Adı', scheduledStartTime: 'Zamanlanmış Başlatma Zamanı', scheduledTime: 'Zamanlanmış Zaman', + autoGeneratorOn: 'Jeneratörü otomatik aç', repeat: 'Tekrarla', channelLevelFiltering: 'Kanal düzeyinde filtreleme', channelFilters: 'Kanal Filtreleri', diff --git a/apps/frontend/src/locales/zh-CN.ts b/apps/frontend/src/locales/zh-CN.ts index b9e34cb7..4f44d00e 100644 --- a/apps/frontend/src/locales/zh-CN.ts +++ b/apps/frontend/src/locales/zh-CN.ts @@ -4192,6 +4192,7 @@ guidance: { triggerName: '触发名称', scheduledStartTime: '计划开始时间', scheduledTime: '计划时间', + autoGeneratorOn: '自动开启信号发生器', repeat: '重复', channelLevelFiltering: '通道级滤波', channelFilters: '通道滤波器', diff --git a/apps/frontend/src/locales/zh-TW.ts b/apps/frontend/src/locales/zh-TW.ts index f6444537..16b3832d 100644 --- a/apps/frontend/src/locales/zh-TW.ts +++ b/apps/frontend/src/locales/zh-TW.ts @@ -4133,6 +4133,7 @@ guidance: { triggerName: '觸發名稱', scheduledStartTime: '排程啟動時間', scheduledTime: '排程時間', + autoGeneratorOn: '自動開啟訊號產生器', repeat: '重複', channelLevelFiltering: '通道級濾波', channelFilters: '通道濾波器', diff --git a/apps/frontend/src/modules/shared/dashboard/__tests__/measurement-control.test.ts b/apps/frontend/src/modules/shared/dashboard/__tests__/measurement-control.test.ts index bc9642d4..fdd8e181 100644 --- a/apps/frontend/src/modules/shared/dashboard/__tests__/measurement-control.test.ts +++ b/apps/frontend/src/modules/shared/dashboard/__tests__/measurement-control.test.ts @@ -1,6 +1,7 @@ import { flushPromises, mount } from '@vue/test-utils' import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, defineComponent, h, nextTick, reactive, ref, toRefs, watch, type PropType, type Ref } from 'vue' +import { ElCheckbox } from 'element-plus' import { START_METHOD, STOP_METHOD, @@ -26,6 +27,7 @@ interface MountComponentOptions { testIntervalTimeUnit?: NonNullable['testIntervalTimeUnit'] averages?: number naturalCompletion?: boolean + showAutoGenerator?: boolean disabled?: boolean allowedStopMethods?: string[] defaultStopMethod?: string @@ -159,7 +161,7 @@ const blockStub = name => setup(props, { attrs, slots, expose }) { if (name === 'ElForm') expose({ clearValidate: vi.fn(), - validate: vi.fn(async (callback?: (valid: boolean) => void) => { callback?.(true); return true }) + validate: vi.fn(async (callback?: (_valid: boolean) => void) => { callback?.(true); return true }) }) return () => h('div', attrs, [ @@ -379,6 +381,7 @@ describe('MeasurementControl trigger editor', () => { testIntervalTimeUnit = 'ms', averages = 3, naturalCompletion = false, + showAutoGenerator = false, disabled = false, allowedStopMethods, defaultStopMethod, @@ -413,6 +416,7 @@ describe('MeasurementControl trigger editor', () => { defaultStopMethod, dataTestidPrefix, naturalCompletion, + showAutoGenerator, historyMode }, global: { @@ -446,7 +450,7 @@ describe('MeasurementControl trigger editor', () => { ElSelect: ElSelectStub, ElOption: ElOptionStub, ElInput: passthroughStub('ElInput'), - ElCheckbox: passthroughStub('ElCheckbox'), + ElCheckbox, ElCollapse: passthroughStub('ElCollapse'), ElCollapseItem: passthroughStub('ElCollapseItem'), ElTimePicker: passthroughStub('ElTimePicker') @@ -455,6 +459,69 @@ describe('MeasurementControl trigger editor', () => { }) } + it('keeps automatic Generator control hidden unless the host enables it', () => { + const wrapper = mountComponent({ dataTestidPrefix: 'fft' }) + expect(wrapper.find('[data-testid="fft-auto-generator-on"]').exists()).toBe(false) + wrapper.unmount() + }) + + it.each([undefined, null, false, true])('shows the saved automatic Generator preference %s', value => { + const collectConfig: DashboardItemConfigDto['collectConfig'] = { autoGeneratorOn: value } + const wrapper = mountComponent({ showAutoGenerator: true, collectConfig }) + const checkbox = wrapper.get('[data-testid="measurement-control-auto-generator-on"] input') + expect(checkbox.element.checked).toBe(value === true) + wrapper.unmount() + }) + + it('retains checked and unchecked edits after the form is saved and loaded', async () => { + const collectConfig: DashboardItemConfigDto['collectConfig'] = {} + const wrapper = mountComponent({ showAutoGenerator: true, collectConfig }) + const checkbox = wrapper.get('[data-testid="measurement-control-auto-generator-on"] input') + expect(checkbox.element.checked).toBe(false) + await checkbox.setValue(true) + expect(collectConfig.autoGeneratorOn).toBe(true) + const saved: DashboardItemConfigDto = JSON.parse(JSON.stringify(wrapper.props('form'))) + wrapper.unmount() + + const reloaded = mountComponent({ showAutoGenerator: true, collectConfig: saved.collectConfig }) + const reloadedCheckbox = reloaded.get('[data-testid="measurement-control-auto-generator-on"] input') + expect(reloadedCheckbox.element.checked).toBe(true) + await reloadedCheckbox.setValue(false) + expect(saved.collectConfig?.autoGeneratorOn).toBe(false) + reloaded.unmount() + }) + + it.each([undefined, false, true])('shows the read-only historical preference %s without changing the snapshot', async value => { + const liveConfig: DashboardItemConfigDto['collectConfig'] = { autoGeneratorOn: value !== true } + const snapshot = Object.freeze(value === undefined ? {} : { autoGeneratorOn: value }) + const wrapper = mountComponent({ + collectConfig: liveConfig, + showAutoGenerator: true, + providedHistoryMode: true, + providedSnapshotCollectConfig: snapshot + }) + const field = wrapper.get('[data-testid="measurement-control-auto-generator-on"]') + const checkbox = field.get('input') + expect(checkbox.element.checked).toBe(value === true) + expect(checkbox.element.disabled).toBe(true) + field.getComponent(ElCheckbox).vm.$emit('update:modelValue', value !== true) + await nextTick() + expect(liveConfig.autoGeneratorOn).toBe(value !== true) + expect(snapshot).toEqual(value === undefined ? {} : { autoGeneratorOn: value }) + wrapper.unmount() + }) + + it('rejects automatic Generator edits while the measurement settings are disabled', async () => { + const collectConfig = { autoGeneratorOn: false } + const wrapper = mountComponent({ showAutoGenerator: true, disabled: true, collectConfig }) + const field = wrapper.get('[data-testid="measurement-control-auto-generator-on"]') + expect(field.get('input').element.disabled).toBe(true) + field.getComponent(ElCheckbox).vm.$emit('update:modelValue', true) + await nextTick() + expect(collectConfig.autoGeneratorOn).toBe(false) + wrapper.unmount() + }) + it('reenables real measurement controls only after the current dashboard is restored from multi-history', async () => { vi.useFakeTimers() try { diff --git a/apps/frontend/src/modules/shared/dashboard/measurement-control.vue b/apps/frontend/src/modules/shared/dashboard/measurement-control.vue index 952cef4c..92585b89 100644 --- a/apps/frontend/src/modules/shared/dashboard/measurement-control.vue +++ b/apps/frontend/src/modules/shared/dashboard/measurement-control.vue @@ -133,6 +133,19 @@ /> + + + {{ $t('fft.setting.autoGeneratorOn') }} + + + (), { showRecordDuration: true, showStopMethod: true, showMore: true, + showAutoGenerator: false, naturalCompletion: false, projectId: '', dataTestidPrefix: 'measurement-control' @@ -272,6 +287,12 @@ const collectConfig = computed(() => props.form?.colle const SnapshotCollectConfig = computed( () => unref(ProvidedSnapshotCollectConfig) ?? collectConfig.value ) +const AutoGeneratorOn = computed({ + get: () => (HistorySnapshotMode.value ? SnapshotCollectConfig.value : collectConfig.value).autoGeneratorOn === true, + set: (value: boolean) => { + if (!ControlDisabled.value && props.showAutoGenerator) collectConfig.value.autoGeneratorOn = value + } +}) const CurrentProjectId = computed(() => props.projectId || projectStore.projectId || '') const startMethodOptions = computed(() => getStartMethodOptions(props.allowedStartMethods)) const allowedStopMethods = computed(() => props.allowedStopMethods || props.allowedStartMethods) diff --git a/apps/frontend/src/plugin-host/measure-settings.ts b/apps/frontend/src/plugin-host/measure-settings.ts index d6fe82ac..6438f693 100644 --- a/apps/frontend/src/plugin-host/measure-settings.ts +++ b/apps/frontend/src/plugin-host/measure-settings.ts @@ -54,6 +54,8 @@ import { createSettingsProjection } from './measure-configuration' import { createPluginDataScope } from './data-sources' import { pluginChartRegistry } from './shared-chart-registry' +const autoGeneratorScenes = new Set(['fft', 'octave', 'soundQuality', 'soundLevelMeter', 'vibration']) + export function createMeasureSettingsContext( entry: RegisteredContribution, provider: DashboardProviderDescriptor, @@ -82,6 +84,13 @@ export function createMeasureSettingsContext( ) as MeasureSettingsContext['charts'] const components = { ...workspaceComponents, + MeasurementControl: defineComponent({ + name: 'FrameworkMeasurementControl', + inheritAttrs: false, + setup(_props, { attrs, slots }) { + return () => h(MeasurementControl, { ...attrs, showAutoGenerator: autoGeneratorScenes.has(provider.scene) }, slots) + } + }), ElButton, ElCheckbox, ElCollapse, @@ -248,6 +257,7 @@ export function createMeasureSettingsAdapter( form: props.form, disabled: props.disabled || props.reanalysisMode, projectId: props.projectId, + showAutoGenerator: autoGeneratorScenes.has(provider.scene), dataTestidPrefix: provider.scene }) } diff --git a/apps/frontend/src/plugin-host/tests/measure-settings.test.ts b/apps/frontend/src/plugin-host/tests/measure-settings.test.ts index b2c95347..5124cfe6 100644 --- a/apps/frontend/src/plugin-host/tests/measure-settings.test.ts +++ b/apps/frontend/src/plugin-host/tests/measure-settings.test.ts @@ -3,9 +3,10 @@ import { mount } from '@vue/test-utils' import { defineAsyncComponent, defineComponent, h, nextTick, reactive, ref } from 'vue' import type { DashboardItemConfigDto } from '@/services/dashboard.types' import DcChannelSelect from '@/modules/shared/dc-channel-select/index.vue' +import { MeasurementControl } from '@/modules/shared/dashboard' import type { DashboardProviderDescriptor } from '../api' import type { RegisteredContribution } from '../registry' -import { createMeasureSettingsAdapter, createMeasureWorkspaceAdapter } from '../measure-settings' +import { createMeasureSettingsAdapter, createMeasureSettingsContext, createMeasureWorkspaceAdapter } from '../measure-settings' const lifecycle = vi.hoisted(() => ({ dispose: vi.fn() })) vi.mock('../workspace-context', async () => { @@ -27,7 +28,10 @@ vi.mock('element-plus', () => ({ ElScrollbar: {}, ElSwitch: {}, ElTabPane: {}, ElTabs: {} })) vi.mock('lucide-vue-next', () => ({ Settings: {} })) -vi.mock('@/modules/shared/dashboard', () => ({ MeasurementControl: {}, MeasureLimitEditorEntry: {} })) +vi.mock('@/modules/shared/dashboard', () => ({ + MeasurementControl: { name: 'MeasurementControl', props: ['showAutoGenerator', 'disabled', 'dataTestidPrefix'], render: () => null }, + MeasureLimitEditorEntry: {} +})) vi.mock('@/components/ui/dc-input-number/index.vue', () => ({ default: {} })) vi.mock('@/modules/shared/dc-simple-select/index.vue', () => ({ default: {} })) vi.mock('@/components/ui/dc-autocomplete/number-version.vue', () => ({ default: {} })) @@ -44,7 +48,7 @@ describe('measure settings adapter', () => { const Settings = defineComponent({ props: ['frameworkConfig', 'config', 'inputChannelIds', 'historyReadonly', 'reanalysisMode', 'disabled'], emits: ['update:frameworkConfig'], - setup(_props, { slots }) { return () => h('div', slots['input-channels']?.()) } + setup(_props, { slots }) { return () => h('div', [slots['input-channels']?.(), slots['measurement-control']?.()]) } }) const provider = { scene: 'fft', configurationKey: 'fftConfig' } as DashboardProviderDescriptor const entry = { @@ -52,6 +56,36 @@ describe('measure settings adapter', () => { } as unknown as RegisteredContribution const Adapter = createMeasureSettingsAdapter(entry, provider) + it.each([ + ['fft', true], ['octave', true], ['soundQuality', true], ['soundLevelMeter', true], ['vibration', true], + ['sweep', false], ['soundPowerTesting', false], ['rt60', false], ['monitor', false], ['SEQUENCE', false] + ] as const)('enables the host automatic Generator option for %s only when supported', (scene, showAutoGenerator) => { + const SceneAdapter = createMeasureSettingsAdapter(entry, { ...provider, scene }) + const wrapper = mount(SceneAdapter, { props: { form: { collectConfig: {} } } }) + expect(wrapper.getComponent(MeasurementControl).props('showAutoGenerator')).toBe(showAutoGenerator) + wrapper.unmount() + }) + + it.each([ + ['fft', true], ['octave', true], ['soundQuality', true], ['soundLevelMeter', true], ['vibration', true], + ['sweep', false], ['soundPowerTesting', false], ['rt60', false], ['monitor', false], ['SEQUENCE', false] + ] as const)('uses the provider scene for direct %s Measurement Control consumers', (scene, showAutoGenerator) => { + const DirectConsumer = defineComponent({ + setup() { + const context = createMeasureSettingsContext(entry, { ...provider, scene }) + return () => h(context.components.MeasurementControl, { + disabled: true, showAutoGenerator: !showAutoGenerator, dataTestidPrefix: 'unrelated-prefix' + }) + } + }) + const wrapper = mount(DirectConsumer) + const control = wrapper.getComponent(MeasurementControl) + expect(control.props('showAutoGenerator')).toBe(showAutoGenerator) + expect(control.props('disabled')).toBe(true) + expect(control.props('dataTestidPrefix')).toBe('unrelated-prefix') + wrapper.unmount() + }) + it('emits framework edits to the parent without mutating its input or replacing other providers', async () => { const original: DashboardItemConfigDto = { collectConfig: { inputChannels: ['Ch1'], stopMethod: 'TIME' }, @@ -127,6 +161,7 @@ describe('measure settings adapter', () => { expect(settings.props()).toMatchObject({ historyReadonly: true, reanalysisMode: true, disabled: false }) const channels = wrapper.getComponent(DcChannelSelect) expect(channels.props('disabled')).toBe(true) + expect(wrapper.getComponent(MeasurementControl).props('disabled')).toBe(true) channels.vm.$emit('update:modelValue', ['Ch2']) settings.vm.$emit('update:frameworkConfig', { collectConfig: { inputChannels: ['Ch2'], acquisitionTime: 20, diff --git a/apps/frontend/src/stores/__tests__/generator.test.ts b/apps/frontend/src/stores/__tests__/generator.test.ts index 3867f6ac..fb28619d 100644 --- a/apps/frontend/src/stores/__tests__/generator.test.ts +++ b/apps/frontend/src/stores/__tests__/generator.test.ts @@ -170,6 +170,25 @@ describe('generator store', () => { store.stopGeneratorRuntimeSync() }) + it('refreshes a locally Off switch after automatic start and lets the operator turn it off', async () => { + const store = await createStore() + store.startGeneratorRuntimeSync('project-1') + await flushPendingWork() + expect(store.generatorEnabled).toBe(false) + + store.refreshAutomaticGeneratorRuntimeState('other-project') + expect(mocks.apiGet).toHaveBeenCalledTimes(1) + mocks.apiGet.mockResolvedValueOnce(runtimeResult(true)) + store.refreshAutomaticGeneratorRuntimeState('project-1') + await flushPendingWork() + expect(store.generatorEnabled).toBe(true) + + await store.switchGeneratorEnabled(false) + expect(mocks.apiPost).toHaveBeenCalledWith('/v1/project/generator/stop', { projectId: 'project-1' }) + expect(store.generatorEnabled).toBe(false) + store.stopGeneratorRuntimeSync() + }) + it('pauses runtime queries during a save and ignores the interrupted response', async () => { const oldQuery = deferred>() const saving = deferred<{ code: number }>() diff --git a/apps/frontend/src/stores/generator.ts b/apps/frontend/src/stores/generator.ts index c5f2f2da..ca815c78 100644 --- a/apps/frontend/src/stores/generator.ts +++ b/apps/frontend/src/stores/generator.ts @@ -422,6 +422,15 @@ export const useGeneratorStore = defineStore('generator', () => { queryGeneratorRuntimeState() } + function refreshAutomaticGeneratorRuntimeState(targetProjectId: string) { + if (runtimeProjectId !== targetProjectId) return + if (runtimeTimer !== null) { + clearTimeout(runtimeTimer) + runtimeTimer = null + } + resumeGeneratorRuntimeSync() + } + function startGeneratorRuntimeSync(targetProjectId: string) { if (runtimeProjectId === targetProjectId) return stopGeneratorRuntimeSync() @@ -713,6 +722,7 @@ export const useGeneratorStore = defineStore('generator', () => { switchGeneratorEnabled, saveGeneratorConfig, reloadGeneratorConfig, + refreshAutomaticGeneratorRuntimeState, startGeneratorRuntimeSync, stopGeneratorRuntimeSync } diff --git a/cli/src/opentest_cli/resources/plugin-development/platform-communication/v1/http/models/dashboard.types.ts b/cli/src/opentest_cli/resources/plugin-development/platform-communication/v1/http/models/dashboard.types.ts index fe5fd3df..3cd85941 100644 --- a/cli/src/opentest_cli/resources/plugin-development/platform-communication/v1/http/models/dashboard.types.ts +++ b/cli/src/opentest_cli/resources/plugin-development/platform-communication/v1/http/models/dashboard.types.ts @@ -215,6 +215,7 @@ export interface DashboardItemConfigDto { triggerConfigs?: TriggerConfigDto[] recordStartTime?: string repeatRecord?: boolean + autoGeneratorOn?: boolean | null repeatUntilStop?: boolean repeatTimes?: number testInterval?: number diff --git a/sdks/client/typescript/packages/generated/src/index.ts b/sdks/client/typescript/packages/generated/src/index.ts index 17174b1b..cc2e1f74 100644 --- a/sdks/client/typescript/packages/generated/src/index.ts +++ b/sdks/client/typescript/packages/generated/src/index.ts @@ -91,7 +91,7 @@ export const PROTOCOL_FILE_HASHES = { "http/models/api.types.ts": "76c9f41216061d324df538008154251f9917e94fb1f1baf3612e5ba720c3f7ad", "http/models/base.types.ts": "c9b9574255daf9b66e33cb34c962bf77904fda2530fbc0db87ab706bcbeb2e32", "http/models/common.types.ts": "d739cb1544523744b96c7acd37c88d59837f3a35a41041efd0b05da637a0f6c8", - "http/models/dashboard.types.ts": "d4ab310e95156ac3f3573d380d9db53601f9ec7b7fbc0468da6ee262e27f6a79", + "http/models/dashboard.types.ts": "2cbc1ac74f584532040c4e28d33d205c0651d018a6316ca90d38fbf9e4d343e7", "http/models/device.types.ts": "39300f9b7c3010150468bebc57663861a5daa9633220818d098d4840d8df95cd", "http/models/project.types.ts": "2a6bffecb28f8def1179412f40c8174347827a1c124bad64ad1e3d01c9f91318", "http/models/sequence.types.ts": "a3ca98ea572178cfe6030a373a15961ee5202303181de4158b09eb76a045838c", diff --git a/sdks/client/typescript/packages/generated/src/models/dashboard.types.ts b/sdks/client/typescript/packages/generated/src/models/dashboard.types.ts index 9e88f5cc..6631af80 100644 --- a/sdks/client/typescript/packages/generated/src/models/dashboard.types.ts +++ b/sdks/client/typescript/packages/generated/src/models/dashboard.types.ts @@ -216,6 +216,7 @@ export interface DashboardItemConfigDto { triggerConfigs?: TriggerConfigDto[] recordStartTime?: string repeatRecord?: boolean + autoGeneratorOn?: boolean | null repeatUntilStop?: boolean repeatTimes?: number testInterval?: number From 100783d07103642af490f5abbda00a3b06ee7edc Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 08:50:08 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(measure):=20=E9=81=BF=E5=85=8D=E5=86=99?= =?UTF-8?q?=E5=85=A5=20Monitor=20=E7=9A=84=20Auto=20Generator=20=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/constants/__tests__/config-dashboard.test.ts | 7 ------- apps/frontend/src/constants/dashboard/colllect.ts | 3 --- 2 files changed, 10 deletions(-) diff --git a/apps/frontend/src/constants/__tests__/config-dashboard.test.ts b/apps/frontend/src/constants/__tests__/config-dashboard.test.ts index ce903e0e..15670bce 100644 --- a/apps/frontend/src/constants/__tests__/config-dashboard.test.ts +++ b/apps/frontend/src/constants/__tests__/config-dashboard.test.ts @@ -123,18 +123,11 @@ describe('config and dashboard constants', () => { expect(getDefaultRecordConfig()).toMatchObject({ startMethod: START_METHOD.MANUAL, stopMethod: STOP_METHOD.TIME, - autoGeneratorOn: false, repeatUntilStop: false, testIntervalTimeUnit: TIME_UNIT_TYPE.S }) }) - it.each([undefined, null, false, true])('defaults automatic Generator control without opting in legacy value %s', value => { - const config: Parameters[0] = { autoGeneratorOn: value } - ensureMeasurementControlDefaults(config) - expect(config.autoGeneratorOn).toBe(value === true) - }) - it('normalizes legacy free-run start method to time', () => { const config: Parameters[0] = { startMethod: 'FREE_RUN' diff --git a/apps/frontend/src/constants/dashboard/colllect.ts b/apps/frontend/src/constants/dashboard/colllect.ts index 72414144..4b0907d4 100644 --- a/apps/frontend/src/constants/dashboard/colllect.ts +++ b/apps/frontend/src/constants/dashboard/colllect.ts @@ -147,7 +147,6 @@ type MeasurementCollectConfig = { recordMode?: string recordStartTime?: string repeatRecord?: boolean - autoGeneratorOn?: boolean | null repeatUntilStop?: boolean repeatTimes?: number testInterval?: number | null @@ -360,7 +359,6 @@ export function getDefaultRecordConfig() { recordMode: RECORD_MODE_ENUM.MANUAL, recordStartTime: '00:00:00', repeatRecord: false, - autoGeneratorOn: false, repeatUntilStop: false, repeatTimes: 1, testInterval: 0, @@ -598,7 +596,6 @@ export function ensureMeasurementControlDefaults( : RECORD_MODE_ENUM.MANUAL config.recordStartTime ||= '00:00:00' config.repeatRecord ??= false - config.autoGeneratorOn ??= false config.repeatUntilStop ??= false config.repeatTimes ??= 1 config.testInterval ??= 0 From 8e333c9e8c2ad2459004d33cbc85aca607ece8ca Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 08:58:26 +0800 Subject: [PATCH 3/3] fix(test): make Monitor recording targets thread-safe --- .../plugins/monitor/measure/MonitorPipelineRecordingTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/backend/opentest-monitor-tools/src/test/java/com/opentest/plugins/monitor/measure/MonitorPipelineRecordingTest.java b/apps/backend/opentest-monitor-tools/src/test/java/com/opentest/plugins/monitor/measure/MonitorPipelineRecordingTest.java index 677f99e6..1731f7d9 100644 --- a/apps/backend/opentest-monitor-tools/src/test/java/com/opentest/plugins/monitor/measure/MonitorPipelineRecordingTest.java +++ b/apps/backend/opentest-monitor-tools/src/test/java/com/opentest/plugins/monitor/measure/MonitorPipelineRecordingTest.java @@ -440,7 +440,7 @@ public void run() throws Exception { /** File output at the SDK boundary; host tests exercise shards and publication. */ private final class WavOutput implements WaveformFileOutput { - final List> targets = new ArrayList<>(); + final List> targets = new CopyOnWriteArrayList<>(); boolean failExternalClose; public Writer open() { return writer(Optional.empty()); } public Writer open(ExternalRecordingOutput target) { return writer(Optional.of(target)); }