package quic
import (
"math/bits"
"slices"
"sync"
"github.com/tmc/go-iroh/internal/qng/internal/ackhandler"
"github.com/tmc/go-iroh/internal/qng/internal/monotime"
"github.com/tmc/go-iroh/internal/qng/internal/protocol"
"github.com/tmc/go-iroh/internal/qng/internal/utils/minheap"
"github.com/tmc/go-iroh/internal/qng/internal/utils/ringbuffer"
"github.com/tmc/go-iroh/internal/qng/internal/wire"
"github.com/tmc/go-iroh/internal/qng/quicvarint"
)
const (
maxPathResponses = 256
maxControlFrames = 16 << 10
)
const maxStreamControlFrameSize = 25
type streamFrameGetter interface {
priority() (urgency int8 , incremental bool , generation uint32 )
popStreamFrame(protocol .ByteCount , protocol .Version ) (_ ackhandler .StreamFrame , _ *wire .StreamDataBlockedFrame , hasMoreData bool )
popRetransmissionFrame(protocol .ByteCount , protocol .Version ) (ackhandler .StreamFrame , bool )
}
type streamControlFrameGetter interface {
getControlFrame(monotime .Time ) (_ ackhandler .Frame , ok, hasMore bool )
}
type streamQueueEntry struct {
id protocol .StreamID
generation uint32
}
type queuedStream struct {
streamFrameGetter
generation uint32
}
type framer struct {
mutex sync .Mutex
activeStreams map [protocol .StreamID ]queuedStream
retransmissionStreams map [protocol .StreamID ]streamFrameGetter
incrementalStreams [8 ]ringbuffer .RingBuffer [streamQueueEntry ]
nonIncrementalStreams [8 ]minheap .Heap [protocol .StreamID , uint32 ]
lastSendWasIncremental [8 ]bool
streamsWithControlFrames map [protocol .StreamID ]streamControlFrameGetter
retransmissionQueue [8 ]ringbuffer .RingBuffer [protocol .StreamID ]
streamMask uint8
retransMask uint8
controlFrameMutex sync .Mutex
controlFrames []wire .Frame
pathResponses []*wire .PathResponseFrame
maxDataFrame wire .MaxDataFrame
hasMaxDataFrame bool
connFlowController *connectionFlowController
queuedTooManyControlFrames bool
}
func newFramer(connFlowController *connectionFlowController ) *framer {
return &framer {
activeStreams : make (map [protocol .StreamID ]queuedStream ),
retransmissionStreams : make (map [protocol .StreamID ]streamFrameGetter ),
streamsWithControlFrames : make (map [protocol .StreamID ]streamControlFrameGetter ),
connFlowController : connFlowController ,
}
}
func (f *framer ) HasData () bool {
f .controlFrameMutex .Lock ()
hasControlFrames := f .hasMaxDataFrame || len (f .streamsWithControlFrames ) > 0 || len (f .controlFrames ) > 0 || len (f .pathResponses ) > 0
f .controlFrameMutex .Unlock ()
if hasControlFrames {
return true
}
f .mutex .Lock ()
defer f .mutex .Unlock ()
for urgency := range f .incrementalStreams {
if !f .incrementalStreams [urgency ].Empty () || !f .nonIncrementalStreams [urgency ].Empty () ||
!f .retransmissionQueue [urgency ].Empty () {
return true
}
}
return false
}
func (f *framer ) QueueControlFrame (frame wire .Frame ) {
f .controlFrameMutex .Lock ()
defer f .controlFrameMutex .Unlock ()
if pr , ok := frame .(*wire .PathResponseFrame ); ok {
if len (f .pathResponses ) >= maxPathResponses {
return
}
f .pathResponses = append (f .pathResponses , pr )
return
}
if len (f .controlFrames ) >= maxControlFrames {
f .queuedTooManyControlFrames = true
return
}
f .controlFrames = append (f .controlFrames , frame )
}
func (f *framer ) QueueMaxDataFrame (offset protocol .ByteCount ) {
f .controlFrameMutex .Lock ()
if !f .hasMaxDataFrame || offset > f .maxDataFrame .MaximumData {
f .maxDataFrame .MaximumData = offset
f .hasMaxDataFrame = true
}
f .controlFrameMutex .Unlock ()
}
func (f *framer ) Append (
frames []ackhandler .Frame ,
streamFrames []ackhandler .StreamFrame ,
maxLen protocol .ByteCount ,
now monotime .Time ,
v protocol .Version ,
) ([]ackhandler .Frame , ackhandler .StreamFrame , bool , []ackhandler .StreamFrame , protocol .ByteCount ) {
f .controlFrameMutex .Lock ()
frames , controlFrameLen := f .appendControlFrames (frames , maxLen , now , v )
maxLen -= controlFrameLen
var lastFrame ackhandler .StreamFrame
var singleFrame ackhandler .StreamFrame
var hasSingleFrame bool
var streamFrameLen protocol .ByteCount
f .mutex .Lock ()
retransmissions :
for m := f .retransMask ; m != 0 ; {
urgency := bits .TrailingZeros8 (m )
m &^= 1 << uint (urgency )
bucket := &f .retransmissionQueue [urgency ]
for !bucket .Empty () && protocol .MinStreamFrameSize <= maxLen {
id := bucket .PeekFront ()
str , ok := f .retransmissionStreams [id ]
if !ok {
bucket .PopFront ()
continue
}
currentUrgency , _ , _ := str .priority ()
if currentUrgency != int8 (urgency ) {
bucket .PopFront ()
f .retransmissionQueue [currentUrgency ].PushBack (id )
f .retransMask |= 1 << uint (currentUrgency )
if int (currentUrgency ) > urgency {
m |= 1 << uint (currentUrgency )
}
continue
}
frameMaxLen := maxLen + protocol .ByteCount (quicvarint .Len (uint64 (maxLen )))
sf , hasMoreRetransmissions := str .popRetransmissionFrame (frameMaxLen , v )
if !hasMoreRetransmissions {
bucket .PopFront ()
delete (f .retransmissionStreams , id )
}
if sf .Frame == nil {
if hasMoreRetransmissions {
break retransmissions
}
continue
}
streamFrames = append (streamFrames , sf )
maxLen -= sf .Frame .Length (v )
lastFrame = sf
streamFrameLen += sf .Frame .Length (v )
}
if bucket .Empty () {
f .retransMask &^= 1 << uint (urgency )
}
}
for m := f .streamMask ; m != 0 ; {
urgency := bits .TrailingZeros8 (m )
m &^= 1 << uint (urgency )
numActiveStreams := f .incrementalStreams [urgency ].Len () + f .nonIncrementalStreams [urgency ].Len ()
for range numActiveStreams {
if protocol .MinStreamFrameSize > maxLen {
break
}
sf , blocked := f .getNextStreamFrame (maxLen , int8 (urgency ), v )
if sf .Frame != nil {
if !hasSingleFrame && len (streamFrames ) == 0 {
singleFrame = sf
hasSingleFrame = true
} else {
if hasSingleFrame {
streamFrames = append (streamFrames , singleFrame )
singleFrame = ackhandler .StreamFrame {}
hasSingleFrame = false
}
streamFrames = append (streamFrames , sf )
}
maxLen -= sf .Frame .Length (v )
lastFrame = sf
streamFrameLen += sf .Frame .Length (v )
}
if blocked != nil {
l := blocked .Length (v )
if maxLen < l {
f .controlFrames = append (f .controlFrames , blocked )
break
}
frames = append (frames , ackhandler .Frame {Frame : blocked })
maxLen -= l
controlFrameLen += l
}
}
if f .incrementalStreams [urgency ].Empty () && f .nonIncrementalStreams [urgency ].Empty () {
f .streamMask &^= 1 << uint (urgency )
}
}
if isBlocked , offset := f .connFlowController .IsNewlyBlocked (); isBlocked {
blocked := &wire .DataBlockedFrame {MaximumData : offset }
l := blocked .Length (v )
if maxLen >= l {
frames = append (frames , ackhandler .Frame {Frame : blocked })
controlFrameLen += l
} else {
f .controlFrames = append (f .controlFrames , blocked )
}
}
f .mutex .Unlock ()
f .controlFrameMutex .Unlock ()
if lastFrame .Frame != nil {
streamFrameLen -= lastFrame .Frame .Length (v )
lastFrame .Frame .DataLenPresent = false
streamFrameLen += lastFrame .Frame .Length (v )
}
return frames , singleFrame , hasSingleFrame , streamFrames , controlFrameLen + streamFrameLen
}
func (f *framer ) AppendControlFrames (
frames []ackhandler .Frame ,
maxLen protocol .ByteCount ,
now monotime .Time ,
v protocol .Version ,
) ([]ackhandler .Frame , protocol .ByteCount ) {
f .controlFrameMutex .Lock ()
defer f .controlFrameMutex .Unlock ()
return f .appendControlFrames (frames , maxLen , now , v )
}
func (f *framer ) appendControlFrames (
frames []ackhandler .Frame ,
maxLen protocol .ByteCount ,
now monotime .Time ,
v protocol .Version ,
) ([]ackhandler .Frame , protocol .ByteCount ) {
var length protocol .ByteCount
if len (f .pathResponses ) > 0 {
frame := f .pathResponses [0 ]
frameLen := frame .Length (v )
if frameLen <= maxLen {
frames = append (frames , ackhandler .Frame {Frame : frame })
length += frameLen
f .pathResponses = f .pathResponses [1 :]
}
}
if f .hasMaxDataFrame {
frameLen := f .maxDataFrame .Length (v )
if length +frameLen <= maxLen {
frames = append (frames , ackhandler .Frame {Frame : &wire .MaxDataFrame {MaximumData : f .maxDataFrame .MaximumData }})
length += frameLen
f .hasMaxDataFrame = false
}
}
for id , str := range f .streamsWithControlFrames {
start :
remainingLen := maxLen - length
if remainingLen <= maxStreamControlFrameSize {
break
}
fr , ok , hasMore := str .getControlFrame (now )
if !hasMore {
delete (f .streamsWithControlFrames , id )
}
if !ok {
continue
}
frames = append (frames , fr )
length += fr .Frame .Length (v )
if hasMore {
goto start
}
}
for len (f .controlFrames ) > 0 {
frame := f .controlFrames [len (f .controlFrames )-1 ]
frameLen := frame .Length (v )
if length +frameLen > maxLen {
break
}
frames = append (frames , ackhandler .Frame {Frame : frame })
length += frameLen
f .controlFrames = f .controlFrames [:len (f .controlFrames )-1 ]
}
return frames , length
}
func (f *framer ) QueuedTooManyControlFrames () bool {
return f .queuedTooManyControlFrames
}
func (f *framer ) AddActiveStream (id protocol .StreamID , str streamFrameGetter ) {
f .mutex .Lock ()
defer f .mutex .Unlock ()
urgency , incremental , generation := str .priority ()
if activeStr , ok := f .activeStreams [id ]; ok && activeStr .generation == generation {
return
}
if incremental {
f .incrementalStreams [urgency ].PushBack (streamQueueEntry {id : id , generation : generation })
} else {
f .nonIncrementalStreams [urgency ].Push (id , generation )
}
f .streamMask |= 1 << uint (urgency )
f .activeStreams [id ] = queuedStream {streamFrameGetter : str , generation : generation }
}
func (f *framer ) AddStreamWithRetransmission (id protocol .StreamID , str streamFrameGetter ) {
f .mutex .Lock ()
defer f .mutex .Unlock ()
urgency , _ , _ := str .priority ()
if _ , ok := f .retransmissionStreams [id ]; ok {
return
}
f .retransmissionQueue [urgency ].PushBack (id )
f .retransMask |= 1 << uint (urgency )
f .retransmissionStreams [id ] = str
}
func (f *framer ) AddStreamWithControlFrames (id protocol .StreamID , str streamControlFrameGetter ) {
f .controlFrameMutex .Lock ()
defer f .controlFrameMutex .Unlock ()
if _ , ok := f .streamsWithControlFrames [id ]; !ok {
f .streamsWithControlFrames [id ] = str
}
}
func (f *framer ) RemoveActiveStream (id protocol .StreamID ) {
f .mutex .Lock ()
defer f .mutex .Unlock ()
delete (f .activeStreams , id )
delete (f .retransmissionStreams , id )
}
func (f *framer ) UpdateStreamPriority (id protocol .StreamID ) {
f .mutex .Lock ()
defer f .mutex .Unlock ()
str , ok := f .activeStreams [id ]
if !ok {
return
}
urgency , incremental , generation := str .priority ()
if str .generation != generation {
if incremental {
f .incrementalStreams [urgency ].PushBack (streamQueueEntry {id : id , generation : generation })
} else {
f .nonIncrementalStreams [urgency ].Push (id , generation )
}
f .streamMask |= 1 << uint (urgency )
str .generation = generation
f .activeStreams [id ] = str
}
}
func (f *framer ) getNextStreamFrame (
maxLen protocol .ByteCount ,
urgency int8 ,
v protocol .Version ,
) (ackhandler .StreamFrame , *wire .StreamDataBlockedFrame ) {
if f .nonIncrementalStreams [urgency ].Empty () || (!f .lastSendWasIncremental [urgency ] && !f .incrementalStreams [urgency ].Empty ()) {
return f .getNextIncrementalStreamFrame (maxLen , urgency , v )
}
return f .getNextNonIncrementalStreamFrame (maxLen , urgency , v )
}
func (f *framer ) getNextIncrementalStreamFrame (
maxLen protocol .ByteCount ,
urgency int8 ,
v protocol .Version ,
) (ackhandler .StreamFrame , *wire .StreamDataBlockedFrame ) {
queue := &f .incrementalStreams [urgency ]
if queue .Empty () {
return ackhandler .StreamFrame {}, nil
}
entry := queue .PopFront ()
str , ok := f .activeStreams [entry .id ]
if !ok {
return ackhandler .StreamFrame {}, nil
}
_ , _ , generation := str .priority ()
if generation != entry .generation {
return ackhandler .StreamFrame {}, nil
}
frame , blocked , hasMoreData := f .popStreamFrame (entry .id , str , maxLen , v )
if hasMoreData {
queue .PushBack (entry )
}
f .lastSendWasIncremental [urgency ] = true
return frame , blocked
}
func (f *framer ) getNextNonIncrementalStreamFrame (
maxLen protocol .ByteCount ,
urgency int8 ,
v protocol .Version ,
) (ackhandler .StreamFrame , *wire .StreamDataBlockedFrame ) {
queue := &f .nonIncrementalStreams [urgency ]
if queue .Empty () {
return ackhandler .StreamFrame {}, nil
}
id , queuedGeneration := queue .Peek ()
str , ok := f .activeStreams [id ]
if !ok {
queue .Pop ()
return ackhandler .StreamFrame {}, nil
}
_ , _ , generation := str .priority ()
if generation != queuedGeneration {
queue .Pop ()
return ackhandler .StreamFrame {}, nil
}
frame , blocked , hasMoreData := f .popStreamFrame (id , str , maxLen , v )
if !hasMoreData {
queue .Pop ()
}
f .lastSendWasIncremental [urgency ] = false
return frame , blocked
}
func (f *framer ) popStreamFrame (
id protocol .StreamID ,
str queuedStream ,
maxLen protocol .ByteCount ,
v protocol .Version ,
) (ackhandler .StreamFrame , *wire .StreamDataBlockedFrame , bool ) {
maxLen += protocol .ByteCount (quicvarint .Len (uint64 (maxLen )))
frame , blocked , hasMoreData := str .popStreamFrame (maxLen , v )
if !hasMoreData {
delete (f .activeStreams , id )
}
return frame , blocked , hasMoreData
}
func (f *framer ) Handle0RTTRejection () {
f .mutex .Lock ()
defer f .mutex .Unlock ()
f .controlFrameMutex .Lock ()
defer f .controlFrameMutex .Unlock ()
f .streamMask = 0
f .retransMask = 0
for urgency := range f .incrementalStreams {
f .incrementalStreams [urgency ].Clear ()
f .nonIncrementalStreams [urgency ].Clear ()
f .lastSendWasIncremental [urgency ] = false
f .retransmissionQueue [urgency ].Clear ()
}
clear (f .activeStreams )
clear (f .retransmissionStreams )
clear (f .streamsWithControlFrames )
var j int
for i , frame := range f .controlFrames {
switch frame .(type ) {
case *wire .MaxDataFrame , *wire .MaxStreamDataFrame , *wire .MaxStreamsFrame ,
*wire .DataBlockedFrame , *wire .StreamDataBlockedFrame , *wire .StreamsBlockedFrame :
continue
default :
f .controlFrames [j ] = f .controlFrames [i ]
j ++
}
}
f .controlFrames = slices .Delete (f .controlFrames , j , len (f .controlFrames ))
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .