plugins

package
v1.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2026 License: Apache-2.0 Imports: 15 Imported by: 23

README

Lynx Plugin SDK

The plugins package provides the core plugin system SDK for the Lynx framework. It defines interfaces, base implementations, and utilities for building extensible plugins.

Overview

This package contains:

  • Plugin Interface - Core interface that all plugins must implement
  • BasePlugin - Base implementation providing common plugin functionality
  • Runtime Interface - Runtime environment for plugins to access resources and events
  • Event System - Event types and handling for inter-plugin communication
  • Dependency Management - Plugin dependency resolution and version constraints
  • Health Checks - Health monitoring and reporting utilities

File Structure

File Description
plugin.go Core Plugin interface, Runtime interface, and related types
base.go TypedBasePlugin and BasePlugin base implementations
unified_runtime.go UnifiedRuntime implementation with resource and event management
events.go Event types and priority definitions
event_adapter.go Event bus adapter for unified event handling
deps.go Dependency, DependencyGraph, and version constraint utilities
errors.go Error types and error handling utilities
health.go HealthReport and health check utilities
version.go Version comparison and semantic versioning utilities
id.go Plugin ID generation and validation utilities
conflict_resolver.go Plugin conflict resolution strategies
upg.go Plugin upgrade capabilities and strategies

Core Interfaces

Plugin Interface
type Plugin interface {
    Metadata      // ID, Name, Version, Description
    Lifecycle     // Initialize, Start, Stop
    LifecycleSteps // InitializeResources, StartupTasks, CleanupTasks
    DependencyAware // GetDependencies, AddDependency
}
Runtime Interface
type Runtime interface {
    // Resource Management
    GetSharedResource(name string) (any, error)
    RegisterSharedResource(name string, resource any) error
    GetPrivateResource(name string) (any, error)
    RegisterPrivateResource(name string, resource any) error
    
    // Configuration
    GetConfig() config.Config
    SetConfig(config.Config)
    
    // Event System
    EmitEvent(event PluginEvent)
    AddListener(listener EventListener, filter *EventFilter)
    RemoveListener(listener EventListener)
    
    // Plugin Context
    WithPluginContext(pluginName string) Runtime
    GetCurrentPluginContext() string
}

Plugin Lifecycle

┌─────────────┐
│  Inactive   │  Plugin loaded, not initialized
└──────┬──────┘
       │ Initialize()
       ▼
┌─────────────┐
│Initializing │  Setting up resources
└──────┬──────┘
       │ Start()
       ▼
┌─────────────┐
│   Active    │  Fully operational
└──────┬──────┘
       │ Stop()
       ▼
┌─────────────┐
│  Stopping   │  Cleaning up
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Terminated  │  Shutdown complete
└─────────────┘
Plugin Status
Status Description
StatusInactive Loaded but not initialized
StatusInitializing Currently initializing
StatusActive Fully operational
StatusSuspended Temporarily paused
StatusStopping Shutting down
StatusTerminated Gracefully shut down
StatusFailed Fatal error occurred
StatusUpgrading Being upgraded
StatusRollback Rolling back from failed upgrade

Creating a Plugin

Basic Plugin
package myplugin

import (
    "github.com/go-lynx/lynx/plugins"
)

type MyPlugin struct {
    *plugins.BasePlugin
    // Your fields here
}

func NewMyPlugin() *MyPlugin {
    return &MyPlugin{
        BasePlugin: plugins.NewBasePlugin(
            "my-plugin-v1",       // ID
            "my-plugin",          // Name
            "My awesome plugin",  // Description
            "1.0.0",              // Version
            "lynx.myplugin",      // Config prefix
            100,                  // Weight (higher = load first)
        ),
    }
}

// InitializeResources sets up plugin resources
func (p *MyPlugin) InitializeResources(rt plugins.Runtime) error {
    // Access shared resources
    db, err := rt.GetSharedResource("database")
    if err != nil {
        return err
    }
    
    // Register your own resources
    return rt.RegisterSharedResource("my-service", myService)
}

// StartupTasks performs startup logic
func (p *MyPlugin) StartupTasks() error {
    // Start your services
    return nil
}

// CleanupTasks performs cleanup logic
func (p *MyPlugin) CleanupTasks() error {
    // Clean up resources
    return nil
}

// CheckHealth performs health check
func (p *MyPlugin) CheckHealth() error {
    // Check if plugin is healthy
    return nil
}
Typed Plugin (with type safety)
type MyTypedPlugin struct {
    *plugins.TypedBasePlugin[*MyConfig]
}

func NewMyTypedPlugin(config *MyConfig) *MyTypedPlugin {
    return &MyTypedPlugin{
        TypedBasePlugin: plugins.NewTypedBasePlugin(
            "my-typed-plugin-v1",
            "my-typed-plugin",
            "Type-safe plugin",
            "1.0.0",
            "lynx.mytypedplugin",
            100,
            config, // Type-safe config
        ),
    }
}

// Access typed config
func (p *MyTypedPlugin) GetConfig() *MyConfig {
    return p.GetTypedInstance()
}
Context-Aware Plugin

The default TypedBasePlugin implementations of StartContext, StopContext, and InitializeContext only run the non-context method in a goroutine and return when the context is done; they do not cancel the running Initialize/Start/Stop. For real cancellation, implement LifecycleWithContext on your plugin and check ctx.Done() inside your logic.

For plugins that need to respect context cancellation and timeouts:

type ContextAwarePlugin struct {
    *plugins.BasePlugin
}

// InitializeContext with context support
func (p *ContextAwarePlugin) InitializeContext(ctx context.Context, plugin plugins.Plugin, rt plugins.Runtime) error {
    select {
    case <-ctx.Done():
        return ctx.Err()
    default:
        return p.Initialize(plugin, rt)
    }
}

// StartContext with context support
func (p *ContextAwarePlugin) StartContext(ctx context.Context, plugin plugins.Plugin) error {
    // Use ctx for cancellation
    return nil
}

// StopContext with context support
func (p *ContextAwarePlugin) StopContext(ctx context.Context, plugin plugins.Plugin) error {
    return nil
}

// IsContextAware marks plugin as truly context-aware
func (p *ContextAwarePlugin) IsContextAware() bool {
    return true
}

Dependencies

Dependency declaration timing

Important: The framework resolves load order by calling GetDependencies() on each plugin before any plugin is initialized. Therefore:

  • Declare required dependencies in your plugin's constructor (e.g. in NewMyPlugin()), or in a method that runs before the plugin list is passed to TopologicalSort.
  • Do not rely on adding dependencies only inside InitializeResources(rt) for load-order resolution; by then the sort has already been done. You may still call AddDependency in InitializeResources for optional/bookkeeping purposes, but required dependencies used for ordering must be available from GetDependencies() as soon as the plugin is created.

This ensures the dependency graph is complete when the manager builds the topological order for initialization and start.

Declaring Dependencies
// Recommended: declare required dependencies in constructor so GetDependencies() is complete before TopologicalSort.
func NewMyPlugin() *MyPlugin {
    p := &MyPlugin{
        BasePlugin: plugins.NewBasePlugin(...),
    }
    p.AddDependency(plugins.Dependency{
        ID: "database-plugin-v1",
        Name: "database-plugin",
        Type: plugins.DependencyTypeRequired,
        Required: true,
        VersionConstraint: &plugins.VersionConstraint{MinVersion: "1.0.0", MaxVersion: "2.0.0"},
    })
    return p
}

func (p *MyPlugin) InitializeResources(rt plugins.Runtime) error {
    // Optional: add more dependencies here only if they are not needed for load order
    p.AddDependency(plugins.Dependency{
        ID:       "cache-plugin-v1",
        Name:     "cache-plugin",
        Type:     plugins.DependencyTypeOptional,
        Required: false,
    })
    return nil
}
Dependency Types
Type Description
DependencyTypeRequired Must be present and loaded first
DependencyTypeOptional Optional, loaded if available
DependencyTypeConflicts Cannot coexist with this plugin
DependencyTypeProvides This plugin provides the capability
Version Constraints
VersionConstraint{
    MinVersion:      "1.0.0",          // Minimum version (>=)
    MaxVersion:      "2.0.0",          // Maximum version (<=)
    ExactVersion:    "1.5.0",          // Exact version required
    ExcludeVersions: []string{"1.3.0"}, // Excluded versions
}

Event System

Event Types

Lifecycle Events:

  • EventPluginInitializing, EventPluginInitialized
  • EventPluginStarting, EventPluginStarted
  • EventPluginStopping, EventPluginStopped

Health Events:

  • EventHealthCheckStarted, EventHealthCheckDone, EventHealthCheckFailed
  • EventHealthStatusOK, EventHealthStatusWarning, EventHealthStatusCritical

Configuration Events:

  • EventConfigurationChanged, EventConfigurationApplied, EventConfigurationInvalid

Upgrade Events:

  • EventUpgradeInitiated, EventUpgradeCompleted, EventUpgradeFailed
  • EventRollbackInitiated, EventRollbackCompleted, EventRollbackFailed
Emitting Events
p.EmitEvent(plugins.PluginEvent{
    Type:     plugins.EventPluginStarted,
    Priority: plugins.PriorityNormal,
    Source:   "MyPlugin",
    Category: "lifecycle",
    Metadata: map[string]any{
        "startup_time_ms": startupTime,
    },
})
Listening for Events
type MyListener struct {
    id string
}

func (l *MyListener) HandleEvent(event plugins.PluginEvent) {
    // Handle the event
}

func (l *MyListener) GetListenerID() string {
    return l.id
}

// Register listener
runtime.AddListener(&MyListener{id: "my-listener"}, &plugins.EventFilter{
    Types: []plugins.EventType{plugins.EventPluginStarted},
})

Resource Management

Shared Resources
// Register shared resource (accessible by all plugins)
runtime.RegisterSharedResource("database", dbConnection)

// Get shared resource
db, err := runtime.GetSharedResource("database")
Private Resources
// Get plugin-scoped runtime
pluginRuntime := runtime.WithPluginContext("my-plugin")

// Register private resource (isolated per plugin)
pluginRuntime.RegisterPrivateResource("local-cache", cache)

// Get private resource
cache, err := pluginRuntime.GetPrivateResource("local-cache")
Type-Safe Resource Access
// Get resource with type safety
db, err := plugins.GetTypedResource[*sql.DB](runtime, "database")
if err != nil {
    return err
}
// db is already *sql.DB type

Health Reporting

type HealthReport struct {
    Status    string          // "healthy", "unhealthy", "suspended", etc.
    Message   string          // Human-readable message
    Details   map[string]any  // Additional details
    Timestamp int64           // Unix timestamp
}

// Get health report
report := plugin.GetHealth()

Upgrade Capabilities

// Supported upgrade capabilities
const (
    UpgradeNone    // No runtime upgrades supported
    UpgradeConfig  // Can update config without restart
    UpgradeVersion // Can upgrade version without restart
    UpgradeReplace // Can be completely replaced at runtime
)

// Prepare for upgrade
plugin.PrepareUpgrade("2.0.0")

// Execute upgrade
plugin.ExecuteUpgrade("2.0.0")

// Rollback if needed
plugin.RollbackUpgrade("1.0.0")

Best Practices

  1. Always declare dependencies - Use AddDependency() for explicit dependency management
  2. Implement health checks - Override CheckHealth() for proper monitoring
  3. Use context-aware methods - Implement LifecycleWithContext for timeout support
  4. Emit lifecycle events - Help other plugins track your state
  5. Clean up resources - Implement proper CleanupTasks() to avoid leaks
  6. Use typed resources - Prefer GetTypedResource[T]() for type safety
  7. Set appropriate weight - Higher weight plugins load first

Example Plugins

