core

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core defines the central interface seams (Driver, Transport, Rule) and shared types for the CoreC IIoT data collection and control engine. Drivers and transports implement these interfaces and register via init().

Index

Constants

View Source
const (
	// DefaultTagInterval is the fallback collection interval for tags
	// that do not specify their own interval.
	DefaultTagInterval = time.Second

	// DefaultDataBusSize is the default buffer capacity for the internal
	// data channel connecting drivers to the processing pipeline.
	DefaultDataBusSize = 8192

	// DefaultShutdownTimeout is the default maximum time to wait for
	// drivers and transports to stop during graceful shutdown.
	DefaultShutdownTimeout = 30 * time.Second

	// DefaultErrorThrottleWindow is the default time window for
	// suppressing repeated error/overrun log messages in the scheduler.
	DefaultErrorThrottleWindow = 10 * time.Second

	// DefaultReconnectBackoff is the initial delay before the first
	// reconnect attempt after a connection loss.
	DefaultReconnectBackoff = 2 * time.Second

	// DefaultMaxReconnectBackoff is the upper bound for the exponential
	// reconnect backoff delay.
	DefaultMaxReconnectBackoff = 30 * time.Second

	// DefaultCommandBufferSize is the default buffer size for transport
	// command channels when TransportConfig.BufferSize is not set.
	DefaultCommandBufferSize = 100

	// DefaultCommandConcurrency is the default maximum number of write
	// commands executed in parallel by the engine. Commands exceeding this
	// limit apply backpressure to the transport's command channel (and
	// ultimately to the dead-letter store per #4). This prevents a single
	// slow write from serializing all subsequent control commands
	// (IMPROVEMENTS #2).
	DefaultCommandConcurrency = 16

	// DefaultHighPriorityWorkers is the default number of dedicated
	// processing workers for high-priority (fast-interval) data. These
	// workers read only from the DataBus high-priority channel, so a burst
	// of low-frequency bulk reads cannot starve high-frequency collection
	// (IMPROVEMENTS #5).
	DefaultHighPriorityWorkers = 2

	// DefaultHighPriorityInterval is the collection interval threshold at
	// or below which a task is classified as high-priority. Tasks with
	// interval ≤ this value are routed to the dedicated high-priority
	// worker pool (IMPROVEMENTS #5).
	DefaultHighPriorityInterval = time.Second

	// DefaultBatchSize is the default batch size for transport batchers
	// when TransportConfig.BatchSize is not set.
	DefaultBatchSize = 100

	// DefaultMaxReconnectFailures is the circuit-breaker threshold: the
	// number of consecutive reconnect failures before the driver enters
	// a long cool-down period.
	DefaultMaxReconnectFailures = 20

	// DefaultDriverTimeout is the default I/O timeout for driver
	// connections (read/write operations).
	DefaultDriverTimeout = 5 * time.Second

	// DefaultIdleTimeout is the default connection idle timeout for
	// drivers that support keep-alive or idle detection.
	DefaultIdleTimeout = 60 * time.Second

	// DefaultTransportTimeout is the default I/O timeout for transport
	// publish/subscribe operations.
	DefaultTransportTimeout = 5 * time.Second

	// DefaultKeepAlive is the default keep-alive interval for transport
	// connections (e.g. MQTT ping interval).
	DefaultKeepAlive = 60 * time.Second

	// DefaultCircuitBreakerBackoff is the cool-down period after the
	// maximum number of reconnect failures is exceeded, before retrying.
	DefaultCircuitBreakerBackoff = 5 * time.Minute

	// DefaultOfflineBufferMaxEntries is the maximum number of data points
	// retained in the offline buffer when transport backends are unavailable.
	DefaultOfflineBufferMaxEntries = 10000

	// DefaultDeadLetterMaxLen is the maximum number of entries in the
	// engine's dead-letter queue for data points that could not be processed.
	DefaultDeadLetterMaxLen = 1000
)

Variables

View Source
var ErrSubscribeNotSupported = errors.New("subscribe not supported by this driver")

ErrSubscribeNotSupported is returned by drivers that don't support subscription mode.

Functions

func RegisterDriver

func RegisterDriver(typeName string, factory DriverFactory)

RegisterDriver registers a driver factory by type name. Typically called in a driver package's init() function.

func RegisterTransport

func RegisterTransport(typeName string, factory TransportFactory)

RegisterTransport registers a transport factory by type name.

func RegisteredDrivers

func RegisteredDrivers() []string

RegisteredDrivers returns all registered driver type names.

func RegisteredTransports

func RegisteredTransports() []string

RegisteredTransports returns all registered transport type names.

Types

type APIConfig

