-
Notifications
You must be signed in to change notification settings - Fork 8
/
stream_handler.go
69 lines (60 loc) · 1.69 KB
/
stream_handler.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
package stream_api_accept
import (
"context"
"io"
"github.com/aperturerobotics/bifrost/link"
stream_api "github.com/aperturerobotics/bifrost/stream/api/rpc"
"github.com/aperturerobotics/controllerbus/bus"
"github.com/sirupsen/logrus"
)
// MountedStreamHandler implements the mounted stream handler.
type MountedStreamHandler struct {
// le is the logger entry
le *logrus.Entry
// rpc is the rpc to use
rpc *queuedRPC
// b is the bus
b bus.Bus
}
// NewMountedStreamHandler constructs the mounted stream handler.
func NewMountedStreamHandler(
le *logrus.Entry,
bus bus.Bus,
rpc *queuedRPC,
) (*MountedStreamHandler, error) {
return &MountedStreamHandler{le: le, rpc: rpc, b: bus}, nil
}
// HandleMountedStream handles an incoming mounted stream.
// Any returned error indicates the stream should be closed.
// This function should return as soon as possible, and start
// additional goroutines to manage the lifecycle of the stream.
func (m *MountedStreamHandler) HandleMountedStream(
ctx context.Context,
strm link.MountedStream,
) error {
rpc := m.rpc.rpc
s := strm.GetStream()
_, estLinkInst, err := m.b.AddDirective(
link.NewEstablishLinkWithPeer(strm.GetLink().GetLocalPeer(), strm.GetPeerID()),
nil,
)
if err != nil {
return err
}
go func() {
defer estLinkInst.Release()
if err := rpc.Send(&stream_api.Data{
State: stream_api.StreamState_StreamState_ESTABLISHED,
}); err != nil {
s.Close()
return
}
if err := stream_api.AttachRPCToStream(rpc, s, nil); err != nil &&
err != io.EOF &&
err != context.Canceled {
m.le.WithError(err).Warn("rpc stream returned an error")
}
}()
return nil
}
var _ link.MountedStreamHandler = ((*MountedStreamHandler)(nil))