make the ratelimiting more accurate.

This commit is contained in:
onyx-and-iris 2026-03-07 00:52:58 +00:00
parent 843f7c5e0d
commit b506265e37

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"io" "io"
"time" "time"
"github.com/charmbracelet/log"
) )
// VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix. // VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix.
@ -11,6 +13,7 @@ type VbanTxt struct {
conn io.WriteCloser conn io.WriteCloser
packet packet packet packet
ratelimit time.Duration ratelimit time.Duration
lastSend time.Time
} }
// New constructs a fully formed VbanTxt instance. This is the package's entry point. // New constructs a fully formed VbanTxt instance. This is the package's entry point.
@ -40,8 +43,18 @@ func New(host string, port int, streamname string, options ...Option) (*VbanTxt,
} }
// Send is responsible for firing each VBAN-TXT request. // Send is responsible for firing each VBAN-TXT request.
// It waits for {vt.ratelimit} time before returning. // It enforces rate limiting by waiting only when necessary.
func (vt *VbanTxt) Send(cmd string) error { func (vt *VbanTxt) Send(cmd string) error {
if elapsed := time.Since(vt.lastSend); elapsed < vt.ratelimit {
log.Debugf(
"Rate limit in effect. Waiting for %v before sending next command.",
vt.ratelimit-elapsed,
)
time.Sleep(vt.ratelimit - elapsed)
}
vt.lastSend = time.Now()
_, err := vt.conn.Write(append(vt.packet.header(), cmd...)) _, err := vt.conn.Write(append(vt.packet.header(), cmd...))
if err != nil { if err != nil {
return fmt.Errorf("error sending command (%s): %w", cmd, err) return fmt.Errorf("error sending command (%s): %w", cmd, err)
@ -49,8 +62,6 @@ func (vt *VbanTxt) Send(cmd string) error {
vt.packet.bumpFrameCounter() vt.packet.bumpFrameCounter()
time.Sleep(vt.ratelimit)
return nil return nil
} }