chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,390 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 30 * time.Second
|
||||
defaultPageSize = 100
|
||||
userAgent = "Academy-Yuque-Connector/1.0"
|
||||
|
||||
// maxJSONResponseBytes bounds every API response body. Listings and document
|
||||
// payloads are small; a larger body means a broken or hostile server.
|
||||
maxJSONResponseBytes = 16 << 20
|
||||
|
||||
// maxPaginationHops bounds every offset-paginated walk in this file. The
|
||||
// only natural exit is a short page, which a gateway, CDN, or self-hosted
|
||||
// deployment that answers every offset with a full page never produces;
|
||||
// /users/{login}/repos carries no meta.total to stop on either. Without the
|
||||
// cap such a walk keeps calling the API until the sync task hits its
|
||||
// deadline, with `all` growing all the way. Mirrors the guard Notion,
|
||||
// Confluence, GitLab, and IMA already carry.
|
||||
maxPaginationHops = 10000
|
||||
)
|
||||
|
||||
// client wraps the Yuque Open API.
|
||||
type client struct {
|
||||
baseURL string
|
||||
token string
|
||||
httpClient *http.Client
|
||||
// jsonLimit caps each API response body; a field so tests can lower it
|
||||
// without materialising the production limit.
|
||||
jsonLimit int64
|
||||
|
||||
// logTokenOnce ensures the redacted token identity is logged at most once
|
||||
// per client lifetime (first real request), rather than on every call.
|
||||
logTokenOnce sync.Once
|
||||
}
|
||||
|
||||
// newClient constructs a client with a normalized base URL.
|
||||
func newClient(cfg *Config) *client {
|
||||
return &client{
|
||||
baseURL: cfg.GetBaseURL(),
|
||||
token: cfg.APIToken,
|
||||
httpClient: datasource.NewConnectorHTTPClient(defaultTimeout),
|
||||
jsonLimit: maxJSONResponseBytes,
|
||||
}
|
||||
}
|
||||
|
||||
// errResponseTooLarge marks a body over the cap. It is deterministic: the same
|
||||
// request returns the same oversized body, so callers must not retry it.
|
||||
var errResponseTooLarge = errors.New("response exceeds maximum size")
|
||||
|
||||
// readCapped reads a response body, refusing anything larger than limit instead
|
||||
// of buffering it. Oversized payloads are reported as an error: a truncated
|
||||
// body would be indexed as if it were the whole document. A non-positive limit
|
||||
// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.
|
||||
func readCapped(body io.Reader, limit int64) ([]byte, error) {
|
||||
if limit <= 0 {
|
||||
limit = maxJSONResponseBytes
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// doRequest executes an authenticated request and decodes JSON, with retry logic
|
||||
// for transient errors (429, 5xx, transport failures).
|
||||
// The raw X-Auth-Token is never logged; only a redacted form is emitted once per
|
||||
// client lifetime (not per request) to keep sync logs readable at thousand-doc scale.
|
||||
func (c *client) doRequest(ctx context.Context, method, path string, result interface{}) error {
|
||||
const (
|
||||
maxRetries = 3
|
||||
max5xxRetries = 1
|
||||
retry5xxDelay = 2 * time.Second
|
||||
)
|
||||
var lastErr error
|
||||
backoff := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second}
|
||||
|
||||
c.logTokenOnce.Do(func() {
|
||||
logger.Infof(ctx, "[Yuque] client configured token=%s base=%s", redactToken(c.token), c.baseURL)
|
||||
})
|
||||
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
reqURL := c.baseURL + path
|
||||
req, err := http.NewRequestWithContext(ctx, method, reqURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("X-Auth-Token", c.token)
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
if attempt == 0 {
|
||||
logger.Infof(ctx, "[Yuque] %s %s", method, path)
|
||||
} else {
|
||||
logger.Infof(ctx, "[Yuque] %s %s (retry %d/%d)", method, path, attempt, maxRetries)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
lastErr = fmt.Errorf("execute request: %w", err)
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
body, readErr := readCapped(resp.Body, c.jsonLimit)
|
||||
resp.Body.Close()
|
||||
if readErr != nil {
|
||||
lastErr = fmt.Errorf("read response body: %w", readErr)
|
||||
if attempt < maxRetries && !errors.Is(readErr, errResponseTooLarge) {
|
||||
if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
bodyPreview := truncate(string(body), 500)
|
||||
logger.Infof(ctx, "[Yuque] %s %s → status=%d bodyLen=%d body=%s",
|
||||
method, path, resp.StatusCode, len(body), bodyPreview)
|
||||
|
||||
if resp.StatusCode == 429 {
|
||||
wait := parseRetryAfter(resp.Header.Get("Retry-After"), backoff[min(attempt, len(backoff)-1)])
|
||||
lastErr = fmt.Errorf("yuque rate limited: status=429 body=%s", bodyPreview)
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepCtx(ctx, wait); sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
|
||||
lastErr = fmt.Errorf("yuque server error: status=%d body=%s", resp.StatusCode, bodyPreview)
|
||||
if attempt < max5xxRetries {
|
||||
if sErr := sleepCtx(ctx, retry5xxDelay); sErr != nil {
|
||||
return sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// 401/403 → surface as ErrInvalidCredentials so DataSourceService can
|
||||
// distinguish bad-token from transient failures and auto-flag the source.
|
||||
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
||||
return fmt.Errorf("%w: status=%d body=%s", datasource.ErrInvalidCredentials, resp.StatusCode, bodyPreview)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
var apiErr apiErrorBody
|
||||
_ = json.Unmarshal(body, &apiErr)
|
||||
if apiErr.Message != "" {
|
||||
return fmt.Errorf("yuque api error: status=%d msg=%s", resp.StatusCode, apiErr.Message)
|
||||
}
|
||||
return fmt.Errorf("yuque api error: status=%d body=%s", resp.StatusCode, bodyPreview)
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
if err := json.Unmarshal(body, result); err != nil {
|
||||
return fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// parseRetryAfter returns the Retry-After duration from the header, or fallback if unparseable.
|
||||
// Retry-After: "0" (or negative) is coerced to 100ms so we still yield and don't busy-retry.
|
||||
// Note: only integer-seconds form is supported (RFC 7231 also allows HTTP-date — not seen from Yuque).
|
||||
func parseRetryAfter(header string, fallback time.Duration) time.Duration {
|
||||
if header == "" {
|
||||
return fallback
|
||||
}
|
||||
if secs, err := time.ParseDuration(header + "s"); err == nil {
|
||||
if secs <= 0 {
|
||||
return 100 * time.Millisecond
|
||||
}
|
||||
return secs
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// sleepCtx pauses for d, returning early if ctx is cancelled.
|
||||
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Ping verifies the credentials by calling GET /api/v2/user.
|
||||
func (c *client) Ping(ctx context.Context) error {
|
||||
var resp v2UserResponse
|
||||
return c.doRequest(ctx, http.MethodGet, "/api/v2/user", &resp)
|
||||
}
|
||||
|
||||
// truncate returns s truncated to maxLen with "..." appended if longer.
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
// Back off to a rune boundary: a partial multi-byte rune is invalid UTF-8,
|
||||
// and this preview reaches sync_logs / data_sources through the sync error
|
||||
// message, which PostgreSQL rejects. Same rule as #4555.
|
||||
cut := maxLen
|
||||
for cut > 0 && !utf8.RuneStart(s[cut]) {
|
||||
cut--
|
||||
}
|
||||
return s[:cut] + "..."
|
||||
}
|
||||
|
||||
// buildQuery encodes query parameters, omitting empty values.
|
||||
func buildQuery(params map[string]string) string {
|
||||
values := url.Values{}
|
||||
for k, v := range params {
|
||||
if v != "" {
|
||||
values.Set(k, v)
|
||||
}
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return "?" + values.Encode()
|
||||
}
|
||||
|
||||
// GetCurrentUser returns the user associated with the current token.
|
||||
func (c *client) GetCurrentUser(ctx context.Context) (v2User, error) {
|
||||
var resp v2UserResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, "/api/v2/user", &resp); err != nil {
|
||||
return v2User{}, err
|
||||
}
|
||||
return resp.Data, nil
|
||||
}
|
||||
|
||||
// ListUserGroups returns the groups the given user belongs to.
|
||||
// Note: userID is Yuque's numeric user ID (not the login) — the /users/{id}/groups
|
||||
// endpoint requires the integer ID form.
|
||||
func (c *client) ListUserGroups(ctx context.Context, userID int64) ([]v2Group, error) {
|
||||
path := fmt.Sprintf("/api/v2/users/%d/groups", userID)
|
||||
var resp v2GroupListResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, path, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Data, nil
|
||||
}
|
||||
|
||||
// ListUserRepos returns document-type (Book) repos owned by the given user login.
|
||||
func (c *client) ListUserRepos(ctx context.Context, login string) ([]v2Repo, error) {
|
||||
return c.listReposPaginated(ctx, fmt.Sprintf("/api/v2/users/%s/repos", login))
|
||||
}
|
||||
|
||||
// ListGroupRepos returns document-type (Book) repos owned by the given group login.
|
||||
func (c *client) ListGroupRepos(ctx context.Context, login string) ([]v2Repo, error) {
|
||||
return c.listReposPaginated(ctx, fmt.Sprintf("/api/v2/groups/%s/repos", login))
|
||||
}
|
||||
|
||||
// listReposPaginated walks the pagination for a repo listing endpoint.
|
||||
// Filters to type=Book (document-type knowledge bases only; design/sheet/resource skipped).
|
||||
func (c *client) listReposPaginated(ctx context.Context, basePath string) ([]v2Repo, error) {
|
||||
var all []v2Repo
|
||||
offset := 0
|
||||
lastFirstID := int64(0)
|
||||
for hop := 0; ; hop++ {
|
||||
if hop >= maxPaginationHops {
|
||||
logger.Warnf(ctx, "[Yuque] %s pagination exceeded %d pages; aborting", basePath, maxPaginationHops)
|
||||
return nil, fmt.Errorf("yuque %s pagination exceeded %d pages", basePath, maxPaginationHops)
|
||||
}
|
||||
q := buildQuery(map[string]string{
|
||||
"type": "Book",
|
||||
"offset": fmt.Sprintf("%d", offset),
|
||||
"limit": fmt.Sprintf("%d", defaultPageSize),
|
||||
})
|
||||
var resp v2RepoListResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, basePath+q, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, resp.Data...)
|
||||
if len(resp.Data) < defaultPageSize {
|
||||
break
|
||||
}
|
||||
// A full page whose first id repeats the previous page means the server
|
||||
// is answering the same page for a growing offset; following it would
|
||||
// append the same repos forever.
|
||||
firstID := resp.Data[0].ID
|
||||
if firstID != 0 && firstID == lastFirstID {
|
||||
logger.Warnf(ctx, "[Yuque] %s pagination repeated page at offset %d; aborting", basePath, offset)
|
||||
return nil, fmt.Errorf("yuque %s pagination repeated page at offset %d", basePath, offset)
|
||||
}
|
||||
lastFirstID = firstID
|
||||
offset += defaultPageSize
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// ListBookDocs lists all documents in a book, handling pagination.
|
||||
// Returns summaries only (body not included — use GetDocDetail to fetch body per doc).
|
||||
func (c *client) ListBookDocs(ctx context.Context, bookID int64) ([]v2Doc, error) {
|
||||
basePath := fmt.Sprintf("/api/v2/repos/%d/docs", bookID)
|
||||
var all []v2Doc
|
||||
offset := 0
|
||||
lastFirstID := int64(0)
|
||||
for hop := 0; ; hop++ {
|
||||
if hop >= maxPaginationHops {
|
||||
logger.Warnf(ctx, "[Yuque] %s pagination exceeded %d pages; aborting", basePath, maxPaginationHops)
|
||||
return nil, fmt.Errorf("yuque %s pagination exceeded %d pages", basePath, maxPaginationHops)
|
||||
}
|
||||
q := buildQuery(map[string]string{
|
||||
"offset": fmt.Sprintf("%d", offset),
|
||||
"limit": fmt.Sprintf("%d", defaultPageSize),
|
||||
})
|
||||
var resp v2DocListResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, basePath+q, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, resp.Data...)
|
||||
if len(resp.Data) < defaultPageSize {
|
||||
break
|
||||
}
|
||||
// meta.total counts the whole listing, so a page that reaches it is the
|
||||
// last one; asking for the next offset would only fetch an empty page.
|
||||
if resp.Meta.Total > 0 && offset+len(resp.Data) >= resp.Meta.Total {
|
||||
break
|
||||
}
|
||||
// Same repeated-page guard as the repo listing: a gateway that ignores
|
||||
// offset hands back the identical full page forever.
|
||||
firstID := resp.Data[0].ID
|
||||
if firstID != 0 && firstID == lastFirstID {
|
||||
logger.Warnf(ctx, "[Yuque] %s pagination repeated page at offset %d; aborting", basePath, offset)
|
||||
return nil, fmt.Errorf("yuque %s pagination repeated page at offset %d", basePath, offset)
|
||||
}
|
||||
lastFirstID = firstID
|
||||
offset += defaultPageSize
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// GetDocDetail fetches the full document detail (including body) by doc ID.
|
||||
func (c *client) GetDocDetail(ctx context.Context, docID int64) (v2DocDetail, error) {
|
||||
path := fmt.Sprintf("/api/v2/repos/docs/%d", docID)
|
||||
var resp v2DocDetailResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, path, &resp); err != nil {
|
||||
return v2DocDetail{}, err
|
||||
}
|
||||
return resp.Data, nil
|
||||
}
|
||||
|
||||
// ListBookTOC fetches the table of contents of a book.
|
||||
//
|
||||
// The endpoint returns the whole tree in a single flat list (no pagination), so
|
||||
// this costs exactly one request per book per sync. Callers fold the result into
|
||||
// per-document folder paths with buildTOCPaths.
|
||||
func (c *client) ListBookTOC(ctx context.Context, bookID int64) ([]v2TOCNode, error) {
|
||||
path := fmt.Sprintf("/api/v2/repos/%d/toc", bookID)
|
||||
var resp v2TOCResponse
|
||||
if err := c.doRequest(ctx, http.MethodGet, path, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
// fakeYuque sets up an httptest server emulating Yuque API endpoints.
|
||||
// Handlers can be overridden per test.
|
||||
type fakeYuque struct {
|
||||
server *httptest.Server
|
||||
mux *http.ServeMux
|
||||
calls []string // methodPath history
|
||||
}
|
||||
|
||||
func newFakeYuque() *fakeYuque {
|
||||
f := &fakeYuque{mux: http.NewServeMux()}
|
||||
f.server = httptest.NewServer(f.mux)
|
||||
// Default /api/v2/user handler (most tests hit it at least once).
|
||||
f.handleJSON("/api/v2/user", 200, v2UserResponse{Data: v2User{ID: 1, Login: "me", Name: "Me"}})
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeYuque) Close() { f.server.Close() }
|
||||
|
||||
func (f *fakeYuque) cfg() *Config {
|
||||
return &Config{APIToken: "tok-super-secret-value-1234", BaseURL: f.server.URL}
|
||||
}
|
||||
|
||||
func (f *fakeYuque) handleJSON(path string, status int, body interface{}) {
|
||||
f.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
f.calls = append(f.calls, r.Method+" "+r.URL.Path+"?"+r.URL.RawQuery)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
})
|
||||
}
|
||||
|
||||
func TestClient_Ping_Success(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
|
||||
c := newClient(f.cfg())
|
||||
if err := c.Ping(context.Background()); err != nil {
|
||||
t.Fatalf("Ping error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_Ping_SendsAuthHeader(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
|
||||
var gotToken string
|
||||
f.mux = http.NewServeMux()
|
||||
f.mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
gotToken = r.Header.Get("X-Auth-Token")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v2UserResponse{Data: v2User{ID: 1, Login: "me"}})
|
||||
})
|
||||
f.server.Config.Handler = f.mux
|
||||
|
||||
c := newClient(f.cfg())
|
||||
if err := c.Ping(context.Background()); err != nil {
|
||||
t.Fatalf("Ping error: %v", err)
|
||||
}
|
||||
if gotToken != "tok-super-secret-value-1234" {
|
||||
t.Errorf("X-Auth-Token = %q, want the token", gotToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_Ping_401(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(401)
|
||||
_, _ = io.WriteString(w, `{"message":"Unauthorized"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(&Config{APIToken: "bad", BaseURL: srv.URL})
|
||||
err := c.Ping(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error on 401")
|
||||
}
|
||||
if !errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Errorf("401 should wrap ErrInvalidCredentials, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_Ping_403WrapsInvalidCredentials(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(403)
|
||||
_, _ = io.WriteString(w, `{"message":"Forbidden"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(&Config{APIToken: "insufficient", BaseURL: srv.URL})
|
||||
err := c.Ping(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error on 403")
|
||||
}
|
||||
if !errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Errorf("403 should wrap ErrInvalidCredentials, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_TokenNeverLoggedInFull(t *testing.T) {
|
||||
t.Cleanup(func() { logger.ConfigureFromEnv() })
|
||||
t.Setenv("ACADEMY_LOG_FORMAT", "")
|
||||
logger.ConfigureFromEnv()
|
||||
|
||||
// Redirect the project's internal logger to an in-memory buffer so we can
|
||||
// assert the raw token never appears in log output. Using stdlib `log`
|
||||
// would be vacuous — the real logger is a private logrus instance.
|
||||
var buf bytes.Buffer
|
||||
logger.SetOutput(&buf)
|
||||
defer logger.SetOutput(os.Stdout)
|
||||
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
|
||||
rawToken := "tok-super-secret-value-1234"
|
||||
cfg := &Config{APIToken: rawToken, BaseURL: f.server.URL}
|
||||
c := newClient(cfg)
|
||||
_ = c.Ping(context.Background())
|
||||
|
||||
out := buf.String()
|
||||
if out == "" {
|
||||
t.Fatal("expected logger output (sanity check — SetOutput wiring may be broken)")
|
||||
}
|
||||
if strings.Contains(out, rawToken) {
|
||||
t.Errorf("raw token leaked into logs:\n%s", out)
|
||||
}
|
||||
// Verify the redacted form was emitted (positive assertion, not just absence).
|
||||
if !strings.Contains(out, redactToken(rawToken)) {
|
||||
t.Errorf("expected redacted token %q in logs, got:\n%s", redactToken(rawToken), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactToken(t *testing.T) {
|
||||
tests := []struct{ in, want string }{
|
||||
{"short", "***"},
|
||||
{"abcdef1234567890", "abcdef...7890"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := redactToken(tt.in); got != tt.want {
|
||||
t.Errorf("redactToken(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_429WithRetryAfter_Retries(t *testing.T) {
|
||||
attempt := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempt++
|
||||
if attempt == 1 {
|
||||
// "0" is coerced to 100ms inside the client so the test stays fast.
|
||||
w.Header().Set("Retry-After", "0")
|
||||
w.WriteHeader(429)
|
||||
_, _ = io.WriteString(w, `{"message":"rate limited"}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v2UserResponse{Data: v2User{ID: 1, Login: "me"}})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(&Config{APIToken: "t", BaseURL: srv.URL})
|
||||
if err := c.Ping(context.Background()); err != nil {
|
||||
t.Fatalf("expected success after retry, got %v", err)
|
||||
}
|
||||
if attempt < 2 {
|
||||
t.Errorf("expected at least 2 attempts, got %d", attempt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_429ExhaustsRetries(t *testing.T) {
|
||||
attempts := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts++
|
||||
w.Header().Set("Retry-After", "0")
|
||||
w.WriteHeader(429)
|
||||
_, _ = io.WriteString(w, `{"message":"rate limited"}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(&Config{APIToken: "t", BaseURL: srv.URL})
|
||||
err := c.Ping(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error when 429s exceed retry budget")
|
||||
}
|
||||
if attempts != 4 { // initial + 3 retries
|
||||
t.Errorf("attempts = %d, want 4 (1 + 3 retries)", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_5xxRetriesOnce(t *testing.T) {
|
||||
attempts := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts++
|
||||
w.WriteHeader(500)
|
||||
_, _ = io.WriteString(w, `{"message":"internal error"}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
// Make the fixed 2-second 5xx sleep negligible by using a context whose
|
||||
// deadline fires after just one retry cycle. We still expect exactly 2
|
||||
// attempts because the implementation should retry 5xx once and then stop.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c := newClient(&Config{APIToken: "t", BaseURL: srv.URL})
|
||||
if err := c.Ping(ctx); err == nil {
|
||||
t.Fatal("expected error after 5xx exhaustion")
|
||||
}
|
||||
if attempts != 2 { // initial + 1 retry
|
||||
t.Errorf("attempts = %d, want 2 (5xx retries exactly once)", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_4xxNotRetried(t *testing.T) {
|
||||
attempts := 0
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts++
|
||||
w.WriteHeader(400)
|
||||
_, _ = io.WriteString(w, `{"message":"bad request"}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(&Config{APIToken: "t", BaseURL: srv.URL})
|
||||
if err := c.Ping(context.Background()); err == nil {
|
||||
t.Fatal("expected error on 400")
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1 (non-429/5xx 4xx must not retry)", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRetryAfter(t *testing.T) {
|
||||
fallback := 5 * time.Second
|
||||
tests := []struct {
|
||||
header string
|
||||
want time.Duration
|
||||
}{
|
||||
{"", fallback},
|
||||
{"0", 100 * time.Millisecond},
|
||||
{"-1", 100 * time.Millisecond}, // negative coerced
|
||||
{"3", 3 * time.Second},
|
||||
{"abc", fallback}, // unparseable
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := parseRetryAfter(tt.header, fallback); got != tt.want {
|
||||
t.Errorf("parseRetryAfter(%q) = %v, want %v", tt.header, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_GetCurrentUser(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
// Override the default /api/v2/user handler via a fresh mux.
|
||||
f.mux = http.NewServeMux()
|
||||
f.mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v2UserResponse{Data: v2User{ID: 42, Login: "alice", Name: "Alice"}})
|
||||
})
|
||||
f.server.Config.Handler = f.mux
|
||||
|
||||
c := newClient(f.cfg())
|
||||
u, err := c.GetCurrentUser(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("GetCurrentUser: %v", err)
|
||||
}
|
||||
if u.ID != 42 || u.Login != "alice" {
|
||||
t.Errorf("got %+v, want {42 alice}", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_ListUserGroups(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/users/42/groups", 200, v2GroupListResponse{Data: []v2Group{
|
||||
{ID: 100, Login: "team-a", Name: "Team A"},
|
||||
{ID: 101, Login: "team-b", Name: "Team B"},
|
||||
}})
|
||||
|
||||
c := newClient(f.cfg())
|
||||
gs, err := c.ListUserGroups(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserGroups: %v", err)
|
||||
}
|
||||
if len(gs) != 2 || gs[0].Login != "team-a" {
|
||||
t.Errorf("got %+v", gs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_ListUserRepos_FiltersType(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
var gotQuery string
|
||||
f.mux.HandleFunc("/api/v2/users/alice/repos", func(w http.ResponseWriter, r *http.Request) {
|
||||
gotQuery = r.URL.RawQuery
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 9, Slug: "book1", Name: "Book 1", Type: "Book", Namespace: "alice/book1"},
|
||||
}})
|
||||
})
|
||||
|
||||
c := newClient(f.cfg())
|
||||
repos, err := c.ListUserRepos(context.Background(), "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserRepos: %v", err)
|
||||
}
|
||||
if !strings.Contains(gotQuery, "type=Book") {
|
||||
t.Errorf("expected type=Book in query, got %q", gotQuery)
|
||||
}
|
||||
if !strings.Contains(gotQuery, "offset=0") {
|
||||
t.Errorf("expected offset=0 in query, got %q", gotQuery)
|
||||
}
|
||||
if !strings.Contains(gotQuery, "limit=100") {
|
||||
t.Errorf("expected limit=100 in query, got %q", gotQuery)
|
||||
}
|
||||
if len(repos) != 1 || repos[0].Namespace != "alice/book1" {
|
||||
t.Errorf("got %+v", repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_ListGroupRepos(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/groups/team-a/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 11, Slug: "tb", Name: "Team Book", Type: "Book", Namespace: "team-a/tb"},
|
||||
}})
|
||||
|
||||
c := newClient(f.cfg())
|
||||
repos, err := c.ListGroupRepos(context.Background(), "team-a")
|
||||
if err != nil {
|
||||
t.Fatalf("ListGroupRepos: %v", err)
|
||||
}
|
||||
if len(repos) != 1 || repos[0].ID != 11 {
|
||||
t.Errorf("got %+v", repos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_ListBookDocs_Pagination(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
// Page 1: 100 docs, page 2: 30 docs, then stop.
|
||||
callCount := 0
|
||||
f.mux.HandleFunc("/api/v2/repos/555/docs", func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
offset := r.URL.Query().Get("offset")
|
||||
docs := make([]v2Doc, 0)
|
||||
switch offset {
|
||||
case "0":
|
||||
for i := 0; i < 100; i++ {
|
||||
docs = append(docs, v2Doc{ID: int64(i + 1), Type: "Doc", Status: "1", Title: fmt.Sprintf("D%d", i+1), ContentUpdatedAt: "2026-04-20T00:00:00Z"})
|
||||
}
|
||||
case "100":
|
||||
for i := 0; i < 30; i++ {
|
||||
docs = append(docs, v2Doc{ID: int64(i + 101), Type: "Doc", Status: "1", Title: fmt.Sprintf("D%d", i+101), ContentUpdatedAt: "2026-04-20T00:00:00Z"})
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v2DocListResponse{Data: docs})
|
||||
})
|
||||
|
||||
c := newClient(f.cfg())
|
||||
docs, err := c.ListBookDocs(context.Background(), 555)
|
||||
if err != nil {
|
||||
t.Fatalf("ListBookDocs: %v", err)
|
||||
}
|
||||
if len(docs) != 130 {
|
||||
t.Errorf("len(docs) = %d, want 130", len(docs))
|
||||
}
|
||||
if callCount != 2 {
|
||||
t.Errorf("callCount = %d, want 2 (one full page + one partial)", callCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_GetDocDetail(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/docs/7", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{
|
||||
ID: 7,
|
||||
Title: "Hello",
|
||||
Body: "# Hello\n\nworld",
|
||||
Format: "markdown",
|
||||
Status: "1",
|
||||
ContentUpdatedAt: "2026-04-20T12:00:00Z",
|
||||
},
|
||||
})
|
||||
|
||||
c := newClient(f.cfg())
|
||||
d, err := c.GetDocDetail(context.Background(), 7)
|
||||
if err != nil {
|
||||
t.Fatalf("GetDocDetail: %v", err)
|
||||
}
|
||||
if d.Body != "# Hello\n\nworld" {
|
||||
t.Errorf("Body = %q", d.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_DoRequest_RejectsOversizedResponse(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
|
||||
var hits atomic.Int32
|
||||
f.mux = http.NewServeMux()
|
||||
f.mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, _ *http.Request) {
|
||||
hits.Add(1)
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))
|
||||
})
|
||||
f.server.Config.Handler = f.mux
|
||||
|
||||
c := newClient(f.cfg())
|
||||
c.jsonLimit = 1 << 20
|
||||
err := c.Ping(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("Ping accepted a response larger than the cap, want error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
// The same document is just as large on every attempt; retrying only burns
|
||||
// the rate-limit budget and re-reads the full cap each time.
|
||||
if got := hits.Load(); got != 1 {
|
||||
t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Compile-time proof that *Connector satisfies the datasource.Connector interface.
|
||||
// Catches signature drift as soon as the interface changes, rather than at
|
||||
// container wiring or runtime.
|
||||
var _ datasource.Connector = (*Connector)(nil)
|
||||
|
||||
// Connector implements datasource.Connector for Yuque.
|
||||
type Connector struct{}
|
||||
|
||||
// NewConnector creates a new Yuque connector.
|
||||
func NewConnector() *Connector { return &Connector{} }
|
||||
|
||||
// Type returns the connector type identifier.
|
||||
func (c *Connector) Type() string { return types.ConnectorTypeYuque }
|
||||
|
||||
// Validate verifies the given credentials by pinging the current-user endpoint.
|
||||
func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {
|
||||
cfg, err := parseYuqueConfig(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cli := newClient(cfg)
|
||||
if err := cli.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("yuque connection failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveResourceAncestors has nothing to do for Yuque: repositories are a flat
|
||||
// list with no nesting, so a selection has no ancestors to reveal.
|
||||
func (c *Connector) ResolveResourceAncestors(
|
||||
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
|
||||
) ([]string, error) {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
// ListResources returns all repos (personal + team) accessible to the token.
|
||||
// Serial fetch for v1 (user groups typically <10). TODO(perf): parallelize if slow.
|
||||
func (c *Connector) ListResources(
|
||||
ctx context.Context, config *types.DataSourceConfig, parentID string,
|
||||
) ([]types.Resource, error) {
|
||||
// Yuque resources are a flat list of repositories (no nesting), so a
|
||||
// lazy-load request for a specific parent has nothing extra to return.
|
||||
if parentID != "" {
|
||||
return []types.Resource{}, nil
|
||||
}
|
||||
|
||||
cfg, err := parseYuqueConfig(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cli := newClient(cfg)
|
||||
|
||||
me, err := cli.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get current user: %w", err)
|
||||
}
|
||||
|
||||
repos := make(map[int64]v2Repo)
|
||||
|
||||
// Team token: /api/v2/user returns type="Group" — the token represents a team,
|
||||
// not a personal user. In this case, directly list the team's own repos instead
|
||||
// of going through the personal-repos + user-groups flow.
|
||||
if me.Type == "Group" {
|
||||
logger.Infof(ctx, "[Yuque] detected team token (type=Group, login=%s), listing team repos directly", me.Login)
|
||||
teamRepos, err := cli.ListGroupRepos(ctx, me.Login)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list team repos: %w", err)
|
||||
}
|
||||
for _, r := range teamRepos {
|
||||
repos[r.ID] = r
|
||||
}
|
||||
} else {
|
||||
// Personal token flow: list user's own repos + repos from joined groups.
|
||||
personal, err := cli.ListUserRepos(ctx, me.Login)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list personal repos: %w", err)
|
||||
}
|
||||
for _, r := range personal {
|
||||
if _, ok := repos[r.ID]; !ok {
|
||||
repos[r.ID] = r
|
||||
}
|
||||
}
|
||||
|
||||
groups, err := cli.ListUserGroups(ctx, me.ID)
|
||||
if err != nil {
|
||||
// Yuque returns 404 when the user has not joined any groups (teams),
|
||||
// instead of an empty list. Treat this as "no groups" and continue
|
||||
// — personal repos were already fetched above.
|
||||
logger.Warnf(ctx, "[Yuque] list user groups failed (treating as empty): %v", err)
|
||||
groups = nil
|
||||
}
|
||||
for _, g := range groups {
|
||||
teamRepos, err := cli.ListGroupRepos(ctx, g.Login)
|
||||
if err != nil {
|
||||
// Skip this group but continue others (e.g., 403 on a restricted group).
|
||||
logger.Warnf(ctx, "[Yuque] skip group %s: %v", g.Login, err)
|
||||
continue
|
||||
}
|
||||
for _, r := range teamRepos {
|
||||
if _, ok := repos[r.ID]; !ok {
|
||||
repos[r.ID] = r
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]types.Resource, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
out = append(out, types.Resource{
|
||||
ExternalID: strconv.FormatInt(r.ID, 10),
|
||||
Name: r.Name,
|
||||
Type: "book",
|
||||
URL: cfg.GetBaseURL() + "/" + r.Namespace,
|
||||
Description: r.Namespace,
|
||||
ModifiedAt: parseContentUpdatedAt(r.UpdatedAt),
|
||||
Metadata: map[string]interface{}{
|
||||
"public": r.Public,
|
||||
"book_type": r.Type,
|
||||
},
|
||||
})
|
||||
}
|
||||
// Stable, deterministic order for UI rendering and response-body caching.
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ExternalID < out[j].ExternalID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FetchAll performs a full sync of all books specified in resourceIDs.
|
||||
func (c *Connector) FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error) {
|
||||
items, _, err := c.walk(ctx, config, resourceIDs, nil, false)
|
||||
return items, err
|
||||
}
|
||||
|
||||
// walk is the shared implementation for FetchAll / FetchIncremental.
|
||||
// If incremental is false, prev is ignored and no cursor is returned (returns nil for cursor).
|
||||
func (c *Connector) walk(
|
||||
ctx context.Context,
|
||||
config *types.DataSourceConfig,
|
||||
resourceIDs []string,
|
||||
prev *yuqueCursor,
|
||||
incremental bool,
|
||||
) ([]types.FetchedItem, *yuqueCursor, error) {
|
||||
cfg, err := parseYuqueConfig(config)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cli := newClient(cfg)
|
||||
settings := parseFolderSettings(ctx, config)
|
||||
if settings.FolderMode != folderModeNone {
|
||||
logger.Infof(ctx, "[Yuque] folder path derivation enabled: folder_mode=%s toc_only=%t",
|
||||
settings.FolderMode, settings.TOCOnly)
|
||||
}
|
||||
|
||||
newCursor := &yuqueCursor{LastSyncTime: time.Now(), BookDocTimes: make(map[string]map[string]string)}
|
||||
var out []types.FetchedItem
|
||||
|
||||
for _, bookIDStr := range resourceIDs {
|
||||
bookID, err := strconv.ParseInt(bookIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid book id %q: %w", bookIDStr, err)
|
||||
}
|
||||
|
||||
docs, err := cli.ListBookDocs(ctx, bookID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("list docs for book %d: %w", bookID, err)
|
||||
}
|
||||
|
||||
// Optionally fetch the book's table of contents and fold it into a
|
||||
// per-document folder path. One request per book per sync.
|
||||
//
|
||||
// tocOK separates "the TOC was fetched and this document is not in it"
|
||||
// from "we could not fetch the TOC at all". Both the path assembly and
|
||||
// the toc_only filter depend on that distinction: with no TOC we must
|
||||
// degrade to the previous flat behaviour rather than silently dropping
|
||||
// every document.
|
||||
var tocSegs map[int64][]string
|
||||
var inTOC map[int64]bool
|
||||
tocOK := false
|
||||
if settings.FolderMode == folderModeTOC {
|
||||
toc, tocErr := cli.ListBookTOC(ctx, bookID)
|
||||
if tocErr != nil {
|
||||
logger.Warnf(ctx, "[Yuque] book %d: fetch TOC failed, falling back to flat file names: %v",
|
||||
bookID, tocErr)
|
||||
} else {
|
||||
tocSegs, inTOC = buildTOCPaths(toc)
|
||||
tocOK = true
|
||||
}
|
||||
}
|
||||
bookName := ""
|
||||
|
||||
currentDocs := make(map[string]bool)
|
||||
newCursor.BookDocTimes[bookIDStr] = make(map[string]string)
|
||||
|
||||
var skippedType, skippedDraft, skippedNotInTOC, kept int
|
||||
var sampleSkipType, sampleSkipDraft, sampleSkipNotInTOC string
|
||||
for _, d := range docs {
|
||||
// Empty type/status is treated as acceptable — forward-compat with
|
||||
// API variations that omit the field.
|
||||
if d.Type != "" && d.Type != "Doc" {
|
||||
skippedType++
|
||||
if sampleSkipType == "" {
|
||||
sampleSkipType = fmt.Sprintf("id=%d type=%q title=%q", d.ID, d.Type, d.Title)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if d.Status != "" && d.Status != "1" {
|
||||
skippedDraft++
|
||||
if sampleSkipDraft == "" {
|
||||
sampleSkipDraft = fmt.Sprintf("id=%d status=%q title=%q", d.ID, d.Status, d.Title)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Mark the document as seen so the deletion detector does not treat a
|
||||
// filtered document as removed from the source. toc_only is an
|
||||
// admission filter: it decides what enters the knowledge base, not what
|
||||
// leaves it. Reporting these as deleted would remove exactly the
|
||||
// documents the Yuque web UI cannot show (created through the API,
|
||||
// never attached to the TOC), leaving their content unreachable from
|
||||
// both sides.
|
||||
docIDStr := strconv.FormatInt(d.ID, 10)
|
||||
currentDocs[docIDStr] = true
|
||||
|
||||
// Filter out documents that do not appear in the TOC. Applies only when
|
||||
// the TOC was actually fetched — see the tocOK comment above. The
|
||||
// predicate is membership in the TOC node list, not "has a path":
|
||||
// a document may sit in the TOC with no enclosing group.
|
||||
if settings.TOCOnly && tocOK && !inTOC[d.ID] {
|
||||
skippedNotInTOC++
|
||||
if sampleSkipNotInTOC == "" {
|
||||
sampleSkipNotInTOC = fmt.Sprintf("id=%d title=%q", d.ID, d.Title)
|
||||
}
|
||||
continue
|
||||
}
|
||||
kept++
|
||||
// Only admitted documents enter the cursor. A filtered document has to
|
||||
// stay unknown to the incremental comparison, so that admitting it
|
||||
// later — by attaching it to the TOC, or by switching toc_only off —
|
||||
// ingests it rather than dismissing it as unchanged.
|
||||
newCursor.BookDocTimes[bookIDStr][docIDStr] = d.ContentUpdatedAt
|
||||
|
||||
// Incremental: skip if content hasn't changed.
|
||||
if incremental && prev != nil && prev.BookDocTimes != nil {
|
||||
if prevTimes, ok := prev.BookDocTimes[bookIDStr]; ok {
|
||||
if prevTimes[docIDStr] == d.ContentUpdatedAt {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rate-limit: pause between GetDocDetail calls to avoid hitting
|
||||
// Yuque's API rate limit (typically ~100 req/5min for personal tokens).
|
||||
if err := sleepCtx(ctx, 300*time.Millisecond); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
detail, err := cli.GetDocDetail(ctx, d.ID)
|
||||
if err != nil {
|
||||
// Do not acknowledge the doc's new version when its detail fetch
|
||||
// failed: rewind the cursor entry to the previously synced version
|
||||
// (existing docs) or drop it (new docs), so the next incremental
|
||||
// sync re-fetches the doc once the endpoint recovers. Acking before
|
||||
// the fetch succeeded made the doc silently skipped by every later
|
||||
// incremental sync (Tencent/WeKnora#3690). The doc stays in
|
||||
// currentDocs, so deletion detection is unaffected.
|
||||
if prev != nil && prev.BookDocTimes != nil {
|
||||
newCursor.BookDocTimes[bookIDStr][docIDStr] = prev.BookDocTimes[bookIDStr][docIDStr]
|
||||
}
|
||||
if newCursor.BookDocTimes[bookIDStr][docIDStr] == "" {
|
||||
delete(newCursor.BookDocTimes[bookIDStr], docIDStr)
|
||||
}
|
||||
// Record failure but continue (placeholder item with error metadata).
|
||||
// Keep doc_id/book_id/slug for observability pipelines that join on these.
|
||||
out = append(out, types.FetchedItem{
|
||||
ExternalID: docIDStr,
|
||||
Title: d.Title,
|
||||
SourceResourceID: bookIDStr,
|
||||
Metadata: map[string]string{
|
||||
"error": err.Error(),
|
||||
"channel": types.ChannelYuque,
|
||||
"doc_id": docIDStr,
|
||||
"book_id": bookIDStr,
|
||||
"slug": d.Slug,
|
||||
},
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Yuque serializes `body` as Markdown when format is "markdown" or
|
||||
// "lake" (Lake XML lives separately in `body_lake`) — empirically
|
||||
// verified against the v2 API. Any other format (e.g. "html") may
|
||||
// put non-Markdown content in `body`, so skip defensively.
|
||||
if detail.Format != "" && detail.Format != "markdown" && detail.Format != "lake" {
|
||||
logger.Warnf(ctx, "[Yuque] skip doc %d (%q): unsupported format %q",
|
||||
d.ID, d.Title, detail.Format)
|
||||
out = append(out, types.FetchedItem{
|
||||
ExternalID: docIDStr,
|
||||
Title: d.Title,
|
||||
SourceResourceID: bookIDStr,
|
||||
Metadata: map[string]string{
|
||||
"channel": types.ChannelYuque,
|
||||
"doc_id": docIDStr,
|
||||
"book_id": bookIDStr,
|
||||
"slug": d.Slug,
|
||||
"skip_reason": "unsupported format: " + detail.Format,
|
||||
},
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Book title for the leading path segment. The detail response
|
||||
// already carries it, so this costs no extra API call. Captured
|
||||
// once per book; falls back to the namespace, then to no prefix.
|
||||
if bookName == "" {
|
||||
bookName = strings.TrimSpace(detail.Book.Name)
|
||||
if bookName == "" {
|
||||
bookName = strings.TrimSpace(detail.Book.Namespace)
|
||||
}
|
||||
}
|
||||
|
||||
// folder_path is derived downstream from FileName alone
|
||||
// (SplitKnowledgeRelativePath → NormalizeKnowledgeFolderPath), so the
|
||||
// hierarchy has to be encoded here as a relative path.
|
||||
fileName := buildFolderFileName(settings, tocOK, bookName, tocSegs[d.ID], d.Title)
|
||||
|
||||
out = append(out, types.FetchedItem{
|
||||
ExternalID: docIDStr,
|
||||
Title: d.Title,
|
||||
Content: []byte(detail.Body),
|
||||
ContentType: "text/markdown",
|
||||
FileName: fileName,
|
||||
URL: buildDocURL(cfg.GetBaseURL(), detail.Book.Namespace, d.Slug),
|
||||
UpdatedAt: parseContentUpdatedAt(d.ContentUpdatedAt),
|
||||
SourceResourceID: bookIDStr,
|
||||
Metadata: map[string]string{
|
||||
"doc_id": docIDStr,
|
||||
"book_id": bookIDStr,
|
||||
"slug": d.Slug,
|
||||
"creator": strconv.FormatInt(d.UserID, 10),
|
||||
"word_count": strconv.Itoa(d.WordCount),
|
||||
"channel": types.ChannelYuque,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Yuque] book %d: total=%d kept=%d skipped_non_doc=%d skipped_draft=%d "+
|
||||
"skipped_not_in_toc=%d toc_loaded=%t non_doc_sample={%s} draft_sample={%s} "+
|
||||
"not_in_toc_sample={%s}",
|
||||
bookID, len(docs), kept, skippedType, skippedDraft, skippedNotInTOC, tocOK,
|
||||
sampleSkipType, sampleSkipDraft, sampleSkipNotInTOC)
|
||||
|
||||
// Deletion detection (incremental only): previous doc IDs not in current → IsDeleted=true
|
||||
if incremental && prev != nil && prev.BookDocTimes != nil {
|
||||
if prevTimes, ok := prev.BookDocTimes[bookIDStr]; ok {
|
||||
for prevDocID := range prevTimes {
|
||||
if !currentDocs[prevDocID] {
|
||||
out = append(out, types.FetchedItem{
|
||||
ExternalID: prevDocID,
|
||||
IsDeleted: true,
|
||||
SourceResourceID: bookIDStr,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !incremental {
|
||||
return out, nil, nil
|
||||
}
|
||||
return out, newCursor, nil
|
||||
}
|
||||
|
||||
// buildDocURL constructs a browser URL for a Yuque doc.
|
||||
// Namespace may be empty on some responses; fall back to base URL only.
|
||||
func buildDocURL(baseURL, namespace, slug string) string {
|
||||
if namespace == "" {
|
||||
return baseURL
|
||||
}
|
||||
return baseURL + "/" + namespace + "/" + slug
|
||||
}
|
||||
|
||||
// FetchIncremental returns items changed (or deleted) since the prior cursor.
|
||||
// Deletion detection: docs present in the prior cursor but absent from the
|
||||
// current list are emitted as IsDeleted=true placeholder items.
|
||||
func (c *Connector) FetchIncremental(
|
||||
ctx context.Context,
|
||||
config *types.DataSourceConfig,
|
||||
cursor *types.SyncCursor,
|
||||
) ([]types.FetchedItem, *types.SyncCursor, error) {
|
||||
resourceIDs := config.ResourceIDs
|
||||
if len(resourceIDs) == 0 {
|
||||
return nil, nil, fmt.Errorf("no resource IDs (book IDs) configured")
|
||||
}
|
||||
|
||||
// Decode prior cursor (if any).
|
||||
var prev *yuqueCursor
|
||||
if cursor != nil && cursor.ConnectorCursor != nil {
|
||||
var p yuqueCursor
|
||||
b, _ := json.Marshal(cursor.ConnectorCursor)
|
||||
_ = json.Unmarshal(b, &p)
|
||||
prev = &p
|
||||
}
|
||||
|
||||
items, newCursor, err := c.walk(ctx, config, resourceIDs, prev, true)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Marshal newCursor into a generic map for the SyncCursor wrapper.
|
||||
cursorMap := make(map[string]interface{})
|
||||
b, _ := json.Marshal(newCursor)
|
||||
_ = json.Unmarshal(b, &cursorMap)
|
||||
|
||||
return items, &types.SyncCursor{
|
||||
LastSyncTime: newCursor.LastSyncTime,
|
||||
ConnectorCursor: cursorMap,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
// TestMain whitelists loopback for the httptest servers and the default base
|
||||
// host so parseYuqueConfig does not resolve www.yuque.com over live DNS during
|
||||
// a unit test. Production keeps the default strict SSRF policy.
|
||||
func TestMain(m *testing.M) {
|
||||
_ = os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost,www.yuque.com")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func makeDSConfig(f *fakeYuque, resourceIDs []string) *types.DataSourceConfig {
|
||||
return &types.DataSourceConfig{
|
||||
Type: types.ConnectorTypeYuque,
|
||||
Credentials: map[string]interface{}{"api_token": f.cfg().APIToken, "base_url": f.cfg().BaseURL},
|
||||
ResourceIDs: resourceIDs,
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_Type(t *testing.T) {
|
||||
if NewConnector().Type() != types.ConnectorTypeYuque {
|
||||
t.Errorf("Type() = %q, want %q", NewConnector().Type(), types.ConnectorTypeYuque)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_Validate_Success(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
|
||||
if err := NewConnector().Validate(context.Background(), makeDSConfig(f, nil)); err != nil {
|
||||
t.Fatalf("Validate error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_Validate_Bad401(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(401)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
err := NewConnector().Validate(context.Background(), &types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"api_token": "bad", "base_url": srv.URL},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 401")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_ListResources_Aggregates(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
// user = alice (id=1)
|
||||
// Override default /api/v2/user handler to return alice (f.handleJSON panics on duplicate path registration).
|
||||
f.mux = http.NewServeMux()
|
||||
f.server.Config.Handler = f.mux
|
||||
f.handleJSON("/api/v2/user", 200, v2UserResponse{Data: v2User{ID: 1, Login: "alice"}})
|
||||
// personal repos
|
||||
f.handleJSON("/api/v2/users/alice/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 10, Slug: "personal", Name: "Personal", Type: "Book", Namespace: "alice/personal"},
|
||||
}})
|
||||
// 2 groups
|
||||
f.handleJSON("/api/v2/users/1/groups", 200, v2GroupListResponse{Data: []v2Group{
|
||||
{ID: 100, Login: "team-a"}, {ID: 101, Login: "team-b"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/groups/team-a/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 20, Slug: "ab", Name: "A Book", Type: "Book", Namespace: "team-a/ab"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/groups/team-b/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 30, Slug: "bb", Name: "B Book", Type: "Book", Namespace: "team-b/bb"},
|
||||
}})
|
||||
|
||||
resources, err := NewConnector().ListResources(context.Background(), makeDSConfig(f, nil), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListResources: %v", err)
|
||||
}
|
||||
if len(resources) != 3 {
|
||||
t.Fatalf("len = %d, want 3", len(resources))
|
||||
}
|
||||
// Verify fields on one entry
|
||||
var ab *types.Resource
|
||||
for i := range resources {
|
||||
if resources[i].Name == "A Book" {
|
||||
ab = &resources[i]
|
||||
}
|
||||
}
|
||||
if ab == nil {
|
||||
t.Fatal("expected A Book resource")
|
||||
}
|
||||
if ab.ExternalID != "20" || ab.Description != "team-a/ab" || ab.Type != "book" {
|
||||
t.Errorf("got %+v", ab)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_ListResources_DedupByID(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.mux = http.NewServeMux()
|
||||
f.server.Config.Handler = f.mux
|
||||
f.handleJSON("/api/v2/user", 200, v2UserResponse{Data: v2User{ID: 1, Login: "alice"}})
|
||||
f.handleJSON("/api/v2/users/alice/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 99, Slug: "shared", Type: "Book", Namespace: "alice/shared"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/users/1/groups", 200, v2GroupListResponse{Data: []v2Group{
|
||||
{ID: 200, Login: "team-x"},
|
||||
}})
|
||||
// Same repo (ID 99) appears again via a team the user is in.
|
||||
f.handleJSON("/api/v2/groups/team-x/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 99, Slug: "shared", Type: "Book", Namespace: "alice/shared"},
|
||||
}})
|
||||
|
||||
resources, err := NewConnector().ListResources(context.Background(), makeDSConfig(f, nil), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListResources: %v", err)
|
||||
}
|
||||
if len(resources) != 1 {
|
||||
t.Errorf("expected dedup to 1, got %d", len(resources))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_Markdown(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
// Book 7 → 2 docs; one published Doc, one draft (filtered)
|
||||
f.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 101, Type: "Doc", Status: "1", Title: "Hello", Slug: "hello", BookID: 7, ContentUpdatedAt: "2026-04-20T10:00:00Z", WordCount: 42},
|
||||
{ID: 102, Type: "Doc", Status: "0", Title: "Draft", Slug: "draft", BookID: 7, ContentUpdatedAt: "2026-04-20T11:00:00Z"}, // draft, skipped
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/101", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 101, Title: "Hello", Body: "# Hello\n\nworld", Format: "markdown", Status: "1",
|
||||
ContentUpdatedAt: "2026-04-20T10:00:00Z", Book: v2Repo{Namespace: "alice/demo"}},
|
||||
})
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"7"}), []string{"7"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("len = %d, want 1 (draft filtered)", len(items))
|
||||
}
|
||||
it := items[0]
|
||||
if it.ExternalID != "101" || it.Title != "Hello" {
|
||||
t.Errorf("got %+v", it)
|
||||
}
|
||||
if string(it.Content) != "# Hello\n\nworld" {
|
||||
t.Errorf("Content = %q", string(it.Content))
|
||||
}
|
||||
if it.ContentType != "text/markdown" {
|
||||
t.Errorf("ContentType = %q", it.ContentType)
|
||||
}
|
||||
if it.FileName != "Hello.md" {
|
||||
t.Errorf("FileName = %q", it.FileName)
|
||||
}
|
||||
if it.Metadata["channel"] != types.ChannelYuque {
|
||||
t.Errorf("channel = %q", it.Metadata["channel"])
|
||||
}
|
||||
if it.UpdatedAt.IsZero() {
|
||||
t.Error("UpdatedAt should be parsed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_DocDetailError_EmitsPlaceholder(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/9/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 301, Type: "Doc", Status: "1", Title: "Broken", Slug: "broken", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 302, Type: "Doc", Status: "1", Title: "OK", Slug: "ok", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f.mux.HandleFunc("/api/v2/repos/docs/301", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest) // 4xx is non-retriable, bubbles up as an error
|
||||
_, _ = w.Write([]byte(`{"message":"broken"}`))
|
||||
})
|
||||
f.handleJSON("/api/v2/repos/docs/302", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 302, Title: "OK", Body: "ok", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"9"}), []string{"9"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll must not abort the batch on a single detail error, got %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("want 2 items (placeholder + ok), got %d: %+v", len(items), items)
|
||||
}
|
||||
// Find the placeholder — the one with the "error" metadata key.
|
||||
var placeholder *types.FetchedItem
|
||||
for i := range items {
|
||||
if items[i].Metadata["error"] != "" {
|
||||
placeholder = &items[i]
|
||||
}
|
||||
}
|
||||
if placeholder == nil {
|
||||
t.Fatal("expected a placeholder item with Metadata[error] set")
|
||||
}
|
||||
if placeholder.ExternalID != "301" || placeholder.Title != "Broken" {
|
||||
t.Errorf("placeholder identity wrong: %+v", placeholder)
|
||||
}
|
||||
if placeholder.Metadata["channel"] != types.ChannelYuque {
|
||||
t.Errorf("placeholder channel = %q", placeholder.Metadata["channel"])
|
||||
}
|
||||
if placeholder.Metadata["book_id"] != "9" || placeholder.Metadata["doc_id"] != "301" || placeholder.Metadata["slug"] != "broken" {
|
||||
t.Errorf("placeholder missing traceability metadata: %+v", placeholder.Metadata)
|
||||
}
|
||||
if len(placeholder.Content) != 0 {
|
||||
t.Errorf("placeholder should have empty Content, got %q", string(placeholder.Content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_LakeFormatIngestedAsMarkdown(t *testing.T) {
|
||||
// Yuque's v2 doc-detail serves `body` as Markdown for type="Doc" regardless
|
||||
// of authoring format. format="lake" means the doc was edited in the Lake
|
||||
// editor, but `body` is still the Markdown representation (Lake XML lives
|
||||
// in `body_lake`). So both should be ingested identically.
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/12/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 401, Type: "Doc", Status: "1", Title: "Lake Doc", Slug: "lake", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 402, Type: "Doc", Status: "1", Title: "MD Doc", Slug: "md", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/401", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 401, Title: "Lake Doc", Format: "lake", Body: "# lake body as markdown", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
f.handleJSON("/api/v2/repos/docs/402", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 402, Title: "MD Doc", Format: "markdown", Body: "# MD", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"12"}), []string{"12"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("want 2 items, got %d", len(items))
|
||||
}
|
||||
wantBody := map[string]string{
|
||||
"401": "# lake body as markdown",
|
||||
"402": "# MD",
|
||||
}
|
||||
for _, it := range items {
|
||||
if string(it.Content) != wantBody[it.ExternalID] {
|
||||
t.Errorf("item %s Content = %q, want %q", it.ExternalID, it.Content, wantBody[it.ExternalID])
|
||||
}
|
||||
if it.ContentType != "text/markdown" {
|
||||
t.Errorf("item %s ContentType = %q, want text/markdown", it.ExternalID, it.ContentType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_SkipsUnsupportedFormats(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/13/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 501, Type: "Doc", Status: "1", Title: "HTML Doc", Slug: "h", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 502, Type: "Doc", Status: "1", Title: "OK Doc", Slug: "ok", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/501", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 501, Title: "HTML Doc", Format: "html", Body: "<p>raw html</p>", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
f.handleJSON("/api/v2/repos/docs/502", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 502, Title: "OK Doc", Format: "lake", Body: "# ok", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"13"}), []string{"13"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("want 2 items (placeholder + ok), got %d", len(items))
|
||||
}
|
||||
var htmlPlaceholder, okItem *types.FetchedItem
|
||||
for i := range items {
|
||||
if items[i].ExternalID == "501" {
|
||||
htmlPlaceholder = &items[i]
|
||||
}
|
||||
if items[i].ExternalID == "502" {
|
||||
okItem = &items[i]
|
||||
}
|
||||
}
|
||||
if htmlPlaceholder == nil || okItem == nil {
|
||||
t.Fatal("missing one of the items")
|
||||
}
|
||||
if htmlPlaceholder.Metadata["skip_reason"] == "" {
|
||||
t.Errorf("html doc should have skip_reason metadata, got %+v", htmlPlaceholder.Metadata)
|
||||
}
|
||||
if len(htmlPlaceholder.Content) != 0 {
|
||||
t.Errorf("html placeholder should have empty Content")
|
||||
}
|
||||
if string(okItem.Content) != "# ok" {
|
||||
t.Errorf("lake doc Content = %q, want %q", string(okItem.Content), "# ok")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_SkipsNonDocTypes(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/8/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 201, Type: "Sheet", Status: "1", Title: "S"},
|
||||
{ID: 202, Type: "Board", Status: "1", Title: "B"},
|
||||
{ID: 203, Type: "Thread", Status: "1", Title: "T"},
|
||||
{ID: 204, Type: "Doc", Status: "1", Title: "D", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/204", 200, v2DocDetailResponse{
|
||||
Data: v2DocDetail{ID: 204, Title: "D", Body: "text", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
})
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"8"}), []string{"8"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0].ExternalID != "204" {
|
||||
t.Errorf("expected only the Doc, got %+v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchIncremental_FirstSync(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B", ContentUpdatedAt: "2026-04-20T11:00:00Z"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}})
|
||||
f.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T11:00:00Z"}})
|
||||
|
||||
items, cursor, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchIncremental: %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Errorf("items = %d, want 2 on first sync", len(items))
|
||||
}
|
||||
if cursor == nil {
|
||||
t.Fatal("cursor must not be nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchIncremental_NoChanges(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}})
|
||||
|
||||
// First sync → establish cursor
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
|
||||
// Second sync with same cursor → 0 items
|
||||
items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
if len(items) != 0 {
|
||||
t.Errorf("expected 0 changed items, got %d", len(items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchIncremental_ReturnsOnlyChanged(t *testing.T) {
|
||||
// First sync: 2 docs, both at t0.
|
||||
f1 := newFakeYuque()
|
||||
f1.handleJSON("/api/v2/repos/11/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B", Slug: "b", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}})
|
||||
f1.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}})
|
||||
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"11"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: doc 1 unchanged, doc 2 has a newer ContentUpdatedAt.
|
||||
f2 := newFakeYuque()
|
||||
defer f2.Close()
|
||||
f2.handleJSON("/api/v2/repos/11/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B2", Slug: "b", ContentUpdatedAt: "2026-04-20T12:00:00Z"},
|
||||
}})
|
||||
// Only doc 2's detail should be fetched; if the implementation incorrectly
|
||||
// fetches doc 1, the test will still pass metadata-wise — but this handler
|
||||
// makes the expected single call clear.
|
||||
f2.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B2", Body: "b2 updated", Status: "1", ContentUpdatedAt: "2026-04-20T12:00:00Z"}})
|
||||
|
||||
items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f2, []string{"11"}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("expected exactly 1 changed item, got %d: %+v", len(items), items)
|
||||
}
|
||||
if items[0].ExternalID != "2" {
|
||||
t.Errorf("expected changed item ExternalID=2, got %q", items[0].ExternalID)
|
||||
}
|
||||
if string(items[0].Content) != "b2 updated" {
|
||||
t.Errorf("expected refreshed body, got %q", string(items[0].Content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchIncremental_DetectsDeletion(t *testing.T) {
|
||||
// First sync: 2 docs
|
||||
f1 := newFakeYuque()
|
||||
f1.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B", ContentUpdatedAt: "2026-04-20T11:00:00Z"},
|
||||
}})
|
||||
f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}})
|
||||
f1.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T11:00:00Z"}})
|
||||
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"10"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: doc 2 removed
|
||||
f2 := newFakeYuque()
|
||||
defer f2.Close()
|
||||
f2.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
|
||||
items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f2, []string{"10"}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
deleted := 0
|
||||
for _, it := range items {
|
||||
if it.IsDeleted && it.ExternalID == "2" {
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
if deleted != 1 {
|
||||
t.Errorf("expected 1 deletion for doc 2, got %d; items=%+v", deleted, items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_ListResources_ContinuesOnGroupFailure(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.mux = http.NewServeMux()
|
||||
f.server.Config.Handler = f.mux
|
||||
f.handleJSON("/api/v2/user", 200, v2UserResponse{Data: v2User{ID: 1, Login: "alice"}})
|
||||
f.handleJSON("/api/v2/users/alice/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 10, Slug: "me", Name: "Mine", Type: "Book", Namespace: "alice/me"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/users/1/groups", 200, v2GroupListResponse{Data: []v2Group{
|
||||
{ID: 100, Login: "team-ok"}, {ID: 101, Login: "team-forbidden"},
|
||||
}})
|
||||
f.handleJSON("/api/v2/groups/team-ok/repos", 200, v2RepoListResponse{Data: []v2Repo{
|
||||
{ID: 20, Slug: "ok", Name: "OK Book", Type: "Book", Namespace: "team-ok/ok"},
|
||||
}})
|
||||
// team-forbidden returns 403 — should be skipped, not abort the whole call.
|
||||
f.mux.HandleFunc("/api/v2/groups/team-forbidden/repos", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"message":"forbidden"}`))
|
||||
})
|
||||
|
||||
resources, err := NewConnector().ListResources(context.Background(), makeDSConfig(f, nil), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListResources should not fail on per-group error, got %v", err)
|
||||
}
|
||||
// Expect the 2 successful repos (personal + team-ok). team-forbidden is skipped.
|
||||
if len(resources) != 2 {
|
||||
t.Fatalf("expected 2 resources (personal + team-ok), got %d: %+v", len(resources), resources)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, r := range resources {
|
||||
names[r.Name] = true
|
||||
}
|
||||
if !names["Mine"] || !names["OK Book"] {
|
||||
t.Errorf("expected Mine + OK Book, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_FileNamePolicy(t *testing.T) {
|
||||
for _, tt := range []struct{ name, title, want string }{
|
||||
{"punctuation and extension", " \tA/B.md ", " \tA_B.md .md"},
|
||||
{"long title", strings.Repeat("测", 100), strings.Repeat("测", 66) + ".md"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
f.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{{
|
||||
ID: 101, Type: "Doc", Status: "1", Title: tt.title, ContentUpdatedAt: "2026-04-20T10:00:00Z",
|
||||
}}})
|
||||
f.handleJSON("/api/v2/repos/docs/101", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 101, Title: tt.title, Body: "# content", Format: "markdown", Status: "1",
|
||||
}})
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"7"}), []string{"7"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("got %d items, want 1", len(items))
|
||||
}
|
||||
if items[0].Title != tt.title || items[0].FileName != tt.want {
|
||||
t.Fatalf("title = %q, filename = %q; want %q, %q", items[0].Title, items[0].FileName, tt.title, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Regression for Tencent/WeKnora#3690: when an existing doc's detail fetch
|
||||
// fails after its content changed, the incremental cursor must keep the doc's
|
||||
// previously synced version instead of acknowledging the new one — otherwise
|
||||
// every later sync sees the doc as unchanged and never retries the fetch.
|
||||
func TestConnector_FetchIncremental_DetailFailureDoesNotAckVersion(t *testing.T) {
|
||||
// First sync: docs 1 and 2, both at t0.
|
||||
f1 := newFakeYuque()
|
||||
f1.handleJSON("/api/v2/repos/12/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B", Slug: "b", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z",
|
||||
}})
|
||||
f1.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z",
|
||||
}})
|
||||
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"12"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: doc 2 changed to t1 but its detail endpoint fails (mixed
|
||||
// success/failure — doc 1 is unchanged, so the batch is not all-failed).
|
||||
f2 := newFakeYuque()
|
||||
f2.handleJSON("/api/v2/repos/12/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B2", Slug: "b", ContentUpdatedAt: "2026-04-20T12:00:00Z"},
|
||||
}})
|
||||
f2.mux.HandleFunc("/api/v2/repos/docs/2", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest) // 4xx is non-retriable, bubbles up as an error
|
||||
_, _ = w.Write([]byte(`{"message":"broken"}`))
|
||||
})
|
||||
|
||||
items2, cursor2, err := NewConnector().FetchIncremental(
|
||||
context.Background(), makeDSConfig(f2, []string{"12"}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync must not fail on a single detail error, got %v", err)
|
||||
}
|
||||
f2.Close()
|
||||
|
||||
var placeholder *types.FetchedItem
|
||||
for i := range items2 {
|
||||
if items2[i].Metadata["error"] != "" && items2[i].ExternalID == "2" {
|
||||
placeholder = &items2[i]
|
||||
}
|
||||
}
|
||||
if placeholder == nil {
|
||||
t.Fatalf("expected an error placeholder for doc 2, got %+v", items2)
|
||||
}
|
||||
|
||||
// The cursor must still hold doc 2's previously synced version (t0), not
|
||||
// the failed t1: acknowledging t1 hid the doc from all future syncs (#3690).
|
||||
var cur2 yuqueCursor
|
||||
if b, merr := json.Marshal(cursor2.ConnectorCursor); merr != nil {
|
||||
t.Fatalf("encode cursor: %v", merr)
|
||||
} else if uerr := json.Unmarshal(b, &cur2); uerr != nil {
|
||||
t.Fatalf("decode cursor: %v", uerr)
|
||||
}
|
||||
if got := cur2.BookDocTimes["12"]["2"]; got != "2026-04-20T10:00:00Z" {
|
||||
t.Fatalf("cursor must keep doc 2's previous version after a failed detail fetch, got %q", got)
|
||||
}
|
||||
|
||||
// Third sync, endpoint recovered: doc 2 must be re-fetched because its
|
||||
// cursor entry (t0) still differs from the listing (t1).
|
||||
f3 := newFakeYuque()
|
||||
defer f3.Close()
|
||||
f3.handleJSON("/api/v2/repos/12/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "B2", Slug: "b", ContentUpdatedAt: "2026-04-20T12:00:00Z"},
|
||||
}})
|
||||
f3.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 2, Title: "B2", Body: "b2 recovered", Status: "1", ContentUpdatedAt: "2026-04-20T12:00:00Z",
|
||||
}})
|
||||
|
||||
items3, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f3, []string{"12"}), cursor2)
|
||||
if err != nil {
|
||||
t.Fatalf("third sync: %v", err)
|
||||
}
|
||||
if len(items3) != 1 || items3[0].ExternalID != "2" {
|
||||
t.Fatalf("expected recovered doc 2 to be re-fetched, got %+v", items3)
|
||||
}
|
||||
if string(items3[0].Content) != "b2 recovered" {
|
||||
t.Errorf("expected recovered body, got %q", string(items3[0].Content))
|
||||
}
|
||||
}
|
||||
|
||||
// Regression for Tencent/WeKnora#3690 (new-doc variant): a newly listed doc
|
||||
// whose detail fetch fails must not enter the cursor at all, so the next sync
|
||||
// still treats it as new and ingests it.
|
||||
func TestConnector_FetchIncremental_NewDocDetailFailureNotAcknowledged(t *testing.T) {
|
||||
// First sync: doc 1 only.
|
||||
f1 := newFakeYuque()
|
||||
f1.handleJSON("/api/v2/repos/13/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
}})
|
||||
f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z",
|
||||
}})
|
||||
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"13"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: new doc 2 appears (t1) but its detail fetch fails.
|
||||
f2 := newFakeYuque()
|
||||
f2.handleJSON("/api/v2/repos/13/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "New", Slug: "new", ContentUpdatedAt: "2026-04-20T12:00:00Z"},
|
||||
}})
|
||||
f2.mux.HandleFunc("/api/v2/repos/docs/2", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest) // 4xx is non-retriable, bubbles up as an error
|
||||
_, _ = w.Write([]byte(`{"message":"broken"}`))
|
||||
})
|
||||
|
||||
items2, cursor2, err := NewConnector().FetchIncremental(
|
||||
context.Background(), makeDSConfig(f2, []string{"13"}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync must not fail on a single detail error, got %v", err)
|
||||
}
|
||||
f2.Close()
|
||||
|
||||
found := false
|
||||
for _, it := range items2 {
|
||||
if it.Metadata["error"] != "" && it.ExternalID == "2" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected an error placeholder for doc 2, got %+v", items2)
|
||||
}
|
||||
|
||||
var cur2 yuqueCursor
|
||||
if b, merr := json.Marshal(cursor2.ConnectorCursor); merr != nil {
|
||||
t.Fatalf("encode cursor: %v", merr)
|
||||
} else if uerr := json.Unmarshal(b, &cur2); uerr != nil {
|
||||
t.Fatalf("decode cursor: %v", uerr)
|
||||
}
|
||||
if _, exists := cur2.BookDocTimes["13"]["2"]; exists {
|
||||
t.Fatal("failed new doc must not be acknowledged into the cursor")
|
||||
}
|
||||
if got := cur2.BookDocTimes["13"]["1"]; got != "2026-04-20T10:00:00Z" {
|
||||
t.Errorf("unchanged doc 1 cursor entry must be untouched, got %q", got)
|
||||
}
|
||||
|
||||
// Third sync, endpoint recovered: doc 2 is ingested as a new item.
|
||||
f3 := newFakeYuque()
|
||||
defer f3.Close()
|
||||
f3.handleJSON("/api/v2/repos/13/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"},
|
||||
{ID: 2, Type: "Doc", Status: "1", Title: "New", Slug: "new", ContentUpdatedAt: "2026-04-20T12:00:00Z"},
|
||||
}})
|
||||
f3.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: 2, Title: "New", Body: "new content", Status: "1", ContentUpdatedAt: "2026-04-20T12:00:00Z",
|
||||
}})
|
||||
|
||||
items3, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f3, []string{"13"}), cursor2)
|
||||
if err != nil {
|
||||
t.Fatalf("third sync: %v", err)
|
||||
}
|
||||
if len(items3) != 1 || items3[0].ExternalID != "2" {
|
||||
t.Fatalf("expected new doc 2 to be ingested after recovery, got %+v", items3)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
// paginationHopCap mirrors maxPaginationHops in client.go. It is spelled as a
|
||||
// literal so this file also compiles — and then fails on behaviour — against a
|
||||
// tree that has no guard at all.
|
||||
const paginationHopCap = 10000
|
||||
|
||||
// paginationBudget is how many requests the "always a full page" fakes below
|
||||
// serve before answering 400. A walk that lacks a guard therefore fails on the
|
||||
// budget error after paginationBudget+1 requests (and on the request-count
|
||||
// assertion) instead of spinning until the go test timeout.
|
||||
const paginationBudget = 300
|
||||
|
||||
// fullDocPage builds a full-ish page of docs with ids startID..startID+n-1.
|
||||
func fullDocPage(startID int64, n int) []v2Doc {
|
||||
docs := make([]v2Doc, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
docs = append(docs, v2Doc{
|
||||
ID: startID + int64(i),
|
||||
Type: "Doc",
|
||||
Status: "1",
|
||||
Title: fmt.Sprintf("D%d", startID+int64(i)),
|
||||
ContentUpdatedAt: "2026-04-20T00:00:00Z",
|
||||
})
|
||||
}
|
||||
return docs
|
||||
}
|
||||
|
||||
// fullRepoPage builds a full-ish page of repos with ids startID..startID+n-1.
|
||||
func fullRepoPage(startID int64, n int) []v2Repo {
|
||||
repos := make([]v2Repo, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
repos = append(repos, v2Repo{
|
||||
ID: startID + int64(i),
|
||||
Type: "Book",
|
||||
Namespace: fmt.Sprintf("alice/book-%d", startID+int64(i)),
|
||||
})
|
||||
}
|
||||
return repos
|
||||
}
|
||||
|
||||
// minimalPage renders a page of defaultPageSize id-only entries, so the hop cap
|
||||
// test can serve 10000 pages without materialising gigabytes of JSON.
|
||||
func minimalPage(prefix string, startID int64) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(`{"data":[`)
|
||||
for i := 0; i < defaultPageSize; i++ {
|
||||
if i > 0 {
|
||||
sb.WriteByte(',')
|
||||
}
|
||||
fmt.Fprintf(&sb, `{"%s":%d}`, prefix, startID+int64(i))
|
||||
}
|
||||
sb.WriteString(`]}`)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// alwaysFullPageServer answers every offset with the same full page: a gateway
|
||||
// or self-hosted deployment that ignores `offset`. Without a repeated-page
|
||||
// guard the walk keeps appending identical entries.
|
||||
func alwaysFullPageServer(t *testing.T, body interface{}) (*httptest.Server, *atomic.Int64) {
|
||||
t.Helper()
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if requests.Add(1) > paginationBudget {
|
||||
http.Error(w, "pagination guard missing: too many requests", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server, &requests
|
||||
}
|
||||
|
||||
// A docs listing whose meta.total is already covered by the first page must end
|
||||
// there. The fake keeps answering a full page for every offset, so before the
|
||||
// fix the walk ran until the fake's budget cut it off 300 requests later.
|
||||
func TestListBookDocs_StopsAtMetaTotal(t *testing.T) {
|
||||
resp := v2DocListResponse{Data: fullDocPage(1, defaultPageSize)}
|
||||
resp.Meta.Total = 5 // far below what this page alone hands out
|
||||
server, requests := alwaysFullPageServer(t, resp)
|
||||
|
||||
c := newClient(&Config{APIToken: "tok", BaseURL: server.URL})
|
||||
docs, err := c.ListBookDocs(context.Background(), 4242)
|
||||
|
||||
require.NoError(t, err, "meta.total covered by the first page must end the walk")
|
||||
require.Len(t, docs, defaultPageSize)
|
||||
require.EqualValues(t, 1, requests.Load(),
|
||||
"the walk must stop on the page that reaches meta.total")
|
||||
}
|
||||
|
||||
// A full page whose first id repeats the previous page means the offset walk is
|
||||
// not making progress. Each endpoint must report that instead of appending the
|
||||
// same page forever.
|
||||
func TestPaginationStopsOnRepeatedPage(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path string
|
||||
call func(context.Context, *client) (int, error)
|
||||
}{
|
||||
{
|
||||
name: "book docs without meta.total",
|
||||
path: "/api/v2/repos/4242/docs",
|
||||
call: func(ctx context.Context, c *client) (int, error) {
|
||||
docs, err := c.ListBookDocs(ctx, 4242)
|
||||
return len(docs), err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user repos",
|
||||
path: "/api/v2/users/alice/repos",
|
||||
call: func(ctx context.Context, c *client) (int, error) {
|
||||
repos, err := c.ListUserRepos(ctx, "alice")
|
||||
return len(repos), err
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var body interface{}
|
||||
if strings.HasSuffix(tc.path, "/docs") {
|
||||
body = v2DocListResponse{Data: fullDocPage(1, defaultPageSize)}
|
||||
} else {
|
||||
body = v2RepoListResponse{Data: fullRepoPage(1, defaultPageSize)}
|
||||
}
|
||||
server, requests := alwaysFullPageServer(t, body)
|
||||
|
||||
c := newClient(&Config{APIToken: "tok", BaseURL: server.URL})
|
||||
n, err := tc.call(context.Background(), c)
|
||||
|
||||
require.Error(t, err, "a repeated full page must not be followed forever")
|
||||
require.Contains(t, err.Error(), "repeated page")
|
||||
require.Zero(t, n, "a stalled walk must not hand back a partial listing")
|
||||
require.LessOrEqual(t, requests.Load(), int64(2),
|
||||
"the guard must reject the repeated page on the second request")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A server that never repeats an id but also never returns a short page can only
|
||||
// be stopped by the hop cap. It must be reported, and the log must carry it too:
|
||||
// visually this failure looks like a healthy, still-running sync.
|
||||
func TestPaginationHopCapStopsWalk(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
call func(context.Context, *client) error
|
||||
}{
|
||||
{
|
||||
name: "book docs",
|
||||
call: func(ctx context.Context, c *client) error {
|
||||
_, err := c.ListBookDocs(ctx, 4242)
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user repos",
|
||||
call: func(ctx context.Context, c *client) error {
|
||||
_, err := c.ListUserRepos(ctx, "alice")
|
||||
return err
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n := requests.Add(1)
|
||||
if n > paginationHopCap+10 {
|
||||
http.Error(w, "hop cap missing: too many requests", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
offset, err := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||
if err != nil {
|
||||
http.Error(w, "unexpected offset", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Fresh ids on every page and no meta.total, so only the hop cap
|
||||
// can end the walk.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(minimalPage("id", int64(offset)+1)))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
c := newClient(&Config{APIToken: "tok", BaseURL: server.URL})
|
||||
|
||||
var logs bytes.Buffer
|
||||
logger.SetOutput(&logs)
|
||||
t.Cleanup(logger.ConfigureFromEnv)
|
||||
|
||||
err := tc.call(context.Background(), c)
|
||||
|
||||
require.ErrorContains(t, err, "pagination exceeded 10000 pages")
|
||||
require.EqualValues(t, paginationHopCap, requests.Load())
|
||||
require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
|
||||
"hitting the hop cap must leave a warning in the log")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// pagedServer serves `total` items in defaultPageSize-sized offset pages, with
|
||||
// the docs response advertising meta.total. It is the well-behaved listing the
|
||||
// guards must not disturb.
|
||||
func pagedServer(t *testing.T, kind string, total int) (*httptest.Server, *atomic.Int64) {
|
||||
t.Helper()
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
offset, err := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||
if err != nil {
|
||||
http.Error(w, "unexpected offset", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
size := total - offset
|
||||
if size > defaultPageSize {
|
||||
size = defaultPageSize
|
||||
}
|
||||
if size < 0 {
|
||||
size = 0
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if kind == "docs" {
|
||||
resp := v2DocListResponse{Data: fullDocPage(int64(offset)+1, size)}
|
||||
resp.Meta.Total = total
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(v2RepoListResponse{Data: fullRepoPage(int64(offset)+1, size)})
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server, &requests
|
||||
}
|
||||
|
||||
// The guards must not truncate a listing that genuinely spans several pages.
|
||||
func TestPaginationCollectsRealPages(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
kind string
|
||||
total int
|
||||
wantReqs int64
|
||||
call func(context.Context, *client) (int, error)
|
||||
}{
|
||||
{
|
||||
name: "docs reaching meta.total exactly",
|
||||
kind: "docs",
|
||||
total: 2 * defaultPageSize,
|
||||
wantReqs: 2,
|
||||
call: func(ctx context.Context, c *client) (int, error) {
|
||||
docs, err := c.ListBookDocs(ctx, 4242)
|
||||
return len(docs), err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "docs with a short final page",
|
||||
kind: "docs",
|
||||
total: defaultPageSize + 30,
|
||||
wantReqs: 2,
|
||||
call: func(ctx context.Context, c *client) (int, error) {
|
||||
docs, err := c.ListBookDocs(ctx, 4242)
|
||||
return len(docs), err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "repos with a short final page",
|
||||
kind: "repos",
|
||||
total: defaultPageSize + 30,
|
||||
wantReqs: 2,
|
||||
call: func(ctx context.Context, c *client) (int, error) {
|
||||
repos, err := c.ListUserRepos(ctx, "alice")
|
||||
return len(repos), err
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server, requests := pagedServer(t, tc.kind, tc.total)
|
||||
|
||||
c := newClient(&Config{APIToken: "tok", BaseURL: server.URL})
|
||||
got, err := tc.call(context.Background(), c)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.total, got, "every item of a real multi-page listing must survive")
|
||||
require.EqualValues(t, tc.wantReqs, requests.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,676 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
func makeDSConfigWithSettings(
|
||||
f *fakeYuque, resourceIDs []string, settings map[string]interface{},
|
||||
) *types.DataSourceConfig {
|
||||
cfg := makeDSConfig(f, resourceIDs)
|
||||
cfg.Settings = settings
|
||||
return cfg
|
||||
}
|
||||
|
||||
func tocTitle(uuid, parent, title string) v2TOCNode {
|
||||
return v2TOCNode{UUID: uuid, Type: tocNodeTypeTitle, Title: title, ParentUUID: parent}
|
||||
}
|
||||
|
||||
func tocDoc(uuid, parent string, docID int64, title string) v2TOCNode {
|
||||
return v2TOCNode{
|
||||
UUID: uuid, Type: tocNodeTypeDoc, Title: title,
|
||||
ParentUUID: parent, DocID: flexibleDocID(docID),
|
||||
}
|
||||
}
|
||||
|
||||
// --- buildTOCPaths ---
|
||||
|
||||
func TestBuildTOCPaths_EmptyAndTitleOnly(t *testing.T) {
|
||||
for name, nodes := range map[string][]v2TOCNode{
|
||||
"nil": nil,
|
||||
"empty": {},
|
||||
"title-only": {tocTitle("t1", "", "Group"), tocTitle("t2", "t1", "Nested")},
|
||||
} {
|
||||
segs, inTOC := buildTOCPaths(nodes)
|
||||
if len(segs) != 0 || len(inTOC) != 0 {
|
||||
t.Errorf("%s: want empty maps, got segs=%v inTOC=%v", name, segs, inTOC)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTOCPaths_SingleLevel(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "Group"),
|
||||
tocDoc("d1", "t1", 101, "Doc"),
|
||||
})
|
||||
if !inTOC[101] {
|
||||
t.Fatal("inTOC[101] should be true")
|
||||
}
|
||||
if got := segs[101]; len(got) != 1 || got[0] != "Group" {
|
||||
t.Errorf("segs[101] = %v, want [Group]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTOCPaths_MultiLevel(t *testing.T) {
|
||||
segs, _ := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "A"),
|
||||
tocTitle("t2", "t1", "B"),
|
||||
tocDoc("d1", "t2", 101, "Doc"),
|
||||
})
|
||||
got := segs[101]
|
||||
if len(got) != 2 || got[0] != "A" || got[1] != "B" {
|
||||
t.Errorf("segs[101] = %v, want [A B] (root first)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A DOC nested under another DOC contributes the parent document's title as an
|
||||
// extra path segment.
|
||||
func TestBuildTOCPaths_DocNestedUnderDoc(t *testing.T) {
|
||||
segs, _ := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "A"),
|
||||
tocDoc("d1", "t1", 101, "Parent doc"),
|
||||
tocDoc("d2", "d1", 102, "Child doc"),
|
||||
})
|
||||
got := segs[102]
|
||||
if len(got) != 2 || got[0] != "A" || got[1] != "Parent doc" {
|
||||
t.Errorf("segs[102] = %v, want [A Parent doc]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A document that appears in the TOC without any enclosing group is still "in
|
||||
// the TOC" — the distinction that keeps toc_only from dropping it.
|
||||
func TestBuildTOCPaths_InTOCWithoutGroup(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocDoc("d1", "", 101, "Loose doc"),
|
||||
})
|
||||
if !inTOC[101] {
|
||||
t.Error("inTOC[101] should be true: the doc is in the TOC node list")
|
||||
}
|
||||
if _, ok := segs[101]; ok {
|
||||
t.Errorf("segs[101] should be absent for a group-less doc, got %v", segs[101])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTOCPaths_DanglingParent(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocDoc("d1", "does-not-exist", 101, "Doc"),
|
||||
})
|
||||
if !inTOC[101] {
|
||||
t.Error("inTOC[101] should be true")
|
||||
}
|
||||
if _, ok := segs[101]; ok {
|
||||
t.Errorf("segs[101] should be absent, got %v", segs[101])
|
||||
}
|
||||
}
|
||||
|
||||
// A cyclic parent_uuid chain must terminate rather than loop forever.
|
||||
func TestBuildTOCPaths_CycleTerminates(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("a", "b", "A"),
|
||||
tocTitle("b", "a", "B"),
|
||||
tocDoc("d", "a", 101, "Doc"),
|
||||
})
|
||||
if !inTOC[101] {
|
||||
t.Error("inTOC[101] should be true")
|
||||
}
|
||||
// Two titles before the cycle is detected; the exact length matters less
|
||||
// than the fact that this returns at all.
|
||||
if got := len(segs[101]); got != 2 {
|
||||
t.Errorf("len(segs[101]) = %d, want 2 (walk must stop at the cycle)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A "/" in a group title must not become an extra nesting level: segments are
|
||||
// sanitised individually, before they are ever joined.
|
||||
func TestBuildTOCPaths_SanitizesEachSegment(t *testing.T) {
|
||||
segs, _ := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "A/B"),
|
||||
tocDoc("d1", "t1", 101, "Doc"),
|
||||
})
|
||||
got := segs[101]
|
||||
if len(got) != 1 || got[0] != "A_B" {
|
||||
t.Errorf("segs[101] = %v, want [A_B]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTOCPaths_SkipsNonDocAndEmptyID(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "Group"),
|
||||
{UUID: "d0", Type: tocNodeTypeDoc, Title: "No id"}, // doc_id absent → 0
|
||||
{UUID: "d1", Type: "SHEET", Title: "Sheet", ParentUUID: "t1"}, // not a DOC node
|
||||
})
|
||||
if len(segs) != 0 || len(inTOC) != 0 {
|
||||
t.Errorf("want empty maps, got segs=%v inTOC=%v", segs, inTOC)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTOCPaths_DuplicateDocID(t *testing.T) {
|
||||
segs, inTOC := buildTOCPaths([]v2TOCNode{
|
||||
tocTitle("t1", "", "A"),
|
||||
tocTitle("t2", "", "B"),
|
||||
tocDoc("d1", "t1", 101, "Doc"),
|
||||
tocDoc("d2", "t2", 101, "Doc"),
|
||||
})
|
||||
if !inTOC[101] {
|
||||
t.Error("inTOC[101] should be true")
|
||||
}
|
||||
// Last write wins; what matters is that the map stays well-formed.
|
||||
if len(segs[101]) != 1 {
|
||||
t.Errorf("segs[101] = %v, want a single segment", segs[101])
|
||||
}
|
||||
}
|
||||
|
||||
// --- flexibleDocID ---
|
||||
|
||||
func TestFlexibleDocID_Unmarshal(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want int64
|
||||
wantErr bool
|
||||
}{
|
||||
{"integer", `{"doc_id":259589930}`, 259589930, false},
|
||||
{"string", `{"doc_id":"259589930"}`, 259589930, false},
|
||||
{"empty string (TITLE node)", `{"doc_id":""}`, 0, false},
|
||||
{"null", `{"doc_id":null}`, 0, false},
|
||||
{"missing", `{}`, 0, false},
|
||||
{"padded string", `{"doc_id":" 42 "}`, 42, false},
|
||||
{"boolean", `{"doc_id":true}`, 0, true},
|
||||
{"non-numeric string", `{"doc_id":"abc"}`, 0, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var n v2TOCNode
|
||||
err := json.Unmarshal([]byte(tc.raw), &n)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for %s", tc.raw)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", tc.raw, err)
|
||||
}
|
||||
if int64(n.DocID) != tc.want {
|
||||
t.Errorf("DocID = %d, want %d", int64(n.DocID), tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The real API mixes node shapes in one response; the whole list must decode.
|
||||
func TestV2TOCResponse_RealisticPayload(t *testing.T) {
|
||||
raw := `{"data":[
|
||||
{"uuid":"t1","type":"TITLE","title":"Group","doc_id":"","parent_uuid":""},
|
||||
{"uuid":"d1","type":"DOC","title":"Doc","doc_id":259589930,"parent_uuid":"t1"},
|
||||
{"uuid":"d2","type":"DOC","title":"Loose","doc_id":"267830135","parent_uuid":""}
|
||||
]}`
|
||||
var resp v2TOCResponse
|
||||
if err := json.Unmarshal([]byte(raw), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
segs, inTOC := buildTOCPaths(resp.Data)
|
||||
if !inTOC[259589930] || !inTOC[267830135] {
|
||||
t.Errorf("inTOC = %v, want both docs", inTOC)
|
||||
}
|
||||
if got := segs[259589930]; len(got) != 1 || got[0] != "Group" {
|
||||
t.Errorf("segs[259589930] = %v, want [Group]", got)
|
||||
}
|
||||
if _, ok := segs[267830135]; ok {
|
||||
t.Errorf("segs[267830135] should be absent, got %v", segs[267830135])
|
||||
}
|
||||
}
|
||||
|
||||
// --- buildFolderFileName ---
|
||||
|
||||
// The regression guard: with default settings the emitted FileName must be
|
||||
// exactly what previous releases produced, byte for byte.
|
||||
func TestBuildFolderFileName_DefaultIsUnchanged(t *testing.T) {
|
||||
got := buildFolderFileName(defaultFolderSettings(), true, "Book", []string{"Group"}, "Title")
|
||||
want := datasource.SanitizeFileName("Title") + ".md"
|
||||
if got != want {
|
||||
t.Errorf("FileName = %q, want %q", got, want)
|
||||
}
|
||||
for _, bookName := range []string{"", "Book"} {
|
||||
for _, segs := range [][]string{nil, {"A"}, {"A", "B"}} {
|
||||
if got := buildFolderFileName(folderSettings{}, true, bookName, segs, "T"); got != "T.md" {
|
||||
t.Errorf("zero-value settings: FileName = %q, want %q", got, "T.md")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildFolderFileName_TOCMode(t *testing.T) {
|
||||
tocMode := folderSettings{FolderMode: folderModeTOC}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
settings folderSettings
|
||||
tocOK bool
|
||||
bookName string
|
||||
segs []string
|
||||
want string
|
||||
}{
|
||||
{"book + group", tocMode, true, "My Book", []string{"A", "B"}, "My Book/A/B/Doc.md"},
|
||||
{"book only (doc not in TOC)", tocMode, true, "My Book", nil, "My Book/Doc.md"},
|
||||
{"empty book name", tocMode, true, "", []string{"A"}, "A/Doc.md"},
|
||||
{"book name needs sanitising", tocMode, true, "A/B", nil, "A_B/Doc.md"},
|
||||
{"toc unavailable degrades to flat", tocMode, false, "My Book", []string{"A"}, "Doc.md"},
|
||||
{"default mode stays flat", defaultFolderSettings(), true, "My Book", []string{"A"}, "Doc.md"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := buildFolderFileName(tc.settings, tc.tocOK, tc.bookName, tc.segs, "Doc"); got != tc.want {
|
||||
t.Errorf("FileName = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- parseFolderSettings ---
|
||||
|
||||
func TestParseFolderSettings_Defaults(t *testing.T) {
|
||||
got := parseFolderSettings(context.Background(), &types.DataSourceConfig{})
|
||||
want := defaultFolderSettings()
|
||||
if got != want {
|
||||
t.Errorf("got %+v, want %+v", got, want)
|
||||
}
|
||||
if got.FolderMode != folderModeNone {
|
||||
t.Errorf("FolderMode = %q, want %q (upgrades must not change behaviour)", got.FolderMode, folderModeNone)
|
||||
}
|
||||
if got := parseFolderSettings(context.Background(), nil); got != want {
|
||||
t.Errorf("nil config: got %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFolderSettings_ReadsValues(t *testing.T) {
|
||||
got := parseFolderSettings(context.Background(), &types.DataSourceConfig{
|
||||
Settings: map[string]interface{}{
|
||||
"folder_mode": "toc",
|
||||
"toc_only": true,
|
||||
},
|
||||
})
|
||||
if got.FolderMode != folderModeTOC || !got.TOCOnly {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFolderSettings_TolerantOfBadInput(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
settings map[string]interface{}
|
||||
want folderSettings
|
||||
}{
|
||||
{"unknown mode", map[string]interface{}{"folder_mode": "bogus"}, defaultFolderSettings()},
|
||||
{"wrong type for mode", map[string]interface{}{"folder_mode": 42}, defaultFolderSettings()},
|
||||
{
|
||||
"string bools",
|
||||
map[string]interface{}{"toc_only": "true"},
|
||||
folderSettings{FolderMode: folderModeNone, TOCOnly: true},
|
||||
},
|
||||
{"unrecognised bool", map[string]interface{}{"toc_only": "maybe"}, defaultFolderSettings()},
|
||||
{
|
||||
"mixed case mode",
|
||||
map[string]interface{}{"folder_mode": " TOC "},
|
||||
folderSettings{FolderMode: folderModeTOC},
|
||||
},
|
||||
{
|
||||
// Unknown keys are ignored rather than failing the sync — settings
|
||||
// arrive from JSON, and a typo must not take a data source down.
|
||||
"unknown key is ignored",
|
||||
map[string]interface{}{"folder_mode": "toc", "no_such_setting": false},
|
||||
folderSettings{FolderMode: folderModeTOC},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := parseFolderSettings(context.Background(), &types.DataSourceConfig{Settings: tc.settings})
|
||||
if got != tc.want {
|
||||
t.Errorf("got %+v, want %+v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- FetchAll integration ---
|
||||
|
||||
const testTS = "2026-04-20T10:00:00Z"
|
||||
|
||||
// fakeBookDocs wires book 7 with three documents: 101 sits under a group, 102
|
||||
// appears in the TOC without any group, and 103 is absent from the TOC.
|
||||
//
|
||||
// FileName is derived from the *list* endpoint's title, so the assertions below
|
||||
// use those (Grouped / Loose / Unfiled) rather than the detail titles.
|
||||
func fakeBookDocs(f *fakeYuque) {
|
||||
f.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 101, Type: "Doc", Status: "1", Title: "Grouped", Slug: "g", BookID: 7, ContentUpdatedAt: testTS},
|
||||
{ID: 102, Type: "Doc", Status: "1", Title: "Loose", Slug: "l", BookID: 7, ContentUpdatedAt: testTS},
|
||||
{ID: 103, Type: "Doc", Status: "1", Title: "Unfiled", Slug: "u", BookID: 7, ContentUpdatedAt: testTS},
|
||||
}})
|
||||
for _, d := range []struct {
|
||||
id int64
|
||||
title string
|
||||
}{{101, "Grouped"}, {102, "Loose"}, {103, "Unfiled"}} {
|
||||
f.handleJSON(docDetailPath(d.id), 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: d.id, Title: d.title, Body: "# body", Format: "markdown", Status: "1",
|
||||
ContentUpdatedAt: testTS,
|
||||
Book: v2Repo{ID: 7, Name: "My Book", Namespace: "alice/demo"},
|
||||
}})
|
||||
}
|
||||
}
|
||||
|
||||
// fakeBookTOC registers the TOC endpoint for book 7. A ServeMux panics on a
|
||||
// duplicate pattern, so this is registered exactly once per test.
|
||||
func fakeBookTOC(f *fakeYuque, status int) {
|
||||
f.handleJSON("/api/v2/repos/7/toc", status, v2TOCResponse{Data: []v2TOCNode{
|
||||
tocTitle("t1", "", "Group"),
|
||||
tocDoc("d1", "t1", 101, "Grouped"),
|
||||
tocDoc("d2", "", 102, "Loose"),
|
||||
}})
|
||||
}
|
||||
|
||||
func docDetailPath(id int64) string {
|
||||
return "/api/v2/repos/docs/" + strconv.FormatInt(id, 10)
|
||||
}
|
||||
|
||||
func itoa(v int64) string { return strconv.FormatInt(v, 10) }
|
||||
|
||||
func fileNames(items []types.FetchedItem) map[string]string {
|
||||
out := make(map[string]string, len(items))
|
||||
for _, it := range items {
|
||||
out[it.ExternalID] = it.FileName
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestConnector_FetchAll_TOCPaths(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
fakeBookDocs(f)
|
||||
fakeBookTOC(f, 200)
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(),
|
||||
makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{"folder_mode": "toc"}),
|
||||
[]string{"7"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
got := fileNames(items)
|
||||
want := map[string]string{
|
||||
"101": "My Book/Group/Grouped.md", // grouped document
|
||||
"102": "My Book/Loose.md", // in the TOC, no group → book segment only
|
||||
"103": "My Book/Unfiled.md", // not in the TOC → book segment only
|
||||
}
|
||||
for id, wantName := range want {
|
||||
if got[id] != wantName {
|
||||
t.Errorf("doc %s: FileName = %q, want %q", id, got[id], wantName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without settings the connector must behave exactly as before: flat names.
|
||||
func TestConnector_FetchAll_DefaultSettingsFlat(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
fakeBookDocs(f)
|
||||
fakeBookTOC(f, 200) // present but must be ignored without folder_mode=toc
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"7"}), []string{"7"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
want := map[string]string{"101": "Grouped.md", "102": "Loose.md", "103": "Unfiled.md"}
|
||||
got := fileNames(items)
|
||||
for id, wantName := range want {
|
||||
if got[id] != wantName {
|
||||
t.Errorf("doc %s: FileName = %q, want %q", id, got[id], wantName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// toc_only must drop documents absent from the TOC but keep a group-less
|
||||
// document that is present in it. The latter is the case most likely to
|
||||
// regress, since its derived path is empty.
|
||||
func TestConnector_FetchAll_TOCOnly(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
fakeBookDocs(f)
|
||||
fakeBookTOC(f, 200)
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(),
|
||||
makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), []string{"7"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
got := fileNames(items)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("kept %d docs, want 2 (101 grouped + 102 group-less); got %v", len(got), got)
|
||||
}
|
||||
if _, ok := got["101"]; !ok {
|
||||
t.Error("doc 101 (grouped) should be kept")
|
||||
}
|
||||
if _, ok := got["102"]; !ok {
|
||||
t.Error("doc 102 (in TOC but group-less) must be kept — not filtered by an empty path")
|
||||
}
|
||||
if _, ok := got["103"]; ok {
|
||||
t.Error("doc 103 (absent from TOC) should be filtered out")
|
||||
}
|
||||
}
|
||||
|
||||
// toc_only is an admission filter, not a reaper. A document that was already
|
||||
// ingested and is then filtered out must not be reported as deleted: Yuque's
|
||||
// own web UI cannot show documents created through the API that were never
|
||||
// attached to the TOC, so removing them here would leave their content
|
||||
// reachable from neither side.
|
||||
func TestConnector_FetchIncremental_TOCOnlyDoesNotDelete(t *testing.T) {
|
||||
// First sync: folder paths on, no admission filter — all three land.
|
||||
f1 := newFakeYuque()
|
||||
fakeBookDocs(f1)
|
||||
fakeBookTOC(f1, 200)
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{"folder_mode": "toc"}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: same source, now with toc_only. Doc 103 is absent from the
|
||||
// TOC so it is filtered, but it is still present in the book's document list.
|
||||
f2 := newFakeYuque()
|
||||
defer f2.Close()
|
||||
fakeBookDocs(f2)
|
||||
fakeBookTOC(f2, 200)
|
||||
|
||||
items, _, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
for _, it := range items {
|
||||
if it.ExternalID == "103" {
|
||||
t.Errorf("doc 103 was filtered by toc_only but is still reported "+
|
||||
"(IsDeleted=%t); an admission filter must not turn into a deletion", it.IsDeleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Admitting a previously filtered document must ingest it. A filtered document
|
||||
// is deliberately kept out of the cursor, so attaching it to the TOC later — or
|
||||
// switching toc_only off — has to read as new rather than as unchanged.
|
||||
func TestConnector_FetchIncremental_AdmitsPreviouslyFilteredDoc(t *testing.T) {
|
||||
// First sync with toc_only on: doc 103 is absent from the TOC and filtered.
|
||||
f1 := newFakeYuque()
|
||||
fakeBookDocs(f1)
|
||||
fakeBookTOC(f1, 200)
|
||||
items1, cursor1, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
for _, it := range items1 {
|
||||
if it.ExternalID == "103" {
|
||||
t.Fatalf("doc 103 should have been filtered on the first sync: %+v", it)
|
||||
}
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Second sync: doc 103 has been attached to the TOC. Its content is
|
||||
// unchanged, so only the admission decision can bring it in.
|
||||
f2 := newFakeYuque()
|
||||
defer f2.Close()
|
||||
fakeBookDocs(f2)
|
||||
f2.handleJSON("/api/v2/repos/7/toc", 200, v2TOCResponse{Data: []v2TOCNode{
|
||||
tocTitle("t1", "", "Group"),
|
||||
tocDoc("d1", "t1", 101, "Grouped"),
|
||||
tocDoc("d2", "", 102, "Loose"),
|
||||
tocDoc("d3", "t1", 103, "Unfiled"),
|
||||
}})
|
||||
|
||||
items2, _, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
var admitted bool
|
||||
for _, it := range items2 {
|
||||
if it.ExternalID != "103" || it.IsDeleted {
|
||||
continue
|
||||
}
|
||||
admitted = true
|
||||
if want := "My Book/Group/Unfiled.md"; it.FileName != want {
|
||||
t.Errorf("doc 103: FileName = %q, want %q", it.FileName, want)
|
||||
}
|
||||
}
|
||||
if !admitted {
|
||||
t.Errorf("doc 103 was attached to the TOC but was not ingested; items=%+v", items2)
|
||||
}
|
||||
}
|
||||
|
||||
// A document that really is gone from the source must still be reported — the
|
||||
// admission filter must not have disabled deletion detection.
|
||||
func TestConnector_FetchIncremental_StillDetectsRealDeletion(t *testing.T) {
|
||||
f1 := newFakeYuque()
|
||||
fakeBookDocs(f1)
|
||||
fakeBookTOC(f1, 200)
|
||||
_, cursor1, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f1, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
f1.Close()
|
||||
|
||||
// Doc 101 disappears from the source entirely.
|
||||
f2 := newFakeYuque()
|
||||
defer f2.Close()
|
||||
f2.handleJSON("/api/v2/repos/7/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{ID: 102, Type: "Doc", Status: "1", Title: "Loose", Slug: "l", BookID: 7, ContentUpdatedAt: testTS},
|
||||
}})
|
||||
fakeBookTOC(f2, 200)
|
||||
|
||||
items, _, err := NewConnector().FetchIncremental(context.Background(),
|
||||
makeDSConfigWithSettings(f2, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), cursor1)
|
||||
if err != nil {
|
||||
t.Fatalf("second sync: %v", err)
|
||||
}
|
||||
deleted := 0
|
||||
for _, it := range items {
|
||||
if it.IsDeleted && it.ExternalID == "101" {
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
if deleted != 1 {
|
||||
t.Errorf("expected doc 101 to be reported as deleted once, got %d; items=%+v", deleted, items)
|
||||
}
|
||||
}
|
||||
|
||||
// If the TOC endpoint is unavailable, toc_only must not filter anything —
|
||||
// otherwise an outage would silently drop the whole book.
|
||||
func TestConnector_FetchAll_TOCUnavailableDegrades(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
fakeBookDocs(f)
|
||||
// Older Yuque deployments have no TOC endpoint at all → 404.
|
||||
fakeBookTOC(f, 404)
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(),
|
||||
makeDSConfigWithSettings(f, []string{"7"}, map[string]interface{}{
|
||||
"folder_mode": "toc", "toc_only": true,
|
||||
}), []string{"7"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll must not fail when the TOC is unavailable: %v", err)
|
||||
}
|
||||
if len(items) != 3 {
|
||||
t.Fatalf("kept %d docs, want 3 (no filtering without a TOC)", len(items))
|
||||
}
|
||||
want := map[string]string{"101": "Grouped.md", "102": "Loose.md", "103": "Unfiled.md"}
|
||||
got := fileNames(items)
|
||||
for id, wantName := range want {
|
||||
if got[id] != wantName {
|
||||
t.Errorf("doc %s: FileName = %q, want flat %q", id, got[id], wantName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A multi-book sync must not merge identically named top-level groups.
|
||||
func TestConnector_FetchAll_SeparatesBooksWithSameGroupName(t *testing.T) {
|
||||
f := newFakeYuque()
|
||||
defer f.Close()
|
||||
for _, book := range []struct {
|
||||
id int64
|
||||
name string
|
||||
}{
|
||||
{7, "Book One"},
|
||||
{8, "Book Two"},
|
||||
} {
|
||||
docID := book.id * 10
|
||||
f.handleJSON("/api/v2/repos/"+itoa(book.id)+"/docs", 200, v2DocListResponse{Data: []v2Doc{
|
||||
{
|
||||
ID: docID, Type: "Doc", Status: "1", Title: "Doc", Slug: "d", BookID: book.id,
|
||||
ContentUpdatedAt: testTS,
|
||||
},
|
||||
}})
|
||||
f.handleJSON("/api/v2/repos/"+itoa(book.id)+"/toc", 200, v2TOCResponse{Data: []v2TOCNode{
|
||||
tocTitle("t1", "", "Shared"),
|
||||
tocDoc("d1", "t1", docID, "Doc"),
|
||||
}})
|
||||
f.handleJSON(docDetailPath(docID), 200, v2DocDetailResponse{Data: v2DocDetail{
|
||||
ID: docID, Title: "Doc", Body: "x", Format: "markdown", Status: "1",
|
||||
ContentUpdatedAt: testTS,
|
||||
Book: v2Repo{ID: book.id, Name: book.name, Namespace: "alice/b"},
|
||||
}})
|
||||
}
|
||||
|
||||
items, err := NewConnector().FetchAll(context.Background(),
|
||||
makeDSConfigWithSettings(f, []string{"7", "8"}, map[string]interface{}{"folder_mode": "toc"}),
|
||||
[]string{"7", "8"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll: %v", err)
|
||||
}
|
||||
got := fileNames(items)
|
||||
if got["70"] != "Book One/Shared/Doc.md" {
|
||||
t.Errorf("book 7: FileName = %q, want %q", got["70"], "Book One/Shared/Doc.md")
|
||||
}
|
||||
if got["80"] != "Book Two/Shared/Doc.md" {
|
||||
t.Errorf("book 8: FileName = %q, want %q", got["80"], "Book Two/Shared/Doc.md")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// truncate caps a connector error preview with a plain byte slice. Connector error
|
||||
// text is often Chinese, so the cut can land inside a multi-byte rune; these
|
||||
// previews reach sync_logs and data_sources through the sync error message, and
|
||||
// PostgreSQL rejects the invalid UTF-8 that a partial rune produces.
|
||||
func TestTruncateKeepsValidUTF8AcrossCaps(t *testing.T) {
|
||||
body := strings.Repeat("错", 400)
|
||||
for _, maxLen := range []int{499, 500, 501, 1000, 1} {
|
||||
got := truncate(body, maxLen)
|
||||
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("%s(%d): preview is not valid UTF-8", "truncate", maxLen)
|
||||
}
|
||||
if len(got) > maxLen+len("...") {
|
||||
t.Fatalf("%s(%d): preview is %d bytes", "truncate", maxLen, len(got))
|
||||
}
|
||||
if !strings.HasPrefix(body, strings.TrimSuffix(got, "...")) {
|
||||
t.Fatalf("%s(%d): preview is not a prefix of the input", "truncate", maxLen)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateLeavesShortAndASCIIInputAlone(t *testing.T) {
|
||||
for _, s := range []string{"", "ok", "服务返回 500", "短"} {
|
||||
if got := truncate(s, 500); got != s {
|
||||
t.Fatalf("%s(%q, 500) = %q, want the input unchanged", "truncate", s, got)
|
||||
}
|
||||
}
|
||||
if got := truncate("abcdef", 3); got != "abc..." {
|
||||
t.Fatalf("truncate keeps the ASCII cut: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
// Package yuque implements the Yuque (语雀) data source connector for Academy.
|
||||
//
|
||||
// It syncs documents from personal and group knowledge bases (books/repos) into Academy
|
||||
// knowledge bases, preserving Markdown formatting.
|
||||
//
|
||||
// Yuque API docs:
|
||||
// - Authentication: X-Auth-Token header, personal token from https://www.yuque.com/settings/tokens
|
||||
// - User: GET /api/v2/user
|
||||
// - Groups: GET /api/v2/users/{id}/groups
|
||||
// - Repos: GET /api/v2/users/{login}/repos, GET /api/v2/groups/{login}/repos
|
||||
// - Docs: GET /api/v2/repos/{book_id}/docs (list), GET /api/v2/repos/docs/{id} (detail)
|
||||
//
|
||||
// Known limitations (v1):
|
||||
// - Only syncs type=Doc (Sheet/Thread/Board/Table skipped)
|
||||
// - Only syncs status="1" (published), drafts skipped
|
||||
// - Private-book images (CDN URLs with auth) may fail to load
|
||||
// - Lake editor may leave non-standard markdown (anchors, sized image attrs)
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// DefaultBaseURL is the Yuque public cloud API base URL.
|
||||
const DefaultBaseURL = "https://www.yuque.com"
|
||||
|
||||
// Config holds Yuque-specific configuration.
|
||||
type Config struct {
|
||||
// APIToken is a personal token from Yuque settings → tokens.
|
||||
APIToken string `json:"api_token"`
|
||||
|
||||
// BaseURL is the Yuque deployment base URL (default: https://www.yuque.com).
|
||||
// For enterprise/private deployments, use the company's yuque domain.
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
}
|
||||
|
||||
// GetBaseURL returns the normalized base URL:
|
||||
// - empty → DefaultBaseURL
|
||||
// - missing scheme → prepend "https://"
|
||||
// - trailing slash → stripped
|
||||
func (c *Config) GetBaseURL() string {
|
||||
url := strings.TrimSpace(c.BaseURL)
|
||||
if url == "" {
|
||||
return DefaultBaseURL
|
||||
}
|
||||
if !strings.Contains(url, "://") {
|
||||
url = "https://" + url
|
||||
}
|
||||
url = strings.TrimRight(url, "/")
|
||||
return url
|
||||
}
|
||||
|
||||
// parseYuqueConfig extracts and validates Yuque-specific configuration.
|
||||
// Uses JSON marshal/unmarshal roundtrip (consistent with Feishu's parseFeishuConfig)
|
||||
// rather than single-field type assertion, because we have multiple fields with
|
||||
// optional defaults.
|
||||
func parseYuqueConfig(config *types.DataSourceConfig) (*Config, error) {
|
||||
if config == nil {
|
||||
return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)
|
||||
}
|
||||
credBytes, err := json.Marshal(config.Credentials)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal credentials: %w", err)
|
||||
}
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(credBytes, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parse yuque credentials: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(cfg.APIToken) == "" {
|
||||
return nil, fmt.Errorf("%w: api_token is required", datasource.ErrInvalidCredentials)
|
||||
}
|
||||
if err := datasource.ValidateConnectorBaseURL(cfg.GetBaseURL()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// --- Yuque API response types ---
|
||||
|
||||
// flexibleStatus accepts either a string ("1") or a number (1) for the doc
|
||||
// `status` field. Yuque's OpenAPI spec declares `status` as string, but the
|
||||
// runtime API returns it as an integer, so unmarshaling into a plain string
|
||||
// fails with "cannot unmarshal number into Go struct field ... of type string".
|
||||
// Normalizing to the textual form lets existing comparisons (e.g. != "1") keep
|
||||
// working for both response shapes.
|
||||
type flexibleStatus string
|
||||
|
||||
func (s *flexibleStatus) UnmarshalJSON(b []byte) error {
|
||||
if string(b) == "null" {
|
||||
*s = ""
|
||||
return nil
|
||||
}
|
||||
if len(b) > 0 && b[0] == '"' {
|
||||
var str string
|
||||
if err := json.Unmarshal(b, &str); err != nil {
|
||||
return err
|
||||
}
|
||||
*s = flexibleStatus(str)
|
||||
return nil
|
||||
}
|
||||
// Integer form. We decode to int64 so that floats, booleans, arrays, and
|
||||
// objects fail loudly instead of being silently stringified — if Yuque
|
||||
// changes the shape again, we'd rather surface a clear error than feed
|
||||
// garbage to the Status == "1" comparison.
|
||||
var i int64
|
||||
if err := json.Unmarshal(b, &i); err != nil {
|
||||
return fmt.Errorf("flexibleStatus: expected string or integer, got %s: %w", b, err)
|
||||
}
|
||||
*s = flexibleStatus(strconv.FormatInt(i, 10))
|
||||
return nil
|
||||
}
|
||||
|
||||
// apiErrorBody is the error body shape Yuque sometimes returns on non-2xx.
|
||||
type apiErrorBody struct {
|
||||
Message string `json:"message"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
// v2UserResponse wraps GET /api/v2/user.
|
||||
type v2UserResponse struct {
|
||||
Data v2User `json:"data"`
|
||||
}
|
||||
|
||||
type v2User struct {
|
||||
ID int64 `json:"id"`
|
||||
Type string `json:"type"` // "User" for personal token, "Group" for team token
|
||||
Login string `json:"login"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// v2GroupListResponse wraps GET /api/v2/users/{id}/groups.
|
||||
type v2GroupListResponse struct {
|
||||
Data []v2Group `json:"data"`
|
||||
}
|
||||
|
||||
type v2Group struct {
|
||||
ID int64 `json:"id"`
|
||||
Login string `json:"login"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// v2RepoListResponse wraps GET /api/v2/users/{login}/repos and /groups/{login}/repos.
|
||||
type v2RepoListResponse struct {
|
||||
Data []v2Repo `json:"data"`
|
||||
}
|
||||
|
||||
type v2Repo struct {
|
||||
ID int64 `json:"id"`
|
||||
Type string `json:"type"` // "Book" | "Design" (listing filter enum; connector requests type=Book)
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
UserID int64 `json:"user_id"`
|
||||
Namespace string `json:"namespace"` // e.g. "group_login/book_slug"
|
||||
Public int `json:"public"` // 0:private, 1:public, 2:internal
|
||||
Description string `json:"description"`
|
||||
UpdatedAt string `json:"updated_at"` // RFC3339 string
|
||||
}
|
||||
|
||||
// v2DocListResponse wraps GET /api/v2/repos/{book_id}/docs.
|
||||
type v2DocListResponse struct {
|
||||
Meta struct {
|
||||
Total int `json:"total"`
|
||||
} `json:"meta"`
|
||||
Data []v2Doc `json:"data"`
|
||||
}
|
||||
|
||||
// v2Doc is the document summary returned by the list endpoint (no body).
|
||||
type v2Doc struct {
|
||||
ID int64 `json:"id"`
|
||||
Type string `json:"type"` // Doc / Sheet / Thread / Board / Table
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
BookID int64 `json:"book_id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
Status flexibleStatus `json:"status"` // "0" draft, "1" published — API may return int or string
|
||||
ContentUpdatedAt string `json:"content_updated_at"` // RFC3339 string — use for change detection
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
WordCount int `json:"word_count"`
|
||||
}
|
||||
|
||||
// v2DocDetailResponse wraps GET /api/v2/repos/docs/{id}.
|
||||
type v2DocDetailResponse struct {
|
||||
Data v2DocDetail `json:"data"`
|
||||
}
|
||||
|
||||
type v2DocDetail struct {
|
||||
ID int64 `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
BookID int64 `json:"book_id"`
|
||||
Format string `json:"format"` // "markdown" / "lake" / "html"
|
||||
Body string `json:"body"` // Markdown content
|
||||
Status flexibleStatus `json:"status"` // API may return int or string
|
||||
ContentUpdatedAt string `json:"content_updated_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
WordCount int `json:"word_count"`
|
||||
Book v2Repo `json:"book"`
|
||||
}
|
||||
|
||||
// yuqueCursor stores incremental sync state.
|
||||
// Key1: book_id (string), Key2: doc_id (string), Value: content_updated_at (raw RFC3339 string)
|
||||
type yuqueCursor struct {
|
||||
LastSyncTime time.Time `json:"last_sync_time"`
|
||||
BookDocTimes map[string]map[string]string `json:"book_doc_times,omitempty"`
|
||||
}
|
||||
|
||||
// parseContentUpdatedAt parses Yuque ISO 8601 timestamp (returns zero time on parse failure).
|
||||
func parseContentUpdatedAt(ts string) time.Time {
|
||||
if ts == "" {
|
||||
return time.Time{}
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, ts)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// redactToken returns a masked form of the token for logging (never log the full token).
|
||||
func redactToken(t string) string {
|
||||
if len(t) < 12 {
|
||||
return "***"
|
||||
}
|
||||
return t[:6] + "..." + t[len(t)-4:]
|
||||
}
|
||||
|
||||
// --- Table of contents (TOC) ---
|
||||
|
||||
// v2TOCResponse wraps GET /api/v2/repos/{book_id}/toc.
|
||||
type v2TOCResponse struct {
|
||||
Data []v2TOCNode `json:"data"`
|
||||
}
|
||||
|
||||
// v2TOCNode is one entry in a book's table of contents.
|
||||
//
|
||||
// The endpoint returns a flat list; the hierarchy is expressed by parent_uuid.
|
||||
// TITLE nodes are grouping headers (their doc_id is empty), DOC nodes are the
|
||||
// actual documents. Both carry a uuid that other nodes reference as parent_uuid.
|
||||
type v2TOCNode struct {
|
||||
UUID string `json:"uuid"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
ParentUUID string `json:"parent_uuid"`
|
||||
DocID flexibleDocID `json:"doc_id"`
|
||||
}
|
||||
|
||||
const (
|
||||
tocNodeTypeTitle = "TITLE"
|
||||
tocNodeTypeDoc = "DOC"
|
||||
)
|
||||
|
||||
// flexibleDocID accepts the TOC `doc_id` field, which the API serializes as a
|
||||
// number on DOC nodes but as an empty string on TITLE nodes. Decoding straight
|
||||
// into int64 fails on "" ("cannot unmarshal string into Go struct field").
|
||||
// Absent or empty IDs normalise to 0, which is never a real Yuque document ID.
|
||||
type flexibleDocID int64
|
||||
|
||||
func (d *flexibleDocID) UnmarshalJSON(b []byte) error {
|
||||
if len(b) == 0 || string(b) == "null" {
|
||||
*d = 0
|
||||
return nil
|
||||
}
|
||||
if b[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
*d = 0
|
||||
return nil
|
||||
}
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("flexibleDocID: %q is not a numeric id: %w", s, err)
|
||||
}
|
||||
*d = flexibleDocID(n)
|
||||
return nil
|
||||
}
|
||||
var n int64
|
||||
if err := json.Unmarshal(b, &n); err != nil {
|
||||
return fmt.Errorf("flexibleDocID: expected string or integer, got %s: %w", b, err)
|
||||
}
|
||||
*d = flexibleDocID(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxTOCDepth bounds the ancestor walk in buildTOCPaths. Real nesting is only a
|
||||
// few levels deep; the bound is a backstop against malformed input.
|
||||
const maxTOCDepth = 32
|
||||
|
||||
// buildTOCPaths folds a flat TOC node list into two per-document lookup maps:
|
||||
//
|
||||
// segs — doc_id → ancestor titles, root-first, each already passed through
|
||||
// sanitizeFileName. Absent when the document sits directly under the
|
||||
// book root.
|
||||
// inTOC — doc_id → whether the document appears in the TOC node list at all.
|
||||
//
|
||||
// The two maps are deliberately separate and must stay that way. A document can
|
||||
// legitimately appear in the TOC without belonging to any group, in which case
|
||||
// inTOC is true and segs is empty. A caller filtering out "documents that are
|
||||
// not in the TOC" must test inTOC — testing segs[id] instead would also drop
|
||||
// those group-less documents.
|
||||
//
|
||||
// Sanitising per segment here (rather than on the joined path) is what keeps a
|
||||
// "/" inside a group title from silently creating an extra nesting level.
|
||||
func buildTOCPaths(nodes []v2TOCNode) (map[int64][]string, map[int64]bool) {
|
||||
byUUID := make(map[string]v2TOCNode, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if n.UUID != "" {
|
||||
byUUID[n.UUID] = n
|
||||
}
|
||||
}
|
||||
|
||||
segs := make(map[int64][]string)
|
||||
inTOC := make(map[int64]bool)
|
||||
|
||||
for _, n := range nodes {
|
||||
if n.Type != tocNodeTypeDoc {
|
||||
continue
|
||||
}
|
||||
id := int64(n.DocID)
|
||||
if id == 0 {
|
||||
continue
|
||||
}
|
||||
inTOC[id] = true
|
||||
|
||||
var reverse []string
|
||||
visited := map[string]bool{n.UUID: true}
|
||||
cur := n
|
||||
for len(reverse) < maxTOCDepth {
|
||||
parent, ok := byUUID[cur.ParentUUID]
|
||||
if !ok || parent.UUID == "" || visited[parent.UUID] {
|
||||
break // reached the root, hit a dangling parent, or a cycle
|
||||
}
|
||||
visited[parent.UUID] = true
|
||||
if title := strings.TrimSpace(parent.Title); title != "" {
|
||||
reverse = append(reverse, datasource.SanitizeFileName(title))
|
||||
}
|
||||
cur = parent
|
||||
}
|
||||
// Walked child → root; flip to root → child for path order.
|
||||
out := make([]string, len(reverse))
|
||||
for i, s := range reverse {
|
||||
out[len(reverse)-1-i] = s
|
||||
}
|
||||
if len(out) > 0 {
|
||||
segs[id] = out
|
||||
}
|
||||
}
|
||||
return segs, inTOC
|
||||
}
|
||||
|
||||
// --- Folder path settings ---
|
||||
|
||||
const (
|
||||
// folderModeNone is the historical behaviour: a bare "<title>.md" file name,
|
||||
// so every synced document lands at the knowledge base root.
|
||||
folderModeNone = "none"
|
||||
// folderModeTOC derives the folder path from the book's table of contents.
|
||||
folderModeTOC = "toc"
|
||||
)
|
||||
|
||||
// folderSettings controls how folder paths are derived for synced documents.
|
||||
// Configured under DataSourceConfig.Settings, never under Credentials.
|
||||
type folderSettings struct {
|
||||
// FolderMode is folderModeNone or folderModeTOC.
|
||||
FolderMode string
|
||||
// TOCOnly admits only documents that appear in the book's TOC. It is an
|
||||
// admission filter, not a reaper: a filtered document is simply not
|
||||
// ingested, and one already in the knowledge base is left untouched. Only
|
||||
// meaningful when FolderMode is folderModeTOC.
|
||||
TOCOnly bool
|
||||
}
|
||||
|
||||
// defaultFolderSettings keeps the emitted FileName byte-for-byte identical to
|
||||
// previous releases, so enabling the new behaviour is strictly opt-in and an
|
||||
// existing data source keeps working unchanged after an upgrade.
|
||||
func defaultFolderSettings() folderSettings {
|
||||
return folderSettings{
|
||||
FolderMode: folderModeNone,
|
||||
TOCOnly: false,
|
||||
}
|
||||
}
|
||||
|
||||
// parseFolderSettings reads the folder-path settings, falling back to the
|
||||
// default for any key that is absent or unrecognised. A typo in the settings
|
||||
// map must not fail a sync.
|
||||
func parseFolderSettings(ctx context.Context, ds *types.DataSourceConfig) folderSettings {
|
||||
s := defaultFolderSettings()
|
||||
if ds == nil || ds.Settings == nil {
|
||||
return s
|
||||
}
|
||||
if raw, ok := ds.Settings["folder_mode"]; ok {
|
||||
mode := strings.ToLower(strings.TrimSpace(fmt.Sprint(raw)))
|
||||
switch mode {
|
||||
case folderModeNone, folderModeTOC:
|
||||
s.FolderMode = mode
|
||||
default:
|
||||
logger.Warnf(ctx, "[Yuque] unknown folder_mode %q, keeping %q", mode, s.FolderMode)
|
||||
}
|
||||
}
|
||||
s.TOCOnly = settingBool(ds.Settings["toc_only"], s.TOCOnly)
|
||||
return s
|
||||
}
|
||||
|
||||
// settingBool interprets a settings value as a boolean, returning def when the
|
||||
// value is absent or of an unrecognised shape. Settings arrive from JSON, so a
|
||||
// hand-edited config may carry either a real bool or its string form.
|
||||
func settingBool(v interface{}, def bool) bool {
|
||||
switch t := v.(type) {
|
||||
case bool:
|
||||
return t
|
||||
case string:
|
||||
switch strings.ToLower(strings.TrimSpace(t)) {
|
||||
case "true", "1", "yes", "on":
|
||||
return true
|
||||
case "false", "0", "no", "off":
|
||||
return false
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// buildFolderFileName assembles the FileName for a synced document.
|
||||
//
|
||||
// folder_path downstream is derived from FileName alone
|
||||
// (SplitKnowledgeRelativePath → NormalizeKnowledgeFolderPath), so the folder
|
||||
// hierarchy has to be encoded here as a relative path.
|
||||
//
|
||||
// With the default settings — or whenever the book's TOC could not be loaded —
|
||||
// this returns exactly "<title>.md", which is the byte-for-byte behaviour of
|
||||
// previous releases.
|
||||
//
|
||||
// When the TOC is in play the book name is always the first segment. It is the
|
||||
// only carrier of the "which book" dimension — the automatic tag granularity is
|
||||
// per data source, not per book — and omitting it would silently merge
|
||||
// same-named top-level groups from different books into one folder.
|
||||
func buildFolderFileName(
|
||||
settings folderSettings, tocOK bool, bookName string, tocSegs []string, title string,
|
||||
) string {
|
||||
fileName := datasource.SanitizeFileName(title) + ".md"
|
||||
if settings.FolderMode != folderModeTOC || !tocOK {
|
||||
return fileName
|
||||
}
|
||||
segments := make([]string, 0, len(tocSegs)+1)
|
||||
if bookName != "" {
|
||||
segments = append(segments, datasource.SanitizeFileName(bookName))
|
||||
}
|
||||
// tocSegs are already sanitised by buildTOCPaths.
|
||||
segments = append(segments, tocSegs...)
|
||||
if len(segments) == 0 {
|
||||
return fileName
|
||||
}
|
||||
return strings.Join(segments, "/") + "/" + fileName
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package yuque
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Yuque's runtime API returns the doc `status` field as an integer (0 or 1),
|
||||
// even though its OpenAPI spec declares it as string. We tolerate both forms.
|
||||
func TestV2Doc_Status_AcceptsNumberAndString(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
want flexibleStatus
|
||||
}{
|
||||
{"number 1", `{"id":1,"status":1}`, "1"},
|
||||
{"number 0", `{"id":1,"status":0}`, "0"},
|
||||
{"string 1", `{"id":1,"status":"1"}`, "1"},
|
||||
{"null", `{"id":1,"status":null}`, ""},
|
||||
{"missing", `{"id":1}`, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var d v2Doc
|
||||
if err := json.Unmarshal([]byte(tc.body), &d); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if d.Status != tc.want {
|
||||
t.Errorf("Status = %q, want %q", d.Status, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestV2DocDetail_Status_AcceptsNumber(t *testing.T) {
|
||||
var d v2DocDetail
|
||||
if err := json.Unmarshal([]byte(`{"id":1,"status":1}`), &d); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if d.Status != "1" {
|
||||
t.Errorf("Status = %q, want %q", d.Status, "1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestV2DocListResponse_Status_Number(t *testing.T) {
|
||||
// Reproduces the real-world failure:
|
||||
// decode response: json: cannot unmarshal number into Go struct field v2Doc.data.status of type string
|
||||
body := `{"meta":{"total":1},"data":[{"id":101,"type":"Doc","status":1,"title":"hello"}]}`
|
||||
var resp v2DocListResponse
|
||||
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(resp.Data) != 1 {
|
||||
t.Fatalf("len(Data) = %d", len(resp.Data))
|
||||
}
|
||||
if resp.Data[0].Status != "1" {
|
||||
t.Errorf("Status = %q, want %q", resp.Data[0].Status, "1")
|
||||
}
|
||||
}
|
||||
|
||||
// flexibleStatus deliberately rejects unexpected JSON shapes so a future Yuque
|
||||
// schema drift (e.g. status becoming a float, bool, array) fails loudly rather
|
||||
// than being silently stringified and bypassing the `!= "1"` filter.
|
||||
func TestV2Doc_Status_RejectsUnexpectedShapes(t *testing.T) {
|
||||
cases := []string{
|
||||
`{"id":1,"status":true}`,
|
||||
`{"id":1,"status":1.5}`,
|
||||
`{"id":1,"status":[1]}`,
|
||||
`{"id":1,"status":{"x":1}}`,
|
||||
}
|
||||
for _, body := range cases {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
var d v2Doc
|
||||
if err := json.Unmarshal([]byte(body), &d); err == nil {
|
||||
t.Errorf("expected error for %s, got Status=%q", body, d.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseYuqueConfig(t *testing.T) {
|
||||
t.Run("valid full", func(t *testing.T) {
|
||||
cfg, err := parseYuqueConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"api_token": "tok-123",
|
||||
"base_url": "https://company.yuque.com",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cfg.APIToken != "tok-123" {
|
||||
t.Errorf("APIToken = %q, want tok-123", cfg.APIToken)
|
||||
}
|
||||
if cfg.BaseURL != "https://company.yuque.com" {
|
||||
t.Errorf("BaseURL = %q", cfg.BaseURL)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("default base_url", func(t *testing.T) {
|
||||
cfg, err := parseYuqueConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{"api_token": "tok-abc"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cfg.GetBaseURL() != "https://www.yuque.com" {
|
||||
t.Errorf("GetBaseURL default = %q, want https://www.yuque.com", cfg.GetBaseURL())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing api_token", func(t *testing.T) {
|
||||
_, err := parseYuqueConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing api_token")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil config", func(t *testing.T) {
|
||||
_, err := parseYuqueConfig(nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil config")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetBaseURL_TrimsTrailingSlash(t *testing.T) {
|
||||
c := &Config{BaseURL: "https://x.yuque.com/"}
|
||||
if got := c.GetBaseURL(); got != "https://x.yuque.com" {
|
||||
t.Errorf("GetBaseURL = %q, want https://x.yuque.com", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBaseURL_AddsSchemeIfMissing(t *testing.T) {
|
||||
c := &Config{BaseURL: "company.yuque.com"}
|
||||
if got := c.GetBaseURL(); got != "https://company.yuque.com" {
|
||||
t.Errorf("GetBaseURL = %q, want https://company.yuque.com", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBaseURL_EmptyUsesDefault(t *testing.T) {
|
||||
c := &Config{BaseURL: ""}
|
||||
if got := c.GetBaseURL(); got != "https://www.yuque.com" {
|
||||
t.Errorf("GetBaseURL = %q, want default", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBaseURL_TrimsWhitespace(t *testing.T) {
|
||||
c := &Config{BaseURL: " https://x.yuque.com/ "}
|
||||
if got := c.GetBaseURL(); got != "https://x.yuque.com" {
|
||||
t.Errorf("GetBaseURL = %q, want https://x.yuque.com", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user