mirror of
https://github.com/ScuroNeko/mtg.git
synced 2026-08-31 19:24:02 +03:00
FILE / ScuroNeko/mtg
mtglib/internal/relay/relay.go
Исходный файл и его история в репозитории.
- 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
64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package relay
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"sync"
|
|
|
|
"github.com/9seconds/mtg/v2/essentials"
|
|
"github.com/9seconds/mtg/v2/mtglib/internal/tls"
|
|
)
|
|
|
|
var bufPool = sync.Pool{
|
|
New: func() any {
|
|
b := make([]byte, tls.MaxRecordPayloadSize)
|
|
return &b
|
|
},
|
|
}
|
|
|
|
func Relay(ctx context.Context, log Logger, telegramConn, clientConn essentials.Conn) {
|
|
defer telegramConn.Close() //nolint: errcheck
|
|
defer clientConn.Close() //nolint: errcheck
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
|
|
stop := context.AfterFunc(ctx, func() {
|
|
telegramConn.Close() //nolint: errcheck
|
|
clientConn.Close() //nolint: errcheck
|
|
})
|
|
defer stop()
|
|
|
|
closeChan := make(chan struct{})
|
|
|
|
go func() {
|
|
defer close(closeChan)
|
|
|
|
pump(log, telegramConn, clientConn, "client -> telegram")
|
|
}()
|
|
|
|
pump(log, clientConn, telegramConn, "telegram -> client")
|
|
|
|
<-closeChan
|
|
}
|
|
|
|
func pump(log Logger, src, dst essentials.Conn, direction string) {
|
|
bp := bufPool.Get().(*[]byte)
|
|
defer bufPool.Put(bp)
|
|
|
|
defer src.CloseRead() //nolint: errcheck
|
|
defer dst.CloseWrite() //nolint: errcheck
|
|
|
|
n, err := io.CopyBuffer(src, dst, *bp)
|
|
|
|
switch {
|
|
case err == nil:
|
|
log.Printf("%s has been finished", direction)
|
|
case errors.Is(err, io.EOF):
|
|
log.Printf("%s has been finished because of EOF. Written %d bytes", direction, n)
|
|
default:
|
|
log.Printf("%s has been finished (written %d bytes): %v", direction, n, err)
|
|
}
|
|
}
|