writesched.go 7.5 KB

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