1. 程式人生 > 其它 >傳送擴充套件幀的幀id錯誤_Go發起HTTP2.0請求流程分析(中篇)——資料幀&流控制

傳送擴充套件幀的幀id錯誤_Go發起HTTP2.0請求流程分析(中篇)——資料幀&流控制

技術標籤:傳送擴充套件幀的幀id錯誤

閱讀建議

這是HTTP2.0系列的第二篇,所以筆者推薦閱讀順序如下:

  1. Go中的HTTP請求之——HTTP1.1請求流程分析

  2. Go發起HTTP2.0請求流程分析(前篇)

本篇主要分為三個部分:資料幀,流控制器以及通過分析原始碼逐步瞭解流控制。

本有意將這三個部分拆成三篇文章,但它們之間又有聯絡,所以最後依舊決定放在一篇文章裡面。由於內容較多,筆者認為分三次分別閱讀三個部分較佳。

資料幀

HTTP2通訊的最小單位是資料幀,每一個幀都包含兩部分:幀頭和Payload。不同資料流的幀可以交錯傳送(同一個資料流的幀必須順序傳送),然後再根據每個幀頭的資料流識別符號重新組裝。

由於Payload中為有效資料,故僅對幀頭進行分析描述。

幀頭

幀頭總長度為9個位元組,幷包含四個部分,分別是:

  1. Payload的長度,佔用三個位元組。

  2. 資料幀型別,佔用一個位元組。

  3. 資料幀識別符號,佔用一個位元組。

  4. 資料流ID,佔用四個位元組。

用圖表示如下:

7cdde369d5c65dc29b14d6c00b75ebb8.png

資料幀的格式和各部分的含義已經清楚了, 那麼我們看看程式碼中怎麼讀取一個幀頭:

func http2readFrameHeader(buf []byte, r io.Reader) (http2FrameHeader, error) {
_, err := io.ReadFull(r, buf[:http2frameHeaderLen])
if err != nil {
return http2FrameHeader{}, err
}
return http2FrameHeader{
Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
Type: http2FrameType(buf[3]),
Flags: http2Flags(buf[4]),
StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
valid: true,
}, nil
}

在上面的程式碼中http2frameHeaderLen是一個常量,其值為9。

從io.Reader中讀取9個位元組後,將前三個位元組和後四個位元組均轉為uint32的型別,從而得到Payload長度和資料流ID。另外需要理解的是幀頭的前三個位元組和後四個位元組儲存格式為大端(大小端筆者就不在這裡解釋了,請尚不瞭解的讀者自行百度)。

資料幀型別

根據http://http2.github.io/http2-spec/#rfc.section.11.2描述,資料幀型別總共有10個。在go原始碼中均有體現:

const (
http2FrameData http2FrameType = 0x0
http2FrameHeaders http2FrameType = 0x1
http2FramePriority http2FrameType = 0x2
http2FrameRSTStream http2FrameType = 0x3
http2FrameSettings http2FrameType = 0x4
http2FramePushPromise http2FrameType = 0x5
http2FramePing http2FrameType = 0x6
http2FrameGoAway http2FrameType = 0x7
http2FrameWindowUpdate http2FrameType = 0x8
http2FrameContinuation http2FrameType = 0x9
)

http2FrameData:主要用於傳送請求body和接收響應的資料幀。

http2FrameHeaders:主要用於傳送請求header和接收響應header的資料幀。

http2FrameSettings:主要用於client和server交流設定相關的資料幀。

http2FrameWindowUpdate:主要用於流控制的資料幀。

其他資料幀型別因為本文不涉及,故不做描述。

資料幀識別符號

由於資料幀識別符號種類較多,筆者在這裡僅介紹其中部分識別符號,先看原始碼:

const (
// Data Frame
http2FlagDataEndStream http2Flags = 0x1

// Headers Frame
http2FlagHeadersEndStream http2Flags = 0x1

// Settings Frame
http2FlagSettingsAck http2Flags = 0x1
// 此處省略定義其他資料幀識別符號的程式碼
)

http2FlagDataEndStream:在前篇中提到,呼叫(*http2ClientConn).newStream方法會建立一個數據流,那這個資料流什麼時候結束呢,這就是http2FlagDataEndStream的作用。

當client收到有響應body的響應時(HEAD請求無響應body,301,302等響應也無響應body),一直讀到http2FrameData資料幀的識別符號為http2FlagDataEndStream則意味著本次請求結束可以關閉當前資料流。

http2FlagHeadersEndStream:如果讀到的http2FrameHeaders資料幀有此識別符號也意味著本次請求結束。

http2FlagSettingsAck:該標示符意味著對方確認收到http2FrameSettings資料幀。

流控制器

流控制是一種阻止傳送方向接收方傳送大量資料的機制,以免超出後者的需求或處理能力。Go中HTTP2通過http2flow結構體進行流控制:

type http2flow struct {
// n is the number of DATA bytes we're allowed to send.
// A flow is kept both on a conn and a per-stream.
n int32

// conn points to the shared connection-level flow that is
// shared by all streams on that conn. It is nil for the flow
// that's on the conn directly.
conn *http2flow
}

欄位含義英文註釋已經描述的很清楚了,所以筆者不再翻譯。下面看一下和流控制有關的方法。

(*http2flow).available

此方法返回當前流控制可傳送的最大位元組數:

func (f *http2flow) available() int32 {
n := f.n
if f.conn != nil && f.conn.n < n {
n = f.conn.n
}
return n
}
  • 如果f.conn為nil則意味著此控制器的控制級別為連線,那麼可傳送的最大位元組數就是f.n

  • 如果f.conn不為nil則意味著此控制器的控制級別為資料流,且當前資料流可傳送的最大位元組數不能超過當前連線可傳送的最大位元組數。

(*http2flow).take

此方法用於消耗當前流控制器的可傳送位元組數:

func (f *http2flow) take(n int32) {
if n > f.available() {
panic("internal error: took too much")
}
f.n -= n
if f.conn != nil {
f.conn.n -= n
}
}

通過實際需要傳遞一個引數,告知當前流控制器想要傳送的資料大小。如果傳送的大小超過流控制器允許的大小,則panic,如果未超過流控制器允許的大小,則將當前資料流和當前連線的可傳送位元組數-n

(*http2flow).add

有消耗就有新增,此方法用於增加流控制器可傳送的最大位元組數:

func (f *http2flow) add(n int32) bool {
sum := f.n + n
if (sum > n) == (f.n > 0) {
f.n = sum
return true
}
return false
}

上面的程式碼唯一需要注意的地方是,當sum超過int32正數最大值(2^31-1)時會返回false。

回顧:在前篇中提到的(*http2Transport).NewClientConn方法和(*http2ClientConn).newStream方法均通過(*http2flow).add初始化可傳送資料視窗大小。

有了幀和流控制器的基本概念,下面我們結合原始碼來分析總結流控制的具體實現。

(*http2ClientConn).readLoop

前篇分析(*http2Transport).newClientConn時止步於讀迴圈,那麼今天我們就從(*http2ClientConn).readLoop開始。

func (cc *http2ClientConn) readLoop() {
rl := &http2clientConnReadLoop{cc: cc}
defer rl.cleanup()
cc.readerErr = rl.run()
if ce, ok := cc.readerErr.(http2ConnectionError); ok {
cc.wmu.Lock()
cc.fr.WriteGoAway(0, http2ErrCode(ce), nil)
cc.wmu.Unlock()
}
}

由上可知,readLoop的邏輯比較簡單,其核心邏輯在(*http2clientConnReadLoop).run方法裡。

func (rl *http2clientConnReadLoop) run() error {
cc := rl.cc
rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
gotReply := false // ever saw a HEADERS reply
gotSettings := false
for {
f, err := cc.fr.ReadFrame()
// 此處省略程式碼
maybeIdle := false // whether frame might transition us to idle

switch f := f.(type) {
case *http2MetaHeadersFrame:
err = rl.processHeaders(f)
maybeIdle = true
gotReply = true
case *http2DataFrame:
err = rl.processData(f)
maybeIdle = true
case *http2GoAwayFrame:
err = rl.processGoAway(f)
maybeIdle = true
case *http2RSTStreamFrame:
err = rl.processResetStream(f)
maybeIdle = true
case *http2SettingsFrame:
err = rl.processSettings(f)
case *http2PushPromiseFrame:
err = rl.processPushPromise(f)
case *http2WindowUpdateFrame:
err = rl.processWindowUpdate(f)
case *http2PingFrame:
err = rl.processPing(f)
default:
cc.logf("Transport: unhandled response frame type %T", f)
}
if err != nil {
if http2VerboseLogs {
cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, http2summarizeFrame(f), err)
}
return err
}
if rl.closeWhenIdle && gotReply && maybeIdle {
cc.closeIfIdle()
}
}
}

由上可知,(*http2clientConnReadLoop).run的核心邏輯是讀取資料幀然後對不同的資料幀進行不同的處理。

cc.fr.ReadFrame()會根據前面介紹的資料幀格式讀出資料幀。

前篇中提到使用了一個支援h2協議的圖片進行分析,本篇繼續複用該圖片對(*http2clientConnReadLoop).run方法進行debug。

收到http2FrameSettings資料幀

讀迴圈會最先讀到http2FrameSettings資料幀。讀到該資料幀後會呼叫(*http2clientConnReadLoop).processSettings方法。(*http2clientConnReadLoop).processSettings主要包含3個邏輯。

1、判斷是否是http2FrameSettings的ack資訊,如果是直接返回,否則繼續後面的步驟。

if f.IsAck() {
if cc.wantSettingsAck {
cc.wantSettingsAck = false
return nil
}
return http2ConnectionError(http2ErrCodeProtocol)
}

2、處理不同http2FrameSettings的資料幀,並根據server傳遞的資訊,修改maxConcurrentStreams等的值。

err := f.ForeachSetting(func(s http2Setting) error {
switch s.ID {
case http2SettingMaxFrameSize:
cc.maxFrameSize = s.Val
case http2SettingMaxConcurrentStreams:
cc.maxConcurrentStreams = s.Val
case http2SettingMaxHeaderListSize:
cc.peerMaxHeaderListSize = uint64(s.Val)
case http2SettingInitialWindowSize:
if s.Val > math.MaxInt32 {
return http2ConnectionError(http2ErrCodeFlowControl)
}
delta := int32(s.Val) - int32(cc.initialWindowSize)
for _, cs := range cc.streams {
cs.flow.add(delta)
}
cc.cond.Broadcast()
cc.initialWindowSize = s.Val
default:
// TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
cc.vlogf("Unhandled Setting: %v", s)
}
return nil
})

當收到ID為http2SettingInitialWindowSize的幀時,會調整當前連線中所有資料流的可傳送資料視窗大小,並修改當前連線的initialWindowSize(每個新建立的資料流均會使用該值初始化可傳送資料視窗大小)為s.Val

3、傳送http2FrameSettings的ack資訊給server。

	cc.wmu.Lock()
defer cc.wmu.Unlock()

cc.fr.WriteSettingsAck()
cc.bw.Flush()
return cc.werr

收到http2WindowUpdateFrame資料幀

在筆者debug的過程中,處理完http2FrameSettings資料幀後,緊接著就收到了http2WindowUpdateFrame資料幀。收到該資料幀後會呼叫(*http2clientConnReadLoop).processWindowUpdate方法:

func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error {
cc := rl.cc
cs := cc.streamByID(f.StreamID, false)
if f.StreamID != 0 && cs == nil {
return nil
}

cc.mu.Lock()
defer cc.mu.Unlock()

fl := &cc.flow
if cs != nil {
fl = &cs.flow
}
if !fl.add(int32(f.Increment)) {
return http2ConnectionError(http2ErrCodeFlowControl)
}
cc.cond.Broadcast()
return nil
}

上面的邏輯主要用於更新當前連線和資料流的可傳送資料視窗大小。如果http2WindowUpdateFrame幀中的StreamID為0,則更新當前連線的可傳送資料視窗大小,否則更新對應資料流可傳送資料視窗大小。

注意:在debug的過程,收到http2WindowUpdateFrame資料幀後,又收到一次http2FrameSettings,且該資料幀識別符號為http2FlagSettingsAck

筆者在這裡特意提醒,這是因為前篇中提到的(*http2Transport).NewClientConn方法,也向server傳送了http2FrameSettings資料幀和http2WindowUpdateFrame資料幀。

另外,在處理http2FrameSettingshttp2WindowUpdateFrame過程中,均出現了cc.cond.Broadcast()呼叫,該呼叫主要用於喚醒因為以下兩種情況而Wait的請求:

  1. 因當前連線處理的資料流已經達到maxConcurrentStreams的上限(詳見前篇中(*http2ClientConn).awaitOpenSlotForRequest方法分析)。

  2. 因傳送資料流已達可傳送資料視窗上限而等待可傳送資料視窗更新的請求(後續會介紹)。

收到http2MetaHeadersFrame資料幀

收到此資料幀意味著某一個請求已經開始接收響應資料。此資料幀對應的處理函式為(*http2clientConnReadLoop).processHeaders

func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error {
cc := rl.cc
cs := cc.streamByID(f.StreamID, false)
// 此處省略程式碼
res, err := rl.handleResponse(cs, f)
if err != nil {
// 此處省略程式碼
cs.resc return nil // return nil from process* funcs to keep conn alive
}
if res == nil {
// (nil, nil) special case. See handleResponse docs.
return nil
}
cs.resTrailer = &res.Trailer
cs.resc return nil
}

首先我們先看cs.resc 這一行程式碼,向資料流寫入http2resAndError即本次請求的響應。在(*http2ClientConn).roundTrip方法中有這樣一行程式碼readLoopResCh := cs.resc

回顧:前篇(*http2ClientConn).roundTrip方法的第7點和本部分關聯起來就可以形成一個完整的請求鏈。

接下來我們對rl.handleResponse方法展開分析。

(*http2clientConnReadLoop).handleResponse

(*http2clientConnReadLoop).handleResponse的主要作用是構建一個Response變數,下面對該函式的關鍵步驟進行描述。

1、構建一個Response變數。

header := make(Header)
res := &Response{
Proto: "HTTP/2.0",
ProtoMajor: 2,
Header: header,
StatusCode: statusCode,
Status: status + " " + StatusText(statusCode),
}

2、構建header(本篇不對header進行展開分析)。

for _, hf := range f.RegularFields() {
key := CanonicalHeaderKey(hf.Name)
if key == "Trailer" {
t := res.Trailer
if t == nil {
t = make(Header)
res.Trailer = t
}
http2foreachHeaderElement(hf.Value, func(v string) {
t[CanonicalHeaderKey(v)] = nil
})
} else {
header[key] = append(header[key], hf.Value)
}
}

3、處理響應body的ContentLength。

streamEnded := f.StreamEnded()
isHead := cs.req.Method == "HEAD"
if !streamEnded || isHead {
res.ContentLength = -1
if clens := res.Header["Content-Length"]; len(clens) == 1 {
if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
res.ContentLength = clen64
} else {
// TODO: care? unlike http/1, it won't mess up our framing, so it's
// more safe smuggling-wise to ignore.
}
} else if len(clens) > 1 {
// TODO: care? unlike http/1, it won't mess up our framing, so it's
// more safe smuggling-wise to ignore.
}
}

由上可知,當前資料流沒有結束或者是HEAD請求才讀取ContentLength。如果header中的ContentLength不合法則res.ContentLength的值為-1。

4、構建res.Body

cs.bufPipe = http2pipe{b: &http2dataBuffer{expected: res.ContentLength}}
cs.bytesRemain = res.ContentLength
res.Body = http2transportResponseBody{cs}
go cs.awaitRequestCancel(cs.req)

if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
res.Header.Del("Content-Encoding")
res.Header.Del("Content-Length")
res.ContentLength = -1
res.Body = &http2gzipReader{body: res.Body}
res.Uncompressed = true
}

根據Content-Encoding的編碼方式,會構建兩種不同的Body:

  1. 非gzip編碼時,構造的res.Body型別為http2transportResponseBody

  2. gzip編碼時,構造的res.Body型別為http2gzipReader

收到http2DataFrame資料幀

收到此資料幀意味著我們開始接收真實的響應,即平常開發中需要處理的業務資料。此資料幀對應的處理函式為(*http2clientConnReadLoop).processData

因為server無法及時知道資料流在client端的狀態,所以server可能會向client中一個已經不存在的資料流傳送資料:

cc := rl.cc
cs := cc.streamByID(f.StreamID, f.StreamEnded())
data := f.Data()
if cs == nil {
cc.mu.Lock()
neverSent := cc.nextStreamID
cc.mu.Unlock()
// 此處省略程式碼
if f.Length > 0 {
cc.mu.Lock()
cc.inflow.add(int32(f.Length))
cc.mu.Unlock()

cc.wmu.Lock()
cc.fr.WriteWindowUpdate(0, uint32(f.Length))
cc.bw.Flush()
cc.wmu.Unlock()
}
return nil
}

接收到的資料幀在client沒有對應的資料流處理時,通過流控制器為當前連線可讀視窗大小增加f.Length,並且通過http2FrameWindowUpdate資料幀告知server將當前連線的可寫視窗大小增加f.Length

如果client有對應的資料流且f.Length大於0:

1、如果是head請求結束當前資料流並返回。

if cs.req.Method == "HEAD" && len(data) > 0 {
cc.logf("protocol error: received DATA on a HEAD request")
rl.endStreamError(cs, http2StreamError{
StreamID: f.StreamID,
Code: http2ErrCodeProtocol,
})
return nil
}

2、檢查當前資料流能否處理f.Length長度的資料。

cc.mu.Lock()
if cs.inflow.available() >= int32(f.Length) {
cs.inflow.take(int32(f.Length))
} else {
cc.mu.Unlock()
return http2ConnectionError(http2ErrCodeFlowControl)
}

由上可知當前資料流如果能夠處理該資料,通過流控制器呼叫cs.inflow.take減小當前資料流可接受視窗大小。

3、當前資料流被重置或者被關閉即cs.didReset為true時又或者資料幀有填充資料時需要調整流控制視窗。

var refund int
if pad := int(f.Length) - len(data); pad > 0 {
refund += pad
}
// Return len(data) now if the stream is already closed,
// since data will never be read.
didReset := cs.didReset
if didReset {
refund += len(data)
}
if refund > 0 {
cc.inflow.add(int32(refund))
cc.wmu.Lock()
cc.fr.WriteWindowUpdate(0, uint32(refund))
if !didReset {
cs.inflow.add(int32(refund))
cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
}
cc.bw.Flush()
cc.wmu.Unlock()
}
cc.mu.Unlock()
  • 如果資料幀有填充資料則計算需要返還的填充資料長度。

  • 如果資料流無效該資料幀的長度需要全部返還。

最後,根據計算的refund增加當前連線或者當前資料流的可接受視窗大小,並且同時告知server增加當前連線或者當前資料流的可寫視窗大小。

