Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:28:51 +01:00
1 parent 7b6db17870
commit 0295eb1ad2
125 files changed
+59376

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
package player
import (
"fmt"
"sort"
"sync"
"git.maze.io/go/bragi/config"
)
// NotFound signals the player can not be found.
type NotFound struct {
Name string
}
func (err NotFound) Error() string {
return fmt.Sprintf("player: %q can not be found", err.Name)
}
// Factory is a function that can instantiate a new Player.
type Factory func(*config.Player) (Player, error)
// Detector checks if this player is available.
type Detector func() bool
type detector struct {
Name string
New Factory
Detect Detector
Priority int
}
var (
// protocols holds the per protocol factories
protocols = new(sync.Map)
detectors []detector
// instances holds the named players
instances = new(sync.Map)
)
// Register a new protocol factory.
func Register(name string, f Factory, d Detector, priority int) {
if _, loaded := protocols.LoadOrStore(name, f); loaded {
panic(fmt.Sprintf("player type %q already registered", name))
}
if d != nil {
detectors = append(detectors, detector{
Name: name,
New: f,
Detect: d,
Priority: priority,
})
sort.Slice(detectors, func(i, j int) bool {
return detectors[i].Priority < detectors[j].Priority
})
}
}
// New returns a player factory for the requested type.
func New(config *config.Player) (Player, error) {
f, ok := protocols.Load(config.Protocol)
if !ok {
return nil, NotFound{Name: config.Protocol}
}
p, err := f.(Factory)(config)
if err != nil {
return nil, err
}
instances.Store(config.Name, p)
return p, nil
}
// RegisterInstance registers a new player instance by name.
func RegisterInstance(name string, p Player) {
if _, loaded := instances.LoadOrStore(name, p); loaded {
panic(fmt.Sprintf("player instance %q already registered", name))
}
}
// Lookup a previously registered instance.
func Lookup(name string) (Player, error) {
f, ok := instances.Load(name)
if ok {
return f.(Player), nil
}
return nil, NotFound{Name: name}
}
// Detect what player is available.
func Detect() (name string, factory Factory) {
for _, d := range detectors {
if d.Detect() {
return d.Name, d.New
}
}
return "", nil
}