Documentation
¶
Overview ¶
Package search 提供论坛主题全文搜索的宿主框架。
设计要点:
- search 包不直接依赖 forum 包(forum 是底层域),通过 TopicReader / TopicSearchIndexer 接口解耦,避免循环依赖。
- Indexer 同时实现 forum.TopicSearchIndexer(EnqueueIndex/EnqueueDelete, 供 forum.Service 在写流程调度)和 searchjobs.TopicIndexer(IndexTopic, 供 River worker 实际执行)。
- 搜索为派生数据:索引文档可从 PostgreSQL 完全重建,索引失败 不阻断主流程。
- 默认引擎为站内 PostgreSQL FTS(sforum.search-site);外部引擎 (Meilisearch 等)通过 search.provider 可选插件实现。Core 不内嵌 任何 Meilisearch SDK。
Index ¶
- Constants
- Variables
- func IsPublicSearchStatus(status string) bool
- type Engine
- type EngineGate
- type IndexStateStore
- type Indexer
- func (i *Indexer) DeleteTopic(ctx context.Context, topicID int64) error
- func (i *Indexer) EnqueueDelete(ctx context.Context, topicID int64) error
- func (i *Indexer) EnqueueIndex(ctx context.Context, topicID int64) error
- func (i *Indexer) EnsureIndex(ctx context.Context) error
- func (i *Indexer) IndexTopic(ctx context.Context, topicID int64) error
- func (i *Indexer) WithIndexStateStore(state IndexStateStore) *Indexer
- type LiveTopicSource
- type MemorySiteEngine
- func (e *MemorySiteEngine) Delete(_ context.Context, topicID int64) error
- func (e *MemorySiteEngine) EnsureIndex(context.Context) error
- func (e *MemorySiteEngine) Index(_ context.Context, doc TopicSearchDoc) error
- func (e *MemorySiteEngine) Probe(context.Context) error
- func (e *MemorySiteEngine) Search(_ context.Context, input SearchInput) (SearchResult, error)
- type PostgresIndexStateStore
- func (s *PostgresIndexStateStore) ListObsoleteTopicIDs(ctx context.Context, providerID string, limit int) ([]int64, error)
- func (s *PostgresIndexStateStore) ListStaleTopicIDs(ctx context.Context, providerID string, limit int) ([]int64, error)
- func (s *PostgresIndexStateStore) MarkDeleted(ctx context.Context, providerID string, topicID int64) error
- func (s *PostgresIndexStateStore) MarkIndexed(ctx context.Context, providerID string, topicID int64, ...) error
- type PostgresReindexStore
- func (s *PostgresReindexStore) CountPendingIndexJobs(ctx context.Context) (int64, error)
- func (s *PostgresReindexStore) CreateRun(ctx context.Context, total int64, startedByUserID int64) (ReindexRun, error)
- func (s *PostgresReindexStore) FinishRun(ctx context.Context, id int64, status string, runErr string) error
- func (s *PostgresReindexStore) GetCurrentRun(ctx context.Context) (ReindexRun, error)
- func (s *PostgresReindexStore) GetRun(ctx context.Context, id int64) (ReindexRun, error)
- func (s *PostgresReindexStore) ListRuns(ctx context.Context, limit int) ([]ReindexRun, error)
- type PostgresSiteEngine
- func (e *PostgresSiteEngine) Delete(ctx context.Context, topicID int64) error
- func (e *PostgresSiteEngine) EnsureIndex(ctx context.Context) error
- func (e *PostgresSiteEngine) Index(ctx context.Context, doc TopicSearchDoc) error
- func (e *PostgresSiteEngine) Probe(ctx context.Context) error
- func (e *PostgresSiteEngine) Search(ctx context.Context, input SearchInput) (SearchResult, error)
- func (e *PostgresSiteEngine) SyncAuthorDisplayName(ctx context.Context, userID int64, displayName string) error
- type ProviderIDResolver
- type ReconcileResult
- type Reconciler
- func (r *Reconciler) Reconcile(ctx context.Context) error
- func (r *Reconciler) ReconcileOnce(ctx context.Context) (ReconcileResult, error)
- func (r *Reconciler) WithBatchSize(batchSize int) *Reconciler
- func (r *Reconciler) WithDispatcher(dispatcher *supportjobs.Dispatcher) *Reconciler
- func (r *Reconciler) WithLogger(logger *slog.Logger) *Reconciler
- type ReindexManager
- type ReindexRun
- type ReindexStatusOutput
- type ReindexStore
- type SearchInput
- type SearchResult
- type Service
- type TopicIDSource
- type TopicPageSizeResolver
- type TopicReader
- type TopicSearchDoc
- type UnavailableEngine
- func (UnavailableEngine) Delete(context.Context, int64) error
- func (UnavailableEngine) EnsureIndex(context.Context) error
- func (UnavailableEngine) Index(context.Context, TopicSearchDoc) error
- func (UnavailableEngine) Probe(context.Context) error
- func (UnavailableEngine) Search(context.Context, SearchInput) (SearchResult, error)
Constants ¶
const ( ReindexStatusRunning = "running" ReindexStatusCompleted = "completed" ReindexStatusFailed = "failed" )
Reindex 状态常量。
const DefaultSiteSearchExtensionID = "sforum.search-site"
DefaultSiteSearchExtensionID 是受保护内置站内搜索扩展 id。 不可卸载;RestoreDefault 与无显式 pin 时解析到此 id。
const IndexUID = "sforum_topics"
IndexUID 是宿主约定的主题索引标识;外部引擎插件应使用同一 UID 或映射到等价索引。
const ProviderSlot = "search.provider"
ProviderSlot 是全文搜索引擎的宿主槽位。 Host 拥有文档 schema、ACL、入队与公开搜索 API;插件实现引擎传输。 默认受保护内置站内搜索(sforum.search-site / PostgresSiteEngine)。
const (
// RecommendedReconcileBatchSize 限制单轮修复量,避免大站点补漏挤占正常搜索任务。
RecommendedReconcileBatchSize = 500
)
Variables ¶
ErrEngineUnavailable 表示未配置/未启用搜索引擎提供方(外部引擎故障等)。 站内默认引擎正常时不应出现。
var ErrNoReindexRun = errors.New("search: no reindex run")
ErrNoReindexRun 表示尚无重建记录。
var ErrReindexAlreadyRunning = errors.New("search: reindex already running")
ErrReindexAlreadyRunning 表示已有重建正在进行,拒绝并发触发。 保证进度统计精确,并避免同一主题在两个全量 run 中重复调度。
var PublicSearchStatuses = []string{"active", "locked"}
PublicSearchStatuses 是公开搜索允许的主题状态(与 forum 公开列表一致)。
Functions ¶
func IsPublicSearchStatus ¶
IsPublicSearchStatus 判断状态是否可出现在公开搜索结果中。
Types ¶
type Engine ¶
type Engine interface {
// Probe 探测引擎是否可达(可选;用于 readiness / 管理端测试)。
Probe(ctx context.Context) error
// EnsureIndex 幂等创建索引并应用 schema 约定的 settings。
EnsureIndex(ctx context.Context) error
// Index 写入或更新一篇主题搜索文档。
Index(ctx context.Context, doc TopicSearchDoc) error
// Delete 按主题 id 删除索引文档。
Delete(ctx context.Context, topicID int64) error
// Search 执行关键词检索。
Search(ctx context.Context, input SearchInput) (SearchResult, error)
}
Engine 是引擎无关的全文搜索传输接口。 站内引擎由 Host 进程内实现;外部引擎(Meilisearch 等)由插件 ProviderCall 适配。
type EngineGate ¶
EngineGate 可选:在入队前用轻量检查(如 DB 选择)判断是否应调度索引 job。 未实现时回退到类型断言 UnavailableEngine。
type IndexStateStore ¶
type IndexStateStore interface {
MarkIndexed(ctx context.Context, providerID string, topicID int64, sourceUpdatedAt time.Time) error
MarkDeleted(ctx context.Context, providerID string, topicID int64) error
ListStaleTopicIDs(ctx context.Context, providerID string, limit int) ([]int64, error)
ListObsoleteTopicIDs(ctx context.Context, providerID string, limit int) ([]int64, error)
}
IndexStateStore 是 Host 自有的搜索同步账本。 provider 只负责传输,Core 以本账本判断缺失、过期和应删除文档。
type Indexer ¶
type Indexer struct {
// contains filtered or unexported fields
}
Indexer 协调 forum 写流程、River worker 与搜索引擎三者:
- EnqueueIndex/EnqueueDelete:forum.Service 在主题写流程调用,经 dispatcher 异步入队 IndexTopicArgs/DeleteTopicArgs(事务外,失败只记日志)。
- IndexTopic/DeleteTopic:River worker 实际执行,读写 Engine。
无可用引擎时入队 no-op,避免堆积无用 job;已经入队的 worker 任务必须返回引擎错误, 交给 River 重试,不能把一次临时不可用误记为 completed。
func NewIndexer ¶
func NewIndexer(engine Engine, reader TopicReader, dispatcher *supportjobs.Dispatcher) *Indexer
func (*Indexer) DeleteTopic ¶
DeleteTopic 从引擎删除主题文档。
func (*Indexer) EnqueueDelete ¶
EnqueueDelete 调度从索引移除指定主题(异步)。无引擎时直接返回 nil。
func (*Indexer) EnqueueIndex ¶
EnqueueIndex 调度重新索引指定主题(异步)。无引擎时直接返回 nil。
func (*Indexer) EnsureIndex ¶
EnsureIndex 委托引擎幂等建索引。
func (*Indexer) IndexTopic ¶
IndexTopic 从 forum 读取主题详情并 upsert 到引擎。
func (*Indexer) WithIndexStateStore ¶
func (i *Indexer) WithIndexStateStore(state IndexStateStore) *Indexer
WithIndexStateStore 在引擎操作成功后提交 Host 同步账本。 账本失败会让 River 重试整个幂等操作,不能把未确认状态误记为完成。
type LiveTopicSource ¶
type LiveTopicSource interface {
// ListPublicByIDs 仅返回仍存在且可公开列表的主题(active/locked + 公开分类)。
// 返回 map 的 key 为 topic id;缺失 id 表示应丢弃。
ListPublicByIDs(ctx context.Context, ids []int64) (map[int64]TopicSearchDoc, error)
}
LiveTopicSource 用权威 topics 表校验引擎命中。 引擎(Meili / 站内 FTS)是可重建派生数据;删库重 seed、异步 delete 失败都会留下幽灵文档。 Search 在返回前用此接口剔除不存在或不可公开的主题,并替换为实时摘要字段。
type MemorySiteEngine ¶
type MemorySiteEngine struct {
// contains filtered or unexported fields
}
MemorySiteEngine 是纯内存站内引擎,供单元测试暴力覆盖 index/search/delete/ACL。
func NewMemorySiteEngine ¶
func NewMemorySiteEngine() *MemorySiteEngine
func (*MemorySiteEngine) Delete ¶
func (e *MemorySiteEngine) Delete(_ context.Context, topicID int64) error
func (*MemorySiteEngine) EnsureIndex ¶
func (e *MemorySiteEngine) EnsureIndex(context.Context) error
func (*MemorySiteEngine) Index ¶
func (e *MemorySiteEngine) Index(_ context.Context, doc TopicSearchDoc) error
func (*MemorySiteEngine) Search ¶
func (e *MemorySiteEngine) Search(_ context.Context, input SearchInput) (SearchResult, error)
type PostgresIndexStateStore ¶
type PostgresIndexStateStore struct {
// contains filtered or unexported fields
}
func NewPostgresIndexStateStore ¶
func NewPostgresIndexStateStore(pool *pgxpool.Pool) *PostgresIndexStateStore
func (*PostgresIndexStateStore) ListObsoleteTopicIDs ¶
func (*PostgresIndexStateStore) ListStaleTopicIDs ¶
func (*PostgresIndexStateStore) MarkDeleted ¶
func (*PostgresIndexStateStore) MarkIndexed ¶
type PostgresReindexStore ¶
type PostgresReindexStore struct {
// contains filtered or unexported fields
}
PostgresReindexStore 基于 pgxpool 的实现。
func NewPostgresReindexStore ¶
func NewPostgresReindexStore(pool *pgxpool.Pool) *PostgresReindexStore
func (*PostgresReindexStore) CountPendingIndexJobs ¶
func (s *PostgresReindexStore) CountPendingIndexJobs(ctx context.Context) (int64, error)
CountPendingIndexJobs 统计 river_job 中 search.index_topic 的未完成 job 数。 未完成 = state 属于 available/pending/retryable/running/scheduled(即尚未成功完成或取消/丢弃)。 River 默认会清理 completed job,所以剩余数随 worker 消费递减,进度据此推进。
func (*PostgresReindexStore) CreateRun ¶
func (s *PostgresReindexStore) CreateRun(ctx context.Context, total int64, startedByUserID int64) (ReindexRun, error)
func (*PostgresReindexStore) GetCurrentRun ¶
func (s *PostgresReindexStore) GetCurrentRun(ctx context.Context) (ReindexRun, error)
func (*PostgresReindexStore) GetRun ¶
func (s *PostgresReindexStore) GetRun(ctx context.Context, id int64) (ReindexRun, error)
func (*PostgresReindexStore) ListRuns ¶
func (s *PostgresReindexStore) ListRuns(ctx context.Context, limit int) ([]ReindexRun, error)
type PostgresSiteEngine ¶
type PostgresSiteEngine struct {
// contains filtered or unexported fields
}
PostgresSiteEngine 是默认站内搜索引擎:PostgreSQL search_documents + tsvector。 由 Host 进程内实现;对应 builtin 扩展 sforum.search-site 的 short-circuit。
func NewPostgresSiteEngine ¶
func NewPostgresSiteEngine(pool *pgxpool.Pool) *PostgresSiteEngine
NewPostgresSiteEngine 构造站内引擎。pool 不可为 nil。
func (*PostgresSiteEngine) Delete ¶
func (e *PostgresSiteEngine) Delete(ctx context.Context, topicID int64) error
func (*PostgresSiteEngine) EnsureIndex ¶
func (e *PostgresSiteEngine) EnsureIndex(ctx context.Context) error
func (*PostgresSiteEngine) Index ¶
func (e *PostgresSiteEngine) Index(ctx context.Context, doc TopicSearchDoc) error
func (*PostgresSiteEngine) Search ¶
func (e *PostgresSiteEngine) Search(ctx context.Context, input SearchInput) (SearchResult, error)
func (*PostgresSiteEngine) SyncAuthorDisplayName ¶
func (e *PostgresSiteEngine) SyncAuthorDisplayName(ctx context.Context, userID int64, displayName string) error
SyncAuthorDisplayName 回写某位作者在站内搜索文档里的展示名。
search_documents 是派生索引:昵称改名后不需要重建主题正文,但作者昵称与 metadata_tsv 都必须跟着变,否则旧帖会永远搜到旧名字。metadata_tsv 是普通列 (不是生成列),所以这里必须按与迁移回填完全相同的表达式重算。
type ProviderIDResolver ¶
ProviderIDResolver 返回当前选中的搜索 provider。 ResolvingSearchEngine 实现该接口;普通 Engine 视为默认站内搜索。
type ReconcileResult ¶
type Reconciler ¶
type Reconciler struct {
// contains filtered or unexported fields
}
Reconciler 只调度差异任务;实际传输仍由 IndexTopic/DeleteTopic worker 完成。
func NewReconciler ¶
func NewReconciler(providers ProviderIDResolver, store IndexStateStore, dispatcher *supportjobs.Dispatcher) *Reconciler
func (*Reconciler) ReconcileOnce ¶
func (r *Reconciler) ReconcileOnce(ctx context.Context) (ReconcileResult, error)
func (*Reconciler) WithBatchSize ¶
func (r *Reconciler) WithBatchSize(batchSize int) *Reconciler
func (*Reconciler) WithDispatcher ¶
func (r *Reconciler) WithDispatcher(dispatcher *supportjobs.Dispatcher) *Reconciler
func (*Reconciler) WithLogger ¶
func (r *Reconciler) WithLogger(logger *slog.Logger) *Reconciler
type ReindexManager ¶
type ReindexManager struct {
// contains filtered or unexported fields
}
ReindexManager 协调搜索索引批量重建:
- Reindex:扫描全部 topic ID → 创建 run → 分批 EnqueueMany。
- ReindexStatus:读当前 run + 实时统计剩余 job 数算进度。
- ListReindexRuns:历史 run。
它不直接执行索引(IndexTopicWorker 负责),只负责"入队 + 进度追踪"。
func NewReindexManager ¶
func NewReindexManager(topics TopicIDSource, store ReindexStore, dispatcher *supportjobs.Dispatcher) *ReindexManager
func (*ReindexManager) ListReindexRuns ¶
func (m *ReindexManager) ListReindexRuns(ctx context.Context) ([]ReindexRun, error)
ListReindexRuns 返回最近的历史 run(默认 20 条)。
func (*ReindexManager) Reindex ¶
func (m *ReindexManager) Reindex(ctx context.Context, startedByUserID int64) (ReindexRun, error)
Reindex 触发一次全量重建。若已有 running run 则拒绝。
func (*ReindexManager) ReindexStatus ¶
func (m *ReindexManager) ReindexStatus(ctx context.Context) (ReindexStatusOutput, error)
ReindexStatus 返回当前 run 的实时进度。 processed/remaining/percent 由查询 river_job 剩余数实时计算。
type ReindexRun ¶
type ReindexRun struct {
ID int64 `json:"id"`
Total int64 `json:"total"`
Status string `json:"status"`
StartedAt time.Time `json:"startedAt"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
StartedByUserID int64 `json:"startedByUserId,omitempty"`
Error string `json:"error,omitempty"`
}
ReindexRun 是一次重建运行的记录。
type ReindexStatusOutput ¶
type ReindexStatusOutput struct {
ReindexRun
Processed int64 `json:"processed"`
Remaining int64 `json:"remaining"`
Percent int `json:"percent"` // 0-100
}
ReindexStatus 是 GET 进度端点的响应,含实时计算的已处理数与百分比。
type ReindexStore ¶
type ReindexStore interface {
// CreateRun 创建一条 running 记录并返回。
CreateRun(ctx context.Context, total int64, startedByUserID int64) (ReindexRun, error)
// GetCurrentRun 返回最近一条 run(无论状态),无记录时返回 ErrNoReindexRun。
GetCurrentRun(ctx context.Context) (ReindexRun, error)
// GetRun 按 ID 返回。
GetRun(ctx context.Context, id int64) (ReindexRun, error)
// ListRuns 返回最近 limit 条 run(按 started_at DESC)。
ListRuns(ctx context.Context, limit int) ([]ReindexRun, error)
// FinishRun 将 run 标记为完成或失败,并记录 finished_at 与可选 error。
FinishRun(ctx context.Context, id int64, status string, runErr string) error
// CountPendingIndexJobs 实时统计 river_job 中 search.index_topic 的剩余(未完成)job 数。
// 这是进度计算的数据源,避免在 worker 里耦合 reindex 回调。
CountPendingIndexJobs(ctx context.Context) (int64, error)
}
ReindexStore 抽象重建运行的持久化。
type SearchInput ¶
SearchInput 是搜索请求的归一化输入。
type SearchResult ¶
type SearchResult struct {
Items []TopicSearchDoc `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PerPage int `json:"perPage"`
}
SearchResult 是搜索响应,结构与 forum.TopicList 对齐便于前端复用。
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service 提供面向公众的主题搜索查询。 关键词检索委托选中的 Engine;可选 LiveTopicSource 用权威 topics 表剔除幽灵命中。
func NewService ¶
func NewService(engine Engine, pageSizes TopicPageSizeResolver) *Service
func (*Service) Search ¶
func (s *Service) Search(ctx context.Context, input SearchInput) (SearchResult, error)
Search 执行关键词检索,支持 categorySlug/tagSlug/status 过滤。 仅返回 active/locked 状态的公开主题(与 forum 公开列表一致;过滤由引擎侧应用)。 若注入 LiveTopicSource,会剔除引擎脏索引中的幽灵文档。为保证独立请求的 分页稳定性,绝不借用下一引擎页填充当前页;total 保持索引侧统计。
func (*Service) SearchWithLiveSource ¶
func (s *Service) SearchWithLiveSource(ctx context.Context, input SearchInput, live LiveTopicSource) (SearchResult, error)
SearchWithLiveSource 为单个调用指定权威主题源。HTTP 适配器使用请求私有 batch 复用 Forum 摘要,普通 Page ViewModel 仍通过 Search 使用服务默认源。
func (*Service) WithLiveSource ¶
func (s *Service) WithLiveSource(live LiveTopicSource) *Service
WithLiveSource 注入权威主题校验源。生产路径应始终注入,避免引擎脏索引返回 404 帖。
type TopicIDSource ¶
TopicIDSource 抽象 forum 包扫描全部可索引主题 ID 的能力,供 Reindex 批量入队。 由 forum.Store 实现并注入,避免 search 反向依赖 forum。
type TopicPageSizeResolver ¶
TopicPageSizeResolver supplies the operator-configured default without coupling Search to the Forum package.
type TopicReader ¶
type TopicReader interface {
// GetTopicForSearch 返回用于建索引的主题快照。注意:与 forum.GetTopicForAction
// 类似,不做公开可见性过滤——已删除/隐藏主题的索引删除由 EnqueueDelete 负责。
GetTopicForSearch(ctx context.Context, topicID int64) (TopicSearchDoc, error)
}
TopicReader 抽象 forum 包对主题详情的读取,供 Indexer 构造搜索文档。 由 forum.Service 或其 store 实现并注入,避免 search 反向依赖 forum。
type TopicSearchDoc ¶
type TopicSearchDoc struct {
ID int64 `json:"id"`
Title string `json:"title"`
Excerpt string `json:"excerpt"`
PlainText string `json:"plainText"` // 用于全文检索的纯文本正文
CategoryID int64 `json:"categoryId"`
CategorySlug string `json:"categorySlug"`
CategoryName string `json:"categoryName"`
AuthorUserID int64 `json:"authorUserId"`
AuthorUsername string `json:"authorUsername"`
AuthorDisplayName string `json:"authorDisplayName"`
Slug string `json:"slug"`
Status string `json:"status"`
IsPinned bool `json:"isPinned"`
CommentCount int64 `json:"commentCount"`
ViewCount int64 `json:"viewCount"`
TagSlugs []string `json:"tagSlugs"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
LastActivityAt time.Time `json:"lastActivityAt"`
}
TopicSearchDoc 是写入搜索引擎的主题文档结构。字段与 forum.TopicSummary 对齐, 但独立声明以解耦。tagSlugs 用数组供引擎侧过滤。
type UnavailableEngine ¶
type UnavailableEngine struct{}
UnavailableEngine 是显式不可用引擎:所有操作返回 ErrEngineUnavailable。 仅用于测试或刻意关闭搜索的装配;生产默认使用站内引擎。
func (UnavailableEngine) EnsureIndex ¶
func (UnavailableEngine) EnsureIndex(context.Context) error
func (UnavailableEngine) Index ¶
func (UnavailableEngine) Index(context.Context, TopicSearchDoc) error
func (UnavailableEngine) Search ¶
func (UnavailableEngine) Search(context.Context, SearchInput) (SearchResult, error)