package party import ( "fmt" "reflect" "strings" "sync" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/pact" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/postcard" "git.golem15.com/golem15/summercms/modules/signpost" ) // Plugin is the required descriptor every compiled plugin implements. type Plugin interface { ID() string Requires() []string Register(app *backpack.App) error Boot(app *backpack.App) error } // Activated is the ordered plugin list published by Activate. Commands look // it up at Run time with app.Lookup[Activated](). The plugins in it are the // application's own instances (see Activate). type Activated []Plugin // registration is one entry of the process-wide registry: a pristine copy of // a pointer-to-struct plugin, a plugin used as is, or a factory. type registration struct { plugin Plugin copyable bool id string factory func() Plugin } var ( mu sync.Mutex plugins []registration ) // Register adds a plugin to the process-wide registry. Plugins call this // from init() after a blank import; Activate selects and orders them. // // A pointer to a struct (the usual &Plugin{}) is copied: Register keeps a // pristine shallow copy and every Activate hands its application a fresh // copy of it, so a plugin keeps per-application state on its struct, never // in package variables. The value passed here is never handed to an // application. Fields set in the literal carry over; a map or pointer set // there is shared by every application, so a plugin that needs its own maps // or pointers per application uses RegisterFactory. A value plugin or a // pointer to a non-struct type is used as is. A nil plugin is ignored. func Register(p Plugin) { if p == nil { return } entry := registration{plugin: p} if v := reflect.ValueOf(p); v.Kind() == reflect.Pointer && !v.IsNil() && v.Elem().Kind() == reflect.Struct { pristine := reflect.New(v.Elem().Type()) pristine.Elem().Set(v.Elem()) if cp, ok := pristine.Interface().(Plugin); ok { entry = registration{plugin: cp, copyable: true} } } mu.Lock() defer mu.Unlock() plugins = append(plugins, entry) } // RegisterFactory adds a plugin built by fn to the process-wide registry. fn // is called on every Activate, so each application gets the plugin fn // returns; use it for plugins whose init builds maps or pointers that must // not be shared between applications. The returned plugin's ID must be id; // a nil result or another ID fails Activate. A nil fn is ignored. func RegisterFactory(id string, fn func() Plugin) { if fn == nil { return } mu.Lock() defer mu.Unlock() plugins = append(plugins, registration{id: id, factory: fn}) } // snapshot returns one fresh instance per registration, in registration // order: a new copy of each pristine pointer-to-struct plugin, the result of // each factory, and the as-is plugins. func snapshot() ([]Plugin, error) { mu.Lock() entries := make([]registration, len(plugins)) copy(entries, plugins) mu.Unlock() out := make([]Plugin, 0, len(entries)) for _, e := range entries { switch { case e.factory != nil: p := e.factory() if p == nil { return nil, fmt.Errorf("party: factory for %q returned nil", e.id) } if got := p.ID(); got != e.id { return nil, fmt.Errorf("party: factory for %q returned plugin %q", e.id, got) } out = append(out, p) case e.copyable: src := reflect.ValueOf(e.plugin) fresh := reflect.New(src.Elem().Type()) fresh.Elem().Set(src.Elem()) out = append(out, fresh.Interface().(Plugin)) default: out = append(out, e.plugin) } } return out, nil } // Activate resolves ids in manifest order, topologically sorts Requires(), // then runs every Register before any Boot. Each call works on fresh plugin // instances (see Register and RegisterFactory), so two applications // activated in one process, also concurrently, never share a plugin struct. func Activate(app *backpack.App, ids []string) ([]Plugin, error) { if app == nil { return nil, fmt.Errorf("party: app is nil") } instances, err := snapshot() if err != nil { return nil, err } return activate(instances, app, ids) } func activate(registered []Plugin, app *backpack.App, ids []string) ([]Plugin, error) { byID := make(map[string]Plugin, len(registered)) for _, p := range registered { if p == nil { continue } id := p.ID() if id == "" { return nil, fmt.Errorf("party: registered plugin has empty id") } if _, exists := byID[id]; exists { return nil, fmt.Errorf("party: duplicate plugin id %q", id) } byID[id] = p } seen := make(map[string]struct{}, len(ids)) selected := make([]Plugin, 0, len(ids)) index := make(map[string]int, len(ids)) for _, id := range ids { if id == "" { return nil, fmt.Errorf("party: empty plugin id in manifest") } if _, dup := seen[id]; dup { return nil, fmt.Errorf("party: duplicate plugin id %q", id) } seen[id] = struct{}{} p, ok := byID[id] if !ok { return nil, fmt.Errorf("party: plugin %q is not registered", id) } index[id] = len(selected) selected = append(selected, p) } for _, p := range selected { for _, req := range p.Requires() { if _, ok := seen[req]; !ok { return nil, fmt.Errorf("party: plugin %q requires %q, which is not registered", p.ID(), req) } } } ordered, err := topoSort(selected, index) if err != nil { return nil, err } orderedIDs := make([]string, len(ordered)) for i, p := range ordered { orderedIDs[i] = p.ID() } app.SetPlugins(orderedIDs) if err := app.Publish(Activated(ordered)); err != nil { return nil, fmt.Errorf("party: %w", err) } for _, p := range ordered { if hc, ok := p.(pact.HasConfig); ok && app.Config != nil { if err := app.Config.MergePlugin(p.ID(), hc.ConfigFS()); err != nil { return nil, fmt.Errorf("party: config %s: %w", p.ID(), err) } } } for _, p := range ordered { if err := p.Register(app); err != nil { return nil, fmt.Errorf("party: register %s: %w", p.ID(), err) } } if err := phrasebook.Activate(app, ordered); err != nil { return nil, fmt.Errorf("party: lang: %w", err) } if err := postcard.Activate(app, ordered); err != nil { return nil, fmt.Errorf("party: mail: %w", err) } // Menu item types (pact.HasMenuItemTypes) are collected after every // Register and before the first Boot, so a plugin's Boot can read the // registry. if err := signpost.Activate(app, ordered); err != nil { return nil, fmt.Errorf("party: menu item types: %w", err) } for _, p := range ordered { if err := postcard.BootPlugin(app, p); err != nil { return nil, fmt.Errorf("party: boot %s: %w", p.ID(), err) } if err := p.Boot(app); err != nil { return nil, fmt.Errorf("party: boot %s: %w", p.ID(), err) } } return ordered, nil } func topoSort(plugins []Plugin, index map[string]int) ([]Plugin, error) { byID := make(map[string]Plugin, len(plugins)) indeg := make(map[string]int, len(plugins)) dependents := make(map[string][]string, len(plugins)) for _, p := range plugins { byID[p.ID()] = p indeg[p.ID()] = 0 } for _, p := range plugins { seenReq := make(map[string]struct{}) for _, req := range p.Requires() { if _, ok := seenReq[req]; ok { continue } seenReq[req] = struct{}{} if _, ok := byID[req]; !ok { continue } indeg[p.ID()]++ dependents[req] = append(dependents[req], p.ID()) } } ready := make([]string, 0, len(plugins)) for _, p := range plugins { if indeg[p.ID()] == 0 { ready = append(ready, p.ID()) } } out := make([]Plugin, 0, len(plugins)) for len(ready) > 0 { id := ready[0] ready = ready[1:] out = append(out, byID[id]) next := append([]string(nil), dependents[id]...) sortByIndex(next, index) for _, dep := range next { indeg[dep]-- if indeg[dep] == 0 { ready = insertByIndex(ready, dep, index) } } } if len(out) != len(plugins) { leftover := make([]string, 0) done := make(map[string]struct{}, len(out)) for _, p := range out { done[p.ID()] = struct{}{} } for _, p := range plugins { if _, ok := done[p.ID()]; !ok { leftover = append(leftover, p.ID()) } } return nil, fmt.Errorf("party: dependency cycle involving %s", strings.Join(leftover, ", ")) } return out, nil } func sortByIndex(ids []string, index map[string]int) { for i := 1; i < len(ids); i++ { j := i for j > 0 && index[ids[j]] < index[ids[j-1]] { ids[j], ids[j-1] = ids[j-1], ids[j] j-- } } } func insertByIndex(ready []string, id string, index map[string]int) []string { at := len(ready) for i, existing := range ready { if index[id] < index[existing] { at = i break } } ready = append(ready, "") copy(ready[at+1:], ready[at:]) ready[at] = id return ready }