core

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2026 License: GPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package core provides the runtime foundation for git-ops.

The central type is ModuleManager, which owns plugin lifecycle, shared HTTP routing, configuration access, and the internal event bus. Plugins are loaded as Go plugins and initialized with a PluginRegistry so they can discover other plugins, register event types, subscribe to events, publish events, and access shared configuration.

The primary lifecycle interfaces are Module and Plugin. Modules participate in Init, Start, and Stop. Plugins are modules that also expose metadata, capabilities, and an Execute entry point for plugin-specific actions.

InternalEvent and related execution/event types define the shared event schema used across the reconciler, notifiers, UI, audit trail, and auxiliary system plugins.

Index

Constants

This section is empty.

Variables

View Source
var Version = "dev"

Version is the build-time version string for the git-ops binary. It is overridden via -ldflags during release and CI builds.

Functions

func DecodeConfigSection

func DecodeConfigSection(section map[string]any, out any) error

DecodeConfigSection decodes a config section into a struct. It is safe to call with a nil or empty section.

Types

type AlertSeverity

type AlertSeverity string

AlertSeverity describes how strongly downstream notifiers should surface an event.

const (
	// AlertSeverityInfo is a low-urgency informational signal.
	AlertSeverityInfo AlertSeverity = "info"
	// AlertSeverityWarning is a warning-level signal that may need attention.
	AlertSeverityWarning AlertSeverity = "warning"
	// AlertSeverityError is an error-level signal for failed operations.
	AlertSeverityError AlertSeverity = "error"
	// AlertSeverityCritical is a high-urgency signal for severe failures.
	AlertSeverityCritical AlertSeverity = "critical"
)

type Capability

type Capability string

Capability identifies one behavior that a plugin provides to the system.

const (
	// CapabilityNotifier marks plugins that emit notifications for selected events.
	CapabilityNotifier Capability = "NOTIFIER"
	// CapabilityUI marks plugins that expose user-facing HTTP routes or assets.
	CapabilityUI Capability = "UI"
	// CapabilityAPI marks plugins that expose machine-facing API endpoints.
	CapabilityAPI Capability = "API"
	// CapabilityMCP marks plugins that expose MCP-compatible endpoints or services.
	CapabilityMCP Capability = "MCP"
	// CapabilityTrigger marks plugins that request reconciliations from external input.
	CapabilityTrigger Capability = "TRIGGER"
	// CapabilitySecrets marks plugins that return secret key/value pairs.
	CapabilitySecrets Capability = "SECRETS"
	// CapabilityRuntimeFiles marks plugins that materialize files for compose execution.
	CapabilityRuntimeFiles Capability = "RUNTIME_FILES"
	// CapabilityAudit marks plugins that record or expose event history.
	CapabilityAudit Capability = "AUDIT"
	// CapabilityDeployer marks plugins that deploy or manage stacks.
	CapabilityDeployer Capability = "DEPLOYER"
	// CapabilitySystem marks plugins that provide core system behavior.
	CapabilitySystem Capability = "SYSTEM"
)

type ConfigProvider

type ConfigProvider interface {
	Config() any
}

ConfigProvider allows plugins to expose a UI-safe view of their configuration. Use core.Secret for any sensitive values to avoid leaking secrets.

type EventTypeDesc

type EventTypeDesc struct {
	Name        EventTypeName           // Unique ID, e.g., "deploy_success"
	Description string                  // Human-readable, e.g., "Fired when a stack deploys successfully"
	PayloadSpec map[string]PayloadField // Optional: Expected fields in event.Details (for validation/docs)
}

EventTypeDesc describes an event type that can be registered on the internal event bus for validation and discoverability.

type EventTypeName

type EventTypeName string

EventTypeName is a string alias for event type identifiers (e.g., "reconcile_now")

const EventTypeExecution EventTypeName = "execution"

EventTypeExecution is the canonical event type name for execution lifecycle updates.

type ExecutionEventInput

type ExecutionEventInput struct {
	ExecutionID   string
	Owner         string
	Repo          string
	FullName      string
	Stage         ExecutionStage
	Status        ExecutionStatus
	FailureClass  FailureClass
	AlertSeverity AlertSeverity
	NodeID        string
	Trigger       string
	Source        string
	Details       map[string]any
}

ExecutionEventInput captures the normalized fields used to build an execution event.

type ExecutionStage

type ExecutionStage string

ExecutionStage identifies the current phase of a stack execution lifecycle.

const (
	// ExecutionStageRequested is the point where execution has been requested.
	ExecutionStageRequested ExecutionStage = "requested"
	// ExecutionStageFetch is the phase that reads desired repository state.
	ExecutionStageFetch ExecutionStage = "fetch"
	// ExecutionStageDiff is the phase that compares desired and local state.
	ExecutionStageDiff ExecutionStage = "diff"
	// ExecutionStageHooks is the phase that runs deployment hooks.
	ExecutionStageHooks ExecutionStage = "hooks"
	// ExecutionStageComposeUp is the phase that applies stack changes via compose up.
	ExecutionStageComposeUp ExecutionStage = "compose_up"
	// ExecutionStageComposeDown is the phase that tears a stack down via compose down.
	ExecutionStageComposeDown ExecutionStage = "compose_down"
	// ExecutionStageComplete is the terminal success stage for an execution.
	ExecutionStageComplete ExecutionStage = "complete"
)

type ExecutionStatus

type ExecutionStatus string
const (
	// ExecutionStatusRequested indicates an execution has been queued but not yet running.
	ExecutionStatusRequested ExecutionStatus = "requested"
	// ExecutionStatusRunning indicates an execution is currently in progress.
	ExecutionStatusRunning ExecutionStatus = "running"
	// ExecutionStatusSucceeded indicates an execution completed successfully.
	ExecutionStatusSucceeded ExecutionStatus = "succeeded"
	// ExecutionStatusFailed indicates an execution ended with an error.
	ExecutionStatusFailed ExecutionStatus = "failed"
	// ExecutionStatusCancelled indicates an execution was cancelled before completion.
	ExecutionStatusCancelled ExecutionStatus = "cancelled"
)

type FailureClass

type FailureClass string

FailureClass categorizes why an execution failed.

const (
	// FailureClassUnknown is used when the failure could not be categorized.
	FailureClassUnknown FailureClass = "unknown"
	// FailureClassTransient indicates a retry may succeed later.
	FailureClassTransient FailureClass = "transient"
	// FailureClassPermanent indicates the same operation is expected to fail again.
	FailureClassPermanent FailureClass = "permanent"
	// FailureClassValidation indicates invalid inputs or local preconditions.
	FailureClassValidation FailureClass = "validation"
	// FailureClassDependency indicates an external dependency is missing or unavailable.
	FailureClassDependency FailureClass = "dependency"
)

type InternalEvent

type InternalEvent struct {
	Type      EventTypeName          `json:"type"`
	Timestamp time.Time              `json:"timestamp"`
	Source    string                 `json:"source"` // "timer", "webhook_trigger", "notifications", etc.
	Repo      string                 `json:"repo,omitempty"`
	Details   map[string]interface{} `json:"details,omitempty"` // Structured metadata lives here; keep the top-level surface small.
	Message   string                 `json:"message,omitempty"`
}

InternalEvent is the message sent over the internal event bus.

Structured metadata belongs in Details. Message is a short human-readable summary used by notifiers and audit views.

func NewExecutionEvent

func NewExecutionEvent(input ExecutionEventInput) InternalEvent

NewExecutionEvent builds a normalized InternalEvent for execution lifecycle updates.

type Listener

type Listener func(ctx context.Context, event InternalEvent)

Listener handles a published InternalEvent delivered by the event bus.

type Module

type Module interface {
	// Name returns the stable module name used for registration and logging.
	Name() string
	// Init prepares the module and receives the shared PluginRegistry.
	Init(ctx context.Context, logger *slog.Logger, registry PluginRegistry) error
	// Start begins the module's runtime work.
	Start(ctx context.Context) error
	// Stop shuts the module down and releases owned resources.
	Stop(ctx context.Context) error
}

Module is the base lifecycle contract for components managed by ModuleManager.

Core modules and plugins implement this interface. Init is called before Start, and Stop is called during shutdown in reverse registration order.

type ModuleManager

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

ModuleManager owns registered modules, shared configuration, the shared HTTP server, and the instance-scoped event bus.

func NewModuleManager

func NewModuleManager(logger *slog.Logger) *ModuleManager

NewModuleManager creates a ModuleManager with an initialized HTTP mux, event bus state, and default HTTP client.

func (*ModuleManager) GetConfig

func (m *ModuleManager) GetConfig() map[string]map[string]any

func (*ModuleManager) GetHTTPClient

func (m *ModuleManager) GetHTTPClient() *http.Client

func (*ModuleManager) GetMuxServer

func (m *ModuleManager) GetMuxServer() *http.ServeMux

func (*ModuleManager) GetPlugin

func (m *ModuleManager) GetPlugin(name string) (Plugin, error)

GetPlugin implements PluginRegistry

func (*ModuleManager) GetPluginsWithCapability

func (m *ModuleManager) GetPluginsWithCapability(cap Capability) []Plugin

GetPluginsWithCapability implements PluginRegistry

func (*ModuleManager) Init

func (m *ModuleManager) Init(ctx context.Context) error

Init initializes all registered modules in registration order.

func (*ModuleManager) ListPlugins

func (m *ModuleManager) ListPlugins() []Plugin

ListPlugins returns all registered plugins in registration order.

func (*ModuleManager) LoadPlugins

func (m *ModuleManager) LoadPlugins(dir string) error

LoadPlugins loads plugins from a directory and registers them with the module manager.

func (*ModuleManager) Publish

func (m *ModuleManager) Publish(ctx context.Context, event InternalEvent)

func (*ModuleManager) Register

func (m *ModuleManager) Register(mod Module)

func (*ModuleManager) RegisterEventType

func (m *ModuleManager) RegisterEventType(desc EventTypeDesc) error

func (*ModuleManager) SetConfig

func (m *ModuleManager) SetConfig(cfg map[string]map[string]any)

func (*ModuleManager) SetHTTPClient

func (m *ModuleManager) SetHTTPClient(client *http.Client)

func (*ModuleManager) Start

func (m *ModuleManager) Start(ctx context.Context)

Start starts the shared HTTP server and then starts all registered modules.

func (*ModuleManager) Stop

func (m *ModuleManager) Stop(ctx context.Context)

Stop stops all modules in reverse registration order and then shuts down the shared HTTP server.

func (*ModuleManager) Subscribe

func (m *ModuleManager) Subscribe(pattern string, handler Listener)

type NotificationPayload

type NotificationPayload struct {
	EventType     EventTypeName  `json:"event_type"`
	Timestamp     time.Time      `json:"timestamp"`
	Source        string         `json:"source,omitempty"`
	Repo          string         `json:"repo,omitempty"`
	Message       string         `json:"message,omitempty"`
	Title         string         `json:"title"`
	Body          string         `json:"body"`
	ExecutionID   string         `json:"execution_id,omitempty"`
	FullName      string         `json:"full_name,omitempty"`
	Stage         string         `json:"stage,omitempty"`
	Status        string         `json:"status,omitempty"`
	FailureClass  string         `json:"failure_class,omitempty"`
	AlertSeverity string         `json:"alert_severity,omitempty"`
	LastError     string         `json:"last_error,omitempty"`
	Details       map[string]any `json:"details,omitempty"`
}

func NewNotificationPayload

func NewNotificationPayload(event InternalEvent) NotificationPayload

func (NotificationPayload) MarshalJSON

func (p NotificationPayload) MarshalJSON() ([]byte, error)

type PayloadField

type PayloadField struct {
	Type        string // e.g., "string", "int", "map[string]interface{}"
	Description string
	Required    bool
}

PayloadField describes one field expected in an event Details payload.

type Plugin

type Plugin interface {
	Module
	// Description returns a human-readable summary of the plugin.
	Description() string
	// Capabilities returns the plugin capabilities it provides to the system.
	Capabilities() []Capability
	// Status reports the current plugin health for APIs and status pages.
	Status() ServiceStatus
	// Execute runs a plugin-specific action with free-form parameters.
	Execute(ctx context.Context, action string, params map[string]interface{}) (interface{}, error)
}

Plugin extends Module with metadata, health, and an action-based execution entry point.

Dynamically loaded plugins implement this interface and expose an exported symbol named Plugin that resolves to a Plugin value.

type PluginRegistry

type PluginRegistry interface {
	// GetPlugin returns a plugin by its registered name.
	GetPlugin(name string) (Plugin, error)
	// GetPluginsWithCapability returns all plugins advertising the given capability.
	GetPluginsWithCapability(cap Capability) []Plugin
	// ListPlugins returns all registered plugins in registration order.
	ListPlugins() []Plugin
	// RegisterEventType declares an event type for validation and discoverability.
	RegisterEventType(desc EventTypeDesc) error
	// Publish delivers an event to matching subscribers on this manager's bus.
	Publish(ctx context.Context, event InternalEvent)
	// GetMuxServer returns the shared HTTP mux used for core and plugin routes.
	GetMuxServer() *http.ServeMux
	// Subscribe registers a listener for an exact event type or wildcard pattern.
	Subscribe(pattern string, handler Listener)
	// GetHTTPClient returns the shared HTTP client for outbound requests.
	GetHTTPClient() *http.Client
	// GetConfig returns the sectioned configuration map visible to plugins.
	GetConfig() map[string]map[string]any
}

PluginRegistry provides shared runtime services to modules during Init and later execution.

ModuleManager implements this interface and passes itself to each module so plugins can discover other plugins, access configuration, publish and subscribe to events, and register HTTP handlers.

type RuntimeFile

type RuntimeFile struct {
	EnvKey   string `json:"env_key"`
	Filename string `json:"filename,omitempty"`
	Content  []byte `json:"-"`
	Mode     uint32 `json:"mode,omitempty"`
}

RuntimeFile describes a file that core materializes before docker compose execution and exposes through an environment variable pointing at the file path.

type Secret

type Secret struct {
	Value string
}

Secret wraps a sensitive string value that should be redacted in logs, API responses, and UI serialization.

func NewSecret

func NewSecret(value string) Secret

NewSecret wraps a raw string as a Secret.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON serializes the redacted form instead of the underlying value.

func (Secret) Redacted

func (s Secret) Redacted() string

Redacted returns the display form used when exposing the secret value.

func (Secret) String

func (s Secret) String() string

String returns the redacted display form for fmt.Stringer-compatible output.

type ServiceStatus

type ServiceStatus string
const (
	StatusHealthy   ServiceStatus = "HEALTHY"
	StatusUnhealthy ServiceStatus = "UNHEALTHY"
	StatusUnknown   ServiceStatus = "UNKNOWN"
	StatusDegraded  ServiceStatus = "DEGRADED"
)

Jump to

Keyboard shortcuts

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