type APIConfig struct {
	Listen          string   `yaml:"listen"`
	Secret          string   `yaml:"secret"`
	TLSCert         string   `yaml:"tls-cert,omitempty"`
	TLSKey          string   `yaml:"tls-key,omitempty"`
	AllowedOrigins  []string `yaml:"allowed-origins,omitempty"`
	RateLimitPerSec int      `yaml:"rate-limit-per-sec,omitempty"`

	// ReadHeaderTimeout is the maximum duration for reading the request
	// headers. Default: 10s. Parse as a duration string.
	ReadHeaderTimeout string `yaml:"read-header-timeout,omitempty"`

	// ReadTimeout is the maximum duration for reading the entire request.
	// Default: 0 (disabled; no overall read deadline). Parse as a duration string.
	ReadTimeout string `yaml:"read-timeout,omitempty"`

	// WriteTimeout is the maximum duration before timing out writes of the
	// response. Default: 0 (disabled; no overall write deadline). Parse as a duration string.
	WriteTimeout string `yaml:"write-timeout,omitempty"`

	// IdleTimeout is the maximum amount of time to wait for the next
	// request when keep-alives are enabled. Default: 120s.
	IdleTimeout string `yaml:"idle-timeout,omitempty"`

	// PprofDisabled controls whether pprof profiling endpoints are
	// disabled. Defaults to false (pprof enabled) for backward
	// compatibility. Set to true to completely disable pprof.
	PprofDisabled bool `yaml:"pprof-disabled,omitempty"`

	// PprofAddr, when non-empty, starts a separate HTTP server for pprof
	// on this address (e.g. "127.0.0.1:6060"). The separate server does
	// NOT require authentication, so it should be bound to a loopback or
	// private interface only. When empty, pprof runs on the main API
	// port (unless PprofDisabled is true).
	PprofAddr string `yaml:"pprof-addr,omitempty"`
}

APIConfig holds API server settings.

type Action

type Action int

Action defines the action to take when a rule matches.

const (
	ActionForward   Action = iota // Forward to target transport
	ActionDrop                    // Discard the data point
	ActionAlert                   // Forward + trigger alert callback
	ActionTransform               // Transform value then forward
	ActionMirror                  // Forward to multiple targets
)

type BufferConfig

type BufferConfig struct {
	Enabled bool   `yaml:"enabled"`
	MaxSize int    `yaml:"max-size"` // max number of buffered batches; <=0 defaults to 10000
	Path    string `yaml:"path"`     // directory path for buffer files
}

BufferConfig holds offline buffer settings for persisting failed publish batches to disk so they can be replayed after transport recovery. This prevents data loss when the northbound transport (MQTT broker / HTTP endpoint) is temporarily unavailable.

type CommandForwarder added in v0.0.3

type CommandForwarder interface {
	ForwardCommand(ctx context.Context, cmd WriteCommand) error
}

CommandForwarder is an optional capability for transports that can republish write commands to downstream nodes. This enables chained-core command passthrough: when a relay node receives a command via command-topic but has no local driver for the target, it forwards the command to downstream nodes via the transport's forward topic.

Transports implement this interface to opt in to command forwarding. The engine type-asserts for this interface; transports that don't implement it are simply skipped during forwarding.

type Config

type Config struct {
	Node          NodeConfig              `yaml:"node,omitempty"`
	Global        GlobalConfig            `yaml:"global"`
	Drivers       []DriverConfig          `yaml:"drivers"`
	Transports    []TransportConfig       `yaml:"transports"`
	Rules         []RuleConfig            `yaml:"rules"`
	RuleProviders []RuleProviderConfig    `yaml:"rule-providers,omitempty"`
	RuleGroups    map[string][]RuleConfig `yaml:"rule-groups,omitempty"`
}

Config is the top-level configuration structure.

type ConnState

type ConnState int

ConnState represents the connection state of a driver or transport.

const (
	StateDisconnected ConnState = iota
	StateConnecting
	StateConnected
	StateError
)

func (ConnState) String

func (s ConnState) String() string

type DataAccessor added in v0.0.3

type DataAccessor interface {
	ReadTag(ctx context.Context, driver, tag string) (*TagValue, error)
	WriteTag(ctx context.Context, cmd WriteCommand) (*WriteResult, error)
	LatestValues(driver string) map[string]DataPoint
}

DataAccessor covers synchronous read/write operations and cached latest values, used by the API layer.

type DataAgeProvider added in v0.0.3

type DataAgeProvider interface {
	DataAgeHistogram() LatencySnapshot
}

DataAgeProvider exposes the data-age (freshness) histogram for Prometheus exposure: the elapsed time between a data point's collection timestamp (DataPoint.Timestamp) and the moment the engine attempts to publish it. It is a separate role interface (mirroring OfflineBufferStatsProvider) so the route layer type-asserts optionally without coupling to the concrete engine type. *CoreCEngine satisfies this interface; test mocks are free to omit it.

