mirror of
https://github.com/onyx-and-iris/vbantxt.git
synced 2026-03-07 02:29:17 +00:00
make the ratelimiting more accurate.
This commit is contained in:
parent
843f7c5e0d
commit
b506265e37
17
vbantxt.go
17
vbantxt.go
@ -4,6 +4,8 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/log"
|
||||
)
|
||||
|
||||
// VbanTxt is used to send VBAN-TXT requests to a distant Voicemeeter/Matrix.
|
||||
@ -11,6 +13,7 @@ type VbanTxt struct {
|
||||
conn io.WriteCloser
|
||||
packet packet
|
||||
ratelimit time.Duration
|
||||
lastSend time.Time
|
||||
}
|
||||
|
||||
// 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.
|
||||
// It waits for {vt.ratelimit} time before returning.
|
||||
// It enforces rate limiting by waiting only when necessary.
|
||||
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...))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error sending command (%s): %w", cmd, err)
|
||||
@ -49,8 +62,6 @@ func (vt *VbanTxt) Send(cmd string) error {
|
||||
|
||||
vt.packet.bumpFrameCounter()
|
||||
|
||||
time.Sleep(vt.ratelimit)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user