See the lynx-plugins repository for production-ready plugin examples:

  • lynx-http - HTTP server plugin
  • lynx-grpc - gRPC server/client plugin
  • lynx-mysql - MySQL database plugin
  • lynx-redis - Redis client plugin
  • lynx-polaris - Polaris service mesh plugin

License

Apache License 2.0

Documentation

Overview

Package plugins provides the core plugin system for the Lynx framework.

Package plugins provides a plugin system for extending application functionality.

Package plugins provides the core plugin system for the Lynx framework.

Runtime is the main environment interface for plugins; the default implementation is UnifiedRuntime (see unified_runtime.go). Runtime composes ResourceManager, ConfigProvider, LogProvider, EventEmitter, and plugin-context helpers.

Index

Constants

View Source
const (
	// PriorityLow indicates minimal impact events that can be processed later
	PriorityLow = 0
	// PriorityNormal indicates standard events requiring routine processing
	PriorityNormal = 1
	// PriorityHigh indicates important events needing prompt attention
	PriorityHigh = 2
	// PriorityCritical indicates urgent events requiring immediate handling
	PriorityCritical = 3
)

Priority levels for plugin events

View Source
const (
	// EventPluginInitializing indicates the plugin is starting initialization.
	// Triggered when plugin begins loading resources and establishing connections.
	EventPluginInitializing = "plugin.initializing"

	// EventPluginInitialized indicates the plugin completed initialization.
	// Triggered when all resources are loaded and connections established.
	EventPluginInitialized = "plugin.initialized"

	// EventPluginStarting indicates the plugin is beginning its operations.
	// Triggered when core functionality is about to begin.
	EventPluginStarting = "plugin.starting"

	// EventPluginStarted indicates the plugin is fully operational.
	// Triggered when all systems are running and ready to handle requests.
	EventPluginStarted = "plugin.started"

	// EventPluginStopping indicates the plugin is beginning shutdown.
	// Triggered when shutdown command is received and cleanup begins.
	EventPluginStopping = "plugin.stopping"

	// EventPluginStopped indicates the plugin completed shutdown.
	// Triggered when all resources are released and connections closed.
	EventPluginStopped = "plugin.stopped"
)

Plugin lifecycle event types for comprehensive system monitoring

View Source
const (
	// EventHealthCheckStarted indicates a health check operation has begun.
	// Triggered when the health check routine starts executing.
	EventHealthCheckStarted = "health.check.started"

	// EventHealthCheckRunning indicates a health check is in progress.
	// Triggered during the execution of health check procedures.
	EventHealthCheckRunning = "health.check.running"

	// EventHealthCheckDone indicates a health check has completed.
	// Triggered when all health check procedures have finished.
	EventHealthCheckDone = "health.check.done"

	// EventHealthStatusOK indicates the plugin is healthy.
	// Triggered when all health metrics are within normal ranges.
	EventHealthStatusOK = "health.status.ok"

	// EventHealthStatusWarning indicates potential health issues.
	// Triggered when health metrics show concerning trends.
	EventHealthStatusWarning = "health.status.warning"

	// EventHealthStatusCritical indicates severe health issues.
	// Triggered when health metrics exceed critical thresholds.
	EventHealthStatusCritical = "health.status.critical"

	// EventHealthStatusUnknown indicates health status cannot be determined.
	// Triggered when health check procedures fail to complete.
	EventHealthStatusUnknown = "health.status.unknown"

	// EventHealthMetricsChanged indicates a change in health metrics.
	// Triggered when monitored metrics show significant changes.
	EventHealthMetricsChanged = "health.metrics.changed"

	// EventHealthThresholdHit indicates metrics exceeded defined thresholds.
	// Triggered when health metrics cross warning or critical levels.
	EventHealthThresholdHit = "health.metrics.threshold"

	// EventHealthStatusChanged indicates overall health status change.
	// Triggered when the aggregate health status transitions.
	EventHealthStatusChanged = "health.status.changed"

	// EventHealthCheckFailed indicates health check operation failure.
	// Triggered when health check procedures encounter errors.
	EventHealthCheckFailed = "health.check.failed"
)

Health check event types for monitoring plugin health status

View Source
const (
	// EventResourceExhausted indicates critical resource depletion.
	// Triggered when system resources reach critical levels.
	EventResourceExhausted = "resource.exhausted"

	// EventPerformanceDegraded indicates performance deterioration.
	// Triggered when system performance metrics decline significantly.
	EventPerformanceDegraded = "performance.degraded"
)

Resource event types for monitoring system resources

View Source
const (
	// EventConfigurationChanged indicates configuration update initiation.
	// Triggered when new configuration is being applied.
	EventConfigurationChanged = "config.changed"

	// EventConfigurationInvalid indicates invalid configuration.
	// Triggered when configuration validation fails.
	EventConfigurationInvalid = "config.invalid"

	// EventConfigurationApplied indicates successful configuration update.
	// Triggered when new configuration is active and verified.
	EventConfigurationApplied = "config.applied"
)

Configuration event types for managing plugin configuration

View Source
const (
	// EventDependencyMissing indicates missing required dependency.
	// Triggered when required plugin or resource is unavailable.
	EventDependencyMissing = "dependency.missing"

	// EventDependencyStatusChanged indicates dependency state change.
	// Triggered when dependent plugin changes operational state.
	EventDependencyStatusChanged = "dependency.status.changed"

	// EventDependencyError indicates dependency-related error.
	// Triggered when dependency fails or becomes unstable.
	EventDependencyError = "dependency.error"
)

Dependency event types for managing plugin dependencies

View Source
const (
	// EventUpgradeAvailable indicates new version availability.
	// Triggered when update check finds newer version.
	EventUpgradeAvailable = "upgrade.available"

	// EventUpgradeInitiated indicates upgrade process start.
	// Triggered when upgrade sequence begins.
	EventUpgradeInitiated = "upgrade.initiated"

	// EventUpgradeValidating indicates upgrade validation.
	// Triggered when validating system state before upgrade.
	EventUpgradeValidating = "upgrade.validating"

	// EventUpgradeInProgress indicates that the upgrade process is ongoing.
	// Triggered when the upgrade process is in progress.
	EventUpgradeInProgress = "upgrade.in_progress"

	// EventUpgradeCompleted indicates successful upgrade.
	// Triggered when new version is installed and verified.
	EventUpgradeCompleted = "upgrade.completed"

	// EventUpgradeFailed indicates failed upgrade attempt.
	// Triggered when upgrade process encounters error.
	EventUpgradeFailed = "upgrade.failed"

	// EventRollbackInitiated indicates version rollback start.
	// Triggered when rollback to previous version begins.
	EventRollbackInitiated = "rollback.initiated"

	// EventRollbackInProgress indicates that the rollback process is ongoing.
	// Triggered when the rollback process has started and is in progress.
	EventRollbackInProgress = "rollback.in_progress"

	// EventRollbackCompleted indicates successful rollback.
	// Triggered when previous version is restored.
	EventRollbackCompleted = "rollback.completed"

	// EventRollbackFailed indicates failed rollback attempt.
	// Triggered when unable to restore previous version.
	EventRollbackFailed = "rollback.failed"
)

Upgrade event types for managing plugin versions

View Source
const (
	// EventSecurityViolation indicates security policy breach.
	// Triggered when security rules are violated.
	EventSecurityViolation = "security.violation"

	// EventAuthenticationFailed indicates failed authentication.
	// Triggered when invalid credentials are used.
	EventAuthenticationFailed = "auth.failed"

	// EventAuthorizationDenied indicates unauthorized access.
	// Triggered when insufficient permissions are detected.
	EventAuthorizationDenied = "auth.denied"
)

Security event types for monitoring security-related events

View Source
const (
	// EventResourceCreated indicates new resource allocation.
	// Triggered when new resource is successfully created.
	EventResourceCreated = "resource.created"

	// EventResourceModified indicates resource modification.
	// Triggered when existing resource is updated.
	EventResourceModified = "resource.modified"

	// EventResourceDeleted indicates resource removal.
	// Triggered when resource is successfully deleted.
	EventResourceDeleted = "resource.deleted"

	// EventResourceUnavailable indicates resource access failure.
	// Triggered when resource becomes inaccessible.
	EventResourceUnavailable = "resource.unavailable"
)

Resource lifecycle event types

View Source
const (
	// EventErrorOccurred indicates error detection.
	// Triggered when system encounters an error condition.
	EventErrorOccurred = "error.occurred"

	// EventErrorResolved indicates error recovery.
	// Triggered when error condition is successfully resolved.
	EventErrorResolved = "error.resolved"

	// EventPanicRecovered indicates panic recovery.
	// Triggered when system recovers from panic condition.
	EventPanicRecovered = "panic.recovered"
)

Error event types for error handling and recovery

View Source
const (
	// DefaultOrg is the default organization identifier
	DefaultOrg = "go-lynx"
	// ComponentType represents the plugin component type
	ComponentType = "plugin"
)

ID format constants

Variables

View Source
var (
	// ErrPluginNotFound indicates that a requested plugin could not be found in the system
	// This error occurs when attempting to access or operate on a non-existent plugin
	ErrPluginNotFound = NewStandardError(ErrorCodePluginNotFound, "plugin not found", "The requested plugin does not exist in the system registry")

	// ErrPluginAlreadyExists indicates an attempt to register a plugin with an ID that is already in use
	// This error helps maintain unique plugin identifiers across the system
	ErrPluginAlreadyExists = NewStandardError(ErrorCodePluginAlreadyExists, "plugin already exists", "A plugin with this ID is already registered in the system")

	// ErrPluginNotInitialized indicates an attempt to use a plugin that hasn't been properly initialized
	// Operations on uninitialized plugins are not allowed to prevent undefined behavior
	ErrPluginNotInitialized = NewStandardError(ErrorCodePluginNotInitialized, "plugin not initialized", "The plugin must be initialized before performing this operation")

	// ErrPluginNotActive indicates an attempt to use a plugin that is not in the active state
	// The plugin must be in StatusActive to perform the requested operation
	ErrPluginNotActive = NewStandardError(ErrorCodePluginNotActive, "plugin not active", "The plugin must be in active state to perform this operation")

	// ErrPluginAlreadyActive indicates an attempt to start an already active plugin
	// Prevents duplicate activation of plugins
	ErrPluginAlreadyActive = NewStandardError(ErrorCodePluginAlreadyActive, "plugin already active", "The plugin is already in active state")

	// ErrInvalidPluginID indicates that the provided plugin ID is invalid
	// Plugin IDs must follow specific formatting rules and be non-empty
	ErrInvalidPluginID = NewStandardError(ErrorCodeInvalidPluginID, "invalid plugin ID", "Plugin ID must be non-empty and follow naming conventions")

	// ErrInvalidPluginVersion indicates that the provided plugin version is invalid
	// Version strings must follow semantic versioning format
	ErrInvalidPluginVersion = NewStandardError(ErrorCodeInvalidPluginVersion, "invalid plugin version", "Plugin version must follow semantic versioning format (e.g., 1.0.0)")

	// ErrInvalidPluginConfig indicates that the provided plugin configuration is invalid
	// Configuration must meet the plugin's specific requirements
	ErrInvalidPluginConfig = NewStandardError(ErrorCodeInvalidPluginConfig, "invalid plugin configuration", "The provided configuration does not meet plugin requirements")

	// ErrInvalidConfiguration indicates that the provided configuration is not of the expected type
	// This error occurs when attempting to configure a plugin with an incompatible configuration type
	ErrInvalidConfiguration = NewStandardError(ErrorCodeInvalidConfiguration, "invalid configuration type", "Configuration type does not match expected plugin configuration interface")

	// ErrPluginDependencyNotMet indicates that one or more plugin dependencies are not satisfied
	// All required dependencies must be available and properly configured
	ErrPluginDependencyNotMet = NewStandardError(ErrorCodePluginDependencyNotMet, "plugin dependency not met", "One or more required plugin dependencies are missing or not properly configured")

	// ErrPluginUpgradeNotSupported indicates that the plugin does not support the requested upgrade operation
	// The plugin must implement the Upgradable interface and support the specific upgrade capability
	ErrPluginUpgradeNotSupported = NewStandardError(ErrorCodePluginUpgradeNotSupported, "plugin upgrade not supported", "The plugin does not implement upgrade capabilities")

	// ErrPluginUpgradeFailed indicates that the plugin upgrade process failed
	// Contains details about the specific failure in upgrade process
	ErrPluginUpgradeFailed = NewStandardError(ErrorCodePluginUpgradeFailed, "plugin upgrade failed", "The plugin upgrade process encountered an error")

	// ErrPluginResourceNotFound indicates that a requested plugin resource is not available
	// The resource must be registered before it can be accessed
	ErrPluginResourceNotFound = NewStandardError(ErrorCodePluginResourceNotFound, "plugin resource not found", "The requested plugin resource is not available or not registered")

	// ErrPluginResourceInvalid indicates that a plugin resource is in an invalid state
	// The resource must be properly initialized and maintained
	ErrPluginResourceInvalid = NewStandardError(ErrorCodePluginResourceInvalid, "plugin resource invalid", "The plugin resource is in an invalid or corrupted state")

	// ErrPluginOperationTimeout indicates that a plugin operation exceeded its time limit
	// Operations must complete within their specified timeout period
	ErrPluginOperationTimeout = NewStandardError(ErrorCodePluginOperationTimeout, "plugin operation timeout", "The plugin operation exceeded the specified timeout period")

	// ErrPluginOperationCancelled indicates that a plugin operation was cancelled
	// The operation was terminated before completion, either by user request or system action
	ErrPluginOperationCancelled = NewStandardError(ErrorCodePluginOperationCancelled, "plugin operation cancelled", "The plugin operation was cancelled before completion")

	// ErrPluginHealthCheckFailed indicates that the plugin's health check failed
	// The plugin is in an unhealthy state and may need attention
	ErrPluginHealthCheckFailed = NewStandardError(ErrorCodePluginHealthCheckFailed, "plugin health check failed", "The plugin health check indicates an unhealthy state")

	// ErrPluginSecurityViolation indicates a security-related violation in the plugin
	// Security policies or constraints have been breached
	ErrPluginSecurityViolation = NewStandardError(ErrorCodePluginSecurityViolation, "plugin security violation", "A security policy or constraint has been violated")
)

