Git Product home page Git Product logo

grpcmonix's Introduction

Build status Dependencies License GRPCMonixGenerator GRPCMonixRuntime

GRPC Monix

Use Monix's Tasks and Observables to implement your GRPC services instead of Java's StreamObservers.

  • Unary calls return a Task[T] for the response returned by the server
  • Server streaming calls return an Observable[T] for the elements returned by the server
  • Client streaming calls take an Observable[T] for the elements emitted by the client and return a Task[U] for the server response
  • Bidi streaming calls take an Observable[T] for the elements emitted by the client and return an Observable[U] for the elements returned by the server

Installation

You need to enable sbt-protoc plugin to generate source code for the proto definitions. You can do it by adding a protoc.sbt file into your project folder with the following lines:

addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.17")

resolvers += Resolver.bintrayRepo("beyondthelines", "maven")

libraryDependencies ++= Seq(
  "com.thesamet.scalapb" %% "compilerplugin" % "0.7.0",
  "beyondthelines"       %% "grpcmonixgenerator" % "0.0.7"
)

Here we add a dependency to the GRPCMonix protobuf generator.

Then we need to trigger the generation from the build.sbt:

PB.targets in Compile := Seq(
  // compile your proto files into scala source files
  scalapb.gen() -> (sourceManaged in Compile).value,
  // generate the GRPCMonix source code
  grpcmonix.generators.GrpcMonixGenerator() -> (sourceManaged in Compile).value
)

resolvers += Resolver.bintrayRepo("beyondthelines", "maven")

libraryDependencies += "beyondthelines" %% "grpcmonixruntime" % "0.0.7"

Usage

You're now ready to implement your GRPC service using Monix's Tasks and Observables.

To implement your service's business logic you simply extend the GRPC monix generated trait.

E.g. for the RouteGuide service:

class RouteGuideMonixService(features: Seq[Feature]) extends RouteGuideGrpcMonix.RouteGuide {
  // Unary call
  override def getFeature(request: Point): Task[Feature] = ???
  // Server streaming
  override def listFeatures(request: Rectangle): Observable[Feature] = ???
  // Client streaming
  override def recordRoute(points: Observable[Point]): Task[RouteSummary] = ???
  // Bidi streaming
  override def routeChat(notes: Observable[RouteNote]): Observable[RouteNote] = ???
}

The server creation is similar except you need to provide a Monix's Scheduler instead of an ExecutionContext when binding the service

val server = ServerBuilder
  .forPort(8980)
  .addService(
    RouteGuideGrpcMonix.bindService(
      new RouteGuideMonixService(features), // the service implemented above
      monix.execution.Scheduler.global
    )
  )
  .build()    

Tasks and Observables are also available on the client side:

val channel = ManagedChannelBuilder
  .forAddress("localhost", 8980)
  .usePlainText(true)
  .build()

val stub = RouteGuideGrpcMonix.stub(channel) // only an async stub is provided

// Unary call
val feature: Task[Feature] = stub.getFeature(408031728, -748645385)
// Server streaming
val request = Rectangle(
  lo = Some(Point(408031728, -748645385)),
  hi = Some(Point(413700272, -742135189))
)
val features: Observable[Feature] = stub.listFeatures(request)
// Client streaming
val route: Observable[Feature] = Observable
  .fromIterable(features.map(_.getLocation)) 
  .delayOnNext(100.millis)
val summary: Task[RouteSummary] = stub.recordRoute(route)
// Bidi streaming
val notes: Observable[RouteNote] = Observable(
  RouteNote(message = "First message", location = Some(Point(0, 0))),
  RouteNote(message = "Second message", location = Some(Point(0, 1))),
  RouteNote(message = "Third message", location = Some(Point(1, 0))),
  RouteNote(message = "Fourth message", location = Some(Point(1, 1)))
).delayOnNext(1.second)
val allNotes = stub.routeChat(notes)

grpcmonix's People

Contributors

btlines avatar xuwei-k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

grpcmonix's Issues

Build error with ScalaPB 0.8.1

I get a build error when using gRPC Monix with ScalaPB 0.8.1:

❱ sbt clean compile
[info] Loading settings for project global-plugins from idea.sbt ...
[info] Loading global plugins from /Users/shane/.sbt/1.0/plugins
[info] Loading settings for project grpc-monix-sample-build from plugins.sbt ...
[info] Loading project definition from [...]/grpc-monix-sample/project
[info] Updating ProjectRef(uri("file:[...]/grpc-monix-sample/project/"), "grpc-monix-sample-build")...
[info] Done updating.
[warn] There may be incompatibilities among your library dependencies.
[warn] Run 'evicted' to see detailed eviction warnings
[...]/grpc-monix-sample/build.sbt:21: error: Symbol 'type scalapb.compiler.DescriptorPimps' is missing from the classpath.
This symbol is required by 'class grpcmonix.generators.GrpcMonixGenerator'.
Make sure that type DescriptorPimps is in your classpath and check for conflicting dependencies with `-Ylog-classpath`.
A full rebuild may help if 'GrpcMonixGenerator.class' was compiled against an incompatible version of scalapb.compiler.
  grpcmonix.generators.GrpcMonixGenerator() -> (sourceManaged in Compile).value
  ^
[error] Type error in expression
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?

I've attached a minimal project that you can use to reproduce the above:
grpc-monix-minimal.zip

Update to latest Monix version (3.0.x)

It would be nice to update to the version of monix in which this project is depending on. If there is not an actual plan to work on that, I can do it by myself.

bindService should pass ServiceDescriptor to ServerServiceDefinition.builder

The current generated code for bindService calls:

ServerServiceDefinition
  .builder("the.name.of.the.Service")
  ...

While this works, it doesn't register the service in a way that the ProtoReflectionService can see.

The generated code already has a ServiceDescriptor that properly describes the service:

val SERVICE: _root_.io.grpc.ServiceDescriptor = ...

If bindService is changed to call this instead, reflection works:

ServerServiceDefinition
  .builder(SERVICE)
  ...

Setting ScalaPB's `flatPackage` to true causes compilation of generated Scala source to fail

Setting ScalaPB's flatPackage to true causes compilation of generated Scala source to fail:

PB.targets in Compile := Seq(
  scalapb.gen(grpc = true, flatPackage = true) -> (sourceManaged in Compile).value,
  grpcmonix.generators.GrpcMonixGenerator -> (sourceManaged in Compile).value
)

Sample error:

[error] /Users/shane/node/app/target/scala-2.12/src_managed/main/mu/node/api/user/UserGrpcMonix.scala:19: object SignUpRequest is not a member of package mu.node.user
[error]       new Marshaller(mu.node.user.SignUpRequest),
[error]                                            ^

This while compiling a file called user.proto.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.