docs: annotate Foundry source and deployment lifecycle in Chinese [skip ci]
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
// 研究列表的无状态游标:保存排序锚点和查询摘要,不承担身份认证或签名校验。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -14,6 +15,8 @@ import (
|
||||
|
||||
// Cursors locate a public corpus row, not an account or authentication token.
|
||||
// Binding to normalized filters prevents accidentally paging a different query.
|
||||
// position 的 ID 用于最近排序;标题排序还需要保留数据库原始 title_key 以稳定处理同名论文。
|
||||
// Before 指示向前翻页,Filter 将游标限定在同一筛选条件和页大小内。
|
||||
type position struct {
|
||||
Version int `json:"v"`
|
||||
ID int64 `json:"id"`
|
||||
@@ -24,6 +27,7 @@ type position struct {
|
||||
|
||||
var errCursor = errors.New("invalid cursor")
|
||||
|
||||
// filterKey 在游标生成与读取两端统一缺省值,把查询条件编码为固定长度摘要。
|
||||
func filterKey(f Filters) string {
|
||||
sort, search := f.Sort, f.SearchIn
|
||||
if sort == "" {
|
||||
@@ -36,6 +40,8 @@ func filterKey(f Filters) string {
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:16])
|
||||
}
|
||||
|
||||
// encodeCursor 复制锚点并写协议版本、翻页方向;非标题排序删除无用 Key,缩小 URL。
|
||||
func encodeCursor(f Filters, p position, before bool) string {
|
||||
p.Version, p.Before, p.Filter = 1, before, filterKey(f)
|
||||
if f.Sort != "title" {
|
||||
@@ -44,6 +50,8 @@ func encodeCursor(f Filters, p position, before bool) string {
|
||||
data, _ := json.Marshal(p)
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
// decodeCursor 将空值视为首页;拒绝过长、额外字段、多 JSON 值或与当前筛选不符的游标。
|
||||
func decodeCursor(f Filters) (position, error) {
|
||||
var p position
|
||||
if f.Cursor == "" {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// 本文件记录研究 API 的回归契约;测试注释描述实际断言,不代表本次已运行测试。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -7,6 +8,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCursorValidation 验证最大 int64 ID、含控制字符的标题键和反向游标可往返;同时拒绝非法编码、版本及跨筛选复用。
|
||||
func TestCursorValidation(t *testing.T) {
|
||||
f := Filters{Query: "graph", Sort: "title", SearchIn: "text", PageSize: 8}
|
||||
f.Cursor = encodeCursor(f, position{ID: 9223372036854775807, Key: "duplicate\x01title"}, true)
|
||||
|
||||
@@ -16,12 +16,14 @@ import (
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Source 描述公开来源链接及其外部标识,不含内部数据库记录 ID。
|
||||
type Source struct {
|
||||
Label string `json:"label"`
|
||||
URL string `json:"url"`
|
||||
ExternalID string `json:"externalId"`
|
||||
}
|
||||
|
||||
// Publication 是一次投稿的出版信息与最新决策证据;同一论文可对应多个投稿。
|
||||
type Publication struct {
|
||||
Venue string `json:"venue"`
|
||||
Year int `json:"year"`
|
||||
@@ -30,6 +32,7 @@ type Publication struct {
|
||||
EvidenceURL string `json:"evidenceUrl,omitempty"`
|
||||
}
|
||||
|
||||
// Paper 是公开 API 的论文投影;可空字段保留源数据缺省语义,ID 用字符串避免前端整数精度丢失。
|
||||
type Paper struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
@@ -44,6 +47,7 @@ type Paper struct {
|
||||
Comments *string `json:"comments,omitempty"`
|
||||
}
|
||||
|
||||
// Filters 由 parseFilters 验证;Cursor 是相同查询下的排序锚点,不是页码或 OFFSET。
|
||||
type Filters struct {
|
||||
Query string
|
||||
SearchIn string
|
||||
@@ -53,6 +57,7 @@ type Filters struct {
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// Page 同时返回当前项、双向游标和语料主题列表;无后续页面的方向使用空字符串。
|
||||
type Page struct {
|
||||
Items []Paper `json:"items"`
|
||||
NextCursor string `json:"nextCursor"`
|
||||
@@ -63,11 +68,13 @@ type Page struct {
|
||||
|
||||
// Repository implementations must use a read-only transaction for each List,
|
||||
// so its metadata and page describe the same database snapshot.
|
||||
// Repository 将 HTTP 与存储解耦;List 的列表及元数据必须来自同一只读快照。
|
||||
type Repository interface {
|
||||
List(context.Context, Filters) (Page, error)
|
||||
Get(context.Context, int64) (Paper, error)
|
||||
}
|
||||
|
||||
// service 共享公开仓库和项目白名单,以 slots 对整个研究 API 限制并发数据库请求。
|
||||
type service struct {
|
||||
repository Repository
|
||||
projects map[string]string
|
||||
@@ -77,6 +84,7 @@ type service struct {
|
||||
|
||||
// Register adds only GET endpoints; no credentials or database errors are sent
|
||||
// to anonymous callers. A nil repository leaves the existing server unchanged.
|
||||
// Register 由 main 调用;没有研究库配置时不挂载路径,项目认证数据不参与公开语料查询。
|
||||
func Register(mux *http.ServeMux, repository Repository, projects map[string]string) {
|
||||
if repository == nil {
|
||||
return
|
||||
@@ -86,6 +94,7 @@ func Register(mux *http.ServeMux, repository Repository, projects map[string]str
|
||||
mux.HandleFunc("GET /projects/{project}/research/papers/{id}", s.serve)
|
||||
}
|
||||
|
||||
// reply 统一公开 JSON 的缓存和内容嗅探策略,写出后不再向调用方返回编码错误。
|
||||
func reply(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
@@ -94,13 +103,16 @@ func reply(w http.ResponseWriter, status int, value any) {
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
// reject 仅公开稳定错误码,数据库结构和底层错误内容不进入响应。
|
||||
func reject(w http.ResponseWriter, status int, code string) {
|
||||
reply(w, status, map[string]string{"error": code})
|
||||
}
|
||||
|
||||
// 主题采用受限分类标识,正整数不接受符号或前导零,简化 ID 和页大小的解析。
|
||||
var topicPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9.-]{0,79}$`)
|
||||
var positiveInteger = regexp.MustCompile(`^[1-9][0-9]*$`)
|
||||
|
||||
// parseFilters 严格拒绝重复/未知参数;限制查询字数、词数和页大小后,再验证游标绑定。
|
||||
func parseFilters(raw string) (Filters, error) {
|
||||
f := Filters{SearchIn: "text", Sort: "recent", PageSize: 8}
|
||||
values, err := url.ParseQuery(raw)
|
||||
@@ -152,6 +164,7 @@ func parseFilters(raw string) (Filters, error) {
|
||||
return f, err
|
||||
}
|
||||
|
||||
// serve 在昂贵查询前验证项目与参数;详情不接受筛选参数,列表使用统一 Filters。
|
||||
func (s *service) serve(w http.ResponseWriter, r *http.Request) {
|
||||
if _, exists := s.projects[r.PathValue("project")]; !exists {
|
||||
reject(w, 404, "not_found")
|
||||
@@ -173,6 +186,7 @@ func (s *service) serve(w http.ResponseWriter, r *http.Request) {
|
||||
reject(w, 400, "invalid_request")
|
||||
return
|
||||
}
|
||||
// 无空闲槽位时立即返回 429,不排队积累匿名查询;defer 覆盖后续所有退出路径。
|
||||
select {
|
||||
case s.slots <- struct{}{}:
|
||||
defer func() { <-s.slots }()
|
||||
@@ -193,6 +207,7 @@ func (s *service) serve(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, 200, result)
|
||||
return
|
||||
}
|
||||
// SQLSTATE 57014 是数据库取消查询;与请求超时统一映射 504,其余依赖故障为 503。
|
||||
var state interface{ SQLState() string }
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// 本文件记录研究 API 的回归契约;测试注释描述实际断言,不代表本次已运行测试。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// fixtureRepository 捕获调用参数和次数,并可模拟依赖失败或等到 context 被取消。
|
||||
type fixtureRepository struct {
|
||||
filters Filters
|
||||
id int64
|
||||
@@ -21,6 +23,7 @@ type fixtureRepository struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
// List 只返回结构化空列表,wait 分支专门验证请求期限与槽位回收。
|
||||
func (f *fixtureRepository) List(ctx context.Context, filters Filters) (Page, error) {
|
||||
f.calls++
|
||||
f.filters = filters
|
||||
@@ -31,18 +34,21 @@ func (f *fixtureRepository) List(ctx context.Context, filters Filters) (Page, er
|
||||
return Page{Items: []Paper{}, Topics: []string{}, PageSize: filters.PageSize}, f.err
|
||||
}
|
||||
|
||||
// Get 保存请求 ID 并给出固定论文,不访问数据库。
|
||||
func (f *fixtureRepository) Get(ctx context.Context, id int64) (Paper, error) {
|
||||
f.calls++
|
||||
f.id = id
|
||||
return Paper{ID: "42", Title: "Original title", Authors: []string{}, Topics: []string{}, Sources: []Source{}}, f.err
|
||||
}
|
||||
|
||||
// request 使用内存 recorder 执行路由,不启动监听端口。
|
||||
func request(handler http.Handler, method, path string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, httptest.NewRequest(method, path, nil))
|
||||
return w
|
||||
}
|
||||
|
||||
// TestAnonymousReadRoutes 通过假仓库验证匿名列表/详情、参数传递、JSON 空值与响应头,并拒绝写方法及未知项目。
|
||||
func TestAnonymousReadRoutes(t *testing.T) {
|
||||
f := &fixtureRepository{}
|
||||
mux := http.NewServeMux()
|
||||
@@ -70,6 +76,7 @@ func TestAnonymousReadRoutes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestInvalidQueriesNeverReachRepository 逐项注入重复、未知、超限及非法 Unicode/ID 参数,要求 400 且仓库调用次数保持零。
|
||||
func TestInvalidQueriesNeverReachRepository(t *testing.T) {
|
||||
queries := []string{"unknown=1", "q=x&q=y", "q=%ff", "q=%00", "q=%zz", "page=0", "page=1001", "page=-1", "page=1.5", "page=01", "pageSize=51", "pageSize=0", "pageSize=9999999999999999999999", "searchIn=sql", "sort=published", "topic=arxiv:cs.LG", "q=" + url.QueryEscape(strings.Repeat("字", 201)), "q=" + url.QueryEscape(strings.Repeat("word ", 21))}
|
||||
for _, query := range queries {
|
||||
@@ -93,6 +100,7 @@ func TestInvalidQueriesNeverReachRepository(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestQueryDefaultsAndUnicode 验证多语言查询只裁剪两端空白,并采用文本搜索、最近排序和八条页大小。
|
||||
func TestQueryDefaultsAndUnicode(t *testing.T) {
|
||||
f, err := parseFilters("q=" + url.QueryEscape(" 论文 Graph "))
|
||||
if err != nil || f.Query != "论文 Graph" || f.PageSize != 8 || f.SearchIn != "text" || f.Sort != "recent" {
|
||||
@@ -100,11 +108,16 @@ func TestQueryDefaultsAndUnicode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// databaseFailure 让测试模拟驱动 SQLState,同时让 Error 带私密文本以验证脱敏。
|
||||
type databaseFailure string
|
||||
|
||||
func (failure databaseFailure) Error() string { return "private database error" }
|
||||
// Error 故意返回私密说明,供响应脱敏断言检查。
|
||||
func (failure databaseFailure) Error() string { return "private database error" }
|
||||
|
||||
// SQLState 模拟 PostgreSQL 驱动错误分类,不暴露其实际内部消息。
|
||||
func (failure databaseFailure) SQLState() string { return string(failure) }
|
||||
|
||||
// TestStorageErrorsAreRedacted 注入缺行、取消和权限错误,检查状态码映射,同时确保私密数据库内容不会进入响应。
|
||||
func TestStorageErrorsAreRedacted(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
@@ -126,6 +139,7 @@ func TestStorageErrorsAreRedacted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrencyAndTimeoutReleaseSlots 手动占满两个槽验证立即 429,再让假仓库等到超时,验证 504 后槽位被释放。
|
||||
func TestConcurrencyAndTimeoutReleaseSlots(t *testing.T) {
|
||||
s := &service{repository: &fixtureRepository{wait: true}, projects: map[string]string{"thesisly": "unused"}, slots: make(chan struct{}, 2), timeout: time.Millisecond}
|
||||
mux := http.NewServeMux()
|
||||
@@ -144,6 +158,7 @@ func TestConcurrencyAndTimeoutReleaseSlots(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestInvalidCursorsNeverReachRepository 验证坏编码、过长、筛选不符及重复游标在 HTTP 层拦截,不触发仓库查询。
|
||||
func TestInvalidCursorsNeverReachRepository(t *testing.T) {
|
||||
f := Filters{Query: "graph", Sort: "recent", SearchIn: "text", PageSize: 8}
|
||||
valid := encodeCursor(f, position{ID: 42}, false)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// PostgreSQL 研究库只读适配器:游标先选窄 ID 集合,再按同一事务快照批量补齐论文元数据。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
// The fixed Paper Atlas migration a3b677b preserves business columns as TEXT
|
||||
// and BIGINT and creates the English title/abstract GIN expression below.
|
||||
// No schema creation, indexing or other writes belong to this repository.
|
||||
// PostgresRepository 的 prefix 仅由已校验 schema 构造;encoded 在启动 Check 成功后确定。
|
||||
type PostgresRepository struct {
|
||||
db *sql.DB
|
||||
prefix string
|
||||
@@ -23,6 +25,7 @@ type PostgresRepository struct {
|
||||
|
||||
var schemaName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,35}$`)
|
||||
|
||||
// NewPostgresRepository 只构造仓库,不连接或迁移;调用方还需在对外服务前执行 Check。
|
||||
func NewPostgresRepository(db *sql.DB, schema string) (*PostgresRepository, error) {
|
||||
if db == nil || !schemaName.MatchString(schema) {
|
||||
return nil, errors.New("invalid research database configuration")
|
||||
@@ -30,10 +33,13 @@ func NewPostgresRepository(db *sql.DB, schema string) (*PostgresRepository, erro
|
||||
return &PostgresRepository{db: db, prefix: `"` + schema + `".`, schema: schema}, nil
|
||||
}
|
||||
|
||||
// query 只替换受信任的 schema 占位符;搜索词、ID 等业务值始终通过 SQL 参数绑定。
|
||||
func (r *PostgresRepository) query(value string) string {
|
||||
return strings.ReplaceAll(value, "{schema}", r.prefix)
|
||||
}
|
||||
|
||||
// begin 为一次 API 请求建立可重复读、只读事务,并设置事务内的查询时间及内存限制。
|
||||
// 设置失败先回滚;成功后由 List/Get/Check 的 defer 负责兜底回收事务。
|
||||
func (r *PostgresRepository) begin(ctx context.Context) (*sql.Tx, error) {
|
||||
tx, err := r.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
|
||||
if err != nil {
|
||||
@@ -51,6 +57,7 @@ func (r *PostgresRepository) begin(ctx context.Context) (*sql.Tx, error) {
|
||||
|
||||
// Check resolves required columns and SELECT permissions without scanning the
|
||||
// corpus. The migration publishes the complete schema atomically.
|
||||
// Check 读取 schema 注释识别文本转义协议,用 WHERE false 探测字段和权限而不扫描语料。
|
||||
func (r *PostgresRepository) Check(ctx context.Context) error {
|
||||
tx, err := r.begin(ctx)
|
||||
if err != nil {
|
||||
@@ -88,6 +95,7 @@ func (r *PostgresRepository) Check(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// whereClause 构造可组合筛选片段及对应参数;作者用 simple 全文检索,标题/摘要用 english。
|
||||
func whereClause(filters Filters) (string, []any) {
|
||||
clauses, values := []string{}, []any{}
|
||||
if filters.Query != "" {
|
||||
@@ -112,8 +120,10 @@ func whereClause(filters Filters) (string, []any) {
|
||||
return " WHERE " + strings.Join(clauses, " AND "), values
|
||||
}
|
||||
|
||||
// scanner 让单行 QueryRow 与多行 Rows 共用论文投影读取逻辑。
|
||||
type scanner interface{ Scan(...any) error }
|
||||
|
||||
// scanPaper 先解码数据库文本,再解析作者 JSON;空摘要和发布日期保留为 nil。
|
||||
func (r *PostgresRepository) scanPaper(row scanner) (Paper, error) {
|
||||
p := Paper{Authors: []string{}, Topics: []string{}, Sources: []Source{}}
|
||||
var id int64
|
||||
@@ -134,6 +144,7 @@ func (r *PostgresRepository) scanPaper(row scanner) (Paper, error) {
|
||||
return p, err
|
||||
}
|
||||
|
||||
// decodeAuthors 兼容直接姓名字符串与 arXiv 元组;交换姓/名展示顺序,忽略第四项所属机构。
|
||||
func decodeAuthors(raw string) ([]string, error) {
|
||||
var entries []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(raw), &entries); err != nil {
|
||||
@@ -173,6 +184,7 @@ func decodeAuthors(raw string) ([]string, error) {
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// positions 只读取 ID 和原始排序键;流式读取或关闭前的错误均交回上层终止本页。
|
||||
func (r *PostgresRepository) positions(ctx context.Context, tx *sql.Tx, query string, args []any) ([]position, error) {
|
||||
rows, err := tx.QueryContext(ctx, r.query(query), args...)
|
||||
if err != nil {
|
||||
@@ -191,12 +203,14 @@ func (r *PostgresRepository) positions(ctx context.Context, tx *sql.Tx, query st
|
||||
return positions, rows.Err()
|
||||
}
|
||||
|
||||
// List 在一个快照中完成锚点选择、详情补全和主题列表;多读一行判定是否还有下一页。
|
||||
func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, error) {
|
||||
result := Page{Items: []Paper{}, Topics: []string{}, PageSize: filters.PageSize}
|
||||
cursor, err := decodeCursor(filters)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
// 保留未转义筛选条件来生成游标摘要;仅实际 SQL 绑定值按已发布 schema 的 codec 转义。
|
||||
original := filters
|
||||
tx, err := r.begin(ctx)
|
||||
if err != nil {
|
||||
@@ -208,6 +222,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
filters.Topic = encodeText(filters.Topic)
|
||||
}
|
||||
where, args := whereClause(filters)
|
||||
// 最近排序按 ID 倒序,标题按 (title_key,id) 正序;向前翻页同时反转比较和 SQL 排序。
|
||||
if cursor.ID != 0 {
|
||||
clause := " AND "
|
||||
if where == "" {
|
||||
@@ -253,6 +268,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
}
|
||||
positions := []position{}
|
||||
topicOnly := filters.Sort != "title" && filters.Topic != "" && filters.Query == ""
|
||||
// 纯主题查询直接走标签关联索引,不必先读取所有匹配论文的宽行。
|
||||
if topicOnly {
|
||||
// The published paper_tags foreign key guarantees these IDs exist.
|
||||
// Walk the (tag_id,paper_id) index instead of joining all matching
|
||||
@@ -290,6 +306,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
// 常见搜索词先试 512/4096 的有限 ID 窗口;不足一页加一行时回退完整索引检索,避免漏项。
|
||||
for _, window := range []int64{512, 4096} {
|
||||
bound, op := int64(0), ">="
|
||||
if anchor > window {
|
||||
@@ -320,6 +337,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
// 截去探测行后恢复面向客户端的固定顺序,再按首尾锚点构造可用方向的游标。
|
||||
more := len(positions) > filters.PageSize
|
||||
if more {
|
||||
positions = positions[:filters.PageSize]
|
||||
@@ -336,6 +354,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
if (!cursor.Before && more) || (cursor.Before && cursor.ID != 0) {
|
||||
result.NextCursor = encodeCursor(original, positions[len(positions)-1], false)
|
||||
}
|
||||
// ANY 查询不保证输入顺序,先按 ID 收集再依照 positions 重新组装结果。
|
||||
ids := make([]int64, len(positions))
|
||||
byID := map[string]Paper{}
|
||||
for i, p := range positions {
|
||||
@@ -389,6 +408,7 @@ func (r *PostgresRepository) List(ctx context.Context, filters Filters) (Page, e
|
||||
return result, tx.Commit()
|
||||
}
|
||||
|
||||
// Get 与列表共享解码和 enrich,在同一事务内读取单篇论文及其附属信息。
|
||||
func (r *PostgresRepository) Get(ctx context.Context, id int64) (Paper, error) {
|
||||
tx, err := r.begin(ctx)
|
||||
if err != nil {
|
||||
@@ -408,11 +428,13 @@ func (r *PostgresRepository) Get(ctx context.Context, id int64) (Paper, error) {
|
||||
|
||||
// Batch metadata queries avoid per-paper round trips and share the page
|
||||
// snapshot. User values are bound; only the validated schema is interpolated.
|
||||
// enrich 批量原地填充 papers:主题、来源、DOI、投稿和决策,所有查询复用调用方事务。
|
||||
func (r *PostgresRepository) enrich(ctx context.Context, tx *sql.Tx, papers []Paper) error {
|
||||
if len(papers) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]int64, len(papers))
|
||||
// 指针指向切片元素,使多组关系查询的追加结果直接回写最终页面。
|
||||
byID := map[int64]*Paper{}
|
||||
for i := range papers {
|
||||
id, err := strconv.ParseInt(papers[i].ID, 10, 64)
|
||||
@@ -466,6 +488,7 @@ func (r *PostgresRepository) enrich(ctx context.Context, tx *sql.Tx, papers []Pa
|
||||
source.Label = "PMLR"
|
||||
}
|
||||
p.Sources = append(p.Sources, source)
|
||||
// 按来源记录顺序采用第一个非空元数据;坏 JSON 不阻止来源链接展示。
|
||||
var fields map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(metadata), &fields) == nil {
|
||||
for key, target := range map[string]**string{"doi": &p.DOI, "journal-ref": &p.Journal, "comments": &p.Comments} {
|
||||
@@ -501,6 +524,7 @@ func (r *PostgresRepository) enrich(ctx context.Context, tx *sql.Tx, papers []Pa
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 每条投稿通过 LATERAL 选择最新观察到的决策;没有决策时仍保留投稿并标为 unknown。
|
||||
rows, err = tx.QueryContext(ctx, r.query(`SELECT s.paper_id,v.acronym,e.year,e.track,coalesce(d.status,'unknown'),coalesce(d.evidence_url,'')
|
||||
FROM {schema}submissions s JOIN {schema}editions e ON e.id=s.edition_id JOIN {schema}venues v ON v.id=e.venue_id
|
||||
LEFT JOIN LATERAL (SELECT status,evidence_url FROM {schema}decisions WHERE submission_id=s.id
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// 真实 PostgreSQL 回归需要 RESEARCH_TEST_DATABASE_URL 指向预装语料 fixture 的可丢弃测试库。
|
||||
// 缺少该变量时跳过;测试包含写入拒绝检查,不能指向生产数据库。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -14,6 +16,7 @@ import (
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// integrationRepository 每个用例打开独立连接池并注册关闭及二十秒 context 清理,不创建 fixture schema。
|
||||
func integrationRepository(t *testing.T) (*PostgresRepository, context.Context) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("RESEARCH_TEST_DATABASE_URL")
|
||||
@@ -35,6 +38,7 @@ func integrationRepository(t *testing.T) (*PostgresRepository, context.Context)
|
||||
return repository, ctx
|
||||
}
|
||||
|
||||
// paperIDs 提取展示顺序,便于断言 SQL 查询和游标返回的 ID 序列。
|
||||
func paperIDs(papers []Paper) []string {
|
||||
ids := []string{}
|
||||
for _, paper := range papers {
|
||||
@@ -43,6 +47,7 @@ func paperIDs(papers []Paper) []string {
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestPostgresPageSearchAndFilters 使用已发布 fixture 验证 SQL 排序、全文与作者检索、主题交集和参数绑定,检查主题命名空间。
|
||||
func TestPostgresPageSearchAndFilters(t *testing.T) {
|
||||
r, ctx := integrationRepository(t)
|
||||
if err := r.Check(ctx); err != nil {
|
||||
@@ -77,6 +82,7 @@ func TestPostgresPageSearchAndFilters(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresMetadataPreservesEvidence 验证原文、作者、来源、DOI 优先级与最新决策证据,保留可空字段和缺失论文语义。
|
||||
func TestPostgresMetadataPreservesEvidence(t *testing.T) {
|
||||
r, ctx := integrationRepository(t)
|
||||
p, err := r.Get(ctx, 1)
|
||||
@@ -111,6 +117,7 @@ func TestPostgresMetadataPreservesEvidence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresCorpusIsReadOnlyAndHTTPWorks 检查事务隔离与资源选项;实际尝试写入须被数据库权限拒绝,再经 HTTP 验证真实 SQL 响应。
|
||||
func TestPostgresCorpusIsReadOnlyAndHTTPWorks(t *testing.T) {
|
||||
r, ctx := integrationRepository(t)
|
||||
tx, err := r.begin(ctx)
|
||||
@@ -153,6 +160,7 @@ func TestPostgresCorpusIsReadOnlyAndHTTPWorks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresPublishedTextCodec 通过编码 fixture 检查论文、作者、评论和 HTTP JSON 均还原控制字符,并可继续搜索。
|
||||
func TestPostgresPublishedTextCodec(t *testing.T) {
|
||||
legacy, ctx := integrationRepository(t)
|
||||
r, err := NewPostgresRepository(legacy.db, "research_encoded_fixture")
|
||||
@@ -182,6 +190,7 @@ func TestPostgresPublishedTextCodec(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresCursorsTraverseBothDirections 按每页一条遍历两种排序,每步反向读取前页,防止游标循环并拒绝换筛选复用。
|
||||
func TestPostgresCursorsTraverseBothDirections(t *testing.T) {
|
||||
r, ctx := integrationRepository(t)
|
||||
for _, sort := range []string{"recent", "title"} {
|
||||
@@ -231,6 +240,7 @@ func TestPostgresCursorsTraverseBothDirections(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresEncodedTitleCursors 在转义标题库中逐页遍历,验证游标保留数据库排序键,不因展示文本解码而改变顺序。
|
||||
func TestPostgresEncodedTitleCursors(t *testing.T) {
|
||||
legacy, ctx := integrationRepository(t)
|
||||
r, err := NewPostgresRepository(legacy.db, "research_encoded_fixture")
|
||||
@@ -264,6 +274,7 @@ func TestPostgresEncodedTitleCursors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresBoundedProbeDoesNotTruncateSparseMatches 用跨越探测窗口的稀疏 ID 和三种页大小验证检索回退不漏项,并检查反向跨空档分页。
|
||||
func TestPostgresBoundedProbeDoesNotTruncateSparseMatches(t *testing.T) {
|
||||
legacy, ctx := integrationRepository(t)
|
||||
r, err := NewPostgresRepository(legacy.db, "research_sparse_fixture")
|
||||
@@ -310,6 +321,7 @@ func TestPostgresBoundedProbeDoesNotTruncateSparseMatches(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPostgresTopicCursorSkipsDuplicateEvidence 验证多个来源产生的重复标签证据不会重复返回论文,且主题游标可双向跨页。
|
||||
func TestPostgresTopicCursorSkipsDuplicateEvidence(t *testing.T) {
|
||||
legacy, ctx := integrationRepository(t)
|
||||
r, err := NewPostgresRepository(legacy.db, "research_sparse_fixture")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// 本文件记录研究 API 的回归契约;测试注释描述实际断言,不代表本次已运行测试。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -8,6 +9,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestStoredAuthorShapes 覆盖姓名字符串及一到四项作者元组,验证姓名重排、机构忽略、空数组和坏结构拒绝。
|
||||
func TestStoredAuthorShapes(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
raw string
|
||||
@@ -35,6 +37,7 @@ func TestStoredAuthorShapes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestQueryValuesRemainBound 将攻击性文本当作普通搜索词,断言它只进入参数而不拼入 SQL,并检查全文/作者/主题分支。
|
||||
func TestQueryValuesRemainBound(t *testing.T) {
|
||||
query := `graph'); DROP TABLE papers; -- OR author:*`
|
||||
where, args := whereClause(Filters{Query: query, Topic: "cs.LG", SearchIn: "text"})
|
||||
@@ -58,6 +61,7 @@ func TestQueryValuesRemainBound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchemaCannotEscapeQualification 验证 schema 名白名单与 nil 连接拒绝,并检查所有占位符都被限定到同一 schema。
|
||||
func TestSchemaCannotEscapeQualification(t *testing.T) {
|
||||
for _, name := range []string{"", `research";DROP SCHEMA public;--`, "a.b", "Public", strings.Repeat("a", 37)} {
|
||||
if _, err := NewPostgresRepository(&sql.DB{}, name); err == nil {
|
||||
|
||||
+6
@@ -1,5 +1,6 @@
|
||||
-- Synthetic fixture for the disposable, network-isolated CI database only.
|
||||
-- Required columns/types follow Paper Atlas's fixed a3b677b migration.
|
||||
-- 基础语料覆盖同名标题、可空摘要/日期、多作者形状及原文特殊字符;仅用于可丢弃测试库。
|
||||
CREATE SCHEMA research_fixture;
|
||||
CREATE TABLE research_fixture.papers (
|
||||
id bigint PRIMARY KEY, title text NOT NULL, abstract text, title_key text COLLATE "C" NOT NULL,
|
||||
@@ -15,6 +16,7 @@ CREATE TABLE research_fixture.source_records (
|
||||
);
|
||||
CREATE TABLE research_fixture.identifiers (scheme text,value text,paper_id bigint REFERENCES research_fixture.papers(id),PRIMARY KEY(scheme,value));
|
||||
CREATE TABLE research_fixture.tags (id bigint PRIMARY KEY,namespace text,value text,UNIQUE(namespace,value));
|
||||
-- evidence_key 允许同论文同标签有多条来源证据,列表和主题分页需去重论文而不是重复返回。
|
||||
CREATE TABLE research_fixture.paper_tags (
|
||||
paper_id bigint REFERENCES research_fixture.papers(id),tag_id bigint REFERENCES research_fixture.tags(id),
|
||||
evidence_key text,PRIMARY KEY(paper_id,tag_id,evidence_key)
|
||||
@@ -47,18 +49,21 @@ INSERT INTO research_fixture.paper_tags VALUES(1,1,'first'),(1,1,'second'),(1,2,
|
||||
INSERT INTO research_fixture.venues VALUES(1,'ICLR'),(2,'ICML');
|
||||
INSERT INTO research_fixture.editions VALUES(7,1,2024,'main'),(8,2,2023,'main');
|
||||
INSERT INTO research_fixture.submissions VALUES(11,1,7),(12,3,8);
|
||||
-- 决策优先最新 observed_at,再 decision_date 与 id;旧观察即使声称未来决策日也不能压过新观察。
|
||||
INSERT INTO research_fixture.decisions VALUES
|
||||
(1,11,'accepted','https://example.test/decision/1','2024-02-01','2024-01-30'),
|
||||
(2,11,'rejected','https://example.test/decision/2','2024-02-01','2024-01-31'),
|
||||
(3,11,'withdrawn','https://example.test/decision/3','2024-02-01','2024-01-31'),
|
||||
(4,11,'accepted','https://example.test/decision/4','2024-01-01','2099-01-01');
|
||||
|
||||
-- 研究运行角色只获 schema USAGE 和表 SELECT,集成测试实际 UPDATE 必须被权限拒绝。
|
||||
CREATE ROLE foundry_research_fixture LOGIN;
|
||||
REVOKE ALL ON SCHEMA research_fixture FROM PUBLIC;
|
||||
GRANT USAGE ON SCHEMA research_fixture TO foundry_research_fixture;
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA research_fixture TO foundry_research_fixture;
|
||||
|
||||
-- Separate encoded schema mirrors the published Paper Atlas nul-soh-v1 format.
|
||||
-- 复制基础数据并加 codec 标记,用 SOH 转义在 PostgreSQL TEXT 中表达原始 NUL,API 需正确还原。
|
||||
CREATE SCHEMA research_encoded_fixture;
|
||||
COMMENT ON SCHEMA research_encoded_fixture IS 'paper-atlas:text-codec=nul-soh-v1';
|
||||
DO $$
|
||||
@@ -82,6 +87,7 @@ GRANT USAGE ON SCHEMA research_encoded_fixture TO foundry_research_fixture;
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA research_encoded_fixture TO foundry_research_fixture;
|
||||
|
||||
-- A large ID gap proves the bounded probe cannot truncate sparse results.
|
||||
-- 复制语料再加入跨 512/4096 探测窗口的 ID 空档,验证稀疏检索回退不漏匹配及反向分页。
|
||||
CREATE SCHEMA research_sparse_fixture;
|
||||
DO $$
|
||||
DECLARE item text;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// 研究库文本 codec 适配:数据库用 SOH 转义 NUL,API 返回前还原原始文本。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
// SOH -> SOH/STX. All other bytes retain their original binary ordering.
|
||||
const textCodec = "nul-soh-v1"
|
||||
|
||||
// encodedSchema 仅识别精确协议版本;无标注视为普通文本,未知版本阻止启动,避免错误解码。
|
||||
func encodedSchema(annotation sql.NullString) (bool, error) {
|
||||
const prefix = "paper-atlas:text-codec="
|
||||
if !annotation.Valid || !strings.HasPrefix(annotation.String, prefix) {
|
||||
@@ -21,10 +23,12 @@ func encodedSchema(annotation sql.NullString) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// encodeText 必须先转义 SOH 再转义 NUL,防止第二次替换改写刚生成的转义序列。
|
||||
func encodeText(value string) string {
|
||||
return strings.ReplaceAll(strings.ReplaceAll(value, "\x01", "\x01\x02"), "\x00", "\x01\x01")
|
||||
}
|
||||
|
||||
// decodeText 逐段复制普通字节,仅接受 SOH/SOH 与 SOH/STX;残缺或未知转义立即报错。
|
||||
func decodeText(value string) (string, error) {
|
||||
if !strings.ContainsRune(value, '\x01') {
|
||||
return value, nil
|
||||
@@ -52,11 +56,13 @@ func decodeText(value string) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// textColumn 实现 sql.Scanner,把可选 codec 与目标字段的 NULL 语义集中处理。
|
||||
type textColumn struct {
|
||||
encoded bool
|
||||
target any
|
||||
}
|
||||
|
||||
// Scan 先用 NullString 接收驱动值,再按 schema 解码;非空字符串目标不允许数据库 NULL。
|
||||
func (column textColumn) Scan(source any) error {
|
||||
var value sql.NullString
|
||||
if err := value.Scan(source); err != nil {
|
||||
@@ -83,6 +89,7 @@ func (column textColumn) Scan(source any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// text 在 scanPaper/enrich 中包装文本列,避免遗漏对来源元数据或主题的解码。
|
||||
func (r *PostgresRepository) text(target any) sql.Scanner {
|
||||
return textColumn{encoded: r.encoded, target: target}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// 本文件记录研究 API 的回归契约;测试注释描述实际断言,不代表本次已运行测试。
|
||||
package research
|
||||
|
||||
import (
|
||||
@@ -6,6 +7,7 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCorpusTextCodecRoundTripAndOrder 对控制字符和 Unicode 两两比较,验证转义既可逆又保留字节排序,并拒绝残缺转义。
|
||||
func TestCorpusTextCodecRoundTripAndOrder(t *testing.T) {
|
||||
values := []string{"", "\x00", "\x00\x01", "\x01", "\x01\x02", "\x02", "A", "A\x00", "A\x01", "Ada 张三 Ω", "Z\x00\x01\x02尾"}
|
||||
for _, value := range values {
|
||||
@@ -27,6 +29,7 @@ func TestCorpusTextCodecRoundTripAndOrder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCorpusTextColumnsRespectCodecAndNulls 验证普通库不解码、编码库还原控制字符,且可空列与必填列保持各自 NULL 约束。
|
||||
func TestCorpusTextColumnsRespectCodecAndNulls(t *testing.T) {
|
||||
var required string
|
||||
if err := (textColumn{target: &required}).Scan("\x01\x01"); err != nil || required != "\x01\x01" {
|
||||
@@ -50,6 +53,7 @@ func TestCorpusTextColumnsRespectCodecAndNulls(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCorpusSchemaCodecMarker 验证无标记沿用普通文本、已知标记开启 codec、未知版本明确失败。
|
||||
func TestCorpusSchemaCodecMarker(t *testing.T) {
|
||||
for _, annotation := range []sql.NullString{{}, {String: "unrelated schema description", Valid: true}} {
|
||||
encoded, err := encodedSchema(annotation)
|
||||
|
||||
Reference in New Issue
Block a user