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