* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package plugin
|
|
|
|
import (
|
|
"log"
|
|
"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("scope:"+s.pluginID, 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("scope:"+s.pluginID, 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(label string, fn func()) {
|
|
defer func() {
|
|
if rec := recover(); rec != nil {
|
|
log.Printf("[plugin] callback panicked (%s): %v", label, rec)
|
|
}
|
|
}()
|
|
fn()
|
|
}
|