diff --git a/docs/adr/005-filesystem-serdes.md b/docs/adr/005-filesystem-serdes.md index cf069f302..c3b044e64 100644 --- a/docs/adr/005-filesystem-serdes.md +++ b/docs/adr/005-filesystem-serdes.md @@ -30,7 +30,8 @@ Entity IDs are `operation//result`, `operation//invoke-payload`. Polling state shares the result identity; retries and polling can serialize more than one value for an identity. External callback/invoke results can have a different producer identity from their consumer. -References must therefore be self-contained and remain readable after later writes. +Readers therefore rebuild the file path from the consumer's own context and ignore +the envelope's file path, so a reference cannot name another file. Include `FileSystemSerDes` and its storage/path options in the main `aws-durable-execution-sdk-java` artifact under @@ -44,11 +45,12 @@ The filesystem serializer wraps a configurable delegate, supports `ALWAYS` and the complete inline UTF-8 JSON envelope against 255 KiB. File/preview envelopes must meet the same limit. Null serialized values remain null. -Every write uses a unique immutable file under the execution directory. The write -and local flush must succeed before its pointer is returned. This preserves older -checkpoints if a subsequent polling/retry write succeeds but its checkpoint does -not. Ordinary exceptions trigger cleanup of unpublished files; crashes may leave -orphans. No successful payload file is deleted automatically. +Each entity has one file under the execution directory, named from the entity ID, +matching the JavaScript and Python SDKs. A later write to the same entity replaces +the file (last write wins), so an older checkpoint reads the newer value. The write +and local flush must succeed before its pointer is returned. A failed write never +deletes the file, but one that fails partway can leave it partial or empty. No payload file is deleted +automatically. Filesystem SerDes is configured per operation, matching .NET. Context-free calls fail clearly. Global Lambda input/output and the internal durable protocol envelope @@ -62,11 +64,12 @@ arrange compatible envelopes and shared storage on both sides of those boundarie thread affinity. No inheritance-based thread-local propagation is needed. - Filesystem I/O stays synchronous, consistent with the existing SerDes contract. Delegate encoding still materializes a string in memory. -- Immutable files preserve replay but require external retention and cleanup. +- Last write wins: a retried or polled entity replaces its earlier value, and files + need external retention and cleanup. - Mounted storage must survive execution-environment replacement. `/tmp` cannot do this; delayed mount synchronization can also lose recent writes. -- The application controls the mount. Path confinement and symlink checks protect - against malformed references but do not sandbox another process with mount access. +- The application controls the mount. Rebuilding the path and the symlink checks protect + against forged references but do not sandbox another process with mount access. - Filesystem serialization uses the existing SDK build, coverage, and publication. Unit tests live in `sdk`; local-runner integration tests live in `sdk-integration-tests`. No module or third-party library is added. @@ -81,9 +84,10 @@ A separate `PayloadOffloader`, dedicated executors, deserialization caches, and serializer retry decorators may be useful independently. They are not required for the per-operation filesystem feature and would expand its API and runtime scope. -Overwriting one file per entity uses less storage but can corrupt an older -checkpoint when a write succeeds and checkpoint publication fails. Immutable -references are required instead. +A unique file per write keeps older checkpoints readable when a write succeeds and +checkpoint publication fails, but it uses more storage and differs from the +JavaScript and Python SDKs. One file per entity was chosen instead, and last write +wins. See the [filesystem serialization guide](../advanced/filesystem-serdes.md) for configuration, wire format, storage lifetime, and validation. diff --git a/docs/advanced/filesystem-serdes.md b/docs/advanced/filesystem-serdes.md index 4fb869f8c..4c073fae1 100644 --- a/docs/advanced/filesystem-serdes.md +++ b/docs/advanced/filesystem-serdes.md @@ -52,14 +52,14 @@ Custom delegates and preview generators must support concurrent use. | `previewGenerator` | Add a small JSON object alongside a file pointer. Return null to omit it. Previews are visible in checkpoint APIs; include only intended fields. | A pointer plus preview must also fit within 255 KiB. Oversized previews fail -serialization and the unpublished file is removed. Preview failures propagate. +serialization before any file is written. Preview failures propagate. ## Operations and external boundaries Configure `serDes(files)` on `StepConfig`, `RunInChildContextConfig`, `MapConfig`, `ParallelBranchConfig`, or `WaitForConditionConfig`. Step exceptions are offloaded -through the same serializer with a separate entity identity. Polling states keep -separate immutable files even though they share an operation ID. +through the same serializer with a separate entity identity. Polling states +share one file, so each poll replaces the previous state (last write wins). Like the .NET filesystem serializer, this implementation requires operation context. Do not use it as `DurableConfig.withSerDes(files)`: the global serializer @@ -68,23 +68,37 @@ Keep handler inputs/outputs small and normally encoded. Calling the two original context-free SerDes methods throws a descriptive `SerDesException`. `CallbackConfig.serDes(files)` and `InvokeConfig.serDes(files)` expect the producer -to supply a filesystem envelope and both sides to access the same mounted path. -The producer can call the explicit context overload with its own stable identity: +to supply a filesystem envelope. The consumer reads a `file` envelope from the path +it builds for its own execution and operation, so a producer should send an inline +`{"data":""}` envelope, for example from an `OVERFLOW` serializer. `OVERFLOW` +stores an inline envelope up to 255 KiB, including escaping; a larger payload still +overflows to a `file` envelope under the producer's identity. The consumer reads its +own file, so this inline route only carries payloads under that +limit: ```java +import software.amazon.lambda.durable.serde.FileSystemSerDes; +import software.amazon.lambda.durable.serde.FileSystemStorageMode; import software.amazon.lambda.durable.serde.SerDesContext; -var envelope = files.serialize(value, +var inline = FileSystemSerDes.builder(base).storageMode(FileSystemStorageMode.OVERFLOW).build(); +var envelope = inline.serialize(value, new SerDesContext(durableExecutionArn, "external/approval/result")); // Send envelope as the callback result, or return it from the invoked function. ``` -The consumer context identifies the receiving operation; it need not equal the -producer context. Ordinary JSON callback/invoke results are not automatically -interpreted as filesystem envelopes. For a normal JSON invoke request with an -offloaded response, explicitly set `InvokeConfig.payloadSerDes(new JacksonSerDes())` -and `.serDes(files)`. Offloading the request itself with `.payloadSerDes(files)` -requires the invoked function to explicitly decode that envelope. +A producer can still offload a payload over that limit, by serializing it with a +`SerDesContext` naming the **consumer's own** execution ARN and the exact entity +value the consumer reads: `operation//result` for a callback or invoke result, +`operation//invoke-payload` for an invoke request. The producer also needs the +same `basePath` and `pathEncoding`. A `file` envelope written under any other +identity, including the producer's own, is not read. Ordinary JSON +callback/invoke results are not automatically interpreted as filesystem envelopes. +For a normal JSON invoke request with an offloaded response, explicitly set +`InvokeConfig.payloadSerDes(new JacksonSerDes())` and `.serDes(files)`. Offloading +the request itself with `.payloadSerDes(files)` means the invoked function must +decode that envelope with the **caller's** execution ARN and operation ID, the +identity `InvokeOperation` wrote the payload under, not its own. Test runners support an explicit serializer when inspecting a step result: @@ -101,37 +115,55 @@ Use `getStepDetails().result()` to inspect the raw checkpoint string. See ## Storage and replay -Use a durable, shared mount such as EFS with the same absolute path on every +Use a durable, shared mount such as EFS, with the same `basePath` on every execution environment. Lambda `/tmp` is ephemeral and unsuitable for production replay. Filesystems with delayed remote synchronization, including S3 Files, can lose recent writes on runtime failure; local flush completion does not remove that storage-specific durability limitation. -Each successful serialization creates a new file, closes and flushes it, then -returns its pointer. Later writes for the same execution/entity never change -previously returned references. A failed write or envelope construction removes -its unpublished file when possible. A process crash can leave an orphaned file. +Each entity has one file. A successful serialization writes it, closes and flushes +it, then returns its pointer. A later write for the same execution and entity +replaces the file (last write wins), so an earlier envelope reads the newer value. +For example, if a polling state is written but its checkpoint then fails, replay +reads that newer state. Concurrent writes to one entity can leave a torn file. +A failed write never deletes the file, but one that fails partway can leave it +partial or empty. Files are never automatically deleted, including after completion. Retain them for the complete execution and replay lifetime and arrange external cleanup for -completed/abandoned executions and orphaned writes. Repeated polling, retries, -and child-context execution can create additional files. - -The mount and base directory must be controlled by the application. Readers reject -relative paths, traversal outside the base, and symlinks below it; writers reject -symlink execution directories. These checks do not isolate the application from +completed and abandoned executions. + +The `file` path in an envelope is for people who browse the mount. Readers do not +open that path. They rebuild it from the base path, the execution ARN and the entity +ID, the same way the writer did. An envelope that names another execution's or +entity's file reads this execution's and entity's file instead, and fails if there +is none. A callback or invoke producer that sends a `file` envelope must have written +it with a `FileSystemSerDes` that used the consumer's execution ARN and entity ID and +the same `basePath` and `pathEncoding`. The `basePath` and `pathEncoding` +must stay the same for an execution's replay lifetime, because the path is rebuilt +from them. + +The mount and base directory must be controlled by the application. Readers ignore the +envelope's file path and reject symlinks in the rebuilt path; writers reject +symlink execution directories and symlink files. These checks do not isolate the application from other processes that can modify its mount. Filesystem permissions and retention remain the application's responsibility. Missing files and I/O failures surface as `SerDesException` with their original cause. +Executions that wrote files with an earlier SDK version cannot be read after +upgrading, because those file names carry a write ID. Let in-flight executions +finish before upgrading. + ## Checkpoint format ```json {"data":""} -{"file":""} +{"file":""} {"file":"","preview":{"characters":400000}} ``` +The writer emits an absolute path. Readers ignore it, so any non-blank string is accepted. + Exactly one string field, `data` or `file`, is required. Inline data is a JSON string containing the delegate payload, not an embedded JSON object. A file contains the delegate payload itself. Null values use the existing null SerDes diff --git a/docs/advanced/testing.md b/docs/advanced/testing.md index ce0fa3375..cf0c5e941 100644 --- a/docs/advanced/testing.md +++ b/docs/advanced/testing.md @@ -111,8 +111,8 @@ identity it was created with, including after replay or when a cloud runner is reused for another execution. Local filesystem tests can use a JUnit `@TempDir`. Cloud tests that decode file -references need access to the same filesystem at the absolute path stored by the -function; the runner does not download payload files from Lambda. Collecting +references use a `FileSystemSerDes` with the function's `basePath` and `pathEncoding` +and need that mount; the runner does not download payload files from Lambda. Collecting results and inspecting raw pointers remains possible without that mount. An explicit filesystem read fails with `SerDesException` if its file is unavailable. diff --git a/docs/design.md b/docs/design.md index 50bde8b0d..794832e05 100644 --- a/docs/design.md +++ b/docs/design.md @@ -694,7 +694,7 @@ The execution ARN remains stable across Lambda invocations. An entity ID combine `SerializableDurableOperation` supplies this context when serializing and deserializing results and exception data. `InvokeOperation` supplies the request context before checkpointing an invocation. Result deserialization receives the same operation identity during initial execution and replay. Exception type reconstruction and stack traces remain the responsibility of the operation runtime and `ExceptionHelper`. -An entity identifies a payload role, not an individual write: retries and polling can serialize multiple values for the same entity. External-storage serializers must preserve every reference already returned for checkpointing. Callback and invoke results may have a different producer identity; their deserialization context identifies the receiving operation. +An entity identifies a payload role, not an individual write: retries and polling can serialize multiple values for the same entity. `FileSystemSerDes` keeps one file per entity, so a later write replaces an earlier value. Callback and invoke results may have a different producer identity; their deserialization context identifies the receiving operation. SerDes calls run synchronously on the calling thread. Serialization and deserialization can occur on different worker or context threads, so context is passed directly to each call and shared serializers must support concurrent use. Calls may repeat, including repeated result reads; there is no general SerDes deserialization cache or dedicated SerDes executor. @@ -750,9 +750,9 @@ The checkpoint representations are: A null delegate result remains null without creating a file. File-pointer envelopes, including any preview, must also fit within 255 KiB. Deserialization validates that the envelope contains exactly one string-valued `data` or `file` field, then delegates the inline or loaded payload using the caller's `TypeToken` and context. -Each offload writes a unique immutable file under the execution directory and flushes and closes it before returning the pointer. If a later write succeeds but its checkpoint fails, an earlier checkpoint still reads its original file. Ordinary failures attempt to remove unpublished files; a process crash can leave an orphan. Published files remain until the application cleans them up after their full execution and replay lifetime. +Each offload writes one file per entity under the execution directory and flushes and closes it before returning the pointer. A later write for the same entity replaces the file (last write wins), and a failed write never deletes it but can leave it partial or empty. Files remain until the application cleans them up after their full execution and replay lifetime. -Filesystem paths must remain accessible at the same absolute location across execution environments. Use a durable shared mount such as EFS; Lambda `/tmp` cannot support that replay contract. Local flush completion does not guarantee remote persistence for mounts with delayed synchronization, including S3 Files. The application controls the mount and base directory; the serializer rejects references outside the base and symlinks below it, but does not isolate other processes with write access to the mount. +Filesystem paths must be reachable through the same `basePath` across execution environments. Use a durable shared mount such as EFS; Lambda `/tmp` cannot support that replay contract. Local flush completion does not guarantee remote persistence for mounts with delayed synchronization, including S3 Files. The application controls the mount and base directory; the serializer ignores the envelope's file path, rebuilds the path under the base, and rejects symlinks in the rebuilt path, but does not isolate other processes with write access to the mount. `FileSystemSerDes` rejects context-free calls, so it cannot be the global `DurableConfig` serializer. Configure it through `StepConfig`, `RunInChildContextConfig`, `MapConfig`, `ParallelBranchConfig`, or `WaitForConditionConfig`. Callback and invoke use also requires the external producer/consumer to understand the envelope and share the storage. Ordinary Lambda input/output and ordinary JSON callback/invoke payloads do not become filesystem envelopes automatically. diff --git a/sdk-integration-tests/src/test/java/software/amazon/lambda/durable/FileSystemSerDesIntegrationTest.java b/sdk-integration-tests/src/test/java/software/amazon/lambda/durable/FileSystemSerDesIntegrationTest.java index c1845cb3e..9726c0ecb 100644 --- a/sdk-integration-tests/src/test/java/software/amazon/lambda/durable/FileSystemSerDesIntegrationTest.java +++ b/sdk-integration-tests/src/test/java/software/amazon/lambda/durable/FileSystemSerDesIntegrationTest.java @@ -3,6 +3,7 @@ package software.amazon.lambda.durable; import static org.junit.jupiter.api.Assertions.*; +import static software.amazon.lambda.durable.model.ExecutionStatus.FAILED; import static software.amazon.lambda.durable.model.ExecutionStatus.PENDING; import static software.amazon.lambda.durable.model.ExecutionStatus.SUCCEEDED; @@ -12,6 +13,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import software.amazon.lambda.durable.config.CallbackConfig; @@ -25,6 +27,7 @@ import software.amazon.lambda.durable.retry.RetryDecision; import software.amazon.lambda.durable.retry.RetryStrategies; import software.amazon.lambda.durable.serde.FileSystemSerDes; +import software.amazon.lambda.durable.serde.FileSystemStorageMode; import software.amazon.lambda.durable.serde.JacksonSerDes; import software.amazon.lambda.durable.serde.SerDes; import software.amazon.lambda.durable.serde.SerDesContext; @@ -134,7 +137,7 @@ void retryKeepsExceptionAndSuccessPayloadsIndependentlyReadable() { } @Test - void pollingRetainsAllCheckpointedStatesAcrossSuspension() { + void pollingOverwritesTheSameFileAcrossSuspension() { var serDes = new TrackingSerDes(directory); var calls = new AtomicInteger(); var runner = LocalDurableTestRunner.create( @@ -158,12 +161,11 @@ void pollingRetainsAllCheckpointedStatesAcrossSuspension() { assertEquals(3, result.getResult(Integer.class)); assertEquals(3, calls.get()); assertEquals(4, serDes.writes.size()); - for (int state = 0; state <= 3; state++) { - var stored = serDes.writes.get(state); - assertEquals(state, serDes.deserialize(stored.payload(), TypeToken.get(Integer.class), stored.context())); + for (var stored : serDes.writes) { + assertEquals(3, serDes.deserialize(stored.payload(), TypeToken.get(Integer.class), stored.context())); } assertEquals(1, serDes.writes.stream().map(Stored::context).distinct().count()); - assertEquals(4, serDes.writes.stream().map(Stored::payload).distinct().count()); + assertEquals(1, serDes.writes.stream().map(Stored::payload).distinct().count()); } @Test @@ -219,7 +221,8 @@ void callbackConsumesAnExplicitlyEncodedExternalEnvelope() { .get()); assertEquals(PENDING, runner.run("input").getStatus()); var producer = new SerDesContext("external-producer", "approval"); - runner.completeCallback(runner.getCallbackId("callback"), serDes.serialize("approved", producer)); + runner.completeCallback( + runner.getCallbackId("callback"), inline(directory).serialize("approved", producer)); var result = runner.runUntilComplete("input"); assertEquals("approved", result.getResult(String.class)); assertEquals( @@ -228,6 +231,67 @@ void callbackConsumesAnExplicitlyEncodedExternalEnvelope() { assertNotEquals(producer, serDes.reads.get(0)); } + @Test + void callbackDoesNotReadAFileWrittenUnderAnotherIdentity() { + var serDes = new TrackingSerDes(directory); + var runner = LocalDurableTestRunner.create( + String.class, + (input, ctx) -> ctx.createCallback( + "callback", + String.class, + CallbackConfig.builder().serDes(serDes).build()) + .get()); + assertEquals(PENDING, runner.run("input").getStatus()); + var forged = serDes.serialize("approved", new SerDesContext("external-producer", "approval")); + runner.completeCallback(runner.getCallbackId("callback"), forged); + var result = runner.runUntilComplete("input"); + assertEquals(FAILED, result.getStatus()); + assertTrue(result.getError().orElseThrow().errorMessage().contains("Cannot read filesystem payload")); + } + + @Test + void callbackReadsAFileWrittenUnderTheConsumersOwnContext() { + var serDes = new TrackingSerDes(directory); + var arn = new AtomicReference(); + var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> { + arn.set(ctx.getExecutionArn()); + return ctx.createCallback( + "callback", + String.class, + CallbackConfig.builder().serDes(serDes).build()) + .get(); + }); + assertEquals(PENDING, runner.run("input").getStatus()); + var own = new SerDesContext( + arn.get(), "operation/" + runner.getOperation("callback").getId() + "/result"); + runner.completeCallback(runner.getCallbackId("callback"), serDes.serialize("approved", own)); + var result = runner.runUntilComplete("input"); + assertEquals(SUCCEEDED, result.getStatus()); + assertEquals("approved", result.getResult(String.class)); + } + + @Test + void invokeReadsAFileWrittenUnderTheConsumersOwnContext() { + var serDes = new TrackingSerDes(directory); + var arn = new AtomicReference(); + var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> { + arn.set(ctx.getExecutionArn()); + return ctx.invoke( + "invoke", + "target", + input, + String.class, + InvokeConfig.builder().serDes(serDes).build()); + }); + assertEquals(PENDING, runner.run("input").getStatus()); + var own = new SerDesContext( + arn.get(), "operation/" + runner.getOperation("invoke").getId() + "/result"); + runner.completeChainedInvoke("invoke", serDes.serialize("output", own)); + var result = runner.runUntilComplete("input"); + assertEquals(SUCCEEDED, result.getStatus()); + assertEquals("output", result.getResult(String.class)); + } + @Test void invokeSeparatesPayloadAndResultIdentity() { var serDes = new TrackingSerDes(directory); @@ -247,7 +311,8 @@ void invokeSeparatesPayloadAndResultIdentity() { assertTrue(payload.context().entityId().endsWith("/invoke-payload")); assertEquals("input", serDes.deserialize(payload.payload(), TypeToken.get(String.class), payload.context())); serDes.reads.clear(); - runner.completeChainedInvoke("invoke", serDes.serialize("output", new SerDesContext("callee", "output"))); + runner.completeChainedInvoke( + "invoke", inline(directory).serialize("output", new SerDesContext("callee", "output"))); assertEquals("output", runner.runUntilComplete("input").getResult(String.class)); assertTrue(serDes.reads.get(0).entityId().endsWith("/result")); assertEquals( @@ -262,6 +327,12 @@ void legacySerializerDefaultOverloadsRemainCompatible() { "value", legacy.deserialize(legacy.serialize("value", context), TypeToken.get(String.class), context)); } + private static FileSystemSerDes inline(Path directory) { + return FileSystemSerDes.builder(directory) + .storageMode(FileSystemStorageMode.OVERFLOW) + .build(); + } + private record Stored(SerDesContext context, String payload) {} private static final class TrackingSerDes implements SerDes { diff --git a/sdk/src/main/java/software/amazon/lambda/durable/serde/FileSystemSerDes.java b/sdk/src/main/java/software/amazon/lambda/durable/serde/FileSystemSerDes.java index 929b2515b..4e3877487 100644 --- a/sdk/src/main/java/software/amazon/lambda/durable/serde/FileSystemSerDes.java +++ b/sdk/src/main/java/software/amazon/lambda/durable/serde/FileSystemSerDes.java @@ -4,7 +4,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.LinkOption.NOFOLLOW_LINKS; +import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; +import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import static java.util.Objects.requireNonNull; @@ -41,9 +43,11 @@ * environment. A mount with delayed remote synchronization can lose payloads even after a successful local write. The * mount and base directory must be controlled by the application, not writable by untrusted processes. * - *

