You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.1 KiB

1 week ago
  1. package agent_client
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/mq/topic"
  6. "github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
  7. "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/credentials/insecure"
  10. )
  11. type SubscribeOption struct {
  12. ConsumerGroup string
  13. ConsumerGroupInstanceId string
  14. Topic topic.Topic
  15. Filter string
  16. MaxSubscribedPartitions int32
  17. PerPartitionConcurrency int32
  18. }
  19. type SubscribeSession struct {
  20. Option *SubscribeOption
  21. stream grpc.BidiStreamingClient[mq_agent_pb.SubscribeRecordRequest, mq_agent_pb.SubscribeRecordResponse]
  22. }
  23. func NewSubscribeSession(agentAddress string, option *SubscribeOption) (*SubscribeSession, error) {
  24. // call local agent grpc server to create a new session
  25. clientConn, err := grpc.NewClient(agentAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
  26. if err != nil {
  27. return nil, fmt.Errorf("dial agent server %s: %v", agentAddress, err)
  28. }
  29. agentClient := mq_agent_pb.NewSeaweedMessagingAgentClient(clientConn)
  30. resp, err := agentClient.StartSubscribeSession(context.Background(), &mq_agent_pb.StartSubscribeSessionRequest{
  31. ConsumerGroup: option.ConsumerGroup,
  32. ConsumerGroupInstanceId: option.ConsumerGroupInstanceId,
  33. Topic: &schema_pb.Topic{
  34. Namespace: option.Topic.Namespace,
  35. Name: option.Topic.Name,
  36. },
  37. MaxSubscribedPartitions: option.MaxSubscribedPartitions,
  38. Filter: option.Filter,
  39. })
  40. if err != nil {
  41. return nil, err
  42. }
  43. if resp.Error != "" {
  44. return nil, fmt.Errorf("start subscribe session: %v", resp.Error)
  45. }
  46. stream, err := agentClient.SubscribeRecord(context.Background())
  47. if err != nil {
  48. return nil, fmt.Errorf("subscribe record: %v", err)
  49. }
  50. if err = stream.Send(&mq_agent_pb.SubscribeRecordRequest{
  51. SessionId: resp.SessionId,
  52. }); err != nil {
  53. return nil, fmt.Errorf("send session id: %v", err)
  54. }
  55. return &SubscribeSession{
  56. Option: option,
  57. stream: stream,
  58. }, nil
  59. }
  60. func (s *SubscribeSession) CloseSession() error {
  61. err := s.stream.CloseSend()
  62. return err
  63. }