Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Improve handling of temporary files in pipelines (#8668)

James Brunton010fda9fae6a
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index b4a88c850d..cf536ee5a7 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -282,6 +282,19 @@ public class ApplicationProperties {
*/
private int runExpiryMinutes = 30;
+ /**
+ * Most steps one pipeline or policy run may have, covering {@code
+ * /api/v1/pipeline/handleData} as well as policies; 0 = unlimited.
+ */
+ private int maxSteps = 50;
+
+ /**
+ * Most files one step of a pipeline or policy run may produce before the run is aborted; 0
+ * = unlimited. A step answering with a ZIP multiplies the files the next step is called on,
+ * so without a cap a few split steps fan out into millions of tool calls.
+ */
+ private int maxFilesPerStep = 10000;
+
/**
* Whether a policy S3 source's custom endpoint may resolve to a loopback, link-local, or
* private address. Off by default so a user-supplied endpoint cannot be pointed at internal
diff --git a/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java b/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
index bc3184ba93..adda7579dd 100644
--- a/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
+++ b/app/common/src/main/java/stirling/software/common/model/tool/ToolDiagnostic.java
@@ -33,6 +33,9 @@ public record ToolDiagnostic(int stepIndex, Severity severity, String code, Stri
/** The previous step emits several files and this one consumes them in a single call. */
public static final String FAN_IN = "fan-in";
+ /** This step is past {@code policies.maxSteps}, so the chain will be refused. */
+ public static final String TOO_MANY_STEPS = "too-many-steps";
+
public static ToolDiagnostic error(int stepIndex, String code, String message) {
return new ToolDiagnostic(stepIndex, Severity.ERROR, code, message);
}
diff --git a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
index d3f3ee102d..ed48ed52be 100644
--- a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
+++ b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java
@@ -179,15 +179,22 @@ public class InternalApiClient {
try {
TempFile tempFile =
tempFileManager.createManagedTempFile("internal-api");
- Files.copy(
- response.getBody(),
- tempFile.getPath(),
- java.nio.file.StandardCopyOption.REPLACE_EXISTING);
- String filename = extractFilename(response.getHeaders());
- TempFileResource resource = new TempFileResource(tempFile, filename);
- return ResponseEntity.status(response.getStatusCode())
- .headers(response.getHeaders())
- .body(resource);
+ try {
+ Files.copy(
+ response.getBody(),
+ tempFile.getPath(),
+ java.nio.file.StandardCopyOption.REPLACE_EXISTING);
+ String filename = extractFilename(response.getHeaders());
+ TempFileResource resource =
+ new TempFileResource(tempFile, filename);
+ return ResponseEntity.status(response.getStatusCode())
+ .headers(response.getHeaders())
+ .body(resource);
+ } catch (IOException | RuntimeException e) {
+ // The caller never receives this file, so nobody else can delete it
+ tempFile.close();
+ throw e;
+ }
} catch (IOException e) {
throw new UncheckedIOException(e);
}
diff --git a/app/common/src/main/java/stirling/software/common/util/PipelineLimits.java b/app/common/src/main/java/stirling/software/common/util/PipelineLimits.java
new file mode 100644
index 0000000000..d866345e5e
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/PipelineLimits.java
@@ -0,0 +1,49 @@
+package stirling.software.common.util;
+
+import stirling.software.common.model.ApplicationProperties;
+
+/**
+ * The per-run limits {@code policies.maxSteps} and {@code policies.maxFilesPerStep}, shared by the
+ * pipeline API, watched folders and policy runs so all of them refuse the same runs the same way. A
+ * limit of 0 or less is unlimited.
+ */
+public final class PipelineLimits {
+
+ private PipelineLimits() {}
+
+ /** A run broke one of the limits; the message names the setting that allows more. */
+ public static class LimitExceededException extends IllegalArgumentException {
+ public LimitExceededException(String message) {
+ super(message);
+ }
+ }
+
+ public static boolean exceedsStepLimit(int steps, ApplicationProperties.Policies policies) {
+ return policies.getMaxSteps() > 0 && steps > policies.getMaxSteps();
+ }
+
+ public static String stepLimitMessage(ApplicationProperties.Policies policies) {
+ return "A pipeline may have at most "
+ + policies.getMaxSteps()
+ + " steps; raise policies.maxSteps to allow more";
+ }
+
+ public static void requireWithinStepLimit(int steps, ApplicationProperties.Policies policies) {
+ if (exceedsStepLimit(steps, policies)) {
+ throw new LimitExceededException(stepLimitMessage(policies));
+ }
+ }
+
+ public static void requireWithinFileLimit(
+ String operation, int files, ApplicationProperties.Policies policies) {
+ int maxFilesPerStep = policies.getMaxFilesPerStep();
+ if (maxFilesPerStep > 0 && files > maxFilesPerStep) {
+ throw new LimitExceededException(
+ "Step "
+ + operation
+ + " produced more than "
+ + maxFilesPerStep
+ + " files; raise policies.maxFilesPerStep to allow more");
+ }
+ }
+}
diff --git a/app/common/src/main/java/stirling/software/common/util/ZipExtractionUtils.java b/app/common/src/main/java/stirling/software/common/util/ZipExtractionUtils.java
index b49d1d2106..149b0a7bdf 100644
--- a/app/common/src/main/java/stirling/software/common/util/ZipExtractionUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/ZipExtractionUtils.java
@@ -6,6 +6,7 @@ import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.function.Consumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@@ -66,23 +67,15 @@ public class ZipExtractionUtils {
/**
* Extract a ZIP resource into a flat list of resources, one per file entry. Nested ZIPs are
- * recursively extracted up to {@link #MAX_UNZIP_DEPTH}. Each entry is materialized as a
- * hardened-extracted managed temp file so downstream consumers can stream the bytes.
- */
- public static List<Resource> extractZip(Resource zip, TempFileManager tempFileManager)
- throws IOException {
- return extractZip(zip, tempFileManager, null);
- }
-
- /**
- * Extract a ZIP resource into a flat list of resources. Each created {@link TempFile} is also
- * passed to {@code tempFileConsumer} when non-null, giving callers the option to register the
- * temp files with an auxiliary lifecycle (e.g. {@code PipelineResult}).
+ * recursively extracted up to {@link #MAX_UNZIP_DEPTH}. Every {@link TempFile} written,
+ * including those of nested archives, is passed to {@code tempFileConsumer} as it is created,
+ * and the consumer owns deleting it: nothing else keeps a reference.
*/
public static List<Resource> extractZip(
Resource zip, TempFileManager tempFileManager, Consumer<TempFile> tempFileConsumer)
throws IOException {
- return extractZipInternal(zip, tempFileManager, tempFileConsumer, 0);
+ return extractZipInternal(
+ zip, tempFileManager, Objects.requireNonNull(tempFileConsumer), 0);
}
private static List<Resource> extractZipInternal(
@@ -108,9 +101,7 @@ public class ZipExtractionUtils {
continue;
}
TempFile tempFile = tempFileManager.createManagedTempFile("unzip");
- if (tempFileConsumer != null) {
- tempFileConsumer.accept(tempFile);
- }
+ tempFileConsumer.accept(tempFile);
try (OutputStream os = Files.newOutputStream(tempFile.getPath())) {
byte[] buffer = new byte[4096];
int count;
diff --git a/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java b/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
index c7c8127fda..febee045e1 100644
--- a/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
+++ b/app/common/src/test/java/stirling/software/common/service/InternalApiClientTest.java
@@ -5,6 +5,9 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -273,6 +276,47 @@ class InternalApiClientTest {
}
}
+ @Test
+ void postReleasesTempFileWhenResponseCopyFails() throws Exception {
+ // E.g. "No space left on device": the partial copy is the file that filled the volume, and
+ // the caller has no handle to it.
+ MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
+ body.add("fileInput", namedResource("input.pdf", "data"));
+
+ Path tempPath = Files.createTempFile("internal-api-copy-fails-test", ".tmp");
+ TempFile tempFile = mock(TempFile.class);
+ when(tempFile.getPath()).thenReturn(tempPath);
+ when(tempFileManager.createManagedTempFile("internal-api")).thenReturn(tempFile);
+
+ InputStream failing = mock(InputStream.class);
+ when(failing.transferTo(any())).thenThrow(new IOException("No space left on device"));
+ ClientHttpResponse response = mock(ClientHttpResponse.class);
+ when(response.getBody()).thenReturn(failing);
+
+ try (var ignored =
+ mockConstruction(
+ RestTemplate.class,
+ (rt, ctx) -> {
+ when(rt.httpEntityCallback(any(), eq(Resource.class)))
+ .thenReturn((RequestCallback) req -> {});
+ when(rt.execute(anyString(), eq(HttpMethod.POST), any(), any()))
+ .thenAnswer(
+ inv ->
+ ((ResponseExtractor<?>) inv.getArgument(3))
+ .extractData(response));
+ })) {
+
+ InternalApiClient mockedClient = newClient();
+ assertThrows(
+ UncheckedIOException.class,
+ () -> mockedClient.post("/api/v1/convert/vector/pdf", body));
+
+ verify(tempFile).close();
+ } finally {
+ Files.deleteIfExists(tempPath);
+ }
+ }
+
@Test
void postRejectsPathTraversal() {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
diff --git a/app/common/src/test/java/stirling/software/common/util/ZipExtractionUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/ZipExtractionUtilsTest.java
index 4b3270025d..a51ef0f53d 100644
--- a/app/common/src/test/java/stirling/software/common/util/ZipExtractionUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/ZipExtractionUtilsTest.java
@@ -153,7 +153,8 @@ class ZipExtractionUtilsTest {
new String[] {"first.txt", "second.txt"},
new byte[][] {bytes("one"), bytes("two")});
- List<Resource> result = ZipExtractionUtils.extractZip(resource(zip), tempFileManager);
+ List<Resource> result =
+ ZipExtractionUtils.extractZip(resource(zip), tempFileManager, created::add);
assertThat(result).hasSize(2);
assertThat(result)
@@ -170,7 +171,8 @@ class ZipExtractionUtilsTest {
new String[] {"dir/", "dir/file.txt"},
new byte[][] {null, bytes("payload")});
- List<Resource> result = ZipExtractionUtils.extractZip(resource(zip), tempFileManager);
+ List<Resource> result =
+ ZipExtractionUtils.extractZip(resource(zip), tempFileManager, created::add);
assertThat(result).hasSize(1);
assertThat(result.get(0).getFilename()).isEqualTo("dir/file.txt");
@@ -180,7 +182,8 @@ class ZipExtractionUtilsTest {
@DisplayName("empty ZIP yields no resources")
void emptyZip() throws IOException {
byte[] zip = buildZip(new String[] {}, new byte[][] {});
- List<Resource> result = ZipExtractionUtils.extractZip(resource(zip), tempFileManager);
+ List<Resource> result =
+ ZipExtractionUtils.extractZip(resource(zip), tempFileManager, created::add);
assertThat(result).isEmpty();
}
@@ -194,7 +197,8 @@ class ZipExtractionUtilsTest {
new String[] {"top.txt", "child.zip"},
new byte[][] {bytes("top-content"), inner});
- List<Resource> result = ZipExtractionUtils.extractZip(resource(outer), tempFileManager);
+ List<Resource> result =
+ ZipExtractionUtils.extractZip(resource(outer), tempFileManager, created::add);
// top.txt + the single file inside child.zip => 2 flat resources
assertThat(result).hasSize(2);
@@ -230,7 +234,8 @@ class ZipExtractionUtilsTest {
byte[] innerZip = buildZip(new String[] {"page.png"}, new byte[][] {bytes("imgdata")});
byte[] outer = buildZip(new String[] {"book.cbz"}, new byte[][] {innerZip});
- List<Resource> result = ZipExtractionUtils.extractZip(resource(outer), tempFileManager);
+ List<Resource> result =
+ ZipExtractionUtils.extractZip(resource(outer), tempFileManager, created::add);
assertThat(result).hasSize(1);
assertThat(result.get(0).getFilename()).isEqualTo("book.cbz");
@@ -249,7 +254,7 @@ class ZipExtractionUtilsTest {
assertThatThrownBy(
() ->
ZipExtractionUtils.extractZip(
- resource(truncated), tempFileManager))
+ resource(truncated), tempFileManager, created::add))
.isInstanceOf(IOException.class);
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java
index dbef080a4d..e9aab5da92 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.controller.api.pipeline;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
@@ -10,10 +11,12 @@ import java.util.zip.ZipOutputStream;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;
@@ -30,6 +33,7 @@ import stirling.software.common.annotations.api.PipelineApi;
import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.service.PostHogService;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.PipelineLimits;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -85,20 +89,23 @@ public class PipelineController {
postHogService.captureEvent("pipeline_api_event", properties);
+ List<Resource> inputFiles = null;
+ PipelineResult result = null;
try {
- List<Resource> inputFiles = processor.generateInputFiles(files);
+ inputFiles = processor.generateInputFiles(files);
if (inputFiles == null || inputFiles.isEmpty()) {
return null;
}
- PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config);
+ result = processor.runPipelineAgainstFiles(inputFiles, config);
List<Resource> outputFiles = result.getOutputFiles();
if (outputFiles != null && outputFiles.size() == 1) {
// If there is only one file, return it directly — stream without int-overflow
Resource singleFile = outputFiles.get(0);
TempFile singleTempFile = new TempFile(tempFileManager, ".out");
try {
- try (InputStream is = singleFile.getInputStream()) {
- is.transferTo(Files.newOutputStream(singleTempFile.getPath()));
+ try (InputStream is = singleFile.getInputStream();
+ OutputStream os = Files.newOutputStream(singleTempFile.getPath())) {
+ is.transferTo(os);
}
log.info("Returning single file response...");
return WebResponseUtils.fileToWebResponse(
@@ -143,9 +150,17 @@ public class PipelineController {
zipTempFile.close();
throw e;
}
+ } catch (PipelineLimits.LimitExceededException e) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
} catch (Exception e) {
log.error("Error handling data: ", e);
return null;
+ } finally {
+ // The response is a copy, so the uploads and step outputs are not needed any longer
+ if (result != null) {
+ result.close();
+ }
+ processor.deleteInputFiles(inputFiles);
}
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java
index 84c57ed4e8..36bc367657 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java
@@ -366,16 +366,17 @@ public class PipelineDirectoryProcessor {
}
}
- private PipelineResult runPipelineAgainstFiles(
+ PipelineResult runPipelineAgainstFiles(
List<File> filesToProcess, PipelineConfig config, Path dir, Path processingDir)
throws IOException {
+ PipelineResult result = null;
try {
List<Resource> inputFiles =
processor.generateInputFiles(filesToProcess.toArray(new File[0]));
if (inputFiles == null || inputFiles.isEmpty()) {
return new PipelineResult();
}
- PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config);
+ result = processor.runPipelineAgainstFiles(inputFiles, config);
if (result.isHasErrors()) {
log.error("Errors occurred during processing, retaining original files");
@@ -387,7 +388,11 @@ public class PipelineDirectoryProcessor {
return result;
} catch (Exception e) {
log.error("Error during processing", e);
- moveFilesBack(filesToProcess, processingDir);
+ if (result != null) {
+ result.close();
+ }
+ // processing/ is never scanned, so leaving them there would lose them silently.
+ moveToErrorDirectory(filesToProcess, dir);
return new PipelineResult();
}
}
@@ -399,7 +404,10 @@ public class PipelineDirectoryProcessor {
}
for (File file : files) {
- Path target = errorDir.resolve(file.getName());
+ if (!file.exists()) {
+ continue;
+ }
+ Path target = resolveUniqueFilePath(errorDir, file.getName());
Files.move(file.toPath(), target);
log.info("Moved failed file to error directory for investigation: {}", target);
}
@@ -482,18 +490,4 @@ public class PipelineDirectoryProcessor {
log.info("Deleted original file: {}", file.getName());
}
}
-
- private void moveFilesBack(List<File> filesToProcess, Path processingDir) {
- for (File file : filesToProcess) {
- try {
- Files.move(processingDir.resolve(file.getName()), file.toPath());
- log.info(
- "Moved file back to original location: {} , {}",
- file.toPath(),
- file.getName());
- } catch (IOException e) {
- log.error("Error moving file back to original location: {}", file.getName(), e);
- }
- }
- }
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessor.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessor.java
index 08684dd5fe..727b1175a6 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessor.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessor.java
@@ -28,9 +28,12 @@ import stirling.software.SPDF.model.PipelineConfig;
import stirling.software.SPDF.model.PipelineOperation;
import stirling.software.SPDF.model.PipelineResult;
import stirling.software.SPDF.service.ApiDocService;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
@@ -46,15 +49,19 @@ public class PipelineProcessor {
private final TempFileManager tempFileManager;
+ private final ApplicationProperties applicationProperties;
+
public PipelineProcessor(
ApiDocService apiDocService,
ToolMetadataService toolMetadataService,
InternalApiClient internalApiClient,
- TempFileManager tempFileManager) {
+ TempFileManager tempFileManager,
+ ApplicationProperties applicationProperties) {
this.apiDocService = apiDocService;
this.toolMetadataService = toolMetadataService;
this.internalApiClient = internalApiClient;
this.tempFileManager = tempFileManager;
+ this.applicationProperties = applicationProperties;
}
public static String removeTrailingNaming(String filename) {
@@ -76,21 +83,34 @@ public class PipelineProcessor {
return name.substring(0, underscoreIndex) + extension;
}
+ /**
+ * Runs the pipeline. The inputs stay the caller's; the caller closes the returned result, which
+ * holds the outputs, once it has read them.
+ *
+ * @throws PipelineLimits.LimitExceededException if the run breaks {@code policies.maxSteps} or
+ * {@code policies.maxFilesPerStep}
+ */
PipelineResult runPipelineAgainstFiles(List<Resource> outputFiles, PipelineConfig config)
throws Exception {
+ PipelineLimits.requireWithinStepLimit(
+ config.getOperations().size(), applicationProperties.getPolicies());
+ PipelineResult result = new PipelineResult();
// One pipeline execution = one automation run. Scope a run id so every tool sub-step
// dispatched via InternalApiClient groups into a single charge on the SaaS billing side
// (see AutomationRunContext); pipeline steps run synchronously on this thread.
try (AutomationRunContext.Scope ignored =
AutomationRunContext.open(UUID.randomUUID().toString())) {
- return runPipelineAgainstFilesInternal(outputFiles, config);
+ return runPipelineAgainstFilesInternal(outputFiles, config, result);
+ } catch (Exception e) {
+ // The caller never receives the result, so release the earlier steps' outputs here
+ result.close();
+ throw e;
}
}
private PipelineResult runPipelineAgainstFilesInternal(
- List<Resource> outputFiles, PipelineConfig config) throws Exception {
- PipelineResult result = new PipelineResult();
-
+ List<Resource> outputFiles, PipelineConfig config, PipelineResult result)
+ throws Exception {
ByteArrayOutputStream logStream = new ByteArrayOutputStream();
PrintStream logPrintStream = new PrintStream(logStream);
boolean hasErrors = false;
@@ -114,6 +134,7 @@ public class PipelineProcessor {
"Invalid operation: " + operation + " with parameters: " + parameters);
}
+ int consumedTempFiles = result.getTempFiles().size();
List<Resource> newOutputFiles = new ArrayList<>();
if (!isMultiInputOperation) {
for (Resource file : outputFiles) {
@@ -266,6 +287,7 @@ public class PipelineProcessor {
}
logPrintStream.close();
outputFiles = newOutputFiles;
+ result.releaseTempFiles(consumedTempFiles);
}
if (hasErrors) {
log.error("Errors occurred during processing. Log: {}", logStream.toString());
@@ -314,6 +336,8 @@ public class PipelineProcessor {
};
newOutputFiles.add(outputResource);
}
+ PipelineLimits.requireWithinFileLimit(
+ operation, newOutputFiles.size(), applicationProperties.getPolicies());
return newOutputFiles;
}
@@ -362,27 +386,43 @@ public class PipelineProcessor {
return outputFiles;
}
+ /**
+ * Copies the uploads to managed temp files; the caller passes the returned list to {@link
+ * #deleteInputFiles} once it no longer needs them.
+ */
List<Resource> generateInputFiles(MultipartFile[] files) throws Exception {
if (files == null || files.length == 0) {
log.info("No files");
return null;
}
List<Resource> outputFiles = new ArrayList<>();
- for (MultipartFile file : files) {
- Path tempFile = Files.createTempFile("SPDF-upload-", ".tmp");
- file.transferTo(tempFile);
-
- Resource fileResource =
- new FileSystemResource(tempFile.toFile()) {
-
- @Override
- public String getFilename() {
- return Filenames.toSimpleFileName(file.getOriginalFilename());
- }
- };
- outputFiles.add(fileResource);
+ List<TempFile> uploads = new ArrayList<>();
+ try {
+ for (MultipartFile file : files) {
+ TempFile upload = tempFileManager.createManagedTempFile("pipeline-upload");
+ uploads.add(upload);
+ file.transferTo(upload.getPath());
+ outputFiles.add(
+ new InternalApiClient.TempFileResource(
+ upload, Filenames.toSimpleFileName(file.getOriginalFilename())));
+ }
+ } catch (IOException | RuntimeException e) {
+ uploads.forEach(TempFile::close);
+ throw e;
}
log.info("Files successfully loaded. Starting processing...");
return outputFiles;
}
+
+ /** Deletes the copies made by {@link #generateInputFiles(MultipartFile[])}; null is a no-op. */
+ void deleteInputFiles(List<Resource> inputFiles) {
+ if (inputFiles == null) {
+ return;
+ }
+ for (Resource input : inputFiles) {
+ if (input instanceof InternalApiClient.TempFileResource upload) {
+ upload.getTempFile().close();
+ }
+ }
+ }
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/PipelineResult.java b/app/core/src/main/java/stirling/software/SPDF/model/PipelineResult.java
index 1f8a9fd885..484eeb3d87 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/PipelineResult.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/PipelineResult.java
@@ -22,6 +22,13 @@ public class PipelineResult implements AutoCloseable {
tempFiles.add(tempFile);
}
+ /** Deletes the {@code count} temp files added first. */
+ public void releaseTempFiles(int count) {
+ List<TempFile> released = tempFiles.subList(0, count);
+ released.forEach(TempFile::close);
+ released.clear();
+ }
+
@Override
public void close() {
for (TempFile file : tempFiles) {
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index dcbbc2b01d..64f5c29c3d 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -449,6 +449,8 @@ policies:
watchQuietPeriodMs: 500 # How long (ms) folder-watch coalesces a burst of file events into a single run
streamTimeoutMs: 1800000 # SSE timeout (ms) for live run-progress streams
runExpiryMinutes: 30 # How long (minutes) a finished run's in-memory state is kept before eviction
+ maxSteps: 50 # Most steps a pipeline or policy run may have (0 = unlimited)
+ maxFilesPerStep: 10000 # Abort a pipeline or policy run when one step produces more files than this (0 = unlimited)
# Model Context Protocol (MCP) server. Exposes Stirling's PDF tools (grouped by namespace)
# plus the AI agents to MCP clients (Inspector, Claude Desktop, custom). OAuth-protected.
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineControllerGapTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineControllerGapTest.java
index edcfbc72ea..08eed8c3ad 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineControllerGapTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineControllerGapTest.java
@@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -40,11 +41,14 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.server.ResponseStatusException;
import stirling.software.SPDF.model.PipelineConfig;
import stirling.software.SPDF.model.PipelineResult;
import stirling.software.SPDF.model.api.HandleDataRequest;
import stirling.software.common.service.PostHogService;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import tools.jackson.databind.ObjectMapper;
@@ -225,6 +229,26 @@ class PipelineControllerGapTest {
}
}
+ @Test
+ @DisplayName("releases the step outputs once the response copy exists")
+ void singleOutput_releasesStepOutputs() throws Exception {
+ stubTempFiles();
+ MultipartFile[] files = oneFile();
+ List<Resource> inputFiles = List.of(namedResource("input.pdf", "in".getBytes()));
+ when(processor.generateInputFiles(files)).thenReturn(inputFiles);
+
+ TempFile stepOutput = mock(TempFile.class);
+ PipelineResult result = new PipelineResult();
+ result.setOutputFiles(List.of(namedResource("result.pdf", "out".getBytes())));
+ result.addTempFile(stepOutput);
+ when(processor.runPipelineAgainstFiles(any(), any())).thenReturn(result);
+
+ assertNotNull(controller.handleData(request(files, VALID_JSON)));
+
+ verify(stepOutput).close();
+ verify(processor).deleteInputFiles(inputFiles);
+ }
+
@Test
@DisplayName("captures analytics event with operations and file count")
void singleOutput_capturesAnalytics() throws Exception {
@@ -351,6 +375,27 @@ class PipelineControllerGapTest {
assertNull(response);
}
+ @Test
+ @DisplayName("answers 400 with the setting to raise when the run breaks a limit")
+ void limitExceeded_isABadRequest() throws Exception {
+ MultipartFile[] files = oneFile();
+ List<Resource> inputFiles = List.of(namedResource("input.pdf", "in".getBytes()));
+ when(processor.generateInputFiles(files)).thenReturn(inputFiles);
+ when(processor.runPipelineAgainstFiles(any(), any()))
+ .thenThrow(
+ new PipelineLimits.LimitExceededException(
+ "raise policies.maxSteps to allow more"));
+
+ ResponseStatusException error =
+ org.junit.jupiter.api.Assertions.assertThrows(
+ ResponseStatusException.class,
+ () -> controller.handleData(request(files, VALID_JSON)));
+
+ assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
+ assertEquals("raise policies.maxSteps to allow more", error.getReason());
+ verify(processor).deleteInputFiles(inputFiles);
+ }
+
@Test
@DisplayName("invalid JSON config propagates as a parse exception")
void invalidJson_throws() {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorFailureTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorFailureTest.java
new file mode 100644
index 0000000000..54103c24b6
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorFailureTest.java
@@ -0,0 +1,119 @@
+package stirling.software.SPDF.controller.api.pipeline;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+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.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.core.io.AbstractResource;
+import org.springframework.core.io.FileSystemResource;
+
+import stirling.software.SPDF.model.PipelineConfig;
+import stirling.software.SPDF.model.PipelineResult;
+import stirling.software.SPDF.service.ApiDocService;
+import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.service.PostHogService;
+import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.FileReadinessChecker;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
+
+import tools.jackson.databind.ObjectMapper;
+
+class PipelineDirectoryProcessorFailureTest {
+
+ @TempDir Path tempDir;
+
+ private final PipelineProcessor pipelineProcessor = mock(PipelineProcessor.class);
+ private Path jobDir;
+ private Path processingDir;
+ private Path queued;
+ private PipelineDirectoryProcessor processor;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ Path watched = tempDir.resolve("watchedFolders");
+ jobDir = watched.resolve("job");
+ processingDir = Files.createDirectories(jobDir.resolve("processing"));
+ queued = Files.writeString(processingDir.resolve("a.pdf"), "pdf");
+ RuntimePathConfig paths = mock(RuntimePathConfig.class);
+ when(paths.getPipelineWatchedFoldersPaths()).thenReturn(List.of(watched.toString()));
+ when(paths.getPipelineFinishedFoldersPath())
+ .thenReturn(tempDir.resolve("finishedFolders").toString());
+ processor =
+ new PipelineDirectoryProcessor(
+ new ObjectMapper(),
+ mock(ApiDocService.class),
+ mock(ToolMetadataService.class),
+ pipelineProcessor,
+ mock(PostHogService.class),
+ mock(FileReadinessChecker.class),
+ paths);
+ when(pipelineProcessor.generateInputFiles(any(File[].class)))
+ .thenReturn(List.of(new FileSystemResource(queued)));
+ }
+
+ @Test
+ void aRunThatFailsMovesItsFilesToTheErrorFolder() throws Exception {
+ when(pipelineProcessor.runPipelineAgainstFiles(any(), any()))
+ .thenThrow(new PipelineLimits.LimitExceededException("too many steps"));
+
+ processor.runPipelineAgainstFiles(
+ List.of(queued.toFile()), config(), jobDir, processingDir);
+
+ assertFalse(Files.exists(queued));
+ assertTrue(Files.exists(jobDir.resolve("error").resolve("a.pdf")));
+ }
+
+ @Test
+ void outputsAreDeletedWhenTheyCannotBeWritten() throws Exception {
+ TempFile output = mock(TempFile.class);
+ PipelineResult result = new PipelineResult();
+ result.addTempFile(output);
+ result.setOutputFiles(List.of(new UnreadableResource()));
+ when(pipelineProcessor.runPipelineAgainstFiles(any(), any())).thenReturn(result);
+
+ processor.runPipelineAgainstFiles(
+ List.of(queued.toFile()), config(), jobDir, processingDir);
+
+ verify(output).close();
+ assertTrue(Files.exists(jobDir.resolve("error").resolve("a.pdf")));
+ }
+
+ private static PipelineConfig config() {
+ PipelineConfig config = new PipelineConfig();
+ config.setName("job");
+ config.setOutputDir("{outputFolder}");
+ config.setOutputPattern("{filename}");
+ return config;
+ }
+
+ private static class UnreadableResource extends AbstractResource {
+ @Override
+ public String getFilename() {
+ return "out.pdf";
+ }
+
+ @Override
+ public String getDescription() {
+ return "unreadable";
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ throw new IOException("unreadable");
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessorTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessorTest.java
index aad630448f..2094f8afdf 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessorTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineProcessorTest.java
@@ -4,28 +4,42 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.model.PipelineConfig;
import stirling.software.SPDF.model.PipelineOperation;
import stirling.software.SPDF.model.PipelineResult;
import stirling.software.SPDF.service.ApiDocService;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@ExtendWith(MockitoExtension.class)
@@ -39,13 +53,19 @@ class PipelineProcessorTest {
@Mock TempFileManager tempFileManager;
+ final ApplicationProperties properties = new ApplicationProperties();
+
PipelineProcessor pipelineProcessor;
@BeforeEach
void setUp() throws Exception {
pipelineProcessor =
new PipelineProcessor(
- apiDocService, toolMetadataService, internalApiClient, tempFileManager);
+ apiDocService,
+ toolMetadataService,
+ internalApiClient,
+ tempFileManager,
+ properties);
}
@Test
@@ -121,6 +141,199 @@ class PipelineProcessorTest {
Files.deleteIfExists(tempPath);
}
+ @Test
+ void failingStepReleasesEarlierStepOutputs() throws Exception {
+ PipelineOperation first = new PipelineOperation();
+ first.setOperation("/api/v1/misc/compress");
+ first.setParameters(Map.of());
+ PipelineOperation second = new PipelineOperation();
+ second.setOperation("/api/v1/misc/repair");
+ second.setParameters(Map.of());
+ PipelineConfig config = new PipelineConfig();
+ config.setOperations(List.of(first, second));
+
+ Path tempPath = Files.createTempFile("test-output", ".pdf");
+ TempFile firstOutput = mock(TempFile.class);
+ when(firstOutput.getFile()).thenReturn(tempPath.toFile());
+ Resource firstResource = new InternalApiClient.TempFileResource(firstOutput, "test.pdf");
+
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.getExtensionTypes(anyBoolean(), anyString()))
+ .thenReturn(List.of("ALL"));
+ when(apiDocService.isValidOperation(anyString(), anyMap())).thenReturn(true);
+
+ when(internalApiClient.post(eq("/api/v1/misc/compress"), any()))
+ .thenReturn(new ResponseEntity<>(firstResource, HttpStatus.OK));
+ when(internalApiClient.post(eq("/api/v1/misc/repair"), any()))
+ .thenThrow(new IllegalStateException("step failed"));
+
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ pipelineProcessor.runPipelineAgainstFiles(
+ List.of(new MyFileByteArrayResource()), config));
+
+ verify(firstOutput, atLeastOnce()).close();
+
+ Files.deleteIfExists(tempPath);
+ }
+
+ @Test
+ void pipelineWithMoreOperationsThanTheLimitIsRejected() {
+ properties.getPolicies().setMaxSteps(2);
+ PipelineConfig config = new PipelineConfig();
+ config.setOperations(Collections.nCopies(3, operation("/api/v1/misc/compress")));
+
+ assertThrows(
+ PipelineLimits.LimitExceededException.class,
+ () ->
+ pipelineProcessor.runPipelineAgainstFiles(
+ List.of(new MyFileByteArrayResource()), config));
+
+ verifyNoInteractions(internalApiClient);
+ }
+
+ @Test
+ void chainedZipOperationsStopAtTheFileLimitAndReleaseTempFiles(@TempDir Path tempDir)
+ throws Exception {
+ properties.getPolicies().setMaxFilesPerStep(50);
+ String split = "/api/v1/general/split-pdf-by-sections";
+ PipelineConfig config = new PipelineConfig();
+ config.setOperations(List.of(operation(split), operation(split)));
+ stubAnyPdfOperation();
+ stubTempFilesIn(tempDir);
+ byte[] zip = zipOfPdfs(20);
+ when(internalApiClient.post(anyString(), any()))
+ .thenAnswer(inv -> ResponseEntity.ok(tempFileResource(zip, "out.zip")));
+
+ assertThrows(
+ PipelineLimits.LimitExceededException.class,
+ () ->
+ pipelineProcessor.runPipelineAgainstFiles(
+ List.of(new MyFileByteArrayResource()), config));
+
+ // One call makes 20 files; the second operation passes 50 on its third call.
+ verify(internalApiClient, times(4)).post(anyString(), any());
+ try (Stream<Path> left = Files.list(tempDir)) {
+ assertEquals(0, left.count());
+ }
+ }
+
+ @Test
+ void tempFilesOfAnOperationAreReleasedOnceTheNextHasRun(@TempDir Path tempDir)
+ throws Exception {
+ PipelineConfig config = new PipelineConfig();
+ config.setOperations(
+ List.of(
+ operation("/api/v1/general/rotate-pdf"),
+ operation("/api/v1/misc/compress")));
+ stubAnyPdfOperation();
+ stubTempFilesIn(tempDir);
+ InternalApiClient.TempFileResource rotated =
+ tempFileResource("rotated".getBytes(), "a.pdf");
+ InternalApiClient.TempFileResource compressed =
+ tempFileResource("compressed".getBytes(), "a.pdf");
+ when(internalApiClient.post(eq("/api/v1/general/rotate-pdf"), any()))
+ .thenReturn(attachment(rotated));
+ when(internalApiClient.post(eq("/api/v1/misc/compress"), any()))
+ .thenReturn(attachment(compressed));
+
+ try (PipelineResult result =
+ pipelineProcessor.runPipelineAgainstFiles(
+ List.of(new MyFileByteArrayResource()), config)) {
+ assertFalse(rotated.getTempFile().exists());
+ assertEquals(
+ "compressed",
+ result.getOutputFiles().get(0).getContentAsString(StandardCharsets.UTF_8));
+ }
+ assertFalse(compressed.getTempFile().exists());
+ }
+
+ @Test
+ void uploadsOutliveTheRunUntilTheCallerDeletesThem(@TempDir Path tempDir) throws Exception {
+ PipelineConfig config = new PipelineConfig();
+ config.setOperations(List.of(operation("/api/v1/misc/compress")));
+ stubAnyPdfOperation();
+ stubTempFilesIn(tempDir);
+ when(internalApiClient.post(anyString(), any()))
+ .thenAnswer(inv -> attachment(tempFileResource("out".getBytes(), "a.pdf")));
+
+ List<Resource> uploads =
+ pipelineProcessor.generateInputFiles(
+ new MultipartFile[] {
+ new MockMultipartFile("fileInput", "a.pdf", null, "in".getBytes())
+ });
+ InternalApiClient.TempFileResource upload =
+ (InternalApiClient.TempFileResource) uploads.get(0);
+ assertEquals("a.pdf", upload.getFilename());
+
+ try (PipelineResult result = pipelineProcessor.runPipelineAgainstFiles(uploads, config)) {
+ assertEquals(
+ "out",
+ result.getOutputFiles().get(0).getContentAsString(StandardCharsets.UTF_8));
+ }
+ assertTrue(upload.getTempFile().exists());
+
+ pipelineProcessor.deleteInputFiles(uploads);
+
+ try (Stream<Path> left = Files.list(tempDir)) {
+ assertEquals(0, left.count());
+ }
+ }
+
+ private static PipelineOperation operation(String path) {
+ PipelineOperation op = new PipelineOperation();
+ op.setOperation(path);
+ op.setParameters(Map.of());
+ return op;
+ }
+
+ private void stubAnyPdfOperation() {
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.getExtensionTypes(anyBoolean(), anyString()))
+ .thenReturn(List.of("pdf"));
+ when(apiDocService.isValidOperation(anyString(), anyMap())).thenReturn(true);
+ }
+
+ private void stubTempFilesIn(Path dir) throws Exception {
+ lenient()
+ .when(tempFileManager.createTempFile(anyString()))
+ .thenAnswer(inv -> Files.createTempFile(dir, "test", inv.getArgument(0)).toFile());
+ lenient()
+ .when(tempFileManager.createManagedTempFile(anyString()))
+ .thenAnswer(inv -> new TempFile(tempFileManager, inv.getArgument(0)));
+ lenient()
+ .when(tempFileManager.deleteTempFile(any(File.class)))
+ .thenAnswer(inv -> inv.<File>getArgument(0).delete());
+ }
+
+ private InternalApiClient.TempFileResource tempFileResource(byte[] content, String filename)
+ throws Exception {
+ TempFile tempFile = new TempFile(tempFileManager, ".tmp");
+ Files.write(tempFile.getPath(), content);
+ return new InternalApiClient.TempFileResource(tempFile, filename);
+ }
+
+ private static ResponseEntity<Resource> attachment(Resource body) {
+ return ResponseEntity.ok()
+ .header(
+ HttpHeaders.CONTENT_DISPOSITION,
+ "attachment; filename=\"" + body.getFilename() + "\"")
+ .body(body);
+ }
+
+ private static byte[] zipOfPdfs(int entries) throws Exception {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
+ for (int i = 0; i < entries; i++) {
+ zip.putNextEntry(new ZipEntry("section_" + i + ".pdf"));
+ zip.write('x');
+ zip.closeEntry();
+ }
+ }
+ return bytes.toByteArray();
+ }
+
private static class MyFileByteArrayResource extends ByteArrayResource {
public MyFileByteArrayResource() {
super("data".getBytes());
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java
index f2ceb7988f..7c12d79dd1 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java
@@ -9,6 +9,7 @@ import java.util.Map;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
@@ -75,7 +76,8 @@ final class ResultFiles {
}
/**
- * Pick the file a step asked for out of an archive.
+ * Pick the file a step asked for out of an archive. The entry is returned in memory, like the
+ * response it came from; the archive's unpacked files are deleted before this returns.
*
* @param select a glob such as {@code *.pdf}, or a 0-based index such as {@code 1}
* @throws IOException if nothing in the archive matches, naming what was there - a silent pick
@@ -83,7 +85,19 @@ final class ResultFiles {
*/
static Resource selectFromArchive(
Resource archive, String select, TempFileManager tempFileManager) throws IOException {
- List<Resource> entries = ZipExtractionUtils.extractZip(archive, tempFileManager);
+ List<TempFile> unpacked = new ArrayList<>();
+ try {
+ Resource entry =
+ pick(
+ ZipExtractionUtils.extractZip(archive, tempFileManager, unpacked::add),
+ select);
+ return asResource(entry.getContentAsByteArray(), entry.getFilename());
+ } finally {
+ unpacked.forEach(TempFile::close);
+ }
+ }
+
+ private static Resource pick(List<Resource> entries, String select) throws IOException {
if (entries.isEmpty()) {
throw new IOException("The API returned an empty archive");
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/tools/McpOperationExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/tools/McpOperationExecutor.java
index 28cb56d965..2f93d6fd29 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/tools/McpOperationExecutor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/tools/McpOperationExecutor.java
@@ -125,7 +125,14 @@ public class McpOperationExecutor {
return McpResponses.error(
mapper, meta.id() + " failed unexpectedly. See server logs for details.");
}
- return buildResult(meta, response);
+ try {
+ return buildResult(meta, response);
+ } finally {
+ // The result was inlined or stored, so the temp file is not needed any longer
+ if (response.getBody() instanceof InternalApiClient.TempFileResource tempFileResource) {
+ tempFileResource.getTempFile().close();
+ }
+ }
}
private ObjectNode buildResult(OperationMeta meta, ResponseEntity<Resource> response) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index 19651ab9eb..547c34f80a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -7,9 +7,9 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.function.Supplier;
import java.util.stream.Stream;
-import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -47,6 +47,7 @@ import stirling.software.common.cluster.JobStoreEntry;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.job.JobResponse;
import stirling.software.common.model.tool.ToolDiagnostic;
+import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.JobOwnershipService;
import stirling.software.common.service.ToolChainValidator;
import stirling.software.common.util.TempFile;
@@ -140,10 +141,16 @@ public class PolicyController {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocRun(definition);
- PolicyInputs inputs = resolveStoredAssets(policyId, toInputs(files));
+ PolicyInputs uploads = toInputs(files);
PolicyRunHandle handle =
- policyRunner.runAdHoc(definition, inputs, PolicyProgressListener.NOOP);
- recordEditorDocs(inputs);
+ startOnUploads(
+ uploads,
+ () ->
+ policyRunner.runAdHoc(
+ definition,
+ resolveStoredAssets(policyId, uploads),
+ PolicyProgressListener.NOOP));
+ recordEditorDocs(uploads);
return ResponseEntity.accepted().body(new JobResponse<>(true, handle.runId(), null));
}
@@ -163,14 +170,21 @@ public class PolicyController {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocRun(definition);
- PolicyInputs inputs = resolveStoredAssets(policyId, toInputs(files));
SseEmitter emitter =
new SseEmitter(applicationProperties.getPolicies().getStreamTimeoutMs());
emitter.onError(e -> log.warn("Policy run SSE emitter error", e));
- PolicyRunHandle handle = policyRunner.runAdHoc(definition, inputs, streamListener(emitter));
- recordEditorDocs(inputs);
+ PolicyInputs uploads = toInputs(files);
+ PolicyRunHandle handle =
+ startOnUploads(
+ uploads,
+ () ->
+ policyRunner.runAdHoc(
+ definition,
+ resolveStoredAssets(policyId, uploads),
+ streamListener(emitter)));
+ recordEditorDocs(uploads);
// whenComplete runs on the worker thread after the run finishes, so the terminal event
// never races the step events.
handle.completion()
@@ -658,14 +672,16 @@ public class PolicyController {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
stampPolicyAudit(policy.toDefinition());
- PolicyInputs inputs = toInputs(files);
+ PolicyInputs uploads = toInputs(files);
String runId =
- policyRunner
- .runWith(
- policy,
- inputs,
- PolicyProgressListener.NOOP,
- documentReferenceFor(files, inputs))
+ startOnUploads(
+ uploads,
+ () ->
+ policyRunner.runWith(
+ policy,
+ uploads,
+ PolicyProgressListener.NOOP,
+ documentReferenceFor(files, uploads)))
.runId();
return ResponseEntity.accepted().body(new JobResponse<>(true, runId, null));
}
@@ -785,19 +801,60 @@ public class PolicyController {
* files.
*/
private PolicyInputs toInputs(PolicyRunFiles files) throws IOException {
- List<Resource> primary = toResources(files.getFileInput());
+ List<Resource> primary = new ArrayList<>();
Map<String, List<Resource>> supportingFiles = new LinkedHashMap<>();
- for (NamedAsset asset : files.getAssets()) {
- Resource resource = toResource(asset.getFile());
- if (resource != null) {
- supportingFiles
- .computeIfAbsent(asset.getKey(), key -> new ArrayList<>())
- .add(resource);
+ try {
+ if (files.getFileInput() != null) {
+ for (MultipartFile file : files.getFileInput()) {
+ Resource resource = toResource(file);
+ if (resource != null) {
+ primary.add(resource);
+ }
+ }
}
+ for (NamedAsset asset : files.getAssets()) {
+ Resource resource = toResource(asset.getFile());
+ if (resource != null) {
+ supportingFiles
+ .computeIfAbsent(asset.getKey(), key -> new ArrayList<>())
+ .add(resource);
+ }
+ }
+ } catch (IOException | RuntimeException e) {
+ deleteUploads(new PolicyInputs(primary, supportingFiles));
+ throw e;
}
return new PolicyInputs(primary, supportingFiles);
}
+ /**
+ * Starts a run on spooled uploads and deletes them once it settles, or straight away if {@code
+ * start} throws. {@code start} must not throw once the run is submitted, or the uploads are
+ * deleted under it.
+ */
+ private static PolicyRunHandle startOnUploads(
+ PolicyInputs uploads, Supplier<PolicyRunHandle> start) {
+ PolicyRunHandle handle;
+ try {
+ handle = start.get();
+ } catch (RuntimeException e) {
+ deleteUploads(uploads);
+ throw e;
+ }
+ handle.completion().whenComplete((run, error) -> deleteUploads(uploads));
+ return handle;
+ }
+
+ private static void deleteUploads(PolicyInputs uploads) {
+ List<Resource> all = new ArrayList<>(uploads.primary());
+ uploads.supportingFiles().values().forEach(all::addAll);
+ for (Resource upload : all) {
+ if (upload instanceof InternalApiClient.TempFileResource spooled) {
+ spooled.getTempFile().close();
+ }
+ }
+ }
+
/**
* Only for a single-document run: an incident holds one file reference, so naming one of
* several would attribute the failure to whichever bound first. Counted off resolved inputs,
@@ -859,33 +916,19 @@ public class PolicyController {
}
}
- private List<Resource> toResources(List<MultipartFile> files) throws IOException {
- List<Resource> resources = new ArrayList<>();
- if (files == null) {
- return resources;
- }
- for (MultipartFile file : files) {
- Resource resource = toResource(file);
- if (resource != null) {
- resources.add(resource);
- }
- }
- return resources;
- }
-
/** Spool a single uploaded file to a managed temp file, preserving its name; null if empty. */
private Resource toResource(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
return null;
}
TempFile tempFile = tempFileManager.createManagedTempFile("policy-run");
- file.transferTo(tempFile.getPath());
- final String originalName = Filenames.toSimpleFileName(file.getOriginalFilename());
- return new FileSystemResource(tempFile.getFile()) {
- @Override
- public String getFilename() {
- return originalName;
- }
- };
+ try {
+ file.transferTo(tempFile.getPath());
+ } catch (IOException | RuntimeException e) {
+ tempFile.close();
+ throw e;
+ }
+ return new InternalApiClient.TempFileResource(
+ tempFile, Filenames.toSimpleFileName(file.getOriginalFilename()));
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
index 02e5773cf7..295905362a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
@@ -392,13 +392,13 @@ public class PolicyEngine {
// hop already happened) so every tool sub-step dispatched via InternalApiClient groups into
// a single charge, and two separate policy runs on the same document stay distinct charges.
try (AutomationRunContext.Scope runScope = AutomationRunContext.open(runId)) {
+ PolicyExecutionResult result = null;
try {
if (!run.markRunning()) {
// Cancelled before it started: nothing runs, nothing delivers.
return;
}
- PolicyExecutionResult result =
- stepExecutor.execute(run.getDefinition(), inputs, listener);
+ result = stepExecutor.execute(run.getDefinition(), inputs, listener);
if (!run.beginDelivery()) {
// Cancelled while the steps ran: discard the produced files —
// delivering would stamp results over files being restored right now.
@@ -466,6 +466,10 @@ public class PolicyEngine {
taskManager.setError(runId, message);
recordFailure(run, message, e);
} finally {
+ // Delivery stored its own copies, so the step outputs are not needed any longer.
+ if (result != null) {
+ result.close();
+ }
// Always resolve so stream/await callers unblock.
completion.complete(run);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutionResult.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutionResult.java
index 2d5552517c..6c1201c1c7 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutionResult.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutionResult.java
@@ -4,6 +4,8 @@ import java.util.List;
import org.springframework.core.io.Resource;
+import stirling.software.common.util.TempFile;
+
import tools.jackson.databind.JsonNode;
/**
@@ -12,7 +14,19 @@ import tools.jackson.databind.JsonNode;
* inputs that the output traces back to, or {@code null} when it has no single source (e.g. a merge
* combining several inputs, or a generated file). Callers use it to map an output back onto the
* file it came from. {@code report}/{@code reportTool} carry the last step's structured report and
- * its operation, or null if no step produced one.
+ * its operation, or null if no step produced one. {@code tempFiles} are all the temp files the
+ * steps produced, {@code files} included; close the result once the files have been stored.
*/
public record PolicyExecutionResult(
- List<Resource> files, List<Integer> origins, JsonNode report, String reportTool) {}
+ List<Resource> files,
+ List<Integer> origins,
+ JsonNode report,
+ String reportTool,
+ List<TempFile> tempFiles)
+ implements AutoCloseable {
+
+ @Override
+ public void close() {
+ tempFiles.forEach(TempFile::close);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
index 5fb8753bee..d817f19c36 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java
@@ -20,11 +20,14 @@ import org.springframework.util.MultiValueMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
import stirling.software.proprietary.policy.model.PipelineDefinition;
@@ -56,6 +59,7 @@ public class PolicyExecutor {
private final ToolMetadataService toolMetadataService;
private final TempFileManager tempFileManager;
private final ObjectMapper objectMapper;
+ private final ApplicationProperties applicationProperties;
// files: result files (one, or many for ZIP-response tools). report: optional structured
// payload the tool surfaced alongside or instead of a file.
@@ -71,14 +75,36 @@ public class PolicyExecutor {
* inputs} bind to named file fields and never enter the document stream.
*
* @throws InternalApiTimeoutException if a tool does not respond within its read timeout
+ * @throws PipelineLimits.LimitExceededException if the run breaks {@code policies.maxSteps} or
+ * {@code policies.maxFilesPerStep}
* @throws IOException on a non-OK tool response, a missing supporting file, or a read failure
*/
public PolicyExecutionResult execute(
PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener)
throws IOException {
+ List<TempFile> tempFiles = new ArrayList<>();
+ try {
+ return executeSteps(definition, inputs, listener, tempFiles);
+ } catch (PolicyInputRequiredException e) {
+ // The engine persists the pending files before it suspends the run: keep them
+ throw e;
+ } catch (IOException | RuntimeException e) {
+ // The caller never receives the result, so release the earlier steps' outputs here
+ tempFiles.forEach(TempFile::close);
+ throw e;
+ }
+ }
+
+ private PolicyExecutionResult executeSteps(
+ PipelineDefinition definition,
+ PolicyInputs inputs,
+ PolicyProgressListener listener,
+ List<TempFile> tempFiles)
+ throws IOException {
// Zero steps is a pure routing policy: inputs pass through unchanged and
// are delivered to the policy's output destinations.
List<PipelineStep> steps = definition.steps();
+ PipelineLimits.requireWithinStepLimit(steps.size(), applicationProperties.getPolicies());
List<PipelineFile> currentFiles = new ArrayList<>();
Map<String, List<Resource>> supportingFiles = inputs.supportingFiles();
@@ -97,8 +123,10 @@ public class PolicyExecutor {
"Pipeline step " + (i + 1) + " has no operation");
}
listener.onStepStart(i + 1, steps.size(), operation);
- StepOutput stepResult = executeStep(step, currentFiles, supportingFiles);
+ int consumedTempFiles = tempFiles.size();
+ StepOutput stepResult = executeStep(step, currentFiles, supportingFiles, tempFiles);
currentFiles = stepResult.files();
+ releaseTempFiles(tempFiles, consumedTempFiles);
if (stepResult.report() != null) {
lastReport = stepResult.report();
lastReportTool = operation;
@@ -110,7 +138,8 @@ public class PolicyExecutor {
currentFiles.stream().map(PipelineFile::resource).toList(),
currentFiles.stream().map(PipelineFile::origin).toList(),
lastReport,
- lastReportTool);
+ lastReportTool,
+ tempFiles);
}
/**
@@ -121,7 +150,8 @@ public class PolicyExecutor {
private StepOutput executeStep(
PipelineStep step,
List<PipelineFile> inputFiles,
- Map<String, List<Resource>> supportingFiles)
+ Map<String, List<Resource>> supportingFiles,
+ List<TempFile> tempFiles)
throws IOException {
List<Resource> resources = inputFiles.stream().map(PipelineFile::resource).toList();
requireAcceptedTypes(step.operation(), resources);
@@ -135,27 +165,32 @@ public class PolicyExecutor {
inputFiles.isEmpty() ? null : inputFiles.getLast().billingOrigin();
ToolResult r;
try (AutomationRunContext.Scope doc = documentScope(billingOrigin)) {
- r = callEndpoint(step, resources, supportingFiles);
+ r = callEndpoint(step, resources, supportingFiles, tempFiles);
}
for (Resource file : r.files()) {
files.add(new PipelineFile(file, origin, billingOrigin));
}
+ requireWithinFileLimit(step, files);
report = r.report();
} else if (inputFiles.isEmpty()) {
- ToolResult r = callEndpoint(step, List.of(), supportingFiles);
+ ToolResult r = callEndpoint(step, List.of(), supportingFiles, tempFiles);
for (Resource file : r.files()) {
files.add(new PipelineFile(file, null, null));
}
+ requireWithinFileLimit(step, files);
report = r.report();
} else {
for (PipelineFile input : inputFiles) {
ToolResult r;
try (AutomationRunContext.Scope doc = documentScope(input.billingOrigin())) {
- r = callEndpoint(step, List.of(input.resource()), supportingFiles);
+ r = callEndpoint(step, List.of(input.resource()), supportingFiles, tempFiles);
}
for (Resource file : r.files()) {
files.add(new PipelineFile(file, input.origin(), input.billingOrigin()));
}
+ // Checked per call, not after the loop: by then a split step has already made
+ // inputs x divisions files.
+ requireWithinFileLimit(step, files);
if (report == null) {
report = r.report();
}
@@ -164,6 +199,18 @@ public class PolicyExecutor {
return new StepOutput(files, report);
}
+ private void requireWithinFileLimit(PipelineStep step, List<PipelineFile> files) {
+ PipelineLimits.requireWithinFileLimit(
+ step.operation(), files.size(), applicationProperties.getPolicies());
+ }
+
+ /** Deletes the {@code count} temp files added first. */
+ private static void releaseTempFiles(List<TempFile> tempFiles, int count) {
+ List<TempFile> released = tempFiles.subList(0, count);
+ released.forEach(TempFile::close);
+ released.clear();
+ }
+
private static Integer sharedOrigin(List<PipelineFile> files) {
if (files.isEmpty()) {
return null;
@@ -189,7 +236,10 @@ public class PolicyExecutor {
* unpacked to a flat file list.
*/
private ToolResult callEndpoint(
- PipelineStep step, List<Resource> files, Map<String, List<Resource>> supportingFiles)
+ PipelineStep step,
+ List<Resource> files,
+ Map<String, List<Resource>> supportingFiles,
+ List<TempFile> tempFiles)
throws IOException {
String endpointPath = step.operation();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
@@ -233,6 +283,9 @@ public class PolicyExecutor {
}
}
ResponseEntity<Resource> response = internalApiClient.post(endpointPath, body);
+ if (response.getBody() instanceof InternalApiClient.TempFileResource tempFileResource) {
+ tempFiles.add(tempFileResource.getTempFile());
+ }
if (!HttpStatus.OK.equals(response.getStatusCode()) || response.getBody() == null) {
throw new IOException(
"Tool returned HTTP " + response.getStatusCode() + " for " + endpointPath);
@@ -258,7 +311,9 @@ public class PolicyExecutor {
JsonNode report = parseReportHeader(headers, endpointPath);
if (toolMetadataService.shouldUnpackZipResponse(endpointPath)) {
- return new ToolResult(ZipExtractionUtils.extractZip(resource, tempFileManager), report);
+ return new ToolResult(
+ ZipExtractionUtils.extractZip(resource, tempFileManager, tempFiles::add),
+ report);
}
return new ToolResult(List.of(resource), report);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
index 2f2d44597a..966cd91b7f 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java
@@ -196,7 +196,13 @@ public class PolicyRunner {
requireDatabaseAccess();
PolicyRunHandle handle =
policyEngine.runPolicy(policy, inputs, listener, null, documentReference);
- docCounter.record(EditorSource.counterKey(policy.teamId()), inputs.primary().size());
+ try {
+ docCounter.record(EditorSource.counterKey(policy.teamId()), inputs.primary().size());
+ } catch (RuntimeException e) {
+ // The run is already executing; failing the call would have the caller clean up the
+ // inputs it is reading.
+ log.warn("Could not count editor documents for policy {}", policy.id(), e);
+ }
return handle;
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
index e281ac18fe..f12fe290ad 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java
@@ -1,5 +1,6 @@
package stirling.software.proprietary.policy.engine;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -8,9 +9,11 @@ import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.tool.ToolDiagnostic;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.service.ToolChainValidator;
+import stirling.software.common.util.PipelineLimits;
import stirling.software.proprietary.document.conditions.ConditionValidator;
import stirling.software.proprietary.policy.asset.PolicyAssetRefs;
import stirling.software.proprietary.policy.asset.PolicyAssetStore;
@@ -47,6 +50,7 @@ public class PolicyValidator {
private final SourceStore sourceStore;
private final PolicyAssetStore assetStore;
private final ToolChainValidator toolChainValidator;
+ private final ApplicationProperties applicationProperties;
/**
* @throws IllegalArgumentException if the policy has more than one input or output, any facet's
@@ -207,7 +211,17 @@ public class PolicyValidator {
new ToolChainValidator.Step(
step.operation(), step.parameters()))
.toList();
- return toolChainValidator.validate(chain, sourceFormat);
+ List<ToolDiagnostic> diagnostics =
+ new ArrayList<>(toolChainValidator.validate(chain, sourceFormat));
+ ApplicationProperties.Policies policies = applicationProperties.getPolicies();
+ if (PipelineLimits.exceedsStepLimit(steps.size(), policies)) {
+ diagnostics.add(
+ ToolDiagnostic.error(
+ policies.getMaxSteps(),
+ ToolDiagnostic.TOO_MANY_STEPS,
+ PipelineLimits.stepLimitMessage(policies)));
+ }
+ return diagnostics;
}
/**
@@ -216,10 +230,11 @@ public class PolicyValidator {
* #validateOutput(OutputSpec)}: a step that dereferences an integration connection by id is
* access-checked here or nowhere, since the worker thread that later runs it has no principal.
*
- * @throws IllegalArgumentException if any step is invalid or references an inaccessible
- * resource
+ * @throws IllegalArgumentException if there are more than {@code policies.maxSteps} steps, or
+ * any step is invalid or references an inaccessible resource
*/
public void validateSteps(List<PipelineStep> steps) {
+ PipelineLimits.requireWithinStepLimit(steps.size(), applicationProperties.getPolicies());
for (PipelineStep step : steps) {
for (PipelineStepValidator validator : stepValidators) {
validator.validate(step);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiWorkflowService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiWorkflowService.java
index 80cd0cff7f..43b7836b08 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiWorkflowService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiWorkflowService.java
@@ -13,7 +13,6 @@ import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
@@ -31,6 +30,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.FileStorage;
+import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.ExceptionUtils;
@@ -346,14 +346,14 @@ public class AiWorkflowService {
private Resource toResource(MultipartFile file) throws IOException {
TempFile tempFile = tempFileManager.createManagedTempFile("ai-workflow");
- file.transferTo(tempFile.getPath());
- final String originalName = Filenames.toSimpleFileName(file.getOriginalFilename());
- return new FileSystemResource(tempFile.getFile()) {
- @Override
- public String getFilename() {
- return originalName;
- }
- };
+ try {
+ file.transferTo(tempFile.getPath());
+ } catch (IOException | RuntimeException e) {
+ tempFile.close();
+ throw e;
+ }
+ return new InternalApiClient.TempFileResource(
+ tempFile, Filenames.toSimpleFileName(file.getOriginalFilename()));
}
private void ingestFile(AiFile file, MultipartFile multipartFile) throws IOException {
@@ -403,14 +403,16 @@ public class AiWorkflowService {
parameters = Map.of();
}
+ List<Resource> inputFiles = List.of();
+ PolicyExecutionResult result = null;
try {
- List<Resource> inputFiles = toResources(filesById);
+ inputFiles = toResources(filesById);
PipelineDefinition definition =
new PipelineDefinition(
null,
List.of(new PipelineStep(endpointPath, parameters)),
OutputSpec.inline());
- PolicyExecutionResult result =
+ result =
policyExecutor.execute(
definition, PolicyInputs.of(inputFiles), stepProgress(listener));
return new WorkflowState.Terminal(
@@ -434,6 +436,13 @@ public class AiWorkflowService {
}
log.error("Failed to execute tool {}: {}", endpointPath, e.getMessage(), e);
return new WorkflowState.Terminal(cannotContinue(toolFailureMessage(endpointPath, e)));
+ } finally {
+ // The response refers to stored copies, so the inputs and step outputs are not needed
+ // any longer
+ if (result != null) {
+ result.close();
+ }
+ deleteCopies(inputFiles);
}
}
@@ -511,11 +520,13 @@ public class AiWorkflowService {
pipelineSteps.add(new PipelineStep(endpointPath, parameters));
}
+ List<Resource> inputFiles = List.of();
+ PolicyExecutionResult result = null;
try {
- List<Resource> inputFiles = toResources(filesById);
+ inputFiles = toResources(filesById);
PipelineDefinition definition =
new PipelineDefinition(summary, pipelineSteps, OutputSpec.inline());
- PolicyExecutionResult result =
+ result =
policyExecutor.execute(
definition, PolicyInputs.of(inputFiles), stepProgress(listener));
@@ -563,6 +574,13 @@ public class AiWorkflowService {
log.error("Failed to execute plan: {}", e.getMessage(), e);
return new WorkflowState.Terminal(
cannotContinue("Plan execution failed: " + e.getMessage()));
+ } finally {
+ // The response refers to stored copies, so the inputs and step outputs are not needed
+ // any longer
+ if (result != null) {
+ result.close();
+ }
+ deleteCopies(inputFiles);
}
}
@@ -621,14 +639,30 @@ public class AiWorkflowService {
};
}
+ /**
+ * Copies the uploads to temp files; the caller passes them to {@link #deleteCopies} when done.
+ */
private List<Resource> toResources(Map<String, MultipartFile> filesById) throws IOException {
List<Resource> resources = new ArrayList<>();
- for (MultipartFile file : filesById.values()) {
- resources.add(toResource(file));
+ try {
+ for (MultipartFile file : filesById.values()) {
+ resources.add(toResource(file));
+ }
+ } catch (IOException | RuntimeException e) {
+ deleteCopies(resources);
+ throw e;
}
return resources;
}
+ private static void deleteCopies(List<Resource> copies) {
+ for (Resource copy : copies) {
+ if (copy instanceof InternalApiClient.TempFileResource tempFileResource) {
+ tempFileResource.getTempFile().close();
+ }
+ }
+ }
+
private AiWorkflowResponse buildCompletedResponse(
String summary,
List<Resource> resultFiles,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java
index ebe6d52fcc..4c1f7e58ea 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java
@@ -88,7 +88,11 @@ class PolicyAutomationBillingDbTest {
TempFileManager tempFiles = new TempFileManager(new TempFileRegistry(), properties);
executor =
new PolicyExecutor(
- internalApiClient, metadata, tempFiles, JsonMapper.builder().build());
+ internalApiClient,
+ metadata,
+ tempFiles,
+ JsonMapper.builder().build(),
+ new ApplicationProperties());
interceptor =
new InstanceEntitlementInterceptor(
gate, entitlementCache, meterProvider, freeTierUsageService, tempFiles);
@@ -249,12 +253,17 @@ class PolicyAutomationBillingDbTest {
switch (operation) {
case SPLIT -> splitOutput();
case MERGE -> file("merged.bin", new byte[] {1, 2});
- default -> (Resource) body.getFirst("fileInput");
+ default -> answerWith((Resource) body.getFirst("fileInput"));
};
interceptor.afterCompletion(request, response, this, null);
return ResponseEntity.ok(output);
}
+ /** Like InternalApiClient, a new file: the executor deletes a step's inputs once it has run. */
+ private static Resource answerWith(Resource input) throws IOException {
+ return file(input.getFilename(), input.getContentAsByteArray());
+ }
+
private static Resource splitOutput() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java
index 34c400c9d5..6c7b830466 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java
@@ -116,7 +116,8 @@ class PolicyFailureAttributionTest {
internalApiClient,
toolMetadataService,
new TempFileManager(new TempFileRegistry(), props),
- JsonMapper.builder().build());
+ JsonMapper.builder().build(),
+ new ApplicationProperties());
engine =
new PolicyEngine(
executor,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java
index 876a52fe47..6d6391516d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java
@@ -108,7 +108,8 @@ class PolicyFailureOwnershipTest {
internalApiClient,
toolMetadataService,
new TempFileManager(new TempFileRegistry(), props),
- JsonMapper.builder().build());
+ JsonMapper.builder().build(),
+ new ApplicationProperties());
engine =
new PolicyEngine(
executor,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultFilesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultFilesTest.java
new file mode 100644
index 0000000000..6fc2e035c5
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultFilesTest.java
@@ -0,0 +1,75 @@
+package stirling.software.proprietary.integration.api;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.core.io.Resource;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+
+class ResultFilesTest {
+
+ @TempDir Path tempDir;
+
+ private TempFileManager tempFileManager;
+
+ @BeforeEach
+ void setUp() {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
+ tempFileManager = new TempFileManager(new TempFileRegistry(), props);
+ }
+
+ @Test
+ void selectedEntryOutlivesTheUnpackedArchive() throws IOException {
+ Resource archive = ResultFiles.asResource(zipOf("cover.txt", "signed.pdf"), "bundle.zip");
+
+ Resource selected = ResultFiles.selectFromArchive(archive, "*.pdf", tempFileManager);
+
+ assertEquals("signed.pdf", selected.getFilename());
+ assertEquals("signed.pdf content", selected.getContentAsString(StandardCharsets.UTF_8));
+ assertNoTempFilesLeft();
+ }
+
+ @Test
+ void unpackedArchiveIsDeletedWhenNothingMatches() throws IOException {
+ Resource archive = ResultFiles.asResource(zipOf("cover.txt"), "bundle.zip");
+
+ assertThrows(
+ IOException.class,
+ () -> ResultFiles.selectFromArchive(archive, "*.pdf", tempFileManager));
+ assertNoTempFilesLeft();
+ }
+
+ private void assertNoTempFilesLeft() throws IOException {
+ try (Stream<Path> left = Files.list(tempDir)) {
+ assertEquals(0, left.count());
+ }
+ }
+
+ private static byte[] zipOf(String... names) throws IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
+ for (String name : names) {
+ zip.putNextEntry(new ZipEntry(name));
+ zip.write((name + " content").getBytes(StandardCharsets.UTF_8));
+ zip.closeEntry();
+ }
+ }
+ return bytes.toByteArray();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index cba7bdde00..1dcc947553 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -15,6 +15,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
+import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@@ -60,6 +61,7 @@ import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PipelineValidation;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.PolicyRunView;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
@@ -302,6 +304,44 @@ class PolicyControllerTest {
verify(docCounter).record(EditorSource.counterKey(3L), 0L);
}
+ @Test
+ @DisplayName("deletes the uploaded files once the run settles")
+ void uploadsAreDeletedOnceTheRunSettles() throws Exception {
+ CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
+ ArgumentCaptor<PolicyInputs> inputs = ArgumentCaptor.forClass(PolicyInputs.class);
+ when(policyRunner.runAdHoc(any(), inputs.capture(), eq(PolicyProgressListener.NOOP)))
+ .thenReturn(new PolicyRunHandle("run-1", completion));
+
+ controller.run(requestWithStep(), null, oneUpload());
+
+ File upload = inputs.getValue().primary().get(0).getFile();
+ assertThat(upload).exists();
+ completion.complete(null);
+ assertThat(upload).doesNotExist();
+ }
+
+ @Test
+ @DisplayName("deletes the uploaded files when the run cannot start")
+ void uploadsAreDeletedWhenTheRunCannotStart() throws Exception {
+ ArgumentCaptor<PolicyInputs> inputs = ArgumentCaptor.forClass(PolicyInputs.class);
+ when(policyRunner.runAdHoc(any(), inputs.capture(), eq(PolicyProgressListener.NOOP)))
+ .thenThrow(new IllegalStateException("no licence"));
+
+ assertThatThrownBy(() -> controller.run(requestWithStep(), null, oneUpload()))
+ .isInstanceOf(IllegalStateException.class);
+
+ assertThat(inputs.getValue().primary().get(0).getFile()).doesNotExist();
+ }
+
+ private PolicyRunFiles oneUpload() {
+ PolicyRunFiles files = new PolicyRunFiles();
+ files.setFileInput(
+ List.of(
+ new MockMultipartFile(
+ "fileInput", "a.pdf", "application/pdf", "pdf".getBytes())));
+ return files;
+ }
+
@Test
@DisplayName("rejects a pipeline with no steps")
void rejectsEmptyPipeline() {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
index 524321075a..f281ef5852 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
@@ -196,7 +196,8 @@ class ProcessingFolderControllerTest {
List.of(),
sourceStore,
assetStore,
- toolChainValidator);
+ toolChainValidator,
+ new ApplicationProperties());
controller =
new ProcessingFolderController(
policyStore,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java
index 5e60383914..2734c0f86d 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java
@@ -87,7 +87,8 @@ class PolicyEngineRoutingTest {
internalApiClient,
toolMetadataService,
new TempFileManager(new TempFileRegistry(), props),
- JsonMapper.builder().build());
+ JsonMapper.builder().build(),
+ new ApplicationProperties());
engine =
new PolicyEngine(
executor,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
index 23c5f6c850..f1a28c0c04 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java
@@ -129,7 +129,8 @@ class PolicyEngineTest {
internalApiClient,
toolMetadataService,
tempFileManager,
- JsonMapper.builder().build());
+ JsonMapper.builder().build(),
+ new ApplicationProperties());
registry = new PolicyRunRegistry(new ApplicationProperties());
InlineOutputSink sink = new InlineOutputSink(fileStorage);
PolicyOutputResolver outputResolver = new PolicyOutputResolver(sourceStore);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
index 68ea8f9a92..c6831b1689 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java
@@ -13,17 +13,20 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -44,6 +47,8 @@ import stirling.software.common.service.AutomationRunContext;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
+import stirling.software.common.util.PipelineLimits;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
import stirling.software.proprietary.policy.model.OutputSpec;
@@ -74,19 +79,23 @@ class PolicyExecutorTest {
@TempDir Path tempDir;
+ private final ApplicationProperties props = new ApplicationProperties();
private TempFileManager tempFileManager;
private PolicyExecutor executor;
@BeforeEach
void setUp() {
- ApplicationProperties props = new ApplicationProperties();
props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
props.getSystem().getTempFileManagement().setPrefix("policy-test-");
tempFileManager = new TempFileManager(new TempFileRegistry(), props);
ObjectMapper objectMapper = JsonMapper.builder().build();
executor =
new PolicyExecutor(
- internalApiClient, toolMetadataService, tempFileManager, objectMapper);
+ internalApiClient,
+ toolMetadataService,
+ tempFileManager,
+ objectMapper,
+ props);
}
@Test
@@ -367,6 +376,51 @@ class PolicyExecutorTest {
PolicyProgressListener.NOOP));
}
+ @Test
+ void eachStepsOutputsGoOnceTheNextStepHasRunAndTheLastOnClose() throws IOException {
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
+ TempFile rotated = tempFileManager.createManagedTempFile("internal-api");
+ TempFile compressed = tempFileManager.createManagedTempFile("internal-api");
+ stubEndpoint(ROTATE, new InternalApiClient.TempFileResource(rotated, "rotated.pdf"));
+ stubEndpoint(COMPRESS, new InternalApiClient.TempFileResource(compressed, "small.pdf"));
+
+ try (PolicyExecutionResult result =
+ executor.execute(
+ definition(
+ new PipelineStep(ROTATE, Map.of()),
+ new PipelineStep(COMPRESS, Map.of())),
+ PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
+ PolicyProgressListener.NOOP)) {
+ assertFalse(rotated.exists());
+ assertTrue(result.files().get(0).exists());
+ }
+
+ assertFalse(compressed.exists());
+ }
+
+ @Test
+ void failingStepReleasesEarlierStepOutputs() throws IOException {
+ when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(ROTATE)).thenReturn(false);
+ TempFile rotated = tempFileManager.createManagedTempFile("internal-api");
+ stubEndpoint(ROTATE, new InternalApiClient.TempFileResource(rotated, "rotated.pdf"));
+ when(internalApiClient.post(eq(COMPRESS), any()))
+ .thenThrow(new IllegalStateException("step failed"));
+
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ executor.execute(
+ definition(
+ new PipelineStep(ROTATE, Map.of()),
+ new PipelineStep(COMPRESS, Map.of())),
+ PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
+ PolicyProgressListener.NOOP));
+
+ assertFalse(rotated.exists());
+ }
+
@Test
void emptyStepsPassInputsThroughUnchanged() throws Exception {
// A pure routing policy has no steps: inputs are delivered to the
@@ -417,6 +471,58 @@ class PolicyExecutorTest {
assertTrue(docIds.get(0).startsWith("run-x:")); // run-scoped
}
+ @Test
+ void definitionWithMoreStepsThanTheLimitIsRefused() {
+ props.getPolicies().setMaxSteps(2);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ executor.execute(
+ definition(
+ new PipelineStep(ROTATE, Map.of()),
+ new PipelineStep(ROTATE, Map.of()),
+ new PipelineStep(ROTATE, Map.of())),
+ PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
+ PolicyProgressListener.NOOP));
+
+ verifyNoInteractions(internalApiClient);
+ }
+
+ @Test
+ void stepProducingMoreFilesThanTheLimitAbortsTheRunAndReleasesItsFiles() throws IOException {
+ props.getPolicies().setMaxFilesPerStep(5);
+ when(toolMetadataService.isMultiInput(SPLIT)).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(SPLIT)).thenReturn(true);
+ List<Entry> pages =
+ List.of(
+ new Entry("p1.pdf", "1"),
+ new Entry("p2.pdf", "2"),
+ new Entry("p3.pdf", "3"));
+ when(internalApiClient.post(eq(SPLIT), any()))
+ .thenAnswer(inv -> ResponseEntity.ok(zip("split.zip", pages)));
+
+ PipelineLimits.LimitExceededException failure =
+ assertThrows(
+ PipelineLimits.LimitExceededException.class,
+ () ->
+ executor.execute(
+ definition(new PipelineStep(SPLIT, Map.of())),
+ PolicyInputs.of(
+ List.of(
+ pdf("a", "a.pdf"),
+ pdf("b", "b.pdf"),
+ pdf("c", "c.pdf"))),
+ PolicyProgressListener.NOOP));
+
+ assertTrue(failure.getMessage().contains("policies.maxFilesPerStep"));
+ // Stopped at the second input's call, when 6 files passed the limit of 5.
+ verify(internalApiClient, times(2)).post(eq(SPLIT), any());
+ try (Stream<Path> left = Files.list(tempDir)) {
+ assertEquals(0, left.count());
+ }
+ }
+
private void stubEndpoint(String endpoint, Resource body) {
when(internalApiClient.post(eq(endpoint), any())).thenReturn(ResponseEntity.ok(body));
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
index a0f9879ff0..749dde0940 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java
@@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -61,6 +62,7 @@ import stirling.software.proprietary.policy.source.EditorSource;
import stirling.software.proprietary.policy.source.InProcessSourceDocCounter;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
import stirling.software.proprietary.policy.source.Source;
+import stirling.software.proprietary.policy.source.SourceDocCounter;
import stirling.software.proprietary.policy.source.SourceStore;
/**
@@ -596,6 +598,34 @@ class PolicyRunnerTest {
verifyNoInteractions(folderSource);
}
+ @Test
+ void aFailedDocumentCountDoesNotFailARunThatHasStarted() {
+ SourceDocCounter failingCounter = mock(SourceDocCounter.class);
+ doThrow(new IllegalStateException("database down"))
+ .when(failingCounter)
+ .record(any(), anyLong());
+ PolicyRunner countingRunner =
+ new PolicyRunner(
+ policyEngine,
+ List.of(folderSource),
+ sourceStore,
+ failingCounter,
+ processedLedger,
+ new ApplicationProperties(),
+ reachableOwners(),
+ databaseLicenseGuard,
+ mock(PolicyFailureRecorder.class),
+ eventPublisher);
+ Policy policy = policy(List.of(InputSpec.folder("/in")));
+ PolicyInputs inputs = PolicyInputs.of(List.of());
+ PolicyRunHandle handle = new PolicyRunHandle("r", new CompletableFuture<>());
+ when(policyEngine.runPolicy(policy, inputs, PolicyProgressListener.NOOP, null, null))
+ .thenReturn(handle);
+
+ assertSame(
+ handle, countingRunner.runWith(policy, inputs, PolicyProgressListener.NOOP, null));
+ }
+
@Test
void anAttendedRunCarriesTheClientsOwnDocumentReferenceAndNoSource() {
// A failure of this run can then name the document the user is still holding, and the null
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
index 73a29a04b1..c577c80540 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java
@@ -20,7 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.tool.ToolArity;
+import stirling.software.common.model.tool.ToolDiagnostic;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIOSource;
import stirling.software.common.model.tool.ToolIOSpec;
@@ -57,6 +59,7 @@ class PolicyValidatorTest {
private final SourceStore sourceStore = new InProcessSourceStore();
private final PolicyAssetStore assetStore = new InProcessPolicyAssetStore();
+ private final ApplicationProperties props = new ApplicationProperties();
private PolicyValidator validator;
@BeforeEach
@@ -69,7 +72,8 @@ class PolicyValidatorTest {
List.of(stepValidator),
sourceStore,
assetStore,
- new ToolChainValidator(path -> java.util.Optional.empty()));
+ new ToolChainValidator(path -> java.util.Optional.empty()),
+ props);
}
@ParameterizedTest
@@ -348,6 +352,33 @@ class PolicyValidatorTest {
ToolArity.SISO,
List.of())));
+ @Test
+ void diagnoseChainFlagsTheFirstStepPastTheLimit() {
+ props.getPolicies().setMaxSteps(2);
+ PipelineStep step = new PipelineStep("/api/v1/general/rotate-pdf", Map.of());
+
+ List<ToolDiagnostic> diagnostics = validator.diagnoseChain(List.of(step, step, step), null);
+
+ assertTrue(
+ diagnostics.contains(
+ ToolDiagnostic.error(
+ 2,
+ ToolDiagnostic.TOO_MANY_STEPS,
+ "A pipeline may have at most 2 steps; raise policies.maxSteps to"
+ + " allow more")));
+ }
+
+ @Test
+ void refusesMoreStepsThanTheLimit() {
+ props.getPolicies().setMaxSteps(2);
+ PipelineStep step = new PipelineStep("/api/v1/general/rotate-pdf", Map.of());
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> validator.validateSteps(List.of(step, step, step)));
+ verify(stepValidator, never()).validate(any());
+ }
+
private PolicyValidator validatorWith(ToolIOSource toolIO) {
return new PolicyValidator(
List.of(trigger),
@@ -356,7 +387,8 @@ class PolicyValidatorTest {
List.of(stepValidator),
sourceStore,
assetStore,
- new ToolChainValidator(toolIO));
+ new ToolChainValidator(toolIO),
+ props);
}
private Policy withSteps(String... operations) {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceMoreTest.java
index 7c44a40a5d..687aeda3ad 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceMoreTest.java
@@ -90,7 +90,11 @@ class AiWorkflowServiceMoreTest {
PolicyExecutor policyExecutor =
new PolicyExecutor(
- internalApiClient, toolMetadataService, tempFileManager, objectMapper);
+ internalApiClient,
+ toolMetadataService,
+ tempFileManager,
+ objectMapper,
+ new ApplicationProperties());
service =
new AiWorkflowService(
pdfDocumentFactory,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java
index b99f7a30e2..14660c27a9 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java
@@ -21,11 +21,13 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
+import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -112,7 +114,11 @@ class AiWorkflowServiceTest {
PolicyExecutor policyExecutor =
new PolicyExecutor(
- internalApiClient, toolMetadataService, tempFileManager, objectMapper);
+ internalApiClient,
+ toolMetadataService,
+ tempFileManager,
+ objectMapper,
+ new ApplicationProperties());
service =
new AiWorkflowService(
pdfDocumentFactory,
@@ -153,6 +159,25 @@ class AiWorkflowServiceTest {
verify(internalApiClient, times(1)).post(eq(ROTATE_ENDPOINT), any());
}
+ @Test
+ void toolCallDeletesItsCopiesOfTheInputs() throws IOException {
+ stubOrchestrator(
+ """
+ {"outcome":"tool_call","tool":"%s","parameters":{"angle":90},"rationale":"Rotating"}
+ """
+ .formatted(ROTATE_ENDPOINT));
+ when(toolMetadataService.isMultiInput(ROTATE_ENDPOINT)).thenReturn(false);
+ when(toolMetadataService.shouldUnpackZipResponse(ROTATE_ENDPOINT)).thenReturn(false);
+ stubEndpoint(ROTATE_ENDPOINT, pdfResource("rotated-bytes", "rotated.pdf"));
+ stubFileStorage();
+
+ service.orchestrate(requestFor(pdf("input.pdf", "original-pdf-bytes"), "rotate 90"));
+
+ try (Stream<Path> left = Files.list(tempDir)) {
+ assertTrue(left.noneMatch(path -> path.toString().endsWith("ai-workflow")));
+ }
+ }
+
@Test
void toolCallZipResponseUnpacksIntoMultipleResults() throws IOException {
MockMultipartFile input = pdf("doc.pdf", "original");