2019-06-03 18:44:43 +01:00
|
|
|
package grpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/client"
|
2019-06-03 18:44:43 +01:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Implements the streamer interface
|
|
|
|
type grpcStream struct {
|
|
|
|
sync.RWMutex
|
2020-01-09 17:00:14 +00:00
|
|
|
closed bool
|
2019-06-11 09:52:35 +01:00
|
|
|
err error
|
|
|
|
conn *grpc.ClientConn
|
|
|
|
stream grpc.ClientStream
|
|
|
|
request client.Request
|
2019-06-08 19:40:44 +01:00
|
|
|
response client.Response
|
2019-06-11 09:52:35 +01:00
|
|
|
context context.Context
|
2020-01-19 22:53:56 +00:00
|
|
|
cancel func()
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Context() context.Context {
|
|
|
|
return g.context
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Request() client.Request {
|
|
|
|
return g.request
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Response() client.Response {
|
2019-06-08 19:40:44 +01:00
|
|
|
return g.response
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Send(msg interface{}) error {
|
|
|
|
if err := g.stream.SendMsg(msg); err != nil {
|
|
|
|
g.setError(err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Recv(msg interface{}) (err error) {
|
|
|
|
defer g.setError(err)
|
|
|
|
if err = g.stream.RecvMsg(msg); err != nil {
|
2019-11-25 22:02:24 +03:00
|
|
|
// #202 - inconsistent gRPC stream behavior
|
|
|
|
// the only way to tell if the stream is done is when we get a EOF on the Recv
|
|
|
|
// here we should close the underlying gRPC ClientConn
|
2020-01-09 17:00:14 +00:00
|
|
|
closeErr := g.Close()
|
2019-11-25 22:02:24 +03:00
|
|
|
if err == io.EOF && closeErr != nil {
|
|
|
|
err = closeErr
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) Error() error {
|
|
|
|
g.RLock()
|
|
|
|
defer g.RUnlock()
|
|
|
|
return g.err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *grpcStream) setError(e error) {
|
|
|
|
g.Lock()
|
|
|
|
g.err = e
|
|
|
|
g.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the gRPC send stream
|
|
|
|
// #202 - inconsistent gRPC stream behavior
|
|
|
|
// The underlying gRPC stream should not be closed here since the
|
|
|
|
// stream should still be able to receive after this function call
|
|
|
|
// TODO: should the conn be closed in another way?
|
|
|
|
func (g *grpcStream) Close() error {
|
2020-01-09 17:00:14 +00:00
|
|
|
g.Lock()
|
|
|
|
defer g.Unlock()
|
|
|
|
|
|
|
|
if g.closed {
|
|
|
|
return nil
|
|
|
|
}
|
2020-01-19 22:53:56 +00:00
|
|
|
// cancel the context
|
|
|
|
g.cancel()
|
2020-01-09 17:00:14 +00:00
|
|
|
g.closed = true
|
|
|
|
g.stream.CloseSend()
|
|
|
|
return g.conn.Close()
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|