plugins

package
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: Apache-2.0 Imports: 19 Imported by: 48

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
plugin_compat.go Legacy compatibility plugin vocabulary such as upgrade-related statuses and config hooks
base.go TypedBasePlugin and BasePlugin core lifecycle implementations
base_compat.go Legacy compatibility upgrade hooks on BasePlugin
unified_runtime.go UnifiedRuntime implementation with resource and event management
events.go Core event types and priority definitions
events_compat.go Legacy upgrade/rollback event vocabulary kept for compatibility
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_compat.go Legacy compatibility upgrade hooks for plugin-owned logic

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 Legacy compatibility state only; not part of the default core lifecycle
StatusRollback Legacy compatibility state only; not part of the default core lifecycle

Creating a Plugin

Basic Plugin

PluginProtocol() is now mandatory. If you embed BasePlugin or TypedBasePlugin, the default managed protocol is already declared for you. If your plugin truly supports context-aware lifecycle, override PluginProtocol() explicitly.

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 run the framework phases inline and check ctx at every phase boundary. For genuine cancellation of the plugin's own work, implement the context-aware step hooks (ContextResourceInitializer, ContextStartupTasker, ContextCleanupTasker); the framework passes ctx straight through so your code can observe ctx.Done(). A plugin that implements only the non-context steps (InitializeResources/StartupTasks/CleanupTasks) cannot be force-stopped — Go cannot kill a running goroutine — so on timeout the work is abandoned safely (counted via OrphanedStageCount), never truly cancelled.

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
}

func (p *ContextAwarePlugin) PluginProtocol() plugins.PluginProtocol {
    return plugins.PluginProtocol{
        ManagedLifecycle: true,
        HealthAware:      true,
        ContextLifecycle: 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()

Legacy Upgrade Compatibility

The following hooks remain available only for plugin-owned compatibility flows. They are not part of Lynx core's default lifecycle, and restart/external rollout remains the preferred model for code and deployment changes.

// Legacy compatibility capabilities for plugin-owned upgrade logic
const (
    UpgradeNone    // Restart-based handling; no legacy upgrade hooks advertised
    UpgradeConfig  // Legacy plugin-owned config mutation hook
    UpgradeVersion // Legacy plugin-owned version upgrade hook
    UpgradeReplace // Legacy plugin-owned replacement hook
)

// Legacy compatibility hook: prepare plugin-owned upgrade logic
plugin.PrepareUpgrade("2.0.0")

// Legacy compatibility hook: execute plugin-owned upgrade logic
plugin.ExecuteUpgrade("2.0.0")

// Legacy compatibility hook: execute plugin-owned rollback logic
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 = "plugin.initializing"
	EventPluginInitialized  = "plugin.initialized"
	EventPluginStarting     = "plugin.starting"
	EventPluginStarted      = "plugin.started"
	EventPluginStopping     = "plugin.stopping"
	EventPluginStopped      = "plugin.stopped"
)

Plugin lifecycle event strings, used as the Type field in PluginEvent.

View Source
const (
	EventHealthCheckStarted   = "health.check.started"
	EventHealthCheckRunning   = "health.check.running"
	EventHealthCheckDone      = "health.check.done"
	EventHealthStatusOK       = "health.status.ok"
	EventHealthStatusWarning  = "health.status.warning"
	EventHealthStatusCritical = "health.status.critical"
	EventHealthStatusUnknown  = "health.status.unknown"
	EventHealthMetricsChanged = "health.metrics.changed"
	EventHealthThresholdHit   = "health.metrics.threshold"
	EventHealthStatusChanged  = "health.status.changed"
	EventHealthCheckFailed    = "health.check.failed"
)

Health check event strings.

View Source
const (
	EventResourceExhausted   = "resource.exhausted"
	EventPerformanceDegraded = "performance.degraded"
)

Resource utilisation event strings.

View Source
const (
	EventConfigurationChanged = "config.changed"
	EventConfigurationInvalid = "config.invalid"
	EventConfigurationApplied = "config.applied"
)

Configuration change event strings.

View Source
const (
	EventDependencyMissing       = "dependency.missing"
	EventDependencyStatusChanged = "dependency.status.changed"
	EventDependencyError         = "dependency.error"
)

Dependency state event strings.

View Source
const (
	EventSecurityViolation    = "security.violation"
	EventAuthenticationFailed = "auth.failed"
	EventAuthorizationDenied  = "auth.denied"
)

Security event strings.

View Source
const (
	EventResourceCreated     = "resource.created"
	EventResourceModified    = "resource.modified"
	EventResourceDeleted     = "resource.deleted"
	EventResourceUnavailable = "resource.unavailable"
)

Resource lifecycle event strings.

View Source
const (
	EventErrorOccurred  = "error.occurred"
	EventErrorResolved  = "error.resolved"
	EventPanicRecovered = "panic.recovered"
)

Error event strings.

View Source
const (
	// EventUpgradeAvailable indicates new version availability.
	EventUpgradeAvailable = "upgrade.available"

	// EventUpgradeInitiated indicates upgrade process start.
	EventUpgradeInitiated = "upgrade.initiated"

	// EventUpgradeValidating indicates upgrade validation.
	EventUpgradeValidating = "upgrade.validating"

	// EventUpgradeInProgress indicates that the upgrade process is ongoing.
	EventUpgradeInProgress = "upgrade.in_progress"

	// EventUpgradeCompleted indicates successful upgrade.
	EventUpgradeCompleted = "upgrade.completed"

	// EventUpgradeFailed indicates failed upgrade attempt.
	EventUpgradeFailed = "upgrade.failed"

	// EventRollbackInitiated indicates version rollback start.
	EventRollbackInitiated = "rollback.initiated"

	// EventRollbackInProgress indicates that the rollback process is ongoing.
	EventRollbackInProgress = "rollback.in_progress"

	// EventRollbackCompleted indicates successful rollback.
	EventRollbackCompleted = "rollback.completed"

	// EventRollbackFailed indicates failed rollback attempt.
	EventRollbackFailed = "rollback.failed"
)

Upgrade and rollback event types are retained only for compatibility with older plugins and external consumers. Lynx core does not use them as part of the default lifecycle model, and restart/external rollout remains the preferred way to apply code or deployment changes.

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")

	// ErrRuntimeConfigNotSupported indicates that runtime configuration orchestration is not supported
	// by the Lynx core base plugin implementation.
	ErrRuntimeConfigNotSupported = NewStandardError(ErrorCodeRuntimeConfigNotSupported, "runtime configuration not supported", "Lynx core does not orchestrate runtime plugin reconfiguration")

	// 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 HasTrueContextLifecycle added in v1.6.0

func HasTrueContextLifecycle(plugin any) bool

HasTrueContextLifecycle reports whether a plugin's lifecycle is genuinely cancellable through its context-aware entrypoints. It is true when the plugin exposes the LifecycleWithContext entrypoints AND either:

  • implements at least one context-aware step hook (the preferred path: the plugin's own work observes ctx, so cancellation is real), or
  • uses the legacy explicit opt-in: declares PluginProtocol().ContextLifecycle and asserts ContextAwareness.IsContextAware()=true.

The framework routes such plugins through StartContext/StopContext/InitializeContext.

func InitializePluginResources added in v1.6.0

func InitializePluginResources(plugin any, rt Runtime) error

InitializePluginResources executes the resource initialization hook when present.

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 reports whether two plugin versions share a major version.

func Publish added in v1.6.0

func Publish[T any](payload T)

Publish broadcasts a typed event to all registered listeners. The event payload is wrapped in an Event envelope for type safety. Example:

type OrderCreated struct { OrderID string }
Publish(OrderCreated{OrderID: "123"})

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 RunCleanupTasks added in v1.6.0

func RunCleanupTasks(plugin any) error

RunCleanupTasks executes cleanup tasks when present.

func RunCleanupTasksContext added in v1.6.2

func RunCleanupTasksContext(ctx context.Context, plugin any) (bool, error)

RunCleanupTasksContext runs the context-aware cleanup hook when present. The returned bool reports whether a context-aware hook handled the call.

func RunHealthCheck added in v1.6.0

func RunHealthCheck(plugin any) error

RunHealthCheck executes the plugin health check when present.

func RunInitializeResourcesContext added in v1.6.2

func RunInitializeResourcesContext(ctx context.Context, plugin any, rt Runtime) (bool, error)

RunInitializeResourcesContext runs the context-aware resource init hook when present. The returned bool reports whether a context-aware hook handled the call; when false, the caller should fall back to the non-context ResourceInitializer.

func RunStartupTasks added in v1.6.0

func RunStartupTasks(plugin any) error

RunStartupTasks executes startup tasks when present.

func RunStartupTasksContext added in v1.6.2

func RunStartupTasksContext(ctx context.Context, plugin any) (bool, error)

RunStartupTasksContext runs the context-aware startup hook when present. The returned bool reports whether a context-aware hook handled the call.

func SetGlobalEventHooks added in v1.6.0

func SetGlobalEventHooks(emitter func(PluginEvent), adder func(EventListener, *EventFilter))

SetGlobalEventHooks wires up the runtime event emitter and listener adder. This must be called once during framework initialisation (typically from lynx.App). Calling it a second time replaces the previous hooks.

func Subscribe added in v1.6.0

func Subscribe[T any](listener func(ctx context.Context, event T) error, filter *EventFilter)

Subscribe registers a typed event listener with optional filtering. The listener function receives strongly-typed event payloads. Example:

type OrderCreated struct { OrderID string }
Subscribe[OrderCreated](func(ctx context.Context, event OrderCreated) error)

func SupportsContextSteps added in v1.6.2

func SupportsContextSteps(plugin any) bool

SupportsContextSteps reports whether a plugin implements any context-aware lifecycle step hook, meaning at least one phase of its lifecycle can be genuinely cancelled rather than merely abandoned on timeout.

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 CleanupTasker added in v1.6.0

type CleanupTasker interface {
	CleanupTasks() error
}

CleanupTasker indicates the plugin exposes shutdown cleanup work.

type ConfigProvider

type ConfigProvider interface {
	// GetConfig returns the plugin configuration manager.
	GetConfig() config.Config
}

ConfigProvider provides access to plugin configuration.

type ConfigRollbacker deprecated added in v1.6.0

type ConfigRollbacker interface {
	RollbackConfig(previous any) error
}

ConfigRollbacker defines optional compatibility rollback support for plugin-owned configuration handling. Lynx core itself remains restart-based.

Deprecated: retained only for legacy compatibility hooks.

type ConfigValidator deprecated added in v1.6.0

type ConfigValidator interface {
	ValidateConfig(conf any) error
}

ConfigValidator defines optional compatibility validation for plugin-owned configuration handling. It does not make live core reload a supported path.

Deprecated: retained only for legacy compatibility hooks.

type Configurable deprecated

type Configurable interface {
	// Configure applies plugin-specific configuration in plugin-owned code paths.
	Configure(conf any) error
}

Configurable defines optional compatibility hooks for plugins that manage their own runtime configuration concerns. Lynx core does not orchestrate in-process config rollout; configuration changes are applied by restart.

Deprecated: retained only for legacy compatibility hooks.

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 ContextCleanupTasker added in v1.6.2

type ContextCleanupTasker interface {
	CleanupTasksContext(ctx context.Context) error
}

ContextCleanupTasker is the context-aware form of CleanupTasker.

type ContextResourceInitializer added in v1.6.2

type ContextResourceInitializer interface {
	InitializeResourcesContext(ctx context.Context, rt Runtime) error
}

ContextResourceInitializer is the context-aware form of ResourceInitializer.

type ContextStartupTasker added in v1.6.2

type ContextStartupTasker interface {
	StartupTasksContext(ctx context.Context) error
}

ContextStartupTasker is the context-aware form of StartupTasker.

type CorePlugin added in v1.6.0

type CorePlugin interface {
	Metadata
	Lifecycle
	DependencyAware
}

CorePlugin is the minimal lifecycle-managed plugin contract. It intentionally excludes step-level hooks so frameworks can reason about plugin identity/lifecycle separately from optional operational capabilities.

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 plugin's required and optional dependencies.
	GetDependencies() []Dependency
}

DependencyAware lets a plugin declare the dependencies that drive load order. The framework calls GetDependencies before initialization to build the graph.

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]any