Common error variables for plugin-related operations

Functions

func FormatErrorForDeveloper added in v1.5.0

func FormatErrorForDeveloper(err error) string

FormatErrorForDeveloper formats an error message for developer debugging

func FormatErrorForUser added in v1.5.0

func FormatErrorForUser(err error) string

FormatErrorForUser formats an error message for end-user display

func GeneratePluginID

func GeneratePluginID(org, name, version string) string

GeneratePluginID generates a standard format plugin ID

func GetPluginMainVersion

func GetPluginMainVersion(id string) (string, error)

GetPluginMainVersion extracts the main version number from a plugin ID

func GetTypedResource added in v1.2.3

func GetTypedResource[T any](manager ResourceManager, name string) (T, error)

GetTypedResource get type-safe resource (standalone function)

func IsPluginError added in v1.5.0

func IsPluginError(err error) bool

IsPluginError checks if an error is a PluginError

func IsPluginVersionCompatible

func IsPluginVersionCompatible(v1, v2 string) bool

IsPluginVersionCompatible checks if two plugin versions are compatible

func PublishEventToGlobalBus added in v1.2.3

func PublishEventToGlobalBus(event PluginEvent) error

PublishEventToGlobalBus publishes an event to the global event bus

func RegisterTypedResource added in v1.2.3

func RegisterTypedResource[T any](manager ResourceManager, name string, resource T) error

RegisterTypedResource register type-safe resource (standalone function)

func SetGlobalEventBusAdapter added in v1.2.3

func SetGlobalEventBusAdapter(adapter EventBusAdapter)

SetGlobalEventBusAdapter sets the global event bus adapter. If never set, EnsureGlobalEventBusAdapter returns a FallbackEventBusAdapter: events are logged with key "plugin_event_bus_fallback" but not delivered to any subscriber.

func SubscribeToGlobalBus added in v1.2.3

func SubscribeToGlobalBus(eventType EventType, handler func(PluginEvent)) error

SubscribeToGlobalBus subscribes to events on the global event bus

func ValidatePluginID

func ValidatePluginID(id string) error

ValidatePluginID validates the recommended plugin ID format (org.plugin.name.vX[.Y.Z]). Non-standard IDs used by existing plugins may not pass; use only when enforcing the standard format.

Types

type ActionStatus added in v1.2.3

type ActionStatus string

ActionStatus action status

const (
	// ActionStatusPending pending execution
	ActionStatusPending ActionStatus = "pending"
	// ActionStatusInProgress in progress
	ActionStatusInProgress ActionStatus = "in_progress"
	// ActionStatusCompleted completed
	ActionStatusCompleted ActionStatus = "completed"
	// ActionStatusFailed execution failed
	ActionStatusFailed ActionStatus = "failed"
	// ActionStatusRollback rolled back
	ActionStatusRollback ActionStatus = "rollback"
)

type BasePlugin

type BasePlugin = TypedBasePlugin[any]

BasePlugin maintains backward compatibility for base plugins

func NewBasePlugin

func NewBasePlugin(id, name, description, version, confPrefix string, weight int) *BasePlugin

NewBasePlugin creates a base plugin (backward compatibility)

type CachePlugin added in v1.2.3

type CachePlugin[T any] interface {
	Plugin
	GetClient() T
	GetConnectionStats() map[string]any
}

CachePlugin cache plugin constraint interface

type CachePluginAny added in v1.2.3

type CachePluginAny interface {
	Plugin
	GetClient() any
	GetConnectionStats() map[string]any
}

CachePluginAny backward compatible cache plugin interface

type ConfigProvider

type ConfigProvider interface {
	// GetConfig returns the plugin configuration manager
	// Provides access to configuration values and updates
	GetConfig() config.Config
}

ConfigProvider provides access to plugin configuration Manages plugin configuration loading and access

type Configurable

type Configurable interface {
	// Configure applies and validates the given configuration
	// Updates plugin configuration during runtime
	Configure(conf any) error
}

Configurable defines methods for plugin configuration management Manages plugin configuration updates and validation

type ConflictAlternative added in v1.2.3

type ConflictAlternative struct {
	PluginID      string       `json:"plugin_id"`
	Name          string       `json:"name"`
	Version       string       `json:"version"`
	Description   string       `json:"description"`
	Compatibility float64      `json:"compatibility"` // Compatibility score 0-1
	Risk          SolutionRisk `json:"risk"`
}

ConflictAlternative conflict alternative solution

type ConflictDetail added in v1.2.3

type ConflictDetail struct {
	PluginID       string `json:"plugin_id"`
	DependencyID   string `json:"dependency_id"`
	RequiredValue  string `json:"required_value"`
	AvailableValue string `json:"available_value"`
	Message        string `json:"message"`
}

ConflictDetail conflict detailed information

type ConflictResolution added in v1.2.3

type ConflictResolution struct {
	ResolvedConflicts  []string           `json:"resolved_conflicts"`
	RemainingConflicts []string           `json:"remaining_conflicts"`
	Actions            []ResolutionAction `json:"actions"`
	Summary            string             `json:"summary"`
	Risk               SolutionRisk       `json:"risk"`
}

ConflictResolution conflict resolution

type ConflictResolver added in v1.2.3

type ConflictResolver interface {
	// DetectConflicts detects all dependency conflicts
	DetectConflicts(graph *DependencyGraph) ([]DependencyConflict, error)
	// ResolveConflicts returns suggested actions to resolve conflicts; it does not modify the graph
	ResolveConflicts(conflicts []DependencyConflict) (*ConflictResolution, error)
	// SuggestAlternatives suggests alternative solutions
	SuggestAlternatives(conflict DependencyConflict, availablePlugins map[string][]Plugin) []ConflictAlternative
	// ValidateResolution validates that the current graph has no conflicts (e.g. after applying resolution elsewhere)
	ValidateResolution(resolution *ConflictResolution, graph *DependencyGraph) error
}

ConflictResolver dependency conflict resolver interface.

ResolveConflicts only produces a ConflictResolution (suggested actions); it does not modify the DependencyGraph. Callers must apply the chosen actions (e.g. change plugin set or versions) and then re-build or update the graph. ValidateResolution checks the current graph state after those changes; it does not apply the resolution itself.

func NewConflictResolver added in v1.2.3

func NewConflictResolver(versionManager VersionManager) ConflictResolver

NewConflictResolver creates a new conflict resolver

type ConflictSeverity added in v1.2.3

type ConflictSeverity string

ConflictSeverity conflict severity level

const (
	// ConflictSeverityCritical critical conflict
	ConflictSeverityCritical ConflictSeverity = "critical"
	// ConflictSeverityHigh high priority conflict
	ConflictSeverityHigh ConflictSeverity = "high"
	// ConflictSeverityMedium medium priority conflict
	ConflictSeverityMedium ConflictSeverity = "medium"
	// ConflictSeverityLow low priority conflict
	ConflictSeverityLow ConflictSeverity = "low"
	// ConflictSeverityInfo informational conflict
	ConflictSeverityInfo ConflictSeverity = "info"
)

type ConflictSolution added in v1.2.3

type ConflictSolution struct {
	ID          string           `json:"id"`
	Type        SolutionType     `json:"type"`
	Description string           `json:"description"`
	Actions     []SolutionAction `json:"actions"`
	Risk        SolutionRisk     `json:"risk"`
	Priority    int              `json:"priority"`
}

ConflictSolution conflict resolution

type ConflictType added in v1.2.3

type ConflictType string

ConflictType conflict type

const (
	// ConflictTypeVersion version conflict
	ConflictTypeVersion ConflictType = "version"
	// ConflictTypeCircular circular dependency conflict
	ConflictTypeCircular ConflictType = "circular"
	// ConflictTypeMissing missing dependency conflict
	ConflictTypeMissing ConflictType = "missing"
	// ConflictTypeIncompatible incompatible conflict
	ConflictTypeIncompatible ConflictType = "incompatible"
	// ConflictTypeResource resource conflict
	ConflictTypeResource ConflictType = "resource"
)

type ContextAwareness added in v1.2.3

type ContextAwareness interface {
	// IsContextAware returns true if the plugin genuinely honors context
	// cancellation/timeout within Initialize/Start/Stop.
	IsContextAware() bool
}

ContextAwareness defines an optional marker for real context awareness. Some plugins may satisfy LifecycleWithContext via embedded base types but still ignore ctx. Implement this interface on the concrete plugin type and return true only when lifecycle methods actually observe ctx cancellation.

type DatabasePlugin added in v1.2.3

type DatabasePlugin[T any] interface {
	Plugin
	GetDriver() T
	GetStats() any
	IsConnected() bool
	CheckHealth() error
}

DatabasePlugin database plugin constraint interface

type DatabasePluginAny added in v1.2.3

type DatabasePluginAny interface {
	Plugin
	GetDriver() any
	GetStats() any
	IsConnected() bool
	CheckHealth() error
}

DatabasePluginAny backward compatible database plugin interface

type DefaultConflictResolver added in v1.2.3

type DefaultConflictResolver struct {
	// contains filtered or unexported fields
}

DefaultConflictResolver default conflict resolver implementation

func (*DefaultConflictResolver) DetectConflicts added in v1.2.3

func (cr *DefaultConflictResolver) DetectConflicts(graph *DependencyGraph) ([]DependencyConflict, error)

