core

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 5 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

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

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

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: 30s. Parse as a duration string.
	ReadTimeout string `yaml:"read-timeout,omitempty"`

	// WriteTimeout is the maximum duration before timing out writes of the
	// response. Default: 30s. 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"`
}

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

func (d DataType) String() string

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 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"`
}

DriverStatus reports the current status of a driver.

type Engine

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

	// Driver management
	AddDriver(config DriverConfig) error
	RemoveDriver(name string) error
	GetDriver(name string) (Driver, bool)
	ListDrivers() []DriverStatus

	// Transport management
	AddTransport(config TransportConfig) error
	RemoveTransport(name string) error
	GetTransport(name string) (Transport, bool)
	ListTransports() []TransportStatus

	// Rule management
	SetRules(rules []RuleConfig) error
	GetRuleStats() []RuleStat
	SetRuleDisabled(index int, disabled bool) error

	// Data operations (for API layer)
	ReadTag(ctx context.Context, driver, tag string) (*TagValue, error)
	WriteTag(ctx context.Context, cmd WriteCommand) (*WriteResult, error)
	LatestValues(driver string) map[string]DataPoint

	// StaleThreshold returns the configured staleness threshold for
	// cached values. Returns 0 if staleness detection is disabled.
	StaleThreshold() time.Duration

	// DeadLetterEntries returns write commands that failed after all
	// retries, stored for inspection or manual retry.
	DeadLetterEntries() []DeadLetterEntry

	// Event subscription
	Subscribe(filter string) (<-chan DataPoint, func())
	OnAlert(handler func(point DataPoint, rule Rule))

	// Status
	Stats() EngineStats
}

Engine is the core orchestrator of the CoreC core.

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"`
}

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 GlobalConfig

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

GlobalConfig holds global settings.

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 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 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
	RemoveTask(id string) error
	Pause() error
	Resume() error
	PauseDriver(name string) error
	ResumeDriver(name string) error
	Stats() SchedulerStats
}

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

type SchedulerStats

type SchedulerStats struct {
	ActiveTasks  int     `json:"active_tasks"`
	PausedTasks  int     `json:"paused_tasks"`
	TickRate     float64 `json:"tick_rate"`
	Overruns     uint64  `json:"overruns"`
	AvgLatencyMs float64 `json:"avg_latency_ms"`
}

SchedulerStats reports scheduler metrics.

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 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"`
}

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