writesched.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package http2
  5. import "fmt"
  6. // WriteScheduler is the interface implemented by HTTP/2 write schedulers.
  7. // Methods are never called concurrently.
  8. type WriteScheduler interface {
  9. // OpenStream opens a new stream in the write scheduler.
  10. // It is illegal to call this with streamID=0 or with a streamID that is
  11. // already open -- the call may panic.
  12. OpenStream(streamID uint32, options OpenStreamOptions)
  13. // CloseStream closes a stream in the write scheduler. Any frames queued on
  14. // this stream should be discarded. It is illegal to call this on a stream
  15. // that is not open -- the call may panic.
  16. CloseStream(streamID uint32)
  17. // AdjustStream adjusts the priority of the given stream. This may be called
  18. // on a stream that has not yet been opened or has been closed. Note that
  19. // RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
  20. // https://tools.ietf.org/html/rfc7540#section-5.1
  21. AdjustStream(streamID uint32, priority PriorityParam)
  22. // Push queues a frame in the scheduler. In most cases, this will not be
  23. // called with wr.StreamID()!=0 unless that stream is currently open. The one
  24. // exception is RST_STREAM frames, which may be sent on idle or closed streams.
  25. Push(wr FrameWriteRequest)
  26. // Pop dequeues the next frame to write. Returns false if no frames can
  27. // be written. Frames with a given wr.StreamID() are Pop'd in the same
  28. // order they are Push'd, except RST_STREAM frames. No frames should be
  29. // discarded except by CloseStream.
  30. Pop() (wr FrameWriteRequest, ok bool)
  31. }
  32. // OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
  33. type OpenStreamOptions struct {
  34. // PusherID is zero if the stream was initiated by the client. Otherwise,
  35. // PusherID names the stream that pushed the newly opened stream.
  36. PusherID uint32
  37. }
  38. // FrameWriteRequest is a request to write a frame.
  39. type FrameWriteRequest struct {
  40. // write is the interface value that does the writing, once the
  41. // WriteScheduler has selected this frame to write. The write
  42. // functions are all defined in write.go.
  43. write writeFramer
  44. // stream is the stream on which this frame will be written.
  45. // nil for non-stream frames like PING and SETTINGS.
  46. // nil for RST_STREAM streams, which use the StreamError.StreamID field instead.
  47. stream *stream
  48. // done, if non-nil, must be a buffered channel with space for
  49. // 1 message and is sent the return value from write (or an
  50. // earlier error) when the frame has been written.
  51. done chan error
  52. }
  53. // StreamID returns the id of the stream this frame will be written to.
  54. // 0 is used for non-stream frames such as PING and SETTINGS.
  55. func (wr FrameWriteRequest) StreamID() uint32 {
  56. if wr.stream == nil {
  57. if se, ok := wr.write.(StreamError); ok {
  58. // (*serverConn).resetStream doesn't set
  59. // stream because it doesn't necessarily have
  60. // one. So special case this type of write
  61. // message.
  62. return se.StreamID
  63. }
  64. return 0
  65. }
  66. return wr.stream.id
  67. }
  68. // isControl reports whether wr is a control frame for MaxQueuedControlFrames
  69. // purposes. That includes non-stream frames and RST_STREAM frames.
  70. func (wr FrameWriteRequest) isControl() bool {
  71. return wr.stream == nil
  72. }
  73. // DataSize returns the number of flow control bytes that must be consumed
  74. // to write this entire frame. This is 0 for non-DATA frames.
  75. func (wr FrameWriteRequest) DataSize() int {
  76. if wd, ok := wr.write.(*writeData); ok {
  77. return len(wd.p)
  78. }
  79. return 0
  80. }
  81. // Consume consumes min(n, available) bytes from this frame, where available
  82. // is the number of flow control bytes available on the stream. Consume returns
  83. // 0, 1, or 2 frames, where the integer return value gives the number of frames
  84. // returned.
  85. //
  86. // If flow control prevents consuming any bytes, this returns (_, _, 0). If
  87. // the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
  88. // returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
  89. // 'rest' contains the remaining bytes. The consumed bytes are deducted from the
  90. // underlying stream's flow control budget.
  91. func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int) {
  92. var empty FrameWriteRequest
  93. // Non-DATA frames are always consumed whole.
  94. wd, ok := wr.write.(*writeData)
  95. if !ok || len(wd.p) == 0 {
  96. return wr, empty, 1
  97. }
  98. // Might need to split after applying limits.
  99. allowed := wr.stream.flow.available()
  100. if n < allowed {
  101. allowed = n
  102. }
  103. if wr.stream.sc.maxFrameSize < allowed {
  104. allowed = wr.stream.sc.maxFrameSize
  105. }
  106. if allowed <= 0 {
  107. return empty, empty, 0
  108. }
  109. if len(wd.p) > int(allowed) {
  110. wr.stream.flow.take(allowed)
  111. consumed := FrameWriteRequest{
  112. stream: wr.stream,
  113. write: &writeData{
  114. streamID: wd.streamID,
  115. p: wd.p[:allowed],
  116. // Even if the original had endStream set, there
  117. // are bytes remaining because len(wd.p) > allowed,
  118. // so we know endStream is false.
  119. endStream: false,
  120. },
  121. // Our caller is blocking on the final DATA frame, not
  122. // this intermediate frame, so no need to wait.
  123. done: nil,
  124. }
  125. rest := FrameWriteRequest{
  126. stream: wr.stream,
  127. write: &writeData{
  128. streamID: wd.streamID,
  129. p: wd.p[allowed:],
  130. endStream: wd.endStream,
  131. },
  132. done: wr.done,
  133. }
  134. return consumed, rest, 2
  135. }
  136. // The frame is consumed whole.
  137. // NB: This cast cannot overflow because allowed is <= math.MaxInt32.
  138. wr.stream.flow.take(int32(len(wd.p)))
  139. return wr, empty, 1
  140. }
  141. // String is for debugging only.
  142. func (wr FrameWriteRequest) String() string {
  143. var des string
  144. if s, ok := wr.write.(fmt.Stringer); ok {
  145. des = s.String()
  146. } else {
  147. des = fmt.Sprintf("%T", wr.write)
  148. }
  149. return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
  150. }
  151. // replyToWriter sends err to wr.done and panics if the send must block
  152. // This does nothing if wr.done is nil.
  153. func (wr *FrameWriteRequest) replyToWriter(err error) {
  154. if wr.done == nil {
  155. return
  156. }
  157. select {
  158. case wr.done <- err:
  159. default:
  160. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
  161. }
  162. wr.write = nil // prevent use (assume it's tainted after wr.done send)
  163. }
  164. // writeQueue is used by implementations of WriteScheduler.
  165. type writeQueue struct {
  166. s []FrameWriteRequest
  167. prev, next *writeQueue
  168. }
  169. func (q *writeQueue) empty() bool { return len(q.s) == 0 }
  170. func (q *writeQueue) push(wr FrameWriteRequest) {
  171. q.s = append(q.s, wr)
  172. }
  173. func (q *writeQueue) shift() FrameWriteRequest {
  174. if len(q.s) == 0 {
  175. panic("invalid use of queue")
  176. }
  177. wr := q.s[0]
  178. // TODO: less copy-happy queue.
  179. copy(q.s, q.s[1:])
  180. q.s[len(q.s)-1] = FrameWriteRequest{}
  181. q.s = q.s[:len(q.s)-1]
  182. return wr
  183. }
  184. // consume consumes up to n bytes from q.s[0]. If the frame is
  185. // entirely consumed, it is removed from the queue. If the frame
  186. // is partially consumed, the frame is kept with the consumed
  187. // bytes removed. Returns true iff any bytes were consumed.
  188. func (q *writeQueue) consume(n int32) (FrameWriteRequest, bool) {
  189. if len(q.s) == 0 {
  190. return FrameWriteRequest{}, false
  191. }
  192. consumed, rest, numresult := q.s[0].Consume(n)
  193. switch numresult {
  194. case 0:
  195. return FrameWriteRequest{}, false
  196. case 1:
  197. q.shift()
  198. case 2:
  199. q.s[0] = rest
  200. }
  201. return consumed, true
  202. }
  203. type writeQueuePool []*writeQueue
  204. // put inserts an unused writeQueue into the pool.
  205. func (p *writeQueuePool) put(q *writeQueue) {
  206. for i := range q.s {
  207. q.s[i] = FrameWriteRequest{}
  208. }
  209. q.s = q.s[:0]
  210. *p = append(*p, q)
  211. }
  212. // get returns an empty writeQueue.
  213. func (p *writeQueuePool) get() *writeQueue {
  214. ln := len(*p)
  215. if ln == 0 {
  216. return new(writeQueue)
  217. }
  218. x := ln - 1
  219. q := (*p)[x]
  220. (*p)[x] = nil
  221. *p = (*p)[:x]
  222. return q
  223. }