From ce2ac3769c29fc89fb64deaeb925ee3ded9bfd93 Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Fri, 27 Nov 2026 17:50:03 +0800 Subject: [PATCH] fix: fill FileIO chunks after short positive reads Motivation: A positional file-channel read can return fewer bytes than requested without reaching EOF. Treating that as EOF could truncate the source. Modification: Keep filling the existing buffer after positive progress. Emit a full chunk, or the remaining bytes on a terminal read, without changing the read-ahead limit or materialized result and close ordering. Result: Short positive reads yield full chunks until the final chunk. The existing zero-read termination policy is unchanged. Tests: - Native FileSourceSpec and FileSourceCloseFailureSpec: 20/20 each on Scala 2.13.18 and 3.3.9, JDK 17. - The exact pre-fix FileSource blob failed the new case, as expected, with the same Scala 2.13 test classes. - Scoped Scalafmt, license header checks and git diff --check passed. References: Refs #3808 and #3815. --- .../stream/operators/FileIO/fromPath.md | 3 + .../pekko/stream/io/FileSourceSpec.scala | 65 ++++++++++++++++++- .../pekko/stream/impl/io/IOSources.scala | 21 +++--- 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/docs/src/main/paradox/stream/operators/FileIO/fromPath.md b/docs/src/main/paradox/stream/operators/FileIO/fromPath.md index d3358a5414..1322f585a6 100644 --- a/docs/src/main/paradox/stream/operators/FileIO/fromPath.md +++ b/docs/src/main/paradox/stream/operators/FileIO/fromPath.md @@ -24,6 +24,9 @@ Emits the contents of a file from the given path, as `ByteString`s, materializes an `IOResult` on end-of-file, cancellation, or failure. If the source opened the file, it attempts to close it before completing the materialized result. +Emitted elements have the configured `chunkSize` in bytes, except that the final element may be smaller. +A short read that returns some bytes does not by itself end the stream. + ## Example Scala diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala index 095d5e4903..da8c3d126a 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala @@ -13,14 +13,15 @@ package org.apache.pekko.stream.io -import java.nio.channels.FileChannel +import java.nio.channels.{ FileChannel, FileLock, ReadableByteChannel, WritableByteChannel } import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.{ Files, NoSuchFileException, StandardOpenOption } +import java.nio.{ ByteBuffer, MappedByteBuffer } import java.util.Random import scala.annotation.nowarn -import scala.concurrent.{ ExecutionContext, Future } import scala.concurrent.duration._ +import scala.concurrent.{ ExecutionContext, Future } import com.google.common.jimfs.{ Configuration, Jimfs } @@ -30,8 +31,8 @@ import pekko.stream.IOResult._ import pekko.stream.SystemMaterializer import pekko.stream._ import pekko.stream.impl.StreamSupervisor.Children -import pekko.stream.impl.{ PhasedFusingActorMaterializer, StreamSupervisor } import pekko.stream.impl.io.FileSource +import pekko.stream.impl.{ PhasedFusingActorMaterializer, StreamSupervisor } import pekko.stream.io.FileSourceSpec.Settings import pekko.stream.scaladsl.{ FileIO, Keep, Sink, Source } import pekko.stream.testkit.Utils._ @@ -101,7 +102,65 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { } } + private final class ShortReadChannel(delegate: FileChannel) extends FileChannel { + @volatile var reachedEof = false + + override def read(dst: ByteBuffer, position: Long): Int = { + val limit = dst.limit() + dst.limit(dst.position() + math.min(dst.remaining(), 2)) + try { + val read = delegate.read(dst, position) + if (read == -1) reachedEof = true + read + } finally dst.limit(limit) + } + + override def position(newPosition: Long): FileChannel = { + delegate.position(newPosition) + this + } + + override def implCloseChannel(): Unit = delegate.close() + + private def unsupported(): Nothing = throw new UnsupportedOperationException + + override def read(dst: ByteBuffer): Int = unsupported() + override def read(dsts: Array[ByteBuffer], offset: Int, length: Int): Long = unsupported() + override def write(src: ByteBuffer): Int = unsupported() + override def write(srcs: Array[ByteBuffer], offset: Int, length: Int): Long = unsupported() + override def write(src: ByteBuffer, position: Long): Int = unsupported() + override def position(): Long = unsupported() + override def size(): Long = unsupported() + override def truncate(size: Long): FileChannel = unsupported() + override def force(metaData: Boolean): Unit = unsupported() + override def transferTo(position: Long, count: Long, target: WritableByteChannel): Long = unsupported() + override def transferFrom(src: ReadableByteChannel, position: Long, count: Long): Long = unsupported() + override def map(mode: FileChannel.MapMode, position: Long, size: Long): MappedByteBuffer = unsupported() + override def lock(position: Long, size: Long, shared: Boolean): FileLock = unsupported() + override def tryLock(position: Long, size: Long, shared: Boolean): FileLock = unsupported() + } + "FileSource" must { + "fill each chunk across short positive reads until reaching EOF" in { + val file = Files.createTempFile(fs.getPath("/"), "short-reads", ".tmp") + Files.write(file, "_#abcdefghij".getBytes(UTF_8)) + val channel = new ShortReadChannel(FileChannel.open(file, StandardOpenOption.READ)) + try { + val (result, probe) = Source + .fromGraph(new FileSource(file, 4, 2, _ => channel)) + .withAttributes(Attributes.inputBuffer(1, 1)) + .toMat(TestSink())(Keep.both) + .run() + + probe.request(1).expectNext(ByteString("abcd")) + probe.request(1).expectNext(ByteString("efgh")) + probe.request(1).expectNext(ByteString("ij")) + probe.expectComplete() + result.futureValue shouldBe createSuccessful(12L) + channel.reachedEof shouldBe true + } finally channel.close() + } + for (cancel <- List(false, true)) { val outcome = if (cancel) "downstream cancellation" else "EOF" s"close the channel before completing the IOResult on $outcome" in { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala index 3805e1147a..4616ad1374 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala @@ -117,21 +117,24 @@ private[pekko] final class FileSource(path: Path, chunkSize: Int, startPosition: } if (readBytes > 0) { - buffer.flip() position += readBytes - val newChunks = chunks :+ ByteString.fromByteBuffer(buffer) - buffer.clear() - - if (readBytes < chunkSize) { - eofEncountered = true - newChunks - } else readAhead(maxChunks, newChunks) + if (buffer.hasRemaining) readAhead(maxChunks, chunks) + else readAhead(maxChunks, chunks :+ takeChunk()) } else { + // Preserve the existing stop-on-no-progress behavior for zero-byte reads. eofEncountered = true - chunks + if (buffer.position() == 0) chunks + else chunks :+ takeChunk() } } else chunks + private def takeChunk(): ByteString = { + buffer.flip() + val chunk = ByteString.fromByteBuffer(buffer) + buffer.clear() + chunk + } + override def onDownstreamFinish(cause: Throwable): Unit = { cause match { case _: SubscriptionWithCancelException.NonFailureCancellation =>