type DataPoint

type DataPoint struct {
	Driver    string            `json:"driver"`
	Device    string            `json:"device"`
	Group     string            `json:"group"`
	Tag       string            `json:"tag"`
	Value     any               `json:"value"`
	Type      DataType          `json:"type"`
	Quality   Quality           `json:"quality"`
	Timestamp time.Time         `json:"timestamp"`
	Metadata  map[string]string `json:"metadata,omitempty"`

	// IsStale is set by the API layer when serving cached values that
	// haven't been updated within the configured stale-threshold. It is
	// not set during normal pipeline processing, so it does not appear
	// in published payloads (omitempty).
	IsStale bool `json:"is_stale,omitempty"`
}

DataPoint is the standard data unit flowing through the engine.

type DataType

type DataType int

DataType represents the data type of a tag value.

const (
	TypeBool DataType = iota
	TypeInt8
	TypeInt16
	TypeInt32
	TypeInt64
	TypeUint8
	TypeUint16
	TypeUint32
	TypeUint64
	TypeFloat32
	TypeFloat64
	TypeString
	TypeBytes
)

func ParseDataType

func ParseDataType(s string) (DataType, bool)

ParseDataType parses a string into a DataType.

func (DataType) MarshalJSON added in v0.0.3

func (d DataType) MarshalJSON() ([]byte, error)

MarshalJSON serializes DataType as a human-readable string (e.g. "float32") rather than a raw integer. This makes JSON payloads in published data points and the /tags API self-describing, and matches the string form used in YAML tag configurations (type: float32).

func (DataType) String

func (d DataType) String() string

func (*DataType) UnmarshalJSON added in v0.0.3

func (d *DataType) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both the string form ("float32") and the legacy integer form (9). The string form is preferred for new integrations because it is self-documenting; the integer form is accepted for backward compatibility with existing clients and persisted payloads.

This dual acceptance resolves a common usability trap: tag configurations in YAML use string types (type: float32), but prior to this change, the JSON API and MQTT command payloads required the raw iota integer (type: 9). Now both forms work in every JSON context.

type DeadLetterEntry added in v0.0.2

type DeadLetterEntry struct {
	Command  WriteCommand `json:"command"`
	Error    string       `json:"error"`
	FailedAt time.Time    `json:"failed_at"`
	Attempts int          `json:"attempts"`
}

DeadLetterEntry represents a failed write command stored in the dead letter queue for later inspection or manual retry.

type Driver

type Driver interface {
	// Lifecycle
	Init(ctx context.Context, config DriverConfig) error
	Start(ctx context.Context) error
	Stop() error
	Restart(ctx context.Context, config DriverConfig) error

	// Data operations
	Read(ctx context.Context, tags []string) ([]TagValue, error)
	Write(ctx context.Context, commands []WriteCommand) ([]WriteResult, error)
	Subscribe(ctx context.Context, tags []string) (<-chan DataPoint, error)

	// Metadata
	Name() string
	Type() string
	Status() DriverStatus
	Capabilities() DriverCapabilities
}

Driver defines the southbound driver interface for industrial protocol communication.

func CreateDriver

func CreateDriver(config DriverConfig) (Driver, error)

CreateDriver creates a driver instance using the registered factory.

type DriverCapabilities

type DriverCapabilities struct {
	CanRead      bool `json:"can_read"`
	CanWrite     bool `json:"can_write"`
	CanSubscribe bool `json:"can_subscribe"`
	BatchRead    bool `json:"batch_read"`
	MaxBatchSize int  `json:"max_batch_size"`
}

DriverCapabilities declares what a driver supports.

type DriverConfig

type DriverConfig struct {
	Name     string         `yaml:"name"`
	Type     string         `yaml:"type"`
	Settings map[string]any `yaml:"settings"`
	Tags     []TagConfig    `yaml:"tags"`

	// TagsFile loads tags from an external YAML file instead of (or in
	// addition to) the inline tags list. The file contains a YAML list of
	// TagConfig entries. This is useful when a driver has hundreds of
	// collection points and the main config file becomes unwieldy.
	//
	// If both Tags and TagsFile are set, the inline tags are appended
	// after the file-loaded tags. Tag names must be unique across both
	// sources.
	TagsFile string `yaml:"tags-file,omitempty"`

	// TagsInterval is the hot-reload interval for the tags file.
	// When set (e.g. "30s"), the engine periodically re-reads the file
	// and hot-swaps the driver's tags if the content changed.
	// Empty or "0" means no auto-reload (tags loaded once at startup).
	TagsInterval string `yaml:"tags-interval,omitempty"`
}

DriverConfig holds configuration for a driver instance.

type DriverFactory

type DriverFactory func(config DriverConfig) (Driver, error)

DriverFactory creates a Driver instance from configuration.

type DriverManager added in v0.0.3

type DriverManager interface {
	AddDriver(config DriverConfig) error
	RemoveDriver(name string) error
	GetDriver(name string) (Driver, bool)
	ListDrivers() []DriverStatus
}

DriverManager covers adding, removing, and inspecting drivers.

type DriverStatus

type DriverStatus struct {
	Name           string    `json:"name"`
	Type           string    `json:"type"`
	State          ConnState `json:"state"`
	LastRead       time.Time `json:"last_read"`
	LastError      string    `json:"last_error"`
	TagCount       int       `json:"tag_count"`
	ReadCount      uint64    `json:"read_count"`
	ErrorCount     uint64    `json:"error_count"`
	ReconnectCount uint64    `json:"reconnect_count"`
}

DriverStatus reports the current status of a driver.

type Engine

Engine is the core orchestrator of the CoreC core.

It is a composite interface assembled from single-role interfaces so that consumers can depend on exactly the capabilities they need (Interface Segregation Principle) instead of the full 25-method surface. Any type that implements every method below implements Engine, so this decomposition is fully backward compatible: existing implementations and mocks that embed Engine continue to satisfy the interface unchanged.

The role interfaces are:

  • Lifecycler — Start, Stop, Reload, Suspend, Resume, Status
  • DriverManager — AddDriver, RemoveDriver, GetDriver, ListDrivers
  • TransportManager — AddTransport, RemoveTransport, GetTransport, ListTransports
  • RuleManager — SetRules, GetRuleStats, SetRuleDisabled
  • DataAccessor — ReadTag, WriteTag, LatestValues
  • EventSubscriber — Subscribe, OnAlert
  • StatsProvider — Stats, StaleThreshold, DeadLetterEntries

type EngineConfig

type EngineConfig struct {
	// DataBusSize is the buffer capacity of the internal data channel
	// connecting drivers to the processing pipeline. Larger values
	// reduce drops under burst load at the cost of memory.
	// Default: 8192.
	DataBusSize int `yaml:"data-bus-size,omitempty"`

	// Workers is the number of processing goroutines for the rule
	// pipeline. 0 means runtime.NumCPU().
	Workers int `yaml:"workers,omitempty"`

	// ShutdownTimeout is the maximum time to wait for drivers and
	// transports to stop during graceful shutdown.
	// Default: 30s. Parse as a duration string, e.g. "30s".
	ShutdownTimeout string `yaml:"shutdown-timeout,omitempty"`

	// ErrorThrottleWindow is the time window within which repeated
	// error/overrun log messages from the scheduler are suppressed.
	// Default: 10s. Parse as a duration string, e.g. "10s".
	ErrorThrottleWindow string `yaml:"error-throttle-window,omitempty"`

	// DefaultTagInterval is the fallback collection interval for tags
	// that do not specify their own interval.
	// Default: 1s. Parse as a duration string, e.g. "1s".
	DefaultTagInterval string `yaml:"default-tag-interval,omitempty"`

	// OnBadQuality controls how DataPoints with QualityBad are handled
	// in the processing pipeline. Valid values:
	//   "publish"         — forward normally (default, backward-compatible).
	//   "drop"            — discard bad-quality points before rule matching.
	//   "mark-and-publish" — publish but set Value to nil, keeping quality=bad.
	//   "alert"           — forward and trigger alert callback.
	// An empty/unrecognized value defaults to "publish".
	OnBadQuality string `yaml:"on-bad-quality,omitempty"`

	// StaleThreshold is the duration after which a cached data point is
	// considered stale (not updated within this window). The API layer
	// uses this to annotate /tags and /drivers/{name}/tags responses
	// with an is_stale flag so consumers can distinguish live data
	// from values held over from a disconnected driver.
	// Default: 0 (disabled; no staleness annotation). e.g. "30s".
	StaleThreshold string `yaml:"stale-threshold,omitempty"`

	// WriteRetryCount is the number of times to retry a failed write
	// command before placing it in the dead letter queue.
	// Unset or 0 uses the default (3 retries). Set to a positive value
	// to override. The total attempt count is WriteRetryCount + 1.
	WriteRetryCount int `yaml:"write-retry-count,omitempty"`

	// CommandConcurrency is the maximum number of write commands the
	// engine executes in parallel. Commands in excess of this limit
	// apply backpressure (the transport's command channel fills, and
	// overflow is diverted to the dead-letter store). This prevents a
	// single slow write from serializing all subsequent control commands.
	// Unset or 0 uses the default (16). Set to 1 to restore the original
	// fully-serial behavior.
	CommandConcurrency int `yaml:"command-concurrency,omitempty"`

	// HighPriorityWorkers is the number of dedicated processing workers
	// for high-priority (fast-interval) data. These workers read only
	// from the DataBus high-priority channel, so a burst of low-frequency
	// bulk reads cannot starve high-frequency collection. Unset or 0 uses
	// the default (2).
	HighPriorityWorkers int `yaml:"high-priority-workers,omitempty"`
}

