store

package
v0.0.0-...-cbee766 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package store owns monitor's SQLite connection and persistence repositories.

Index

Constants

View Source
const MaxLogRecordPage = 200

MaxLogRecordPage 是一页最多返回的条数。

Variables

View Source
var (
	ErrResourceReferenced = errors.New("resource is still referenced")
	ErrInvalidReference   = errors.New("referenced resource is missing or disabled")
)
View Source
var ErrNotificationChannelExists = errors.New("该 Webhook URL 已经添加过")

ErrNotificationChannelExists 表示同一个 Webhook URL 已经添加过。

Functions

func DeleteBefore

func DeleteBefore(ctx context.Context, db *gorm.DB, table, column string, cutoff time.Time) (int64, error)

DeleteBefore removes the rows of table whose column is before cutoff, in batches of at most retentionDeleteRows. column must be indexed.

func WithDatabase

func WithDatabase[T any](m *Store, fn func(*gorm.DB) T) (T, error)

WithDatabase runs a short-lived construction callback against the private database handle. Production callers should prefer Repositories or domain methods; this escape hatch is reserved for bounded-context adapters.

Types

type AlertRepository

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

func NewAlertRepository

func NewAlertRepository(db *gorm.DB) *AlertRepository

func (*AlertRepository) CountFiring

func (r *AlertRepository) CountFiring(ctx context.Context, spaceID string) (int64, error)

func (*AlertRepository) CreateEvent

func (r *AlertRepository) CreateEvent(ctx context.Context, event *domain.AlertEvent) error

func (*AlertRepository) CreateEventIdempotent

func (r *AlertRepository) CreateEventIdempotent(ctx context.Context, event *domain.AlertEvent) error

func (*AlertRepository) CreateRule

func (r *AlertRepository) CreateRule(ctx context.Context, rule *domain.AlertRule) error

func (*AlertRepository) DeleteEventsOlderThan

func (r *AlertRepository) DeleteEventsOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

func (*AlertRepository) DeleteRule

func (r *AlertRepository) DeleteRule(ctx context.Context, spaceID, ruleID string) error

func (*AlertRepository) GetRule

func (r *AlertRepository) GetRule(ctx context.Context, spaceID, ruleID string) (*domain.AlertRule, error)

func (*AlertRepository) GetRuleByID

func (r *AlertRepository) GetRuleByID(ctx context.Context, ruleID string) (*domain.AlertRule, error)

func (*AlertRepository) GetState

func (r *AlertRepository) GetState(ctx context.Context, spaceID, ruleID, checkID string) (*domain.AlertState, error)

func (*AlertRepository) LatestFiringEvent

func (r *AlertRepository) LatestFiringEvent(ctx context.Context, spaceID, ruleID, checkID string) (*domain.AlertEvent, error)

func (*AlertRepository) LatestTriggeredEventBefore

func (r *AlertRepository) LatestTriggeredEventBefore(ctx context.Context, spaceID, checkID string, before time.Time) (*domain.AlertEvent, error)

LatestTriggeredEventBefore 返回某个检查在 before 之前最近一次触发事件;没有时返回 nil。

func (*AlertRepository) ListEnabledFiringStates

func (r *AlertRepository) ListEnabledFiringStates(ctx context.Context, spaceID string, limit int) ([]domain.AlertState, error)

ListEnabledFiringStates applies the code-owned check/rule filter in SQL before limiting the response. This keeps the health page bounded without letting disabled rows crowd out active alerts or issuing N+1 lookups.

func (*AlertRepository) ListEnabledRulesForCheck

func (r *AlertRepository) ListEnabledRulesForCheck(ctx context.Context, spaceID, checkID string) ([]domain.AlertRule, error)

func (*AlertRepository) ListEvents

func (r *AlertRepository) ListEvents(ctx context.Context, spaceID string, limit int) ([]domain.AlertEvent, error)

func (*AlertRepository) ListEventsSince

func (r *AlertRepository) ListEventsSince(ctx context.Context, spaces []string, since time.Time, limit int) ([]domain.AlertEvent, error)

