#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix pipeline failures when outputs are unavailable (#7981)
Anthony Stirling707761c6f919
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.javaindex 9e277c7dbd..6a0c038041 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@@ -191,15 +191,33 @@ public class PolicyEngine {// the triggering user, or the run goes out principal-less and its tool sub-steps bill the// team-less INTERNAL_API_USER, which PAYG refuses with a usage-limit 402.String billingPrincipal = policy.owner() != null ? policy.owner() : triggeringUser;- // Stored supporting files (certificates, watermark images, ...) load here, before the- // async hop: worker threads have no principal, so assets bind by the policy's own team.- PolicyInputs resolved = assetResolver.resolve(policy, inputs);- // Resolve the referenced output destinations live (like sourceIds), so a stored policy- // delivers to each of its saved Source destinations. Unreferenced policies fall back to- // their inline output.- PipelineDefinition definition =- new PipelineDefinition(- policy.name(), policy.steps(), outputResolver.resolve(policy));+ PolicyInputs resolved;+ PipelineDefinition definition;+ try {+ // Supporting files and destinations resolve before the worker loses the request+ // principal.+ resolved = assetResolver.resolve(policy, inputs);+ definition =+ new PipelineDefinition(+ policy.name(), policy.steps(), outputResolver.resolve(policy));+ } catch (RuntimeException e) {+ if (sourceId == null) {+ throw e;+ }+ // Sources already claimed their inputs; a terminal handle settles every claim normally.+ PolicyRun run =+ registerRun(+ policy.id(),+ new PipelineDefinition(policy.name(), policy.steps(), List.of()),+ sourceId,+ fileIdentity,+ triggeringUser);+ String message = "Policy run could not start: " + e.getMessage();+ run.fail(message);+ taskManager.setError(run.getRunId(), message);+ recordFailure(run, message, e);+ return new PolicyRunHandle(run.getRunId(), CompletableFuture.completedFuture(run));+ }return submitForPrincipal(billingPrincipal,fileOwner,@@ -226,17 +244,8 @@ public class PolicyEngine {String sourceId,String fileIdentity,Semaphore admission) {- // Scope the run id to the current user (this request thread) so the file-download- // ownership check passes. No-op when security is off.- String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());- taskManager.createTask(runId);- // Tag the shared job entry with the policy id so peers can list it as a policy run.- if (policyId != null) {- taskManager.putMetadata(runId, "policyId", policyId);- }- PolicyRun run =- new PolicyRun(runId, policyId, definition, sourceId, fileIdentity, triggeringUser);- registry.register(run);+ PolicyRun run = registerRun(policyId, definition, sourceId, fileIdentity, triggeringUser);+ String runId = run.getRunId();CompletableFuture<PolicyRun> completion = new CompletableFuture<>();PolicyProgressListener tracking = trackingListener(runId, run, listener);// Re-establish the acting principal as the audit principal on the worker thread. Each tool@@ -291,6 +300,26 @@ public class PolicyEngine {return new PolicyRunHandle(runId, completion);}+ private PolicyRun registerRun(+ String policyId,+ PipelineDefinition definition,+ String sourceId,+ String fileIdentity,+ String triggeringUser) {+ // Scope the run id to the current user (this request thread) so the file-download+ // ownership check passes. No-op when security is off.+ String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());+ taskManager.createTask(runId);+ // Tag the shared job entry with the policy id so peers can list it as a policy run.+ if (policyId != null) {+ taskManager.putMetadata(runId, "policyId", policyId);+ }+ PolicyRun run =+ new PolicyRun(runId, policyId, definition, sourceId, fileIdentity, triggeringUser);+ registry.register(run);+ return run;+ }+public PolicyRun getRun(String runId) {return registry.get(runId);}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.javaindex 3e9d804683..3b5f737f6c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java@@ -1,12 +1,10 @@package stirling.software.proprietary.policy.output;-import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;import stirling.software.proprietary.policy.model.OutputSpec;import stirling.software.proprietary.policy.model.Policy;@@ -14,15 +12,9 @@ import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.source.SourceStore;/**- * Resolves a policy's effective output destinations at run time: each {@code outputId} references a- * {@link Source} used as a destination, looked up live (so editing a location updates every policy- * that writes to it), exactly as input {@code sourceIds} are resolved. A run is delivered to every- * resolved destination. A policy with no references keeps its inline output (results returned to- * the caller) - the case for editor and one-off policies. A reference that no longer resolves- * (location deleted out from under a live policy - normally blocked by the source delete guard) is- * skipped; if none resolve, delivery falls back to inline so the run still completes.+ * Resolves saved destinations at dispatch; unavailable references fail instead of returning files+ * inline.*/-@Slf4j@Service@RequiredArgsConstructorpublic class PolicyOutputResolver {@@ -34,20 +26,18 @@ public class PolicyOutputResolver {if (outputIds.isEmpty()) {return List.of(policy.output());}- List<OutputSpec> resolved = new ArrayList<>();- for (String outputId : outputIds) {- sourceStore- .get(outputId)- .map(Source::toOutputSpec)- .ifPresentOrElse(- resolved::add,- () ->- log.warn(- "Policy {} references missing output source {}; skipping"- + " that destination",- policy.id(),- outputId));- }- return resolved.isEmpty() ? List.of(policy.output()) : resolved;+ return outputIds.stream()+ .map(+ id ->+ sourceStore+ .get(id)+ .filter(Source::enabled)+ .filter(source -> !"editor".equals(source.type()))+ .orElseThrow(+ () ->+ new IllegalArgumentException(+ "The output destination is missing, disabled, or unavailable"))+ .toOutputSpec())+ .toList();}}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.javaindex efc51c9487..2100d4c150 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@@ -14,6 +14,7 @@ import static org.mockito.Mockito.atLeastOnce;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;@@ -21,6 +22,7 @@ import static org.mockito.Mockito.when;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;@@ -33,9 +35,12 @@ 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.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.slf4j.MDC;+import org.springframework.core.env.StandardEnvironment;import org.springframework.core.io.ByteArrayResource;import org.springframework.core.io.Resource;import org.springframework.http.HttpHeaders;@@ -43,6 +48,7 @@ import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.client.HttpClientErrorException;+import stirling.software.common.configuration.RuntimePathConfig;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.model.job.ResultFile;import stirling.software.common.service.FileStorage;@@ -53,13 +59,19 @@ import stirling.software.common.service.JobQueue;import stirling.software.common.service.ResourceMonitor;import stirling.software.common.service.TaskManager;import stirling.software.common.service.ToolMetadataService;+import stirling.software.common.util.FileReadinessChecker;import stirling.software.common.util.TempFileManager;import stirling.software.common.util.TempFileRegistry;import stirling.software.proprietary.failure.PolicyFailureRecorder;import stirling.software.proprietary.policy.asset.InProcessPolicyAssetStore;import stirling.software.proprietary.policy.asset.PolicyAssetResolver;+import stirling.software.proprietary.policy.config.FolderAccessGuard;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.input.FolderInputSource;+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;import stirling.software.proprietary.policy.model.OutputSpec;import stirling.software.proprietary.policy.model.PipelineDefinition;+import stirling.software.proprietary.policy.model.PipelineInput;import stirling.software.proprietary.policy.model.PipelineStep;import stirling.software.proprietary.policy.model.Policy;import stirling.software.proprietary.policy.model.PolicyInputs;@@ -70,7 +82,9 @@ import stirling.software.proprietary.policy.output.OutputDelivery;import stirling.software.proprietary.policy.output.PolicyOutputResolver;import stirling.software.proprietary.policy.output.PolicyOutputSink;import stirling.software.proprietary.policy.progress.PolicyProgressListener;+import stirling.software.proprietary.policy.source.InProcessSourceDocCounter;import stirling.software.proprietary.policy.source.InProcessSourceStore;+import stirling.software.proprietary.policy.source.Source;import tools.jackson.databind.json.JsonMapper;@@ -97,6 +111,7 @@ class PolicyEngineTest {@TempDir Path tempDir;+ private final InProcessSourceStore sourceStore = new InProcessSourceStore();private final RecordingSink recordingSink = new RecordingSink();private PolicyRunRegistry registry;private PolicyEngine engine;@@ -115,7 +130,7 @@ class PolicyEngineTest {JsonMapper.builder().build());registry = new PolicyRunRegistry(new ApplicationProperties());InlineOutputSink sink = new InlineOutputSink(fileStorage);- PolicyOutputResolver outputResolver = new PolicyOutputResolver(new InProcessSourceStore());+ PolicyOutputResolver outputResolver = new PolicyOutputResolver(sourceStore);engine =new PolicyEngine(executor,@@ -139,6 +154,108 @@ class PolicyEngineTest {lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);}+ @ParameterizedTest+ @CsvSource({"track,false", "track,true", "consume,false", "consume,true"})+ void unavailableOutputFailsEveryClaimWithoutConsumingFiles(String mode, boolean disabled)+ throws Exception {+ Path input = Files.createDirectory(tempDir.resolve("input"));+ Files.writeString(input.resolve("first.pdf"), "first original");+ Files.writeString(input.resolve("second.pdf"), "second original");+ Source source =+ sourceStore.save(+ new Source(+ null,+ "Input",+ "folder",+ Map.of("directory", input.toString(), "mode", mode),+ true,+ "owner",+ null));+ String outputId =+ disabled+ ? sourceStore+ .save(+ new Source(+ null,+ "Output",+ "folder",+ Map.of(+ "directory",+ tempDir.resolve("out").toString()),+ false,+ "owner",+ null))+ .id()+ : "missing";+ Policy policy =+ new Policy(+ "p1",+ "Process",+ "owner",+ true,+ List.of(new PipelineInput(source.id(), null)),+ List.of(new PipelineStep(ROTATE, Map.of())),+ OutputSpec.inline())+ .withOutputIds(List.of(outputId));+ ApplicationProperties properties = new ApplicationProperties();+ properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));+ FileReadinessChecker readiness = mock(FileReadinessChecker.class);+ when(readiness.isReady(any())).thenReturn(true);+ FolderInputSource folder =+ new FolderInputSource(+ readiness,+ new FolderAccessGuard(+ properties,+ new RuntimePathConfig(properties),+ new StandardEnvironment(),+ sourceStore));+ InProcessProcessedLedger ledger = new InProcessProcessedLedger();+ PolicyRunner runner =+ new PolicyRunner(+ engine,+ List.of(folder),+ sourceStore,+ new InProcessSourceDocCounter(),+ ledger,+ properties,+ mock(PolicyAccessGuard.class));++ SweepOutcome outcome = runner.run(policy);++ assertEquals(2, outcome.runIds().size());+ for (String id : outcome.runIds()) {+ assertEquals(PolicyRunStatus.FAILED, engine.getRun(id).getStatus());+ assertEquals(source.id(), engine.getRun(id).getSourceId());+ verify(taskManager).setError(eq(id), anyString());+ verify(failureRecorder)+ .recordRunFailure(+ eq(id),+ any(),+ eq(source.id()),+ anyString(),+ isNull(),+ anyString(),+ any(Throwable.class));+ }+ assertFalse(ledger.anyInFlight(policy.id()));+ assertTrue(runner.quiesced(policy.id()));+ assertEquals("first original", Files.readString(input.resolve("first.pdf")));+ assertEquals("second original", Files.readString(input.resolve("second.pdf")));+ assertTrue(runner.run(policy).runIds().isEmpty());+ verifyNoInteractions(internalApiClient, fileStorage);+ }++ @Test+ void suppliedInputsStillRejectUnavailableDestinationsBeforeCreatingARun() {+ Policy policy = policyOwnedBy("owner").withOutputIds(List.of("missing"));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ engine.runPolicy(+ policy, PolicyInputs.of(List.of()), PolicyProgressListener.NOOP));+ verifyNoInteractions(taskManager, failureRecorder, internalApiClient);+ }+@Testvoid submitRunsPipelineToCompletionAndRegistersOutputs() throws Exception {when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.javaindex acaa68dae1..dfff624ed6 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java@@ -1,6 +1,7 @@package stirling.software.proprietary.policy.output;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;import java.util.List;import java.util.Map;@@ -17,7 +18,7 @@ import stirling.software.proprietary.policy.source.SourceStore;/*** Tests for {@link PolicyOutputResolver}: a policy's {@code outputIds} resolve live to the stored* sources used as destinations (one spec each), an unreferenced policy keeps its inline output, and- * a dangling reference falls back to inline delivery rather than failing the run.+ * an unavailable reference fails the run rather than falling back to inline delivery.*/class PolicyOutputResolverTest {@@ -46,12 +47,31 @@ class PolicyOutputResolverTest {}@Test- void whenNoReferencesResolveItFallsBackToInline() {- List<OutputSpec> specs =- resolver.resolve(policy().withOutputIds(List.of("does-not-exist")));+ void unavailableDestinationsNeverFallBackToInline() {+ assertThrows(+ IllegalArgumentException.class,+ () -> resolver.resolve(policy().withOutputIds(List.of("missing"))));+ Source disabled =+ sourceStore.save(+ new Source(+ null,+ "Disabled",+ "folder",+ Map.of("directory", "/out"),+ false,+ "owner",+ null));+ assertThrows(+ IllegalArgumentException.class,+ () -> resolver.resolve(policy().withOutputIds(List.of(disabled.id()))));+ }- assertEquals(1, specs.size());- assertEquals("inline", specs.get(0).type());+ @Test+ void oneMissingDestinationRejectsTheWholeDelivery() {+ Source archive = sourceStore.save(folder("Archive", "/out"));+ assertThrows(+ IllegalArgumentException.class,+ () -> resolver.resolve(policy().withOutputIds(List.of(archive.id(), "missing"))));}private static Source folder(String name, String directory) {