Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SLCORE-1077 Cancel analysis when requested by the client #1294

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -693,8 +693,8 @@ public UUID scheduleForcedAnalysis(String configurationScopeId, List<URI> files,
}

public CompletableFuture<AnalysisResult> scheduleAnalysis(String configurationScopeId, UUID analysisId, List<URI> files, Map<String, String> extraProperties,
long startTime, boolean shouldFetchServerIssues, TriggerType triggerType) {
var progressMonitor = new RpcProgressMonitor(client, new SonarLintCancelMonitor(), configurationScopeId, analysisId);
long startTime, boolean shouldFetchServerIssues, TriggerType triggerType, SonarLintCancelMonitor cancelChecker) {
var progressMonitor = new RpcProgressMonitor(client, cancelChecker, configurationScopeId, analysisId);
var ruleDetailsCache = new ConcurrentHashMap<String, RuleDetailsForAnalysis>();
var rawIssues = new ArrayList<RawIssue>();
var analysisTask = new AnalyzeCommand(configurationScopeId, () -> getAnalysisConfigForEngine(configurationScopeId, files, extraProperties, false, triggerType),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public CompletableFuture<AnalyzeFilesResponse> analyzeFilesAndTrack(AnalyzeFiles
var analysisResults = getBean(AnalysisService.class)
.scheduleAnalysis(params.getConfigurationScopeId(), params.getAnalysisId(), params.getFilesToAnalyze(), params.getExtraProperties(), params.getStartTime(),
// consider this method as an automatic analysis. This will take exclusions into account
params.isShouldFetchServerIssues(), TriggerType.AUTO)
params.isShouldFetchServerIssues(), TriggerType.AUTO, cancelChecker)
.join();
return generateAnalyzeFilesResponse(analysisResults);
}, configurationScopeId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* SonarLint Core - Medium Tests
* Copyright (C) 2016-2025 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package mediumtest.analysis;

import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import mediumtest.analysis.sensor.WaitingCancellationSensor;
import org.junit.jupiter.api.io.TempDir;
import org.sonarsource.sonarlint.core.rpc.protocol.backend.analysis.AnalyzeFilesAndTrackParams;
import org.sonarsource.sonarlint.core.rpc.protocol.common.ClientFileDto;
import org.sonarsource.sonarlint.core.rpc.protocol.common.Language;
import org.sonarsource.sonarlint.core.test.utils.junit5.SonarLintTest;
import org.sonarsource.sonarlint.core.test.utils.junit5.SonarLintTestHarness;

import static mediumtest.analysis.sensor.WaitingCancellationSensor.CANCELLATION_FILE_PATH_PROPERTY_NAME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.sonarsource.sonarlint.core.test.utils.plugins.SonarPluginBuilder.newSonarPlugin;
import static utils.AnalysisUtils.createFile;

class AnalysisCancellationMediumTests {

private static final String CONFIG_SCOPE_ID = "CONFIG_SCOPE_ID";

@SonarLintTest
void it_should_analyze_file_on_open(SonarLintTestHarness harness, @TempDir Path baseDir) throws InterruptedException {
var filePath = createFile(baseDir, "pom.xml", "");
var fileUri = filePath.toUri();
var client = harness.newFakeClient()
.withInitialFs(CONFIG_SCOPE_ID, baseDir, List.of(new ClientFileDto(fileUri, baseDir.relativize(filePath), CONFIG_SCOPE_ID, false,
null, filePath, null, null, true)))
.build();
var plugin = newSonarPlugin("xml")
.withSensor(WaitingCancellationSensor.class)
.generate(baseDir);
var backend = harness.newBackend()
.withUnboundConfigScope(CONFIG_SCOPE_ID)
.withStandaloneEmbeddedPlugin(plugin)
.withEnabledLanguageInStandaloneMode(Language.XML)
.start(client);
var cancelationFilePath = baseDir.resolve("cancellation.result");
var future = backend.getAnalysisService()
.analyzeFilesAndTrack(new AnalyzeFilesAndTrackParams(CONFIG_SCOPE_ID, UUID.randomUUID(), List.of(fileUri),
Map.of(CANCELLATION_FILE_PATH_PROPERTY_NAME, cancelationFilePath.toString()), false, System.currentTimeMillis()));
Thread.sleep(500);

future.cancel(false);

assertThat(future.isCancelled()).isTrue();
await().atMost(3, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(cancelationFilePath).hasContent("CANCELED"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* SonarLint Core - Medium Tests
* Copyright (C) 2016-2025 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package mediumtest.analysis.sensor;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;

public class WaitingCancellationSensor implements Sensor {

public static final String CANCELLATION_FILE_PATH_PROPERTY_NAME = "cancellation.file.path";

@Override
public void describe(SensorDescriptor sensorDescriptor) {
sensorDescriptor.name("WaitingCancellationSensor");
}

@Override
public void execute(SensorContext sensorContext) {
var cancellationFilePath = Path.of(sensorContext.config().get(CANCELLATION_FILE_PATH_PROPERTY_NAME)
.orElseThrow(() -> new IllegalArgumentException("Missing '" + CANCELLATION_FILE_PATH_PROPERTY_NAME + "' property")));
var startTime = System.currentTimeMillis();
while (!sensorContext.isCancelled() && startTime + 2000 > System.currentTimeMillis()) {
System.out.println("HElloooo");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if (sensorContext.isCancelled()) {
try {
Files.writeString(cancellationFilePath, "CANCELED");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}