-
Notifications
You must be signed in to change notification settings - Fork 422
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
[WIP] netty-cats: support multipart requests #3933
Draft
kciesielski
wants to merge
10
commits into
master
Choose a base branch
from
netty-multipart
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4cb7800
wip
kciesielski 4720157
Split multipart tests into request / response
kciesielski 33affa7
Manage decoder as a Resource
kciesielski 1b843c3
No need for onError
kciesielski b4b7be5
Handle max content length
kciesielski eb5bc1a
Fix compilation issues
kciesielski 86d3b25
Test chunked multipart requests
kciesielski 6e9b395
Count bytes before sending data to decoder
kciesielski 4567780
Update tests
kciesielski 7127ef7
Merge branch 'master' into netty-multipart
kciesielski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,15 @@ import sttp.tapir.{FileRange, InputStreamRange, RawBodyType, TapirFile} | |
import java.io.InputStream | ||
import java.nio.ByteBuffer | ||
|
||
import scala.collection.JavaConverters._ | ||
import sttp.tapir.RawPart | ||
import io.netty.handler.codec.http.multipart.InterfaceHttpData | ||
import sttp.model.Part | ||
import io.netty.handler.codec.http.multipart.HttpData | ||
import io.netty.handler.codec.http.multipart.FileUpload | ||
import java.io.ByteArrayInputStream | ||
import java.io.File | ||
|
||
/** Common logic for processing request body in all Netty backends. It requires particular backends to implement a few operations. */ | ||
private[netty] trait NettyRequestBody[F[_], S <: Streams[S]] extends RequestBody[F, S] { | ||
|
||
|
@@ -37,6 +46,16 @@ private[netty] trait NettyRequestBody[F[_], S <: Streams[S]] extends RequestBody | |
*/ | ||
def publisherToBytes(publisher: Publisher[HttpContent], contentLength: Option[Long], maxBytes: Option[Long]): F[Array[Byte]] | ||
|
||
/** Reads the reactive stream emitting HttpData into a vector of parts. Implementation-specific, as file manipulations and stream | ||
* processing logic can be different for different backends. | ||
*/ | ||
def publisherToMultipart( | ||
nettyRequest: StreamedHttpRequest, | ||
serverRequest: ServerRequest, | ||
m: RawBodyType.MultipartBody, | ||
maxBytes: Option[Long] | ||
): F[RawValue[Seq[RawPart]]] | ||
|
||
/** Backend-specific way to process all elements emitted by a Publisher[HttpContent] and write their bytes into a file. | ||
* | ||
* @param serverRequest | ||
|
@@ -50,6 +69,8 @@ private[netty] trait NettyRequestBody[F[_], S <: Streams[S]] extends RequestBody | |
*/ | ||
def writeToFile(serverRequest: ServerRequest, file: TapirFile, maxBytes: Option[Long]): F[Unit] | ||
|
||
def writeBytesToFile(bytes: Array[Byte], file: File): F[Unit] | ||
|
||
override def toRaw[RAW]( | ||
serverRequest: ServerRequest, | ||
bodyType: RawBodyType[RAW], | ||
|
@@ -70,8 +91,8 @@ private[netty] trait NettyRequestBody[F[_], S <: Streams[S]] extends RequestBody | |
file <- createFile(serverRequest) | ||
_ <- writeToFile(serverRequest, file, maxBytes) | ||
} yield RawValue(FileRange(file), Seq(FileRange(file))) | ||
case _: RawBodyType.MultipartBody => | ||
monad.error(new UnsupportedOperationException) | ||
case m: RawBodyType.MultipartBody => | ||
publisherToMultipart(serverRequest.underlying.asInstanceOf[StreamedHttpRequest], serverRequest, m, maxBytes) | ||
} | ||
|
||
private def readAllBytes(serverRequest: ServerRequest, maxBytes: Option[Long]): F[Array[Byte]] = | ||
|
@@ -96,4 +117,72 @@ private[netty] trait NettyRequestBody[F[_], S <: Streams[S]] extends RequestBody | |
throw new UnsupportedOperationException(s"Unexpected Netty request of type ${other.getClass.getName}") | ||
} | ||
} | ||
|
||
protected def toRawPart[R]( | ||
serverRequest: ServerRequest, | ||
data: InterfaceHttpData, | ||
partType: RawBodyType[R] | ||
): F[Part[R]] = { | ||
val partName = data.getName() | ||
data match { | ||
case httpData: HttpData => | ||
// TODO filename* attribute is not used by netty. Non-ascii filenames like https://github.com/http4s/http4s/issues/5809 are unsupported. | ||
toRawPartHttpData(partName, serverRequest, httpData, partType) | ||
case unsupportedDataType => | ||
monad.error(new UnsupportedOperationException(s"Unsupported multipart data type: $unsupportedDataType in part $partName")) | ||
} | ||
} | ||
|
||
private def toRawPartHttpData[R]( | ||
partName: String, | ||
serverRequest: ServerRequest, | ||
httpData: HttpData, | ||
partType: RawBodyType[R] | ||
): F[Part[R]] = { | ||
val fileName = httpData match { | ||
case fileUpload: FileUpload => Option(fileUpload.getFilename()) | ||
case _ => None | ||
} | ||
partType match { | ||
case RawBodyType.StringBody(defaultCharset) => | ||
// TODO otherDispositionParams not supported. They are normally a part of the content-disposition part header, but this header is not directly accessible, they are extracted internally by the decoder. | ||
val charset = if (httpData.getCharset() != null) httpData.getCharset() else defaultCharset | ||
readHttpData(httpData, _.getString(charset)).map(body => Part(partName, body, fileName = fileName)) | ||
case RawBodyType.ByteArrayBody => | ||
readHttpData(httpData, _.get()).map(body => Part(partName, body, fileName = fileName)) | ||
case RawBodyType.ByteBufferBody => | ||
readHttpData(httpData, _.get()).map(body => Part(partName, ByteBuffer.wrap(body), fileName = fileName)) | ||
case RawBodyType.InputStreamBody => | ||
(if (httpData.isInMemory()) | ||
monad.unit(new ByteArrayInputStream(httpData.get())) | ||
else { | ||
monad.blocking(java.nio.file.Files.newInputStream(httpData.getFile().toPath())) | ||
}).map(body => Part(partName, body, fileName = fileName)) | ||
case RawBodyType.InputStreamRangeBody => | ||
val body = () => { | ||
if (httpData.isInMemory()) | ||
new ByteArrayInputStream(httpData.get()) | ||
else | ||
java.nio.file.Files.newInputStream(httpData.getFile().toPath()) | ||
} | ||
monad.unit(Part(partName, InputStreamRange(body), fileName = fileName)) | ||
case RawBodyType.FileBody => | ||
val fileF: F[File] = | ||
if (httpData.isInMemory()) | ||
(for { | ||
file <- createFile(serverRequest) | ||
_ <- writeBytesToFile(httpData.get(), file) | ||
} yield file) | ||
else monad.unit(httpData.getFile()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. note: Netty decoder creates the file (if it's > 16KB), so we can just get its handle here. |
||
fileF.map(file => Part(partName, FileRange(file), fileName = fileName)) | ||
case _: RawBodyType.MultipartBody => | ||
monad.error(new UnsupportedOperationException(s"Nested multipart not supported, part name = $partName")) | ||
} | ||
} | ||
|
||
private def readHttpData[T](httpData: HttpData, f: HttpData => T): F[T] = | ||
if (httpData.isInMemory()) | ||
monad.unit(f(httpData)) | ||
else | ||
monad.blocking(f(httpData)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
question: This is the part that concerns me. The
decoder
is stateful, so it has an internal state changed with every call tooffer
. Each time a newHttpContent
flows through the stream, themonad.blocking
call gets a thread from the blocking pool, where it callsoffer
. There are no race conditions, but aren't internals of the decoder risking visibility issues because of such circumstances?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is fine as long as there's some memory barrier along the way (see e.g. https://stackoverflow.com/questions/12438464/volatile-variables-and-other-variables). There should be a couple of those along the way, I suspect putting back/obtaining a thread to execute blocking ops itself imposes at least one such barrier.