mirror of
https://github.com/ScuroNeko/mtg.git
synced 2026-08-31 11:54:01 +03:00
Reduce per-connection memory overhead
- Use sync.Pool for relay buffers instead of stack-allocated arrays. A [16379]byte on the goroutine stack forces Go to grow it to 32KB (next power of two). Pooled buffers keep goroutine stacks small. - Same fix for doppelganger write buffer ([16384]byte in conn.start). - Replace idle goroutines with context.AfterFunc in proxy.ServeConn and relay.Relay. These goroutines existed only to wait on ctx.Done() and close connections. AfterFunc achieves the same without allocating a goroutine until the context is actually cancelled. Net effect: at 3000 concurrent connections on a 1-vCPU/961MB VPS, the unmodified binary drops 246 connections and falls to 10 MB/s. With these changes: zero failures, 63 MB/s, 31% lower RSS. Closes #412
This commit is contained in:
@@ -9,6 +9,13 @@ import (
|
||||
"github.com/9seconds/mtg/v2/mtglib/internal/tls"
|
||||
)
|
||||
|
||||
var doppelBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, tls.MaxRecordSize)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
type Conn struct {
|
||||
essentials.Conn
|
||||
|
||||
@@ -46,7 +53,9 @@ func (c Conn) Start() {
|
||||
}
|
||||
|
||||
func (c Conn) start() {
|
||||
buf := [tls.MaxRecordSize]byte{}
|
||||
bp := doppelBufPool.Get().(*[]byte)
|
||||
buf := *bp
|
||||
defer doppelBufPool.Put(bp)
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -68,7 +77,7 @@ func (c Conn) start() {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := tls.WriteRecordInPlace(c.Conn, buf[:], n); err != nil {
|
||||
if err := tls.WriteRecordInPlace(c.Conn, buf, n); err != nil {
|
||||
c.p.ctxCancel(err)
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user