GetDependencyStats gets dependency statistics

func (*DependencyGraph) GetDependencyTree added in v1.2.3

func (dg *DependencyGraph) GetDependencyTree(pluginID string) map[string]any

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"
	ErrorCodeRuntimeConfigNotSupported ErrorCode = "RUNTIME_CONFIG_NOT_SUPPORTED"

	// 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 Event added in v1.6.0

type Event[T any] struct {
	Payload T
}

Event wraps event payloads with a concrete type so adapters can avoid untyped values on the hot path while keeping the legacy PluginEvent API intact.

func NewEvent added in v1.6.0

func NewEvent[T any](payload T) Event[T]

NewEvent creates a typed event envelope.

func (Event[T]) Unwrap added in v1.6.0

func (e Event[T]) Unwrap() T

Unwrap returns the original typed payload.

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

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 a single plugin event.
	HandleEvent(event PluginEvent)
}

EventHandler processes plugin lifecycle events delivered by the event system.

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.

const (
	// EventPluginManagerShutdown indicates the plugin manager has begun shutdown.
	// Emitted once before UnloadPlugins stops individual plugins.
	EventPluginManagerShutdown EventType = "system.plugin_manager_shutdown"
)

System-level event types emitted by the plugin manager infrastructure itself

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.
	GetHealth() HealthReport
}

