message.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package protocol
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "io/ioutil"
  6. )
  7. // The various compression codec recognized by Kafka in messages.
  8. type CompressionCodec int
  9. const (
  10. COMPRESSION_NONE CompressionCodec = 0
  11. COMPRESSION_GZIP CompressionCodec = 1
  12. COMPRESSION_SNAPPY CompressionCodec = 2
  13. )
  14. // The spec just says: "This is a version id used to allow backwards compatible evolution of the message
  15. // binary format." but it doesn't say what the current value is, so presumably 0...
  16. const message_format int8 = 0
  17. type Message struct {
  18. Codec CompressionCodec // codec used to compress the message contents
  19. Key []byte // the message key, may be nil
  20. Value []byte // the message contents
  21. }
  22. func (m *Message) encode(pe packetEncoder) {
  23. pe.pushCRC32()
  24. pe.putInt8(message_format)
  25. var attributes int8 = 0
  26. attributes |= int8(m.Codec & 0x07)
  27. pe.putInt8(attributes)
  28. pe.putBytes(m.Key)
  29. var body []byte
  30. switch m.Codec {
  31. case COMPRESSION_NONE:
  32. body = m.Value
  33. case COMPRESSION_GZIP:
  34. if m.Value != nil {
  35. var buf bytes.Buffer
  36. writer := gzip.NewWriter(&buf)
  37. writer.Write(m.Value)
  38. writer.Close()
  39. body = buf.Bytes()
  40. }
  41. case COMPRESSION_SNAPPY:
  42. // TODO
  43. }
  44. pe.putBytes(body)
  45. pe.pop()
  46. }
  47. func (m *Message) decode(pd packetDecoder) (err error) {
  48. err = pd.pushCRC32()
  49. if err != nil {
  50. return err
  51. }
  52. format, err := pd.getInt8()
  53. if err != nil {
  54. return err
  55. }
  56. if format != message_format {
  57. return DecodingError("Message format mismatch.")
  58. }
  59. attribute, err := pd.getInt8()
  60. if err != nil {
  61. return err
  62. }
  63. m.Codec = CompressionCodec(attribute & 0x07)
  64. m.Key, err = pd.getBytes()
  65. if err != nil {
  66. return err
  67. }
  68. m.Value, err = pd.getBytes()
  69. if err != nil {
  70. return err
  71. }
  72. switch m.Codec {
  73. case COMPRESSION_NONE:
  74. // nothing to do
  75. case COMPRESSION_GZIP:
  76. if m.Value == nil {
  77. return DecodingError("Nil contents cannot be compressed.")
  78. }
  79. reader, err := gzip.NewReader(bytes.NewReader(m.Value))
  80. if err != nil {
  81. return err
  82. }
  83. m.Value, err = ioutil.ReadAll(reader)
  84. if err != nil {
  85. return err
  86. }
  87. case COMPRESSION_SNAPPY:
  88. // TODO
  89. default:
  90. return DecodingError("Unknown compression codec.")
  91. }
  92. err = pd.pop()
  93. if err != nil {
  94. return err
  95. }
  96. return nil
  97. }