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: 20 Imported by: 0

Documentation

Overview

Package store 是策略模块的 SQLite 持久化层:定义、实例、会话、结果与解释、回放。

Index

Constants

View Source
const (
	HealthOK                = "ok"
	HealthDegraded          = "degraded"
	HealthSessionUnverified = "session_unverified"
)

实例健康状态:degraded 是求值类问题,下一个 ok 周期自动恢复;session_unverified 是 Trade 会话结果未知, 只有重新核实会话成功才恢复,ok 周期不会清除它。

View Source
const (
	ReplayPending   = "pending"
	ReplayRunning   = "running"
	ReplayDone      = "done"
	ReplayFailed    = "failed"
	ReplayCancelled = "cancelled"
)

回放状态。

View Source
const (
	StatusOK      = "ok"
	StatusSkipped = "skipped"
)

结果状态。

View Source
const (
	SkipOutOfOrder = "out_of_order"
	SkipExpired    = "expired"
	// SkipCatchup 是恢复追赶中记录的周期:只记因子指纹(供下一期的相邻周期检查),不求值、不发目标。
	SkipCatchup = "catchup"
	// SkipMarketMissing 是绑定两个因子任务的实例里,另一个市场的数据没有到:缺的那个 View 已经到了更晚的一期,或更晚的一期已经汇合求值,
	// 这一期不会再等到齐。属于数据未到,不计入实例故障。
	SkipMarketMissing = "market_missing"
	// SkipPoolWarmupFailed 是策略池预热失败时留在结果里的一条记录:原因写在输入摘要的说明里,页面的历史结果能直接看到。
	SkipPoolWarmupFailed = "pool_warmup_failed"
)

由存储层或投递流程识别的跳过原因。

View Source
const (
	CancelSuperseded = "superseded" // 被同一会话更新的 ok 结果替代
	CancelExpired    = "expired"    // 投递前已过有效期
	CancelInactive   = "inactive"   // 投递前实例已停用、删除或换了会话
	CancelRejected   = "rejected"   // 事件无法通过契约校验(永久发布错误)
)

待投递结果被取消的原因。

View Source
const MaxActiveReplays = 20

MaxActiveReplays 是每个空间同时排队与运行的回放上限:回放由一个执行循环逐个运行,排队过多只会让后发起的 任务长时间等待,并让按个数清理失去意义。

View Source
const MaxReplayFeeBps = 1000

MaxReplayFeeBps 是回放单边手续费的上限(bps)。

Variables

View Source
var (
	// ErrResultInvalid 表示结果本身不完整。
	ErrResultInvalid = errors.New("策略结果无效")
	// ErrResultInstanceNotActive 表示实例未启用或会话不匹配。
	ErrResultInstanceNotActive = errors.New("实例未在该会话中启用")
	// ErrResultExpired 表示 ok 结果的有效期已过。
	ErrResultExpired = errors.New("策略结果已过期")
	// ErrResultOlder 表示 ok 结果早于已提交的最新周期。
	ErrResultOlder = errors.New("策略结果早于已提交的最新周期")
	// ErrResultCASConflict 表示提交时的前序记录与期望不符。
	ErrResultCASConflict = errors.New("策略结果比较交换冲突")
)

CancelReasons 是全部取消原因。

View Source
var ErrNotFound = gorm.ErrRecordNotFound

ErrNotFound 表示记录不存在。

Functions

func EncodeNextParams

func EncodeNextParams(period time.Time, members json.RawMessage) (json.RawMessage, error)

EncodeNextParams 把目标期和各成员的快照编码成结果里的 next_params_json。

func FriendlyMessage

func FriendlyMessage(err error) (message string, replaced bool)

FriendlyMessage 把错误链中的 SQLite 驱动错误替换为中文概述,避免把表名、列名等内部细节返回给接口调用方; replaced 为 true 时调用方应把原始错误写入日志。

func IsPermanentWriteError

func IsPermanentWriteError(err error) bool

IsPermanentWriteError 判断写入错误是否是确定性的:结果校验失败或违反表约束,原样重试不会成功。

func NewID

func NewID() (string, error)

NewID 生成 UUIDv4 形式的随机标识,用于定义、实例、会话、结果与回放。

func SameTasks

func SameTasks(a, b map[string]string) bool

SameTasks 报告两份因子任务绑定相同。

func SessionTasks

func SessionTasks(resolvedJSON []byte) map[string]string