ListEventsSince 返回 since 之后(含)的告警事件,按时间升序;超过 limit 条时只保留最新的 limit 条。 spaces 为空表示不限空间。

func (*AlertRepository) ListFiringStates

func (r *AlertRepository) ListFiringStates(ctx context.Context, spaceID string, limit int) ([]domain.AlertState, error)

func (*AlertRepository) ListRecentEvents

func (r *AlertRepository) ListRecentEvents(ctx context.Context, limit int) ([]domain.AlertEvent, error)

ListRecentEvents returns recent alert transitions across all spaces.

func (*AlertRepository) ListRules

func (r *AlertRepository) ListRules(ctx context.Context, spaceID string) ([]domain.AlertRule, error)

func (*AlertRepository) ListRulesForCheck

func (r *AlertRepository) ListRulesForCheck(ctx context.Context, spaceID, checkID string) ([]domain.AlertRule, error)

func (*AlertRepository) UpdateRule

func (r *AlertRepository) UpdateRule(ctx context.Context, rule *domain.AlertRule) error

func (*AlertRepository) UpsertState

func (r *AlertRepository) UpsertState(ctx context.Context, state *domain.AlertState) error

type CheckRepository

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

func NewCheckRepository

func NewCheckRepository(db *gorm.DB) *CheckRepository

func (*CheckRepository) Count

func (*CheckRepository) CountEnabled

func (r *CheckRepository) CountEnabled(ctx context.Context) (int64, error)

func (*CheckRepository) Create

func (r *CheckRepository) Create(ctx context.Context, check *domain.Check) error

func (*CheckRepository) Delete

func (r *CheckRepository) Delete(ctx context.Context, spaceID, checkID string) error

func (*CheckRepository) Get

func (r *CheckRepository) Get(ctx context.Context, spaceID, checkID string) (*domain.Check, error)

func (*CheckRepository) GetByCheckID

func (r *CheckRepository) GetByCheckID(ctx context.Context, checkID string) (*domain.Check, error)

func (*CheckRepository) List

func (*CheckRepository) ListDue

func (r *CheckRepository) ListDue(ctx context.Context, now time.Time, limit int) ([]domain.Check, error)

func (*CheckRepository) ListEnabledKinds

func (r *CheckRepository) ListEnabledKinds(ctx context.Context, spaceID string, kinds []string, limit int) ([]domain.Check, error)

ListEnabledKinds filters structured namespaces before the response bound.

func (*CheckRepository) MarkChecked

func (r *CheckRepository) MarkChecked(ctx context.Context, spaceID, checkID string, checkedAt, nextAt time.Time) error

func (*CheckRepository) Update

func (r *CheckRepository) Update(ctx context.Context, check *domain.Check) error

type ComponentHealthRepository

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

func (*ComponentHealthRepository) List

func (*ComponentHealthRepository) Reconcile

Reconcile is called by the sampler, never by an overview HTTP request.

type GatewayRepository

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

func (*GatewayRepository) List

func (*GatewayRepository) Reconcile

func (r *GatewayRepository) Reconcile(ctx context.Context, observations []domain.GatewayObservation, now time.Time) error

Reconcile receives one attempted observation per enabled host. Read failures preserve the last verified status and mismatch deadline. Removed/disabled hosts leave the active cache; their alert checks are retired by the evaluator.

type InventoryRepository

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

InventoryRepository 保存最后一份有效的采集任务清单(只有一行)。

func NewInventoryRepository

func NewInventoryRepository(store *Store) *InventoryRepository

NewInventoryRepository 创建清单仓储。

func (*InventoryRepository) LoadInventory

func (r *InventoryRepository) LoadInventory(ctx context.Context) ([]byte, time.Time, error)

LoadInventory 读取清单;没有则返回空。

func (*InventoryRepository) SaveInventory

func (r *InventoryRepository) SaveInventory(ctx context.Context, snapshot []byte, fetchedAt time.Time) error

SaveInventory 覆盖保存清单。

type ListChecksOptions

type ListChecksOptions struct {
	SpaceID   string
	GroupName string
	Source    string
	Enabled   *bool
	Page      Page
}

type LogBucket

