Skip to content

Commit

Permalink
Optimise zio.http.Body.FileBody.asStream code
Browse files Browse the repository at this point in the history
  • Loading branch information
guizmaii committed Nov 19, 2024
1 parent dc1f3f4 commit e4653a3
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions zio-http/shared/src/main/scala/zio/http/Body.scala
Original file line number Diff line number Diff line change
Expand Up @@ -548,11 +548,11 @@ object Body {
}

private[zio] final case class FileBody(
file: java.io.File,
chunkSize: Int = 1024 * 4,
fileSize: Long,
override val contentType: Option[Body.ContentType] = None,
) extends Body {
file: java.io.File,
chunkSize: Int = 1024 * 4,
fileSize: Long,
override val contentType: Option[Body.ContentType] = None,
) extends Body {

override def asArray(implicit trace: Trace): Task[Array[Byte]] = ZIO.attemptBlocking {
Files.readAllBytes(file.toPath)
Expand All @@ -567,21 +567,27 @@ object Body {

override def asStream(implicit trace: Trace): ZStream[Any, Throwable, Byte] =
ZStream.unwrap {
for {
file <- ZIO.attempt(file)
fs <- ZIO.attemptBlocking(new FileInputStream(file))
size <- ZIO.attemptBlocking(Math.min(chunkSize.toLong, file.length()).toInt)
} yield ZStream
.repeatZIOOption[Any, Throwable, Chunk[Byte]] {
for {
buffer <- ZIO.succeed(new Array[Byte](size))
len <- ZIO.attemptBlocking(fs.read(buffer)).mapError(Some(_))
bytes <-
if (len > 0) ZIO.succeed(Chunk.fromArray(buffer.slice(0, len)))
else ZIO.fail(None)
} yield bytes
}
.ensuring(ZIO.attemptBlocking(fs.close()).ignoreLogged)
ZIO.blocking {
for {
r <- ZIO.attempt {
val fs = new FileInputStream(file)
val size = Math.min(chunkSize.toLong, file.length()).toInt

(fs, size)
}
(fs, size) = r
} yield ZStream
.repeatZIOOption[Any, Throwable, Chunk[Byte]] {
for {
buffer <- ZIO.succeed(new Array[Byte](size))
len <- ZIO.attempt(fs.read(buffer)).mapError(Some(_))
bytes <-
if (len > 0) ZIO.succeed(Chunk.fromArray(buffer.slice(0, len)))
else ZIO.fail(None)
} yield bytes
}
.ensuring(ZIO.attempt(fs.close()).ignoreLogged)
}
}.flattenChunks

override def contentType(newContentType: Body.ContentType): Body = copy(contentType = Some(newContentType))
Expand Down

0 comments on commit e4653a3

Please sign in to comment.