fix(wiki): 重建链接逐页写失败不再静默,半成品不再回 200 (#3884)
RebuildLinks 的保存循环把每页 UpdateMeta 的失败降级成一条 Warn,函数最后 无条件 return nil,于是 handler 里既有的 err != nil 分支永远进不去:任意 一页写失败(行锁等待、死锁、连接中断、超时)时调用方仍拿到 200 "Links rebuilt successfully",而这些页面的 in_links/out_links 保持旧 值,反向链接与图谱继续显示过期关系,且没有任何途径知道"只重建了一部分"。 保持尽力而为的语义不变(一页失败不影响其余页面继续写入),但把失败页聚合 起来在结尾返回,沿用同仓库 knowledge_delete.go / wiki_ingest.go 的 errors.Join 写法,以及同文件 MovePage 对同一个 UpdateMeta 调用的报错写法。 handler 无需改动:其既有 500 分支会如实返回 "N of M pages failed" 与失败页 slug。 回归用例用 SQLite 触发器让指定页的 UPDATE 真的报错(不是 mock),走真实仓库 与真实 handler: - 部分失败:RebuildLinks 返回聚合错误,可写页仍被刷新,失败页保持旧值; - 全部失败:错误里含 3 of 3 与全部 slug; - HTTP 层:部分失败回 500 且错误体含失败页与底层原因,全部成功才回 200。 Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>main
parent
4d7e663128
commit
626185a120
|
|
@ -915,13 +915,23 @@ func (s *wikiPageService) RebuildLinks(ctx context.Context, kbID string) error {
|
|||
}
|
||||
}
|
||||
|
||||
// Save all pages (link rebuild is metadata-only, no version bump)
|
||||
// Save all pages (link rebuild is metadata-only, no version bump).
|
||||
// The rebuild stays best-effort — one unwritable page must not discard the
|
||||
// pages that can be written — but the failures are accumulated and
|
||||
// reported, so callers never see a successful rebuild for a half-written
|
||||
// link graph.
|
||||
var failures []error
|
||||
for _, p := range pages {
|
||||
p.UpdatedAt = time.Now()
|
||||
if err := s.repo.UpdateMeta(ctx, p); err != nil {
|
||||
logger.Warnf(ctx, "wiki: failed to update links for page %s: %v", p.Slug, err)
|
||||
failures = append(failures, fmt.Errorf("%s: %w", p.Slug, err))
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return fmt.Errorf("rebuild wiki links: %d of %d pages failed: %w",
|
||||
len(failures), len(pages), errors.Join(failures...))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,123 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const rebuildLinksTestKBID = "kb-rebuild-links"
|
||||
|
||||
// newRebuildLinksWiki seeds a three-page wiki in a real SQLite database:
|
||||
// concept/a -> concept/b -> concept/c. No page has links stored yet, so every
|
||||
// page must be written for the rebuild to be complete.
|
||||
func newRebuildLinksWiki(
|
||||
t *testing.T,
|
||||
) (context.Context, *gorm.DB, interfaces.WikiPageRepository, interfaces.WikiPageService) {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
|
||||
|
||||
ctx := context.Background()
|
||||
repo := repository.NewWikiPageRepository(db)
|
||||
svc := NewWikiPageService(repo, nil, nil, nil, nil, nil)
|
||||
|
||||
now := time.Now()
|
||||
for _, page := range []*types.WikiPage{
|
||||
{ID: "page-a", Slug: "concept/a", Title: "A", Content: "see [[concept/b]]"},
|
||||
{ID: "page-b", Slug: "concept/b", Title: "B", Content: "see [[concept/c]]"},
|
||||
{ID: "page-c", Slug: "concept/c", Title: "C", Content: "nothing to link"},
|
||||
} {
|
||||
page.TenantID = 1
|
||||
page.KnowledgeBaseID = rebuildLinksTestKBID
|
||||
page.PageType = types.WikiPageTypeConcept
|
||||
page.Status = types.WikiPageStatusPublished
|
||||
page.Version = 1
|
||||
page.CreatedAt = now
|
||||
page.UpdatedAt = now
|
||||
require.NoError(t, repo.Create(ctx, page))
|
||||
}
|
||||
|
||||
return ctx, db, repo, svc
|
||||
}
|
||||
|
||||
// failWikiMetaUpdatesWhen installs a SQLite trigger that makes every UPDATE on
|
||||
// wiki_pages fail while `when` holds. The failure is raised by the database
|
||||
// itself (RAISE(ABORT)), so it travels the real repository write path instead
|
||||
// of being simulated by a mock.
|
||||
func failWikiMetaUpdatesWhen(t *testing.T, db *gorm.DB, when string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Exec(fmt.Sprintf(`
|
||||
CREATE TRIGGER fail_wiki_meta_update
|
||||
BEFORE UPDATE ON wiki_pages
|
||||
WHEN %s
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'injected wiki metadata write failure');
|
||||
END`, when)).Error)
|
||||
}
|
||||
|
||||
func TestRebuildLinksSucceedsWhenEveryPageIsWritten(t *testing.T) {
|
||||
ctx, _, repo, svc := newRebuildLinksWiki(t)
|
||||
|
||||
require.NoError(t, svc.RebuildLinks(ctx, rebuildLinksTestKBID))
|
||||
|
||||
b, err := repo.GetBySlug(ctx, rebuildLinksTestKBID, "concept/b")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"concept/a"}, []string(b.InLinks))
|
||||
|
||||
c, err := repo.GetBySlug(ctx, rebuildLinksTestKBID, "concept/c")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"concept/b"}, []string(c.InLinks))
|
||||
}
|
||||
|
||||
func TestRebuildLinksReportsPartialWriteFailure(t *testing.T) {
|
||||
ctx, db, repo, svc := newRebuildLinksWiki(t)
|
||||
// concept/b can no longer be written; the other two pages still can.
|
||||
failWikiMetaUpdatesWhen(t, db, "OLD.slug = 'concept/b'")
|
||||
|
||||
err := svc.RebuildLinks(ctx, rebuildLinksTestKBID)
|
||||
|
||||
require.Error(t, err, "one unwritable page must not surface as a successful rebuild")
|
||||
require.Contains(t, err.Error(), "1 of 3")
|
||||
require.Contains(t, err.Error(), "concept/b")
|
||||
require.Contains(t, err.Error(), "injected wiki metadata write failure")
|
||||
|
||||
// Rebuild stays best-effort: the writable pages were still refreshed.
|
||||
a, getErr := repo.GetBySlug(ctx, rebuildLinksTestKBID, "concept/a")
|
||||
require.NoError(t, getErr)
|
||||
require.Equal(t, []string{"concept/b"}, []string(a.OutLinks))
|
||||
|
||||
// concept/b keeps the stale links — the exact half-rebuilt state the
|
||||
// caller has to be told about.
|
||||
b, getErr := repo.GetBySlug(ctx, rebuildLinksTestKBID, "concept/b")
|
||||
require.NoError(t, getErr)
|
||||
require.Empty(t, b.InLinks)
|
||||
}
|
||||
|
||||
func TestRebuildLinksReportsTotalWriteFailure(t *testing.T) {
|
||||
ctx, db, repo, svc := newRebuildLinksWiki(t)
|
||||
failWikiMetaUpdatesWhen(t, db, "1 = 1")
|
||||
|
||||
err := svc.RebuildLinks(ctx, rebuildLinksTestKBID)
|
||||
|
||||
require.Error(t, err, "a rebuild that wrote nothing must not report success")
|
||||
require.Contains(t, err.Error(), "3 of 3")
|
||||
for _, slug := range []string{"concept/a", "concept/b", "concept/c"} {
|
||||
require.Contains(t, err.Error(), slug)
|
||||
}
|
||||
require.Contains(t, err.Error(), "injected wiki metadata write failure")
|
||||
|
||||
c, getErr := repo.GetBySlug(ctx, rebuildLinksTestKBID, "concept/c")
|
||||
require.NoError(t, getErr)
|
||||
require.Empty(t, c.InLinks, "no page may be reported as rebuilt when the write failed")
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// newRebuildLinksHandler wires the real wiki page service over a real SQLite
|
||||
// repository into the HTTP handler, so the response contract is asserted
|
||||
// end-to-end instead of through a stubbed service.
|
||||
func newRebuildLinksHandler(t *testing.T) (*gin.Engine, *gorm.DB, interfaces.WikiPageRepository) {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
|
||||
|
||||
ctx := context.Background()
|
||||
repo := repository.NewWikiPageRepository(db)
|
||||
now := time.Now()
|
||||
for _, page := range []*types.WikiPage{
|
||||
{ID: "page-a", Slug: "concept/a", Title: "A", Content: "see [[concept/b]]"},
|
||||
{ID: "page-b", Slug: "concept/b", Title: "B", Content: "nothing to link"},
|
||||
} {
|
||||
page.TenantID = 1
|
||||
page.KnowledgeBaseID = "kb-rebuild-links"
|
||||
page.PageType = types.WikiPageTypeConcept
|
||||
page.Status = types.WikiPageStatusPublished
|
||||
page.Version = 1
|
||||
page.CreatedAt = now
|
||||
page.UpdatedAt = now
|
||||
require.NoError(t, repo.Create(ctx, page))
|
||||
}
|
||||
|
||||
handler := &WikiPageHandler{
|
||||
wikiService: service.NewWikiPageService(repo, nil, nil, nil, nil, nil),
|
||||
kbService: &stubKBService{get: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
return &types.KnowledgeBase{
|
||||
ID: id,
|
||||
TenantID: 1,
|
||||
IndexingStrategy: types.IndexingStrategy{WikiEnabled: true},
|
||||
}, nil
|
||||
}},
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.POST("/knowledgebase/:kb_id/wiki/rebuild-links", func(c *gin.Context) {
|
||||
c.Set(types.TenantIDContextKey.String(), uint64(1))
|
||||
handler.RebuildLinks(c)
|
||||
})
|
||||
return engine, db, repo
|
||||
}
|
||||
|
||||
func postRebuildLinks(engine *gin.Engine) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/knowledgebase/kb-rebuild-links/wiki/rebuild-links", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func TestRebuildLinksHandlerReportsPartialWriteFailure(t *testing.T) {
|
||||
engine, db, _ := newRebuildLinksHandler(t)
|
||||
require.NoError(t, db.Exec(`
|
||||
CREATE TRIGGER fail_wiki_meta_update
|
||||
BEFORE UPDATE ON wiki_pages
|
||||
WHEN OLD.slug = 'concept/b'
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'injected wiki metadata write failure');
|
||||
END`).Error)
|
||||
|
||||
recorder := postRebuildLinks(engine)
|
||||
t.Logf("rebuild-links response: %d %s", recorder.Code, recorder.Body.String())
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, recorder.Code,
|
||||
"a half-rebuilt link graph must not answer 200")
|
||||
require.NotContains(t, recorder.Body.String(), "Links rebuilt successfully")
|
||||
require.Contains(t, recorder.Body.String(), "concept/b")
|
||||
require.Contains(t, recorder.Body.String(), "injected wiki metadata write failure")
|
||||
}
|
||||
|
||||
func TestRebuildLinksHandlerReportsSuccessWhenEveryPageIsWritten(t *testing.T) {
|
||||
engine, _, _ := newRebuildLinksHandler(t)
|
||||
|
||||
recorder := postRebuildLinks(engine)
|
||||
t.Logf("rebuild-links response: %d %s", recorder.Code, recorder.Body.String())
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Contains(t, recorder.Body.String(), "Links rebuilt successfully")
|
||||
}
|
||||
|
|
@ -88,6 +88,8 @@ type WikiPageService interface {
|
|||
GetStats(ctx context.Context, kbID string) (*types.WikiStats, error)
|
||||
|
||||
// RebuildLinks re-parses all pages and rebuilds bidirectional link references.
|
||||
// It is best-effort: pages that could not be written are skipped, and any
|
||||
// such failure is returned as a joined error counting the failed pages.
|
||||
RebuildLinks(ctx context.Context, kbID string) error
|
||||
|
||||
// InjectCrossLinks scans specified pages and injects [[wiki-links]] for mentions
|
||||
|
|
|
|||
Loading…
Reference in New Issue