DetectConflicts detects all dependency conflicts

func (*DefaultConflictResolver) ResolveConflicts added in v1.2.3

func (cr *DefaultConflictResolver) ResolveConflicts(conflicts []DependencyConflict) (*ConflictResolution, error)

ResolveConflicts resolves dependency conflicts

func (*DefaultConflictResolver) SuggestAlternatives added in v1.2.3

func (cr *DefaultConflictResolver) SuggestAlternatives(conflict DependencyConflict, availablePlugins map[string][]Plugin) []ConflictAlternative

SuggestAlternatives suggests alternative solutions

func (*DefaultConflictResolver) ValidateResolution added in v1.2.3

func (cr *DefaultConflictResolver) ValidateResolution(resolution *ConflictResolution, graph *DependencyGraph) error

ValidateResolution validates conflict resolution

type DefaultVersionManager added in v1.2.3

type DefaultVersionManager struct{}

DefaultVersionManager default version manager implementation

func (*DefaultVersionManager) CompareVersions added in v1.2.3

func (vm *DefaultVersionManager) CompareVersions(v1, v2 *Version) int

CompareVersions compares two versions Return value: -1 (v1 < v2), 0 (v1 == v2), 1 (v1 > v2)

func (*DefaultVersionManager) GetCompatibleVersions added in v1.2.3

func (vm *DefaultVersionManager) GetCompatibleVersions(required *VersionConstraint, available []*Version) []*Version

GetCompatibleVersions gets compatible version list

func (*DefaultVersionManager) IsVersionInRange added in v1.2.3

func (vm *DefaultVersionManager) IsVersionInRange(version *Version, rng *VersionRange) bool

IsVersionInRange checks if version is within range

func (*DefaultVersionManager) ParseVersion added in v1.2.3

func (vm *DefaultVersionManager) ParseVersion(version string) (*Version, error)

ParseVersion parses version string

func (*DefaultVersionManager) ParseVersionRange added in v1.2.3

func (vm *DefaultVersionManager) ParseVersionRange(rangeStr string) (*VersionRange, error)

ParseVersionRange parses version range string

func (*DefaultVersionManager) ResolveVersionConflict added in v1.2.3

func (vm *DefaultVersionManager) ResolveVersionConflict(conflicts []VersionConflict) (map[string]string, error)

ResolveVersionConflict resolves version conflicts

func (*DefaultVersionManager) SatisfiesConstraint added in v1.2.3

func (vm *DefaultVersionManager) SatisfiesConstraint(version *Version, constraint *VersionConstraint) bool

SatisfiesConstraint checks if version satisfies constraint

type Dependency

type Dependency struct {
	ID                string             `json:"id"`                 // Unique identifier of the dependent plugin
	Name              string             `json:"name"`               // Name of the dependent plugin
	Type              DependencyType     `json:"type"`               // Dependency type (source of truth)
	VersionConstraint *VersionConstraint `json:"version_constraint"` // Version constraint
	Required          bool               `json:"required"`           // Whether it's a required dependency; should be true when Type == DependencyTypeRequired
	Checker           DependencyChecker  `json:"-"`                  // Dependency validator
	Metadata          map[string]any     `json:"metadata"`           // Additional dependency information
	Description       string             `json:"description"`        // Dependency description
}

Dependency describes dependency relationships between plugins. Type is the source of truth for semantics; Required is redundant with Type (Required should be true when Type is DependencyTypeRequired). Prefer setting Type and keep Required consistent for JSON/API.

type DependencyAware

type DependencyAware interface {
	// GetDependencies returns the list of plugin dependencies
	// Lists all required and optional dependencies
	GetDependencies() []Dependency
}

DependencyAware defines methods for plugin dependency management Manages plugin dependencies and their relationships

type DependencyChecker

type DependencyChecker interface {
	// Check validates whether dependency conditions are met
	Check(plugin Plugin) bool
	// Description returns a human-readable description of the condition
	Description() string
}

DependencyChecker defines the interface for dependency validation

type DependencyConflict added in v1.2.3

type DependencyConflict struct {
	ID          string             `json:"id"`
	Type        ConflictType       `json:"type"`
	Severity    ConflictSeverity   `json:"severity"`
	Description string             `json:"description"`
	Plugins     []string           `json:"plugins"`
	Details     []ConflictDetail   `json:"details"`
	Solutions   []ConflictSolution `json:"solutions"`
}

DependencyConflict dependency conflict information

type DependencyError added in v1.2.3

type DependencyError struct {
	PluginID     string `json:"plugin_id"`
	DependencyID string `json:"dependency_id"`
	ErrorType    string `json:"error_type"`
	Message      string `json:"message"`
	Severity     string `json:"severity"` // "error", "warning", "info"
}

DependencyError dependency error information

type DependencyGraph added in v1.2.3

type DependencyGraph struct {
	// contains filtered or unexported fields
}

DependencyGraph dependency graph structure

func NewDependencyGraph added in v1.2.3

func NewDependencyGraph() *DependencyGraph

NewDependencyGraph creates a new dependency graph

func (*DependencyGraph) AddDependency added in v1.2.3

func (dg *DependencyGraph) AddDependency(pluginID string, dependency *Dependency) error

AddDependency adds a dependency relationship

func (*DependencyGraph) AddPlugin added in v1.2.3

func (dg *DependencyGraph) AddPlugin(plugin Plugin)

AddPlugin adds a plugin to the dependency graph

func (*DependencyGraph) CheckCircularDependencies added in v1.2.3

func (dg *DependencyGraph) CheckCircularDependencies() ([]string, error)

CheckCircularDependencies checks for circular dependencies

func (*DependencyGraph) CheckVersionConflicts added in v1.2.3

func (dg *DependencyGraph) CheckVersionConflicts() ([]VersionConflict, error)

CheckVersionConflicts checks for version conflicts

func (*DependencyGraph) CleanupOrphanedDependencies added in v1.2.3

func (dg *DependencyGraph) CleanupOrphanedDependencies() int

CleanupOrphanedDependencies cleans up orphaned dependency relationships

func (*DependencyGraph) GetAllDependencies added in v1.2.3

func (dg *DependencyGraph) GetAllDependencies() map[string][]*Dependency

GetAllDependencies gets all plugin dependency relationships

func (*DependencyGraph) GetAllPlugins added in v1.2.3

func (dg *DependencyGraph) GetAllPlugins() map[string]Plugin

GetAllPlugins gets all plugins

func (*DependencyGraph) GetDependencies added in v1.2.3

func (dg *DependencyGraph) GetDependencies(pluginID string) []*Dependency

GetDependencies gets all dependencies of a plugin

func (*DependencyGraph) GetDependencyStats added in v1.2.3

func (dg *DependencyGraph) GetDependencyStats() map[string]interface{}

GetDependencyStats gets dependency statistics

func (*DependencyGraph) GetDependencyTree added in v1.2.3

func (dg *DependencyGraph) GetDependencyTree(pluginID string) map[string]interface{}

GetDependencyTree gets the dependency tree structure

func (*DependencyGraph) GetDependents added in v1.2.3

func (dg *DependencyGraph) GetDependents(pluginID string) []string

GetDependents gets all plugins that depend on this plugin

func (*DependencyGraph) HasPlugin added in v1.2.3

func (dg *DependencyGraph) HasPlugin(pluginID string) bool

HasPlugin checks if a plugin exists

func (*DependencyGraph) RemoveDependency added in v1.2.3

func (dg *DependencyGraph) RemoveDependency(pluginID string, dependencyID string) error

RemoveDependency removes a dependency relationship

func (*DependencyGraph) RemovePlugin added in v1.2.3

func (dg *DependencyGraph) RemovePlugin(pluginID string)

RemovePlugin removes a plugin from the dependency graph

func (*DependencyGraph) ResolveDependencies added in v1.2.3

func (dg *DependencyGraph) ResolveDependencies() ([]string, error)

ResolveDependencies resolves dependency relationships and returns the correct loading order

func (*DependencyGraph) ValidateDependencies added in v1.2.3

func (dg *DependencyGraph) ValidateDependencies(plugins map[string]Plugin) ([]DependencyError, error)

ValidateDependencies validates whether all dependencies are satisfied

type DependencyManager added in v1.2.3

type DependencyManager interface {
	// AddDependency adds a dependency relationship
	AddDependency(pluginID string, dependency *Dependency) error
	// RemoveDependency removes a dependency relationship
	RemoveDependency(pluginID string, dependencyID string) error
	// GetDependencies gets all dependencies of a plugin
	GetDependencies(pluginID string) []*Dependency
	// GetDependents gets all plugins that depend on this plugin
	GetDependents(pluginID string) []string
	// CheckCircularDependencies checks for circular dependencies
	CheckCircularDependencies() ([]string, error)
	// ResolveDependencies resolves dependency relationships and returns the correct loading order
	ResolveDependencies() ([]string, error)
	// CheckVersionConflicts checks for version conflicts
	CheckVersionConflicts() ([]VersionConflict, error)
	// ValidateDependencies validates whether all dependencies are satisfied
	ValidateDependencies(plugins map[string]Plugin) ([]DependencyError, error)
}

DependencyManager dependency manager interface

type DependencyType added in v1.2.3

type DependencyType string

DependencyType defines dependency types

const (
	// DependencyTypeRequired required dependency
	DependencyTypeRequired DependencyType = "required"
	// DependencyTypeOptional optional dependency
	DependencyTypeOptional DependencyType = "optional"
	// DependencyTypeConflicts conflicting dependency
	DependencyTypeConflicts DependencyType = "conflicts"
	// DependencyTypeProvides provided dependency
	DependencyTypeProvides DependencyType = "provides"
)

type ErrorCode added in v1.5.0

type ErrorCode string

ErrorCode represents a specific error type for better categorization

const (
	// Plugin lifecycle errors
	ErrorCodePluginNotFound       ErrorCode = "PLUGIN_NOT_FOUND"
	ErrorCodePluginAlreadyExists  ErrorCode = "PLUGIN_ALREADY_EXISTS"
	ErrorCodePluginNotInitialized ErrorCode = "PLUGIN_NOT_INITIALIZED"
	ErrorCodePluginNotActive      ErrorCode = "PLUGIN_NOT_ACTIVE"
	ErrorCodePluginAlreadyActive  ErrorCode = "PLUGIN_ALREADY_ACTIVE"

	// Configuration errors
	ErrorCodeInvalidPluginID      ErrorCode = "INVALID_PLUGIN_ID"
	ErrorCodeInvalidPluginVersion ErrorCode = "INVALID_PLUGIN_VERSION"
	ErrorCodeInvalidPluginConfig  ErrorCode = "INVALID_PLUGIN_CONFIG"
	ErrorCodeInvalidConfiguration ErrorCode = "INVALID_CONFIGURATION"

	// Dependency errors
	ErrorCodePluginDependencyNotMet ErrorCode = "PLUGIN_DEPENDENCY_NOT_MET"

	// Upgrade errors
	ErrorCodePluginUpgradeNotSupported ErrorCode = "PLUGIN_UPGRADE_NOT_SUPPORTED"
	ErrorCodePluginUpgradeFailed       ErrorCode = "PLUGIN_UPGRADE_FAILED"

	// Resource errors
	ErrorCodePluginResourceNotFound ErrorCode = "PLUGIN_RESOURCE_NOT_FOUND"
	ErrorCodePluginResourceInvalid  ErrorCode = "PLUGIN_RESOURCE_INVALID"

	// Operation errors
	ErrorCodePluginOperationTimeout   ErrorCode = "PLUGIN_OPERATION_TIMEOUT"
	ErrorCodePluginOperationCancelled ErrorCode = "PLUGIN_OPERATION_CANCELLED"

	// Health and security errors
	ErrorCodePluginHealthCheckFailed ErrorCode = "PLUGIN_HEALTH_CHECK_FAILED"
	ErrorCodePluginSecurityViolation ErrorCode = "PLUGIN_SECURITY_VIOLATION"
)

