| 1 |
package vnet |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
type DelayFilter struct { |
| 11 |
NIC |
| 12 |
delay time.Duration |
| 13 |
push chan struct{} |
| 14 |
queue *chunkQueue |
| 15 |
} |
| 16 |
|
| 17 |
type timedChunk struct { |
| 18 |
Chunk |
| 19 |
deadline time.Time |
| 20 |
} |
| 21 |
|
| 22 |
|
| 23 |
func NewDelayFilter(nic NIC, delay time.Duration) (*DelayFilter, error) { |
| 24 |
return &DelayFilter{ |
| 25 |
NIC: nic, |
| 26 |
delay: delay, |
| 27 |
push: make(chan struct{}), |
| 28 |
queue: newChunkQueue(0, 0), |
| 29 |
}, nil |
| 30 |
} |
| 31 |
|
| 32 |
func (f *DelayFilter) onInboundChunk(c Chunk) { |
| 33 |
f.queue.push(timedChunk{ |
| 34 |
Chunk: c, |
| 35 |
deadline: time.Now().Add(f.delay), |
| 36 |
}) |
| 37 |
f.push <- struct{}{} |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
func (f *DelayFilter) Run(ctx context.Context) { |
| 44 |
timer := time.NewTimer(0) |
| 45 |
for { |
| 46 |
select { |
| 47 |
case <-ctx.Done(): |
| 48 |
return |
| 49 |
case <-f.push: |
| 50 |
next := f.queue.peek().(timedChunk) |
| 51 |
if !timer.Stop() { |
| 52 |
<-timer.C |
| 53 |
} |
| 54 |
timer.Reset(time.Until(next.deadline)) |
| 55 |
case now := <-timer.C: |
| 56 |
next := f.queue.peek() |
| 57 |
if next == nil { |
| 58 |
timer.Reset(time.Minute) |
| 59 |
continue |
| 60 |
} |
| 61 |
if n, ok := next.(timedChunk); ok && n.deadline.Before(now) { |
| 62 |
f.queue.pop() |
| 63 |
f.NIC.onInboundChunk(n.Chunk) |
| 64 |
} |
| 65 |
next = f.queue.peek() |
| 66 |
if next == nil { |
| 67 |
timer.Reset(time.Minute) |
| 68 |
continue |
| 69 |
} |
| 70 |
if n, ok := next.(timedChunk); ok { |
| 71 |
timer.Reset(time.Until(n.deadline)) |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
} |