middleware: the onUsage queue holds a pointer a row, not the row

observer.Serve makes its 1024-row onUsage queue when the gateway starts,
for every user, with or without a module that has onUsage. Its slots were
whole usage.Records (~930 bytes each), so the empty queue held ~1 MB for
the life of the process: 1.08 MB of the 18.9 MB idle heap with real
accounts at 1c3056a2e. A slot is now a pointer (8 KB for the queue); a row
is copied only when a module has onUsage, as before (Ledger returns first
otherwise).

Run on mote at this head: go test ./internal/middleware ok; gofmt clean;
GOOS=windows go vet and GOOS=linux go vet -tags nogui
./internal/middleware ok.
Broken by hand: with the old points.go, TestOnUsageQueueIsSmall fails
("the queue's slots take 950272 bytes, want at most 16 KB").
Siblings: no other buffered channel of a value type is larger than 16
slots (grep make(chan in internal).
This commit is contained in:
yetone
2026-11-11 07:23:43 +08:00
parent b50910fee5
commit 9f2537f26f
2 changed files with 25 additions and 4 deletions
+4 -4
View File
@@ -362,7 +362,7 @@ func Points() usage.Observer { return &observer{} }
type observer struct {
mu sync.Mutex
queue chan usage.Record
queue chan *usage.Record // a pointer each: a 1024-row queue of Records held ~1 MB from the start, for every user, with or without an onUsage
using atomic.Bool // the set served has an onUsage
serving *set
removes []func()
@@ -384,7 +384,7 @@ func (o *observer) Ledger(r usage.Record) {
return
}
select {
case q <- r:
case q <- &r:
default:
for _, m := range s.list {
if m.hasUse {
@@ -400,7 +400,7 @@ func (o *observer) Ledger(r usage.Record) {
// Serve registers the strategies of the modules loaded and keeps them as
// the modules load again, and gives onUsage its rows, until stop.
func (o *observer) Serve() (stop func()) {
q := make(chan usage.Record, usageQueue)
q := make(chan *usage.Record, usageQueue)
done := make(chan struct{})
var wg sync.WaitGroup
o.mu.Lock()
@@ -443,7 +443,7 @@ func (o *observer) Serve() (stop func()) {
if time.Since(priced) > 5*time.Minute {
cost, priced = usage.NewCoster(), time.Now()
}
b, err := json.Marshal(rowOf(r, cost))
b, err := json.Marshal(rowOf(*r, cost))
if err != nil {
continue
}
+21
View File
@@ -0,0 +1,21 @@
package middleware
import (
"reflect"
"testing"
)
// The onUsage queue is made when the gateway starts, for every user, with
// or without a module that has onUsage: its slots stay small (a 1024-row
// queue of whole Records held ~1 MB from the start).
func TestOnUsageQueueIsSmall(t *testing.T) {
o := Points().(*observer)
stop := o.Serve()
defer stop()
o.mu.Lock()
q := o.queue
o.mu.Unlock()
if n := int(reflect.TypeOf(q).Elem().Size()) * cap(q); n > 16<<10 {
t.Fatalf("the queue's slots take %d bytes, want at most 16 KB", n)
}
}