type LogBucket struct {
	Hour   string
	Errors int64
	Events int64
}

LogBucket 是一个小时里的日志条数:Errors 是 Error 及以上,Events 是其余的(关键事件)。

type LogRecordFilter

type LogRecordFilter struct {
	HostID    string
	Component string
	// Level 是最低级别:error 只看 Error 及以上,info 连关键事件一起看;空表示不限。
	Level string
	// Keyword 在正文、事件名、代码位置里按子串匹配。
	Keyword string
	Start   time.Time
	End     time.Time
	// BeforeID 大于 0 时只返回主键更小的记录(向更早翻页)。
	BeforeID int64
	Limit    int
}

LogRecordFilter 是查询条件;零值字段不参与筛选。

type LogRecordRepository

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

LogRecordRepository 保存各服务上报的重要日志。

这里的方法不能写 tRPC 日志:Monitor 自己的 Error 日志也会进这张表,写库失败时再打 Error 会循环。

func NewLogRecordRepository

func NewLogRecordRepository(db *gorm.DB) *LogRecordRepository

func (*LogRecordRepository) Buckets

func (r *LogRecordRepository) Buckets(ctx context.Context, filter LogRecordFilter) ([]LogBucket, error)

Buckets 按小时统计符合条件的日志条数(不看 BeforeID 和 Limit),按时间升序,只含有记录的小时。 Hour 是这个小时的起点(UTC,RFC 3339)。

func (*LogRecordRepository) InsertBatch

func (r *LogRecordRepository) InsertBatch(ctx context.Context, records []domain.LogRecord) (int64, error)

InsertBatch 写入一批日志,已经存在的(同一个 RecordKey)跳过。返回实际新写入的条数。

func (*LogRecordRepository) Prune

func (r *LogRecordRepository) Prune(ctx context.Context, cutoff time.Time, maxRows int64) (int64, error)

Prune 删除日志时间早于 cutoff 的记录;之后如果总行数仍超过 maxRows,从最旧的删起。返回删除的行数。

func (*LogRecordRepository) Query

Query 按条件返回日志,新的在前(按主键倒序,主键随写入递增)。

type NotificationRepository

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

func NewNotificationRepository

func NewNotificationRepository(db *gorm.DB) *NotificationRepository

func (*NotificationRepository) Add

func (r *NotificationRepository) Add(ctx context.Context, channelType, webhookURL, secret string) (*domain.NotificationChannel, error)

Add 新增一个渠道并返回它。URL 的格式、平台域名与密钥由调用方校验,这里只保证类型合法、URL 不重复。

func (*NotificationRepository) Delete

func (r *NotificationRepository) Delete(ctx context.Context, channelID string) error

Delete 删除一个渠道;不存在时返回 gorm.ErrRecordNotFound。

func (*NotificationRepository) List

List 按添加顺序返回全部通知渠道。

type Page

type Page struct {
	Page     int
	PageSize int
}

func (Page) Limit

func (p Page) Limit() int

type Repositories

type Repositories struct {
	Checks          *CheckRepository
	Topology        *TopologyRepository
	ComponentHealth *ComponentHealthRepository
	Gateways        *GatewayRepository
	Results         *ResultRepository
	Alerts          *AlertRepository
	Notifications   *NotificationRepository
	Logs            *LogRecordRepository
}

Repositories is the monitor control-plane persistence graph. Bootstrap creates it once and injects the individual capabilities into services, keeping database construction out of orchestration code.

func NewRepositories

func NewRepositories(db *gorm.DB) *Repositories

type ResultRepository

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

func NewResultRepository

func NewResultRepository(db *gorm.DB) *ResultRepository

func (*ResultRepository) DeleteOlderThan

func (r *ResultRepository) DeleteOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

func (*ResultRepository) Earliest

func (r *ResultRepository) Earliest(ctx context.Context, spaceID, checkID string) (*domain.CheckResult, error)

Earliest 返回检查最早一条结果;没有时返回 nil。

func (*ResultRepository) Insert

func (r *ResultRepository) Insert(ctx context.Context, result *domain.CheckResult) error

func (*ResultRepository) InsertIfAbsent