type EventBusAdapter added in v1.2.3

type EventBusAdapter interface {
	PublishEvent(event PluginEvent) error
	Subscribe(eventType EventType, handler func(PluginEvent)) error
	SubscribeTo(eventType EventType, handler func(PluginEvent)) error
}

EventBusAdapter provides an interface for plugins to interact with the unified event bus This avoids circular imports between plugins and app/events packages

func EnsureGlobalEventBusAdapter added in v1.2.3

func EnsureGlobalEventBusAdapter() EventBusAdapter

EnsureGlobalEventBusAdapter ensures the global event bus adapter is available. When none was set via SetGlobalEventBusAdapter, returns a FallbackEventBusAdapter so that publish/subscribe do not panic; events are logged but not actually delivered.

func GetGlobalEventBusAdapter added in v1.2.3

func GetGlobalEventBusAdapter() EventBusAdapter

GetGlobalEventBusAdapter returns the global event bus adapter (may be nil).

type EventEmitter

type EventEmitter interface {
	// EmitEvent broadcasts a plugin event to all registered listeners.
	// Event will be processed according to its priority and any active filters.
	EmitEvent(event PluginEvent)

	// AddListener registers a new event listener with optional filters.
	// Listener will only receive events that match its filter criteria.
	AddListener(listener EventListener, filter *EventFilter)

	// RemoveListener unregisters an event listener.
	// After removal, the listener will no longer receive any events.
	RemoveListener(listener EventListener)

	// GetEventHistory retrieves historical events based on filter criteria.
	// Returns events that match the specified filter parameters.
	GetEventHistory(filter EventFilter) []PluginEvent
}

EventEmitter defines the interface for the plugin event system.

type EventFilter

type EventFilter struct {
	// Types specifies which event types to include
	Types []EventType

	// Priorities specifies which priority levels to include
	Priorities []int

	// PluginIDs specifies which plugins to monitor
	PluginIDs []string

	// Categories specifies which event categories to include
	Categories []string

	// FromTime specifies the start time for event filtering
	FromTime int64

	// ToTime specifies the end time for event filtering
	ToTime int64
}

EventFilter defines criteria for filtering plugin events. It allows selective processing of events based on various attributes.

type EventHandler

type EventHandler interface {
	// HandleEvent processes plugin lifecycle events
	// Handles various plugin system events
	HandleEvent(event PluginEvent)
}

EventHandler defines methods for plugin event handling Processes plugin-related events and notifications

type EventListener

type EventListener interface {
	// HandleEvent processes plugin lifecycle events.
	// Implementation should handle the event according to its type and priority.
	HandleEvent(event PluginEvent)

	// GetListenerID returns a stable unique identifier for this listener.
	// The same logical listener must return the same ID on every call so that RemoveListener
	// can correctly unregister it. Avoid using pointer addresses (e.g. fmt.Sprintf("%p", l))
	// if the listener struct is recreated between Add and Remove.
	GetListenerID() string
}

EventListener defines the interface for handling plugin events.

type EventProcessor

type EventProcessor interface {
	// ProcessEvent processes an event through all registered filters.
	// Returns true if the event should be propagated, false if it should be filtered.
	ProcessEvent(event PluginEvent) bool

	// AddFilter adds a new event filter to the processor.
	// Filter will be applied to all subsequent events.
	AddFilter(filter EventFilter)

	// RemoveFilter removes an event filter by its ID.
	// Events will no longer be filtered by the removed filter.
	RemoveFilter(filterID string)
}

EventProcessor provides event processing and filtering capabilities.

type EventType

type EventType string

EventType represents the type of event that occurred in the plugin system.

type FallbackEventBusAdapter added in v1.2.3

type FallbackEventBusAdapter struct{}

FallbackEventBusAdapter provides a safe fallback when no global adapter is available. Events published via PublishEvent are logged with key "plugin_event_bus_fallback" and are not delivered to any subscriber. Subscribe/SubscribeTo are no-ops; handlers will not be invoked.

func (*FallbackEventBusAdapter) PublishEvent added in v1.2.3

func (f *FallbackEventBusAdapter) PublishEvent(event PluginEvent) error

PublishEvent handles event publishing when no adapter is available

func (*FallbackEventBusAdapter) Subscribe added in v1.2.3

func (f *FallbackEventBusAdapter) Subscribe(eventType EventType, handler func(PluginEvent)) error

Subscribe handles event subscription when no adapter is available

func (*FallbackEventBusAdapter) SubscribeTo added in v1.2.3

func (f *FallbackEventBusAdapter) SubscribeTo(eventType EventType, handler func(PluginEvent)) error

SubscribeTo handles specific event subscription when no adapter is available

type HealthCheck

type HealthCheck interface {
	// GetHealth returns the current health status of the plugin
	// Provides detailed health information
	GetHealth() HealthReport
}

HealthCheck defines methods for plugin health monitoring Provides health status and monitoring capabilities

type HealthReport

type HealthReport struct {
	Status    string         // Current health status (healthy, degraded, unhealthy)
	Details   map[string]any // Detailed health metrics and information
	Timestamp int64          // Time of the health check (Unix timestamp)
	Message   string         // Optional descriptive message
}

HealthReport represents the detailed health status of a plugin Provides comprehensive health information for monitoring

type IDFormat

type IDFormat struct {
	Organization string // e.g., "go-lynx"
	Type         string // e.g., "plugin"
	Name         string // e.g., "http"
	Version      string // e.g., "v1" or "v1.0.0"
}

IDFormat represents the components of a plugin ID

func ParsePluginID

func ParsePluginID(id string) (*IDFormat, error)

ParsePluginID parses a plugin ID string into its components

type Lifecycle

type Lifecycle interface {
	// Initialize prepares the plugin for use
	// Sets up resources, connections, and internal state
	// Returns error if initialization fails
	Initialize(plugin Plugin, rt Runtime) error

	// Start begins the plugin's main functionality
	// Should only be called after successful initialization
	// Returns error if startup fails
	Start(plugin Plugin) error

	// Stop gracefully terminates the plugin's functionality
	// Releases resources and closes connections
	// Returns error if shutdown fails
	Stop(plugin Plugin) error

	// Status returns the current status of the plugin
	// Provides real-time state information
	Status(plugin Plugin) PluginStatus
}

Lifecycle defines the basic lifecycle methods for a plugin Handles initialization, operation, and termination of the plugin

type LifecycleSteps

type LifecycleSteps interface {
	InitializeResources(rt Runtime) error
	StartupTasks() error
	CleanupTasks() error
	CheckHealth() error
}

type LifecycleWithContext added in v1.2.3

type LifecycleWithContext interface {
	// InitializeContext prepares the plugin with context support.
	InitializeContext(ctx context.Context, plugin Plugin, rt Runtime) error

	// StartContext starts the plugin with context support.
	StartContext(ctx context.Context, plugin Plugin) error

	// StopContext stops the plugin with context support.
	StopContext(ctx context.Context, plugin Plugin) error
}

LifecycleWithContext defines optional context-aware lifecycle methods. Plugins implementing this interface can receive cancellation/timeout signals and are encouraged to stop work promptly when the context is done. This interface is backward-compatible and optional; if not implemented, the manager will fall back to calling the non-context methods.

type LogProvider

type LogProvider interface {
	// GetLogger returns the plugin logger instance
	// Provides structured logging capabilities
	GetLogger() log.Logger
}

LogProvider provides access to logging functionality Manages plugin logging capabilities

type MessagingPlugin added in v1.2.3

type MessagingPlugin[T any] interface {
	Plugin
	GetProducer() T
	GetConsumer() T
}

MessagingPlugin messaging plugin constraint interface

type MessagingPluginAny added in v1.2.3

type MessagingPluginAny interface {
	Plugin
	GetProducer() any
	GetConsumer() any
}

MessagingPluginAny backward compatible messaging plugin interface

type Metadata

type Metadata interface {
	// ID returns the unique identifier of the plugin
	// This ID must be unique across all plugins in the system
	ID() string

	// Name returns the display name of the plugin
	// This is a human-readable name used for display purposes
	Name() string

	// Description returns a detailed description of the plugin
	// Should provide information about the plugin's purpose and functionality
	Description() string

	// Version returns the semantic version of the plugin
	// Should follow semver format (MAJOR.MINOR.PATCH)
	Version() string

	// Weight returns the weight value
	Weight() int
}

Metadata defines methods for retrieving plugin metadata This interface provides essential information about the plugin

type Plugin

type Plugin interface {
	Metadata
	Lifecycle
	LifecycleSteps
	DependencyAware
}

Plugin is the minimal interface that all plugins must implement It combines basic metadata and lifecycle management capabilities

type PluginError

type PluginError struct {
	// PluginID identifies the plugin where the error occurred
	PluginID string `json:"plugin_id"`

	// Operation describes the action that was being performed when the error occurred
	Operation string `json:"operation"`

	// Message provides a detailed description of the error
	Message string `json:"message"`

	// Err is the underlying error that caused this PluginError
	Err error `json:"-"`

	// Code represents the error type for better categorization
	Code ErrorCode `json:"code,omitempty"`

	// Context provides additional context information
	Context map[string]interface{} `json:"context,omitempty"`

	// Timestamp when the error occurred
	Timestamp time.Time `json:"timestamp"`

	// StackTrace provides debugging information
	StackTrace string `json:"stack_trace,omitempty"`
}

PluginError represents a detailed error that occurred during plugin operations

func GetPluginError added in v1.5.0

func GetPluginError(err error) *PluginError

GetPluginError extracts PluginError from error chain

func NewPluginError

func NewPluginError(pluginID, operation, message string, err error) *PluginError

NewPluginError creates a new PluginError with the given details Provides a convenient way to create structured plugin errors

func NewPluginErrorWithCode added in v1.5.0

func NewPluginErrorWithCode(code ErrorCode, pluginID, operation, message string, err error) *PluginError

NewPluginErrorWithCode creates a new PluginError with error code

func (*PluginError) Error

func (e *PluginError) Error() string

Error implements the error interface for PluginError Returns a formatted error message including plugin ID, operation, and details

func (*PluginError) Unwrap

func (e *PluginError) Unwrap() error

Unwrap implements the errors unwrap interface Returns the underlying error for error chain handling

func (*PluginError) WithContext added in v1.5.0

func (e *PluginError) WithContext(key string, value interface{}) *PluginError

WithContext adds context information to the error

func (*PluginError) WithStackTrace added in v1.5.0

func (e *PluginError) WithStackTrace() *PluginError

WithStackTrace adds stack trace information to the error

type PluginEvent

type PluginEvent struct {
	// Type indicates the specific kind of event that occurred
	Type EventType

	// Priority indicates the importance level of the event
	Priority int

	// PluginID identifies the plugin that generated the event
	PluginID string

	// Source identifies where in the plugin the event originated
	Source string

	// Category groups related events for easier filtering
	Category string

	// Status represents the plugin's state when event occurred
	Status PluginStatus

	// Error contains any error information if applicable
	Error error

	// Metadata contains additional event-specific information
	Metadata map[string]any

	// Timestamp records when the event occurred
	Timestamp int64
}

PluginEvent represents a lifecycle event in the plugin system. It contains detailed information about the event, including its type, priority, source, and any associated metadata.

type PluginStatus

type PluginStatus int

PluginStatus represents the current operational status of a plugin in the system. It tracks the plugin's lifecycle state from initialization through termination.

