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

Experiment faster stateful implement #493

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 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
22 changes: 4 additions & 18 deletions runtime/src/main/scala/fs2/grpc/server/Fs2ServerCallHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package fs2
package grpc
package server

import cats.syntax.all._
import cats.effect._
import cats.effect.std.Dispatcher
import io.grpc._
Expand All @@ -35,26 +34,13 @@ class Fs2ServerCallHandler[F[_]: Async] private (

def unaryToUnaryCall[Request, Response](
implementation: (Request, Metadata) => F[Response]
): ServerCallHandler[Request, Response] = new ServerCallHandler[Request, Response] {
def startCall(call: ServerCall[Request, Response], headers: Metadata): ServerCall.Listener[Request] = {
val listener = dispatcher.unsafeRunSync(Fs2UnaryServerCallListener[F](call, dispatcher, options))
listener.unsafeUnaryResponse(new Metadata(), _ flatMap { request => implementation(request, headers) })
listener
}
}
): ServerCallHandler[Request, Response] =
ImpureUnaryServerCall.unary(implementation, options, dispatcher)

def unaryToStreamingCall[Request, Response](
implementation: (Request, Metadata) => Stream[F, Response]
): ServerCallHandler[Request, Response] = new ServerCallHandler[Request, Response] {
def startCall(call: ServerCall[Request, Response], headers: Metadata): ServerCall.Listener[Request] = {
val listener = dispatcher.unsafeRunSync(Fs2UnaryServerCallListener[F](call, dispatcher, options))
listener.unsafeStreamResponse(
new Metadata(),
v => Stream.eval(v) flatMap { request => implementation(request, headers) }
)
listener
}
}
): ServerCallHandler[Request, Response] =
ImpureUnaryServerCall.stream(implementation, options, dispatcher)

def streamingToUnaryCall[Request, Response](
implementation: (Stream[F, Request], Metadata) => F[Response]
Expand Down
163 changes: 163 additions & 0 deletions runtime/src/main/scala/fs2/grpc/server/ImpureUnaryServerCall.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* Copyright (c) 2018 Gary Coady / Fs2 Grpc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package fs2
package grpc
package server

import cats.effect.Async
import cats.effect.Sync
import cats.effect.kernel.Outcome
import cats.effect.std.Dispatcher
import fs2.grpc.server.ImpureUnaryServerCall.Cancel
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.Status
import io.grpc.StatusException
import io.grpc.StatusRuntimeException

object ImpureUnaryServerCall {
type Cancel = () => Any
private val Noop: Cancel = () => ()
private val Closed: Cancel = () => ()

private def tooManyRequests =
Status.INTERNAL.withDescription("Too many requests").asRuntimeException

def mkListener[Request, Response](
run: Request => Cancel,
call: ServerCall[Request, Response]
): ServerCall.Listener[Request] =
new ServerCall.Listener[Request] {

private var request: Request = _
private var cancel: Cancel = Noop

override def onCancel(): Unit =
cancel()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be blocked until cancellation is completed?


override def onMessage(message: Request): Unit =
if (request == null) {
request = message
} else if (cancel eq Noop) {
earlyClose(Status.INTERNAL.withDescription("Too many requests"))
}

override def onHalfClose(): Unit =
if (cancel eq Noop) {
if (request == null) {
earlyClose(Status.INTERNAL.withDescription("Half-closed without a request"))
} else {
cancel = run(request)
}
}

private def earlyClose(status: Status): Unit = {
cancel = Closed
call.close(status, new Metadata())
}
}

def unary[F[_]: Async, Request, Response](
impl: (Request, Metadata) => F[Response],
options: ServerOptions,
dispatcher: Dispatcher[F]
): ServerCallHandler[Request, Response] =
new ServerCallHandler[Request, Response] {
private val opt = options.callOptionsFn(ServerCallOptions.default)

def startCall(call: ServerCall[Request, Response], headers: Metadata): ServerCall.Listener[Request] = {
val responder = ImpureResponder.setup(opt, call, dispatcher)
call.request(2)
mkListener[Request, Response](req => responder.unary(impl(req, headers)), call)
}
}

def stream[F[_]: Async, Request, Response](
impl: (Request, Metadata) => fs2.Stream[F, Response],
options: ServerOptions,
dispatcher: Dispatcher[F]
): ServerCallHandler[Request, Response] =
new ServerCallHandler[Request, Response] {
private val opt = options.callOptionsFn(ServerCallOptions.default)

def startCall(call: ServerCall[Request, Response], headers: Metadata): ServerCall.Listener[Request] = {
val responder = ImpureResponder.setup(opt, call, dispatcher)
call.request(2)
mkListener[Request, Response](req => responder.stream(impl(req, headers)), call)
}
}
}

final class ImpureResponder[F[_], Request, Response](
val call: ServerCall[Request, Response],
dispatcher: Dispatcher[F]
) {

def stream(response: fs2.Stream[F, Response])(implicit F: Sync[F]): Cancel =
dispatcher.unsafeRunCancelable(handleOutcome(response.map(sendMessage).compile.drain))

def unary(response: F[Response])(implicit F: Sync[F]): Cancel =
dispatcher.unsafeRunCancelable(handleOutcome(F.map(response)(sendMessage)))

private var sentHeader: Boolean = false

private def sendMessage(message: Response): Unit =
if (!sentHeader) {
sentHeader = true
call.sendHeaders(new Metadata())
call.sendMessage(message)
} else {
call.sendMessage(message)
}

private def handleOutcome(completed: F[Unit])(implicit F: Sync[F]): F[Unit] = {
F.guaranteeCase(completed) {
case Outcome.Succeeded(_) => closeStream(Status.OK, new Metadata())
case Outcome.Errored(e) =>
e match {
case ex: StatusException =>
closeStream(ex.getStatus, Option(ex.getTrailers).getOrElse(new Metadata()))
case ex: StatusRuntimeException =>
closeStream(ex.getStatus, Option(ex.getTrailers).getOrElse(new Metadata()))
case ex =>
closeStream(Status.INTERNAL.withDescription(ex.getMessage).withCause(ex), new Metadata())
}
case Outcome.Canceled() => closeStream(Status.CANCELLED, new Metadata())
}
}

private def closeStream(status: Status, metadata: Metadata)(implicit F: Sync[F]): F[Unit] =
F.delay(call.close(status, metadata))
}

object ImpureResponder {
def setup[F[_], I, O](
options: ServerCallOptions,
call: ServerCall[I, O],
dispatcher: Dispatcher[F]
): ImpureResponder[F, I, O] = {
call.setMessageCompression(options.messageCompression)
options.compressor.map(_.name).foreach(call.setCompression)
new ImpureResponder[F, I, O](call, dispatcher)
}
}