func (r *ResultRepository) InsertIfAbsent(ctx context.Context, result *domain.CheckResult) (bool, error)

func (*ResultRepository) LastFailure

func (r *ResultRepository) LastFailure(ctx context.Context, spaceID, checkID string) (*domain.CheckResult, error)

LastFailure preserves the cause while an alert waits for its recovery threshold.

func (*ResultRepository) Latest

func (r *ResultRepository) Latest(ctx context.Context, limit int) ([]domain.CheckResult, error)

Latest returns the newest result for each monitored check.

func (*ResultRepository) LatestWithoutMessage

func (r *ResultRepository) LatestWithoutMessage(ctx context.Context, spaceID, checkID, message string) (*domain.CheckResult, error)

LatestWithoutMessage 返回检查最近一条说明不等于 message 的结果;没有时返回 nil。

func (*ResultRepository) Recent

func (r *ResultRepository) Recent(ctx context.Context, spaceID, checkID string, limit int) ([]domain.CheckResult, error)

func (*ResultRepository) Stats

func (r *ResultRepository) Stats(ctx context.Context, spaceID string, since time.Time) (float64, int64, error)

type Store

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

func Open

func Open(path string) (*Store, error)

func OpenFromConfig

func OpenFromConfig(cfg config.DatabaseConfig) (*Store, error)

func (*Store) ApplySchema

func (m *Store) ApplySchema(sql string) error

func (*Store) Close

func (m *Store) Close() error

func (*Store) Ping

func (m *Store) Ping(ctx context.Context) error

Ping verifies that the database is available.

func (*Store) Repositories

func (m *Store) Repositories() *Repositories

Repositories builds the monitor control-plane repository graph.

func (*Store) SQLDB

func (s *Store) SQLDB() (*sql.DB, error)

SQLDB 返回底层数据库连接(重置时备份与清表用,由生命周期的重置实现调用)。

func (*Store) TableExists

func (m *Store) TableExists(name string) (bool, error)

TableExists 判断表是否已经存在;用于区分首次建库(例如只在首次建库时写入部署配置里的通知渠道)。

type SubjectFirstSeenRepository

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

SubjectFirstSeenRepository 记录活跃对象第一次出现在采集对象清单里的时间,供 K 线新鲜度给新上线对象宽限期。

func NewSubjectFirstSeenRepository

func NewSubjectFirstSeenRepository(store *Store) *SubjectFirstSeenRepository

NewSubjectFirstSeenRepository 创建对象首次出现时间的仓储。

func (*SubjectFirstSeenRepository) DatasetFirstSeen

func (r *SubjectFirstSeenRepository) DatasetFirstSeen(ctx context.Context, spaceID, datasetID string) (time.Time, bool, error)

DatasetFirstSeen 返回数据集的对象最早出现在采集清单里的时间(含部署前的存量);还没有记录时 ok 为假。

func (*SubjectFirstSeenRepository) ObserveSubjects

func (r *SubjectFirstSeenRepository) ObserveSubjects(ctx context.Context, spaceID, datasetID string, active map[string]struct{}, now time.Time) (map[string]time.Time, error)

ObserveSubjects 对账一个数据集当前的活跃对象,返回其中新上线对象的首次出现时间:

  • 数据集还没有任何记录时(首次部署,或数据集刚出现),当前全部活跃对象记为存量,不给宽限;
  • 之后第一次出现的对象记下 now;
  • 已不再活跃的对象删除记录,下次重新上线时重新拿到宽限,表也不会无限增长。

active 为空时不做任何修改:清单异常为空不能清空历史。

type TopologyRepository

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

func (*TopologyRepository) Reconcile

func (r *TopologyRepository) Reconcile(ctx context.Context, snapshot domain.TopologySnapshot, checks []domain.Check) (int, error)

Reconcile commits registration and its probe definitions together. A failed discovery or probe collision cannot leave the overview with half a topology.

func (*TopologyRepository) Snapshot

Snapshot returns nil until a complete discovery has succeeded. An absent snapshot must never be interpreted as an authoritative empty deployment set.

Jump to

Keyboard shortcuts

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