Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimise zio.http.Body.FileBody.asStream code #3215

Merged
merged 2 commits into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions zio-http/shared/src/main/scala/zio/http/Body.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading