send_queue.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package quic
  2. type sender interface {
  3. Send(p *packetBuffer)
  4. Run() error
  5. WouldBlock() bool
  6. Available() <-chan struct{}
  7. Close()
  8. }
  9. type sendQueue struct {
  10. queue chan *packetBuffer
  11. closeCalled chan struct{} // runStopped when Close() is called
  12. runStopped chan struct{} // runStopped when the run loop returns
  13. available chan struct{}
  14. conn sendConn
  15. }
  16. var _ sender = &sendQueue{}
  17. const sendQueueCapacity = 8
  18. func newSendQueue(conn sendConn) sender {
  19. return &sendQueue{
  20. conn: conn,
  21. runStopped: make(chan struct{}),
  22. closeCalled: make(chan struct{}),
  23. available: make(chan struct{}, 1),
  24. queue: make(chan *packetBuffer, sendQueueCapacity),
  25. }
  26. }
  27. // Send sends out a packet. It's guaranteed to not block.
  28. // Callers need to make sure that there's actually space in the send queue by calling WouldBlock.
  29. // Otherwise Send will panic.
  30. func (h *sendQueue) Send(p *packetBuffer) {
  31. select {
  32. case h.queue <- p:
  33. // clear available channel if we've reached capacity
  34. if len(h.queue) == sendQueueCapacity {
  35. select {
  36. case <-h.available:
  37. default:
  38. }
  39. }
  40. case <-h.runStopped:
  41. default:
  42. panic("sendQueue.Send would have blocked")
  43. }
  44. }
  45. func (h *sendQueue) WouldBlock() bool {
  46. return len(h.queue) == sendQueueCapacity
  47. }
  48. func (h *sendQueue) Available() <-chan struct{} {
  49. return h.available
  50. }
  51. func (h *sendQueue) Run() error {
  52. defer close(h.runStopped)
  53. var shouldClose bool
  54. for {
  55. if shouldClose && len(h.queue) == 0 {
  56. return nil
  57. }
  58. select {
  59. case <-h.closeCalled:
  60. h.closeCalled = nil // prevent this case from being selected again
  61. // make sure that all queued packets are actually sent out
  62. shouldClose = true
  63. case p := <-h.queue:
  64. if err := h.conn.Write(p.Data); err != nil {
  65. // This additional check enables:
  66. // 1. Checking for "datagram too large" message from the kernel, as such,
  67. // 2. Path MTU discovery,and
  68. // 3. Eventual detection of loss PingFrame.
  69. if !isMsgSizeErr(err) {
  70. return err
  71. }
  72. }
  73. p.Release()
  74. select {
  75. case h.available <- struct{}{}:
  76. default:
  77. }
  78. }
  79. }
  80. }
  81. func (h *sendQueue) Close() {
  82. close(h.closeCalled)
  83. // wait until the run loop returned
  84. <-h.runStopped
  85. }