-
Notifications
You must be signed in to change notification settings - Fork 422
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3017 from softwaremill/feature/netty-streaming
Netty streaming for Cats Effect
- Loading branch information
Showing
23 changed files
with
487 additions
and
109 deletions.
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
73 changes: 73 additions & 0 deletions
73
examples/src/main/scala/sttp/tapir/examples/streaming/StreamingNettyFs2Server.scala
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 |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package sttp.tapir.examples.streaming | ||
|
||
import cats.effect.{ExitCode, IO, IOApp} | ||
import cats.implicits._ | ||
import fs2.{Chunk, Stream} | ||
import sttp.capabilities.fs2.Fs2Streams | ||
import sttp.client3._ | ||
import sttp.model.HeaderNames | ||
import sttp.tapir._ | ||
import sttp.tapir.server.ServerEndpoint | ||
import sttp.tapir.server.netty.cats.{NettyCatsServer, NettyCatsServerBinding} | ||
|
||
import java.nio.charset.StandardCharsets | ||
import scala.concurrent.duration._ | ||
|
||
object StreamingNettyFs2Server extends IOApp { | ||
// corresponds to: GET /receive?name=... | ||
// We need to provide both the schema of the value (for documentation), as well as the format (media type) of the | ||
// body. Here, the schema is a `string` (set by `streamTextBody`) and the media type is `text/plain`. | ||
val streamingEndpoint: PublicEndpoint[Unit, Unit, (Long, Stream[IO, Byte]), Fs2Streams[IO]] = | ||
endpoint.get | ||
.in("receive") | ||
.out(header[Long](HeaderNames.ContentLength)) | ||
.out(streamTextBody(Fs2Streams[IO])(CodecFormat.TextPlain(), Some(StandardCharsets.UTF_8))) | ||
|
||
val serverEndpoint: ServerEndpoint[Fs2Streams[IO], IO] = streamingEndpoint | ||
.serverLogicSuccess { _ => | ||
val size = 100L | ||
Stream | ||
.emit(List[Char]('a', 'b', 'c', 'd')) | ||
.repeat | ||
.flatMap(list => Stream.chunk(Chunk.seq(list))) | ||
.metered[IO](100.millis) | ||
.take(size) | ||
.covary[IO] | ||
.map(_.toByte) | ||
.pure[IO] | ||
.map(s => (size, s)) | ||
} | ||
|
||
private val declaredPort = 9090 | ||
private val declaredHost = "localhost" | ||
|
||
override def run(args: List[String]): IO[ExitCode] = { | ||
// starting the server | ||
NettyCatsServer | ||
.io() | ||
.use { server => | ||
|
||
val startServer: IO[NettyCatsServerBinding[IO]] = server | ||
.port(declaredPort) | ||
.host(declaredHost) | ||
.addEndpoint(serverEndpoint) | ||
.start() | ||
|
||
startServer | ||
.map { binding => | ||
|
||
val port = binding.port | ||
val host = binding.hostName | ||
println(s"Server started at port = ${binding.port}") | ||
|
||
val backend: SttpBackend[Identity, Any] = HttpURLConnectionBackend() | ||
val result: String = | ||
basicRequest.response(asStringAlways).get(uri"http://$declaredHost:$declaredPort/receive").send(backend).body | ||
println("Got result: " + result) | ||
|
||
assert(result == "abcd" * 25) | ||
} | ||
.as(ExitCode.Success) | ||
} | ||
} | ||
} |
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
64 changes: 64 additions & 0 deletions
64
...ty-server/cats/src/main/scala/sttp/tapir/server/netty/internal/NettyCatsRequestBody.scala
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 |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package sttp.tapir.server.netty.internal | ||
|
||
import cats.effect.{Async, Sync} | ||
import cats.syntax.all._ | ||
import com.typesafe.netty.http.StreamedHttpRequest | ||
import fs2.Chunk | ||
import fs2.interop.reactivestreams.StreamSubscriber | ||
import fs2.io.file.{Files, Path} | ||
import io.netty.buffer.ByteBufUtil | ||
import io.netty.handler.codec.http.{FullHttpRequest, HttpContent} | ||
import sttp.capabilities.fs2.Fs2Streams | ||
import sttp.tapir.model.ServerRequest | ||
import sttp.tapir.server.interpreter.{RawValue, RequestBody} | ||
import sttp.tapir.{FileRange, InputStreamRange, RawBodyType, TapirFile} | ||
|
||
import java.io.ByteArrayInputStream | ||
import java.nio.ByteBuffer | ||
|
||
private[netty] class NettyCatsRequestBody[F[_]](createFile: ServerRequest => F[TapirFile])(implicit val monad: Async[F]) | ||
extends RequestBody[F, Fs2Streams[F]] { | ||
|
||
override val streams: Fs2Streams[F] = Fs2Streams[F] | ||
|
||
override def toRaw[R](serverRequest: ServerRequest, bodyType: RawBodyType[R]): F[RawValue[R]] = { | ||
|
||
bodyType match { | ||
case RawBodyType.StringBody(charset) => nettyRequestBytes(serverRequest).map(bs => RawValue(new String(bs, charset))) | ||
case RawBodyType.ByteArrayBody => | ||
nettyRequestBytes(serverRequest).map(RawValue(_)) | ||
case RawBodyType.ByteBufferBody => | ||
nettyRequestBytes(serverRequest).map(bs => RawValue(ByteBuffer.wrap(bs))) | ||
case RawBodyType.InputStreamBody => | ||
nettyRequestBytes(serverRequest).map(bs => RawValue(new ByteArrayInputStream(bs))) | ||
case RawBodyType.InputStreamRangeBody => | ||
nettyRequestBytes(serverRequest).map(bs => RawValue(InputStreamRange(() => new ByteArrayInputStream(bs)))) | ||
case RawBodyType.FileBody => | ||
createFile(serverRequest) | ||
.flatMap(tapirFile => { | ||
toStream(serverRequest) | ||
.through( | ||
Files[F](Files.forAsync[F]).writeAll(Path.fromNioPath(tapirFile.toPath)) | ||
) | ||
.compile | ||
.drain | ||
.map(_ => RawValue(FileRange(tapirFile), Seq(FileRange(tapirFile)))) | ||
}) | ||
case _: RawBodyType.MultipartBody => ??? | ||
} | ||
} | ||
|
||
override def toStream(serverRequest: ServerRequest): streams.BinaryStream = { | ||
val nettyRequest = serverRequest.underlying.asInstanceOf[StreamedHttpRequest] | ||
fs2.Stream | ||
.eval(StreamSubscriber[F, HttpContent](NettyRequestBody.DefaultChunkSize)) | ||
.flatMap(s => s.sub.stream(Sync[F].delay(nettyRequest.subscribe(s)))) | ||
.flatMap(httpContent => fs2.Stream.chunk(Chunk.byteBuffer(httpContent.content.nioBuffer()))) | ||
} | ||
|
||
private def nettyRequestBytes(serverRequest: ServerRequest): F[Array[Byte]] = serverRequest.underlying match { | ||
case req: FullHttpRequest => monad.delay(ByteBufUtil.getBytes(req.content())) | ||
case _: StreamedHttpRequest => toStream(serverRequest).compile.to(Chunk).map(_.toArray[Byte]) | ||
case other => monad.raiseError(new UnsupportedOperationException(s"Unexpected Netty request of type ${other.getClass().getName()}")) | ||
} | ||
} |
Oops, something went wrong.