HealthCheck defines methods for plugin health monitoring.

type HealthChecker added in v1.6.0

type HealthChecker interface {
	CheckHealth() error
}

HealthChecker indicates the plugin can actively verify its own health.

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.

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 (resources, connections, internal state).
	// Must be called before Start.
	Initialize(plugin Plugin, rt Runtime) error

	// Start begins the plugin's main functionality. Call only after Initialize succeeds.
	Start(plugin Plugin) error

	// Stop gracefully terminates the plugin, releasing resources and connections.
	Stop(plugin Plugin) error

	// Status returns the plugin's current lifecycle state.
	Status(plugin Plugin) PluginStatus
}

Lifecycle defines the core lifecycle transitions the framework drives on a plugin. The framework calls these in order: Initialize, then Start; Stop on shutdown.

type LifecycleSteps

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

LifecycleSteps are the plugin-supplied hooks the base lifecycle invokes at each phase: InitializeResources during Initialize, StartupTasks and CheckHealth during Start, CleanupTasks during Stop. Embedding TypedBasePlugin provides no-op defaults to override as needed.

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 optional; if not implemented, the manager will fall back to calling the non-context methods.

func GetTrueContextLifecycle added in v1.6.0

func GetTrueContextLifecycle(plugin any) (LifecycleWithContext, bool)

GetTrueContextLifecycle returns the plugin's LifecycleWithContext only when it is truly context-aware according to HasTrueContextLifecycle.

type LogProvider

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

LogProvider provides access to logging functionality.

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 plugin's unique identifier, which must be unique across all plugins.
	ID() string

	// Name returns the human-readable display name.
	Name() string

	// Description returns a description of the plugin's purpose and functionality.
	Description() string

	// Version returns the semantic version (MAJOR.MINOR.PATCH).
	Version() string

	// Weight returns the load-ordering weight; higher values load first.
	Weight() int
}

Metadata exposes a plugin's identity and descriptive attributes.

type Plugin

type Plugin interface {
	CorePlugin
	LifecycleSteps
}

Plugin is the current managed plugin contract used by Lynx today. New code should prefer reasoning in terms of CorePlugin plus specific capability interfaces below, rather than assuming every plugin must implement one wide interface.

type PluginCapabilities added in v1.6.0

type PluginCapabilities struct {
	HasMetadata         bool
	HasLifecycle        bool
	HasDependencies     bool
	HasResourceInit     bool
	HasStartupTasks     bool
	HasCleanupTasks     bool
	HasHealthCheck      bool
	HasLifecycleWithCtx bool
	IsTrulyContextAware bool
	// HasContextSteps is true when the plugin implements at least one context-aware
	// lifecycle step hook (ContextResourceInitializer / ContextStartupTasker /
	// ContextCleanupTasker), meaning that phase's work genuinely observes ctx.
	HasContextSteps  bool
	IsManagedPlugin  bool
	Protocol         PluginProtocol
	ProtocolExplicit bool
}

PluginCapabilities describes which optional capabilities a plugin exposes.

func DescribePluginCapabilities added in v1.6.0

func DescribePluginCapabilities(plugin any) PluginCapabilities