4、資料長度大於0且資料流正常則將資料寫入資料流緩衝區。

if len(data) > 0 && !didReset {
if _, err := cs.bufPipe.Write(data); err != nil {
rl.endStreamError(cs, err)
return err
}
}

回顧:前面的(*http2clientConnReadLoop).handleResponse方法中有這樣一行程式碼res.Body = http2transportResponseBody{cs},所以在業務開發時能夠通過Response讀取到資料流中的緩衝資料。

(http2transportResponseBody).Read

在前面的內容裡,如果資料流狀態正常且資料幀沒有填充資料則資料流和連線的可接收視窗會一直變小,而這部分內容就是增加資料流的可接受視窗大小。

因為篇幅和主旨的問題筆者僅分析描述該方法內和流控制有關的部分。

1、讀取響應資料後計算當前連線需要增加的可接受視窗大小。

cc.mu.Lock()
defer cc.mu.Unlock()
var connAdd, streamAdd int32
// Check the conn-level first, before the stream-level.
if v := cc.inflow.available(); v < http2transportDefaultConnFlow/2 {
connAdd = http2transportDefaultConnFlow - v
cc.inflow.add(connAdd)
}

如果當前連線可接受視窗的大小已經小於http2transportDefaultConnFlow(1G)的一半,則當前連線可接收視窗大小需要增加http2transportDefaultConnFlow - cc.inflow.available()

回顧:http2transportDefaultConnFlow在前篇(*http2Transport).NewClientConn方法部分有提到,且連線剛建立時會通過http2WindowUpdateFrame資料幀告知server當前連線可傳送視窗大小增加http2transportDefaultConnFlow

2、讀取響應資料後計算當前資料流需要增加的可接受視窗大小。

if err == nil { // No need to refresh if the stream is over or failed.
// Consider any buffered body data (read from the conn but not
// consumed by the client) when computing flow control for this
// stream.
v := int(cs.inflow.available()) + cs.bufPipe.Len()
if v < http2transportDefaultStreamFlow-http2transportDefaultStreamMinRefresh {
streamAdd = int32(http2transportDefaultStreamFlow - v)
cs.inflow.add(streamAdd)
}
}

如果當前資料流可接受視窗大小加上當前資料流緩衝區剩餘未讀資料的長度小於http2transportDefaultStreamFlow-http2transportDefaultStreamMinRefresh(4M-4KB),則當前資料流可接受視窗大小需要增加http2transportDefaultStreamFlow - v

回顧:http2transportDefaultStreamFlow在前篇(*http2Transport).NewClientConn方法和(*http2ClientConn).newStream方法中均有提到。

連線剛建立時,傳送http2FrameSettings資料幀,告知server每個資料流的可傳送視窗大小為http2transportDefaultStreamFlow

newStream時,資料流預設的可接收視窗大小為http2transportDefaultStreamFlow

3、將連線和資料流分別需要增加的視窗大小通過http2WindowUpdateFrame資料幀告知server。

if connAdd != 0 || streamAdd != 0 {
cc.wmu.Lock()
defer cc.wmu.Unlock()
if connAdd != 0 {
cc.fr.WriteWindowUpdate(0, http2mustUint31(connAdd))
}
if streamAdd != 0 {
cc.fr.WriteWindowUpdate(cs.ID, http2mustUint31(streamAdd))
}
cc.bw.Flush()
}

以上就是server向client傳送資料的流控制邏輯。

(*http2clientStream).writeRequestBody

前篇中(*http2ClientConn).roundTrip未對(*http2clientStream).writeRequestBody進行分析,下面我們看看該方法的原始碼:

func (cs *http2clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
cc := cs.cc
sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
// 此處省略程式碼
req := cs.req
hasTrailers := req.Trailer != nil
remainLen := http2actualContentLength(req)
hasContentLen := remainLen != -1

var sawEOF bool
for !sawEOF {
n, err := body.Read(buf[:len(buf)-1])
// 此處省略程式碼
remain := buf[:n]
for len(remain) > 0 && err == nil {
var allowed int32
allowed, err = cs.awaitFlowControl(len(remain))
switch {
case err == http2errStopReqBodyWrite:
return err
case err == http2errStopReqBodyWriteAndCancel:
cc.writeStreamReset(cs.ID, http2ErrCodeCancel, nil)
return err
case err != nil:
return err
}
cc.wmu.Lock()
data := remain[:allowed]
remain = remain[allowed:]
sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
err = cc.fr.WriteData(cs.ID, sentEnd, data)
if err == nil {
err = cc.bw.Flush()
}
cc.wmu.Unlock()
}
if err != nil {
return err
}
}
// 此處省略程式碼
return err
}

上面的邏輯可簡單總結為:不停的讀取請求body然後將讀取的內容通過cc.fr.WriteData轉為http2FrameData資料幀傳送給server,直到請求body讀完為止。其中和流控制有關的方法是awaitFlowControl,下面我們對該方法進行分析。

(*http2clientStream).awaitFlowControl

此方法的主要作用是等待當前資料流可寫視窗有容量能夠寫入資料。

func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
cc := cs.cc
cc.mu.Lock()
defer cc.mu.Unlock()
for {
if cc.closed {
return 0, http2errClientConnClosed
}
if cs.stopReqBody != nil {
return 0, cs.stopReqBody
}
if err := cs.checkResetOrDone(); err != nil {
return 0, err
}
if a := cs.flow.available(); a > 0 {
take := a
if int(take) > maxBytes {

take = int32(maxBytes) // can't truncate int; take is int32
}
if take > int32(cc.maxFrameSize) {
take = int32(cc.maxFrameSize)
}
cs.flow.take(take)
return take, nil
}
cc.cond.Wait()
}
}

根據原始碼可以知道,資料流被關閉或者停止傳送請求body,則當前資料流無法寫入資料。當資料流狀態正常時,又分為兩種情況:

  1. 當前資料流可寫視窗剩餘可寫資料大於0,則計算可寫位元組數,並將當前資料流可寫視窗大小消耗take

  2. 當前資料流可寫視窗剩餘可寫資料小於等於0,則會一直等待直到被喚醒並進入下一次檢查。

上面的第二種情況在收到http2WindowUpdateFrame資料幀這一節中提到過。

server讀取當前資料流的資料後會向client對應資料流傳送http2WindowUpdateFrame資料幀,client收到該資料幀後會增大對應資料流可寫視窗,並執行cc.cond.Broadcast()喚醒因傳送資料已達流控制上限而等待的資料流繼續傳送資料。

以上就是client向server傳送資料的流控制邏輯。

總結

  1. 幀頭長度為9個位元組,幷包含四個部分:Payload的長度、幀型別、幀識別符號和資料流ID。

  2. 流控制可分為兩個步驟:

  • 初始時,通過http2FrameSettings資料幀和http2WindowUpdateFrame資料幀告知對方當前連線讀寫視窗大小以及連線中資料流讀寫視窗大小。

  • 在讀寫資料過程中,通過傳送http2WindowUpdateFrame資料幀控制另一端的寫視窗大小。

預告

前篇和中篇已經完成,下一期將對http2.0標頭壓縮排行分析。

最後,衷心希望本文能夠對各位讀者有一定的幫助。

注:寫本文時, 筆者所用go版本為: go1.14.2


推薦閱讀

  • Go發起HTTP2.0請求流程分析(前篇)

學習交流 Go 語言,掃碼回覆「進群」即可

f70ea582f3c880b77731e09c3977bc14.png

站長 polarisxu

自己的原創文章

不限於 Go 技術

職場和創業經驗

Go語言中文網

每天為你

分享 Go 知識

Go愛好者值得關注

3b97db4aac89ee24f219f21e4d14fd83.png