const (
	// StatusInactive indicates that the plugin is loaded but not yet initialized
	// This is the initial state of a plugin when it is first loaded into the system
	StatusInactive PluginStatus = iota

	// StatusInitializing indicates that the plugin is currently performing initialization
	// During this state, the plugin is setting up resources, establishing connections,
	// and preparing for normal operation
	StatusInitializing

	// StatusActive indicates that the plugin is fully operational and running normally
	// In this state, the plugin is processing requests and performing its intended functions
	StatusActive

	// StatusSuspended indicates that the plugin is temporarily paused
	// The plugin retains its resources but is not processing new requests
	// Can be resumed to StatusActive without full reinitialization
	StatusSuspended

	// StatusStopping indicates that the plugin is in the process of shutting down
	// During this state, the plugin is cleaning up resources and finishing pending operations
	StatusStopping

	// StatusTerminated indicates that the plugin has been gracefully shut down
	// All resources have been released and connections closed
	// Requires full reinitialization to become active again
	StatusTerminated

	// StatusFailed indicates that the plugin has encountered a fatal error
	// The plugin is non-operational and may require manual intervention
	// Should transition to StatusTerminated or attempt recovery
	StatusFailed

	// StatusUpgrading indicates that the plugin is currently being upgraded
	// During this state, the plugin may be partially operational
	// Should transition to StatusActive or StatusFailed
	StatusUpgrading

	// StatusRollback indicates that the plugin is rolling back from a failed upgrade
	// Attempting to restore the previous working state
	// Should transition to StatusActive or StatusFailed
	StatusRollback
)

type ResolutionAction added in v1.2.3

type ResolutionAction struct {
	ConflictID string           `json:"conflict_id"`
	SolutionID string           `json:"solution_id"`
	Actions    []SolutionAction `json:"actions"`
	Status     ActionStatus     `json:"status"`
}

ResolutionAction resolution action

type ResourceInfo added in v1.2.3

type ResourceInfo struct {
	Name        string
	Type        string
	PluginID    string
	IsPrivate   bool
	CreatedAt   time.Time
	LastUsedAt  time.Time
	AccessCount int64
	Size        int64 // Resource size (bytes)
	Metadata    map[string]any
}

ResourceInfo resource information

type ResourceManager

type ResourceManager interface {
	// GetResource retrieves a shared plugin resource by name
	// Returns the resource and any error encountered
	GetResource(name string) (any, error)

	// RegisterResource registers a resource to be shared with other plugins
	// Returns error if registration fails
	RegisterResource(name string, resource any) error

	// New: Resource lifecycle management
	GetResourceInfo(name string) (*ResourceInfo, error)
	ListResources() []*ResourceInfo
	CleanupResources(pluginID string) error
	GetResourceStats() map[string]any
}

ResourceManager resource manager interface

type Runtime

type Runtime interface {
	TypedResourceManager
	ConfigProvider
	LogProvider
	EventEmitter
	// New: Logically separated resource management
	GetPrivateResource(name string) (any, error)
	RegisterPrivateResource(name string, resource any) error
	GetSharedResource(name string) (any, error)
	RegisterSharedResource(name string, resource any) error
	// New: Improved event system
	EmitPluginEvent(pluginName string, eventType string, data map[string]any)
	AddPluginListener(pluginName string, listener EventListener, filter *EventFilter)
	GetPluginEventHistory(pluginName string, filter EventFilter) []PluginEvent
	// New: Event system configuration and metrics
	SetEventDispatchMode(mode string) error
	SetEventWorkerPoolSize(size int)
	SetEventTimeout(timeout time.Duration)
	GetEventStats() map[string]any
	// New: Plugin context management
	WithPluginContext(pluginName string) Runtime
	GetCurrentPluginContext() string
	// New: Configuration management
	SetConfig(conf config.Config)
	// Shutdown gracefully shuts down the runtime (cancels shutdown context, closes event adapter, etc.).
	// Safe to call multiple times. Should be called when the application is closing.
	Shutdown()
}

Runtime is the main interface for plugin runtime environment (resources, config, log, events, context). Implementations may compose smaller interfaces (ResourceManager, EventEmitter, etc.) for clarity.

func NewSimpleRuntime added in v1.2.3

func NewSimpleRuntime() Runtime

NewSimpleRuntime returns the default Runtime implementation (UnifiedRuntime). Kept for backward compatibility; prefer NewUnifiedRuntime() for new code.

type ServiceDiscoveryPlugin added in v1.2.3

type ServiceDiscoveryPlugin[T any] interface {
	Plugin
	GetRegistry() T
	GetDiscovery() T
}

ServiceDiscoveryPlugin service discovery plugin constraint interface

type ServiceDiscoveryPluginAny added in v1.2.3

type ServiceDiscoveryPluginAny interface {
	Plugin
	GetRegistry() any
	GetDiscovery() any
}

ServiceDiscoveryPluginAny backward compatible service discovery plugin interface

type ServicePlugin added in v1.2.3

type ServicePlugin[T any] interface {
	Plugin
	GetServer() T
	GetServerType() string
}

ServicePlugin service plugin constraint interface

type ServicePluginAny added in v1.2.3

type ServicePluginAny interface {
	Plugin
	GetServer() any
	GetServerType() string
}

ServicePluginAny backward compatible service plugin interface

type SolutionAction added in v1.2.3

type SolutionAction struct {
	Type        string            `json:"type"`
	Target      string            `json:"target"`
	Value       string            `json:"value"`
	Description string            `json:"description"`
	Parameters  map[string]string `json:"parameters"`
}

SolutionAction solution action

type SolutionRisk added in v1.2.3

type SolutionRisk string

SolutionRisk solution risk

const (
	// SolutionRiskLow low risk
	SolutionRiskLow SolutionRisk = "low"
	// SolutionRiskMedium medium risk
	SolutionRiskMedium SolutionRisk = "medium"
	// SolutionRiskHigh high risk
	SolutionRiskHigh SolutionRisk = "high"
)

type SolutionType added in v1.2.3

type SolutionType string

SolutionType solution type

const (
	// SolutionTypeUpgrade upgrade version
	SolutionTypeUpgrade SolutionType = "upgrade"
	// SolutionTypeDowngrade downgrade version
	SolutionTypeDowngrade SolutionType = "downgrade"
	// SolutionTypeReplace replace plugin
	SolutionTypeReplace SolutionType = "replace"
	// SolutionTypeRemove remove plugin
	SolutionTypeRemove SolutionType = "remove"
	// SolutionTypeConfigure configuration adjustment
	SolutionTypeConfigure SolutionType = "configure"
)

type StandardError added in v1.5.0

type StandardError struct {
	Code        ErrorCode `json:"code"`
	Message     string    `json:"message"`
	Description string    `json:"description"`
	Timestamp   time.Time `json:"timestamp"`
}

StandardError represents a standard error with enhanced information

func NewStandardError added in v1.5.0

func NewStandardError(code ErrorCode, message, description string) *StandardError

NewStandardError creates a new StandardError with the given details

func (*StandardError) Error added in v1.5.0

func (e *StandardError) Error() string

Error implements the error interface for StandardError

type Suspendable

type Suspendable interface {
	// Suspend temporarily suspends plugin operations
	// Pauses plugin activity while maintaining state
	Suspend() error

	// Resume restores plugin operations from a suspended state
	// Resumes normal operation without reinitialization
	Resume() error
}

Suspendable defines methods for temporary plugin suspension Manages temporary plugin deactivation and reactivation

type TypedBasePlugin added in v1.2.3

type TypedBasePlugin[T any] struct {
	// contains filtered or unexported fields
}

TypedBasePlugin provides a generic base plugin with type-safe plugin foundation implementation. All reads and writes to status are protected by statusMu for concurrent safety (e.g. health checks and lifecycle operations from different goroutines).

func NewTypedBasePlugin added in v1.2.3

func NewTypedBasePlugin[T any](
	id, name, description, version, confPrefix string,
	weight int,
	instance T,
) *TypedBasePlugin[T]

NewTypedBasePlugin creates a new instance of TypedBasePlugin with the provided metadata. This is the recommended way to initialize a new typed plugin implementation.

func (*TypedBasePlugin[T]) AddDependency added in v1.2.3

func (p *TypedBasePlugin[T]) AddDependency(dep Dependency)

AddDependency adds a new dependency to the plugin. The dependency will be validated during plugin initialization. For load-order resolution, add required dependencies in the plugin constructor so GetDependencies() is complete before the manager runs topological sort.

func (*TypedBasePlugin[T]) AddEventFilter added in v1.2.3

func (p *TypedBasePlugin[T]) AddEventFilter(filter EventFilter)

AddEventFilter adds a new event filter to the plugin. Events will be filtered according to the specified criteria.

func (*TypedBasePlugin[T]) ApplyConfig added in v1.2.3

func (p *TypedBasePlugin[T]) ApplyConfig(conf any) error

ApplyConfig applies the validated configuration. This is called after configuration validation succeeds.

func (*TypedBasePlugin[T]) CheckHealth added in v1.2.3

func (p *TypedBasePlugin[T]) CheckHealth() error

CheckHealth performs the actual health check operations. This is called during health status reporting.

func (*TypedBasePlugin[T]) CleanupTasks added in v1.2.3

func (p *TypedBasePlugin[T]) CleanupTasks() error

CleanupTasks performs cleanup during plugin shutdown. This method can be overridden by embedding structs to provide custom cleanup logic.

func (*TypedBasePlugin[T]) Configure added in v1.2.3

func (p *TypedBasePlugin[T]) Configure(conf any) error

Configure updates the plugin's configuration with the provided settings. This method validates and applies new configuration values.

func (*TypedBasePlugin[T]) Description added in v1.2.3

func (p *TypedBasePlugin[T]) Description() string

Description returns a detailed description of the plugin's functionality. This helps users understand the plugin's purpose and capabilities.

func (*TypedBasePlugin[T]) EmitEvent added in v1.2.3

func (p *TypedBasePlugin[T]) EmitEvent(event PluginEvent)

EmitEvent emits an event to the runtime event system. This method adds standard fields to the event before emission.

func (*TypedBasePlugin[T]) EmitEventInternal added in v1.2.3

func (p *TypedBasePlugin[T]) EmitEventInternal(event PluginEvent)

EmitEventInternal emits an event to the unified event bus system. This method adds standard fields to the event before emission. Safe to call before Initialize: if runtime is nil, the event is dropped to avoid panic.

func (*TypedBasePlugin[T]) EventMatchesFilter added in v1.2.3

func (p *TypedBasePlugin[T]) EventMatchesFilter(event PluginEvent, filter EventFilter) bool

EventMatchesFilter checks if an event matches a specific filter. This implements the detailed filter matching logic.

func (*TypedBasePlugin[T]) ExecuteUpgrade added in v1.2.3

func (p *TypedBasePlugin[T]) ExecuteUpgrade(targetVersion string) error

ExecuteUpgrade performs the plugin upgrade. This method checks if the plugin is in the upgrading state.

func (*TypedBasePlugin[T]) GetCapabilities added in v1.2.3

func (p *TypedBasePlugin[T]) GetCapabilities() []UpgradeCapability

GetCapabilities returns the plugin's upgrade capabilities.

func (*TypedBasePlugin[T]) GetDependencies added in v1.2.3

func (p *TypedBasePlugin[T]) GetDependencies() []Dependency

GetDependencies returns a copy of the plugin dependencies so callers cannot mutate the slice and to avoid races with concurrent AddDependency. For correct load order: the framework calls this before initializing plugins (during TopologicalSort). Required dependencies that affect load order should be added in the plugin constructor so they are available here.

func (*TypedBasePlugin[T]) GetHealth added in v1.2.3

func (p *TypedBasePlugin[T]) GetHealth() HealthReport

GetHealth performs a health check and returns a detailed health report. This method should be called periodically to monitor plugin health.

func (*TypedBasePlugin[T]) GetTypedInstance added in v1.2.3

func (p *TypedBasePlugin[T]) GetTypedInstance() T

