aboutsummaryrefslogtreecommitdiff
path: root/weed/messaging/msgclient/pub_chan.go
blob: 9bc88f7c08eab3beb640603358d58f58d37a7d8f (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
package msgclient

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

	"google.golang.org/grpc"

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

type PubChannel struct {
	client         messaging_pb.SeaweedMessaging_PublishClient
	grpcConnection *grpc.ClientConn
	md5hash        hash.Hash
}

func (mc *MessagingClient) NewPubChannel(chanName string) (*PubChannel, error) {
	tp := broker.TopicPartition{
		Namespace: "chan",
		Topic:     chanName,
		Partition: 0,
	}
	grpcConnection, err := mc.findBroker(tp)
	if err != nil {
		return nil, err
	}
	pc, err := setupPublisherClient(grpcConnection, tp)
	if err != nil {
		return nil, err
	}
	return &PubChannel{
		client:         pc,
		grpcConnection: grpcConnection,
		md5hash:        md5.New(),
	}, nil
}

func (pc *PubChannel) Publish(m []byte) error {
	err := pc.client.Send(&messaging_pb.PublishRequest{
		Data: &messaging_pb.Message{
			Value: m,
		},
	})
	if err == nil {
		pc.md5hash.Write(m)
	}
	return err
}
func (pc *PubChannel) Close() error {

	// println("send closing")
	if err := pc.client.Send(&messaging_pb.PublishRequest{
		Data: &messaging_pb.Message{
			IsClose: true,
		},
	}); err != nil {
		log.Printf("err send close: %v", err)
	}
	// println("receive closing")
	if _, err := pc.client.Recv(); err != nil && err != io.EOF {
		log.Printf("err receive close: %v", err)
	}
	// println("close connection")
	if err := pc.grpcConnection.Close(); err != nil {
		log.Printf("err connection close: %v", err)
	}
	return nil
}

func (pc *PubChannel) Md5() []byte {
	return pc.md5hash.Sum(nil)
}