forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
96 lines (78 loc) · 1.4 KB
/
stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package grpc
import (
"io"
"sync"
"github.com/micro/go-micro/client"
"google.golang.org/grpc"
"golang.org/x/net/context"
)
// Implements the streamer interface
type grpcStream struct {
sync.RWMutex
seq uint64
closed chan bool
err error
conn *grpc.ClientConn
request client.Request
stream grpc.ClientStream
context context.Context
}
func (g *grpcStream) isClosed() bool {
select {
case <-g.closed:
return true
default:
return false
}
}
func (g *grpcStream) Context() context.Context {
return g.context
}
func (g *grpcStream) Request() client.Request {
return g.request
}
func (g *grpcStream) Send(msg interface{}) error {
g.Lock()
defer g.Unlock()
if g.isClosed() {
g.err = errShutdown
return errShutdown
}
if err := g.stream.SendMsg(msg); err != nil {
g.err = err
return err
}
return nil
}
func (g *grpcStream) Recv(msg interface{}) error {
g.Lock()
defer g.Unlock()
if g.isClosed() {
g.err = errShutdown
return errShutdown
}
if err := g.stream.RecvMsg(msg); err != nil {
if err == io.EOF && !g.isClosed() {
g.err = io.ErrUnexpectedEOF
return io.ErrUnexpectedEOF
}
g.err = err
return err
}
return nil
}
func (g *grpcStream) Error() error {
g.RLock()
defer g.RUnlock()
return g.err
}
func (g *grpcStream) Close() error {
select {
case <-g.closed:
return nil
default:
close(g.closed)
g.stream.CloseSend()
return g.conn.Close()
}
}