EngineConfig holds engine-wide runtime tuning parameters. All fields are optional; zero values fall back to sensible defaults.

type EngineStats

type EngineStats struct {
	Status         EngineStatus               `json:"status"`
	Uptime         time.Duration              `json:"uptime"`
	Drivers        int                        `json:"drivers"`
	Transports     int                        `json:"transports"`
	Rules          int                        `json:"rules"`
	TotalRead      uint64                     `json:"total_read"`
	TotalPublish   uint64                     `json:"total_publish"`
	TotalErrors    uint64                     `json:"total_errors"`
	TotalDropped   uint64                     `json:"total_dropped"`
	PointsPerSec   float64                    `json:"points_per_sec"`
	DriverStats    map[string]DriverStatus    `json:"driver_stats"`
	TransportStats map[string]TransportStatus `json:"transport_stats"`
}

EngineStats contains runtime statistics.

type EngineStatus

type EngineStatus string

EngineStatus represents the operational state of the engine.

const (
	EngineStatusRunning   EngineStatus = "running"
	EngineStatusSuspended EngineStatus = "suspended"
	EngineStatusStopped   EngineStatus = "stopped"
)

type EventSubscriber added in v0.0.3

type EventSubscriber interface {
	Subscribe(filter string) (<-chan DataPoint, func())
	OnAlert(handler func(point DataPoint, rule Rule))
}

EventSubscriber covers real-time data subscriptions and alert handlers.

type FlushBatchesDroppedProvider added in v0.0.3

type FlushBatchesDroppedProvider interface {
	FlushBatchesDropped() uint64
}