GetTypedInstance returns the type-safe instance

func (*TypedBasePlugin[T]) HandleConfigEvent added in v1.2.3

func (p *TypedBasePlugin[T]) HandleConfigEvent(event PluginEvent)

HandleConfigEvent processes configuration-related events. This implements specific handling for configuration events.

func (*TypedBasePlugin[T]) HandleDefaultEvent added in v1.2.3

func (p *TypedBasePlugin[T]) HandleDefaultEvent(event PluginEvent)

HandleDefaultEvent processes events that don't have specific handlers. This implements default event handling behavior.

func (*TypedBasePlugin[T]) HandleDependencyEvent added in v1.2.3

func (p *TypedBasePlugin[T]) HandleDependencyEvent(event PluginEvent)

HandleDependencyEvent processes dependency-related events. This implements specific handling for dependency events.

func (*TypedBasePlugin[T]) HandleEvent added in v1.2.3

func (p *TypedBasePlugin[T]) HandleEvent(event PluginEvent)

HandleEvent processes incoming plugin events. Events are filtered and handled according to configured filters.

func (*TypedBasePlugin[T]) HandleHealthEvent added in v1.2.3

func (p *TypedBasePlugin[T]) HandleHealthEvent(event PluginEvent)

HandleHealthEvent processes health-related events. This implements specific handling for health events.

func (*TypedBasePlugin[T]) ID added in v1.2.3

func (p *TypedBasePlugin[T]) ID() string

ID returns the unique identifier of the plugin. This ID must be unique across all plugins in the system.

func (*TypedBasePlugin[T]) Initialize added in v1.2.3

func (p *TypedBasePlugin[T]) Initialize(plugin Plugin, rt Runtime) error

Initialize prepares the plugin for use by setting up its runtime environment. This method must be called before the plugin can be started.

func (*TypedBasePlugin[T]) InitializeContext added in v1.2.3

func (p *TypedBasePlugin[T]) InitializeContext(ctx context.Context, plugin Plugin, rt Runtime) error

InitializeContext provides a context-aware Initialize with timeout monitoring. The default implementation only wraps Initialize in a goroutine and returns on ctx.Done(); the underlying Initialize is not cancelled. Override and check ctx.Err() for real cancellation.

func (*TypedBasePlugin[T]) InitializeResources added in v1.2.3

func (p *TypedBasePlugin[T]) InitializeResources(rt Runtime) error

InitializeResources sets up the plugin's required resources. This method can be overridden by embedding structs to provide custom initialization.

func (*TypedBasePlugin[T]) IsContextAware added in v1.2.3

func (p *TypedBasePlugin[T]) IsContextAware() bool

IsContextAware returns false by default for base plugin Subclasses should override this if they truly respect context cancellation

func (*TypedBasePlugin[T]) Name added in v1.2.3

func (p *TypedBasePlugin[T]) Name() string

Name returns the human-readable name of the plugin. This name is used for display and logging purposes.

func (*TypedBasePlugin[T]) PerformRollback added in v1.2.3

func (p *TypedBasePlugin[T]) PerformRollback(previousVersion string) error

PerformRollback handles the actual rollback process. This is an internal method called by RollbackUpgrade.

func (*TypedBasePlugin[T]) PerformUpgrade added in v1.2.3

func (p *TypedBasePlugin[T]) PerformUpgrade(targetVersion string) error

PerformUpgrade handles the actual upgrade process. This is an internal method called by ExecuteUpgrade.

func (*TypedBasePlugin[T]) PrepareUpgrade added in v1.2.3

func (p *TypedBasePlugin[T]) PrepareUpgrade(targetVersion string) error

PrepareUpgrade prepares the plugin for upgrade. This method checks if the plugin supports the upgrade capability.

func (*TypedBasePlugin[T]) RemoveEventFilter added in v1.2.3

func (p *TypedBasePlugin[T]) RemoveEventFilter(index int)

RemoveEventFilter removes an event filter from the plugin. This affects how future events will be processed.

func (*TypedBasePlugin[T]) Resume added in v1.2.3

func (p *TypedBasePlugin[T]) Resume() error

Resume resumes the plugin from suspended state. This method checks if the plugin is in the suspended state.

func (*TypedBasePlugin[T]) RollbackUpgrade added in v1.2.3

func (p *TypedBasePlugin[T]) RollbackUpgrade(previousVersion string) error

RollbackUpgrade rolls back the plugin upgrade. This method checks if the plugin is in the upgrading or failed state.

func (*TypedBasePlugin[T]) SetStatus added in v1.2.3

func (p *TypedBasePlugin[T]) SetStatus(status PluginStatus)

SetStatus sets the current operational status of the plugin. This method is thread-safe and should be used to update plugin status.

func (*TypedBasePlugin[T]) ShouldEmitEvent added in v1.2.3

func (p *TypedBasePlugin[T]) ShouldEmitEvent(event PluginEvent) bool

ShouldEmitEvent checks if an event should be emitted based on filters. This implements the event filtering logic.

func (*TypedBasePlugin[T]) ShouldHandleEvent added in v1.2.3

func (p *TypedBasePlugin[T]) ShouldHandleEvent(event PluginEvent) bool

ShouldHandleEvent checks if an event should be handled based on filters. This implements the event handling filter logic.

func (*TypedBasePlugin[T]) Start added in v1.2.3

func (p *TypedBasePlugin[T]) Start(plugin Plugin) error

Start activates the plugin and begins its main operations. The plugin must be initialized before it can be started.

func (*TypedBasePlugin[T]) StartContext added in v1.2.3

func (p *TypedBasePlugin[T]) StartContext(ctx context.Context, plugin Plugin) error

StartContext provides a context-aware Start with timeout monitoring. The default implementation only wraps Start in a goroutine and returns on ctx.Done(); the underlying Start is not cancelled. For real cancellation, implement LifecycleWithContext on your plugin and check ctx.Done() inside Start (or StartContext).

func (*TypedBasePlugin[T]) StartupTasks added in v1.2.3

func (p *TypedBasePlugin[T]) StartupTasks() error

StartupTasks performs necessary tasks during plugin startup. This method can be overridden by embedding structs to provide custom startup logic.

func (*TypedBasePlugin[T]) Status added in v1.2.3

func (p *TypedBasePlugin[T]) Status(plugin Plugin) PluginStatus

Status returns the current operational status of the plugin. This method is thread-safe and can be called at any time.

func (*TypedBasePlugin[T]) Stop added in v1.2.3

func (p *TypedBasePlugin[T]) Stop(plugin Plugin) error

Stop gracefully terminates the plugin's operations. This method should release all resources and perform cleanup.

func (*TypedBasePlugin[T]) StopContext added in v1.2.3

func (p *TypedBasePlugin[T]) StopContext(ctx context.Context, plugin Plugin) error

StopContext provides a context-aware Stop with timeout monitoring. The default implementation only wraps Stop in a goroutine and returns on ctx.Done(); the underlying Stop is not cancelled. Override and honor ctx in cleanup for real cancellation.

func (*TypedBasePlugin[T]) SupportsCapability added in v1.2.3

func (p *TypedBasePlugin[T]) SupportsCapability(cap UpgradeCapability) bool

SupportsCapability checks if the plugin supports the specified upgrade capability.

func (*TypedBasePlugin[T]) Suspend added in v1.2.3

func (p *TypedBasePlugin[T]) Suspend() error

Suspend temporarily suspends the plugin. This method checks if the plugin is in the active state.

func (*TypedBasePlugin[T]) ValidateConfig added in v1.2.3

func (p *TypedBasePlugin[T]) ValidateConfig(conf any) error

ValidateConfig validates the provided configuration. This is called before applying new configuration.

func (*TypedBasePlugin[T]) Version added in v1.2.3

func (p *TypedBasePlugin[T]) Version() string

Version returns the semantic version of the plugin. Version format should follow semver conventions (MAJOR.MINOR.PATCH).

func (*TypedBasePlugin[T]) Weight added in v1.2.3

func (p *TypedBasePlugin[T]) Weight() int

Weight returns the plugin weight for prioritization

type TypedPlugin added in v1.2.3

type TypedPlugin[T any] interface {
	Plugin
	GetTypedInstance() T
}

TypedPlugin generic plugin interface, T is the specific plugin type Provides type-safe plugin access capabilities

type TypedResourceManager added in v1.2.3

type TypedResourceManager interface {
	ResourceManager
}

TypedResourceManager generic resource manager interface

type TypedRuntime added in v1.2.3

type TypedRuntime interface {
	Runtime
}

TypedRuntime generic runtime interface

type TypedRuntimeImpl added in v1.2.3

type TypedRuntimeImpl struct {
	// contains filtered or unexported fields
}

TypedRuntimeImpl generic runtime implementation

func NewTypedRuntime added in v1.2.3

func NewTypedRuntime() *TypedRuntimeImpl

NewTypedRuntime create generic runtime environment

func (*TypedRuntimeImpl) AddListener added in v1.2.3

func (r *TypedRuntimeImpl) AddListener(listener EventListener, filter *EventFilter)

AddListener add event listener

func (*TypedRuntimeImpl) AddPluginListener added in v1.2.3

func (r *TypedRuntimeImpl) AddPluginListener(pluginName string, listener EventListener, filter *EventFilter)

AddPluginListener add specific plugin event listener

func (*TypedRuntimeImpl) CleanupResources added in v1.2.3

func (r *TypedRuntimeImpl) CleanupResources(pluginID string) error

CleanupResources clean up resources for a specific plugin

func (*TypedRuntimeImpl) EmitEvent added in v1.2.3

func (r *TypedRuntimeImpl) EmitEvent(event PluginEvent)

EmitEvent emit event

func (*TypedRuntimeImpl) EmitPluginEvent added in v1.2.3

func (r *TypedRuntimeImpl) EmitPluginEvent(pluginName string, eventType string, data map[string]any)

EmitPluginEvent emit plugin namespace event

func (*TypedRuntimeImpl) GetConfig added in v1.2.3

func (r *TypedRuntimeImpl) GetConfig() config.Config

GetConfig get configuration

func (*TypedRuntimeImpl) GetCurrentPluginContext added in v1.2.3

func (r *TypedRuntimeImpl) GetCurrentPluginContext() string

GetCurrentPluginContext get current plugin context

func (*TypedRuntimeImpl) GetEventHistory added in v1.2.3

func (r *TypedRuntimeImpl) GetEventHistory(filter EventFilter) []PluginEvent

GetEventHistory get event history

func (*TypedRuntimeImpl) GetLogger added in v1.2.3

func (r *TypedRuntimeImpl) GetLogger() log.Logger

GetLogger get logger

func (*TypedRuntimeImpl) GetPluginEventHistory added in v1.2.3

func (r *TypedRuntimeImpl) GetPluginEventHistory(pluginName string, filter EventFilter) []PluginEvent

GetPluginEventHistory get specific plugin event history

func (*TypedRuntimeImpl) GetPrivateResource added in v1.2.3

func (r *TypedRuntimeImpl) GetPrivateResource(name string) (any, error)

GetPrivateResource get private resource

func (*TypedRuntimeImpl) GetResource added in v1.2.3

func (r *TypedRuntimeImpl) GetResource(name string) (any, error)

GetResource get resource (compatible with old interface)

func (*TypedRuntimeImpl) GetResourceInfo added in v1.2.3

func (r *TypedRuntimeImpl) GetResourceInfo(name string) (*ResourceInfo, error)

GetResourceInfo get resource info

func (*TypedRuntimeImpl) GetResourceStats added in v1.2.3

func (r *TypedRuntimeImpl) GetResourceStats() map[string]any

GetResourceStats get resource statistics

func (*TypedRuntimeImpl) GetSharedResource added in v1.2.3

