Files
Reims-Go/internal/plugin/scope.go
T
NwflowerandClaude Opus 5.5 5c1a280271 refactor(plugin): share the registry and localization boilerplate
Registering, listing and counting contributions each had one copy per
contribution kind, and so did overriding their text from language packs.
One generic helper now covers each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:20:53 -07:00

102 lines
2.2 KiB
Go

package plugin
import (
"sync"
)
// Scope tracks all reversible side effects registered by one activated plugin (§4.1).
// When the plugin is disabled, upgraded, or fails mid-activation, Dispose runs
// all registered cleanup callbacks in strict LIFO (reverse) order.
type Scope struct {
pluginID string
registry *Registry
mu sync.Mutex
disposers []func()
disposed bool
}
func newScope(pluginID string, reg *Registry) *Scope {
return &Scope{
pluginID: pluginID,
registry: reg,
}
}
// PluginID returns the owning plugin's identifier.
func (s *Scope) PluginID() string {
return s.pluginID
}
// Registry returns the parent plugin registry.
func (s *Scope) Registry() *Registry {
return s.registry
}
// OnDispose registers a cleanup function to be invoked in reverse order on disposal.
// If the scope is already disposed, fn is invoked immediately.
func (s *Scope) OnDispose(fn func()) {
if fn == nil {
return
}
s.mu.Lock()
if s.disposed {
s.mu.Unlock()
safeInvoke(fn)
return
}
s.disposers = append(s.disposers, fn)
s.mu.Unlock()
}
// Provide registers a named service with a SemVer version and auto-removes it on dispose.
func (s *Scope) Provide(name, version string, svc any) {
if s.registry == nil || name == "" {
return
}
s.registry.provideService(s.pluginID, name, version, svc)
s.OnDispose(func() {
s.registry.unprovideService(s.pluginID, name)
})
}
// Lookup fetches a provided service by name from the registry.
func (s *Scope) Lookup(name string) (any, bool) {
if s.registry == nil {
return nil, false
}
return s.registry.LookupService(name)
}
// Dispose runs all registered cleanup functions in reverse order, catching panics
// so one faulty cleanup never prevents remaining resources from being released.
func (s *Scope) Dispose() {
s.mu.Lock()
if s.disposed {
s.mu.Unlock()
return
}
s.disposed = true
fns := s.disposers
s.disposers = nil
s.mu.Unlock()
for i := len(fns) - 1; i >= 0; i-- {
safeInvoke(fns[i])
}
}
// Disposed reports whether Dispose has been called.
func (s *Scope) Disposed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.disposed
}
func safeInvoke(fn func()) {
defer func() {
_ = recover()
}()
fn()
}