aboutsummaryrefslogtreecommitdiff
path: root/weed/messaging/msgclient/sub_chan.go
blob: 213ff46662e683f1d2baf1be91022aa047128b41 (plain)
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
package msgclient

import (
	"context"
	"crypto/md5"
	"hash"
	"io"
	"log"
	"time"

	"github.com/chrislusf/seaweedfs/weed/messaging/broker"
	"github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
)

type SubChannel struct {
	ch      chan []byte
	stream  messaging_pb.SeaweedMessaging_SubscribeClient
	md5hash hash.Hash
	cancel  context.CancelFunc
}

func (mc *MessagingClient) NewSubChannel(subscriberId, chanName string) (*SubChannel, error) {
	tp := broker.TopicPartition{
		Namespace: "chan",
		Topic:     chanName,
		Partition: 0,
	}
	grpcConnection, err := mc.findBroker(tp)
	if err != nil {
		return nil, err
	}
	ctx, cancel := context.WithCancel(context.Background())
	sc, err := setupSubscriberClient(ctx, grpcConnection, tp, subscriberId, time.Unix(0, 0))
	if err != nil {
		return nil, err
	}

	t := &SubChannel{
		ch:      make(chan []byte),
		stream:  sc,
		md5hash: md5.New(),
		cancel:  cancel,
	}

	go func() {
		for {
			resp, subErr := t.stream.Recv()
			if subErr == io.EOF {
				return
			}
			if subErr != nil {
				log.Printf("fail to receive from netchan %s: %v", chanName, subErr)
				return
			}
			if resp.Data == nil {
				// this could be heartbeat from broker
				continue
			}
			if resp.Data.IsClose {
				t.stream.Send(&messaging_pb.SubscriberMessage{
					IsClose: true,
				})
				close(t.ch)
				cancel()
				return
			}
			t.ch <- resp.Data.Value
			t.md5hash.Write(resp.Data.Value)
		}
	}()

	return t, nil
}

func (sc *SubChannel) Channel() chan []byte {
	return sc.ch
}

func (sc *SubChannel) Md5() []byte {
	return sc.md5hash.Sum(nil)
}

func (sc *SubChannel) Cancel() {
	sc.cancel()
}