publish.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package pub_client
  2. import (
  3. "fmt"
  4. "github.com/golang/protobuf/proto"
  5. "github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
  6. "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
  7. "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
  8. "github.com/seaweedfs/seaweedfs/weed/util"
  9. "time"
  10. )
  11. func (p *TopicPublisher) Publish(key, value []byte) error {
  12. if p.config.RecordType != nil {
  13. return fmt.Errorf("record type is set, use PublishRecord instead")
  14. }
  15. return p.doPublish(key, value)
  16. }
  17. func (p *TopicPublisher) doPublish(key, value []byte) error {
  18. hashKey := util.HashToInt32(key) % pub_balancer.MaxPartitionCount
  19. if hashKey < 0 {
  20. hashKey = -hashKey
  21. }
  22. inputBuffer, found := p.partition2Buffer.Floor(hashKey+1, hashKey+1)
  23. if !found {
  24. return fmt.Errorf("no input buffer found for key %d", hashKey)
  25. }
  26. return inputBuffer.Enqueue(&mq_pb.DataMessage{
  27. Key: key,
  28. Value: value,
  29. TsNs: time.Now().UnixNano(),
  30. })
  31. }
  32. func (p *TopicPublisher) PublishRecord(key []byte, recordValue *schema_pb.RecordValue) error {
  33. // serialize record value
  34. value, err := proto.Marshal(recordValue)
  35. if err != nil {
  36. return fmt.Errorf("failed to marshal record value: %v", err)
  37. }
  38. return p.doPublish(key, value)
  39. }
  40. func (p *TopicPublisher) FinishPublish() error {
  41. if inputBuffers, found := p.partition2Buffer.AllIntersections(0, pub_balancer.MaxPartitionCount); found {
  42. for _, inputBuffer := range inputBuffers {
  43. inputBuffer.Enqueue(&mq_pb.DataMessage{
  44. TsNs: time.Now().UnixNano(),
  45. Ctrl: &mq_pb.ControlMessage{
  46. IsClose: true,
  47. PublisherName: p.config.PublisherName,
  48. },
  49. })
  50. }
  51. }
  52. return nil
  53. }