-
Notifications
You must be signed in to change notification settings - Fork 423
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
Chunked transmission lasts longer than timeout #4214
Draft
sergiuszkierat
wants to merge
10
commits into
master
Choose a base branch
from
fix/chunked_transmission_timeout
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.
+240
−6
Draft
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
755dcd5
Chunked transmission lasts longer than timeout
sergiuszkierat 699e4aa
Flatten nested Iterator correctly in Scala 2.12
sergiuszkierat e176a1a
fixes after adamw's feedback
sergiuszkierat fd85325
Clean up
sergiuszkierat 4ffd614
add playServer and longLastingClient
sergiuszkierat ebf5495
wip
sergiuszkierat 024332b
Revert "wip"
sergiuszkierat 0bbc22e
fixes
sergiuszkierat f217517
revert
sergiuszkierat f1aad13
fixes after review
sergiuszkierat 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
55 changes: 55 additions & 0 deletions
55
examples/src/main/scala/sttp/tapir/examples/streaming/longLastingClient.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,55 @@ | ||
//> using dep com.softwaremill.sttp.tapir::tapir-core:1.11.11 | ||
//> using dep org.apache.pekko::pekko-stream:1.1.2 | ||
//> using dep org.typelevel::cats-effect:3.5.7 | ||
//> using dep com.softwaremill.sttp.client3::core:3.10.2 | ||
//> using dep com.softwaremill.sttp.client3::pekko-http-backend:3.10.2 | ||
|
||
package sttp.tapir.examples.streaming | ||
|
||
import cats.effect.{ExitCode, IO, IOApp, Resource} | ||
import sttp.capabilities.WebSockets | ||
import sttp.client3.pekkohttp.PekkoHttpBackend | ||
import sttp.client3.{Response, SttpBackend, UriContext, basicRequest} | ||
|
||
import scala.concurrent.Future | ||
import sttp.model.{Header, HeaderNames, Method, QueryParams} | ||
import sttp.tapir.* | ||
import org.apache.pekko | ||
import org.apache.pekko.actor.ActorSystem | ||
import sttp.capabilities.pekko.PekkoStreams | ||
import pekko.stream.scaladsl.{Flow, Source} | ||
import pekko.util.ByteString | ||
import cats.effect.* | ||
import cats.syntax.all.* | ||
|
||
import scala.concurrent.duration.* | ||
import scala.concurrent.duration.FiniteDuration | ||
|
||
object longLastingClient extends IOApp: | ||
implicit val actorSystem: ActorSystem = ActorSystem("longLastingClient") | ||
|
||
private val givenLength: Long = 10000 | ||
private val chunkSize = 100 | ||
private val noChunks = givenLength / chunkSize | ||
|
||
private def makeRequest(backend: SttpBackend[Future, PekkoStreams & WebSockets]): Future[Response[Either[String, String]]] = | ||
val stream: Source[ByteString, Any] = | ||
Source.tick(1.seconds, 1.seconds, ByteString(Array.fill(chunkSize)('A').map(_.toByte))) | ||
.zipWithIndex | ||
.take(noChunks) | ||
.map { case (chunk, idx) => | ||
println(s"Chunk ${idx + 1} sent ${java.time.LocalTime.now()}"); chunk | ||
} | ||
|
||
basicRequest | ||
.post(uri"http://localhost:9000/chunks") | ||
.header(Header(HeaderNames.ContentLength, givenLength.toString)) | ||
.streamBody(PekkoStreams)(stream) | ||
.send(backend) | ||
|
||
override def run(args: List[String]): IO[ExitCode] = | ||
val backend = PekkoHttpBackend.usingActorSystem(actorSystem) | ||
val responseIO: IO[Response[Either[String, String]]] = IO.fromFuture(IO(makeRequest(backend))) | ||
responseIO.flatMap { response => | ||
IO(println(response.body)) | ||
}.as(ExitCode.Success) |
112 changes: 112 additions & 0 deletions
112
examples/src/main/scala/sttp/tapir/examples/streaming/playServer.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,112 @@ | ||
//> using dep com.softwaremill.sttp.tapir::tapir-core:1.11.11 | ||
//> using dep com.softwaremill.sttp.tapir::tapir-play-server:1.11.11 | ||
//> using dep org.playframework::play-netty-server:3.0.6 | ||
//> using dep com.softwaremill.sttp.client3::core:3.10.2 | ||
//> using dep org.slf4j:slf4j-simple:2.0.16 | ||
|
||
package sttp.tapir.examples.streaming | ||
|
||
import play.core.server.* | ||
import play.api.routing.Router.Routes | ||
import org.apache.pekko.actor.ActorSystem | ||
import org.apache.pekko.stream.Materializer | ||
import sttp.capabilities.pekko.PekkoStreams | ||
import sttp.tapir.server.ServerEndpoint | ||
import sttp.tapir.* | ||
import sttp.tapir.server.play.PlayServerInterpreter | ||
|
||
import scala.concurrent.ExecutionContext.Implicits.global | ||
import scala.concurrent.Future | ||
import sttp.model.{HeaderNames, MediaType, Part, StatusCode} | ||
import sttp.tapir.* | ||
|
||
import scala.concurrent.{ExecutionContext, Future} | ||
import scala.util.* | ||
import org.apache.pekko | ||
import pekko.stream.scaladsl.{Flow, Source, Sink} | ||
import pekko.util.ByteString | ||
import sttp.tapir.server.play.PlayServerOptions | ||
|
||
given ExecutionContext = ExecutionContext.global | ||
|
||
type ErrorInfo = String | ||
|
||
implicit val actorSystem: ActorSystem = ActorSystem("playServer") | ||
|
||
def handleErrors[T](f: Future[T]): Future[Either[ErrorInfo, T]] = | ||
f.transform { | ||
case Success(v) => Success(Right(v)) | ||
case Failure(e) => | ||
println(s"Exception when running endpoint logic: $e") | ||
Success(Left(e.getMessage)) | ||
} | ||
|
||
def logic(s: (Long, Source[ByteString, Any])): Future[String] = { | ||
val (length, stream) = s | ||
println(s"Transmitting $length bytes...") | ||
val result = stream | ||
.runFold(List.empty[ByteString])((acc, byteS) => acc :+ byteS) | ||
.map(_.reduce(_ ++ _).decodeString("UTF-8")) | ||
result.onComplete { | ||
case Failure(ex) => | ||
println(s"Stream failed with exception: $ex" ) | ||
case Success(s) => | ||
println(s"Stream finished: ${s.length}/$length transmitted") | ||
} | ||
result | ||
} | ||
|
||
val e = endpoint.post | ||
.in("chunks") | ||
.in(header[Long](HeaderNames.ContentLength)) | ||
.in(streamTextBody(PekkoStreams)(CodecFormat.TextPlain())) | ||
.out(stringBody) | ||
.errorOut(plainBody[ErrorInfo]) | ||
.serverLogic(logic.andThen(handleErrors)) | ||
|
||
|
||
val routes = PlayServerInterpreter(PlayServerOptions.customiseInterceptors().serverLog(PlayServerOptions.defaultServerLog.logWhenReceived(true) | ||
.logAllDecodeFailures(true)).options).toRoutes(e) | ||
|
||
@main def playServer(): Unit = | ||
import play.api.Configuration | ||
import play.api.Mode | ||
import play.core.server.ServerConfig | ||
|
||
|
||
import java.io.File | ||
import java.util.Properties | ||
|
||
val customConfig = Configuration( | ||
"play.server.http.idleTimeout" -> "75 seconds", | ||
"play.server.https.idleTimeout" -> "75 seconds", | ||
"play.server.https.wantClientAuth" -> false, | ||
"play.server.https.needClientAuth" -> false, | ||
"play.server.netty.server-header" -> null, | ||
"play.server.netty.shutdownQuietPeriod" -> "2 seconds", | ||
"play.server.netty.maxInitialLineLength" -> "4096", | ||
"play.server.netty.maxChunkSize" -> "8192", | ||
"play.server.netty.eventLoopThreads" -> "0", | ||
"play.server.netty.transport" -> "jdk", | ||
"play.server.max-header-size" -> "8k", | ||
"play.server.waitBeforeTermination" -> "0", | ||
"play.server.deferBodyParsing" -> false, | ||
"play.server.websocket.frame.maxLength" -> "64k", | ||
"play.server.websocket.periodic-keep-alive-mode" -> "ping", | ||
"play.server.websocket.periodic-keep-alive-max-idle" -> "infinite", | ||
"play.server.max-content-length" -> "infinite", | ||
"play.server.netty.log.wire" -> true, | ||
"play.server.netty.option.child.SO_KEEPALIVE" -> false, | ||
"play.server.pekko.requestTimeout" -> "5 seconds", | ||
) | ||
val serverConfig = ServerConfig( | ||
rootDir = new File("."), | ||
port = Some(9000), | ||
sslPort = None, | ||
address = "0.0.0.0", | ||
mode = Mode.Dev, | ||
properties = System.getProperties, | ||
configuration = customConfig | ||
) | ||
|
||
NettyServer.fromRouterWithComponents(serverConfig) { components => routes } |
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.
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.
hm well if this test passes, something is wrong - we set the timeout to 1s, so we should never receive a response if it takes 2s to send it? unless the request timeout is for something else?
anyway, this doesn't test the scenario from the test case - where the transmission is interrupted half-way because of connection problems; I don't know if we can simulate this in a test case, but using a timeout is a good approximation. But probably a good way to check if we can at all reproduce the bug is to run: a long-running client sender process; a server process; then
kill -9
the client process when it's half-way sending the data, and seeing on the server if received the incomplete data in the server logicThere 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.
I have given it another try as you suggested. There are playServer and longLastingClient but I don't know what's wrong with that approach. Suggestions are welcome 💡
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.
When you write "I don't know what's wrong with this approach ", do you mean that it works as expected (that is: you run both, interrupt the client brutally after some time, and the server properly closes the connection), or is there something else that's wrong?
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.
I'm trying with the following steps:
$ scala-cli run playServer.scala
$ scala-cli run longLastingClient.scala
$ ps aux | grep longLastingClient | awk '{print $2}' | head -n 1 | xargs kill -9
and nothing new (error/exception/whatever) on server side 🤔
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.
I think the lack of exception/error might be the problem here ;) but first there are two problems in the code:
stream.map(_.length)
, which just creates aSource[Long]
, that is a description of a stream that produces lenghts of received byte-strings (byte chunks). You never run (receive) the stream, and that's where you'd expect to see errors (when the stream is being run)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.
🤦♂️ added pointed adjustments and the result is the following :
killing client
server side
😞
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.
So, I suppose, that's the problem as originally reported?
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.
We can now try to fix it, and/or reproduce using a test :)
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.
So, I suppose that we should return an error with a descriptive message i.e.
java.lang.IllegalStateException: Expected
Content-Length: 10000bytes, but only 800 were written
, right?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.
Yes, since the client interrupted the transmission, I think it's reasonable to expect that the stream will fail? With any exception for a start.