tx_batch.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package batch
  2. import "net/netip"
  3. const SendBatchCap = 128
  4. // batchWriter is the minimal subset of udp.Conn needed by SendBatch to flush.
  5. type batchWriter interface {
  6. WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error)
  7. }
  8. // SendBatch accumulates encrypted UDP packets and flushes them via WriteBatch.
  9. // One SendBatch is owned by each listenIn goroutine; no locking is needed.
  10. // Slots are backed by an Arena (see its docs)
  11. type SendBatch struct {
  12. out batchWriter
  13. bufs [][]byte
  14. dsts []netip.AddrPort
  15. arena *Arena
  16. }
  17. // NewSendBatch makes a SendBatch with batchCap slots and an arenaSize byte buffer for slices to back those slots
  18. func NewSendBatch(out batchWriter, batchCap, arenaSize int) *SendBatch {
  19. return &SendBatch{
  20. out: out,
  21. bufs: make([][]byte, 0, batchCap),
  22. dsts: make([]netip.AddrPort, 0, batchCap),
  23. arena: NewArena(arenaSize),
  24. }
  25. }
  26. func (b *SendBatch) Reserve(sz int) []byte {
  27. return b.arena.Reserve(sz)
  28. }
  29. // Len reports how many packets are queued for the next Flush. Callers use
  30. // it to flush incrementally once a full sendmmsg batch has accumulated,
  31. // bounding how long the first packet of a large read batch waits.
  32. func (b *SendBatch) Len() int { return len(b.bufs) }
  33. func (b *SendBatch) Commit(pkt []byte, dst netip.AddrPort) {
  34. b.bufs = append(b.bufs, pkt)
  35. b.dsts = append(b.dsts, dst)
  36. }
  37. // Reset drops every queued packet without sending it.
  38. func (b *SendBatch) Reset() {
  39. clear(b.bufs)
  40. b.bufs = b.bufs[:0]
  41. b.dsts = b.dsts[:0]
  42. b.arena.Reset()
  43. }
  44. // Flush writes every queued packet and reports how many actually went out. A short count means some destinations
  45. // were undeliverable; the batch is drained either way.
  46. func (b *SendBatch) Flush() (int, error) {
  47. var err error
  48. written := 0
  49. if len(b.bufs) > 0 {
  50. written, err = b.out.WriteBatch(b.bufs, b.dsts)
  51. }
  52. b.Reset()
  53. return written, err
  54. }