diff --git a/README.md b/README.md index 111f360..69179ad 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ constraints, and view definitions. - **GenModel Processing**: Apply standardization rules and download the corrected file - **VSUM Build**: Generate genmodels and a Methodologist-Template project from metamodels, reactions, and VitruvOCL constraints, build and smoke-test it, and return the project zip or executable jar +- **VSUM Validation**: Run the checks of the build without building, e.g. after every save - **OpenAPI / Swagger UI**: Interactive API documentation - **Error Handling**: Centralized exception handling with structured error responses - **Docker Support**: Dockerfile and Compose setup included @@ -173,6 +174,38 @@ but counted in `hiddenFollowUpErrors`. Problems are reported for metamodels and the build, for Reactions compiler and Java compiler errors, and for failures of the smoke test (constraints that cannot be evaluated, exceptions in reactions or routines while creating the VSUM). +### Validate VSUM + +**POST** `/api/vsum/validate` takes the same parts as `/api/vsum/build` and runs the +[checks before the build](#checks-before-the-build) through the same code, without writing a project or +running Maven, so it can run after every save while the project is edited. + +It returns `200` also for invalid projects, with the problems the build would report before Maven: + +```json +{ + "valid": false, + "problems": [ + { + "source": "REACTIONS", + "file": "my.reactions", + "line": 51, + "column": 30, + "message": "'Entitiy' is not a class of the metamodel 'model2' (http://vitruv.tools/methodologisttemplate/model2)", + "excerpt": " val entity = new model2::Entitiy\n ^", + "hint": "Did you mean 'Entity'?" + } + ] +} +``` + +`valid` is `false` if there is any problem. Like the build, the checks stop at the first stage with +problems: reactions are only checked once the metamodels are valid. Malformed requests (no metamodel, +empty files, wrong extensions, duplicate names) are rejected with `400` and `VSUM_INPUT_ERROR` or +`INVALID_REQUEST`, as for builds. Errors only Maven finds (Reactions compiler, Java compiler, smoke +test) are not reported. Validations don't use the build slots (`setup.vsum.max-concurrent-builds`), so they +never wait for running builds. + ### Checks before the build Most mistakes are found in milliseconds, before Maven runs, and come with a suggestion: diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java index 873f81e..348d16b 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/controller/VsumController.java @@ -21,9 +21,11 @@ import org.springframework.web.multipart.MultipartFile; import tools.vitruv.methodologist.setup.vsum.service.VsumBuildRequest; import tools.vitruv.methodologist.setup.vsum.service.VsumProjectBuildService; +import tools.vitruv.methodologist.setup.vsum.service.VsumValidationResult; +import tools.vitruv.methodologist.setup.vsum.service.VsumValidationService; import tools.vitruv.methodologist.setup.vsum.service.project.ProjectLayout; -/** REST API for VSUM project generation and packaging. */ +/** REST API for VSUM project generation, packaging, and validation. */ @RestController @RequestMapping("/api/vsum") @RequiredArgsConstructor @@ -31,6 +33,7 @@ public class VsumController { private final VsumProjectBuildService vsumProjectBuildService; + private final VsumValidationService vsumValidationService; /** * Builds a VSUM from the uploaded files and returns the generated project as a zip archive. @@ -119,6 +122,51 @@ public ResponseEntity buildJar( return attachment(jar, "application/java-archive", ProjectLayout.VSUM_JAR_FILENAME); } + /** + * Checks the uploaded files like a build does before Maven runs, without building them. + * + * @param metamodelFiles Ecore metamodels + * @param reactionFiles Reactions consistency specifications + * @param constraintFiles VitruvOCL constraints + * @param viewFiles NeoJoin view definitions + * @return whether the project is valid, and its problems + */ + @PostMapping( + value = "/validate", + consumes = MediaType.MULTIPART_FORM_DATA_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + @Operation( + summary = "Validate VSUM project", + description = + "Runs the checks /build runs before Maven, without generating a project or running" + + " Maven, and returns the problems found. Invalid projects are reported with 200" + + " and valid: false. Validations do not use the build slots, so they never wait" + + " for running builds", + responses = { + @ApiResponse( + responseCode = "200", + description = "Validation result, also for invalid projects", + content = @Content(mediaType = "application/json")), + @ApiResponse(responseCode = "400", description = "Malformed request") + }) + public VsumValidationResult validateProject( + @Parameter(description = "Ecore metamodel files", required = true) + @RequestPart("metamodelFiles") + List metamodelFiles, + @Parameter(description = "Reactions files") + @RequestPart(value = "reactionFiles", required = false) + List reactionFiles, + @Parameter(description = "VitruvOCL constraint files") + @RequestPart(value = "constraintFiles", required = false) + List constraintFiles, + @Parameter(description = "NeoJoin view definitions") + @RequestPart(value = "viewFiles", required = false) + List viewFiles) { + VsumBuildRequest request = + VsumBuildRequest.fromMultipart(metamodelFiles, reactionFiles, constraintFiles, viewFiles); + return vsumValidationService.validate(request); + } + private ResponseEntity attachment(byte[] content, String mediaType, String filename) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(mediaType)); diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java index 902b2a8..6c8f7c1 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildService.java @@ -124,6 +124,7 @@ private static boolean isNotCausedByTheUploads(MethodologistSetupException e) { * @throws IOException when writing the project fails */ ProjectSources generateProject(VsumBuildRequest request, Path projectRoot) throws IOException { + // VsumValidationService runs the checks of these steps without writing; keep both in sync List metamodels = metamodelProcessor.process(request.metamodels(), projectRoot); List specifications = diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationResult.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationResult.java new file mode 100644 index 0000000..9e8cdc9 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationResult.java @@ -0,0 +1,28 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import java.util.List; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; + +/** + * The result of checking a VSUM project without building it. + * + * @param valid whether the build would get past its checks, i.e. there is no error + * @param problems the problems the build would report before running Maven, root causes first + */ +public record VsumValidationResult(boolean valid, List problems) { + + /** Makes the problem list immutable. */ + public VsumValidationResult { + problems = List.copyOf(problems); + } + + /** + * Creates the result for the problems of the checks; the project is valid if there are none. + * + * @param problems the problems, empty if the checks passed + * @return the result + */ + public static VsumValidationResult of(List problems) { + return new VsumValidationResult(problems.isEmpty(), problems); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java new file mode 100644 index 0000000..4d0acc6 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationService.java @@ -0,0 +1,44 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import java.util.List; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; +import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; + +/** + * Checks a VSUM project without building it, so that problems can be shown while it is edited. + * + *