FlushBatchesDroppedProvider exposes the total number of full batches evicted or dropped from batcher flush queues due to sustained backpressure (IMPROVEMENTS #1: async batcher). It is a separate role interface so the route layer type-asserts optionally. *CoreCEngine satisfies this interface.

type GlobalConfig

type GlobalConfig struct {
	LogLevel  string       `yaml:"log-level"`
	LogFormat string       `yaml:"log-format"`
	API       APIConfig    `yaml:"api"`
	Engine    EngineConfig `yaml:"engine"`
	Buffer    BufferConfig `yaml:"buffer"`
}

GlobalConfig holds global settings.

type LatencyProvider added in v0.0.3

type LatencyProvider interface {
	ReadLatencyHistogram() LatencySnapshot
	PublishLatencyHistogram() LatencySnapshot
}

LatencyProvider exposes latency histograms for Prometheus histogram exposure. It is a separate role interface (not embedded in Engine) so that the route layer can type-assert optionally without coupling to the concrete engine type. *CoreCEngine satisfies this interface; test mocks are free to omit it.

type LatencySnapshot added in v0.0.3

type LatencySnapshot struct {
	Buckets []float64
	Counts  []uint64
	Sum     float64
	Count   uint64
}

LatencySnapshot is a point-in-time copy of a latency histogram's state. Buckets and Counts are aligned: Buckets[i] is the upper bound (in seconds) and Counts[i] is the cumulative number of observations with duration <= Buckets[i]. The final +Inf bucket is implied by Count (total observations).

type Lifecycler added in v0.0.3

type Lifecycler interface {
	Start(ctx context.Context, config *Config) error
	Stop() error
	Reload(config *Config) error
	Suspend() error
	Resume() error
	Status() EngineStatus
}

Lifecycler covers engine start/stop and runtime state transitions.

type Logger added in v0.0.3

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the port for structured logging from drivers and other components. Defining it as an interface in the core port package keeps concrete logging backends (slog, the project's log package, a test capture, …) out of the domain and lets each component depend on exactly this capability.

NOTE: This port is defined but NOT yet injected into drivers. Wiring it through Driver.Init / a driver constructor is a larger, separate refactor; the goal here is to establish the port so future work can adopt it without changing the core contract.

type Metrics added in v0.0.3

type Metrics interface {
	// IncCounter increments a named counter by 1, tagged with labels.
	IncCounter(name string, labels map[string]string)
	// SetGauge sets a named gauge to value, tagged with labels.
	SetGauge(name string, value float64, labels map[string]string)
}

Metrics is the port for emitting observability metrics (counters and gauges) from drivers and other components. Defining it as an interface in the core port package keeps concrete metric backends (Prometheus, statsd, no-op, …) out of the domain and lets each component depend on exactly this capability.

NOTE: This port is defined but NOT yet injected into drivers. Wiring it through Driver.Init / a driver constructor is a larger, separate refactor; the goal here is to establish the port so future work can adopt it without changing the core contract.

type NodeConfig added in v0.0.2

type NodeConfig struct {
	// ID is the unique identifier for this node in the topology.
	// Must be set to enable auto-discovery.
	ID string `yaml:"id"`

	// Role declares this node's function in the topology.
	//   collector  — has drivers, publishes data, no upstream
	//   relay      — receives from upstream, processes, republishes
	//   aggregator — receives from multiple upstreams, merges
	//   sink       — receives from upstream, does not republish
	Role string `yaml:"role"`

	// Subscribe lists upstream node IDs to receive data from.
	// The discovery module auto-subscribes to each upstream's publish
	// topic when the upstream comes online.
	Subscribe []string `yaml:"subscribe,omitempty"`

	// TopicPrefix overrides the default "topo" prefix for auto-generated
	// topics. Auto-generated format: {prefix}/{node-id}/data/{driver}/{tag}
	TopicPrefix string `yaml:"topic-prefix,omitempty"`
}

NodeConfig holds node-level configuration for topology auto-discovery. When ID is non-empty, the engine enables auto-discovery: topic-template, command-topic, and parser are auto-generated where not explicitly set, and the node broadcasts heartbeats so other instances can find it. When ID is empty (the default), all auto-discovery features are disabled and the engine behaves exactly as before — full backward compatibility.

type NoopLogger added in v0.0.3

type NoopLogger struct{}

NoopLogger is a Logger implementation that discards every call. It is the zero-dependency default for drivers and components that do not log, so they can hold a Logger value without a real backend.

func (NoopLogger) Debug added in v0.0.3

func (NoopLogger) Debug(msg string, args ...any)

Debug satisfies Logger; it does nothing.

func (NoopLogger) Error added in v0.0.3

func (NoopLogger) Error(msg string, args ...any)

Error satisfies Logger; it does nothing.

func (NoopLogger) Info added in v0.0.3

func (NoopLogger) Info(msg string, args ...any)

Info satisfies Logger; it does nothing.

func (NoopLogger) Warn added in v0.0.3

func (NoopLogger) Warn(msg string, args ...any)

Warn satisfies Logger; it does nothing.

type NoopMetrics added in v0.0.3

type NoopMetrics struct{}

NoopMetrics is a Metrics implementation that discards every call. It is the zero-dependency default for drivers and components that do not emit metrics, so they can hold a Metrics value without a real backend.

func (NoopMetrics) IncCounter added in v0.0.3

func (NoopMetrics) IncCounter(name string, labels map[string]string)

IncCounter satisfies Metrics; it does nothing.

func (NoopMetrics) SetGauge added in v0.0.3

func (NoopMetrics) SetGauge(name string, value float64, labels map[string]string)

SetGauge satisfies Metrics; it does nothing.

type OfflineBufferStatsProvider added in v0.0.3

type OfflineBufferStatsProvider interface {
	OfflineBufferStats() (pending int, drained uint64, pushed uint64)
}

OfflineBufferStatsProvider exposes offline-buffer observability counters for Prometheus exposure. It is a separate role interface so the route layer can type-assert optionally. *CoreCEngine satisfies this interface.

type Quality

type Quality int

Quality represents the quality of a data value (inspired by OPC UA).

const (
	QualityGood      Quality = 0
	QualityBad       Quality = 1
	QualityUncertain Quality = 2
)

func (Quality) String

func (q Quality) String() string

type Registry

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

Registry holds driver and transport factories.

type Rule

type Rule interface {
	Match(point DataPoint) bool
	Action() Action
	Target() string
	Targets() []string // For mirror action
	Priority() int
	Name() string
	Payload() string             // match expression or reference
	RuleType() string            // "simple", "rule-set", "sub-rule"
	Transform() *TransformConfig // transform config (nil unless action == transform)
	String() string
}

Rule defines a data routing rule.

type RuleConfig

type RuleConfig struct {
	Name      string           `yaml:"name"`
	Match     string           `yaml:"match"`
	Action    string           `yaml:"action"`
	Target    string           `yaml:"target,omitempty"`
	Targets   []string         `yaml:"targets,omitempty"`
	Priority  int              `yaml:"priority,omitempty"`
	Transform *TransformConfig `yaml:"transform,omitempty"`
}

RuleConfig defines a rule from YAML configuration.

type RuleEngine added in v0.0.3

type RuleEngine interface {
	// SetRules parses rule configs and sets the active rule set.
	SetRules(configs []RuleConfig) error

	// SetSubRules parses named sub-rule groups for SUB-RULE references.
	SetSubRules(groups map[string][]RuleConfig) error

	// Match finds the first matching rule for a DataPoint in priority
	// order. Returns nil if no rule matches.
	Match(point DataPoint) *RuleMatchResult

	// RuleStats returns runtime statistics for all rules.
	RuleStats() []RuleStat

	// SetRuleDisabled enables or disables a rule by index.
	SetRuleDisabled(index int, disabled bool) error

	// AddProvider registers a rule provider for RULE-SET references.
	AddProvider(p RuleProvider)

	// CloseProviders closes and removes all registered rule providers,
	// stopping any background goroutines they started.
	CloseProviders()

	// ProviderCount returns the number of registered rule providers.
	ProviderCount() int

	// Rules returns the active rules. Used by the engine to report the
	// configured rule count in Stats().
	Rules() []Rule
}

RuleEngine is the port (hexagonal architecture) for the rule matching and routing engine. The engine package depends on this interface rather than the concrete *rule.Engine adapter, so the rule implementation can be swapped or mocked without touching the engine.

The method set is exactly the set of operations the engine calls on its rule engine (plus Rules, used by Stats, and ProviderCount, used by reload tests). The concrete rule.Engine satisfies this interface; see the compile-time assertion in rule/engine.go.

type RuleManager added in v0.0.3

type RuleManager interface {
	SetRules(rules []RuleConfig) error
	GetRuleStats() []RuleStat
	SetRuleDisabled(index int, disabled bool) error
}

RuleManager covers configuring rules and reading rule statistics.

type RuleMatchResult added in v0.0.3

type RuleMatchResult struct {
	Rule      Rule
	Targets   []string
	Transform *TransformConfig
}

RuleMatchResult contains the matched rule and resolved targets for a DataPoint evaluated by a RuleEngine. It is the port-level equivalent of rule.MatchResult; the rule package aliases its MatchResult to this type so the concrete adapter satisfies the RuleEngine port without conversion.

type RuleProvider

type RuleProvider interface {
	Name() string
	Initial() error
	Update() error
	Match(point DataPoint) bool
	Count() int
}

RuleProvider supplies an external set of match-only rules.

type RuleProviderConfig

type RuleProviderConfig struct {
	Name     string `yaml:"name"`
	Type     string `yaml:"type"`               // "file"
	Path     string `yaml:"path"`               // file path
	Interval string `yaml:"interval,omitempty"` // hot-reload interval, e.g. "30s"
}

RuleProviderConfig defines an external rule-set provider.

type RuleStat

type RuleStat struct {
	Index     int       `json:"index"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	Match     string    `json:"match"`
	Action    string    `json:"action"`
	Target    string    `json:"target"`
	Targets   []string  `json:"targets"`
	Priority  int       `json:"priority"`
	Disabled  bool      `json:"disabled"`
	HitCount  uint64    `json:"hit_count"`
	HitAt     time.Time `json:"hit_at"`
	MissCount uint64    `json:"miss_count"`
	MissAt    time.Time `json:"miss_at"`
}

RuleStat contains runtime statistics for a rule.

type RuleWrapper

type RuleWrapper interface {
	Rule
	SetDisabled(v bool)
	IsDisabled() bool
	HitCount() uint64
	HitAt() time.Time
	MissCount() uint64
	MissAt() time.Time
	Unwrap() Rule
}

RuleWrapper wraps a Rule with runtime statistics and enable/disable control.

type ScheduleTask

type ScheduleTask struct {
	ID        string             `json:"id"`
	Driver    string             `json:"driver"`
	Tags      []string           `json:"tags"`
	Interval  time.Duration      `json:"interval"`
	Priority  int                `json:"priority"`
	DeadBands map[string]float64 `json:"deadbands,omitempty"` // tag → deadband threshold

	// ReadTimeout is the maximum duration for a single read operation.
	// <=0 means fall back to Interval. This decouples the read deadline
	// from the collection cadence so that high-frequency tasks (e.g.
	// 200 ms interval) can still allow a generous read timeout (e.g. 1 s)
	// without being cut short by network jitter.
	ReadTimeout time.Duration `json:"read_timeout,omitempty"`
}

ScheduleTask defines a periodic collection task.

type Scheduler

type Scheduler interface {
	Start(ctx context.Context) error
	Stop() error
	AddTask(task ScheduleTask) error
	Pause() error
	Resume() error
	PauseDriver(name string) error
}

Scheduler manages timed data collection tasks. This is unique to CoreC; the scheduler proactively polls on intervals.

type StatsProvider added in v0.0.3

type StatsProvider interface {
	Stats() EngineStats
	StaleThreshold() time.Duration
	DeadLetterEntries() []DeadLetterEntry
}

StatsProvider covers aggregate engine statistics and staleness/dead-letter inspection. StaleThreshold returns the configured staleness threshold for cached values (0 if disabled); DeadLetterEntries returns write commands that failed after all retries, stored for inspection or manual retry.

type TagConfig

type TagConfig struct {
	Name     string  `yaml:"name"`
	Address  string  `yaml:"address"`
	Type     string  `yaml:"type"`
	Group    string  `yaml:"group"`
	Interval string  `yaml:"interval"`
	Scale    float64 `yaml:"scale,omitempty"`
	Offset   float64 `yaml:"offset,omitempty"`
	DeadBand float64 `yaml:"deadband,omitempty"`

	// ReadTimeout is an optional per-tag read timeout, independent of the
	// collection interval. When unset (empty), the scheduler falls back to
	// the collection interval. This decouples "how often to poll" from
	// "how long to wait for a response", which matters for high-frequency
	// 采集 (e.g. interval=200ms but read-timeout=1s) and low-frequency
	// 采集 (e.g. interval=10s but read-timeout=3s).
	ReadTimeout string `yaml:"read-timeout,omitempty"`
}

TagConfig defines the configuration for a single tag/data point.

type TagValue

type TagValue struct {
	Tag       string    `json:"tag"`
	Value     any       `json:"value"`
	Type      DataType  `json:"type"`
	Quality   Quality   `json:"quality"`
	Timestamp time.Time `json:"timestamp"`
	Error     error     `json:"-"`
}

TagValue represents a raw value read from a device.

type TransformConfig

type TransformConfig struct {
	Expression string `yaml:"expression"`
	TagRename  string `yaml:"tag-rename,omitempty"`
}

TransformConfig defines a data transformation.

type Transport

type Transport interface {
	// Lifecycle
	Init(ctx context.Context, config TransportConfig) error
	Start(ctx context.Context) error
	Stop() error

	// Data publishing
	Publish(ctx context.Context, point DataPoint) error
	PublishBatch(ctx context.Context, points []DataPoint) error

	// Reverse channel for receiving write commands
	OnCommand() <-chan WriteCommand

	// OnData returns a channel of DataPoints received from an upstream
	// source (e.g. another CoreC instance via MQTT subscription or an
	// HTTP webhook).  This enables chained-core topologies where a
	// transport acts as both a data consumer (inbound) and a data
	// producer (outbound).  Returns nil when data ingestion is not
	// configured for this transport.
	OnData() <-chan DataPoint

	// Metadata
	Name() string
	Type() string
	Status() TransportStatus
}

Transport defines the northbound transport interface.

func CreateTransport

func CreateTransport(config TransportConfig) (Transport, error)

CreateTransport creates a transport instance using the registered factory.

type TransportConfig

type TransportConfig struct {
	Name          string         `yaml:"name"`
	Type          string         `yaml:"type"`
	Settings      map[string]any `yaml:"settings"`
	BatchSize     int            `yaml:"batch-size,omitempty"`
	FlushInterval string         `yaml:"flush-interval,omitempty"`
	RetryCount    int            `yaml:"retry-count,omitempty"`
	// BufferSize is the capacity of the internal command channel.
	// <=0 falls back to core.DefaultCommandBufferSize (100).
	BufferSize int `yaml:"buffer-size,omitempty"`
	// Fallback names a secondary transport to use when this transport
	// fails to publish. The engine routes the data point to the
	// fallback transport on publish failure. Empty = no fallback.
	Fallback string `yaml:"fallback,omitempty"`
}

TransportConfig holds configuration for a transport instance.

type TransportFactory

type TransportFactory func(config TransportConfig) (Transport, error)

TransportFactory creates a Transport instance from configuration.

type TransportManager added in v0.0.3

type TransportManager interface {
	AddTransport(config TransportConfig) error
	RemoveTransport(name string) error
	GetTransport(name string) (Transport, bool)
	ListTransports() []TransportStatus
}

TransportManager covers adding, removing, and inspecting transports.

type TransportStatus

type TransportStatus struct {
	Name        string    `json:"name"`
	Type        string    `json:"type"`
	State       ConnState `json:"state"`
	Published   uint64    `json:"published"`
	Failed      uint64    `json:"failed"`
	Received    uint64    `json:"received"` // data points ingested via OnData (chained-core inbound)
	LastPublish time.Time `json:"last_publish"`
	QueueSize   int       `json:"queue_size"`
	// DroppedCommands counts write commands dropped at ingress because the
	// command channel was full. Non-zero indicates sustained command
	// backpressure; investigate buffer-size tuning or consumer throughput.
	DroppedCommands uint64 `json:"dropped_commands"`
}

TransportStatus reports the current status of a transport.

type WriteCommand

type WriteCommand struct {
	Driver string   `json:"driver"`
	Device string   `json:"device"`
	Tag    string   `json:"tag"`
	Value  any      `json:"value"`
	Type   DataType `json:"type"`
}

WriteCommand represents a command to write a value to a device.

type WriteResult

type WriteResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

WriteResult represents the result of a write operation.

Jump to

Keyboard shortcuts

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