Convert our usage of go-diodes into a simplified, generic version

This commit is contained in:
Deluan 2023-04-01 21:53:45 -04:00
parent 1c7fb74a1d
commit e6bfa2bb0b
5 changed files with 108 additions and 93 deletions

38
utils/diodes/diodes.go Normal file
View file

@ -0,0 +1,38 @@
package diodes
import (
"context"
"code.cloudfoundry.org/go-diodes"
)
type Diode[T any] struct {
d *diodes.Waiter
}
type Alerter = diodes.Alerter
type AlertFunc = diodes.AlertFunc
func New[T any](ctx context.Context, size int, alerter Alerter) *Diode[T] {
return &Diode[T]{
d: diodes.NewWaiter(diodes.NewOneToOne(size, alerter), diodes.WithWaiterContext(ctx)),
}
}
func (d *Diode[T]) Put(data T) {
d.d.Set(diodes.GenericDataType(&data))
}
func (d *Diode[T]) TryNext() (*T, bool) {
data, ok := d.d.TryNext()
if !ok {
return nil, ok
}
return (*T)(data), true
}
func (d *Diode[T]) Next() *T {
data := d.d.Next()
return (*T)(data)
}

View file

@ -0,0 +1,62 @@
package diodes_test
import (
"context"
"testing"
"github.com/navidrome/navidrome/tests"
. "github.com/navidrome/navidrome/utils/diodes"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestDiodes(t *testing.T) {
tests.Init(t, false)
RegisterFailHandler(Fail)
RunSpecs(t, "Diodes Suite")
}
var _ = Describe("Diode", func() {
type message struct {
data string
}
var diode *Diode[message]
var ctx context.Context
var ctxCancel context.CancelFunc
var missed int
BeforeEach(func() {
missed = 0
ctx, ctxCancel = context.WithCancel(context.Background())
diode = New[message](ctx, 2, AlertFunc(func(m int) { missed = m }))
})
It("enqueues the data correctly", func() {
diode.Put(message{data: "1"})
diode.Put(message{data: "2"})
Expect(diode.Next()).To(Equal(&message{data: "1"}))
Expect(diode.Next()).To(Equal(&message{data: "2"}))
Expect(missed).To(BeZero())
})
It("drops messages when Diode is full", func() {
diode.Put(message{data: "1"})
diode.Put(message{data: "2"})
diode.Put(message{data: "3"})
next, ok := diode.TryNext()
Expect(ok).To(BeTrue())
Expect(next).To(Equal(&message{data: "3"}))
_, ok = diode.TryNext()
Expect(ok).To(BeFalse())
Expect(missed).To(Equal(2))
})
It("returns nil when Diode is empty and the context is canceled", func() {
diode.Put(message{data: "1"})
ctxCancel()
Expect(diode.Next()).To(Equal(&message{data: "1"}))
Expect(diode.Next()).To(BeNil())
})
})