SessionTasks 从会话固化的绑定解析(resolved_json)里取出全部任务键 → 因子任务:主帧的 tasks、参考市场 references 与附加来源 sources(任务键 来源名:市场)。无法解析时返回空表。

func ValidateTaskKeys

func ValidateTaskKeys(tasks map[string]string) error

ValidateTaskKeys 校验实例登记的因子任务:键是市场或 来源名:市场,市场只能是 spot、swap、equity、multi,任务 ID 不能为空,个数不超过上限。

Types

type CommitRequest

type CommitRequest struct {
	Result Result
	Items  []ResultItem
	// ExpectedLatestResultID 非 nil 时要求本实例本会话当前最新处理记录的 ID 等于它(空串表示期望没有记录)。
	ExpectedLatestResultID *string
	Now                    time.Time
}

CommitRequest 是一次结果提交。

type Definition

type Definition struct {
	StrategyID string
	Name       string
	DSLYaml    string
	DSLHash    string
	DeletedAt  *time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Definition 是一份策略定义:DSL 文本及其内容哈希。

type DefinitionVersion

type DefinitionVersion struct {
	DSLHash   string
	DSLYaml   string
	CreatedAt time.Time
}

DefinitionVersion 是出现过的一个 DSL 版本。

type DisplayHidden

type DisplayHidden struct {
	Categories []string `json:"categories,omitempty"`
	Members    []string `json:"members,omitempty"`
	Columns    []string `json:"columns,omitempty"`
}

DisplayHidden 是实例外显设置里隐藏的内容;没有记录时全部展示。

type InputRecord

type InputRecord struct {
	Bar      string               `json:"bar"`
	Calendar string               `json:"calendar"`
	BarStart time.Time            `json:"bar_start"`
	Views    map[string]ViewInput `json:"views,omitempty"`
	Detail   string               `json:"detail,omitempty"`
}

InputRecord 是结果中保存的输入摘要(c_input_json 的结构):每个绑定的 View 一份。

type Instance

type Instance struct {
	InstanceID string
	StrategyID string
	SpaceID    string
	// FactorTasks 是任务键 → 因子任务 ID:主帧与参考市场的任务键是市场(spot、swap、equity),统一数据集上的任务登记为 multi;
	// 附加来源的任务键是 来源名:市场(见 dsl.TaskKey)。
	FactorTasks      map[string]string
	LogicalAccountID *string
	Enabled          bool
	SessionID        *string
	ResolvedJSON     json.RawMessage
	Health           string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

Instance 把定义绑定到一个空间、一个或两个因子任务和可选的组合账户。因子任务在创建时写定、不能修改;读取的 View 是任务结果数据集的默认 View。

type OutboxStats

type OutboxStats struct {
	PendingCount  int64
	OldestPending time.Time
}

OutboxStats 是待投递结果的统计。

type ParamDelivery

type ParamDelivery struct {
	ResultID   string
	InstanceID string
	SessionID  string
	// Period 是参数生效的目标期(存储起点)。
	Period time.Time
	// Members 是各可变成员的完整快照:{成员键: {参数名: {default, overrides}}}。
	Members json.RawMessage
}

ParamDelivery 是一条等待投递的下一期参数:产出它的结果、实例与会话,以及目标期和各成员的完整快照。

type PublishStatus

type PublishStatus string

PublishStatus 是结果的投递状态。

const (
	PublishNone      PublishStatus = "none"
	PublishPending   PublishStatus = "pending"
	PublishSent      PublishStatus = "sent"
	PublishCancelled PublishStatus = "cancelled"
)

type ReadyEvent

type ReadyEvent struct {
	InstanceID string
	SessionID  string
	ViewID     string
	BarEnd     time.Time
	EventID    string
	Payload    []byte
	ArrivedAt  time.Time
}

ReadyEvent 是绑定多个因子任务的实例收到的一个 View 的就绪事件(原始 ViewDataReady 按字节保存)。

type Replay

type Replay struct {
	ReplayID   string
	StrategyID *string
	// InstanceID 与 SessionID 记录从实例发起的回放来自哪个实例、回放的是哪个会话固化的 DSL。
	InstanceID *string
	SessionID  *string
	DSLYaml    string
	// DSLHash 是被回放 DSL 的内容哈希(列表不带 DSL 全文时据此展示版本)。Calendar 是回放所用的日历
	// (A 股日线的区间按上海日期解释,页面据此显示日期)。
	DSLHash  string
	Calendar string
	SpaceID  string
	// Tasks 是各任务键(市场 spot、swap、equity,统一数据集上的任务是 multi;附加来源是 来源名:市场)读取的因子任务与结果 View。
	Tasks     map[string]ReplayTask
	StartTime time.Time
	EndTime   time.Time
	// SpotFeeBps 是现货与股票的单边手续费,SwapFeeBps 是永续的(基点)。
	SpotFeeBps float64
	SwapFeeBps float64
	// FundingColumn 非空时永续持仓按 View 里的这一列(本根累计的资金费率)结算资金费;空串表示不计。
	FundingColumn string
	// MembersJSON 是策略池回放发起时固化的成员(input.PoolMember 列表的 JSON,与会话的成员快照同一格式);执行时只读它,
	// 不重读成员定义。单策略回放为空(落库为 NULL);列表不读这一列。
	MembersJSON string
	// Factors 是发起回放时固化的因子定义指纹;执行时与当时的定义比对,排队期间变化即拒绝执行。
	Factors      map[string]string
	Status       string
	ProgressTime *time.Time
	MetricsJSON  json.RawMessage
	Error        string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

Replay 是一次基于 View 的研究回放任务。

type ReplayBar

type ReplayBar struct {
	ReplayID      string
	BarEndTime    time.Time
	Status        string
	TargetsJSON   json.RawMessage
	PositionsJSON json.RawMessage
	SummaryJSON   json.RawMessage
	Return        float64
	Equity        float64
	Turnover      float64
	Fee           float64
	// SpotValue 是期末现货类持仓的市值之和,SwapValue 是永续持仓的净名义价值(多头为正、空头为负)。
	SpotValue  float64
	SwapValue  float64
	Holdings   int
	Frozen     int
	SkipReason string
	Unfilled   int
	Liquidated int
}

ReplayBar 是回放中一个周期的记录。

type ReplayTask

type ReplayTask struct {
	FactorTaskID string `json:"factor_task_id"`
	// ViewID 是任务的结果 View;ViewGeneration 是提交时校验区间所用的活动索引代次:同一代索引只追加、不删除行,
	// 执行时代次没变就沿用提交时的区间。
	ViewID         string `json:"view_id"`
	ViewGeneration string `json:"view_generation"`
}

ReplayTask 是回放在一个市场读取的因子任务及其结果 View。

type Result

type Result struct {
	ResultID       string
	InstanceID     string
	SessionID      string
	BarEndTime     time.Time
	ValidUntil     time.Time
	Status         string
	SkipReason     string
	DSLHash        string
	InputJSON      json.RawMessage
	TargetsJSON    json.RawMessage
	RuleStatesJSON json.RawMessage
	SummaryJSON    json.RawMessage
	EventData      []byte
	PublishStatus  PublishStatus
	CreatedAt      time.Time
	// NextParamsJSON 是这一期算出的下一期可变成员参数(形如 {"period": 目标期 Unix 秒, "members": {成员键: {参数名: {default, overrides}}}}),
	// 没有可变成员或求值失败时为空。ParamsDeliveredAt 是它被因子侧接受的时间,ParamsError 是被因子侧明确拒绝的原因(不再重试)。
	NextParamsJSON    json.RawMessage
	ParamsDeliveredAt *time.Time
	ParamsError       string
}

Result 是一个处理过的周期:ok 带目标与规则状态,skipped 带原因。

type ResultItem

type ResultItem struct {
	RuleID       string
	InstrumentID string
	// Market 是入选的权重进入的市场,其余是所选行所在的市场(spot | swap | equity)。
	Market string
	Stage  string
	Score  *float64
	Rank   *int
	Weight *string
	Reason string
	// Scale 是乘在输出权重上的仓位系数(Weight 已乘过);规则没写 scale 时为空。
	Scale *float64
}

ResultItem 是一条规则下一个标的的解释。

type Session

type Session struct {
	SessionID    string
	InstanceID   string
	DSLHash      string
	ResolvedJSON string
	// MembersJSON 是策略池固化的成员(input.PoolMember 列表的 JSON),非池为空。
	MembersJSON string
	// WarmState 是策略池预热完成时的引擎状态(engine.State 的 JSON);WarmedThrough 是预热推进到的最后一期(bar_end),
	// nil 表示预热还没完成。非池会话两者都为空。
	WarmState     string
	WarmedThrough *time.Time
	CreatedAt     time.Time
	ClosedAt      *time.Time
}

Session 是一次启用:固化当时的 DSL 版本与绑定解析。

type Store

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

Store 持有单写连接的 SQLite 数据库。

func New

func New(db *gorm.DB) *Store

New 用已打开的连接构造 Store(测试使用)。

func Open

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

Open 打开策略数据库并配置单写连接池;已存在的表必须与当前 schema 一致。

func (*Store) ActiveReplaysOfInstance

func (s *Store) ActiveReplaysOfInstance(ctx context.Context, instanceID, spaceID string, taskIDs []string) ([]string, error)

ActiveReplaysOfInstance 返回还在排队或执行、会读到实例数据的回放 ID:从实例发起的,以及空间内读取 taskIDs 中任一任务的。

func (*Store) AdjacentRecord

func (s *Store) AdjacentRecord(ctx context.Context, instanceID string, viewIDs []string, bar, calendar string, barEnd time.Time, factorIDs []string, preferSessionID string) (Result, InputRecord, bool, error)

AdjacentRecord 查找本实例对某一根 bar 的可信处理记录:同一 bar 与日历,且每个 View 都含有全部所需因子的指纹; 不限会话,优先当前会话,其次创建时间最新。

func (*Store) AppendReplayBar

func (s *Store) AppendReplayBar(ctx context.Context, bar ReplayBar) error

AppendReplayBar 写入一个周期的回放记录。

func (*Store) ApplySchema

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

ApplySchema 执行建表 SQL 并校验结果。

func (*Store) CancelReplay

func (s *Store) CancelReplay(ctx context.Context, replayID string, at time.Time) error

CancelReplay 取消 pending 或 running 的回放;运行中的任务由执行循环在下一期检查状态后停止。

func (*Store) ClaimNextReplay

func (s *Store) ClaimNextReplay(ctx context.Context, at time.Time) (Replay, bool, error)

ClaimNextReplay 把最早的 pending 回放改为 running 并返回;没有则返回 false。

func (*Store) ClearInstanceSession

func (s *Store) ClearInstanceSession(ctx context.Context, instanceID, expectedSessionID string, at time.Time) error

ClearInstanceSession 在 Trade 确认释放后清空停用实例的会话;比较交换,避免延迟的释放清掉新会话。

func (*Store) Close

func (s *Store) Close() error

Close 释放数据库连接。

func (*Store) CloseSession

func (s *Store) CloseSession(ctx context.Context, sessionID string, at time.Time) error

CloseSession 记录会话结束时间(停用或启用失败)。

func (*Store) CommitResult

func (s *Store) CommitResult(ctx context.Context, request CommitRequest) (Result, bool, error)

CommitResult 在一个事务内写入结果与解释明细。ok 结果要求实例启用、会话匹配、未过期且不早于最新周期; skipped 结果允许过去的有效期与更早的周期(乱序记录)。同一周期重复提交返回已有记录。

func (*Store) CountActiveReplays

func (s *Store) CountActiveReplays(ctx context.Context, spaceID string) (int64, error)

CountActiveReplays 返回空间内排队与运行中的回放数。

func (*Store) CreateDefinition

func (s *Store) CreateDefinition(ctx context.Context, def Definition) error

CreateDefinition 新建定义并登记其 DSL 版本。

func (*Store) CreateInstance

func (s *Store) CreateInstance(ctx context.Context, instance Instance) error

CreateInstance 新建停用状态的实例。

func (*Store) CreateReplay

func (s *Store) CreateReplay(ctx context.Context, replay Replay) error

CreateReplay 登记一个 pending 的回放任务。

func (*Store) DeleteInstance

func (s *Store) DeleteInstance(ctx context.Context, instanceID, spaceID string, viewIDs []string) error

DeleteInstance 在一个事务里删除已停用、没有会话的实例在策略库里的全部记录:会话、结果与明细、到达记录、回放、外显设置、 因子任务登记和实例本身;viewIDs 是实例结果数据集的 View,按 (空间, View) 存的年龄探针记录一并删除。 实例不存在返回 ErrNotFound;实例已启用或还挂着会话时什么也不删。

func (*Store) DeleteReadyEventsBefore

func (s *Store) DeleteReadyEventsBefore(ctx context.Context, cutoff time.Time) (int64, error)

DeleteReadyEventsBefore 删除到达时间早于 cutoff 的就绪事件记录(分批,不在单连接上长时间阻塞)。

func (*Store) DeleteReplaysBefore

func (s *Store) DeleteReplaysBefore(ctx context.Context, cutoff time.Time) (int64, error)

DeleteReplaysBefore 删除创建时间早于 cutoff 且已结束的回放:逐个回放先分批删周期记录,再删任务本身, 每条语句的工作量有界,不会在单连接上长时间阻塞事件处理与接口。

func (*Store) DeleteReplaysBeyond

func (s *Store) DeleteReplaysBeyond(ctx context.Context, keep int) (int64, error)

DeleteReplaysBeyond 让每个空间只保留最近 keep 个已结束的回放:每期都记录持仓账本,一个长回放可达数十 MB, 只按天数清理挡不住频繁回放把数据库撑大。运行中与排队中的回放不删。

func (*Store) DeleteResultItemsBefore

func (s *Store) DeleteResultItemsBefore(ctx context.Context, cutoff time.Time) (int64, error)

DeleteResultItemsBefore 删除创建时间早于 cutoff 的解释明细;结果主表永久保留。 明细自带 c_ctime 索引,每次只扫描新过期的行,耗时不随历史结果增长。

func (*Store) DeleteTemplate

func (s *Store) DeleteTemplate(ctx context.Context, templateID string) (bool, error)

DeleteTemplate 删除一个模板;已生成的策略不受影响。

func (*Store) DisableInstance

func (s *Store) DisableInstance(ctx context.Context, instanceID string, sessionID, pending *string, health string, at time.Time) error

DisableInstance 在一个事务里停用实例并关闭会话:pending 非空时保留它等待 Trade 释放,否则清空。 停用与关闭会话必须同时成功,否则再次启用时可能沿用一个本应关闭的会话。health 非空时在同一事务里设置健康状态 (对账自动停用时标记 degraded,让原因留在实例上)。

func (*Store) EnabledInstancesByView

func (s *Store) EnabledInstancesByView(ctx context.Context, spaceID, viewID string) ([]Instance, error)

EnabledInstancesByView 返回事件路由到某个 View 的启用实例:实例读取的是关联因子任务的结果 View,所以由 View ID 推出任务 ID 再按任务查;不是因子结果 View 的 ID 没有实例。

func (*Store) FinishReplay

func (s *Store) FinishReplay(ctx context.Context, replayID, status string, metricsJSON json.RawMessage, errText string, at time.Time) error

FinishReplay 把运行中的回放置为终态(done | failed)。

func (*Store) GetDefinition

func (s *Store) GetDefinition(ctx context.Context, strategyID string) (Definition, error)

GetDefinition 读取定义,包括已软删除的(DeletedAt 非空),供历史页面还原。

func (*Store) GetDefinitionVersion

func (s *Store) GetDefinitionVersion(ctx context.Context, dslHash string) (DefinitionVersion, error)

GetDefinitionVersion 按内容哈希读取 DSL 文本。

func (*Store) GetDisplayHidden

func (s *Store) GetDisplayHidden(ctx context.Context, instanceID string) (DisplayHidden, error)

GetDisplayHidden 读取实例的外显设置;没有记录时返回空设置(全部展示)。

func (*Store) GetInstance

func (s *Store) GetInstance(ctx context.Context, instanceID string) (Instance, error)

GetInstance 读取实例。

func (*Store) GetReplay

func (s *Store) GetReplay(ctx context.Context, replayID string) (Replay, error)

GetReplay 读取回放任务。

func (*Store) GetResult

func (s *Store) GetResult(ctx context.Context, resultID string) (Result, error)

GetResult 读取结果。

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, sessionID string) (Session, error)

GetSession 读取会话快照。

func (*Store) GetTemplate

func (s *Store) GetTemplate(ctx context.Context, templateID string) (Template, bool, error)

GetTemplate 读取一个模板。

func (*Store) LatestBarEnds

func (s *Store) LatestBarEnds(ctx context.Context, instanceID string) (processed, ok time.Time, err error)

LatestBarEnds 返回实例(不分会话)最近处理的一根与最近一个 ok 的一根的 bar_end;没有记录时为零值。Monitor 的 期望间隔以它们为基准,进程重启或重新启用后从库里恢复,而不是退回偏宽或偏紧的估计。

func (*Store) LatestOk

func (s *Store) LatestOk(ctx context.Context, instanceID, sessionID string) (Result, bool, error)

LatestOk 返回本会话最近的 ok 决策,规则状态只从它恢复。

func (*Store) LatestProcessed

func (s *Store) LatestProcessed(ctx context.Context, instanceID, sessionID string) (Result, bool, error)

LatestProcessed 返回本会话最近处理的周期(ok 或 skipped)。

func (*Store) LatestReadyByView

func (s *Store) LatestReadyByView(ctx context.Context, instanceID, sessionID string, viewIDs []string) (map[string]time.Time, error)

LatestReadyByView 返回本会话给定的每个 View 已到达的最晚一期;没有记录的 View 不出现在结果里。 每个 View 各查一次“按 bar_end 倒序取一行”:沿主键(实例, 会话, bar_end, View)从最新一期往回找,命中即停,不扫整个会话的记录。

func (*Store) LatestState

func (s *Store) LatestState(ctx context.Context, instanceID, sessionID string) (Result, bool, error)

LatestState 返回本会话最近一条带规则状态的记录:ok 决策,以及迟到周期(追赶、有效期已过)只推进状态的 skipped 记录。 其他 skipped 记录的规则状态是空对象,不参与。规则状态从它恢复,状态才不会因为跳过的周期而缺口。

func (*Store) ListDefinitions

func (s *Store) ListDefinitions(ctx context.Context) ([]Definition, error)

ListDefinitions 列出未删除的定义。

func (*Store) ListInstances

func (s *Store) ListInstances(ctx context.Context, spaceID string, enabled *bool) ([]Instance, error)

ListInstances 列出实例;spaceID 为空表示全部空间。

func (*Store) ListPendingResults

func (s *Store) ListPendingResults(ctx context.Context, limit int) ([]Result, error)

ListPendingResults 按创建顺序列出待投递的结果。

func (*Store) ListReplayBars

func (s *Store) ListReplayBars(ctx context.Context, replayID string, offset, limit int, brief bool) ([]ReplayBar, int64, error)

ListReplayBars 按周期顺序分页读取回放记录。brief 为 true 时不读目标、持仓与摘要 JSON(返回空值), 用于绘制权益曲线与概览,单页可以取得很大而不受报文大小限制。

func (*Store) ListReplays

func (s *Store) ListReplays(ctx context.Context, spaceID string, offset, limit int) ([]Replay, int64, error)

ListReplays 按创建时间倒序分页列出空间内的回放。

func (*Store) ListResultItems

func (s *Store) ListResultItems(ctx context.Context, resultID string) ([]ResultItem, error)

ListResultItems 读取一个结果的解释明细,按规则与标的排序。

func (*Store) ListResults

func (s *Store) ListResults(ctx context.Context, instanceID, sessionID string, offset, limit int) ([]Result, int64, error)

ListResults 按周期倒序分页列出实例的结果;sessionID 为空表示全部会话。

func (*Store) ListSessions

func (s *Store) ListSessions(ctx context.Context, instanceID string) ([]Session, error)

ListSessions 按创建时间倒序列出实例的会话。

func (*Store) ListTemplates

func (s *Store) ListTemplates(ctx context.Context) ([]Template, error)

ListTemplates 按模板 ID 列出全部模板。

func (*Store) LoadAgePassed

func (s *Store) LoadAgePassed(ctx context.Context, spaceID, viewID, indexID string, minAgeBars int, market string) ([]string, error)

LoadAgePassed 读出某个 View 活动索引下、某个 min_age_bars、某个市场已通过年龄探针的标的。

func (*Store) MarkInstanceDegraded

func (s *Store) MarkInstanceDegraded(ctx context.Context, instanceID, sessionID string, at time.Time) error

MarkInstanceDegraded 在求值类问题出现时把健康的实例标记为 degraded;不覆盖 session_unverified。 只作用于仍以该会话启用的实例:求值期间实例被停用或换了会话时,这一期的结论已不代表实例的当前状态。

func (*Store) MarkParamsDelivered

func (s *Store) MarkParamsDelivered(ctx context.Context, resultID string, at time.Time) error

MarkParamsDelivered 记下参数已被因子侧接受(含幂等重复)。

func (*Store) MarkParamsRejected

func (s *Store) MarkParamsRejected(ctx context.Context, resultID, reason string) error

MarkParamsRejected 记下参数被因子侧明确拒绝的原因:不再重试,也不算送达(连续没有送达会触发告警)。

func (*Store) MarkRunningReplaysInterrupted

func (s *Store) MarkRunningReplaysInterrupted(ctx context.Context, at time.Time) (int64, error)

MarkRunningReplaysInterrupted 在进程启动时把遗留的 running 任务标记为 failed(interrupted),已写入的 bars 保留。

func (*Store) OpenSession

func (s *Store) OpenSession(ctx context.Context, session Session, dslYaml string) error

OpenSession 写入会话快照;dslYaml 用于登记 DSL 版本(已存在则忽略)。

func (*Store) ParamDeliveryStale

func (s *Store) ParamDeliveryStale(ctx context.Context, instanceID, sessionID string, n int) (bool, error)

ParamDeliveryStale 报告实例当前会话里最近 n 条带参数的结果是否都没有送达:不足 n 条时为 false(还谈不上"连续没有送达")。

func (*Store) PendingOutboxStats

func (s *Store) PendingOutboxStats(ctx context.Context) (OutboxStats, error)

PendingOutboxStats 返回待投递结果的数量与最早创建时间。

func (*Store) PendingParamDeliveries

func (s *Store) PendingParamDeliveries(ctx context.Context, limit int) ([]ParamDelivery, error)

PendingParamDeliveries 返回每个启用实例当前会话里待投递的参数(设计 8.3):只投会话里最新一条带参数的结果, 并且它还没送达也没被因子侧明确拒绝;更早的未送达记录被覆盖,不再投递。实例停用或换了会话后,旧会话的记录不再投递。

func (*Store) PendingWarmSessions

func (s *Store) PendingWarmSessions(ctx context.Context) ([]Session, error)

PendingWarmSessions 返回还没有完成预热的策略池会话(未关闭、挂在启用实例上、有成员快照):进程启动时据此重新开始预热。

func (*Store) Ping

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

Ping 检查数据库是否可用。

func (*Store) PreparePendingResult

func (s *Store) PreparePendingResult(ctx context.Context, resultID string, now time.Time) (Result, bool, error)

PreparePendingResult 在投递前复查:实例仍在该会话启用、未过期、且是本会话最新的 ok 决策; 不满足即标记 cancelled,不阻塞后续结果。

func (*Store) PutReadyEvent

func (s *Store) PutReadyEvent(ctx context.Context, event ReadyEvent) (bool, error)

PutReadyEvent 记录一个 View 的就绪事件;(实例, 会话, bar_end, View) 重复时保留先到的那条,返回是否新写入。

func (*Store) ReadyEventsAt

func (s *Store) ReadyEventsAt(ctx context.Context, instanceID, sessionID string, barEnd time.Time) ([]ReadyEvent, error)

ReadyEventsAt 返回本会话某个周期已到达的就绪事件(按 View 排序)。

func (*Store) RecordCancelledReplayMetrics

func (s *Store) RecordCancelledReplayMetrics(ctx context.Context, replayID string, metricsJSON json.RawMessage, at time.Time) error

RecordCancelledReplayMetrics 为已取消的回放写入截至取消时的部分指标。

func (*Store) RecoverInstanceHealth

func (s *Store) RecoverInstanceHealth(ctx context.Context, instanceID, sessionID string, at time.Time) error

RecoverInstanceHealth 在 ok 周期把 degraded 恢复为 ok;session_unverified 只能由重新核实会话恢复。 只作用于仍以该会话启用的实例:对账循环自动停用并标记的 degraded 不能被一个并发提交的 ok 周期抹掉。

func (*Store) ReplayStatus

func (s *Store) ReplayStatus(ctx context.Context, replayID string) (string, error)

ReplayStatus 只读取状态,供执行循环检查取消。

func (*Store) ResultAtBar

func (s *Store) ResultAtBar(ctx context.Context, instanceID, sessionID string, barEnd time.Time) (Result, bool, error)

ResultAtBar 返回本会话某个周期的记录。

func (*Store) SQLDB

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

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

func (*Store) SaveAgePassed

func (s *Store) SaveAgePassed(ctx context.Context, spaceID, viewID, indexID string, minAgeBars int, market string, subjectIDs []string, at time.Time) error

SaveAgePassed 登记通过年龄探针的标的,并清掉该 View 其他活动索引下的旧记录(索引重建后不再有效)。

func (*Store) SaveTemplate

func (s *Store) SaveTemplate(ctx context.Context, value Template) (Template, error)

SaveTemplate 新建或整体替换一个模板(按模板 ID)。

func (*Store) SetCancelObserver

func (s *Store) SetCancelObserver(fn func(reason string, count int64))

SetCancelObserver 设置待投递结果被取消时的回调(事务提交之后调用);传 nil 关闭。

func (*Store) SetDisplayHidden

func (s *Store) SetDisplayHidden(ctx context.Context, instanceID string, hidden DisplayHidden, at time.Time) (DisplayHidden, error)

SetDisplayHidden 保存实例的外显设置;全部展示时删除记录。实例不存在或已删除返回 ErrNotFound。

func (*Store) SetInstanceEnabled

func (s *Store) SetInstanceEnabled(ctx context.Context, instanceID string, enabled bool, sessionID *string, resolvedJSON json.RawMessage, at time.Time) error

SetInstanceEnabled 推进启用握手:enabled=false 把会话挂到停用的实例上(启用流程先写会话再联系 Trade,认领响应 丢失时启动对账能释放这个确定的身份);enabled=true 把挂着该会话的实例置为启用。两步都对会话做比较交换。 停用走 DisableInstance(同时关闭会话)。

func (*Store) SetInstanceHealth

func (s *Store) SetInstanceHealth(ctx context.Context, instanceID, health string, at time.Time) error

SetInstanceHealth 更新健康状态(ok | degraded)。

func (*Store) SetSentAfterCancelObserver

func (s *Store) SetSentAfterCancelObserver(fn func())

SetSentAfterCancelObserver 设置已取消的结果确认已经发出、改记 sent 时的回调;传 nil 关闭。

func (*Store) SetSessionWarmed

func (s *Store) SetSessionWarmed(ctx context.Context, sessionID, state string, through time.Time) (bool, error)

SetSessionWarmed 写入策略池预热的结果(预热完成时的引擎状态与推进到的最后一期):比较交换,只在会话未关闭、 且还没有预热结果时写入,返回是否写入(会话已被停用或已经预热过时为 false)。

func (*Store) SoftDeleteDefinition

func (s *Store) SoftDeleteDefinition(ctx context.Context, strategyID string, at time.Time) error

SoftDeleteDefinition 软删除定义;仍被实例引用时拒绝(实例不可删除,被引用的定义因此也不可删除)。

func (*Store) TransitionPublishStatus

func (s *Store) TransitionPublishStatus(ctx context.Context, resultID string, from, to PublishStatus) error

TransitionPublishStatus 把待投递结果标记为已发送或已取消。

func (*Store) UnprocessedReadyPeriods

func (s *Store) UnprocessedReadyPeriods(ctx context.Context, instanceID, sessionID string, after, before time.Time) (map[time.Time][]string, []time.Time, error)

UnprocessedReadyPeriods 返回本会话晚于 after(已处理到的那一期,零值表示没有)、早于 before、有到达记录但还没有结果的周期(升序), 以及每个周期已到达的 View。

func (*Store) UpdateDefinition

func (s *Store) UpdateDefinition(ctx context.Context, def Definition) error

UpdateDefinition 替换 DSL 文本;只允许在没有启用实例引用时修改,并登记新版本。

func (*Store) UpdateInstance

func (s *Store) UpdateInstance(ctx context.Context, instance Instance) error

UpdateInstance 修改停用且无会话实例的定义与账户绑定。因子任务在创建时写定,不能修改(也不写这一列)。

func (*Store) UpdateReplayProgress

func (s *Store) UpdateReplayProgress(ctx context.Context, replayID string, progress, at time.Time) error

UpdateReplayProgress 推进回放进度。

type Template

type Template struct {
	TemplateID   string
	Name         string
	Description  string
	TemplateYAML string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

Template 是一份策略模板:解析与校验由 template 包负责,这里只存原文与展示字段。

type ViewInput

type ViewInput struct {
	EventID  string            `json:"event_id,omitempty"`
	Factors  map[string]string `json:"factors,omitempty"`
	Revision uint64            `json:"revision,omitempty"`
}

ViewInput 是结果中保存的一个 View 的输入摘要:收到的事件与各因子成员的契约指纹。附加来源的 View 另记本期读取时的修订号 (汇合 bar 上还有来源的事件与指纹;非汇合 bar 只有修订号)。

Jump to

Keyboard shortcuts

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