#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
Process new arrivals in server processing folders (#8038)
Reece Browne9c70b33f0b61
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.javaindex 2c3e7d006a..10cfeea3f4 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@@ -229,6 +229,12 @@ public class ApplicationProperties {/** How often (seconds) the schedule trigger checks for policies whose schedule is due. */private long scheduleSweepSeconds = 60;+ /**+ * Seconds between safety-net sweeps of server processing folders; minimum one second.+ * Placement sweeps the folder itself, so this only catches what this instance never saw.+ */+ private long storageFolderSweepSeconds = 60;+/*** How often (seconds) the folder-watch trigger reconciles its watch registrations and* re-runs every folder-watch policy as a safety net for filesystem events that were misseddiff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 05d968bf5b..ded6be7bad 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -424,6 +424,7 @@ policies:# disabled in SaaS mode.allowedFolderRoots: [] # e.g. ["/data/inbox", "/data/outbox"]scheduleSweepSeconds: 60 # How often (seconds) scheduled policies are checked for being due+ storageFolderSweepSeconds: 60 # Seconds between safety-net sweeps of server processing folders (arrivals sweep immediately)watchReconcileSeconds: 300 # How often (seconds) folder-watch re-syncs watches and re-runs as a safety net for missed eventswatchQuietPeriodMs: 500 # How long (ms) folder-watch coalesces a burst of file events into a single runstreamTimeoutMs: 1800000 # SSE timeout (ms) for live run-progress streamsdiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.javaindex d74d3b40c3..e1e7de4a76 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java@@ -42,6 +42,7 @@ import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.PolicyValidator;import stirling.software.proprietary.policy.engine.SweepKind;import stirling.software.proprietary.policy.engine.SweepOutcome;+import stirling.software.proprietary.policy.input.StorageFolderInputSource;import stirling.software.proprietary.policy.ledger.ClaimState;import stirling.software.proprietary.policy.ledger.FolderIdentities;import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;@@ -88,7 +89,7 @@ public class ProcessingFolderController {public static final String SURFACE = Policy.SURFACE_PROCESSING_FOLDER;/** The paired source's type; the policies/pipelines surfaces hide sources of this type too. */- public static final String SOURCE_TYPE = "storage-folder";+ public static final String SOURCE_TYPE = StorageFolderInputSource.TYPE;static final String DISK_SOURCE_TYPE = FolderAccessGuard.FOLDER_TYPE;@@ -271,14 +272,14 @@ public class ProcessingFolderController {request.enabled() == null || request.enabled(),false,"",- // Disk directories watch, so arrivals process on their- // own; storage-backed folders stay manual for now.List.of(new PipelineInput(source.id(),onDisk? new TriggerConfig(WATCH_TRIGGER, Map.of())- : null)),+ : new TriggerConfig(+ TriggerConfig.STORAGE_FOLDER_WATCH,+ Map.of()))),request.steps() == null ? List.of() : request.steps(),outputSpecFor(request, folder),outputIds,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.javaindex 9bc8bc1e2c..7054285496 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@@ -4,9 +4,11 @@ import java.io.IOException;import java.time.Duration;import java.util.ArrayList;import java.util.List;+import java.util.concurrent.CompletableFuture;import java.util.concurrent.Semaphore;import java.util.function.Consumer;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;@@ -50,6 +52,7 @@ public class PolicyRunner {private final ApplicationProperties applicationProperties;private final PolicyAccessGuard policyAccessGuard;private final DatabaseLicenseGuard databaseLicenseGuard;+ private final ApplicationEventPublisher eventPublisher;/*** One admission gate per sweep: every run is visible immediately, but only this many execute at@@ -124,12 +127,13 @@ public class PolicyRunner {// folder outputs are pruned instead of accumulating until the policy is deleted.runIds.add(startRun(- policy,- null,- null,- PolicyInputs.of(List.of()),- unused -> {},- admission));+ policy,+ null,+ null,+ PolicyInputs.of(List.of()),+ unused -> {},+ admission)+ .runId());}for (PipelineInput input : inputs) {String sourceId = input.sourceId();@@ -268,23 +272,62 @@ public class PolicyRunner {return List.of();}List<String> runIds = new ArrayList<>();+ List<CompletableFuture<PolicyRun>> completions = new ArrayList<>();long docsFed = 0;for (ResolvedInput unit : work) {- runIds.add(+ PolicyRunHandle handle =startRun(policy,storedSource,unit.fileIdentity(),unit.inputs(),unit.onComplete(),- admission));+ admission);+ runIds.add(handle.runId());+ completions.add(+ handle.completion()+ .handle(+ (run, error) -> {+ if (error != null) {+ log.warn(+ "Could not finish run {} in source batch {} for policy {}",+ handle.runId(),+ storedSource.id(),+ policy.id(),+ error);+ return null;+ }+ return run;+ }));docsFed += unit.inputs().primary().size();}+ if (!completions.isEmpty()) {+ CompletableFuture.allOf(completions.toArray(CompletableFuture[]::new))+ .thenRun(+ () -> {+ if (completions.stream()+ .map(CompletableFuture::join)+ .anyMatch(PolicyRunner::madeProgress)) {+ eventPublisher.publishEvent(+ new SourceBatchSettledEvent(+ policy.id(), storedSource.id()));+ }+ })+ .exceptionally(+ error -> {+ log.warn(+ "Could not finish source batch {} for policy {}",+ storedSource.id(),+ policy.id(),+ error);+ return null;+ });+ }docCounter.record(storedSource.id(), docsFed);return runIds;}- private String startRun(+ private PolicyRunHandle startRun(Policy policy,Source source,String fileIdentity,@@ -301,29 +344,36 @@ public class PolicyRunner {source,fileIdentity,admission);- handle.completion()- .whenComplete(- (run, throwable) -> {- boolean cancelled =- run != null && run.getStatus() == PolicyRunStatus.CANCELLED;- boolean neverAdmitted =- run != null- && PolicyEngine.QUEUE_FULL_CODE.equals(- run.getErrorCode());- if (cancelled || neverAdmitted) {- // Neither is a verdict on the file: cancellation is the- // user's intent, and queue-full means nothing was attempted.- // Settle, then drop the row, so the file reads as queued and- // the next sweep takes it again.- onComplete.accept(false);- if (fileIdentity != null) {- processedLedger.forget(policy.id(), fileIdentity);- }- return;- }- onComplete.accept(succeeded(run, throwable));- });- return handle.runId();+ CompletableFuture<PolicyRun> settled =+ handle.completion()+ .whenComplete(+ (run, throwable) -> {+ boolean cancelled =+ run != null+ && run.getStatus() == PolicyRunStatus.CANCELLED;+ boolean neverAdmitted =+ run != null+ && PolicyEngine.QUEUE_FULL_CODE.equals(+ run.getErrorCode());+ if (cancelled || neverAdmitted) {+ // Neither cancellation nor queue rejection is a verdict+ // on the file; a later sweep may claim it again.+ onComplete.accept(false);+ if (fileIdentity != null) {+ processedLedger.forget(policy.id(), fileIdentity);+ }+ return;+ }+ onComplete.accept(succeeded(run, throwable));+ });+ return new PolicyRunHandle(handle.runId(), settled);+ }++ private static boolean madeProgress(PolicyRun run) {+ return run != null+ && (run.getStatus() == PolicyRunStatus.COMPLETED+ || run.getStatus() == PolicyRunStatus.FAILED)+ && !PolicyEngine.QUEUE_FULL_CODE.equals(run.getErrorCode());}private static boolean succeeded(PolicyRun run, Throwable throwable) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.javaindex 2ad5cdb4b7..66adc2fadf 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicySweep.java@@ -21,6 +21,8 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;*/final class PolicySweep implements ResolveContext {+ private static final int MAX_BATCH_CLAIMS = 100;+private final String policyId;private final SweepKind kind;private final ProcessedLedger ledger;@@ -36,6 +38,7 @@ final class PolicySweep implements ResolveContext {private final Set<String> prefetchedIdentities = new HashSet<>();private boolean cleanupVetoed;private int retried;+ private int claimedCount;PolicySweep(String policyId, SweepKind kind, ProcessedLedger ledger, String target) {this.policyId = policyId;@@ -52,6 +55,9 @@ final class PolicySweep implements ResolveContext {if (target != null && !target.equals(identity)) {return false;}+ if (kind == SweepKind.BATCH && claimedCount >= MAX_BATCH_CLAIMS) {+ return false;+ }ClaimState observed =prefetchedIdentities.contains(identity)? prefetched.get(identity)@@ -70,6 +76,7 @@ final class PolicySweep implements ResolveContext {}boolean claimed = ledger.claim(policyId, identity, gate, contentHash, observed);if (claimed) {+ claimedCount++;// A nested source surfacing the same file later in this sweep sees it in flight// without another lookup.prefetchedIdentities.add(identity);@@ -112,9 +119,9 @@ final class PolicySweep implements ResolveContext {}/**- * Summarise the sweep from state already in hand (no extra ledger reads): the prefetched rows- * were loaded before claiming, and successful claims flipped their entries to PROCESSING, so- * what remains DONE or ERROR is exactly what this sweep skipped.+ * Summarise from prefetched ledger state updated with successful claims, without extra reads.+ * Files deferred by the BATCH cap can have no ledger state: they count toward filesListed but+ * none of the status totals, so those totals need not account for every listed file.*/synchronized SweepOutcome outcome(List<String> runIds) {int alreadyProcessed = 0;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SourceBatchSettledEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SourceBatchSettledEvent.javanew file mode 100644index 0000000000..35191a7694--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SourceBatchSettledEvent.java@@ -0,0 +1,10 @@+package stirling.software.proprietary.policy.engine;++/**+ * Every run in a nonempty source batch has finished its settlement attempt, and at least one+ * completed or failed run settled successfully. Consumers must still check policy quiescence: a+ * failed settlement can leave a claim in flight. Cancellation, queue rejection, or exceptional+ * completion alone does not request more work, preventing immediate resubmission of a batch that+ * made no progress.+ */+public record SourceBatchSettledEvent(String policyId, String sourceId) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.javaindex 423c25e54c..e37f41884c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/SweepKind.java@@ -9,5 +9,7 @@ package stirling.software.proprietary.policy.engine;public enum SweepKind {FULL,LIGHT,- USER+ USER,+ /** Full listing with at most 100 new runs, leaving the rest for the next automatic sweep. */+ BATCH}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.javaindex 86918aa5b6..7871ef5f38 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java@@ -2,6 +2,7 @@ package stirling.software.proprietary.policy.input;import java.io.IOException;import java.io.InputStream;+import java.io.UncheckedIOException;import java.util.ArrayList;import java.util.List;import java.util.UUID;@@ -39,7 +40,7 @@ import stirling.software.proprietary.storage.repository.StoredFileRepository;@RequiredArgsConstructorpublic class StorageFolderInputSource implements InputSource {- private static final String TYPE = "storage-folder";+ public static final String TYPE = "storage-folder";private final StoredFileRepository storedFileRepository;private final FolderRepository folderRepository;@@ -104,8 +105,22 @@ public class StorageFolderInputSource implements InputSource {String gate = gate(file);// The hash tier turns metadata-only gate bumps (a folder move, a rename) into a gate// refresh instead of a reprocess; only genuinely new content runs again.- if (!ctx.claim(identity, gate, () -> ownedContentHash(file, folderId, owner))) {+ try {+ if (!ctx.claim(identity, gate, () -> ownedContentHash(file, folderId, owner))) {+ continue;+ }+ } catch (IllegalArgumentException | UncheckedIOException e) {+ log.warn("Could not claim stored input {}: {}", identity, e.getMessage());continue;+ } catch (RuntimeException e) {+ // A ledger or database failure can affect every remaining file. Return earlier+ // claims so the runner can dispatch them instead of leaving them in PROCESSING.+ log.warn(+ "Stopped claiming inputs for storage folder {}; {} files already claimed",+ folderId,+ work.size(),+ e);+ break;}Long fileId = file.getId();work.add(diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyBinding.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyBinding.javaindex 18e93ce1bc..b3fb1702f4 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyBinding.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyBinding.java@@ -13,19 +13,24 @@ public record PolicyBinding(Policy policy, PipelineInput input) {* The bindings across these policies whose input carries a trigger of the given type. Shared by* the {@code PolicyStore} implementations so every backend derives a trigger's bindings the* same way. Callers pass the policies a background trigger should consider (i.e. the enabled- * ones).+ * ones). Processing-folder inputs without an explicit trigger default to storage polling; the+ * trigger verifies that the referenced source is storage-backed.*/public static List<PolicyBinding> matching(List<Policy> policies, String triggerType) {return policies.stream().flatMap(policy ->policy.inputs().stream()- .filter(- input ->- input.trigger() != null- && triggerType.equals(- input.trigger().type()))+ .filter(input -> matches(policy, input, triggerType)).map(input -> new PolicyBinding(policy, input))).toList();}++ private static boolean matches(Policy policy, PipelineInput input, String triggerType) {+ if (input.trigger() != null) {+ return triggerType.equals(input.trigger().type());+ }+ return TriggerConfig.STORAGE_FOLDER_WATCH.equals(triggerType)+ && Policy.SURFACE_PROCESSING_FOLDER.equals(policy.surface());+ }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/TriggerConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/TriggerConfig.javaindex 477de122e7..bab03c22ce 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/TriggerConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/TriggerConfig.java@@ -4,11 +4,14 @@ import java.util.Map;/*** A {@link Policy}'s automatic trigger; {@code type} keys a trigger bean (e.g. "schedule"). Manual- * running is not a trigger kind: a manual-only policy carries a {@code null} {@code TriggerConfig}.+ * running is not a trigger kind: ordinary manual-only policies carry a {@code null} {@code+ * TriggerConfig}. Processing-folder inputs without a trigger default to storage-folder polling.* Answers only "when"; file sources are the policy's {@link InputSpec}s.*/public record TriggerConfig(String type, Map<String, Object> options) {+ public static final String STORAGE_FOLDER_WATCH = "storage-folder-watch";+public TriggerConfig {options = options == null ? Map.of() : options;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/StorageFolderTrigger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/StorageFolderTrigger.javanew file mode 100644index 0000000000..68e6e082c2--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/StorageFolderTrigger.java@@ -0,0 +1,240 @@+package stirling.software.proprietary.policy.trigger;++import java.util.List;+import java.util.Objects;+import java.util.Optional;+import java.util.Set;+import java.util.UUID;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.RejectedExecutionException;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;++import org.springframework.context.event.EventListener;+import org.springframework.stereotype.Service;+import org.springframework.transaction.event.TransactionPhase;+import org.springframework.transaction.event.TransactionalEventListener;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.SourceBatchSettledEvent;+import stirling.software.proprietary.policy.engine.SweepKind;+import stirling.software.proprietary.policy.input.StorageFolderInputSource;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.model.PolicyBinding;+import stirling.software.proprietary.policy.model.TriggerConfig;+import stirling.software.proprietary.policy.source.Source;+import stirling.software.proprietary.policy.source.SourceStore;+import stirling.software.proprietary.policy.store.PolicyStore;+import stirling.software.proprietary.storage.event.StorageFolderArrivalEvent;++/**+ * Runs storage-folder bindings when files arrive. A placement event sweeps just the folder it names+ * so an upload is processed promptly; the periodic poll re-sweeps everything as the safety net for+ * arrivals this instance never saw: another node's placement, or one that landed while it was down.+ * Settled batches prompt another sweep, so a folder drains without waiting for the poll. Each+ * folder drains its current batch before another is submitted. Coordination between backend+ * instances depends on the processed-file ledger and its recovery behaviour.+ */+@Service+@RequiredArgsConstructor+@Slf4j+public class StorageFolderTrigger implements PolicyTrigger {+ private final PolicyStore policyStore;+ private final SourceStore sourceStore;+ private final PolicyRunner policyRunner;+ private final ApplicationProperties applicationProperties;++ /** Folders named by arrivals not yet swept, coalesced so a bulk move costs one sweep. */+ private final Set<UUID> pendingArrivals = ConcurrentHashMap.newKeySet();++ private final AtomicBoolean flushScheduled = new AtomicBoolean();+ private ScheduledExecutorService scheduler;++ @Override+ public String type() {+ return TriggerConfig.STORAGE_FOLDER_WATCH;+ }++ @Override+ public boolean requiresSource() {+ return true;+ }++ @Override+ public Set<String> supportedSourceTypes() {+ return Set.of(StorageFolderInputSource.TYPE);+ }++ @Override+ public synchronized void start() {+ if (scheduler != null) {+ return;+ }+ long seconds =+ Math.max(1, applicationProperties.getPolicies().getStorageFolderSweepSeconds());+ scheduler =+ Executors.newSingleThreadScheduledExecutor(+ Thread.ofVirtual().name("storage-folder-poll-", 0).factory());+ scheduler.scheduleWithFixedDelay(this::safeSweep, 0, seconds, TimeUnit.SECONDS);+ }++ @Override+ public synchronized void stop() {+ if (scheduler != null) {+ scheduler.shutdownNow();+ scheduler = null;+ }+ pendingArrivals.clear();+ flushScheduled.set(false);+ }++ /**+ * After commit, so the sweep that follows can see the placement it was told about. Handing the+ * work to the scheduler keeps the request thread off the folder listing, and puts arrival+ * sweeps on the same single thread as the poll, so two sweeps of one folder cannot overlap.+ *+ * <p>{@code fallbackExecution} covers a publisher running outside a transaction, where this+ * would otherwise drop the event without a trace. A sweep is idempotent, so a redundant one+ * costs a listing; a swallowed arrival costs the whole point of the trigger.+ */+ @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)+ public void onArrival(StorageFolderArrivalEvent event) {+ requestSweep(event.folderId());+ }++ /** Recheck the live binding before continuing a batch: it may have been paused or removed. */+ @EventListener+ public void onBatchSettled(SourceBatchSettledEvent event) {+ Policy policy = policyStore.get(event.policyId()).orElse(null);+ if (policy == null+ || !policy.enabled()+ || PolicyBinding.matching(List.of(policy), type()).stream()+ .noneMatch(+ binding -> event.sourceId().equals(binding.input().sourceId()))) {+ return;+ }+ Source source = liveStorageSource(event.sourceId()).orElse(null);+ if (source == null) {+ return;+ }+ try {+ requestSweep(UUID.fromString(folderIdText(source)));+ } catch (IllegalArgumentException e) {+ log.warn("Could not continue processing folder {}: {}", policy.id(), e.getMessage());+ }+ }++ private void requestSweep(UUID folderId) {+ if (folderId == null) {+ return;+ }+ pendingArrivals.add(folderId);+ scheduleFlush();+ }++ /**+ * One flush is in flight at a time: arrivals during the quiet period join the pending set+ * instead of queueing their own sweep, so moving 200 files sweeps the folder once.+ */+ private synchronized void scheduleFlush() {+ if (scheduler == null || !flushScheduled.compareAndSet(false, true)) {+ return;+ }+ long quietMs = Math.max(0, applicationProperties.getPolicies().getWatchQuietPeriodMs());+ try {+ scheduler.schedule(this::flushArrivals, quietMs, TimeUnit.MILLISECONDS);+ } catch (RejectedExecutionException shuttingDown) {+ flushScheduled.set(false);+ }+ }++ private void flushArrivals() {+ // Cleared before draining: an arrival landing mid-drain schedules the next flush rather+ // than being dropped, at worst costing one extra sweep of a folder already in hand.+ flushScheduled.set(false);+ for (UUID folderId : drainPending()) {+ try {+ sweep(folderId);+ } catch (RuntimeException e) {+ log.warn("Could not sweep folder {} after arrival: {}", folderId, e.getMessage());+ }+ }+ }++ private Set<UUID> drainPending() {+ Set<UUID> drained = Set.copyOf(pendingArrivals);+ pendingArrivals.removeAll(drained);+ return drained;+ }++ private void safeSweep() {+ try {+ sweep();+ } catch (RuntimeException e) {+ log.warn("Could not poll processing folders: {}", e.getMessage(), e);+ }+ }++ void sweep() {+ sweep(null);+ }++ /** Sweeps every storage folder, or only the one given when an arrival named it. */+ void sweep(UUID onlyFolderId) {+ if (!applicationProperties.getStorage().isEnabled()+ || !applicationProperties.getSecurity().isEnableLogin()) {+ return;+ }+ for (PolicyBinding binding : policyStore.findBindingsByTriggerType(type())) {+ if (Thread.currentThread().isInterrupted()) {+ return;+ }+ try {+ // Earlier folders can take time to enumerate; honour edits and pauses made+ // meanwhile.+ Policy current = policyStore.get(binding.policy().id()).orElse(null);+ if (current == null || !current.enabled() || !policyRunner.quiesced(current.id())) {+ continue;+ }+ for (PolicyBinding latest : PolicyBinding.matching(List.of(current), type())) {+ if (!Objects.equals(latest.input().sourceId(), binding.input().sourceId())) {+ continue;+ }+ boolean enabledStorage =+ liveStorageSource(latest.input().sourceId())+ .filter(source -> watches(source, onlyFolderId))+ .isPresent();+ if (enabledStorage) {+ policyRunner.runInput(current, latest.input(), SweepKind.BATCH);+ }+ }+ } catch (RuntimeException e) {+ log.warn(+ "Could not poll processing folder {}: {}",+ binding.policy().id(),+ e.getMessage());+ }+ }+ }++ private Optional<Source> liveStorageSource(String sourceId) {+ return sourceStore+ .get(sourceId)+ .filter(Source::enabled)+ .filter(source -> StorageFolderInputSource.TYPE.equals(source.type()));+ }++ private static String folderIdText(Source source) {+ return String.valueOf(source.options().get("folderId"));+ }++ private static boolean watches(Source source, UUID onlyFolderId) {+ return onlyFolderId == null || onlyFolderId.toString().equals(folderIdText(source));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/event/StorageFolderArrivalEvent.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/event/StorageFolderArrivalEvent.javanew file mode 100644index 0000000000..672b885531--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/event/StorageFolderArrivalEvent.java@@ -0,0 +1,14 @@+package stirling.software.proprietary.storage.event;++import java.util.UUID;++/**+ * Files were placed into a storage folder by a user action (a move from the file manager or the+ * editor). Published so a processing folder starts its run on the arrival rather than on the next+ * poll; the poll remains the safety net for events lost to a restart or another instance.+ *+ * <p>Deliberately raised only from the placement calls a user drives. Policy output re-enters the+ * folder through {@code StorageOutputSink}, which writes the row directly, so a run cannot announce+ * its own results back to the trigger that started it.+ */+public record StorageFolderArrivalEvent(UUID folderId) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FolderService.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FolderService.javaindex c0f07f8ceb..60254ab6a0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FolderService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FolderService.java@@ -10,6 +10,7 @@ import java.util.Map;import java.util.Set;import java.util.UUID;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.http.HttpStatus;import org.springframework.security.core.Authentication;@@ -23,6 +24,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.event.StorageFolderArrivalEvent;import stirling.software.proprietary.storage.model.Folder;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.model.api.CreateFolderRequest;@@ -66,6 +68,7 @@ public class FolderService {private final FolderRepository folderRepository;private final StoredFileRepository storedFileRepository;private final ApplicationProperties applicationProperties;+ private final ApplicationEventPublisher eventPublisher;/*** Gate every public method on storage being enabled, mirroring {@code@@ -260,6 +263,7 @@ public class FolderService {"File not found or not owned by current user"));file.setFolder(resolveOwnedFolder(folderId, user));storedFileRepository.save(file);+ eventPublisher.publishEvent(new StorageFolderArrivalEvent(folderId));}/**@@ -300,6 +304,9 @@ public class FolderService {}List<Long> moved = owned.stream().map(StoredFile::getId).toList();+ if (!moved.isEmpty()) {+ eventPublisher.publishEvent(new StorageFolderArrivalEvent(folderId));+ }List<Long> skipped = fileIds.stream().filter(id -> !ownedIds.contains(id)).toList();if (!skipped.isEmpty()) {log.warn(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.javaindex 0c38e4fa23..ed68df17ae 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@@ -59,6 +59,7 @@ import stirling.software.proprietary.policy.source.SourceAccessGuard;import stirling.software.proprietary.policy.store.InProcessPolicyStore;import stirling.software.proprietary.policy.trigger.PolicyTrigger;import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;+import stirling.software.proprietary.policy.trigger.StorageFolderTrigger;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.storage.model.Folder;@@ -164,7 +165,10 @@ class ProcessingFolderControllerTest {lenient().when(diskFolderSink.supports(any())).thenReturn(true);PolicyValidator validator =new PolicyValidator(- List.of(folderWatchTrigger),+ List.of(+ folderWatchTrigger,+ new StorageFolderTrigger(+ policyStore, sourceStore, policyRunner, properties)),List.of(new StorageFolderInputSource(storedFileRepository,@@ -477,10 +481,11 @@ class ProcessingFolderControllerTest {}@Test- void aStorageFolderStaysManualUntilTheArrivalTriggerExists() {+ void aStorageFolderAutomaticallyProcessesArrivals() {var view = controller.save(request(null, "new_version")).getBody();- assertThat(policyStore.get(view.id()).orElseThrow().inputs().get(0).trigger()).isNull();+ assertThat(policyStore.get(view.id()).orElseThrow().inputs().get(0).trigger().type())+ .isEqualTo("storage-folder-watch");}@Testdiff --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 aac2ae1193..3ac6371e7c 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@@ -290,7 +290,8 @@ class PolicyEngineTest {mock(PolicyAccessGuard.class),org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee- .DatabaseLicenseGuard.class));+ .DatabaseLicenseGuard.class),+ mock(org.springframework.context.ApplicationEventPublisher.class));SweepOutcome outcome = runner.run(policy);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.javaindex f9571d44fe..1a9a76b1be 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@@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;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.lenient;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;@@ -21,13 +22,17 @@ import java.util.Map;import java.util.Set;import java.util.concurrent.CompletableFuture;import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.core.io.ByteArrayResource;import stirling.software.common.model.ApplicationProperties;@@ -62,6 +67,7 @@ import stirling.software.proprietary.policy.source.SourceStore;class PolicyRunnerTest {@Mock private PolicyEngine policyEngine;+ @Mock private ApplicationEventPublisher eventPublisher;@Mockprivate stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard@@ -86,7 +92,8 @@ class PolicyRunnerTest {processedLedger,new ApplicationProperties(),reachableOwners(),- databaseLicenseGuard);+ databaseLicenseGuard,+ eventPublisher);}@Test@@ -126,7 +133,8 @@ class PolicyRunnerTest {reachableOwners(),org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee- .DatabaseLicenseGuard.class));+ .DatabaseLicenseGuard.class),+ eventPublisher);InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));// One file already processed at its current version, one parked by a failed run.@@ -192,6 +200,117 @@ class PolicyRunnerTest {assertTrue(outcome.get());}+ @Test+ void theBatchNotificationWaitsForEverySettlementHook() throws Exception {+ InputSpec spec = InputSpec.folder("/in");+ Policy policy = policy(List.of(spec));+ AtomicInteger settled = new AtomicInteger();+ AtomicInteger settledAtNotification = new AtomicInteger();+ ResolvedInput unit =+ new ResolvedInput(+ PolicyInputs.of(List.of()), null, success -> settled.incrementAndGet());+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit, unit));+ CompletableFuture<PolicyRun> first = new CompletableFuture<>();+ CompletableFuture<PolicyRun> second = new CompletableFuture<>();+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(new PolicyRunHandle("r1", first), new PolicyRunHandle("r2", second));+ doAnswer(+ invocation -> {+ settledAtNotification.set(settled.get());+ return null;+ })+ .when(eventPublisher)+ .publishEvent(any(SourceBatchSettledEvent.class));+ runner.run(policy);+ PolicyRun run = mock(PolicyRun.class);+ when(run.getStatus()).thenReturn(PolicyRunStatus.COMPLETED);++ first.complete(run);+ verifyNoInteractions(eventPublisher);+ second.complete(run);++ assertEquals(2, settledAtNotification.get());+ verify(eventPublisher)+ .publishEvent(+ new SourceBatchSettledEvent(+ policy.id(), policy.inputs().getFirst().sourceId()));+ }++ @ParameterizedTest+ @EnumSource(+ value = PolicyRunStatus.class,+ names = {"COMPLETED", "FAILED"})+ void exceptionalRunsDoNotSuppressBatchProgress(PolicyRunStatus status) throws Exception {+ InputSpec spec = InputSpec.folder("/in");+ Policy policy = policy(List.of(spec));+ AtomicInteger settled = new AtomicInteger();+ ResolvedInput unit =+ new ResolvedInput(+ PolicyInputs.of(List.of()), null, success -> settled.incrementAndGet());+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any())).thenReturn(List.of(unit, unit, unit));+ CompletableFuture<PolicyRun> first = new CompletableFuture<>();+ CompletableFuture<PolicyRun> second = new CompletableFuture<>();+ CompletableFuture<PolicyRun> third = new CompletableFuture<>();+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(+ new PolicyRunHandle("r1", first),+ new PolicyRunHandle("r2", second),+ new PolicyRunHandle("r3", third));+ runner.run(policy);+ PolicyRun run = mock(PolicyRun.class);+ when(run.getStatus()).thenReturn(status);++ first.completeExceptionally(new IllegalStateException("first run interrupted"));+ verifyNoInteractions(eventPublisher);+ second.complete(run);+ verifyNoInteractions(eventPublisher);+ third.completeExceptionally(new IllegalStateException("last run interrupted"));++ assertEquals(3, settled.get());+ verify(eventPublisher)+ .publishEvent(+ new SourceBatchSettledEvent(+ policy.id(), policy.inputs().getFirst().sourceId()));+ }++ @ParameterizedTest+ @EnumSource(+ value = PolicyRunStatus.class,+ names = {"COMPLETED", "FAILED"})+ void aThrowingSettlementHookDoesNotSuppressOtherBatchProgress(PolicyRunStatus status)+ throws Exception {+ InputSpec spec = InputSpec.folder("/in");+ Policy policy = policy(List.of(spec));+ ResolvedInput unsettled =+ new ResolvedInput(+ PolicyInputs.of(List.of()),+ null,+ success -> {+ throw new IllegalStateException("ledger unavailable");+ });+ when(folderSource.supports(spec)).thenReturn(true);+ when(folderSource.resolve(eq(spec), any()))+ .thenReturn(List.of(ResolvedInput.of(PolicyInputs.of(List.of())), unsettled));+ CompletableFuture<PolicyRun> first = new CompletableFuture<>();+ CompletableFuture<PolicyRun> second = new CompletableFuture<>();+ when(policyEngine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(new PolicyRunHandle("r1", first), new PolicyRunHandle("r2", second));+ runner.run(policy);+ PolicyRun run = mock(PolicyRun.class);+ when(run.getStatus()).thenReturn(status);++ first.complete(run);+ verifyNoInteractions(eventPublisher);+ second.complete(run);++ verify(eventPublisher)+ .publishEvent(+ new SourceBatchSettledEvent(+ policy.id(), policy.inputs().getFirst().sourceId()));+ }+@Testvoid reportsFailureToTheCompletionHookWhenTheRunDoesNotComplete() throws Exception {InputSpec spec = InputSpec.folder("/in");@@ -208,6 +327,7 @@ class PolicyRunnerTest {completion.completeExceptionally(new RuntimeException("boom"));assertFalse(outcome.get());+ verifyNoInteractions(eventPublisher);}@Test@@ -413,7 +533,8 @@ class PolicyRunnerTest {guardOver(loginOn, noUsers()),org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee- .DatabaseLicenseGuard.class));+ .DatabaseLicenseGuard.class),+ eventPublisher);for (String owner : new String[] {null, "", "deleted-user"}) {Source source =sourceStore.save(@@ -461,7 +582,8 @@ class PolicyRunnerTest {guardOver(loginOn, noUsers()),org.mockito.Mockito.mock(stirling.software.proprietary.security.configuration.ee- .DatabaseLicenseGuard.class));+ .DatabaseLicenseGuard.class),+ eventPublisher);SweepOutcome outcome = enforced.run(stranded.withSurface(Policy.SURFACE_PROCESSING_FOLDER));@@ -527,8 +649,12 @@ class PolicyRunnerTest {assertFalse(runner.awaitQuiesce("p1", java.time.Duration.ofMillis(50)));}- @Test- void aQueueFullRejectionReleasesTheClaimForTheNextSweep() throws Exception {+ @ParameterizedTest+ @EnumSource(+ value = PolicyRunStatus.class,+ names = {"FAILED", "CANCELLED"})+ void unstartedRunsReleaseTheirClaimsWithoutRequestingAnotherBatch(PolicyRunStatus status)+ throws Exception {InputSpec spec = InputSpec.folder("/in");Policy policy = policy(List.of(spec));java.util.concurrent.atomic.AtomicBoolean outcome =@@ -543,12 +669,14 @@ class PolicyRunnerTest {runner.run(policy);PolicyRun run = mock(PolicyRun.class);- when(run.getStatus()).thenReturn(PolicyRunStatus.FAILED);- when(run.getErrorCode()).thenReturn("POLICY_QUEUE_FULL");+ when(run.getStatus()).thenReturn(status);+ if (status == PolicyRunStatus.FAILED) {+ when(run.getErrorCode()).thenReturn(PolicyEngine.QUEUE_FULL_CODE);+ }completion.complete(run);- // Nothing was attempted on the file: the claim is dropped, not parked failed.assertFalse(outcome.get());verify(processedLedger).forget("p1", "/in/doc.pdf");+ verifyNoInteractions(eventPublisher);}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.javaindex dd14646b75..fd7f5e9d52 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java@@ -157,7 +157,8 @@ class StorageFolderAuthorizationTest {new InProcessProcessedLedger(),properties,policies,- mock(DatabaseLicenseGuard.class));+ mock(DatabaseLicenseGuard.class),+ mock(org.springframework.context.ApplicationEventPublisher.class));}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.javanew file mode 100644index 0000000000..191a3558f3--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java@@ -0,0 +1,657 @@+package stirling.software.proprietary.policy.trigger;++import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.ArgumentMatchers.*;+import static org.mockito.Mockito.*;++import java.io.IOException;+import java.time.LocalDateTime;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CopyOnWriteArrayList;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.TimeUnit;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.context.ApplicationEventPublisher;+import org.springframework.core.io.ByteArrayResource;+import org.springframework.dao.DataAccessResourceFailureException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.engine.PolicyEngine;+import stirling.software.proprietary.policy.engine.PolicyRunHandle;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.engine.SourceBatchSettledEvent;+import stirling.software.proprietary.policy.engine.SweepKind;+import stirling.software.proprietary.policy.input.StorageFolderInputSource;+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;+import stirling.software.proprietary.policy.ledger.StorageFileIdentities;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PipelineInput;+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.TriggerConfig;+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.store.InProcessPolicyStore;+import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.proprietary.storage.event.StorageFolderArrivalEvent;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;++/**+ * Polling through the real source, runner and ledger; only tool execution and storage I/O are+ * doubled.+ */+class StorageFolderTriggerTest {+ private final InProcessPolicyStore policies = new InProcessPolicyStore();+ private final InProcessSourceStore sources = new InProcessSourceStore();+ private final InProcessProcessedLedger ledger = spy(new InProcessProcessedLedger());+ private final PolicyEngine engine = mock(PolicyEngine.class);+ private final ApplicationEventPublisher events = mock(ApplicationEventPublisher.class);+ private final StoredFileRepository files = mock(StoredFileRepository.class);+ private final FolderRepository folders = mock(FolderRepository.class);+ private final StorageProvider blobs = mock(StorageProvider.class);+ private final UserService users = mock(UserService.class);+ private final ApplicationProperties properties = new ApplicationProperties();+ private final User owner = new User();+ private final Folder folder = new Folder();+ private final Map<Long, StoredFile> stored = new LinkedHashMap<>();+ private final List<String> processed = new CopyOnWriteArrayList<>();+ private final List<Runnable> completions = new CopyOnWriteArrayList<>();+ private volatile boolean holdCompletions;+ private PolicyRunner runner;+ private StorageFolderTrigger trigger;++ @BeforeEach+ void setUp() throws IOException {+ properties.getStorage().setEnabled(true);+ properties.getSecurity().setEnableLogin(true);+ owner.setId(7L);+ owner.setUsername("alice");+ folder.setId(UUID.randomUUID());+ folder.setOwner(owner);+ when(users.findByUsername("alice")).thenReturn(Optional.of(owner));+ when(folders.findByIdAndOwner(folder.getId(), owner)).thenReturn(Optional.of(folder));+ when(files.findAllByFolderIdAndOwner(folder.getId(), owner))+ .thenAnswer(inv -> List.copyOf(stored.values()));+ when(files.findByIdAndOwner(anyLong(), eq(owner)))+ .thenAnswer(inv -> Optional.ofNullable(stored.get(inv.getArgument(0))));+ when(blobs.load(anyString()))+ .thenAnswer(inv -> new ByteArrayResource(inv.<String>getArgument(0).getBytes()));+ StorageFolderInputSource input =+ new StorageFolderInputSource(files, folders, blobs, properties, users);+ runner =+ new PolicyRunner(+ engine,+ List.of(input),+ sources,+ new InProcessSourceDocCounter(),+ ledger,+ properties,+ mock(PolicyAccessGuard.class),+ mock(DatabaseLicenseGuard.class),+ events);+ trigger = new StorageFolderTrigger(policies, sources, runner, properties);+ doAnswer(+ invocation -> {+ trigger.onBatchSettled(invocation.getArgument(0));+ return null;+ })+ .when(events)+ .publishEvent(any(SourceBatchSettledEvent.class));+ when(engine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenAnswer(+ inv -> {+ Policy policy = inv.getArgument(0);+ PolicyInputs inputs = inv.getArgument(1);+ String identity = inv.getArgument(4);+ inputs.primary().getFirst().getInputStream().close();+ processed.add(identity);+ PolicyRun run =+ new PolicyRun(+ UUID.randomUUID().toString(),+ policy.id(),+ policy.toDefinition(),+ inv.<Source>getArgument(3).id(),+ identity,+ null);+ CompletableFuture<PolicyRun> completion = new CompletableFuture<>();+ Runnable finish =+ () -> {+ run.complete(List.of());+ completion.complete(run);+ };+ if (holdCompletions) completions.add(finish);+ else finish.run();+ return new PolicyRunHandle(run.getRunId(), completion);+ });+ }++ private Policy processingFolder(String id, boolean legacy) {+ Source source =+ sources.save(+ new Source(+ id + "-source",+ "Input",+ "storage-folder",+ Map.of("folderId", folder.getId().toString()),+ true,+ "alice",+ 1L));+ return policies.save(+ new Policy(+ id,+ id,+ "alice",+ true,+ List.of(+ new PipelineInput(+ source.id(),+ legacy+ ? null+ : new TriggerConfig(+ TriggerConfig.STORAGE_FOLDER_WATCH,+ Map.of()))),+ List.of(),+ OutputSpec.inline(),+ 1L)+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER));+ }++ private StoredFile upload(long id) {+ StoredFile file = new StoredFile();+ file.setId(id);+ file.setOwner(owner);+ file.setFolder(folder);+ file.setOriginalFilename(id + ".pdf");+ file.setStorageKey("blob-" + id);+ file.setSizeBytes(10L);+ file.setUpdatedAt(LocalDateTime.of(2026, 9, 15, 12, 0));+ stored.put(id, file);+ return file;+ }++ @Test+ void filesUploadedAfterTheInitialRunProcessWithoutAManualTrigger() {+ processingFolder("p1", false);+ upload(1);+ trigger.sweep();+ upload(2);+ trigger.sweep();+ trigger.sweep();+ assertEquals(List.of("storage:1", "storage:2"), processed);+ }++ @Test+ void existingFoldersWithoutAnExplicitTriggerAlsoPickUpArrivals() {+ processingFolder("p1", true);+ trigger.sweep();+ upload(1);+ trigger.sweep();+ assertEquals(List.of("storage:1"), processed);+ }++ @Test+ void pausePreventsNewWorkAndResumePicksUpTheBacklog() {+ Policy policy = processingFolder("p1", false);+ policies.save(policy.withEnabled(false));+ upload(1);+ trigger.sweep();+ assertTrue(processed.isEmpty());+ policies.save(policy.withEnabled(true));+ trigger.sweep();+ assertEquals(List.of("storage:1"), processed);+ }++ @Test+ void deletedPoliciesAndDisabledSourcesDoNotProcessFiles() {+ Policy policy = processingFolder("p1", true);+ Source source = sources.get(policy.inputs().getFirst().sourceId()).orElseThrow();+ sources.save(+ new Source(+ source.id(),+ source.name(),+ source.type(),+ source.options(),+ false,+ source.owner(),+ source.teamId()));+ upload(1);+ trigger.sweep();+ assertTrue(processed.isEmpty());+ sources.save(source);+ policies.delete(policy.id());+ trigger.sweep();+ assertTrue(processed.isEmpty());+ }++ @Test+ void restartingTheTriggerDiscoversBacklogWithoutReprocessingSettledFiles() {+ processingFolder("p1", true);+ upload(1);+ trigger.sweep();+ upload(2);+ new StorageFolderTrigger(policies, sources, runner, properties).sweep();+ assertEquals(List.of("storage:1", "storage:2"), processed);+ }++ @Test+ void aBacklogDrainsInBoundedBatchesAndWaitsForTheCurrentBatch() {+ processingFolder("p1", false);+ for (long id = 1; id <= 205; id++) upload(id);+ holdCompletions = true;+ trigger.sweep();+ assertEquals(100, processed.size());+ trigger.sweep();+ assertEquals(100, processed.size());+ completions.forEach(Runnable::run);+ completions.clear();+ trigger.sweep();+ assertEquals(200, processed.size());+ completions.forEach(Runnable::run);+ completions.clear();+ holdCompletions = false;+ trigger.sweep();+ trigger.sweep();+ assertEquals(205, processed.size());+ assertEquals(205, processed.stream().distinct().count());+ }++ @Test+ void anUnreadableBlobDoesNotStrandEarlierClaimsOrBlockLaterFiles() throws IOException {+ Policy policy = processingFolder("p1", false);+ upload(1);+ upload(2);+ upload(3);+ when(blobs.load("blob-2")).thenThrow(new IOException("blob unavailable"));+ trigger.sweep();+ assertEquals(List.of("storage:1", "storage:3"), processed);+ assertTrue(runner.quiesced(policy.id()));+ doReturn(new ByteArrayResource("repaired".getBytes())).when(blobs).load("blob-2");+ trigger.sweep();+ assertEquals(List.of("storage:1", "storage:3", "storage:2"), processed);+ }++ @Test+ void aLedgerFailureStopsDiscoveryWithoutStrandingEarlierClaims() {+ Policy policy = processingFolder("p1", false);+ upload(1);+ upload(2);+ upload(3);+ doThrow(new DataAccessResourceFailureException("ledger unavailable"))+ .doCallRealMethod()+ .when(ledger)+ .claim(eq(policy.id()), eq("storage:2"), anyString(), any(), any());++ trigger.sweep();++ assertEquals(List.of("storage:1"), processed);+ assertTrue(runner.quiesced(policy.id()));+ verify(ledger, never()).claim(eq(policy.id()), eq("storage:3"), anyString(), any(), any());++ trigger.sweep();+ trigger.sweep();++ assertEquals(List.of("storage:1", "storage:2", "storage:3"), processed);+ assertTrue(runner.quiesced(policy.id()));+ }++ @Test+ void deletingAFileDuringDiscoveryDoesNotBlockTheFolder() throws IOException {+ Policy policy = processingFolder("p1", false);+ upload(1);+ upload(2);+ upload(3);+ when(blobs.load("blob-1"))+ .thenAnswer(+ inv -> {+ stored.remove(2L);+ return new ByteArrayResource("first".getBytes());+ });++ trigger.sweep();++ assertEquals(List.of("storage:1", "storage:3"), processed);+ assertTrue(runner.quiesced(policy.id()));+ upload(4);+ trigger.sweep();+ assertEquals(List.of("storage:1", "storage:3", "storage:4"), processed);+ assertTrue(runner.quiesced(policy.id()));+ }++ @Test+ void oneBrokenFolderDoesNotPreventOtherFoldersFromRunning() {+ Policy broken = processingFolder("p1", false);+ Source source = sources.get(broken.inputs().getFirst().sourceId()).orElseThrow();+ sources.save(+ new Source(+ source.id(),+ source.name(),+ source.type(),+ Map.of("folderId", "invalid"),+ true,+ "alice",+ 1L));+ processingFolder("p2", false);+ upload(1);+ trigger.sweep();+ assertEquals(List.of("storage:1"), processed);+ }++ @Test+ void manualPoliciesAndDiskFoldersDoNotGetStoragePolling() {+ Policy manual = processingFolder("p1", true);+ policies.save(manual.withSurface(Policy.SURFACE_POLICY));+ Policy disk = processingFolder("p2", true);+ Source source = sources.get(disk.inputs().getFirst().sourceId()).orElseThrow();+ sources.save(+ new Source(+ source.id(),+ source.name(),+ "folder",+ Map.of("directory", "/tmp"),+ true,+ "alice",+ 1L));+ upload(1);+ trigger.sweep();+ assertTrue(processed.isEmpty());+ }++ @Test+ void storageDisabledDoesNotPoll() {+ processingFolder("p1", true);+ upload(1);+ properties.getStorage().setEnabled(false);+ trigger.sweep();+ properties.getStorage().setEnabled(true);+ properties.getSecurity().setEnableLogin(false);+ trigger.sweep();+ assertTrue(processed.isEmpty());+ verifyNoInteractions(files);+ }++ @Test+ void aFolderPausedAfterListingIsRecheckedBeforeDispatch() {+ Policy policy = processingFolder("p1", false);+ upload(1);+ InProcessPolicyStore changingStore = spy(policies);+ doAnswer(+ inv -> {+ Object listed = inv.callRealMethod();+ policies.save(policy.withEnabled(false));+ return listed;+ })+ .when(changingStore)+ .findBindingsByTriggerType(TriggerConfig.STORAGE_FOLDER_WATCH);+ new StorageFolderTrigger(changingStore, sources, runner, properties).sweep();+ assertTrue(processed.isEmpty());+ }++ @Test+ void anAdmissionFailureForOneFolderDoesNotStopOtherFolders() {+ Policy denied = processingFolder("p1", false);+ processingFolder("p2", false);+ upload(1);+ PolicyRunner guarded = spy(runner);+ doThrow(new IllegalStateException("Allowance unavailable"))+ .when(guarded)+ .runInput(+ eq(denied),+ any(),+ eq(stirling.software.proprietary.policy.engine.SweepKind.BATCH));+ new StorageFolderTrigger(policies, sources, guarded, properties).sweep();+ assertEquals(List.of("storage:1"), processed);+ }++ @Test+ void startingTheTriggerImmediatelyChecksTheBacklog() {+ processingFolder("p1", true);+ upload(1);+ try {+ trigger.start();+ trigger.start();+ verify(engine, timeout(5000))+ .runPolicy(any(), any(), any(), any(), eq("storage:1"), any());+ } finally {+ trigger.stop();+ }+ }++ @Test+ void anArrivalSweepsOnlyTheFolderItNames() {+ processingFolder("p1", false);+ upload(1);+ Folder other = otherFolder();+ processingFolderIn("p2", other);+ StoredFile elsewhere = uploadTo(2, other);++ trigger.sweep(other.getId());++ assertEquals(List.of(identityOf(elsewhere)), processed);+ }++ @Test+ void anArrivalRunsWithoutWaitingForTheNextPoll() throws Exception {+ // A long poll interval leaves the arrival as the only thing that can start this run.+ processingFolder("p1", false);+ try {+ startAfterEmptySweep();+ upload(1);+ clearInvocations(ledger);++ trigger.onArrival(new StorageFolderArrivalEvent(folder.getId()));++ awaitProcessed(1);+ } finally {+ trigger.stop();+ }+ }++ @Test+ void aBurstOfArrivalsCostsOneSweep() throws Exception {+ processingFolder("p1", false);+ try {+ startAfterEmptySweep();+ holdCompletions = true;+ upload(1);+ upload(2);+ upload(3);+ clearInvocations(ledger);++ for (int i = 0; i < 3; i++) {+ trigger.onArrival(new StorageFolderArrivalEvent(folder.getId()));+ }++ awaitProcessed(3);+ // Coalesced: three placements enumerate the folder once, not once each.+ verify(ledger, times(1)).statesFor(eq("p1"), any());+ } finally {+ trigger.stop();+ }+ }++ @Test+ void aBacklogContinuesWhenEachBatchSettlesWithoutWaitingForThePoll() throws Exception {+ processingFolder("p1", false);+ try {+ startAfterEmptySweep();+ clearInvocations(files);+ holdCompletions = true;+ for (long id = 1; id <= 205; id++) upload(id);++ trigger.onArrival(new StorageFolderArrivalEvent(folder.getId()));+ awaitCompletions(100);+ assertEquals(100, processed.size());+ List<Runnable> first = List.copyOf(completions);+ completions.clear();+ first.subList(0, 99).forEach(Runnable::run);+ verifyNoInteractions(events);++ first.getLast().run();+ awaitCompletions(100);+ assertEquals(200, processed.size());+ finishBatch();+ awaitCompletions(5);+ assertEquals(205, processed.size());+ finishBatch();++ verify(files, timeout(5000).times(4)).findAllByFolderIdAndOwner(folder.getId(), owner);+ verify(events, times(3)).publishEvent(any(SourceBatchSettledEvent.class));+ assertEquals(205, processed.stream().distinct().count());+ } finally {+ trigger.stop();+ }+ }++ @Test+ void anArrivalDuringAManualRunContinuesAfterThatRunSettles() throws Exception {+ Policy policy = processingFolder("p1", false);+ trigger = spy(trigger);+ try {+ startAfterEmptySweep();+ holdCompletions = true;+ upload(1);+ runner.run(policy, SweepKind.USER);+ upload(2);++ trigger.onArrival(new StorageFolderArrivalEvent(folder.getId()));+ verify(trigger, timeout(5000)).sweep(folder.getId());+ assertEquals(List.of("storage:1"), processed);++ finishBatch();+ awaitCompletions(1);+ assertEquals(List.of("storage:1", "storage:2"), processed);+ } finally {+ trigger.stop();+ }+ }++ @Test+ void pausingBeforeCompletionPreventsTheNextBatch() throws Exception {+ Policy policy = processingFolder("p1", false);+ trigger = spy(trigger);+ try {+ startAfterEmptySweep();+ holdCompletions = true;+ for (long id = 1; id <= 101; id++) upload(id);+ trigger.onArrival(new StorageFolderArrivalEvent(folder.getId()));+ awaitCompletions(100);+ policies.save(policy.withEnabled(false));++ finishBatch();++ verify(events).publishEvent(any(SourceBatchSettledEvent.class));+ verify(trigger, after(750).times(1)).sweep(folder.getId());+ assertEquals(100, processed.size());+ } finally {+ trigger.stop();+ }+ }++ private void startAfterEmptySweep() throws InterruptedException {+ properties.getPolicies().setStorageFolderSweepSeconds(3600);+ CountDownLatch startup = new CountDownLatch(1);+ doAnswer(+ invocation -> {+ Object result = invocation.callRealMethod();+ startup.countDown();+ return result;+ })+ .when(ledger)+ .deleteUnseen(eq("p1"), anyLong());+ trigger.start();+ assertTrue(+ startup.await(5, TimeUnit.SECONDS), "Startup must finish listing before uploads");+ }++ private void awaitCompletions(int expected) throws InterruptedException {+ long deadline = System.currentTimeMillis() + 5_000;+ while (completions.size() < expected && System.currentTimeMillis() < deadline) {+ Thread.sleep(10);+ }+ assertEquals(expected, completions.size());+ }++ private void finishBatch() {+ List<Runnable> batch = List.copyOf(completions);+ completions.clear();+ batch.forEach(Runnable::run);+ }++ /** Waits for the arrival flush, which runs on the trigger's own scheduler thread. */+ private void awaitProcessed(int expected) throws InterruptedException {+ long deadline = System.currentTimeMillis() + 5_000;+ while (processed.size() < expected && System.currentTimeMillis() < deadline) {+ Thread.sleep(10);+ }+ assertEquals(expected, processed.size());+ }++ private Folder otherFolder() {+ Folder other = new Folder();+ other.setId(UUID.randomUUID());+ other.setOwner(owner);+ when(folders.findByIdAndOwner(other.getId(), owner)).thenReturn(Optional.of(other));+ when(files.findAllByFolderIdAndOwner(other.getId(), owner))+ .thenAnswer(+ inv ->+ stored.values().stream()+ .filter(f -> other.equals(f.getFolder()))+ .toList());+ return other;+ }++ private Policy processingFolderIn(String id, Folder target) {+ Source source =+ sources.save(+ new Source(+ id + "-source",+ "Input",+ "storage-folder",+ Map.of("folderId", target.getId().toString()),+ true,+ "alice",+ 1L));+ return policies.save(+ new Policy(+ id,+ id,+ "alice",+ true,+ List.of(+ new PipelineInput(+ source.id(),+ new TriggerConfig(+ TriggerConfig.STORAGE_FOLDER_WATCH,+ Map.of()))),+ List.of(),+ OutputSpec.inline(),+ 1L)+ .withSurface(Policy.SURFACE_PROCESSING_FOLDER));+ }++ private StoredFile uploadTo(long id, Folder target) {+ StoredFile file = upload(id);+ file.setFolder(target);+ return file;+ }++ private static String identityOf(StoredFile file) {+ return StorageFileIdentities.identity(file);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FolderServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FolderServiceTest.javaindex 13bcfbfdac..867af5d2b8 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FolderServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FolderServiceTest.java@@ -6,6 +6,8 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;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.when;import java.util.Optional;@@ -17,6 +19,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.context.ApplicationEventPublisher;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.context.SecurityContext;import org.springframework.security.core.context.SecurityContextHolder;@@ -24,6 +27,7 @@ import org.springframework.web.server.ResponseStatusException;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.event.StorageFolderArrivalEvent;import stirling.software.proprietary.storage.model.Folder;import stirling.software.proprietary.storage.model.api.CreateFolderRequest;import stirling.software.proprietary.storage.repository.FolderRepository;@@ -52,6 +56,8 @@ class FolderServiceTest {@Mock private ApplicationProperties.Security security;@Mock private ApplicationProperties.Storage storage;+ @Mock private ApplicationEventPublisher eventPublisher;+private FolderService service;private User user;@@ -64,7 +70,12 @@ class FolderServiceTest {lenient().when(security.isEnableLogin()).thenReturn(true);lenient().when(storage.isEnabled()).thenReturn(true);- service = new FolderService(folderRepository, storedFileRepository, applicationProperties);+ service =+ new FolderService(+ folderRepository,+ storedFileRepository,+ applicationProperties,+ eventPublisher);user = new User();user.setId(42L);@@ -285,6 +296,36 @@ class FolderServiceTest {assertThat(result.skippedFileIds()).containsExactly(3L, 4L);}+ @Test+ void bulkMove_announces_the_arrival_once_for_the_whole_batch() {+ Folder target = makeFolder(UUID.randomUUID(), null);+ when(folderRepository.findByIdAndOwner(eq(target.getId()), eq(user)))+ .thenReturn(Optional.of(target));+ stirling.software.proprietary.storage.model.StoredFile fileA =+ mock(stirling.software.proprietary.storage.model.StoredFile.class);+ when(fileA.getId()).thenReturn(1L);+ when(storedFileRepository.findAllByIdInAndOwner(any(), eq(user)))+ .thenReturn(java.util.List.of(fileA));++ service.bulkMoveFilesToFolder(target.getId(), java.util.List.of(1L, 2L));++ verify(eventPublisher).publishEvent(new StorageFolderArrivalEvent(target.getId()));+ }++ @Test+ void bulkMove_stays_quiet_when_the_caller_owns_none_of_the_files() {+ // Nothing moved, so a processing folder has no reason to enumerate itself.+ Folder target = makeFolder(UUID.randomUUID(), null);+ when(folderRepository.findByIdAndOwner(eq(target.getId()), eq(user)))+ .thenReturn(Optional.of(target));+ when(storedFileRepository.findAllByIdInAndOwner(any(), eq(user)))+ .thenReturn(java.util.List.of());++ service.bulkMoveFilesToFolder(target.getId(), java.util.List.of(9L));++ verify(eventPublisher, never()).publishEvent(any(StorageFolderArrivalEvent.class));+ }+// ─── helpers ────────────────────────────────────────────────────────────────private Folder makeFolder(UUID id, Folder parent) {diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 452feaeb42..3ba5191d62 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -9096,6 +9096,7 @@ editor-upload = "Every upload"folder-watch = "Folder watch"manual = "Manual"schedule = "Scheduled"+storage-folder-watch = "New files in storage folder"[portal.pipelines.type]pipeline = "Pipeline"