Each write creates an immutable file so retrying or polling never changes an earlier checkpoint's value. Files are - * not automatically deleted: retain them for the execution's full replay lifetime, then apply external cleanup. - * Configuration is immutable; custom delegates and preview generators must support concurrent calls. + *

Each entity has one file; a later write replaces it (last write wins). Concurrent writes can leave it torn. + * + *

Deserialization ignores the envelope's file path and rebuilds it from the base path, execution and entity. + * + *

Configuration is immutable; custom delegates and preview generators must support concurrent calls. */ public final class FileSystemSerDes implements SerDes { // Leave 1 KiB below the service's 256 KiB limit for checkpoint metadata. @@ -106,9 +110,9 @@ public T deserialize(String data, TypeToken typeToken, SerDesContext cont String serialized; try { serialized = envelope.has("file") - ? readFile(Path.of(envelope.get("file").textValue())) + ? readFile(resolveFilePath(context)) : envelope.get("data").textValue(); - } catch (IOException | IllegalArgumentException e) { + } catch (IOException e) { throw new SerDesException( "Cannot read filesystem payload; its shared mount must remain available for replay", e); } @@ -117,43 +121,50 @@ public T deserialize(String data, TypeToken typeToken, SerDesContext cont private String writeFile(String serialized, Map preview, SerDesContext context) throws IOException { var directory = executionDirectory(context.durableExecutionArn()); - var file = Files.createTempFile(directory, encodeSegment(context.entityId()) + "-", ".json"); - try { - var fields = new LinkedHashMap(); - fields.put("file", file.toString()); - if (preview != null) fields.put("preview", preview); - var envelope = encodeEnvelope(fields); - if (!fitsCheckpoint(envelope)) { - throw new SerDesException( - "Filesystem pointer and preview exceed the 255 KiB checkpoint envelope limit"); - } - writePayload(file, serialized); - return envelope; - } catch (IOException | RuntimeException | Error e) { - try { - Files.deleteIfExists(file); - } catch (IOException cleanupFailure) { - e.addSuppressed(cleanupFailure); - } - throw e; + var file = directory.resolve(fileName(context.entityId())); + var fields = new LinkedHashMap(); + fields.put("file", file.toString()); + if (preview != null) fields.put("preview", preview); + var envelope = encodeEnvelope(fields); + if (!fitsCheckpoint(envelope)) { + throw new SerDesException("Filesystem pointer and preview exceed the 255 KiB checkpoint envelope limit"); } + writePayload(file, serialized); + return envelope; } private static void writePayload(Path file, String serialized) throws IOException { - // The unique file is published only by returning its pointer after the complete write and flush. - try (var channel = FileChannel.open(file, WRITE, NOFOLLOW_LINKS)) { + try (var channel = FileChannel.open(file, CREATE, WRITE, TRUNCATE_EXISTING, NOFOLLOW_LINKS)) { var buffer = ByteBuffer.wrap(serialized.getBytes(UTF_8)); while (buffer.hasRemaining()) channel.write(buffer); channel.force(true); } } + /** Rebuilds the file path that {@link #writeFile} uses for this execution and entity. */ + private Path resolveFilePath(SerDesContext context) { + var directory = basePath; + for (var segment : executionSegments(context.durableExecutionArn())) { + directory = directory.resolve(segment); + } + return directory.resolve(fileName(context.entityId())); + } + + private String fileName(String entityId) { + return encodeSegment(entityId) + ".json"; + } + + private String[] executionSegments(String arn) { + var segments = pathEncoding == FileSystemPathEncoding.HASH ? new String[] {arn} : arn.split("/", -1); + for (int i = 0; i < segments.length; i++) segments[i] = encodeSegment(segments[i]); + return segments; + } + private Path executionDirectory(String arn) throws IOException { Files.createDirectories(basePath); var directory = basePath; - var segments = pathEncoding == FileSystemPathEncoding.HASH ? new String[] {arn} : arn.split("/", -1); - for (var segment : segments) { - directory = directory.resolve(encodeSegment(segment)); + for (var segment : executionSegments(arn)) { + directory = directory.resolve(segment); try { Files.createDirectory(directory); } catch (FileAlreadyExistsException e) { @@ -164,17 +175,13 @@ private Path executionDirectory(String arn) throws IOException { } private String readFile(Path file) throws IOException { - var normalized = file.normalize(); - if (!file.isAbsolute() || !normalized.startsWith(basePath) || normalized.equals(basePath)) { - throw new SerDesException("Filesystem payload must be within the configured base path"); - } var current = basePath; - for (var segment : basePath.relativize(normalized)) { + for (var segment : basePath.relativize(file)) { current = current.resolve(segment); if (Files.isSymbolicLink(current)) throw new SerDesException("Filesystem payload paths cannot contain symlinks"); } - try (var channel = Files.newByteChannel(normalized, READ, NOFOLLOW_LINKS); + try (var channel = Files.newByteChannel(file, READ, NOFOLLOW_LINKS); var stream = Channels.newInputStream(channel)) { return new String(stream.readAllBytes(), UTF_8); } diff --git a/sdk/src/test/java/software/amazon/lambda/durable/serde/FileSystemSerDesTest.java b/sdk/src/test/java/software/amazon/lambda/durable/serde/FileSystemSerDesTest.java index afe51a413..47124f73e 100644 --- a/sdk/src/test/java/software/amazon/lambda/durable/serde/FileSystemSerDesTest.java +++ b/sdk/src/test/java/software/amazon/lambda/durable/serde/FileSystemSerDesTest.java @@ -25,6 +25,9 @@ class FileSystemSerDesTest { private static final SerDesContext CONTEXT = new SerDesContext( "arn:aws:lambda:us-east-1:123456789012:function:test:1/durable-execution/order/invocation", "operation/1/result"); + private static final SerDesContext OTHER_EXECUTION = new SerDesContext( + "arn:aws:lambda:us-east-1:123456789012:function:test:1/durable-execution/other/invocation", + "operation/1/result"); private static final TypeToken STRING = TypeToken.get(String.class); private static final ObjectMapper JSON = new ObjectMapper(); @@ -33,16 +36,27 @@ class FileSystemSerDesTest { @ParameterizedTest @EnumSource(FileSystemPathEncoding.class) - void roundTripsGenericValuesAndKeepsEarlierReferencesReadable(FileSystemPathEncoding encoding) throws Exception { + void roundTripsGenericValues(FileSystemPathEncoding encoding) throws Exception { var serDes = FileSystemSerDes.builder(directory).pathEncoding(encoding).build(); - var first = serDes.serialize(List.of("first", "日本語"), CONTEXT); - var second = serDes.serialize(List.of("second"), CONTEXT); + var envelope = serDes.serialize(List.of("first", "日本語"), CONTEXT); var type = new TypeToken>() {}; - assertEquals(List.of("first", "日本語"), serDes.deserialize(first, type, CONTEXT)); - assertEquals(List.of("second"), serDes.deserialize(second, type, CONTEXT)); - assertNotEquals(file(first), file(second)); - assertEquals("[\"first\",\"日本語\"]", Files.readString(file(first))); - assertTrue(file(first).isAbsolute()); + assertEquals(List.of("first", "日本語"), serDes.deserialize(envelope, type, CONTEXT)); + assertEquals("[\"first\",\"日本語\"]", Files.readString(file(envelope))); + assertTrue(file(envelope).isAbsolute()); + } + + @ParameterizedTest + @EnumSource(FileSystemPathEncoding.class) + void secondWriteOverwritesTheFirst(FileSystemPathEncoding encoding) throws Exception { + var serDes = FileSystemSerDes.builder(directory).pathEncoding(encoding).build(); + var first = serDes.serialize("first", CONTEXT); + var second = serDes.serialize("second", CONTEXT); + assertEquals(file(first), file(second)); + assertEquals("second", serDes.deserialize(second, STRING, CONTEXT)); + assertEquals("second", serDes.deserialize(first, STRING, CONTEXT)); + try (var files = Files.walk(directory)) { + assertEquals(1, files.filter(Files::isRegularFile).count()); + } } @Test @@ -115,14 +129,13 @@ public T deserialize(String data, TypeToken type) { } @Test - void rejectsOversizedPreviewAndRemovesUnpublishedFile() throws Exception { + void rejectsOversizedPreviewAndKeepsEarlierFile() throws Exception { var serDes = FileSystemSerDes.builder(directory) - .previewGenerator(value -> Map.of("large", "x".repeat(256 * 1024))) + .previewGenerator(value -> Map.of("large", "big".equals(value) ? "x".repeat(256 * 1024) : "x")) .build(); - assertThrows(SerDesException.class, () -> serDes.serialize("value", CONTEXT)); - try (var files = Files.walk(directory)) { - assertEquals(0, files.filter(Files::isRegularFile).count()); - } + var first = serDes.serialize("small", CONTEXT); + assertThrows(SerDesException.class, () -> serDes.serialize("big", CONTEXT)); + assertEquals("small", serDes.deserialize(first, STRING, CONTEXT)); } @ParameterizedTest @@ -168,17 +181,19 @@ void requiresExplicitIdentityEvenForNullAndInlineValues() { } @Test - void rejectsPathsOutsideBaseAndMissingFiles() throws Exception { + void ignoresEnvelopePathsAndRejectsMissingFiles() throws Exception { var base = directory.resolve("payloads"); var serDes = FileSystemSerDes.builder(base).build(); var outside = Files.writeString(directory.resolve("outside.json"), "\"outside\""); - for (var path : List.of(outside, base.resolve("../outside.json"), Path.of("relative.json"))) { - var envelope = JSON.writeValueAsString(Map.of("file", path.toString())); - assertThrows(SerDesException.class, () -> serDes.deserialize(envelope, STRING, CONTEXT)); + var paths = List.of(outside.toString(), base.resolve("../outside.json").toString(), "relative.json"); + for (var path : paths) { + var error = assertThrows(SerDesException.class, () -> serDes.deserialize(envelope(path), STRING, CONTEXT)); + assertInstanceOf(IOException.class, error.getCause()); } - var envelope = serDes.serialize("value", CONTEXT); - Files.delete(file(envelope)); - var error = assertThrows(SerDesException.class, () -> serDes.deserialize(envelope, STRING, CONTEXT)); + var own = serDes.serialize("self", CONTEXT); + for (var path : paths) assertEquals("self", serDes.deserialize(envelope(path), STRING, CONTEXT)); + Files.delete(file(own)); + var error = assertThrows(SerDesException.class, () -> serDes.deserialize(own, STRING, CONTEXT)); assertInstanceOf(IOException.class, error.getCause()); } @@ -198,6 +213,22 @@ void rejectsSymlinkFilesAndExecutionDirectories() throws Exception { assertThrows(SerDesException.class, () -> other.serialize("value", new SerDesContext("execution", "entity"))); } + @Test + void rejectsSymlinkAtTheEntityFileOnOverwrite() throws Exception { + var serDes = FileSystemSerDes.builder(directory).build(); + var path = file(serDes.serialize("value", CONTEXT)); + var other = Files.writeString(directory.resolve("other.json"), "\"other\""); + Files.delete(path); + Files.createSymbolicLink(path, other); + assertThrows(SerDesException.class, () -> serDes.serialize("new", CONTEXT)); + assertEquals("\"other\"", Files.readString(other)); + var missing = directory.resolve("missing.json"); + Files.delete(path); + Files.createSymbolicLink(path, missing); + assertThrows(SerDesException.class, () -> serDes.serialize("new", CONTEXT)); + assertFalse(Files.exists(missing)); + } + @Test void encodesTraversalAndSeparatesExecutionsAndRoles() throws Exception { var serDes = FileSystemSerDes.builder(directory).build(); @@ -224,14 +255,17 @@ void hashSupportsLongIdentitiesAndConcurrentWrites() throws Exception { var executor = Executors.newFixedThreadPool(4); try { var tasks = new ArrayList>(); + var contexts = new ArrayList(); for (int i = 0; i < 16; i++) { var value = "value-" + i; - tasks.add(() -> serDes.serialize(value, context)); + var entity = new SerDesContext(context.durableExecutionArn(), context.entityId() + i); + contexts.add(entity); + tasks.add(() -> serDes.serialize(value, entity)); } var results = executor.invokeAll(tasks); for (int i = 0; i < results.size(); i++) { var envelope = results.get(i).get(); - assertEquals("value-" + i, serDes.deserialize(envelope, STRING, context)); + assertEquals("value-" + i, serDes.deserialize(envelope, STRING, contexts.get(i))); assertEquals( 64, file(envelope).getParent().getFileName().toString().length()); } @@ -240,6 +274,24 @@ void hashSupportsLongIdentitiesAndConcurrentWrites() throws Exception { } } + @ParameterizedTest + @EnumSource(FileSystemPathEncoding.class) + void readsOwnFileWhenEnvelopePointsToAnotherExecutionOrEntity(FileSystemPathEncoding encoding) throws Exception { + var serDes = FileSystemSerDes.builder(directory).pathEncoding(encoding).build(); + var otherEntity = new SerDesContext(CONTEXT.durableExecutionArn(), "operation/2/result"); + for (var other : List.of(OTHER_EXECUTION, otherEntity)) { + var otherEnvelope = serDes.serialize("other", other); + assertThrows(SerDesException.class, () -> serDes.deserialize(otherEnvelope, STRING, CONTEXT)); + var own = file(serDes.serialize("self", CONTEXT)); + assertEquals("self", serDes.deserialize(otherEnvelope, STRING, CONTEXT)); + Files.delete(own); + } + } + + private static String envelope(String file) throws Exception { + return JSON.writeValueAsString(Map.of("file", file)); + } + private static Path file(String envelope) throws Exception { return Path.of(JSON.readTree(envelope).get("file").asText()); }