Runs the checks {@link VsumProjectBuildService} runs before Maven, through the same code, but + * writes no project and does not run Maven. Validations do not use the build slots ({@code + * setup.vsum.max-concurrent-builds}), so they never wait behind running builds. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class VsumValidationService { + + private final MetamodelProcessor metamodelProcessor; + private final ReactionsProcessor reactionsProcessor; + + /** + * Checks the project. Like the build, the checks stop at the first stage with problems: reactions + * are only checked once the metamodels are valid. + * + * @param request the project, as for a build + * @return the problems the build would report before running Maven + */ + public VsumValidationResult validate(VsumBuildRequest request) { + try { + List metamodels = metamodelProcessor.check(request.metamodels()); + reactionsProcessor.check(request.reactions(), metamodels); + return VsumValidationResult.of(List.of()); + } catch (VsumBuildException e) { + log.debug("VSUM validation found problems: {}", e.getMessage()); + return VsumValidationResult.of(e.getProblems()); + } + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java index 0397513..a910eb6 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java @@ -63,6 +63,12 @@ public class MetamodelProcessor { private static final Map SAVE_OPTIONS = Map.of(XMLResource.OPTION_ENCODING, "UTF-8"); + /** + * Project root that {@link #check(List)} names the resources after. Nothing is read from or + * written to it; the resources only need URIs to resolve the references between the uploads. + */ + private static final Path UNWRITTEN_PROJECT_ROOT = Path.of("unwritten-project"); + static { GenModelPackage.eINSTANCE.eClass(); EValidator.Registry.INSTANCE.put(EcorePackage.eINSTANCE, EcoreValidator.INSTANCE); @@ -82,8 +88,30 @@ public class MetamodelProcessor { public List process(List metamodels, Path projectRoot) throws IOException { Path ecoreDirectory = ProjectLayout.ecoreDirectory(projectRoot); + Checked checked = checkAndGenerate(metamodels, ecoreDirectory); + Files.createDirectories(ecoreDirectory); + for (Resource resource : checked.resourceSet().getResources()) { + resource.save(SAVE_OPTIONS); + } + return checked.metamodels(); + } + + /** + * Runs the same checks as {@link #process(List, Path)} without writing anything. + * + * @param metamodels uploaded ecore files + * @return one entry per uploaded metamodel, in upload order + * @throws VsumBuildException when a metamodel is unparsable, invalid, or references a metamodel + * that was not uploaded + */ + public List check(List metamodels) { + return checkAndGenerate(metamodels, ProjectLayout.ecoreDirectory(UNWRITTEN_PROJECT_ROOT)) + .metamodels(); + } + /** Checks the metamodels and generates their genmodels in memory, without saving them. */ + private Checked checkAndGenerate(List metamodels, Path ecoreDirectory) { ResourceSet resourceSet = createIsolatedResourceSet(); Map packages = load(metamodels, resourceSet, ecoreDirectory); resolveCrossReferences(resourceSet, packages); @@ -105,15 +133,16 @@ public List process(List metamodels, Path proj checkGeneratedNames(packages, genModels); addUsedGenPackages(genModels); - for (Resource resource : resourceSet.getResources()) { - resource.save(SAVE_OPTIONS); - } - - return genModels.entrySet().stream() - .map(entry -> describe(entry.getKey(), entry.getValue())) - .toList(); + return new Checked( + resourceSet, + genModels.entrySet().stream() + .map(entry -> describe(entry.getKey(), entry.getValue())) + .toList()); } + /** Checked metamodels and their genmodels, all in one resource set that is not saved yet. */ + private record Checked(ResourceSet resourceSet, List metamodels) {} + /** * Creates a resource set that never loads anything from disk or network. All metamodels must be * uploaded; Ecore's own packages come from the global package registry. diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java index 1e4b9d8..ea04b23 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java @@ -63,6 +63,32 @@ public class ReactionsProcessor { public List process( List reactions, List metamodels, Path projectRoot) throws IOException { + List specifications = check(reactions, metamodels); + + Path directory = ProjectLayout.reactionsDirectory(projectRoot); + Files.createDirectories(directory); + for (UploadedFile file : reactions) { + String text = file.text(); + String normalized = hoistJavaImports(text); + if (normalized.equals(text)) { + Files.write(directory.resolve(file.fileName()), file.content()); + } else { + Files.writeString(directory.resolve(file.fileName()), normalized, StandardCharsets.UTF_8); + } + } + return specifications; + } + + /** + * Runs the same checks as {@link #process(List, List, Path)} without writing anything. + * + * @param reactions uploaded reactions files + * @param metamodels the checked metamodels the reactions may import + * @return generated change propagation specification class names, one per reactions segment + * @throws VsumBuildException when a file declares no segment, a segment is declared twice, or a + * file imports a metamodel that was not uploaded + */ + public List check(List reactions, List metamodels) { Set knownNsUris = new LinkedHashSet<>(); metamodels.forEach( metamodel -> metamodel.packages().forEach(pkg -> knownNsUris.add(pkg.nsUri()))); @@ -127,18 +153,6 @@ public List process( "The uploaded reactions do not match the uploaded metamodels:", problems); } - - Path directory = ProjectLayout.reactionsDirectory(projectRoot); - Files.createDirectories(directory); - for (UploadedFile file : reactions) { - String text = file.text(); - String normalized = hoistJavaImports(text); - if (normalized.equals(text)) { - Files.write(directory.resolve(file.fileName()), file.content()); - } else { - Files.writeString(directory.resolve(file.fileName()), normalized, StandardCharsets.UTF_8); - } - } return specifications; } diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java index e7ef4e1..5e0aa99 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/controller/VsumControllerErrorHandlingTest.java @@ -24,6 +24,8 @@ import tools.vitruv.methodologist.setup.exception.MethodologistSetupException; import tools.vitruv.methodologist.setup.vsum.service.VsumErrorCodes; import tools.vitruv.methodologist.setup.vsum.service.VsumProjectBuildService; +import tools.vitruv.methodologist.setup.vsum.service.VsumValidationResult; +import tools.vitruv.methodologist.setup.vsum.service.VsumValidationService; import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; @@ -37,13 +39,15 @@ class VsumControllerErrorHandlingTest { "reactionFiles", "a.reactions", "text/plain", "reactions: a".getBytes()); private VsumProjectBuildService buildService; + private VsumValidationService validationService; private MockMvc mockMvc; @BeforeEach void setUp() { buildService = mock(VsumProjectBuildService.class); + validationService = mock(VsumValidationService.class); mockMvc = - MockMvcBuilders.standaloneSetup(new VsumController(buildService)) + MockMvcBuilders.standaloneSetup(new VsumController(buildService, validationService)) .setControllerAdvice(new GlobalExceptionHandler()) .build(); } @@ -170,4 +174,59 @@ void buildFailuresUseTheStatusOfTheException() throws Exception { .andExpect(jsonPath("$.errorCode").value(VsumErrorCodes.BUILD_FAILED)) .andExpect(jsonPath("$.message").value("The VSUM build failed:\n[ERROR] boom")); } + + @Test + void invalidProjectsAreValidatedWithOk() throws Exception { + when(validationService.validate(any())) + .thenReturn( + VsumValidationResult.of( + List.of( + BuildProblem.at( + Source.REACTIONS, + "a.reactions", + "import \"http://x\"\n", + 1, + 8, + "imports 'http://x', which is not the nsURI of an uploaded metamodel") + .withHint("Did you mean 'http://a'?")))); + + mockMvc + .perform(multipart("/api/vsum/validate").file(METAMODEL).file(REACTIONS)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.valid").value(false)) + .andExpect(jsonPath("$.problems[0].source").value("REACTIONS")) + .andExpect(jsonPath("$.problems[0].file").value("a.reactions")) + .andExpect(jsonPath("$.problems[0].line").value(1)) + .andExpect(jsonPath("$.problems[0].column").value(8)) + .andExpect(jsonPath("$.problems[0].hint").value("Did you mean 'http://a'?")) + .andExpect(jsonPath("$.problems[0].hiddenFollowUpErrors").doesNotExist()); + verify(validationService) + .validate( + argThat( + request -> + request.metamodels().get(0).fileName().equals("a.ecore") + && request.reactions().get(0).fileName().equals("a.reactions"))); + verifyNoInteractions(buildService); + } + + @Test + void validProjectsHaveNoProblems() throws Exception { + when(validationService.validate(any())).thenReturn(VsumValidationResult.of(List.of())); + + mockMvc + .perform(multipart("/api/vsum/validate").file(METAMODEL)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.valid").value(true)) + .andExpect(jsonPath("$.problems").isEmpty()); + } + + @Test + void malformedValidationRequestsAreABadRequest() throws Exception { + mockMvc + .perform(multipart("/api/vsum/validate").file(REACTIONS)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.errorCode").value("INVALID_REQUEST")); + verifyNoInteractions(validationService); + } } diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java new file mode 100644 index 0000000..89b8b11 --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumValidationServiceTest.java @@ -0,0 +1,196 @@ +package tools.vitruv.methodologist.setup.vsum.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.fixture; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.text; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.util.unit.DataSize; +import tools.vitruv.methodologist.setup.vsum.service.build.MavenBuildRunner; +import tools.vitruv.methodologist.setup.vsum.service.constraints.ConstraintsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; +import tools.vitruv.methodologist.setup.vsum.service.project.ProjectGenerator; +import tools.vitruv.methodologist.setup.vsum.service.reactions.ReactionsProcessor; +import tools.vitruv.methodologist.setup.vsum.service.views.NeoJoinViewDefinitionProcessor; + +class VsumValidationServiceTest { + + private static final VsumBuildRequest TEMPLATE_REQUEST = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(fixture("templateReactions.reactions")), + List.of(fixture("constraints.ocl")), + List.of(text("components.nj", "view stub"))); + + private final VsumBuildProperties properties = new VsumBuildProperties(); + private final VsumValidationService service = + new VsumValidationService(new MetamodelProcessor(), new ReactionsProcessor()); + + @TempDir Path temporaryDirectory; + + @Test + void validProjectsHaveNoProblems() { + VsumValidationResult result = service.validate(TEMPLATE_REQUEST); + + assertTrue(result.valid()); + assertEquals(List.of(), result.problems()); + } + + @Test + void reportsTheMetamodelProblemsTheBuildReportsBeforeMaven() { + String metamodel = + fixture("model2.ecore").text().replaceFirst("nsURI=\"[^\"]*\"", "nsURI=\"\""); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), text("model2.ecore", metamodel)), + List.of(fixture("templateReactions.reactions")), + List.of(), + List.of()); + + VsumValidationResult result = service.validate(request); + + assertFalse(result.valid()); + assertEquals(Source.METAMODEL, result.problems().get(0).source()); + assertEquals("model2.ecore", result.problems().get(0).file()); + assertEquals(problemsOfTheBuild(request), result); + } + + @Test + void reportsTheReactionsProblemsTheBuildReportsBeforeMaven() { + String reactions = + fixture("templateReactions.reactions") + .text() + .replace("val entity = new model2::Entity", "val entity = new model2::Entitiy"); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(text("my.reactions", reactions)), + List.of(), + List.of()); + + VsumValidationResult result = service.validate(request); + + assertFalse(result.valid()); + assertEquals("my.reactions", result.problems().get(0).file()); + assertEquals("Did you mean 'Entity'?", result.problems().get(0).hint()); + assertEquals(problemsOfTheBuild(request), result); + } + + @Test + void leavesNoFilesBehind() throws IOException { + Set before = buildWorkspaces(); + + service.validate(TEMPLATE_REQUEST); + + assertEquals(before, buildWorkspaces()); + assertFalse(Files.exists(Path.of("unwritten-project"))); + } + + /** + * The only build slot is taken by a build whose Maven never finishes; the validation is answered + * anyway. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void isAnsweredWhileABuildIsRunning() throws Exception { + Path started = temporaryDirectory.resolve("started"); + Path maven = temporaryDirectory.resolve("mvn"); + Files.writeString(maven, "#!/bin/sh\necho started >> '" + started + "'\nexec sleep 120\n"); + Files.setPosixFilePermissions(maven, PosixFilePermissions.fromString("rwx------")); + VsumBuildProperties buildProperties = new VsumBuildProperties(); + buildProperties.setMavenCommand(maven.toString()); + buildProperties.setMinFreeDiskSpace(DataSize.ofBytes(0)); + buildProperties.setMaxConcurrentBuilds(1); + VsumProjectBuildService buildService = + new VsumProjectBuildService( + new MetamodelProcessor(), + new ReactionsProcessor(), + new ConstraintsProcessor(), + new NeoJoinViewDefinitionProcessor(), + new ProjectGenerator(buildProperties), + new MavenBuildRunner(buildProperties), + buildProperties); + + ExecutorService builds = Executors.newSingleThreadExecutor(); + try { + Future running = builds.submit(() -> buildService.buildProjectJar(TEMPLATE_REQUEST)); + assertTimeoutPreemptively( + Duration.ofSeconds(60), + () -> { + while (!Files.exists(started)) { + Thread.sleep(50); + } + }, + "the build runs Maven"); + + VsumValidationResult result = + assertTimeoutPreemptively( + Duration.ofSeconds(30), () -> service.validate(TEMPLATE_REQUEST)); + + assertTrue(result.valid()); + assertFalse(running.isDone(), "the build is still running"); + } finally { + builds.shutdownNow(); + assertTrue(builds.awaitTermination(30, TimeUnit.SECONDS)); + } + } + + /** Builds the project with a Maven build that must not be reached, returning its problems. */ + private VsumValidationResult problemsOfTheBuild(VsumBuildRequest request) { + MavenBuildRunner mavenBuildRunner = mock(MavenBuildRunner.class); + VsumProjectBuildService buildService = + new VsumProjectBuildService( + new MetamodelProcessor(), + new ReactionsProcessor(), + new ConstraintsProcessor(), + new NeoJoinViewDefinitionProcessor(), + new ProjectGenerator(properties), + mavenBuildRunner, + properties); + + VsumBuildException exception = + assertThrows(VsumBuildException.class, () -> buildService.buildProjectJar(request)); + + verify(mavenBuildRunner, never()).build(any(), any()); + return VsumValidationResult.of(exception.getProblems()); + } + + private static Set buildWorkspaces() throws IOException { + try (Stream paths = Files.list(Path.of(System.getProperty("java.io.tmpdir")))) { + return new HashSet<>( + paths + .filter( + path -> + path.getFileName() + .toString() + .startsWith(VsumProjectBuildService.WORKSPACE_PREFIX)) + .toList()); + } + } +}