controlbuf.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package transport
  19. import (
  20. "bytes"
  21. "fmt"
  22. "runtime"
  23. "sync"
  24. "golang.org/x/net/http2"
  25. "golang.org/x/net/http2/hpack"
  26. )
  27. var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) {
  28. e.SetMaxDynamicTableSizeLimit(v)
  29. }
  30. type itemNode struct {
  31. it interface{}
  32. next *itemNode
  33. }
  34. type itemList struct {
  35. head *itemNode
  36. tail *itemNode
  37. }
  38. func (il *itemList) enqueue(i interface{}) {
  39. n := &itemNode{it: i}
  40. if il.tail == nil {
  41. il.head, il.tail = n, n
  42. return
  43. }
  44. il.tail.next = n
  45. il.tail = n
  46. }
  47. // peek returns the first item in the list without removing it from the
  48. // list.
  49. func (il *itemList) peek() interface{} {
  50. return il.head.it
  51. }
  52. func (il *itemList) dequeue() interface{} {
  53. if il.head == nil {
  54. return nil
  55. }
  56. i := il.head.it
  57. il.head = il.head.next
  58. if il.head == nil {
  59. il.tail = nil
  60. }
  61. return i
  62. }
  63. func (il *itemList) dequeueAll() *itemNode {
  64. h := il.head
  65. il.head, il.tail = nil, nil
  66. return h
  67. }
  68. func (il *itemList) isEmpty() bool {
  69. return il.head == nil
  70. }
  71. // The following defines various control items which could flow through
  72. // the control buffer of transport. They represent different aspects of
  73. // control tasks, e.g., flow control, settings, streaming resetting, etc.
  74. // registerStream is used to register an incoming stream with loopy writer.
  75. type registerStream struct {
  76. streamID uint32
  77. wq *writeQuota
  78. }
  79. // headerFrame is also used to register stream on the client-side.
  80. type headerFrame struct {
  81. streamID uint32
  82. hf []hpack.HeaderField
  83. endStream bool // Valid on server side.
  84. initStream func(uint32) (bool, error) // Used only on the client side.
  85. onWrite func()
  86. wq *writeQuota // write quota for the stream created.
  87. cleanup *cleanupStream // Valid on the server side.
  88. onOrphaned func(error) // Valid on client-side
  89. }
  90. type cleanupStream struct {
  91. streamID uint32
  92. idPtr *uint32
  93. rst bool
  94. rstCode http2.ErrCode
  95. onWrite func()
  96. }
  97. type dataFrame struct {
  98. streamID uint32
  99. endStream bool
  100. h []byte
  101. d []byte
  102. // onEachWrite is called every time
  103. // a part of d is written out.
  104. onEachWrite func()
  105. }
  106. type incomingWindowUpdate struct {
  107. streamID uint32
  108. increment uint32
  109. }
  110. type outgoingWindowUpdate struct {
  111. streamID uint32
  112. increment uint32
  113. }
  114. type incomingSettings struct {
  115. ss []http2.Setting
  116. }
  117. type outgoingSettings struct {
  118. ss []http2.Setting
  119. }
  120. type settingsAck struct {
  121. }
  122. type incomingGoAway struct {
  123. }
  124. type goAway struct {
  125. code http2.ErrCode
  126. debugData []byte
  127. headsUp bool
  128. closeConn bool
  129. }
  130. type ping struct {
  131. ack bool
  132. data [8]byte
  133. }
  134. type outFlowControlSizeRequest struct {
  135. resp chan uint32
  136. }
  137. type outStreamState int
  138. const (
  139. active outStreamState = iota
  140. empty
  141. waitingOnStreamQuota
  142. )
  143. type outStream struct {
  144. id uint32
  145. state outStreamState
  146. itl *itemList
  147. bytesOutStanding int
  148. wq *writeQuota
  149. next *outStream
  150. prev *outStream
  151. }
  152. func (s *outStream) deleteSelf() {
  153. if s.prev != nil {
  154. s.prev.next = s.next
  155. }
  156. if s.next != nil {
  157. s.next.prev = s.prev
  158. }
  159. s.next, s.prev = nil, nil
  160. }
  161. type outStreamList struct {
  162. // Following are sentinel objects that mark the
  163. // beginning and end of the list. They do not
  164. // contain any item lists. All valid objects are
  165. // inserted in between them.
  166. // This is needed so that an outStream object can
  167. // deleteSelf() in O(1) time without knowing which
  168. // list it belongs to.
  169. head *outStream
  170. tail *outStream
  171. }
  172. func newOutStreamList() *outStreamList {
  173. head, tail := new(outStream), new(outStream)
  174. head.next = tail
  175. tail.prev = head
  176. return &outStreamList{
  177. head: head,
  178. tail: tail,
  179. }
  180. }
  181. func (l *outStreamList) enqueue(s *outStream) {
  182. e := l.tail.prev
  183. e.next = s
  184. s.prev = e
  185. s.next = l.tail
  186. l.tail.prev = s
  187. }
  188. // remove from the beginning of the list.
  189. func (l *outStreamList) dequeue() *outStream {
  190. b := l.head.next
  191. if b == l.tail {
  192. return nil
  193. }
  194. b.deleteSelf()
  195. return b
  196. }
  197. type controlBuffer struct {
  198. ch chan struct{}
  199. done <-chan struct{}
  200. mu sync.Mutex
  201. consumerWaiting bool
  202. list *itemList
  203. err error
  204. }
  205. func newControlBuffer(done <-chan struct{}) *controlBuffer {
  206. return &controlBuffer{
  207. ch: make(chan struct{}, 1),
  208. list: &itemList{},
  209. done: done,
  210. }
  211. }
  212. func (c *controlBuffer) put(it interface{}) error {
  213. _, err := c.executeAndPut(nil, it)
  214. return err
  215. }
  216. func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it interface{}) (bool, error) {
  217. var wakeUp bool
  218. c.mu.Lock()
  219. if c.err != nil {
  220. c.mu.Unlock()
  221. return false, c.err
  222. }
  223. if f != nil {
  224. if !f(it) { // f wasn't successful
  225. c.mu.Unlock()
  226. return false, nil
  227. }
  228. }
  229. if c.consumerWaiting {
  230. wakeUp = true
  231. c.consumerWaiting = false
  232. }
  233. c.list.enqueue(it)
  234. c.mu.Unlock()
  235. if wakeUp {
  236. select {
  237. case c.ch <- struct{}{}:
  238. default:
  239. }
  240. }
  241. return true, nil
  242. }
  243. func (c *controlBuffer) get(block bool) (interface{}, error) {
  244. for {
  245. c.mu.Lock()
  246. if c.err != nil {
  247. c.mu.Unlock()
  248. return nil, c.err
  249. }
  250. if !c.list.isEmpty() {
  251. h := c.list.dequeue()
  252. c.mu.Unlock()
  253. return h, nil
  254. }
  255. if !block {
  256. c.mu.Unlock()
  257. return nil, nil
  258. }
  259. c.consumerWaiting = true
  260. c.mu.Unlock()
  261. select {
  262. case <-c.ch:
  263. case <-c.done:
  264. c.finish()
  265. return nil, ErrConnClosing
  266. }
  267. }
  268. }
  269. func (c *controlBuffer) finish() {
  270. c.mu.Lock()
  271. if c.err != nil {
  272. c.mu.Unlock()
  273. return
  274. }
  275. c.err = ErrConnClosing
  276. // There may be headers for streams in the control buffer.
  277. // These streams need to be cleaned out since the transport
  278. // is still not aware of these yet.
  279. for head := c.list.dequeueAll(); head != nil; head = head.next {
  280. hdr, ok := head.it.(*headerFrame)
  281. if !ok {
  282. continue
  283. }
  284. if hdr.onOrphaned != nil { // It will be nil on the server-side.
  285. hdr.onOrphaned(ErrConnClosing)
  286. }
  287. }
  288. c.mu.Unlock()
  289. }
  290. type side int
  291. const (
  292. clientSide side = iota
  293. serverSide
  294. )
  295. type loopyWriter struct {
  296. side side
  297. cbuf *controlBuffer
  298. sendQuota uint32
  299. oiws uint32 // outbound initial window size.
  300. estdStreams map[uint32]*outStream // Established streams.
  301. activeStreams *outStreamList // Streams that are sending data.
  302. framer *framer
  303. hBuf *bytes.Buffer // The buffer for HPACK encoding.
  304. hEnc *hpack.Encoder // HPACK encoder.
  305. bdpEst *bdpEstimator
  306. draining bool
  307. // Side-specific handlers
  308. ssGoAwayHandler func(*goAway) (bool, error)
  309. }
  310. func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter {
  311. var buf bytes.Buffer
  312. l := &loopyWriter{
  313. side: s,
  314. cbuf: cbuf,
  315. sendQuota: defaultWindowSize,
  316. oiws: defaultWindowSize,
  317. estdStreams: make(map[uint32]*outStream),
  318. activeStreams: newOutStreamList(),
  319. framer: fr,
  320. hBuf: &buf,
  321. hEnc: hpack.NewEncoder(&buf),
  322. bdpEst: bdpEst,
  323. }
  324. return l
  325. }
  326. const minBatchSize = 1000
  327. // run should be run in a separate goroutine.
  328. func (l *loopyWriter) run() (err error) {
  329. defer func() {
  330. if err == ErrConnClosing {
  331. // Don't log ErrConnClosing as error since it happens
  332. // 1. When the connection is closed by some other known issue.
  333. // 2. User closed the connection.
  334. // 3. A graceful close of connection.
  335. infof("transport: loopyWriter.run returning. %v", err)
  336. err = nil
  337. }
  338. }()
  339. for {
  340. it, err := l.cbuf.get(true)
  341. if err != nil {
  342. return err
  343. }
  344. if err = l.handle(it); err != nil {
  345. return err
  346. }
  347. if _, err = l.processData(); err != nil {
  348. return err
  349. }
  350. gosched := true
  351. hasdata:
  352. for {
  353. it, err := l.cbuf.get(false)
  354. if err != nil {
  355. return err
  356. }
  357. if it != nil {
  358. if err = l.handle(it); err != nil {
  359. return err
  360. }
  361. if _, err = l.processData(); err != nil {
  362. return err
  363. }
  364. continue hasdata
  365. }
  366. isEmpty, err := l.processData()
  367. if err != nil {
  368. return err
  369. }
  370. if !isEmpty {
  371. continue hasdata
  372. }
  373. if gosched {
  374. gosched = false
  375. if l.framer.writer.offset < minBatchSize {
  376. runtime.Gosched()
  377. continue hasdata
  378. }
  379. }
  380. l.framer.writer.Flush()
  381. break hasdata
  382. }
  383. }
  384. }
  385. func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error {
  386. return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment)
  387. }
  388. func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error {
  389. // Otherwise update the quota.
  390. if w.streamID == 0 {
  391. l.sendQuota += w.increment
  392. return nil
  393. }
  394. // Find the stream and update it.
  395. if str, ok := l.estdStreams[w.streamID]; ok {
  396. str.bytesOutStanding -= int(w.increment)
  397. if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota {
  398. str.state = active
  399. l.activeStreams.enqueue(str)
  400. return nil
  401. }
  402. }
  403. return nil
  404. }
  405. func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error {
  406. return l.framer.fr.WriteSettings(s.ss...)
  407. }
  408. func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error {
  409. if err := l.applySettings(s.ss); err != nil {
  410. return err
  411. }
  412. return l.framer.fr.WriteSettingsAck()
  413. }
  414. func (l *loopyWriter) registerStreamHandler(h *registerStream) error {
  415. str := &outStream{
  416. id: h.streamID,
  417. state: empty,
  418. itl: &itemList{},
  419. wq: h.wq,
  420. }
  421. l.estdStreams[h.streamID] = str
  422. return nil
  423. }
  424. func (l *loopyWriter) headerHandler(h *headerFrame) error {
  425. if l.side == serverSide {
  426. str, ok := l.estdStreams[h.streamID]
  427. if !ok {
  428. warningf("transport: loopy doesn't recognize the stream: %d", h.streamID)
  429. return nil
  430. }
  431. // Case 1.A: Server is responding back with headers.
  432. if !h.endStream {
  433. return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite)
  434. }
  435. // else: Case 1.B: Server wants to close stream.
  436. if str.state != empty { // either active or waiting on stream quota.
  437. // add it str's list of items.
  438. str.itl.enqueue(h)
  439. return nil
  440. }
  441. if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil {
  442. return err
  443. }
  444. return l.cleanupStreamHandler(h.cleanup)
  445. }
  446. // Case 2: Client wants to originate stream.
  447. str := &outStream{
  448. id: h.streamID,
  449. state: empty,
  450. itl: &itemList{},
  451. wq: h.wq,
  452. }
  453. str.itl.enqueue(h)
  454. return l.originateStream(str)
  455. }
  456. func (l *loopyWriter) originateStream(str *outStream) error {
  457. hdr := str.itl.dequeue().(*headerFrame)
  458. sendPing, err := hdr.initStream(str.id)
  459. if err != nil {
  460. if err == ErrConnClosing {
  461. return err
  462. }
  463. // Other errors(errStreamDrain) need not close transport.
  464. return nil
  465. }
  466. if err = l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil {
  467. return err
  468. }
  469. l.estdStreams[str.id] = str
  470. if sendPing {
  471. return l.pingHandler(&ping{data: [8]byte{}})
  472. }
  473. return nil
  474. }
  475. func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error {
  476. if onWrite != nil {
  477. onWrite()
  478. }
  479. l.hBuf.Reset()
  480. for _, f := range hf {
  481. if err := l.hEnc.WriteField(f); err != nil {
  482. warningf("transport: loopyWriter.writeHeader encountered error while encoding headers:", err)
  483. }
  484. }
  485. var (
  486. err error
  487. endHeaders, first bool
  488. )
  489. first = true
  490. for !endHeaders {
  491. size := l.hBuf.Len()
  492. if size > http2MaxFrameLen {
  493. size = http2MaxFrameLen
  494. } else {
  495. endHeaders = true
  496. }
  497. if first {
  498. first = false
  499. err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{
  500. StreamID: streamID,
  501. BlockFragment: l.hBuf.Next(size),
  502. EndStream: endStream,
  503. EndHeaders: endHeaders,
  504. })
  505. } else {
  506. err = l.framer.fr.WriteContinuation(
  507. streamID,
  508. endHeaders,
  509. l.hBuf.Next(size),
  510. )
  511. }
  512. if err != nil {
  513. return err
  514. }
  515. }
  516. return nil
  517. }
  518. func (l *loopyWriter) preprocessData(df *dataFrame) error {
  519. str, ok := l.estdStreams[df.streamID]
  520. if !ok {
  521. return nil
  522. }
  523. // If we got data for a stream it means that
  524. // stream was originated and the headers were sent out.
  525. str.itl.enqueue(df)
  526. if str.state == empty {
  527. str.state = active
  528. l.activeStreams.enqueue(str)
  529. }
  530. return nil
  531. }
  532. func (l *loopyWriter) pingHandler(p *ping) error {
  533. if !p.ack {
  534. l.bdpEst.timesnap(p.data)
  535. }
  536. return l.framer.fr.WritePing(p.ack, p.data)
  537. }
  538. func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error {
  539. o.resp <- l.sendQuota
  540. return nil
  541. }
  542. func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error {
  543. c.onWrite()
  544. if str, ok := l.estdStreams[c.streamID]; ok {
  545. // On the server side it could be a trailers-only response or
  546. // a RST_STREAM before stream initialization thus the stream might
  547. // not be established yet.
  548. delete(l.estdStreams, c.streamID)
  549. str.deleteSelf()
  550. }
  551. if c.rst { // If RST_STREAM needs to be sent.
  552. if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil {
  553. return err
  554. }
  555. }
  556. if l.side == clientSide && l.draining && len(l.estdStreams) == 0 {
  557. return ErrConnClosing
  558. }
  559. return nil
  560. }
  561. func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error {
  562. if l.side == clientSide {
  563. l.draining = true
  564. if len(l.estdStreams) == 0 {
  565. return ErrConnClosing
  566. }
  567. }
  568. return nil
  569. }
  570. func (l *loopyWriter) goAwayHandler(g *goAway) error {
  571. // Handling of outgoing GoAway is very specific to side.
  572. if l.ssGoAwayHandler != nil {
  573. draining, err := l.ssGoAwayHandler(g)
  574. if err != nil {
  575. return err
  576. }
  577. l.draining = draining
  578. }
  579. return nil
  580. }
  581. func (l *loopyWriter) handle(i interface{}) error {
  582. switch i := i.(type) {
  583. case *incomingWindowUpdate:
  584. return l.incomingWindowUpdateHandler(i)
  585. case *outgoingWindowUpdate:
  586. return l.outgoingWindowUpdateHandler(i)
  587. case *incomingSettings:
  588. return l.incomingSettingsHandler(i)
  589. case *outgoingSettings:
  590. return l.outgoingSettingsHandler(i)
  591. case *headerFrame:
  592. return l.headerHandler(i)
  593. case *registerStream:
  594. return l.registerStreamHandler(i)
  595. case *cleanupStream:
  596. return l.cleanupStreamHandler(i)
  597. case *incomingGoAway:
  598. return l.incomingGoAwayHandler(i)
  599. case *dataFrame:
  600. return l.preprocessData(i)
  601. case *ping:
  602. return l.pingHandler(i)
  603. case *goAway:
  604. return l.goAwayHandler(i)
  605. case *outFlowControlSizeRequest:
  606. return l.outFlowControlSizeRequestHandler(i)
  607. default:
  608. return fmt.Errorf("transport: unknown control message type %T", i)
  609. }
  610. }
  611. func (l *loopyWriter) applySettings(ss []http2.Setting) error {
  612. for _, s := range ss {
  613. switch s.ID {
  614. case http2.SettingInitialWindowSize:
  615. o := l.oiws
  616. l.oiws = s.Val
  617. if o < l.oiws {
  618. // If the new limit is greater make all depleted streams active.
  619. for _, stream := range l.estdStreams {
  620. if stream.state == waitingOnStreamQuota {
  621. stream.state = active
  622. l.activeStreams.enqueue(stream)
  623. }
  624. }
  625. }
  626. case http2.SettingHeaderTableSize:
  627. updateHeaderTblSize(l.hEnc, s.Val)
  628. }
  629. }
  630. return nil
  631. }
  632. func (l *loopyWriter) processData() (bool, error) {
  633. if l.sendQuota == 0 {
  634. return true, nil
  635. }
  636. str := l.activeStreams.dequeue()
  637. if str == nil {
  638. return true, nil
  639. }
  640. dataItem := str.itl.peek().(*dataFrame)
  641. if len(dataItem.h) == 0 && len(dataItem.d) == 0 {
  642. // Client sends out empty data frame with endStream = true
  643. if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil {
  644. return false, err
  645. }
  646. str.itl.dequeue()
  647. if str.itl.isEmpty() {
  648. str.state = empty
  649. } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers.
  650. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil {
  651. return false, err
  652. }
  653. if err := l.cleanupStreamHandler(trailer.cleanup); err != nil {
  654. return false, nil
  655. }
  656. } else {
  657. l.activeStreams.enqueue(str)
  658. }
  659. return false, nil
  660. }
  661. var (
  662. idx int
  663. buf []byte
  664. )
  665. if len(dataItem.h) != 0 { // data header has not been written out yet.
  666. buf = dataItem.h
  667. } else {
  668. idx = 1
  669. buf = dataItem.d
  670. }
  671. size := http2MaxFrameLen
  672. if len(buf) < size {
  673. size = len(buf)
  674. }
  675. if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 {
  676. str.state = waitingOnStreamQuota
  677. return false, nil
  678. } else if strQuota < size {
  679. size = strQuota
  680. }
  681. if l.sendQuota < uint32(size) {
  682. size = int(l.sendQuota)
  683. }
  684. // Now that outgoing flow controls are checked we can replenish str's write quota
  685. str.wq.replenish(size)
  686. var endStream bool
  687. // This last data message on this stream and all
  688. // of it can be written in this go.
  689. if dataItem.endStream && size == len(buf) {
  690. // buf contains either data or it contains header but data is empty.
  691. if idx == 1 || len(dataItem.d) == 0 {
  692. endStream = true
  693. }
  694. }
  695. if dataItem.onEachWrite != nil {
  696. dataItem.onEachWrite()
  697. }
  698. if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil {
  699. return false, err
  700. }
  701. buf = buf[size:]
  702. str.bytesOutStanding += size
  703. l.sendQuota -= uint32(size)
  704. if idx == 0 {
  705. dataItem.h = buf
  706. } else {
  707. dataItem.d = buf
  708. }
  709. if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out.
  710. str.itl.dequeue()
  711. }
  712. if str.itl.isEmpty() {
  713. str.state = empty
  714. } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers.
  715. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil {
  716. return false, err
  717. }
  718. if err := l.cleanupStreamHandler(trailer.cleanup); err != nil {
  719. return false, err
  720. }
  721. } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota.
  722. str.state = waitingOnStreamQuota
  723. } else { // Otherwise add it back to the list of active streams.
  724. l.activeStreams.enqueue(str)
  725. }
  726. return false, nil
  727. }