Documentation
¶
Index ¶
- Constants
- func PluginTypeName(pluginType PluginType) string
- func PopulateCmdlineOptions(fs *pflag.FlagSet) error
- func Register(entry PluginEntry)
- func SplitAndTrim(val string) []string
- func ValidateHTTPURL(value string) error
- func ValidateHostPort(value string) error
- type Base
- func (b *Base) Context() context.Context
- func (b *Base) Done() <-chan struct{}
- func (b *Base) Emit(evt event.Event) bool
- func (b *Base) ErrorChan() <-chan error
- func (b *Base) Fail(err error)
- func (b *Base) Failed() <-chan struct{}
- func (b *Base) Failure() error
- func (b *Base) Go(fn func())
- func (b *Base) Input() <-chan event.Event
- func (b *Base) InputChan() chan<- event.Event
- func (b *Base) Logger() Logger
- func (b *Base) OutputChan() <-chan event.Event
- func (b *Base) Running() bool
- func (b *Base) SendError(err error) bool
- func (b *Base) SetLogger(l Logger)
- func (b *Base) Shutdown(hooks ShutdownHooks) error
- func (b *Base) StartRun(ctx context.Context, cfg BaseConfig, setup func(context.Context) error, ...) error
- func (b *Base) TrySendError(err error) bool
- func (b *Base) Wait()
- type BaseConfig
- type Configuration
- type FailureReporter
- type Lifecycle
- type Logger
- type ManagedPlugin
- type Options
- type PluginEntry
- type PluginOption
- type PluginOptionType
- type PluginType
- type ShutdownHooks
Constants ¶
const ( // DefaultEventBuffer is the event channel buffer a plugin gets when // BaseConfig leaves the size unset. DefaultEventBuffer = 10 // ErrorBuffer is the capacity of each Base-owned error channel. It is // deliberately not configurable: an unbuffered error channel makes a // worker block until the pipeline happens to read, which no plugin // wants. ErrorBuffer = 16 )
Variables ¶
This section is empty.
Functions ¶
func PluginTypeName ¶
func PluginTypeName(pluginType PluginType) string
func PopulateCmdlineOptions ¶
func Register ¶
func Register(entry PluginEntry)
Register publishes a definition. Invalid or duplicate definitions are programmer errors.
func SplitAndTrim ¶ added in v0.44.0
SplitAndTrim splits comma-separated values, discarding whitespace and empty entries.
func ValidateHTTPURL ¶ added in v0.46.0
ValidateHTTPURL checks configured HTTP endpoints without exposing credentials in errors.
func ValidateHostPort ¶ added in v0.46.0
ValidateHostPort checks TCP endpoints, including bracketed IPv6 addresses.
Types ¶
type Base ¶ added in v0.46.0
type Base struct {
// contains filtered or unexported fields
}
Base owns the channel plumbing, goroutine tracking and shutdown sequencing shared by the built-in plugins. Embed it by value:
type MyOutput struct {
plugin.Base
format string
}
Embedding satisfies the ErrorChan, InputChan and OutputChan methods of the ManagedPlugin interface. Base contains a mutex, so a plugin embedding it must never be copied.
func (*Base) Context ¶ added in v0.46.0
Context returns the current run's context, canceled by Shutdown or cancellation of the parent context. Capture it once for a worker or connection attempt. Before initialization it returns context.Background().
func (*Base) Done ¶ added in v0.46.0
func (b *Base) Done() <-chan struct{}
Done returns a channel closed when the plugin starts shutting down. Capture it once when a worker starts.
func (*Base) Emit ¶ added in v0.46.0
Emit waits for an output send or run cancellation and reports whether it sent. A ready send can win when cancellation is also ready.
It is safe from any goroutine, including ones Base does not track -- a callback a dependency invokes on its own goroutine, which wg.Wait knows nothing about. Two things together make that true, and neither is sufficient alone. The senders WaitGroup holds the close back until every in-flight send has returned; Shutdown's wait on it is what a select case cannot replace, because a send on an already-closed channel is a ready case that panics rather than one select declines to take. The done case then guarantees that wait terminates: without it a sender parked on a full channel whose consumer has stopped would never return, and the close would never come.
func (*Base) Fail ¶ added in v0.46.0
Fail records the first terminal error and cancels this run without joining workers. It is safe to call from a worker. Stop is still required for cleanup. Failure notification cannot block on an absent error-channel consumer. A best-effort copy also goes to ErrorChan for existing diagnostic consumers. Errors arriving after cancellation or normal shutdown are ignored.
func (*Base) Failed ¶ added in v0.46.0
func (b *Base) Failed() <-chan struct{}
Failed returns this run's terminal-failure signal, or nil before StartRun. Normal shutdown does not close it; obtain it again after restart.
func (*Base) Failure ¶ added in v0.46.0
Failure returns the first terminal error, retained until the next StartRun.
func (*Base) Go ¶ added in v0.46.0
func (b *Base) Go(fn func())
Go runs fn in a tracked goroutine. Shutdown waits for every goroutine started this way.
It panics if StartRun has never initialized the Base. That is a programming error with no quiet failure mode worth preserving: every accessor would return nil, every sender would report false, Start would return nil, and the pipeline would wire itself to a black hole. Go is the one method every working plugin reaches, so the check lives here and nowhere else.
It does nothing, beyond a warning, if the Base was initialized but is not currently running: starting a worker while Shutdown is waiting would be a WaitGroup misuse, and the worker would come up after its channels were closed. That is a legitimate shutdown race rather than a mistake, so it drops the worker instead of panicking. The warning needs a logger to be seen, since the symptom is otherwise just a plugin that quietly does nothing.
func (*Base) Input ¶ added in v0.46.0
Input returns the receive side of the input channel, for the plugin's own workers. Capture it once when a worker starts.
func (*Base) InputChan ¶ added in v0.46.0
InputChan returns the plugin's input event channel, or nil for a plugin that does not consume events.
func (*Base) Logger ¶ added in v0.46.0
Logger returns the logger set with SetLogger, or nil. Plugins that want a global fallback keep their own log() helper.
func (*Base) OutputChan ¶ added in v0.46.0
OutputChan returns the plugin's output event channel, or nil for a plugin that does not produce events.
func (*Base) Running ¶ added in v0.46.0
Running reports whether setup completed without a matching Shutdown. During setup, after terminal failure, or after failed setup it returns false. Parent-context cancellation alone does not change this result.
func (*Base) SendError ¶ added in v0.46.0
SendError waits for a diagnostic send or run cancellation and reports whether it sent. A ready send can win against cancellation. Sending does not guarantee consumption or persistence. Use Fail for terminal errors.
It is safe from any goroutine, including callbacks racing Shutdown.
func (*Base) SetLogger ¶ added in v0.46.0
SetLogger injects the logger without coupling Base to application configuration.
func (*Base) Shutdown ¶ added in v0.46.0
func (b *Base) Shutdown(hooks ShutdownHooks) error
Shutdown first cancels the run context, including in-progress setup, then acquires the lifecycle mutex and runs this sequence once per run:
- If DrainOnStop, close the input channel so workers drain it.
- Close the shutdown signal returned by Done.
- hooks.BeforeWait.
- Wait for every goroutine started with Go.
- hooks.AfterWait.
- Retire the senders Go does not track, waiting until they are gone.
- Close the remaining channels.
It returns the first non-nil hook error.
Concurrent callers are serialized by the lifecycle mutex: the sequence and its hooks run exactly once, and the callers that lose the race do not return until the winner has closed the channels. A nil return therefore always means "the workers have exited and the channels are closed", never "someone else is still working on it". Once the sequence has run, further calls return nil immediately, and StartRun re-arms it for the next run.
Never call it from a goroutine started with Go: step 4 would wait on the caller's own WaitGroup entry and block forever.
func (*Base) StartRun ¶ added in v0.46.0
func (b *Base) StartRun( ctx context.Context, cfg BaseConfig, setup func(context.Context) error, hooks ShutdownHooks, ) error
StartRun initializes a plugin once and runs setup while owning its lifecycle. The run context is derived from ctx. Repeated calls on a healthy running plugin are no-ops and do not replace its context. A failed run returns its terminal error until Shutdown completes. Setup must use the supplied run context for blocking operations and register workers with Go. On failure or cancellation, hooks unwind partial resources before StartRun returns. Hooks must tolerate partially initialized resources. Neither setup nor a tracked worker may call StartRun or Shutdown on this Base. Shutdown hooks must stop and join dependency-owned callback sources before returning; callbacks invoked after Shutdown completes do not belong to a run and could otherwise observe channels created by a later restart.
func (*Base) TrySendError ¶ added in v0.46.0
TrySendError attempts to send err without waiting for a receiver. It reports false when the channel is full or absent, in which case the caller should log the error instead.
It is safe from any goroutine, including callbacks racing Shutdown.
type BaseConfig ¶ added in v0.46.0
type BaseConfig struct {
// HasInput creates the input event channel. Input-only plugins leave
// it false so InputChan returns nil.
HasInput bool
// InputBuffer is the input channel buffer. Non-positive values mean
// DefaultEventBuffer.
InputBuffer int
// HasOutput creates the output event channel. Output-only plugins
// leave it false so OutputChan returns nil.
HasOutput bool
// OutputBuffer is the output channel buffer. Non-positive values mean
// DefaultEventBuffer.
OutputBuffer int
// DrainOnStop closes the input channel before the shutdown signal so
// a worker ranging over it processes buffered events on the way out.
// A worker in a DrainOnStop plugin must exit when its input channel
// closes and must not rely on Done alone.
DrainOnStop bool
}
BaseConfig describes the channels and shutdown behavior a plugin needs from Base. A plugin builds one in its StartContext method and hands it to StartRun.
type Configuration ¶ added in v0.46.0
type Configuration struct {
// contains filtered or unexported fields
}
Configuration is an immutable snapshot of resolved plugin options.
func ResolveConfig ¶ added in v0.46.0
func ResolveConfig( data map[string]map[string]map[string]any, fs *pflag.FlagSet, lookup func(string) (string, bool), ) (*Configuration, error)
ResolveConfig validates all supplied keys and scalar values, then snapshots defaults < YAML < environment < explicitly changed flags. A nil lookup uses os.LookupEnv; supply a lookup returning false for hermetic resolution. Custom environment aliases override generated names at the environment tier. Plugin-specific semantic validation happens when Configuration.New is called.
func (*Configuration) New ¶ added in v0.46.0
func (c *Configuration) New( kind PluginType, name string, ) (ManagedPlugin, error)
New constructs an instance using this snapshot, without rereading flags or environment.
func (*Configuration) Options ¶ added in v0.46.0
func (c *Configuration) Options(kind PluginType, name string) (Options, error)
Options returns resolved scalar values without rereading flags or environment. The returned value exposes no mutable option storage.
type FailureReporter ¶ added in v0.46.0
type FailureReporter interface {
Failed() <-chan struct{}
Failure() error
}
FailureReporter exposes the first terminal error of a run independently of the recoverable error channel. Failed must be non-nil after successful startup and closes only on failure, not normal Stop. Reacquire Failed after restart. Failure remains available until the next run. Accessors must be concurrency-safe and nonblocking. Call Stop after failure to join workers and release resources.
type Lifecycle ¶ added in v0.46.0
type Lifecycle interface {
StartContext(context.Context) error
Stop() error
FailureReporter
}
Lifecycle governs setup, cancellation, failure, and cleanup for one run. StartContext must return with workers and ports ready. Production runs in workers: synchronous sends during setup can block before pipeline wiring. The context governs both setup and the run. Failed startup must release partial resources before returning. Cancellation requests shutdown; Stop must still join all workers and release resources before returning. Stop is safe to call concurrently or repeatedly, including before startup. A stopped instance may restart; callers must reacquire its channels.
type Logger ¶
type Logger interface {
Info(string, ...any)
Warn(string, ...any)
Debug(string, ...any)
Error(string, ...any)
}
Logger provides a logging interface for plugins.
type ManagedPlugin ¶ added in v0.46.0
type ManagedPlugin interface {
Lifecycle
Role() PluginType
ErrorChan() <-chan error
InputChan() chan<- event.Event
OutputChan() <-chan event.Event
}
ManagedPlugin is required by pipelines and registered factories. Plugins own their channels; a pipeline borrows them for one run and exclusively owns the connected instances' lifecycle. Role must be stable, acquire no resources, and match the ports: inputs produce, outputs consume, filters do both. Unused ports return nil. ErrorChan reports recoverable diagnostics and may be nil; terminal errors use FailureReporter. Base is an optional implementation. A convenience Start method is not part of this contract.
func GetPlugin ¶
func GetPlugin( kind PluginType, name string, values map[string]any, ) (ManagedPlugin, error)
GetPlugin constructs a registered plugin with instance-owned configuration.
type Options ¶ added in v0.46.0
type Options struct {
// contains filtered or unexported fields
}
Options contains validated, immutable scalar values for one factory invocation. Accessors require a name and type declared by the factory's PluginEntry. A mismatched accessor is a programming error and panics.
type PluginEntry ¶
type PluginEntry struct {
NewFromOptionsFunc func(Options) (ManagedPlugin, error)
Name string
Description string
Options []PluginOption
Type PluginType
}
PluginEntry declares a factory and its configuration schema. Factories must validate semantic constraints and return errors without starting workers.
func GetPlugins ¶
func GetPlugins(kind PluginType) []PluginEntry
func (PluginEntry) New ¶ added in v0.46.0
func (e PluginEntry) New(values map[string]any) (ManagedPlugin, error)
New constructs an independent instance from defaults and explicit values. It does not read process environment or command-line flags.
type PluginOption ¶
type PluginOption struct {
DefaultValue any
Name string
CustomEnvVar string
CustomFlag string
Description string
Type PluginOptionType
}
PluginOption describes a scalar option. Definitions contain no instance state.
func (PluginOption) AddToFlagSet ¶
func (p PluginOption) AddToFlagSet(fs *pflag.FlagSet, kind, name string) error
AddToFlagSet registers independent flag storage for this definition.
type PluginOptionType ¶
type PluginOptionType int
const ( PluginOptionTypeString PluginOptionType = 1 PluginOptionTypeBool PluginOptionType = 2 PluginOptionTypeInt PluginOptionType = 3 PluginOptionTypeUint PluginOptionType = 4 )
type PluginType ¶
type PluginType int
const ( PluginTypeInput PluginType = 1 PluginTypeOutput PluginType = 2 PluginTypeFilter PluginType = 3 )
type ShutdownHooks ¶ added in v0.46.0
type ShutdownHooks struct {
// BeforeWait runs after workers are signalled to stop but before
// they are waited on, so it can unblock them: closing a network
// connection, cancelling a context.
BeforeWait func() error
// AfterWait runs once every tracked worker has exited and before the
// remaining channels close, for resources workers used, such as an open
// file.
AfterWait func() error
}
ShutdownHooks are the optional plugin-specific callbacks Shutdown runs.