func (r *TypedRuntimeImpl) GetSharedResource(name string) (any, error)

GetSharedResource get shared resource

func (*TypedRuntimeImpl) ListResources added in v1.2.3

func (r *TypedRuntimeImpl) ListResources() []*ResourceInfo

ListResources list all resources

func (*TypedRuntimeImpl) RegisterPrivateResource added in v1.2.3

func (r *TypedRuntimeImpl) RegisterPrivateResource(name string, resource any) error

RegisterPrivateResource register private resource

func (*TypedRuntimeImpl) RegisterResource added in v1.2.3

func (r *TypedRuntimeImpl) RegisterResource(name string, resource any) error

RegisterResource register resource (compatible with old interface)

func (*TypedRuntimeImpl) RegisterSharedResource added in v1.2.3

func (r *TypedRuntimeImpl) RegisterSharedResource(name string, resource any) error

RegisterSharedResource register shared resource

func (*TypedRuntimeImpl) RemoveListener added in v1.2.3

func (r *TypedRuntimeImpl) RemoveListener(listener EventListener)

RemoveListener remove event listener

func (*TypedRuntimeImpl) SetConfig added in v1.2.3

func (r *TypedRuntimeImpl) SetConfig(conf config.Config)

SetConfig set configuration

func (*TypedRuntimeImpl) Shutdown added in v1.5.3

func (r *TypedRuntimeImpl) Shutdown()

Shutdown delegates to the underlying runtime.

func (*TypedRuntimeImpl) WithPluginContext added in v1.2.3

func (r *TypedRuntimeImpl) WithPluginContext(pluginName string) Runtime

WithPluginContext create runtime with plugin context

type UnifiedRuntime added in v1.5.0

type UnifiedRuntime struct {
	// contains filtered or unexported fields
}

UnifiedRuntime is a unified Runtime implementation that consolidates all existing capabilities

func NewUnifiedRuntime added in v1.5.0

func NewUnifiedRuntime() *UnifiedRuntime

NewUnifiedRuntime creates a new unified Runtime instance

func (*UnifiedRuntime) AddListener added in v1.5.0

func (r *UnifiedRuntime) AddListener(listener EventListener, filter *EventFilter)

AddListener adds an event listener

func (*UnifiedRuntime) AddPluginListener added in v1.5.0

func (r *UnifiedRuntime) AddPluginListener(pluginName string, listener EventListener, filter *EventFilter)

AddPluginListener adds a plugin-specific event listener

func (*UnifiedRuntime) CleanupResources added in v1.5.0

func (r *UnifiedRuntime) CleanupResources(pluginID string) error

CleanupResources cleans up resources for a plugin. Permission: only the plugin that owns the resources (current plugin context), the "system" context, or empty context (e.g. during system shutdown) may call this for a given pluginID.

func (*UnifiedRuntime) Close added in v1.5.0

func (r *UnifiedRuntime) Close()

Close closes the Runtime (compatibility API)

func (*UnifiedRuntime) EmitEvent added in v1.5.0

func (r *UnifiedRuntime) EmitEvent(event PluginEvent)

EmitEvent publishes an event

func (*UnifiedRuntime) EmitPluginEvent added in v1.5.0

func (r *UnifiedRuntime) EmitPluginEvent(pluginName string, eventType string, data map[string]any)

EmitPluginEvent publishes a plugin event

func (*UnifiedRuntime) GetConfig added in v1.5.0

func (r *UnifiedRuntime) GetConfig() config.Config

GetConfig returns the config

func (*UnifiedRuntime) GetCurrentPluginContext added in v1.5.0

func (r *UnifiedRuntime) GetCurrentPluginContext() string

GetCurrentPluginContext returns current plugin context

func (*UnifiedRuntime) GetEventHistory added in v1.5.0

func (r *UnifiedRuntime) GetEventHistory(filter EventFilter) []PluginEvent

GetEventHistory returns event history

func (*UnifiedRuntime) GetEventStats added in v1.5.0

func (r *UnifiedRuntime) GetEventStats() map[string]any

GetEventStats returns event stats (delegates to event bus)

func (*UnifiedRuntime) GetLogger added in v1.5.0

func (r *UnifiedRuntime) GetLogger() log.Logger

GetLogger returns the logger

func (*UnifiedRuntime) GetPluginEventHistory added in v1.5.0

func (r *UnifiedRuntime) GetPluginEventHistory(pluginName string, filter EventFilter) []PluginEvent

GetPluginEventHistory returns plugin event history

func (*UnifiedRuntime) GetPrivateResource added in v1.5.0

func (r *UnifiedRuntime) GetPrivateResource(name string) (any, error)

GetPrivateResource gets a private (plugin-scoped) resource

func (*UnifiedRuntime) GetResource added in v1.5.0

func (r *UnifiedRuntime) GetResource(name string) (any, error)

GetResource gets a resource (backward compatible API)

func (*UnifiedRuntime) GetResourceInfo added in v1.5.0

func (r *UnifiedRuntime) GetResourceInfo(name string) (*ResourceInfo, error)

GetResourceInfo returns a copy of resource info so callers cannot mutate internal state.

func (*UnifiedRuntime) GetResourceStats added in v1.5.0

func (r *UnifiedRuntime) GetResourceStats() map[string]any

GetResourceStats returns resource statistics including size and plugin information

func (*UnifiedRuntime) GetSharedResource added in v1.5.0

func (r *UnifiedRuntime) GetSharedResource(name string) (any, error)

GetSharedResource retrieves a shared resource

func (*UnifiedRuntime) ListResources added in v1.5.0

func (r *UnifiedRuntime) ListResources() []*ResourceInfo

ListResources returns copies of all resource infos so callers cannot mutate internal state.

func (*UnifiedRuntime) RegisterPrivateResource added in v1.5.0

func (r *UnifiedRuntime) RegisterPrivateResource(name string, resource any) error

RegisterPrivateResource registers a private (plugin-scoped) resource. If the key already exists, the previous resource is closed before being replaced.

func (*UnifiedRuntime) RegisterResource added in v1.5.0

func (r *UnifiedRuntime) RegisterResource(name string, resource any) error

RegisterResource registers a resource (backward compatible API)

func (*UnifiedRuntime) RegisterSharedResource added in v1.5.0

func (r *UnifiedRuntime) RegisterSharedResource(name string, resource any) error

RegisterSharedResource registers a shared resource. If the name already exists, the previous resource is closed before being replaced to avoid leaks.

func (*UnifiedRuntime) RemoveListener added in v1.5.0

func (r *UnifiedRuntime) RemoveListener(listener EventListener)

RemoveListener removes an event listener

func (*UnifiedRuntime) SetConfig added in v1.5.0

func (r *UnifiedRuntime) SetConfig(conf config.Config)

SetConfig sets the config

func (*UnifiedRuntime) SetEventDispatchMode added in v1.5.0

func (r *UnifiedRuntime) SetEventDispatchMode(mode string) error

SetEventDispatchMode sets event dispatch mode (delegates to event bus)

func (*UnifiedRuntime) SetEventTimeout added in v1.5.0

func (r *UnifiedRuntime) SetEventTimeout(timeout time.Duration)

SetEventTimeout sets event timeout (delegates to event bus)

func (*UnifiedRuntime) SetEventWorkerPoolSize added in v1.5.0

func (r *UnifiedRuntime) SetEventWorkerPoolSize(size int)

SetEventWorkerPoolSize sets event worker pool size (delegates to event bus)

func (*UnifiedRuntime) SetLogger added in v1.5.0

func (r *UnifiedRuntime) SetLogger(logger log.Logger)

SetLogger sets the logger

func (*UnifiedRuntime) Shutdown added in v1.5.0

func (r *UnifiedRuntime) Shutdown()

Shutdown closes the Runtime

func (*UnifiedRuntime) WithPluginContext added in v1.5.0

func (r *UnifiedRuntime) WithPluginContext(pluginName string) Runtime

WithPluginContext creates a Runtime bound with plugin context Implements context forging prevention similar to simpleRuntime

type Upgradable

type Upgradable interface {
	// GetCapabilities returns the supported upgrade capabilities
	// Lists the ways this plugin can be upgraded
	GetCapabilities() []UpgradeCapability

	// PrepareUpgrade prepares for version upgrade
	// Validates and prepares for the upgrade process
	PrepareUpgrade(targetVersion string) error

	// ExecuteUpgrade performs the actual version upgrade
	// Applies the upgrade and verifies success
	ExecuteUpgrade(targetVersion string) error

	// RollbackUpgrade reverts to the previous version
	// Restores the plugin to its previous state
	RollbackUpgrade(previousVersion string) error
}

Upgradable defines methods for plugin upgrade operations Manages plugin version upgrades and updates

type UpgradeCapability

type UpgradeCapability int

UpgradeCapability defines the various ways a plugin can be upgraded during runtime

const (
	// UpgradeNone indicates the plugin does not support any runtime upgrades
	// Must be stopped and restarted to apply any changes
	UpgradeNone UpgradeCapability = iota

	// UpgradeConfig indicates the plugin can update its configuration without restart
	// Supports runtime configuration changes but not code updates
	UpgradeConfig

	// UpgradeVersion indicates the plugin can perform version upgrades without restart
	// Supports both configuration and code updates during runtime
	UpgradeVersion

	// UpgradeReplace indicates the plugin supports complete replacement during runtime
	// Can be entirely replaced with a new instance while maintaining service
	UpgradeReplace
)

type Version added in v1.2.3

type Version struct {
	Major      int
	Minor      int
	Patch      int
	PreRelease string
	Build      string
	Original   string
}

Version structure

func (*Version) IsPreRelease added in v1.2.3

func (v *Version) IsPreRelease() bool

IsPreRelease checks if it's a pre-release version

func (*Version) IsStable added in v1.2.3

func (v *Version) IsStable() bool

IsStable checks if it's a stable version

func (*Version) String added in v1.2.3

func (v *Version) String() string

GetVersionString gets version string representation

type VersionConflict added in v1.2.3

type VersionConflict struct {
	PluginID         string `json:"plugin_id"`
	DependencyID     string `json:"dependency_id"`
	RequiredVersion  string `json:"required_version"`
	AvailableVersion string `json:"available_version"`
	ConflictType     string `json:"conflict_type"`
	Description      string `json:"description"`
}

VersionConflict version conflict information

type VersionConstraint added in v1.2.3

type VersionConstraint struct {
	MinVersion      string   `json:"min_version"`      // Minimum version
	MaxVersion      string   `json:"max_version"`      // Maximum version
	ExactVersion    string   `json:"exact_version"`    // Exact version
	ExcludeVersions []string `json:"exclude_versions"` // Excluded versions
}

VersionConstraint version constraint

type VersionManager added in v1.2.3

type VersionManager interface {
	// ParseVersion parses version string
	ParseVersion(version string) (*Version, error)
	// CompareVersions compares two versions
	CompareVersions(v1, v2 *Version) int
	// SatisfiesConstraint checks if version satisfies constraint
	SatisfiesConstraint(version *Version, constraint *VersionConstraint) bool
	// ResolveVersionConflict resolves version conflicts
	ResolveVersionConflict(conflicts []VersionConflict) (map[string]string, error)
	// GetCompatibleVersions gets compatible version list
	GetCompatibleVersions(required *VersionConstraint, available []*Version) []*Version
}

VersionManager version manager interface

func NewVersionManager added in v1.2.3

func NewVersionManager() VersionManager

NewVersionManager creates a new version manager

type VersionRange added in v1.2.3

type VersionRange struct {
	Min *Version
	Max *Version
}

VersionRange version range

Directories

Path Synopsis
db
mysql module
pgsql module
mq
kafka module
nosql
redis module
polaris module
seata module
service
grpc module
http module
sql
base module
interfaces module
mysql module
pgsql module
swagger module
tracer module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL