scalapb / zio-grpc

ScalaPB meets ZIO: write purely functional gRPC services and clients using ZIO
Apache License 2.0
257 stars 81 forks source link

Add Request Type into Transform trait #608

Open BaekGeunYoung opened 3 months ago

BaekGeunYoung commented 3 months ago

How about adding one more type parameter which stands for the request type, into GTransform? I came up with this idea while thinking how to add request body logging easily.

Let's call this new trait RTransform.

trait RTransform[+ContextIn, -ErrorIn, -ContextOut, +ErrorOut] { self =>
  def effect[Req, Resp](
      io: (Req, ContextIn) => IO[ErrorIn, Resp],
  ): (Req, ContextOut) => IO[ErrorOut, Resp]

  def stream[Req, Resp](
      io: (Req, ContextIn) => ZStream[Any, ErrorIn, Resp],
  ): (Req, ContextOut) => ZStream[Any, ErrorOut, Resp]

  def andThen[ContextIn2 <: ContextOut, ErrorIn2 >: ErrorOut, ContextOut2, ErrorOut2](
      other: RTransform[ContextIn2, ErrorIn2, ContextOut2, ErrorOut2],
  ): RTransform[ContextIn, ErrorIn, ContextOut2, ErrorOut2] =
    new RTransform[ContextIn, ErrorIn, ContextOut2, ErrorOut2] {
      def effect[Req, Resp](
          io: (Req, ContextIn) => ZIO[Any, ErrorIn, Resp],
      ): (Req, ContextOut2) => ZIO[Any, ErrorOut2, Resp] =
        other.effect(self.effect(io))

      def stream[Req, Resp](
          io: (Req, ContextIn) => ZStream[Any, ErrorIn, Resp],
      ): (Req, ContextOut2) => ZStream[Any, ErrorOut2, Resp] =
        other.stream(self.stream(io))
    }

  def compose[ContextIn2, ErrorIn2, ContextOut2 >: ContextIn, ErrorOut2 <: ErrorIn](
      other: RTransform[ContextIn2, ErrorIn2, ContextOut2, ErrorOut2],
  ): RTransform[ContextIn2, ErrorIn2, ContextOut, ErrorOut] = other.andThen(self)
}

I didn't split Request into RequestIn and RequestOut, because I think there would be no any need to transform the content of request itself. (But it could be an option, still.)

And the result of codegen should be like below.

object ZioExampleService {
  trait GExampleService[-Context, +Error] extends scalapb.zio_grpc.GenericGeneratedService[Context, Error, GExampleService] {
    self =>
    def exampleFunction(request: ExampleFunctionRequest, context: Context): _root_.zio.IO[Error, ExampleFunctionResponse]

    // new transform function, using RTransform
    def rTransform[Context1, Error1](f: RTransform[Context, Error, Context1, Error1]): ZioExampleService.GExampleService[Context1, Error1] = new ZioExampleService.GExampleService[Context1, Error1] {
      def exampleFunction(request: ExampleFunctionRequest, context: Context1): _root_.zio.IO[Error1, ExampleFunctionResponse] = f.effect((req, ctx) => self.exampleFunction(req, ctx))(request, context)
    }

    // legacy transform function
    def transform[Context1, Error1](f: GTransform[Context, Error, Context1, Error1]): ZioExampleService.GExampleService[Context1, Error1] = ...
  }

  ...
}