framer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package framer implements simple frame decoding techniques for an io.ReadCloser
  14. package framer
  15. import (
  16. "encoding/binary"
  17. "encoding/json"
  18. "io"
  19. )
  20. type lengthDelimitedFrameWriter struct {
  21. w io.Writer
  22. h [4]byte
  23. }
  24. func NewLengthDelimitedFrameWriter(w io.Writer) io.Writer {
  25. return &lengthDelimitedFrameWriter{w: w}
  26. }
  27. // Write writes a single frame to the nested writer, prepending it with the length in
  28. // in bytes of data (as a 4 byte, bigendian uint32).
  29. func (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error) {
  30. binary.BigEndian.PutUint32(w.h[:], uint32(len(data)))
  31. n, err := w.w.Write(w.h[:])
  32. if err != nil {
  33. return 0, err
  34. }
  35. if n != len(w.h) {
  36. return 0, io.ErrShortWrite
  37. }
  38. return w.w.Write(data)
  39. }
  40. type lengthDelimitedFrameReader struct {
  41. r io.ReadCloser
  42. remaining int
  43. }
  44. // NewLengthDelimitedFrameReader returns an io.Reader that will decode length-prefixed
  45. // frames off of a stream.
  46. //
  47. // The protocol is:
  48. //
  49. // stream: message ...
  50. // message: prefix body
  51. // prefix: 4 byte uint32 in BigEndian order, denotes length of body
  52. // body: bytes (0..prefix)
  53. //
  54. // If the buffer passed to Read is not long enough to contain an entire frame, io.ErrShortRead
  55. // will be returned along with the number of bytes read.
  56. func NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser {
  57. return &lengthDelimitedFrameReader{r: r}
  58. }
  59. // Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer
  60. // is returned and subsequent calls will attempt to read the last frame. A frame is complete when
  61. // err is nil.
  62. func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {
  63. if r.remaining <= 0 {
  64. header := [4]byte{}
  65. n, err := io.ReadAtLeast(r.r, header[:4], 4)
  66. if err != nil {
  67. return 0, err
  68. }
  69. if n != 4 {
  70. return 0, io.ErrUnexpectedEOF
  71. }
  72. frameLength := int(binary.BigEndian.Uint32(header[:]))
  73. r.remaining = frameLength
  74. }
  75. expect := r.remaining
  76. max := expect
  77. if max > len(data) {
  78. max = len(data)
  79. }
  80. n, err := io.ReadAtLeast(r.r, data[:max], int(max))
  81. r.remaining -= n
  82. if err == io.ErrShortBuffer || r.remaining > 0 {
  83. return n, io.ErrShortBuffer
  84. }
  85. if err != nil {
  86. return n, err
  87. }
  88. if n != expect {
  89. return n, io.ErrUnexpectedEOF
  90. }
  91. return n, nil
  92. }
  93. func (r *lengthDelimitedFrameReader) Close() error {
  94. return r.r.Close()
  95. }
  96. type jsonFrameReader struct {
  97. r io.ReadCloser
  98. decoder *json.Decoder
  99. remaining []byte
  100. }
  101. // NewJSONFramedReader returns an io.Reader that will decode individual JSON objects off
  102. // of a wire.
  103. //
  104. // The boundaries between each frame are valid JSON objects. A JSON parsing error will terminate
  105. // the read.
  106. func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser {
  107. return &jsonFrameReader{
  108. r: r,
  109. decoder: json.NewDecoder(r),
  110. }
  111. }
  112. // ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
  113. // byte slice will be modified the next time ReadFrame is invoked and should not be altered.
  114. func (r *jsonFrameReader) Read(data []byte) (int, error) {
  115. // Return whatever remaining data exists from an in progress frame
  116. if n := len(r.remaining); n > 0 {
  117. if n <= len(data) {
  118. data = append(data[0:0], r.remaining...)
  119. r.remaining = nil
  120. return n, nil
  121. }
  122. n = len(data)
  123. data = append(data[0:0], r.remaining[:n]...)
  124. r.remaining = r.remaining[n:]
  125. return n, io.ErrShortBuffer
  126. }
  127. // RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
  128. // data written to data, or be larger than data and a different array.
  129. n := len(data)
  130. m := json.RawMessage(data[:0])
  131. if err := r.decoder.Decode(&m); err != nil {
  132. return 0, err
  133. }
  134. // If capacity of data is less than length of the message, decoder will allocate a new slice
  135. // and set m to it, which means we need to copy the partial result back into data and preserve
  136. // the remaining result for subsequent reads.
  137. if len(m) > n {
  138. data = append(data[0:0], m[:n]...)
  139. r.remaining = m[n:]
  140. return n, io.ErrShortBuffer
  141. }
  142. return len(m), nil
  143. }
  144. func (r *jsonFrameReader) Close() error {
  145. return r.r.Close()
  146. }