DescribePluginCapabilities returns a structured capability report for a plugin-like object.

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]any `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 any) *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 PluginProtocol added in v1.6.0

type PluginProtocol struct {
	ManagedLifecycle bool
	HealthAware      bool
	ContextLifecycle bool
	Recoverable      bool
}

PluginProtocol declares lifecycle-related capabilities explicitly. New plugins should prefer declaring protocol instead of relying on legacy runtime probing.

Configuration-mutation flags (ConfigHotReload, ConfigValidation, ConfigRollback) have been removed: Lynx core applies configuration changes by process restart, so advertising in-process config-reload capability is misleading. Plugins that previously set those flags should use Configurable / ConfigValidator / ConfigRollbacker interfaces directly, and callers should rely on GetRestartRequirementReport() to discover which plugins need a restart after configuration changes.

type PluginStatus

type PluginStatus int

PluginStatus is the lifecycle state of a plugin.

const (
	// StatusInactive — loaded but not yet initialized; the initial state.
	StatusInactive PluginStatus = iota
	// StatusInitializing — Initialize/Start is in progress.
	StatusInitializing
	// StatusActive — fully operational; processing requests.
	StatusActive
	// StatusSuspended — temporarily paused; resources retained, can resume without reinit.
	StatusSuspended
	// StatusStopping — graceful shutdown in progress.
	StatusStopping
	// StatusTerminated — cleanly shut down; requires full reinit to restart.
	StatusTerminated
	// StatusFailed — encountered a fatal error; non-operational.
	StatusFailed
)
const StatusRollback PluginStatus = 8

StatusRollback is legacy compatibility vocabulary; Lynx core does not orchestrate in-process rollback as a standard lifecycle path.

Deprecated: retained only for legacy compatibility.

const StatusUpgrading PluginStatus = 7

StatusUpgrading is legacy compatibility vocabulary; Lynx core does not treat live upgrade as a standard lifecycle path.

Deprecated: retained only for legacy compatibility.

type ProtocolAwarePlugin added in v1.6.0

type ProtocolAwarePlugin interface {
	PluginProtocol() PluginProtocol
}

ProtocolAwarePlugin explicitly declares its lifecycle protocol.

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 ResourceHandle added in v1.6.0

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

ResourceHandle provides a stable typed view over a named runtime resource. It does not hold the concrete object; each call resolves the current resource, so it remains valid across runtime replacements.

func NewResourceHandle added in v1.6.0

func NewResourceHandle[T any](manager ResourceManager, name string) ResourceHandle[T]

NewResourceHandle creates a stable typed handle for a named resource.

func (ResourceHandle[T]) Get added in v1.6.0

func (h ResourceHandle[T]) Get() (T, error)

Get resolves the current typed resource.

func (ResourceHandle[T]) Info added in v1.6.0

func (h ResourceHandle[T]) Info() (*ResourceInfo, error)

Info returns the current resource metadata when the manager supports it.

func (ResourceHandle[T]) Name added in v1.6.0

func (h ResourceHandle[T]) Name() string

Name returns the bound resource name.

type ResourceInfo added in v1.2.3

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

ResourceInfo resource information

type ResourceInitializer added in v1.6.0

type ResourceInitializer interface {
	InitializeResources(rt Runtime) error
}

ResourceInitializer indicates the plugin has an initialization hook for runtime-bound resources.

type ResourceManager

type ResourceManager interface {
	// GetResource retrieves a shared plugin resource by name.
	GetResource(name string) (any, error)

	// RegisterResource registers a resource to be shared with other plugins.
	RegisterResource(name string, resource any) error

	GetResourceInfo(name string) (*ResourceInfo, error)
	ListResources() []*ResourceInfo
	CleanupResources(pluginID string) error
	GetResourceStats() map[string]any
}

ResourceManager manages named resources shared across plugins, plus their lifecycle metadata.

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 StartupTasker added in v1.6.0

type StartupTasker interface {
	StartupTasks() error
}

StartupTasker indicates the plugin exposes startup work beyond basic activation.

type Suspendable

type Suspendable interface {
	// Suspend pauses plugin operations while preserving state.
	Suspend() error

	// Resume restores operation from a suspended state without reinitialization.
	Resume() error
}

Suspendable allows temporarily pausing and resuming a plugin without reinitializing it; suspended plugins retain their state and resources.

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 TypedBasePlugin with the provided metadata. Plugins should embed this and call it from their own constructor.

func (*TypedBasePlugin[T]) AddCapability deprecated added in v1.6.0

func (p *TypedBasePlugin[T]) AddCapability(cap UpgradeCapability)

AddCapability appends an upgrade capability when it is not already declared.

Deprecated: retained only for legacy compatibility metadata.

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 appends an event filter; events that match no filter are suppressed.

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

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

ApplyConfig is the no-op default; override to apply validated config.

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

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

CheckHealth is the no-op default; override to report plugin-specific health.

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

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

CleanupTasks is a no-op default; override in the embedding struct to run teardown work.

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

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

Deprecated: retained only for legacy compatibility; base plugin does not support runtime configuration reload.

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.

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.

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

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

EmitEventInternal stamps the event with plugin ID, status, and timestamp, then forwards it to the runtime bus. Dropped silently when the runtime has not been set yet.

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

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

EventMatchesFilter reports whether an event satisfies all non-empty criteria in filter.

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

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

ExecuteUpgrade is intentionally unsupported by the base plugin.

Deprecated: retained only for legacy compatibility.

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

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

GetCapabilities returns the plugin's upgrade capabilities.

Deprecated: retained only for legacy compatibility metadata.

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 runs CheckHealth (when active) and returns a structured health report.

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

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

GetTypedInstance returns the concrete plugin instance stored in this base.

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

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

HandleConfigEvent processes configuration-related events. Override to add behavior.

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

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

HandleDefaultEvent processes events without a specific handler. Override to add behavior.

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

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

HandleDependencyEvent processes dependency-related events. Override to add behavior.

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

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

HandleEvent routes an event to the appropriate typed handler after filter check.

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

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

HandleHealthEvent processes health-related events. Override to add behavior.

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

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

ID returns the unique identifier of the plugin.

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

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

Initialize stores the runtime, drives the InitializeResources hook, and transitions the plugin from Inactive through Initializing back to Inactive on success.

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

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

InitializeContext initializes the plugin with genuine context cancellation. It mirrors StartContext: the ContextResourceInitializer hook is preferred for real cancellation, and a legacy ResourceInitializer is abandoned safely on timeout.

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

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

InitializeResources is a no-op default; override in the embedding struct to set up resources.

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 plugin name used for lookup and logging.

func (*TypedBasePlugin[T]) OrphanedStageCount added in v1.6.2

func (p *TypedBasePlugin[T]) OrphanedStageCount() int64

OrphanedStageCount returns the number of legacy lifecycle tasks that were abandoned after a context cancellation and are still running in the background. A non-zero value means a plugin's task is ignoring cancellation; it should drop back to zero once those tasks finish.

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

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

PerformRollback is intentionally unsupported by the base plugin.

Deprecated: retained only for legacy compatibility.

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

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

PerformUpgrade is intentionally unsupported by the base plugin.

Deprecated: retained only for legacy compatibility.

func (*TypedBasePlugin[T]) PluginProtocol added in v1.6.0

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

PluginProtocol declares the default explicit lifecycle protocol for base plugins. Concrete plugins may override this method to opt into stronger capabilities. The framework default stays conservative: plugin orchestration and stability are core concerns, while runtime hot-reload/rollback capabilities must be explicitly declared by concrete plugins rather than inherited implicitly.

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

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

PrepareUpgrade is intentionally unsupported by the base plugin; live upgrade belongs to external rollout tooling, not Lynx core.

Deprecated: retained only for legacy compatibility.

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

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

RemoveEventFilter removes the filter at the given index.

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

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

Resume transitions the plugin from Suspended back to Active.

func (*TypedBasePlugin[T]) RollbackConfig deprecated added in v1.6.0

func (p *TypedBasePlugin[T]) RollbackConfig(previous any) error

Deprecated: retained only for legacy compatibility; base plugin does not support runtime configuration rollback.

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

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

RollbackUpgrade is intentionally unsupported by the base plugin.

Deprecated: retained only for legacy compatibility.

func (*TypedBasePlugin[T]) SetCapabilities deprecated added in v1.6.0

func (p *TypedBasePlugin[T]) SetCapabilities(caps ...UpgradeCapability)

SetCapabilities replaces the plugin's declared upgrade capabilities.

Deprecated: retained only for legacy compatibility metadata.

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

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

SetStatus updates the plugin's lifecycle state.

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

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

ShouldEmitEvent returns true if the event passes all configured filters, or when no filters are configured.

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

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

ShouldHandleEvent delegates to ShouldEmitEvent; separate entry point for incoming event routing.

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

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

Start runs StartupTasks and CheckHealth, then transitions the plugin to Active.

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

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

StartContext starts the plugin with genuine context cancellation.

Unlike a naive wrapper that spawns Start in a goroutine and returns early on ctx.Done() (leaking the goroutine and letting it flip the plugin to Active behind the caller's back), this implementation:

  • runs the framework lifecycle inline and checks ctx at every phase boundary, so a cancelled context aborts progression instead of racing it;
  • prefers the plugin's ContextStartupTasker hook, passing ctx straight through so the plugin's own work observes cancellation — this is real cancellation;
  • for a legacy StartupTasker that cannot observe ctx, honours the deadline for the caller via runLegacyStageWatched and abandons the work *safely* — the abandoned goroutine never mutates plugin status, and the orphan is counted and logged rather than silently leaked;
  • re-checks ctx after the startup stage so a late-completing legacy task can never promote the plugin to Active once cancellation has been observed.

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

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

StartupTasks is a no-op default; override in the embedding struct to run startup work.

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

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

Status returns the plugin's current lifecycle state.

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

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

Stop runs CleanupTasks and transitions the plugin to Terminated.

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

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

StopContext stops the plugin with genuine context cancellation. It mirrors StartContext: framework phases run inline with ctx checks, the ContextCleanupTasker hook is preferred for real cancellation, and a legacy CleanupTasker is abandoned safely (counted, never corrupting status) on timeout.

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

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

SupportsCapability reports whether the plugin declares the given upgrade capability.

Deprecated: retained only for legacy compatibility metadata.

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

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

Suspend pauses the plugin without releasing its resources, moving it to Suspended.

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

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

ValidateConfig is the no-op default; override to validate config before applying it.

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 TypedEventEmitter added in v1.6.0

type TypedEventEmitter[T any] interface {
	EmitTypedEvent(event Event[T])
	AddTypedListener(listener TypedEventListener[T], filter *EventFilter)
	RemoveTypedListener(listener TypedEventListener[T])
	GetTypedEventHistory(filter EventFilter) []Event[T]
}

TypedEventEmitter provides type-safe event publishing/listening for new integrations.

type TypedEventListener added in v1.6.0

type TypedEventListener[T any] interface {
	HandleTypedEvent(event Event[T])
	GetListenerID() string
}

TypedEventListener provides type-safe event handling for new integrations.

type TypedEventProcessor added in v1.6.0

type TypedEventProcessor[T any] interface {
	ProcessTypedEvent(event Event[T]) bool
	AddFilter(filter EventFilter)
	RemoveFilter(filterID string)
}

TypedEventProcessor provides a type-safe event processor for new integrations.

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)

func (*TypedRuntimeImpl) AddPluginListener added in v1.2.3

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

func (*TypedRuntimeImpl) CleanupResources added in v1.2.3

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

func (*TypedRuntimeImpl) EmitEvent added in v1.2.3

func (r *TypedRuntimeImpl) EmitEvent(event PluginEvent)

func (*TypedRuntimeImpl) EmitPluginEvent added in v1.2.3

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

func (*TypedRuntimeImpl) GetConfig added in v1.2.3

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

func (*TypedRuntimeImpl) GetCurrentPluginContext added in v1.2.3

func (r *TypedRuntimeImpl) GetCurrentPluginContext() string

func (*TypedRuntimeImpl) GetEventHistory added in v1.2.3

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

func (*TypedRuntimeImpl) GetLogger added in v1.2.3

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

func (*TypedRuntimeImpl) GetPluginEventHistory added in v1.2.3

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

func (*TypedRuntimeImpl) GetPrivateResource added in v1.2.3

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

func (*TypedRuntimeImpl) GetResource added in v1.2.3

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

func (*TypedRuntimeImpl) GetResourceInfo added in v1.2.3

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

func (*TypedRuntimeImpl) GetResourceStats added in v1.2.3

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

func (*TypedRuntimeImpl) GetSharedResource added in v1.2.3

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

func (*TypedRuntimeImpl) ListResources added in v1.2.3

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

func (*TypedRuntimeImpl) RegisterPrivateResource added in v1.2.3

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

func (*TypedRuntimeImpl) RegisterResource added in v1.2.3

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

func (*TypedRuntimeImpl) RegisterSharedResource added in v1.2.3

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

func (*TypedRuntimeImpl) RemoveListener added in v1.2.3

func (r *TypedRuntimeImpl) RemoveListener(listener EventListener)

func (*TypedRuntimeImpl) SetConfig added in v1.2.3

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

func (*TypedRuntimeImpl) Shutdown added in v1.5.3

func (r *TypedRuntimeImpl) Shutdown()

func (*TypedRuntimeImpl) WithPluginContext added in v1.2.3

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

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) AddTypedListener added in v1.6.0

func (r *UnifiedRuntime) AddTypedListener(listener TypedEventListener[PluginEvent], filter *EventFilter)

AddTypedListener adds a type-safe event listener.

func (*UnifiedRuntime) AddTypedPluginListener added in v1.6.0

func (r *UnifiedRuntime) AddTypedPluginListener(pluginName string, listener TypedEventListener[PluginEvent], filter *EventFilter)

AddTypedPluginListener adds a type-safe 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.

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) EmitTypedEvent added in v1.6.0

func (r *UnifiedRuntime) EmitTypedEvent(event Event[PluginEvent])

EmitTypedEvent publishes a typed event envelope.

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 from the adapter plus runtime state.

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) GetTypedEventHistory added in v1.6.0

func (r *UnifiedRuntime) GetTypedEventHistory(filter EventFilter) []Event[PluginEvent]

GetTypedEventHistory returns event history wrapped in typed envelopes.

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.

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.

func (*UnifiedRuntime) RemoveListener added in v1.5.0

func (r *UnifiedRuntime) RemoveListener(listener EventListener)

RemoveListener removes an event listener.

func (*UnifiedRuntime) RemoveTypedListener added in v1.6.0

func (r *UnifiedRuntime) RemoveTypedListener(listener TypedEventListener[PluginEvent])

RemoveTypedListener removes a type-safe event listener.

func (*UnifiedRuntime) SetConfig added in v1.5.0

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

SetConfig sets the config.

func (*UnifiedRuntime) SetEventBusAdapter added in v1.6.0

func (r *UnifiedRuntime) SetEventBusAdapter(adapter EventBusAdapter)

SetEventBusAdapter injects the event adapter used by this runtime instance.

func (*UnifiedRuntime) SetEventDispatchMode added in v1.5.0

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

SetEventDispatchMode sets event dispatch mode via the adapter.

func (*UnifiedRuntime) SetEventTimeout added in v1.5.0

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

SetEventTimeout sets event timeout via the adapter.

func (*UnifiedRuntime) SetEventWorkerPoolSize added in v1.5.0

func (r *UnifiedRuntime) SetEventWorkerPoolSize(size int)

SetEventWorkerPoolSize sets event worker pool size via the adapter.

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.

type Upgradable

type Upgradable interface {
	// GetCapabilities returns the legacy upgrade capabilities advertised by the plugin.
	GetCapabilities() []UpgradeCapability

	// PrepareUpgrade prepares plugin-owned upgrade logic.
	PrepareUpgrade(targetVersion string) error

	// ExecuteUpgrade performs plugin-owned upgrade logic.
	ExecuteUpgrade(targetVersion string) error

	// RollbackUpgrade performs plugin-owned rollback logic.
	RollbackUpgrade(previousVersion string) error
}

Upgradable defines legacy plugin-local upgrade hooks. This is intentionally optional compatibility metadata; Lynx core focuses on orchestration and does not provide a framework guarantee for live plugin replacement or in-process rollout.

type UpgradeCapability deprecated

type UpgradeCapability int

UpgradeCapability describes optional legacy plugin self-management behaviors. Lynx core does not treat live upgrade or replacement as a framework-level guarantee; these flags are advisory compatibility metadata only and concrete plugins must opt in explicitly where needed.

Deprecated: retained only for legacy compatibility metadata.

const (
	// UpgradeNone indicates the plugin does not advertise legacy live-upgrade hooks.
	// Restart remains the default core path for change application.
	UpgradeNone UpgradeCapability = iota

	// UpgradeConfig indicates the plugin advertises legacy self-managed config mutation.
	// This does not mean Lynx core orchestrates in-process rollout.
	UpgradeConfig

	// UpgradeVersion indicates the plugin advertises legacy self-managed version upgrade hooks.
	// Lynx core still expects restart/external rollout as the standard path.
	UpgradeVersion

	// UpgradeReplace indicates the plugin advertises legacy replacement semantics.
	// Lynx core does not provide a framework guarantee for live replacement.
	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