Skip to content

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

Add Track mode for retained pipeline inputs (#7982)

Anthony Stirling3273c051ad4d
diff --git a/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java b/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java
index b26b9b06d8..b4f0b6d7cb 100644
--- a/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java
+++ b/app/common/src/main/java/stirling/software/common/util/FileReadinessChecker.java
@@ -1,12 +1,12 @@
package stirling.software.common.util;
import java.io.IOException;
-import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Locale;
@@ -33,7 +33,7 @@ import stirling.software.common.model.ApplicationProperties.AutoPipeline.FileRea
* <li>The file size is stable: two reads separated by {@code sizeCheckDelayMillis} return the
* same value. This catches active copies on Linux/macOS where advisory file locking alone
* cannot detect a mid-copy file.
- * <li>An exclusive file-system lock can be acquired, confirming no other process holds it.
+ * <li>A shared file-system lock can be acquired, confirming no writer holds an exclusive lock.
* </ol>
*
* <p>All behaviour is controlled through {@link FileReadiness} inside {@link
@@ -179,16 +179,15 @@ public class FileReadinessChecker {
}
/**
- * Returns {@code true} when an exclusive file-system lock cannot be acquired, which indicates
+ * Returns {@code true} when a shared file-system lock cannot be acquired, which indicates
* another process still holds the file open for writing.
*
* <p>{@link OverlappingFileLockException} is also treated as locked: the JVM already holds a
* lock on this file (e.g. from another thread), so it is unsafe to process.
*/
private boolean isLocked(Path path) {
- try (RandomAccessFile raf = new RandomAccessFile(path.toFile(), "rw");
- FileChannel channel = raf.getChannel()) {
- FileLock lock = channel.tryLock();
+ try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
+ FileLock lock = channel.tryLock(0, Long.MAX_VALUE, true);
if (lock == null) {
log.debug("File '{}' is locked by another process", path.getFileName());
return true;
diff --git a/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java b/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java
index 5a93d106ee..b5e9d74345 100644
--- a/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/FileReadinessCheckerTest.java
@@ -309,6 +309,19 @@ class FileReadinessCheckerTest {
}
}
+ @Test
+ @DisplayName("read-only input with no writer lock is ready")
+ void readOnlyFileIsReady() throws Exception {
+ Path file = realFile("read-only.pdf", "data");
+ setLastModifiedInPast(file, 60_000);
+ org.junit.jupiter.api.Assumptions.assumeTrue(file.toFile().setReadOnly());
+ try {
+ assertTrue(checker.isReady(file));
+ } finally {
+ file.toFile().setWritable(true);
+ }
+ }
+
@Test
@DisplayName("file with no external lock and all checks passing → ready")
void noLock_ready() throws IOException {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
index e4d8ada9aa..59836624ad 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java
@@ -157,14 +157,13 @@ public class FolderInputSource implements InputSource {
identity,
success -> {
if (config.track()) {
- // Track mode never removes the input. A success settles at
- // the file's CURRENT version: an in-place pipeline replaces
- // the input with its result, and the claimed version would
- // leave the folder re-processing its own output forever.
- ctx.settle(
+ completeTracked(
+ ctx,
identity,
- success ? currentGate(file, claimedGate) : claimedGate,
- null,
+ file,
+ claimedGate,
+ contentHash,
+ config.hashIdentity(),
success);
return;
}
@@ -178,6 +177,45 @@ public class FolderInputSource implements InputSource {
return work;
}
+ /**
+ * Settle a tracked file at its post-run version. Track mode never removes the input, so an
+ * in-place pipeline has replaced the file with its own output by now: settling the claimed gate
+ * would leave the folder reprocessing that output forever.
+ *
+ * <p>The content hash is re-read for the same reason. Settling null here would leave the
+ * verification tier blind for the rest of the file's life - every later metadata-only bump (a
+ * touch, an rsync, a backup restore) would then fail the {@code hash.equals(stored)} check
+ * against a null and reprocess an unchanged document, which is exactly what {@code identity:
+ * hash} is chosen to prevent.
+ */
+ private static void completeTracked(
+ ResolveContext ctx,
+ String identity,
+ Path file,
+ String claimedGate,
+ MemoizedContentHash contentHash,
+ boolean hashIdentity,
+ boolean success) {
+ if (!success) {
+ ctx.settle(identity, claimedGate, claimedHash(file, claimedGate, contentHash), success);
+ return;
+ }
+ // Hash before gate: a file changed between the two then reads as an older gate carrying
+ // newer content, so the next sweep reprocesses. The reverse order could skip a real edit.
+ String finalHash = hashIdentity ? currentHash(file) : null;
+ ctx.settle(identity, currentGate(file, claimedGate), finalHash, true);
+ }
+
+ /** The file's content hash as it is now; null when it cannot be read. */
+ private static String currentHash(Path file) {
+ try {
+ return FolderIdentities.contentHash(file);
+ } catch (IOException | UncheckedIOException e) {
+ log.debug("Could not hash {} at settle: {}", file, e.getMessage());
+ return null;
+ }
+ }
+
/** The file's stat gate as it is now; the claimed gate when it cannot be read. */
private static String currentGate(Path file, String claimedGate) {
try {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
index 326ccef147..b5256fce42 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java
@@ -111,6 +111,7 @@ public class S3InputSource implements InputSource {
.map(object -> S3Identities.identity(config.bucket(), object.key()))
.toList());
+ boolean track = "track".equals(String.valueOf(spec.options().get("mode")).trim());
List<ResolvedInput> work = new ArrayList<>();
for (S3Object object : objects) {
String identity = S3Identities.identity(config.bucket(), object.key());
@@ -123,14 +124,15 @@ public class S3InputSource implements InputSource {
PolicyInputs.of(List.of(objectResource(client, config, object))),
identity,
success ->
- completeConsumed(
+ complete(
ctx,
client,
config,
object.key(),
identity,
gate,
- success)));
+ success,
+ track)));
}
return work;
}
@@ -141,16 +143,17 @@ public class S3InputSource implements InputSource {
* consensus delete. A failed run settles ERROR and never deletes; the DONE row of an object
* that could not be deleted still stops reprocessing.
*/
- private void completeConsumed(
+ private void complete(
ResolveContext ctx,
S3Client client,
S3Config config,
String key,
String identity,
String claimGate,
- boolean success) {
+ boolean success,
+ boolean track) {
ctx.settle(identity, claimGate, null, success);
- if (!success) {
+ if (!success || track) {
return;
}
try {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkConfig.java
index 403799a1bf..4947df22be 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkConfig.java
@@ -174,9 +174,9 @@ public record NetworkConfig(
if (mode == null || mode.isBlank()) {
return false;
}
- if (!MODE_CONSUME.equals(mode) && !MODE_SNAPSHOT.equals(mode)) {
+ if (!MODE_CONSUME.equals(mode) && !MODE_SNAPSHOT.equals(mode) && !"track".equals(mode)) {
throw new IllegalArgumentException(
- "network config 'mode' must be 'consume' or 'snapshot'");
+ "network config 'mode' must be 'consume', 'track' or 'snapshot'");
}
return MODE_SNAPSHOT.equals(mode);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
index 0fdf8d116f..6d29790e42 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java
@@ -95,6 +95,7 @@ public class NetworkInputSource implements InputSource {
.map(file -> NetworkIdentities.identity(config, file.path()))
.toList());
+ boolean track = "track".equals(String.valueOf(spec.options().get("mode")).trim());
List<ResolvedInput> work = new ArrayList<>();
for (RemoteFile file : files) {
String identity = NetworkIdentities.identity(config, file.path());
@@ -107,7 +108,7 @@ public class NetworkInputSource implements InputSource {
PolicyInputs.of(List.of(resource(config, file))),
identity,
success ->
- completeConsumed(ctx, config, file, identity, gate, success)));
+ complete(ctx, config, file, identity, gate, success, track)));
}
return work;
}
@@ -118,15 +119,16 @@ public class NetworkInputSource implements InputSource {
* consensus delete. A failed run settles ERROR and never deletes; the DONE row of a file that
* could not be deleted still stops reprocessing.
*/
- private void completeConsumed(
+ private void complete(
ResolveContext ctx,
NetworkConfig config,
RemoteFile file,
String identity,
String claimGate,
- boolean success) {
+ boolean success,
+ boolean track) {
ctx.settle(identity, claimGate, null, success);
- if (!success) {
+ if (!success || track) {
return;
}
try (RemoteFileClient client = clientFactory.connect(config)) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3Config.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3Config.java
index faaa8fe76d..adf0648ec4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3Config.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3Config.java
@@ -57,8 +57,12 @@ public record S3Config(
"s3 config requires an 'accessKeyId' and 'secretAccessKey'");
}
String mode = trimmed(options.get(MODE_OPTION));
- if (mode != null && !MODE_CONSUME.equals(mode) && !MODE_SNAPSHOT.equals(mode)) {
- throw new IllegalArgumentException("s3 config 'mode' must be 'consume' or 'snapshot'");
+ if (mode != null
+ && !MODE_CONSUME.equals(mode)
+ && !MODE_SNAPSHOT.equals(mode)
+ && !"track".equals(mode)) {
+ throw new IllegalArgumentException(
+ "s3 config 'mode' must be 'consume', 'track' or 'snapshot'");
}
// Object Lock: write-once retention, for records that must survive an administrator.
// COMPLIANCE cannot be shortened or deleted by anyone (not even the account root) before
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java
index 94e1bd52ab..0ada2d781e 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java
@@ -207,6 +207,39 @@ class FolderInputSourceTest {
assertTrue(source.resolve(hashSpec, ctx).isEmpty());
}
+ @Test
+ void trackModeInHashIdentityDoesNotReprocessAnInPlaceOutputOnALaterTouch() throws IOException {
+ Path dir = Files.createDirectories(tempDir.resolve("track-hash"));
+ Path file = dir.resolve("doc.pdf");
+ Files.writeString(file, "original");
+ InputSpec spec =
+ new InputSpec(
+ "folder",
+ Map.of(
+ "directory", dir.toString(),
+ "mode", "track",
+ "identity", "hash"));
+
+ // A run that rewrites the file in place, as an OCR-and-replace pipeline does.
+ ResolvedInput first = source.resolve(spec, ctx).get(0);
+ Files.writeString(file, "processed");
+ first.onComplete().accept(true);
+
+ assertTrue(source.resolve(spec, ctx).isEmpty(), "the in-place output must not re-claim");
+
+ // A metadata-only bump a month later: a backup restore, an rsync, an antivirus rewrite.
+ Files.setLastModifiedTime(file, FileTime.from(Instant.now().plusSeconds(60)));
+
+ // Settling a null hash here would leave nothing to compare against, so the content
+ // check would fail against null and reprocess an unchanged document.
+ assertTrue(
+ source.resolve(spec, ctx).isEmpty(),
+ "an unchanged tracked file must not reprocess on a touch under identity: hash");
+
+ Files.writeString(file, "edited by a person");
+ assertEquals(1, source.resolve(spec, ctx).size(), "a real edit must still be picked up");
+ }
+
@Test
void hashModeRetriesAFailureOnARealContentChange() throws IOException {
Path inputDir = Files.createDirectories(tempDir.resolve("in"));
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/S3InputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/S3InputSourceTest.java
index 9054b4f304..e6222f8652 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/S3InputSourceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/S3InputSourceTest.java
@@ -71,6 +71,18 @@ class S3InputSourceTest {
ctx = new RecordingContext();
}
+ @Test
+ void trackKeepsOriginalsAndOnlyClaimsChangedObjects() throws IOException {
+ listingReturns(object("doc.pdf", "etag-1"));
+ InputSpec tracked = new InputSpec("s3", options(Map.of("mode", "track")));
+ source.resolve(tracked, ctx).getFirst().onComplete().accept(true);
+ assertTrue(source.resolve(tracked, ctx).isEmpty());
+ verify(s3Client, never()).deleteObject(any(DeleteObjectRequest.class));
+ verify(s3Client, never()).headObject(any(HeadObjectRequest.class));
+ listingReturns(object("doc.pdf", "etag-2"));
+ assertEquals(1, source.resolve(tracked, ctx).size());
+ }
+
@Test
void consumeRemovesTheObjectOnceProcessed() throws IOException {
listingReturns(object("doc.pdf", "\"etag-1\""));
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/network/NetworkInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/network/NetworkInputSourceTest.java
index c125dd4919..aeda5f1a9a 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/network/NetworkInputSourceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/network/NetworkInputSourceTest.java
@@ -77,6 +77,17 @@ class NetworkInputSourceTest {
return new InputSpec("sftp", options);
}
+ @Test
+ void trackKeepsOriginalsAndOnlyClaimsChangedFiles() throws Exception {
+ server.put("in/doc.pdf", "data", 1000);
+ InputSpec tracked = sftp(Map.of("mode", "track"));
+ source.resolve(tracked, ctx).getFirst().onComplete().accept(true);
+ assertTrue(source.resolve(tracked, ctx).isEmpty());
+ assertEquals(1, source.resolve(sftp(Map.of("mode", "snapshot")), ctx).size());
+ server.put("in/doc.pdf", "changed", 2000);
+ assertEquals(1, source.resolve(tracked, ctx).size());
+ }
+
@Test
void supportsTheThreeNetworkSourceTypes() {
assertTrue(source.supports(new InputSpec("sftp", Map.of())));
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 643fcbf4bf..9c6c40400e 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -9065,10 +9065,6 @@ summary = "Strips hidden data, converts to the PDF/A archival format, and valida
[portal.policies.config.ingestion]
summary = "Classifies documents, extracts structured data, enforces naming, and normalizes pages."
-[portal.policies.config.ingestion.fields]
-belowThreshold = "Below threshold"
-minConfidence = "Min confidence"
-
[portal.policies.config.ingestion.rules]
0 = "Classify"
1 = "Extract"
@@ -9790,6 +9786,7 @@ openNav = "Open navigation"
search = "Search"
[portal.sources]
+processingModeHelp = "Track keeps originals and processes each version once. Snapshot keeps originals and processes them on every run. Consume deletes originals after successful delivery."
subtitle = "Reusable input connections that feed documents into Stirling. Configure a source once, then reference it from any number of pipelines."
title = "Sources"
@@ -9832,12 +9829,12 @@ label = "Folder"
placeholder = "Login home or share root"
[portal.sources.networkFields.mode]
-helperText = "Whether to leave the original file in place after it has been processed. If the original file is left in place, it will be re-processed next time the pipeline scans the source."
label = "After processing"
[portal.sources.networkFields.mode.options]
consume = "Delete the file"
snapshot = "Leave it in place"
+track = "Keep originals; process changes once"
[portal.sources.networkFields.recursive]
helperText = "Include subfolders if your files are organised into nested folders, or watch only the top level."
@@ -9894,12 +9891,13 @@ hash = "File Metadata & Content"
stat = "File Metadata"
[portal.sources.types.folder.fields.mode]
-helperText = "Whether to leave the original file in place after it has been processed. If the original file is left in place, it will be re-processed next time the pipeline scans the source."
+helperText = "What happens to the original file once it has been processed. \"Keep it\" remembers what it has already handled, so a file is only processed again when it actually changes."
label = "After processing"
[portal.sources.types.folder.fields.mode.options]
consume = "Delete the file"
-snapshot = "Leave it in place"
+snapshot = "Keep it, and process it again every scan"
+track = "Keep it, and only process it again if it changes"
[portal.sources.types.folder.fields.recursive]
helperText = "Include subfolders if your files are organised into nested folders, or watch only the top level."
@@ -9934,12 +9932,12 @@ helperText = "The saved connection with the bucket and credentials. Shared by ev
label = "Connection"
[portal.sources.types.s3.fields.mode]
-helperText = "Whether to leave the original object in place after it has been processed. If the original object is left in place, it will be re-processed next time the pipeline scans the source."
label = "After processing"
[portal.sources.types.s3.fields.mode.options]
consume = "Delete the object"
snapshot = "Leave it in place"
+track = "Keep originals; process changes once"
[portal.sources.types.s3.fields.prefix]
helperText = "The folder (key prefix) within the bucket to watch."
diff --git a/frontend/editor/src/portal/components/sources/SourceModal.tsx b/frontend/editor/src/portal/components/sources/SourceModal.tsx
index db83b8fdfb..eb85e72019 100644
--- a/frontend/editor/src/portal/components/sources/SourceModal.tsx
+++ b/frontend/editor/src/portal/components/sources/SourceModal.tsx
@@ -515,10 +515,10 @@ export function SourceModal({
}
// A field can gate itself on another's current value (e.g. change detection
- // only applies in consume mode), so a knob that does nothing never shows.
+ // applies to the tracked modes), so a knob that does nothing never shows.
function fieldVisible(field: SourceFieldDef): boolean {
const cond = field.visibleWhen;
- return !cond || (options[cond.key] ?? "") === cond.equals;
+ return !cond || cond.oneOf.includes(options[cond.key] ?? "");
}
const visibleFields = type.fields.filter(fieldVisible);
diff --git a/frontend/editor/src/portal/components/sources/sourceTypes.ts b/frontend/editor/src/portal/components/sources/sourceTypes.ts
index c6196a4aab..33e7dfaa42 100644
--- a/frontend/editor/src/portal/components/sources/sourceTypes.ts
+++ b/frontend/editor/src/portal/components/sources/sourceTypes.ts
@@ -76,8 +76,8 @@ export interface SourceFieldDef {
defaultValue?: string;
/** Tucked behind the "Advanced" disclosure: power settings whose default suits almost everyone. */
advanced?: boolean;
- /** Only rendered while another field currently equals this value (e.g. a knob that only applies in one mode). */
- visibleWhen?: { key: string; equals: string };
+ /** Only rendered while another field currently holds one of these values (e.g. a knob that only applies in some modes). */
+ visibleWhen?: { key: string; oneOf: string[] };
/**
* For `control: "connection"` - the connection-catalogue entry id this slot accepts (e.g.
* "sftp"). Filters the picker to matching connections and pins the inline "new connection" form.
@@ -120,13 +120,17 @@ function networkSourceFields(connectionTypeId: string): SourceFieldDef[] {
labelKey: "portal.sources.networkFields.mode.label",
control: "select",
defaultValue: "consume",
- helperTextKey: "portal.sources.networkFields.mode.helperText",
+ helperTextKey: "portal.sources.processingModeHelp",
advanced: true,
options: [
{
value: "consume",
labelKey: "portal.sources.networkFields.mode.options.consume",
},
+ {
+ value: "track",
+ labelKey: "portal.sources.networkFields.mode.options.track",
+ },
{
value: "snapshot",
labelKey: "portal.sources.networkFields.mode.options.snapshot",
@@ -174,13 +178,17 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
labelKey: "portal.sources.types.folder.fields.mode.label",
control: "select",
defaultValue: "consume",
- helperTextKey: "portal.sources.types.folder.fields.mode.helperText",
+ helperTextKey: "portal.sources.processingModeHelp",
advanced: true,
options: [
{
value: "consume",
labelKey: "portal.sources.types.folder.fields.mode.options.consume",
},
+ {
+ value: "track",
+ labelKey: "portal.sources.types.folder.fields.mode.options.track",
+ },
{
value: "snapshot",
labelKey:
@@ -215,8 +223,9 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
defaultValue: "stat",
helperTextKey: "portal.sources.types.folder.fields.identity.helperText",
advanced: true,
- // Change detection only governs the consume ledger; snapshot re-reads everything regardless.
- visibleWhen: { key: "mode", equals: "consume" },
+ // Change detection governs the ledger, which only consume and track keep;
+ // snapshot re-reads everything regardless.
+ visibleWhen: { key: "mode", oneOf: ["consume", "track"] },
options: [
{
value: "stat",
@@ -256,13 +265,17 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
labelKey: "portal.sources.types.s3.fields.mode.label",
control: "select",
defaultValue: "consume",
- helperTextKey: "portal.sources.types.s3.fields.mode.helperText",
+ helperTextKey: "portal.sources.processingModeHelp",
advanced: true,
options: [
{
value: "consume",
labelKey: "portal.sources.types.s3.fields.mode.options.consume",
},
+ {
+ value: "track",
+ labelKey: "portal.sources.types.s3.fields.mode.options.track",
+ },
{
value: "snapshot",
labelKey: "portal.sources.types.s3.fields.mode.options.snapshot",