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.

74 lines
2.0 KiB

  1. package agent_client
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/mq/schema"
  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 PublishSession struct {
  12. schema *schema.Schema
  13. partitionCount int
  14. publisherName string
  15. stream grpc.BidiStreamingClient[mq_agent_pb.PublishRecordRequest, mq_agent_pb.PublishRecordResponse]
  16. }
  17. func NewPublishSession(agentAddress string, topicSchema *schema.Schema, partitionCount int, publisherName string) (*PublishSession, error) {
  18. // call local agent grpc server to create a new session
  19. clientConn, err := grpc.NewClient(agentAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
  20. if err != nil {
  21. return nil, fmt.Errorf("dial agent server %s: %v", agentAddress, err)
  22. }
  23. agentClient := mq_agent_pb.NewSeaweedMessagingAgentClient(clientConn)
  24. resp, err := agentClient.StartPublishSession(context.Background(), &mq_agent_pb.StartPublishSessionRequest{
  25. Topic: &schema_pb.Topic{
  26. Namespace: topicSchema.Namespace,
  27. Name: topicSchema.Name,
  28. },
  29. PartitionCount: int32(partitionCount),
  30. RecordType: topicSchema.RecordType,
  31. PublisherName: publisherName,
  32. })
  33. if err != nil {
  34. return nil, err
  35. }
  36. if resp.Error != "" {
  37. return nil, fmt.Errorf("start publish session: %v", resp.Error)
  38. }
  39. stream, err := agentClient.PublishRecord(context.Background())
  40. if err != nil {
  41. return nil, fmt.Errorf("publish record: %v", err)
  42. }
  43. if err = stream.Send(&mq_agent_pb.PublishRecordRequest{
  44. SessionId: resp.SessionId,
  45. }); err != nil {
  46. return nil, fmt.Errorf("send session id: %v", err)
  47. }
  48. return &PublishSession{
  49. schema: topicSchema,
  50. partitionCount: partitionCount,
  51. publisherName: publisherName,
  52. stream: stream,
  53. }, nil
  54. }
  55. func (a *PublishSession) CloseSession() error {
  56. if a.schema == nil {
  57. return nil
  58. }
  59. err := a.stream.CloseSend()
  60. if err != nil {
  61. return fmt.Errorf("close send: %v", err)
  62. }
  63. a.schema = nil
  64. return err
  65. }