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,354 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
userAgent = "Academy-Seafile-Connector/1.0"
|
||||
apiTimeout = 30 * time.Second
|
||||
downloadTimeout = 120 * time.Second
|
||||
|
||||
// maxAttempts is the initial request plus two retries.
|
||||
maxAttempts = 3
|
||||
// maxRetryAfter bounds an honoured Retry-After; anything longer aborts the run.
|
||||
maxRetryAfter = 60 * time.Second
|
||||
|
||||
listingJSONLimit = int64(32 << 20)
|
||||
smallJSONLimit = int64(64 << 10)
|
||||
)
|
||||
|
||||
var (
|
||||
errRetryAfterTooLong = errors.New("seafile asked to retry after more than 60 seconds")
|
||||
errInvalidResponse = errors.New("seafile returned an unexpected response")
|
||||
errSSRFBlocked = errors.New("seafile download URL was blocked by the SSRF policy")
|
||||
errTooLarge = errors.New("seafile file exceeds the size limit")
|
||||
errEmptyFile = errors.New("seafile file is empty")
|
||||
errSourceChanged = errors.New("seafile file changed while it was being fetched")
|
||||
|
||||
// sleep performs every backoff wait; tests replace it to avoid real waits.
|
||||
sleep = sleepCtx
|
||||
)
|
||||
|
||||
// client talks to one Seafile deployment. API requests carry the token; the
|
||||
// fileserver client never does, and both keep the shared SSRF redirect policy.
|
||||
type client struct {
|
||||
baseURL string
|
||||
token string
|
||||
api *http.Client
|
||||
files *http.Client
|
||||
}
|
||||
|
||||
func newClient(cfg config) *client {
|
||||
return &client{
|
||||
baseURL: cfg.baseURL,
|
||||
token: cfg.token,
|
||||
api: datasource.NewConnectorHTTPClient(apiTimeout),
|
||||
files: datasource.NewConnectorHTTPClient(downloadTimeout),
|
||||
}
|
||||
}
|
||||
|
||||
// httpError reports a non-success status. Op is a fixed label, never a URL,
|
||||
// path or response body, so the message is safe to surface.
|
||||
type httpError struct {
|
||||
Op string
|
||||
Status int
|
||||
retryAfter string
|
||||
}
|
||||
|
||||
func (e *httpError) Error() string { return fmt.Sprintf("seafile %s: HTTP %d", e.Op, e.Status) }
|
||||
func (e *httpError) Unwrap() error { return datasource.ErrFetchFailed }
|
||||
|
||||
// statusOf returns the HTTP status carried by err, or 0.
|
||||
func statusOf(err error) int {
|
||||
var statusErr *httpError
|
||||
if errors.As(err, &statusErr) {
|
||||
return statusErr.Status
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// transportError hides the request URL (a *url.Error would echo a signed
|
||||
// download link) while remembering whether a retry is worthwhile.
|
||||
type transportError struct {
|
||||
Op string
|
||||
transient bool
|
||||
}
|
||||
|
||||
func (e *transportError) Error() string { return "seafile " + e.Op + ": request failed" }
|
||||
func (e *transportError) Unwrap() error { return datasource.ErrFetchFailed }
|
||||
|
||||
func invalidResponse(op string) error {
|
||||
return fmt.Errorf("%w: seafile %s: %w", datasource.ErrFetchFailed, op, errInvalidResponse)
|
||||
}
|
||||
|
||||
func isTransientNetworkError(err error) bool {
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||
return true
|
||||
}
|
||||
var opErr *net.OpError
|
||||
return errors.As(err, &opErr) && opErr.Op == "dial"
|
||||
}
|
||||
|
||||
func retryableStatus(status int) bool {
|
||||
return status == http.StatusTooManyRequests || status == http.StatusBadGateway ||
|
||||
status == http.StatusServiceUnavailable || status == http.StatusGatewayTimeout
|
||||
}
|
||||
|
||||
func backoff(attempt int) time.Duration {
|
||||
return time.Second << attempt
|
||||
}
|
||||
|
||||
// retryAfter parses a Retry-After header (delta seconds or HTTP date). Values
|
||||
// above maxRetryAfter, including unparsable huge numbers, are run-fatal.
|
||||
func retryAfter(value string, now time.Time) (time.Duration, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return 0, nil
|
||||
}
|
||||
if strings.Trim(value, "0123456789") == "" {
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds > int64(maxRetryAfter/time.Second) {
|
||||
return 0, errRetryAfterTooLong
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
date, err := http.ParseTime(value)
|
||||
if err != nil {
|
||||
return 0, nil
|
||||
}
|
||||
if wait := date.Sub(now); wait > maxRetryAfter {
|
||||
return 0, errRetryAfterTooLong
|
||||
} else if wait > 0 {
|
||||
return wait, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// get performs a GET with retries on throttling, upstream 5xx and transient
|
||||
// network errors. authenticated selects the API client and token; otherwise
|
||||
// the fileserver client is used without credentials and only 200 is accepted.
|
||||
func (c *client) get(
|
||||
ctx context.Context, target, op string, authenticated bool, limit int64,
|
||||
) ([]byte, http.Header, error) {
|
||||
for attempt := 0; ; attempt++ {
|
||||
body, headers, err := c.once(ctx, target, op, authenticated, limit)
|
||||
if err == nil {
|
||||
return body, headers, nil
|
||||
}
|
||||
delay, retry, err := classify(err, attempt)
|
||||
if !retry || attempt == maxAttempts-1 {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := sleep(ctx, delay); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// classify decides whether err is worth retrying and how long to wait.
|
||||
func classify(err error, attempt int) (time.Duration, bool, error) {
|
||||
var statusErr *httpError
|
||||
var netErr *transportError
|
||||
switch {
|
||||
case errors.As(err, &statusErr):
|
||||
if !retryableStatus(statusErr.Status) {
|
||||
return 0, false, err
|
||||
}
|
||||
wait, raErr := retryAfter(statusErr.retryAfter, time.Now())
|
||||
if raErr != nil {
|
||||
return 0, false, fmt.Errorf("%w: %w", statusErr, raErr)
|
||||
}
|
||||
return max(backoff(attempt), wait), true, err
|
||||
case errors.As(err, &netErr):
|
||||
return backoff(attempt), netErr.transient, err
|
||||
default:
|
||||
return 0, false, err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client) once(
|
||||
ctx context.Context, target, op string, authenticated bool, limit int64,
|
||||
) ([]byte, http.Header, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return nil, nil, invalidResponse(op)
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
httpClient := c.files
|
||||
if authenticated {
|
||||
httpClient = c.api
|
||||
req.Header.Set("Authorization", "Token "+c.token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, nil, c.transport(ctx, op, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
ok := resp.StatusCode == http.StatusOK
|
||||
if authenticated {
|
||||
ok = resp.StatusCode >= 200 && resp.StatusCode < 300
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil, &httpError{Op: op, Status: resp.StatusCode, retryAfter: resp.Header.Get("Retry-After")}
|
||||
}
|
||||
if !authenticated && resp.ContentLength > limit {
|
||||
return nil, nil, errTooLarge
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
if err != nil {
|
||||
return nil, nil, c.transport(ctx, op, err)
|
||||
}
|
||||
if int64(len(body)) > limit {
|
||||
if authenticated {
|
||||
return nil, nil, invalidResponse(op)
|
||||
}
|
||||
return nil, nil, errTooLarge
|
||||
}
|
||||
return body, resp.Header, nil
|
||||
}
|
||||
|
||||
func (c *client) transport(ctx context.Context, op string, err error) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if errors.Is(err, utils.ErrSSRFRedirectBlocked) {
|
||||
return fmt.Errorf("%w: %w", datasource.ErrFetchFailed, errSSRFBlocked)
|
||||
}
|
||||
return &transportError{Op: op, transient: isTransientNetworkError(err)}
|
||||
}
|
||||
|
||||
func (c *client) getJSON(ctx context.Context, endpoint, op string, limit int64, out any) (http.Header, error) {
|
||||
body, headers, err := c.get(ctx, c.baseURL+endpoint, op, true, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return nil, invalidResponse(op)
|
||||
}
|
||||
return headers, nil
|
||||
}
|
||||
|
||||
// credentialError maps 401/403 on account-level endpoints to
|
||||
// ErrInvalidCredentials. Directory-level 403s are scoping problems and are
|
||||
// left to the connector.
|
||||
func credentialError(err error) error {
|
||||
if status := statusOf(err); status == http.StatusUnauthorized || status == http.StatusForbidden {
|
||||
return fmt.Errorf("%w: %w", datasource.ErrInvalidCredentials, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *client) ping(ctx context.Context) error {
|
||||
var pong string
|
||||
if _, err := c.getJSON(ctx, "/api2/auth/ping/", "ping", smallJSONLimit, &pong); err != nil {
|
||||
return credentialError(err)
|
||||
}
|
||||
if pong != "pong" {
|
||||
return invalidResponse("ping")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) listRepos(ctx context.Context) ([]repoInfo, error) {
|
||||
var repos []repoInfo
|
||||
if _, err := c.getJSON(ctx, "/api2/repos/", "repos", listingJSONLimit, &repos); err != nil {
|
||||
return nil, credentialError(err)
|
||||
}
|
||||
if repos == nil {
|
||||
return nil, invalidResponse("repos")
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
func repoEndpoint(repoID, kind string, query url.Values) string {
|
||||
return "/api2/repos/" + url.PathEscape(repoID) + "/" + kind + "/?" + query.Encode()
|
||||
}
|
||||
|
||||
// listDir returns one directory level. Non-2xx statuses come back as
|
||||
// *httpError so the connector can tell 403/404 apart.
|
||||
func (c *client) listDir(ctx context.Context, repoID, path string) ([]dirent, error) {
|
||||
var entries []dirent
|
||||
endpoint := repoEndpoint(repoID, "dir", url.Values{"p": {path}})
|
||||
if _, err := c.getJSON(ctx, endpoint, "dir", listingJSONLimit, &entries); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entries == nil {
|
||||
return nil, invalidResponse("dir")
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// downloadLink resolves a reusable fileserver URL and the file's object id
|
||||
// from the response header (empty when the server omits it).
|
||||
func (c *client) downloadLink(ctx context.Context, repoID, path string) (link, oid string, err error) {
|
||||
endpoint := repoEndpoint(repoID, "file", url.Values{"p": {path}, "reuse": {"1"}})
|
||||
headers, err := c.getJSON(ctx, endpoint, "file", smallJSONLimit, &link)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if !validDownloadURL(link) {
|
||||
return "", "", invalidResponse("file")
|
||||
}
|
||||
return link, headers.Get("oid"), nil
|
||||
}
|
||||
|
||||
// validDownloadURL accepts absolute http(s) URLs without userinfo, which Go
|
||||
// would otherwise turn into a Basic Authorization header.
|
||||
func validDownloadURL(link string) bool {
|
||||
u, err := url.Parse(link)
|
||||
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != "" && u.User == nil
|
||||
}
|
||||
|
||||
// download fetches a fileserver link without credentials. The body must be
|
||||
// exactly expectedSize bytes and at most limit bytes.
|
||||
func (c *client) download(ctx context.Context, link string, expectedSize, limit int64) ([]byte, error) {
|
||||
if !validDownloadURL(link) {
|
||||
return nil, invalidResponse("download")
|
||||
}
|
||||
if err := utils.ValidateURLForSSRF(link); err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", datasource.ErrFetchFailed, errSSRFBlocked)
|
||||
}
|
||||
body, _, err := c.get(ctx, link, "download", false, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(body) == 0 {
|
||||
return nil, errEmptyFile
|
||||
}
|
||||
if int64(len(body)) != expectedSize {
|
||||
return nil, errSourceChanged
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) error {
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// noWait replaces the package sleep with a recorder so tests never wait.
|
||||
func noWait(t *testing.T) *[]time.Duration {
|
||||
t.Helper()
|
||||
original := sleep
|
||||
var waits []time.Duration
|
||||
sleep = func(ctx context.Context, d time.Duration) error {
|
||||
waits = append(waits, d)
|
||||
return ctx.Err()
|
||||
}
|
||||
t.Cleanup(func() { sleep = original })
|
||||
return &waits
|
||||
}
|
||||
|
||||
func testClient(t *testing.T) (*fakeSeafile, *client, *[]time.Duration) {
|
||||
t.Helper()
|
||||
waits := noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
f.addRepo(testRepoID, "Library", "repo", false)
|
||||
c := newClient(config{baseURL: f.baseURL(), token: testToken})
|
||||
t.Cleanup(c.api.CloseIdleConnections)
|
||||
t.Cleanup(c.files.CloseIdleConnections)
|
||||
return f, c, waits
|
||||
}
|
||||
|
||||
func assertNoCredentials(t *testing.T, requests []fakeRequest) {
|
||||
t.Helper()
|
||||
for _, req := range requests {
|
||||
if req.Headers.Get("Authorization") != "" || req.Headers.Get("Cookie") != "" {
|
||||
t.Fatal("fileserver received credentials")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPing(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
status int
|
||||
want error
|
||||
}{
|
||||
{name: "pong"},
|
||||
{name: "unauthorized", status: 401, want: datasource.ErrInvalidCredentials},
|
||||
{name: "forbidden", status: 403, want: datasource.ErrInvalidCredentials},
|
||||
{name: "object", body: `{"ok":true}`, want: datasource.ErrFetchFailed},
|
||||
{name: "wrong string", body: `"not pong"`, want: datasource.ErrFetchFailed},
|
||||
{name: "malformed", body: testToken, want: datasource.ErrFetchFailed},
|
||||
{name: "server error", status: 500, want: datasource.ErrFetchFailed},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
if tc.body != "" {
|
||||
f.rawBody["ping"] = tc.body
|
||||
}
|
||||
if tc.status != 0 {
|
||||
f.fail("ping", tc.status, 1)
|
||||
}
|
||||
err := c.ping(t.Context())
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("ping = %v, want %v", err, tc.want)
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), testToken) {
|
||||
t.Fatalf("ping error leaked the token: %v", err)
|
||||
}
|
||||
if f.count("ping") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("unexpected retries: counts=%v waits=%v", f.counts(), *waits)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIHeadersAndDeploymentPrefix(t *testing.T) {
|
||||
f, c, _ := testClient(t)
|
||||
f.prefix = "/seafile"
|
||||
c.baseURL = f.baseURL()
|
||||
f.addFile(testRepoID, "/file", []byte("body"), 123)
|
||||
f.addRepo(otherRepoID, "Encrypted", "srepo", true)
|
||||
|
||||
if c.api.Timeout != apiTimeout || c.files.Timeout != downloadTimeout ||
|
||||
c.api.CheckRedirect == nil || c.files.CheckRedirect == nil {
|
||||
t.Fatal("clients must come from the shared SSRF-guarded constructor")
|
||||
}
|
||||
if err := c.ping(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repos, err := c.listRepos(t.Context())
|
||||
if err != nil || len(repos) != 2 || !repos[1].Encrypted || repos[1].Type != "srepo" {
|
||||
t.Fatalf("listRepos = %+v, %v", repos, err)
|
||||
}
|
||||
if _, err := c.listDir(t.Context(), testRepoID, "/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link, oid, err := c.downloadLink(t.Context(), testRepoID, "/file")
|
||||
if err != nil || oid == "" {
|
||||
t.Fatalf("downloadLink oid = %q, %v", oid, err)
|
||||
}
|
||||
body, err := c.download(t.Context(), link, 4, 4)
|
||||
if err != nil || string(body) != "body" {
|
||||
t.Fatalf("download = %q, %v", body, err)
|
||||
}
|
||||
for _, key := range []string{"ping", "repos", "dir:/", "file:/file"} {
|
||||
requests := f.requests(key)
|
||||
if len(requests) != 1 {
|
||||
t.Fatalf("%s requests = %d", key, len(requests))
|
||||
}
|
||||
h := requests[0].Headers
|
||||
if h.Get("Authorization") != "Token "+testToken || h.Get("Accept") != "application/json" ||
|
||||
h.Get("User-Agent") != userAgent {
|
||||
t.Fatalf("%s missing API headers: %v", key, h)
|
||||
}
|
||||
}
|
||||
assertNoCredentials(t, f.requests("download:/file"))
|
||||
}
|
||||
|
||||
func TestListReposCredentials(t *testing.T) {
|
||||
for _, status := range []int{401, 403} {
|
||||
t.Run(fmt.Sprint(status), func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.fail("repos", status, -1)
|
||||
_, err := c.listRepos(t.Context())
|
||||
if !errors.Is(err, datasource.ErrInvalidCredentials) || statusOf(err) != status ||
|
||||
f.count("repos") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("listRepos = %v, counts = %v", err, f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirQueryAndOptionalSize(t *testing.T) {
|
||||
f, c, _ := testClient(t)
|
||||
f.addDir(testRepoID, "/产品/Z目录")
|
||||
f.addFile(testRepoID, "/产品/a.pdf", []byte("pdf"), 42)
|
||||
entries, err := c.listDir(t.Context(), testRepoID, "/产品")
|
||||
if err != nil || len(entries) != 2 {
|
||||
t.Fatalf("listDir = %+v, %v", entries, err)
|
||||
}
|
||||
if entries[0].Type != "dir" || entries[0].Size != nil ||
|
||||
entries[1].Size == nil || *entries[1].Size != 3 || entries[1].Mtime != 42 {
|
||||
t.Fatalf("unexpected entries: %+v", entries)
|
||||
}
|
||||
if got := f.requests("dir:/产品")[0].RawQuery; got != "p=%2F%E4%BA%A7%E5%93%81" {
|
||||
t.Fatalf("path encoded incorrectly: %s", got)
|
||||
}
|
||||
f.addDir(testRepoID, "/a:%2Fb")
|
||||
if _, err := c.listDir(t.Context(), testRepoID, "/a:%2Fb"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := f.requests("dir:/a:%2Fb")[0].RawQuery; got != "p=%2Fa%3A%252Fb" {
|
||||
t.Fatalf("literal percent encoded incorrectly: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirRetries(t *testing.T) {
|
||||
twoWaits := []time.Duration{time.Second, 2 * time.Second}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
failures int
|
||||
retryAfter string
|
||||
calls int
|
||||
final int
|
||||
waits []time.Duration
|
||||
tooLong bool
|
||||
}{
|
||||
{name: "503 twice", status: 503, failures: 2, calls: 3, waits: twoWaits},
|
||||
{name: "503 exhausted", status: 503, failures: 3, calls: 3, final: 503, waits: twoWaits},
|
||||
{name: "502", status: 502, failures: 1, calls: 2, waits: []time.Duration{time.Second}},
|
||||
{name: "504", status: 504, failures: 1, calls: 2, waits: []time.Duration{time.Second}},
|
||||
{
|
||||
name: "429 retry-after", status: 429, failures: 1, retryAfter: "3",
|
||||
calls: 2, waits: []time.Duration{3 * time.Second},
|
||||
},
|
||||
{name: "429 too long", status: 429, failures: 3, retryAfter: "120", calls: 1, final: 429, tooLong: true},
|
||||
{name: "401", status: 401, failures: 3, calls: 1, final: 401},
|
||||
{name: "403", status: 403, failures: 3, calls: 1, final: 403},
|
||||
{name: "404", status: 404, failures: 3, calls: 1, final: 404},
|
||||
{name: "500", status: 500, failures: 3, calls: 1, final: 500},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.failWithRetryAfter("dir:/", tc.status, tc.failures, tc.retryAfter)
|
||||
_, err := c.listDir(t.Context(), testRepoID, "/")
|
||||
if statusOf(err) != tc.final || (err == nil) != (tc.final == 0) {
|
||||
t.Fatalf("listDir = %v, want status %d", err, tc.final)
|
||||
}
|
||||
if errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Fatal("listDir must not map directory 401/403 to ErrInvalidCredentials")
|
||||
}
|
||||
if tc.tooLong && (!errors.Is(err, errRetryAfterTooLong) || !errors.Is(err, datasource.ErrFetchFailed)) {
|
||||
t.Fatalf("missing run-fatal Retry-After sentinels: %v", err)
|
||||
}
|
||||
if tc.final != 0 && !errors.Is(err, datasource.ErrFetchFailed) {
|
||||
t.Fatalf("status error must wrap ErrFetchFailed: %v", err)
|
||||
}
|
||||
if f.count("dir:/") != tc.calls || !slices.Equal(*waits, tc.waits) {
|
||||
t.Fatalf("counts = %v, waits = %v", f.counts(), *waits)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirInvalidJSON(t *testing.T) {
|
||||
for _, body := range []string{"{", "null", `[] []`} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.rawBody["dir:/"] = body
|
||||
_, err := c.listDir(t.Context(), testRepoID, "/")
|
||||
if !errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed) ||
|
||||
f.count("dir:/") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("invalid listing = %v, counts = %v", err, f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryAfter(t *testing.T) {
|
||||
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
for _, tc := range []struct {
|
||||
value string
|
||||
want time.Duration
|
||||
fatal bool
|
||||
}{
|
||||
{"", 0, false},
|
||||
{"0", 0, false},
|
||||
{"3", 3 * time.Second, false},
|
||||
{"60", 60 * time.Second, false},
|
||||
{"61", 0, true},
|
||||
{"120", 0, true},
|
||||
{"9223372037", 0, true},
|
||||
{"999999999999999999999999999999", 0, true},
|
||||
{"invalid", 0, false},
|
||||
{now.Add(-time.Hour).Format(http.TimeFormat), 0, false},
|
||||
{now.Add(30 * time.Second).Format(http.TimeFormat), 30 * time.Second, false},
|
||||
{now.Add(61 * time.Second).Format(http.TimeFormat), 0, true},
|
||||
} {
|
||||
wait, err := retryAfter(tc.value, now)
|
||||
if wait != tc.want || errors.Is(err, errRetryAfterTooLong) != tc.fatal {
|
||||
t.Fatalf("retryAfter(%q) = (%v, %v), want (%v, fatal=%v)", tc.value, wait, err, tc.want, tc.fatal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadLink(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`"http://user:secret@localhost/files/token"`, `"/relative"`,
|
||||
`"ftp://localhost/file"`, `""`, `null`, `{"link":"x"}`,
|
||||
`"http://localhost/file" "extra"`,
|
||||
} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.addFile(testRepoID, "/file", []byte("body"), 1)
|
||||
f.rawBody["file:/file"] = body
|
||||
_, _, err := c.downloadLink(t.Context(), testRepoID, "/file")
|
||||
if !errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed) ||
|
||||
f.count("file:/file") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("invalid link = %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("invalid link leaked in error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, oid := range []string{"override-oid", ""} {
|
||||
t.Run("oid="+oid, func(t *testing.T) {
|
||||
f, c, _ := testClient(t)
|
||||
f.addFile(testRepoID, "/a:b%.pdf", []byte("body"), 1)
|
||||
f.linkOID["/a:b%.pdf"] = oid
|
||||
link, got, err := c.downloadLink(t.Context(), testRepoID, "/a:b%.pdf")
|
||||
if err != nil || got != oid || !strings.HasPrefix(link, f.fileserver.URL+"/files/") {
|
||||
t.Fatalf("downloadLink = (%q, %q, %v)", link, got, err)
|
||||
}
|
||||
if query := f.requests("file:/a:b%.pdf")[0].RawQuery; query != "p=%2Fa%3Ab%25.pdf&reuse=1" {
|
||||
t.Fatalf("file query = %s", query)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONCaps(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
key string
|
||||
body string
|
||||
limit int64
|
||||
call func(*client, context.Context) error
|
||||
}{
|
||||
{"repos", "repos", "[]", listingJSONLimit, func(c *client, ctx context.Context) error {
|
||||
_, err := c.listRepos(ctx)
|
||||
return err
|
||||
}},
|
||||
{"dir", "dir:/", "[]", listingJSONLimit, func(c *client, ctx context.Context) error {
|
||||
_, err := c.listDir(ctx, testRepoID, "/")
|
||||
return err
|
||||
}},
|
||||
{"ping", "ping", `"pong"`, smallJSONLimit, func(c *client, ctx context.Context) error {
|
||||
return c.ping(ctx)
|
||||
}},
|
||||
{
|
||||
"link", "file:/file", `"http://localhost/files/token"`, smallJSONLimit,
|
||||
func(c *client, ctx context.Context) error {
|
||||
_, _, err := c.downloadLink(ctx, testRepoID, "/file")
|
||||
return err
|
||||
},
|
||||
},
|
||||
} {
|
||||
for _, extra := range []int{0, 1} {
|
||||
t.Run(fmt.Sprintf("%s/extra=%d", tc.name, extra), func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.addFile(testRepoID, "/file", []byte("body"), 1)
|
||||
f.rawBody[tc.key] = tc.body + strings.Repeat(" ", int(tc.limit)-len(tc.body)+extra)
|
||||
err := tc.call(c, t.Context())
|
||||
if extra == 0 && err != nil {
|
||||
t.Fatalf("body at cap rejected: %v", err)
|
||||
}
|
||||
if extra == 1 && (!errors.Is(err, errInvalidResponse) || !errors.Is(err, datasource.ErrFetchFailed)) {
|
||||
t.Fatalf("body above cap accepted: %v", err)
|
||||
}
|
||||
if f.count(tc.key) != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("unexpected retries: %v", f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownload(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
expected int64
|
||||
chunked int64
|
||||
partial bool
|
||||
want error
|
||||
status int
|
||||
}{
|
||||
{name: "exact limit", body: "body", expected: 4},
|
||||
{name: "content-length oversize", body: "large", expected: 5, want: errTooLarge},
|
||||
{name: "chunked oversize", body: "body", expected: 4, chunked: 5, want: errTooLarge},
|
||||
{
|
||||
name: "partial content", body: "body", expected: 4, partial: true,
|
||||
want: datasource.ErrFetchFailed, status: 206,
|
||||
},
|
||||
{name: "source changed", body: "body", expected: 5, want: errSourceChanged},
|
||||
{name: "empty", expected: 0, want: errEmptyFile},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.addFile(testRepoID, "/file", []byte(tc.body), 1)
|
||||
f.chunkedOversize["/file"] = tc.chunked
|
||||
f.partialContent["/file"] = tc.partial
|
||||
link, _, err := c.downloadLink(t.Context(), testRepoID, "/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := c.download(t.Context(), link, tc.expected, 4)
|
||||
if !errors.Is(err, tc.want) || statusOf(err) != tc.status {
|
||||
t.Fatalf("download = %v, want %v", err, tc.want)
|
||||
}
|
||||
if err == nil && string(body) != tc.body {
|
||||
t.Fatalf("body = %q", body)
|
||||
}
|
||||
if err != nil && (strings.Contains(err.Error(), link) || strings.Contains(err.Error(), testToken)) {
|
||||
t.Fatalf("download error leaked the link or token: %v", err)
|
||||
}
|
||||
if f.count("download:/file") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("unexpected retries: %v", f.counts())
|
||||
}
|
||||
assertNoCredentials(t, f.requests("download:/file"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRetries(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.addFile(testRepoID, "/file", []byte("body"), 1)
|
||||
f.fail("download:/file", 503, 2)
|
||||
link, _, err := c.downloadLink(t.Context(), testRepoID, "/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := c.download(t.Context(), link, 4, 4)
|
||||
if err != nil || string(body) != "body" || f.count("download:/file") != 3 ||
|
||||
!slices.Equal(*waits, []time.Duration{time.Second, 2 * time.Second}) {
|
||||
t.Fatalf("download retries = %v, counts = %v, waits = %v", err, f.counts(), *waits)
|
||||
}
|
||||
assertNoCredentials(t, f.requests("download:/file"))
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func TestDownloadSSRFBlocked(t *testing.T) {
|
||||
_, c, waits := testClient(t)
|
||||
calls := 0
|
||||
c.files.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return nil, errors.New("unexpected request")
|
||||
})
|
||||
link := "http://169.254.169.254/x"
|
||||
_, err := c.download(t.Context(), link, 1, 4)
|
||||
if !errors.Is(err, errSSRFBlocked) || !errors.Is(err, datasource.ErrFetchFailed) || calls != 0 || len(*waits) != 0 {
|
||||
t.Fatalf("download = %v, calls = %d", err, calls)
|
||||
}
|
||||
if strings.Contains(err.Error(), link) {
|
||||
t.Fatalf("blocked download leaked the URL: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRejectsUserinfo(t *testing.T) {
|
||||
_, c, waits := testClient(t)
|
||||
calls := 0
|
||||
c.files.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return nil, errors.New("unexpected request")
|
||||
})
|
||||
_, err := c.download(t.Context(), "http://user:secret@localhost/files/x", 1, 4)
|
||||
if !errors.Is(err, errInvalidResponse) || calls != 0 || len(*waits) != 0 {
|
||||
t.Fatalf("download = %v, calls = %d", err, calls)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("download error leaked userinfo: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkRetries(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
failure error
|
||||
failures int
|
||||
attempts int
|
||||
}{
|
||||
{"dial recovered", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New(testToken)}, 2, 3},
|
||||
{"dial exhausted", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New(testToken)}, 3, 3},
|
||||
{"timeout recovered", &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}, 2, 3},
|
||||
{"other error", errors.New(testToken), 3, 1},
|
||||
{"SSRF redirect", utils.ErrSSRFRedirectBlocked, 3, 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, c, waits := testClient(t)
|
||||
base := c.api.Transport
|
||||
attempts := 0
|
||||
c.api.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
attempts++
|
||||
if attempts <= tc.failures {
|
||||
return nil, tc.failure
|
||||
}
|
||||
return base.RoundTrip(r)
|
||||
})
|
||||
err := c.ping(t.Context())
|
||||
if (err == nil) != (tc.failures < tc.attempts) || attempts != tc.attempts || len(*waits) != tc.attempts-1 {
|
||||
t.Fatalf("ping = %v, attempts = %d, waits = %v", err, attempts, *waits)
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), testToken) {
|
||||
t.Fatalf("transport error leaked the token: %v", err)
|
||||
}
|
||||
if err != nil && !errors.Is(err, datasource.ErrFetchFailed) {
|
||||
t.Fatalf("transport error must wrap ErrFetchFailed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanceledContext(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
err := c.ping(ctx)
|
||||
if !errors.Is(err, context.Canceled) || f.count("ping") != 0 || len(*waits) != 0 {
|
||||
t.Fatalf("canceled ping = %v, counts = %v", err, f.counts())
|
||||
}
|
||||
if err := sleepCtx(ctx, time.Hour); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("sleepCtx ignored cancellation: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectPolicy(t *testing.T) {
|
||||
t.Run("download redirected to private address", func(t *testing.T) {
|
||||
f, c, waits := testClient(t)
|
||||
f.addFile(testRepoID, "/file", []byte("body"), 1)
|
||||
f.redirects["download:/file"] = "http://169.254.169.254/private-signed-link"
|
||||
link, _, err := c.downloadLink(t.Context(), testRepoID, "/file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = c.download(t.Context(), link, 4, 4)
|
||||
if !errors.Is(err, errSSRFBlocked) || f.count("download:/file") != 1 || len(*waits) != 0 {
|
||||
t.Fatalf("redirect = %v, counts = %v", err, f.counts())
|
||||
}
|
||||
if strings.Contains(err.Error(), "private-signed-link") {
|
||||
t.Fatalf("redirect error leaked the target: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("api redirected to private address", func(t *testing.T) {
|
||||
f, c, _ := testClient(t)
|
||||
f.redirects["repos"] = "http://169.254.169.254/"
|
||||
_, err := c.listRepos(t.Context())
|
||||
if !errors.Is(err, datasource.ErrFetchFailed) || errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Fatalf("listRepos = %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("cross-origin hop strips the token", func(t *testing.T) {
|
||||
f, c, _ := testClient(t)
|
||||
f.addFile(testRepoID, "/pong", []byte(`"pong"`), 1)
|
||||
link, _, err := c.downloadLink(t.Context(), testRepoID, "/pong")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.redirects["ping"] = link
|
||||
f.mu.Unlock()
|
||||
if err := c.ping(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requests := f.requests("download:/pong")
|
||||
if len(requests) != 1 {
|
||||
t.Fatalf("download requests = %d", len(requests))
|
||||
}
|
||||
assertNoCredentials(t, requests)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
var (
|
||||
_ datasource.Connector = (*Connector)(nil)
|
||||
_ datasource.StreamingConnector = (*Connector)(nil)
|
||||
_ datasource.FullStreamingConnector = (*Connector)(nil)
|
||||
)
|
||||
|
||||
// Connector is stateless: every data source carries its own server URL and
|
||||
// API token in its encrypted credentials.
|
||||
type Connector struct{}
|
||||
|
||||
// NewConnector creates the Seafile connector registered in the container.
|
||||
func NewConnector() *Connector { return &Connector{} }
|
||||
|
||||
// Type returns the connector type key stored on data sources.
|
||||
func (*Connector) Type() string { return types.ConnectorTypeSeafile }
|
||||
|
||||
// Validate checks the selection locally, pings Seafile with the token and,
|
||||
// when resources are selected, confirms they belong to one existing,
|
||||
// unencrypted library; it never lists directories.
|
||||
func (*Connector) Validate(ctx context.Context, ds *types.DataSourceConfig) error {
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var repoID string
|
||||
if len(ds.ResourceIDs) > 0 {
|
||||
if repoID, _, err = collapseRoots(ds.ResourceIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
client := newClient(cfg)
|
||||
if err := client.ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if repoID == "" {
|
||||
return nil
|
||||
}
|
||||
repos, err := client.listRepos(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = selectedRepo(repos, repoID)
|
||||
return err
|
||||
}
|
||||
|
||||
func selectedRepo(repos []repoInfo, repoID string) (repoInfo, error) {
|
||||
for _, repo := range repos {
|
||||
if repo.ID != repoID {
|
||||
continue
|
||||
}
|
||||
if repo.Encrypted {
|
||||
return repoInfo{}, fmt.Errorf("%w: encrypted Seafile libraries are not supported",
|
||||
datasource.ErrInvalidConfig)
|
||||
}
|
||||
return repo, nil
|
||||
}
|
||||
return repoInfo{}, fmt.Errorf("%w: Seafile library %s", datasource.ErrResourceNotFound, repoID)
|
||||
}
|
||||
|
||||
// ListResources returns the unencrypted libraries for an empty parent and one
|
||||
// directory level otherwise. Files with unsupported extensions are omitted so
|
||||
// the picker only offers what a sync would import. Entries the sync would
|
||||
// reject are skipped here rather than failing the whole level: the picker
|
||||
// stays browsable and the sync reports the strict failure on its own.
|
||||
func (*Connector) ListResources(
|
||||
ctx context.Context, ds *types.DataSourceConfig, parentID string,
|
||||
) ([]types.Resource, error) {
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := newClient(cfg)
|
||||
var out []types.Resource
|
||||
if parentID == "" {
|
||||
out, err = listLibraries(ctx, client)
|
||||
} else {
|
||||
out, err = listDirectory(ctx, client, parentID)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].Name != out[j].Name {
|
||||
return out[i].Name < out[j].Name
|
||||
}
|
||||
return out[i].ExternalID < out[j].ExternalID
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func listLibraries(ctx context.Context, client *client) ([]types.Resource, error) {
|
||||
repos, err := client.listRepos(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]types.Resource, 0, len(repos))
|
||||
for _, repo := range repos {
|
||||
if repo.Encrypted {
|
||||
continue
|
||||
}
|
||||
out = append(out, types.Resource{
|
||||
ExternalID: encodeResourceID(repo.ID, "/"),
|
||||
Name: repo.Name,
|
||||
Type: "library",
|
||||
Description: repo.Type,
|
||||
HasChildren: true,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func listDirectory(ctx context.Context, client *client, parentID string) ([]types.Resource, error) {
|
||||
repoID, dir, err := parseResourceID(parentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := client.listDir(ctx, repoID, dir)
|
||||
if err != nil {
|
||||
return nil, mapDirError(err, dir)
|
||||
}
|
||||
out := make([]types.Resource, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if !validEntryName(e.Name) {
|
||||
continue
|
||||
}
|
||||
var kind string
|
||||
switch e.Type {
|
||||
case "dir":
|
||||
kind = "directory"
|
||||
case "file":
|
||||
if !utils.IsSupportedImportExtension(path.Ext(e.Name)) {
|
||||
continue
|
||||
}
|
||||
kind = "file"
|
||||
default:
|
||||
continue
|
||||
}
|
||||
out = append(out, types.Resource{
|
||||
ExternalID: encodeResourceID(repoID, path.Join(dir, e.Name)),
|
||||
Name: e.Name,
|
||||
Type: kind,
|
||||
ParentID: parentID,
|
||||
HasChildren: e.Type == "dir",
|
||||
ModifiedAt: time.Unix(e.Mtime, 0).UTC(),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// mapDirError classifies a directory listing failure: 404 means the resource
|
||||
// is gone, 403 is a permission scoping problem rather than a bad token. The
|
||||
// 403 message carries the reason code so the sync log names the cause the
|
||||
// same way error items do.
|
||||
func mapDirError(err error, p string) error {
|
||||
switch statusOf(err) {
|
||||
case http.StatusNotFound:
|
||||
return fmt.Errorf("%w: Seafile path %s", datasource.ErrResourceNotFound, p)
|
||||
case http.StatusForbidden:
|
||||
return fmt.Errorf("%w: %s: Seafile path %s", datasource.ErrFetchFailed, reasonPermissionDenied, p)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveResourceAncestors derives ancestors from the IDs alone; no request
|
||||
// is made and unparsable IDs contribute nothing.
|
||||
func (*Connector) ResolveResourceAncestors(
|
||||
_ context.Context, _ *types.DataSourceConfig, ids []string,
|
||||
) ([]string, error) {
|
||||
seen := make(map[string]bool)
|
||||
out := make([]string, 0)
|
||||
for _, id := range ids {
|
||||
for _, ancestor := range ancestorIDs(id) {
|
||||
if !seen[ancestor] {
|
||||
seen[ancestor] = true
|
||||
out = append(out, ancestor)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// collector adapts the streaming engine to the collecting Connector methods.
|
||||
type collector struct{ items []types.FetchedItem }
|
||||
|
||||
func (h *collector) Emit(_ context.Context, item types.FetchedItem) error {
|
||||
h.items = append(h.items, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*collector) Checkpoint(context.Context, *types.SyncCursor) error { return nil }
|
||||
|
||||
// FetchAll collects a fresh sync of the given resources without a cursor.
|
||||
func (c *Connector) FetchAll(
|
||||
ctx context.Context, ds *types.DataSourceConfig, resourceIDs []string,
|
||||
) ([]types.FetchedItem, error) {
|
||||
if ds == nil {
|
||||
return nil, datasource.ErrInvalidConfig
|
||||
}
|
||||
dsCopy := *ds
|
||||
dsCopy.ResourceIDs = resourceIDs
|
||||
items, _, err := c.FetchIncremental(ctx, &dsCopy, nil)
|
||||
return items, err
|
||||
}
|
||||
|
||||
// FetchIncremental collects one streaming run into memory.
|
||||
func (c *Connector) FetchIncremental(
|
||||
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor,
|
||||
) ([]types.FetchedItem, *types.SyncCursor, error) {
|
||||
h := &collector{}
|
||||
next, err := c.FetchStream(ctx, ds, old, h)
|
||||
return h.items, next, err
|
||||
}
|
||||
|
||||
// FetchStream is the production sync path: it scans the selected scope,
|
||||
// emits changed files as they are downloaded and checkpoints the cursor so
|
||||
// an interrupted run resumes instead of restarting.
|
||||
func (c *Connector) FetchStream(
|
||||
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
|
||||
) (*types.SyncCursor, error) {
|
||||
return c.runSync(ctx, ds, old, h, false)
|
||||
}
|
||||
|
||||
// FetchFullStream re-downloads every file while keeping the old cursor as a
|
||||
// deletion baseline until the run completes.
|
||||
func (c *Connector) FetchFullStream(
|
||||
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor, h datasource.StreamHandler,
|
||||
) (*types.SyncCursor, error) {
|
||||
return c.runSync(ctx, ds, old, h, true)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
)
|
||||
|
||||
func TestConnectorResources(t *testing.T) {
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
f.addRepo(testRepoID, "Zulu", "repo", false)
|
||||
f.addRepo(otherRepoID, "Alpha", "srepo", false)
|
||||
f.addRepo("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Hidden", "repo", true)
|
||||
cfg := syncConfig(f)
|
||||
c := NewConnector()
|
||||
if c.Type() != "seafile" {
|
||||
t.Fatalf("Type = %q", c.Type())
|
||||
}
|
||||
got, err := c.ListResources(t.Context(), cfg, "")
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatalf("libraries = %+v, %v", got, err)
|
||||
}
|
||||
for i, want := range []struct{ id, name, typ string }{
|
||||
{otherRepoID, "Alpha", "srepo"}, {testRepoID, "Zulu", "repo"},
|
||||
} {
|
||||
r := got[i]
|
||||
if r.ExternalID != want.id+":/" || r.Name != want.name ||
|
||||
r.Type != "library" || r.Description != want.typ || !r.HasChildren {
|
||||
t.Fatalf("library[%d] = %+v", i, r)
|
||||
}
|
||||
}
|
||||
p := "/产品/100% 文档"
|
||||
f.addDir(testRepoID, p+"/子目录")
|
||||
f.addFile(testRepoID, p+"/说明.pdf", []byte("pdf"), 1)
|
||||
f.addFile(testRepoID, p+"/archive.zip", []byte("zip"), 1)
|
||||
f.addFile(testRepoID, p+"/page.mdx", []byte("mdx"), 1)
|
||||
parent := testRepoID + ":" + p
|
||||
got, err = c.ListResources(t.Context(), cfg, parent)
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatalf("children = %+v, %v", got, err)
|
||||
}
|
||||
wantTypes := map[string]string{"子目录": "directory", "说明.pdf": "file"}
|
||||
for _, r := range got {
|
||||
typ, ok := wantTypes[r.Name]
|
||||
if !ok || r.Type != typ || r.HasChildren != (typ == "directory") ||
|
||||
r.ParentID != parent || r.ExternalID != parent+"/"+r.Name {
|
||||
t.Fatalf("child = %+v", r)
|
||||
}
|
||||
delete(wantTypes, r.Name)
|
||||
}
|
||||
reqs := f.requests("dir:" + p)
|
||||
if len(reqs) != 1 || reqs[0].RawQuery != (url.Values{"p": {p}}).Encode() {
|
||||
t.Fatalf("directory query was not encoded exactly once: %+v", reqs)
|
||||
}
|
||||
_, err = c.ListResources(t.Context(), cfg, testRepoID+":/missing")
|
||||
if !errors.Is(err, datasource.ErrResourceNotFound) {
|
||||
t.Fatalf("missing directory = %v", err)
|
||||
}
|
||||
f.fail("repos", 403, -1)
|
||||
_, err = c.ListResources(t.Context(), cfg, "")
|
||||
if !errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Fatalf("forbidden libraries = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorAncestors(t *testing.T) {
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
c := NewConnector()
|
||||
cfg := syncConfig(f)
|
||||
got, err := c.ResolveResourceAncestors(t.Context(), cfg, []string{
|
||||
testRepoID + ":/a/b/c/d.pdf", testRepoID + ":/a/b/e.pdf",
|
||||
testRepoID + ":/a/b/c/d.pdf", testRepoID + ":/",
|
||||
})
|
||||
want := []string{testRepoID + ":/", testRepoID + ":/a", testRepoID + ":/a/b", testRepoID + ":/a/b/c"}
|
||||
if err != nil || !slices.Equal(got, want) {
|
||||
t.Fatalf("ancestors = %v, %v; want %v", got, err, want)
|
||||
}
|
||||
got, err = c.ResolveResourceAncestors(t.Context(), cfg, []string{testRepoID + ":/"})
|
||||
if err != nil || len(got) != 0 || len(f.counts()) != 0 {
|
||||
t.Fatalf("root ancestors = %v, %v; requests = %v", got, err, f.counts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
roots []string
|
||||
encrypted bool
|
||||
want error
|
||||
}{
|
||||
{"credentials only", nil, false, nil},
|
||||
{"selected directory", []string{"/docs"}, false, nil},
|
||||
{"two repositories", []string{"/docs", "other"}, false, datasource.ErrInvalidConfig},
|
||||
{"encrypted", []string{"/docs"}, true, datasource.ErrInvalidConfig},
|
||||
{"unknown repository", []string{"other"}, false, datasource.ErrResourceNotFound},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
f.addRepo(testRepoID, "Library", "repo", tc.encrypted)
|
||||
f.addDir(testRepoID, "/docs")
|
||||
cfg := syncConfig(f, tc.roots...)
|
||||
for i, p := range tc.roots {
|
||||
if p == "other" {
|
||||
cfg.ResourceIDs[i] = otherRepoID + ":/"
|
||||
}
|
||||
}
|
||||
err := NewConnector().Validate(t.Context(), cfg)
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("Validate = %v; want %v", err, tc.want)
|
||||
}
|
||||
if tc.want == nil && f.count("ping") != 1 {
|
||||
t.Fatalf("Validate did not ping: %v", f.counts())
|
||||
}
|
||||
if tc.encrypted && f.countPrefix("dir:") != 0 {
|
||||
t.Fatalf("encrypted repository was traversed: %v", f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorEmptySelection(t *testing.T) {
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
h := &recorder{}
|
||||
_, err := run(t, NewConnector(), syncConfig(f), nil, h, false)
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) || len(f.counts()) != 0 ||
|
||||
len(h.items) != 0 || len(h.checkpoints) != 0 {
|
||||
t.Fatalf("empty selection = %v; requests = %v; handler = %+v", err, f.counts(), h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorBatchWrappers(t *testing.T) {
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
f.addRepo(testRepoID, "Library", "repo", false)
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
f.addFile(testRepoID, "/outside/b.pdf", []byte("b"), 1)
|
||||
c := NewConnector()
|
||||
cfg := syncConfig(f, "/outside")
|
||||
items, err := c.FetchAll(t.Context(), cfg, []string{testRepoID + ":/docs"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPaths(t, items, "/docs/a.pdf")
|
||||
cfg = syncConfig(f, "/docs")
|
||||
items, cur, err := c.FetchIncremental(t.Context(), cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPaths(t, items, "/docs/a.pdf")
|
||||
f.touch(testRepoID, "/docs/a.pdf")
|
||||
items, cur, err = c.FetchIncremental(t.Context(), cfg, cur)
|
||||
if err != nil || len(filesOf(cur)) != 1 {
|
||||
t.Fatalf("incremental wrapper = %v, cursor = %+v", err, cur)
|
||||
}
|
||||
assertPaths(t, items, "/docs/a.pdf")
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const cursorSchemaVersion = 1
|
||||
|
||||
// cursor is the connector state persisted between runs. Files maps every
|
||||
// known path to its fingerprint; an empty fingerprint marks a path whose
|
||||
// fetch failed and must be retried. FullSync and FullSyncBaseline exist only
|
||||
// while a forced full run is in progress (same shape as Confluence).
|
||||
type cursor struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
RepoID string `json:"repo_id"`
|
||||
RepoName string `json:"repo_name"`
|
||||
Files map[string]string `json:"files"`
|
||||
FullSync bool `json:"full_sync,omitempty"`
|
||||
FullSyncBaseline map[string]string `json:"full_sync_baseline,omitempty"`
|
||||
}
|
||||
|
||||
// decodeCursor accepts a nil or empty cursor as a fresh state; anything else
|
||||
// must carry the current schema version.
|
||||
func decodeCursor(old *types.SyncCursor) (cursor, error) {
|
||||
c := cursor{SchemaVersion: cursorSchemaVersion}
|
||||
if old != nil && len(old.ConnectorCursor) > 0 {
|
||||
c.SchemaVersion = 0
|
||||
raw, err := json.Marshal(old.ConnectorCursor)
|
||||
if err == nil {
|
||||
err = json.Unmarshal(raw, &c)
|
||||
}
|
||||
if err != nil {
|
||||
return cursor{}, fmt.Errorf("%w: invalid Seafile cursor: %w", datasource.ErrInvalidConfig, err)
|
||||
}
|
||||
if c.SchemaVersion != cursorSchemaVersion {
|
||||
return cursor{}, fmt.Errorf("%w: unsupported Seafile cursor schema %d",
|
||||
datasource.ErrInvalidConfig, c.SchemaVersion)
|
||||
}
|
||||
}
|
||||
if c.Files == nil {
|
||||
c.Files = make(map[string]string)
|
||||
}
|
||||
if c.FullSyncBaseline == nil {
|
||||
c.FullSyncBaseline = make(map[string]string)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// toSyncCursor produces a snapshot independent of the working maps through a
|
||||
// JSON round trip, so the service can serialize it after the run moves on.
|
||||
// Neither step can fail: the cursor is plain strings and string maps.
|
||||
func (c *cursor) toSyncCursor() *types.SyncCursor {
|
||||
raw, _ := json.Marshal(c)
|
||||
fields := map[string]interface{}{}
|
||||
_ = json.Unmarshal(raw, &fields)
|
||||
return &types.SyncCursor{LastSyncTime: time.Now().UTC(), ConnectorCursor: fields}
|
||||
}
|
||||
|
||||
// prepareCursor decodes the previous cursor, enforces the library binding and
|
||||
// switches into full-sync mode when requested. The returned flag reports
|
||||
// whether the cursor changed and therefore needs saving.
|
||||
func prepareCursor(old *types.SyncCursor, repoID string, forceFull bool) (cursor, bool, error) {
|
||||
c, err := decodeCursor(old)
|
||||
if err != nil {
|
||||
return cursor{}, false, err
|
||||
}
|
||||
if c.RepoID != "" && c.RepoID != repoID {
|
||||
return cursor{}, false, fmt.Errorf(
|
||||
"%w: this data source already synced Seafile library %q; restore that library "+
|
||||
"or create a new data source instead of switching to %s",
|
||||
datasource.ErrInvalidConfig, c.RepoName, repoID)
|
||||
}
|
||||
changed := false
|
||||
if c.RepoID == "" {
|
||||
c.RepoID = repoID
|
||||
changed = true
|
||||
}
|
||||
if forceFull && !c.FullSync {
|
||||
c.FullSyncBaseline = maps.Clone(c.Files)
|
||||
c.Files = make(map[string]string)
|
||||
c.FullSync = true
|
||||
changed = true
|
||||
}
|
||||
return c, changed, nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
c, _, err := prepareCursor(nil, testRepoID, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.RepoName = "原资料库"
|
||||
c.Files = map[string]string{"/ok.pdf": "o:abc|m:1|s:3", "/retry.pdf": ""}
|
||||
c.FullSync = true
|
||||
c.FullSyncBaseline = map[string]string{"/gone.pdf": "old", "/pending.pdf": ""}
|
||||
data, err := json.Marshal(c.toSyncCursor())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wire types.SyncCursor
|
||||
if err := json.Unmarshal(data, &wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"schema_version", "repo_id", "repo_name", "files", "full_sync", "full_sync_baseline"} {
|
||||
if _, ok := wire.ConnectorCursor[key]; !ok {
|
||||
t.Errorf("cursor missing JSON key %q", key)
|
||||
}
|
||||
}
|
||||
got, err := decodeCursor(&wire)
|
||||
if err != nil || !reflect.DeepEqual(got, c) {
|
||||
t.Fatalf("round trip = %+v, %v; want %+v", got, err, c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorEmptyAndUnknownVersion(t *testing.T) {
|
||||
got, err := decodeCursor(nil)
|
||||
if err != nil || got.Files == nil || len(got.Files) != 0 || len(got.FullSyncBaseline) != 0 {
|
||||
t.Fatalf("nil cursor = %+v, %v", got, err)
|
||||
}
|
||||
old := &types.SyncCursor{ConnectorCursor: map[string]any{"schema_version": 999999}}
|
||||
if _, err := decodeCursor(old); !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("unknown schema = %v", err)
|
||||
}
|
||||
if _, _, err := prepareCursor(old, testRepoID, false); !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("prepare unknown schema = %v", err)
|
||||
}
|
||||
// A non-empty cursor from another connector or a truncated write carries
|
||||
// no usable version and must not be reinterpreted as Seafile state.
|
||||
for name, foreign := range map[string]map[string]any{
|
||||
"missing version": {"files": map[string]any{"/a.pdf": "x"}},
|
||||
"null version": {"schema_version": nil, "repo_id": testRepoID},
|
||||
"zero version": {"schema_version": 0, "repo_id": testRepoID},
|
||||
} {
|
||||
_, err := decodeCursor(&types.SyncCursor{ConnectorCursor: foreign})
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("%s = %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareCursorFullSync(t *testing.T) {
|
||||
old := seededCursor(t, "Library", map[string]string{"/a.pdf": "a", "/pending.pdf": ""})
|
||||
before := cursorJSON(t, old)
|
||||
c, changed, err := prepareCursor(old, testRepoID, true)
|
||||
if err != nil || !changed || !c.FullSync || len(c.Files) != 0 ||
|
||||
!reflect.DeepEqual(c.FullSyncBaseline, filesOf(old)) {
|
||||
t.Fatalf("prepare full = %+v, changed=%v, err=%v", c, changed, err)
|
||||
}
|
||||
c.FullSyncBaseline["/a.pdf"] = "mutated"
|
||||
c.Files["/new.pdf"] = "new"
|
||||
if cursorJSON(t, old) != before {
|
||||
t.Fatal("full cursor aliases the old cursor")
|
||||
}
|
||||
c.FullSyncBaseline["/a.pdf"] = "a"
|
||||
active := c.toSyncCursor()
|
||||
before = cursorJSON(t, active)
|
||||
for _, force := range []bool{false, true} {
|
||||
resumed, _, err := prepareCursor(active, testRepoID, force)
|
||||
if err != nil || !resumed.FullSync || !reflect.DeepEqual(resumed.Files, c.Files) ||
|
||||
!reflect.DeepEqual(resumed.FullSyncBaseline, c.FullSyncBaseline) {
|
||||
t.Fatalf("resume force=%v: %+v, %v", force, resumed, err)
|
||||
}
|
||||
}
|
||||
if cursorJSON(t, active) != before {
|
||||
t.Fatal("prepare mutated an active full-sync cursor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorRepositoryMismatchBeforeHTTP(t *testing.T) {
|
||||
old := seededCursor(t, "原资料库", map[string]string{"/a.pdf": "saved"})
|
||||
before := cursorJSON(t, old)
|
||||
_, _, err := prepareCursor(old, otherRepoID, false)
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) || !strings.Contains(err.Error(), "原资料库") {
|
||||
t.Fatalf("prepare mismatch = %v", err)
|
||||
}
|
||||
f := newFakeSeafile(t)
|
||||
cfg := syncConfig(f)
|
||||
cfg.ResourceIDs = []string{otherRepoID + ":/"}
|
||||
h := &recorder{}
|
||||
_, err = run(t, NewConnector(), cfg, old, h, false)
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) || !strings.Contains(err.Error(), "原资料库") {
|
||||
t.Fatalf("stream mismatch = %v", err)
|
||||
}
|
||||
if len(f.counts()) != 0 || len(h.items) != 0 || len(h.checkpoints) != 0 || cursorJSON(t, old) != before {
|
||||
t.Fatalf("mismatch had side effects: requests=%v, handler=%+v", f.counts(), h)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// TestMain whitelists loopback for SSRF so the httptest servers are reachable.
|
||||
// Production keeps the default strict policy.
|
||||
func TestMain(m *testing.M) {
|
||||
_ = os.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
utils.ResetSSRFWhitelistForTest()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
type fakeNode struct {
|
||||
Type string
|
||||
ID string
|
||||
Mtime int64
|
||||
Body []byte
|
||||
}
|
||||
|
||||
type fakeLocation struct{ repo, path string }
|
||||
|
||||
type fakeRequest struct {
|
||||
Headers http.Header
|
||||
RawQuery string
|
||||
}
|
||||
|
||||
type fakeFailure struct {
|
||||
status int
|
||||
remaining int // negative repeats forever
|
||||
retryAfter string
|
||||
}
|
||||
|
||||
// fakeSeafile is an in-process stand-in for a Seafile 10.0.1 deployment with
|
||||
// the API and the fileserver on separate servers. Requests are keyed as
|
||||
// "ping", "repos", "dir:<path>", "file:<path>" and "download:<path>"; the
|
||||
// same keys drive failure injection.
|
||||
type fakeSeafile struct {
|
||||
api *httptest.Server
|
||||
fileserver *httptest.Server
|
||||
// prefix simulates a deployment path such as "/seafile".
|
||||
prefix string
|
||||
|
||||
mu sync.Mutex
|
||||
repos []repoInfo
|
||||
tree map[string]map[string]*fakeNode // repo → path → node
|
||||
forbidden map[string]bool // directory listings answering 403
|
||||
|
||||
failures map[string]*fakeFailure
|
||||
rawBody map[string]string // raw 200 body per key
|
||||
redirects map[string]string // 302 target per key
|
||||
linkOID map[string]string // path → oid header override
|
||||
linkURL map[string]string // path → download link override
|
||||
chunkedOversize map[string]int64 // path → bytes streamed without Content-Length
|
||||
partialContent map[string]bool // path → answer 206
|
||||
|
||||
tokens map[string]fakeLocation
|
||||
calls map[string]int
|
||||
seen map[string][]fakeRequest
|
||||
}
|
||||
|
||||
func newFakeSeafile(t *testing.T) *fakeSeafile {
|
||||
t.Helper()
|
||||
f := &fakeSeafile{
|
||||
tree: map[string]map[string]*fakeNode{},
|
||||
forbidden: map[string]bool{},
|
||||
failures: map[string]*fakeFailure{},
|
||||
rawBody: map[string]string{},
|
||||
redirects: map[string]string{},
|
||||
linkOID: map[string]string{},
|
||||
linkURL: map[string]string{},
|
||||
chunkedOversize: map[string]int64{},
|
||||
partialContent: map[string]bool{},
|
||||
tokens: map[string]fakeLocation{},
|
||||
calls: map[string]int{},
|
||||
seen: map[string][]fakeRequest{},
|
||||
}
|
||||
f.fileserver = httptest.NewServer(http.HandlerFunc(f.handleDownload))
|
||||
t.Cleanup(f.fileserver.Close)
|
||||
f.api = httptest.NewServer(http.HandlerFunc(f.handleAPI))
|
||||
t.Cleanup(f.api.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) baseURL() string { return f.api.URL + f.prefix }
|
||||
|
||||
func (f *fakeSeafile) addRepo(id, name, typ string, encrypted bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.repos = append(f.repos, repoInfo{ID: id, Name: name, Type: typ, Encrypted: encrypted, Permission: "rw"})
|
||||
f.addDirLocked(id, "/")
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) renameRepo(id, name string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for i := range f.repos {
|
||||
if f.repos[i].ID == id {
|
||||
f.repos[i].Name = name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) addDirLocked(repo, p string) {
|
||||
if f.tree[repo] == nil {
|
||||
f.tree[repo] = map[string]*fakeNode{}
|
||||
}
|
||||
for {
|
||||
if f.tree[repo][p] == nil {
|
||||
f.tree[repo][p] = &fakeNode{Type: "dir", ID: "dir-" + p}
|
||||
}
|
||||
if p == "/" {
|
||||
return
|
||||
}
|
||||
p = path.Dir(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) addDir(repo, p string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.addDirLocked(repo, p)
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) addFile(repo, p string, body []byte, mtime int64) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.addDirLocked(repo, path.Dir(p))
|
||||
f.tree[repo][p] = &fakeNode{
|
||||
Type: "file", ID: fmt.Sprintf("%x", sha1.Sum(body)), Mtime: mtime, Body: bytes.Clone(body),
|
||||
}
|
||||
}
|
||||
|
||||
// removePath deletes a file or a directory subtree.
|
||||
func (f *fakeSeafile) removePath(repo, p string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for name := range f.tree[repo] {
|
||||
if name == p || strings.HasPrefix(name, strings.TrimSuffix(p, "/")+"/") {
|
||||
delete(f.tree[repo], name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// movePath renames a file or directory subtree, keeping oids and mtimes.
|
||||
func (f *fakeSeafile) movePath(repo, from, to string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
moved := map[string]*fakeNode{}
|
||||
for name, node := range f.tree[repo] {
|
||||
if name == from || strings.HasPrefix(name, from+"/") {
|
||||
moved[to+strings.TrimPrefix(name, from)] = node
|
||||
delete(f.tree[repo], name)
|
||||
}
|
||||
}
|
||||
f.addDirLocked(repo, path.Dir(to))
|
||||
for name, node := range moved {
|
||||
f.tree[repo][name] = node
|
||||
}
|
||||
}
|
||||
|
||||
// setBody replaces a file's content, which changes its oid and bumps mtime.
|
||||
func (f *fakeSeafile) setBody(repo, p string, body []byte) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if node := f.tree[repo][p]; node != nil {
|
||||
node.Body = bytes.Clone(body)
|
||||
node.ID = fmt.Sprintf("%x", sha1.Sum(body))
|
||||
node.Mtime++
|
||||
}
|
||||
}
|
||||
|
||||
// touch bumps a file's mtime without changing its content or oid.
|
||||
func (f *fakeSeafile) touch(repo, p string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if node := f.tree[repo][p]; node != nil {
|
||||
node.Mtime++
|
||||
}
|
||||
}
|
||||
|
||||
// fail makes the next count requests for key answer status (count < 0: always).
|
||||
func (f *fakeSeafile) fail(key string, status, count int) {
|
||||
f.failWithRetryAfter(key, status, count, "")
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) failWithRetryAfter(key string, status, count int, retryAfter string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.failures[key] = &fakeFailure{status: status, remaining: count, retryAfter: retryAfter}
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) count(key string) int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls[key]
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) counts() map[string]int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := make(map[string]int, len(f.calls))
|
||||
for key, n := range f.calls {
|
||||
out[key] = n
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) resetCounts() {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = map[string]int{}
|
||||
f.seen = map[string][]fakeRequest{}
|
||||
}
|
||||
|
||||
// countPrefix sums the counters whose key starts with prefix ("dir:", "download:").
|
||||
func (f *fakeSeafile) countPrefix(prefix string) int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
total := 0
|
||||
for key, n := range f.calls {
|
||||
if strings.HasPrefix(key, prefix) {
|
||||
total += n
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) requests(key string) []fakeRequest {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := make([]fakeRequest, 0, len(f.seen[key]))
|
||||
for _, req := range f.seen[key] {
|
||||
out = append(out, fakeRequest{Headers: req.Headers.Clone(), RawQuery: req.RawQuery})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The handler helpers below run with mu held.
|
||||
|
||||
func (f *fakeSeafile) record(key string, r *http.Request) {
|
||||
f.calls[key]++
|
||||
f.seen[key] = append(f.seen[key], fakeRequest{Headers: r.Header.Clone(), RawQuery: r.URL.RawQuery})
|
||||
}
|
||||
|
||||
// injected serves a configured redirect, failure or raw body for key.
|
||||
func (f *fakeSeafile) injected(w http.ResponseWriter, r *http.Request, key string) bool {
|
||||
if target, ok := f.redirects[key]; ok {
|
||||
http.Redirect(w, r, target, http.StatusFound)
|
||||
return true
|
||||
}
|
||||
if failure := f.failures[key]; failure != nil && failure.remaining != 0 {
|
||||
if failure.remaining > 0 {
|
||||
failure.remaining--
|
||||
}
|
||||
if failure.retryAfter != "" {
|
||||
w.Header().Set("Retry-After", failure.retryAfter)
|
||||
}
|
||||
w.WriteHeader(failure.status)
|
||||
_, _ = w.Write([]byte("injected failure"))
|
||||
return true
|
||||
}
|
||||
if body, ok := f.rawBody[key]; ok {
|
||||
_, _ = w.Write([]byte(body))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) handleAPI(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Method != http.MethodGet || !strings.HasPrefix(r.URL.Path, f.prefix+"/api2/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
route := strings.TrimPrefix(r.URL.Path, f.prefix)
|
||||
switch route {
|
||||
case "/api2/auth/ping/":
|
||||
f.record("ping", r)
|
||||
if !f.injected(w, r, "ping") {
|
||||
_ = json.NewEncoder(w).Encode("pong")
|
||||
}
|
||||
return
|
||||
case "/api2/repos/":
|
||||
f.record("repos", r)
|
||||
if !f.injected(w, r, "repos") {
|
||||
_ = json.NewEncoder(w).Encode(f.repos)
|
||||
}
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.Trim(route, "/"), "/")
|
||||
if len(parts) != 4 || parts[0] != "api2" || parts[1] != "repos" || (parts[3] != "dir" && parts[3] != "file") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
repo, op, p := parts[2], parts[3], r.URL.Query().Get("p")
|
||||
key := op + ":" + p
|
||||
f.record(key, r)
|
||||
if f.injected(w, r, key) {
|
||||
return
|
||||
}
|
||||
node := f.tree[repo][p]
|
||||
if op == "dir" {
|
||||
if f.forbidden[p] {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if node == nil || node.Type != "dir" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
f.writeDir(w, repo, p)
|
||||
return
|
||||
}
|
||||
if node == nil || node.Type != "file" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("reuse") != "1" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
oid := node.ID
|
||||
if override, ok := f.linkOID[p]; ok {
|
||||
oid = override
|
||||
}
|
||||
w.Header().Set("oid", oid)
|
||||
token := fmt.Sprintf("download-token-%d", len(f.tokens)+1)
|
||||
f.tokens[token] = fakeLocation{repo: repo, path: p}
|
||||
link := f.fileserver.URL + "/files/" + token
|
||||
if override, ok := f.linkURL[p]; ok {
|
||||
link = override
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(link)
|
||||
}
|
||||
|
||||
// writeDir renders one level like seahub: every entry carries id, name, type,
|
||||
// mtime and permission; only files carry size.
|
||||
func (f *fakeSeafile) writeDir(w http.ResponseWriter, repo, dir string) {
|
||||
entries := make([]map[string]any, 0)
|
||||
for name, node := range f.tree[repo] {
|
||||
if name == dir || path.Dir(name) != dir {
|
||||
continue
|
||||
}
|
||||
entry := map[string]any{
|
||||
"id": node.ID, "name": path.Base(name), "type": node.Type,
|
||||
"mtime": node.Mtime, "permission": "rw",
|
||||
}
|
||||
if node.Type == "file" {
|
||||
entry["size"] = len(node.Body)
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
return entries[i]["name"].(string) < entries[j]["name"].(string)
|
||||
})
|
||||
_ = json.NewEncoder(w).Encode(entries)
|
||||
}
|
||||
|
||||
func (f *fakeSeafile) handleDownload(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
location, ok := f.tokens[strings.TrimPrefix(r.URL.Path, "/files/")]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
p := location.path
|
||||
key := "download:" + p
|
||||
f.record(key, r)
|
||||
if f.injected(w, r, key) {
|
||||
return
|
||||
}
|
||||
node := f.tree[location.repo][p]
|
||||
if node == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if f.partialContent[p] {
|
||||
status = http.StatusPartialContent
|
||||
}
|
||||
if n := f.chunkedOversize[p]; n > 0 {
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(bytes.Repeat([]byte("x"), int(n-1)))
|
||||
w.(http.Flusher).Flush()
|
||||
_, _ = w.Write([]byte("x"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(node.Body)))
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write(node.Body)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"academy/internal/datasource"
|
||||
)
|
||||
|
||||
// knowledgeFileName maps a library file to the knowledge base folder
|
||||
// convention "<library name>/<path inside the library>". Every segment is
|
||||
// sanitized on its own; depth and length limits are applied by the service.
|
||||
func knowledgeFileName(repoName, filePath string) string {
|
||||
segments := strings.Split(strings.TrimPrefix(filePath, "/"), "/")
|
||||
last := len(segments) - 1
|
||||
for i := 0; i < last; i++ {
|
||||
segments[i] = datasource.SanitizeFileName(segments[i])
|
||||
}
|
||||
ext := path.Ext(segments[last])
|
||||
segments[last] = datasource.SanitizeFileName(strings.TrimSuffix(segments[last], ext)) + ext
|
||||
return datasource.SanitizeFileName(repoName) + "/" + strings.Join(segments, "/")
|
||||
}
|
||||
|
||||
func externalID(repoID, filePath string) string {
|
||||
return "seafile:" + repoID + ":" + filePath
|
||||
}
|
||||
|
||||
// fingerprint identifies a file version; three equal parts mean unchanged.
|
||||
func fingerprint(oid string, mtime, size int64) string {
|
||||
return fmt.Sprintf("o:%s|m:%d|s:%d", oid, mtime, size)
|
||||
}
|
||||
|
||||
// validEntryName accepts a single non-empty path segment.
|
||||
func validEntryName(name string) bool {
|
||||
return name != "" && name != "." && name != ".." &&
|
||||
!strings.ContainsAny(name, "/\\") && !strings.ContainsFunc(name, unicode.IsControl)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestKnowledgeFileName(t *testing.T) {
|
||||
if got := knowledgeFileName("01-机场线", "/产品/产品A/需求: v2.docx"); got != "01-机场线/产品/产品A/需求_ v2.docx" {
|
||||
t.Fatalf("filename = %q", got)
|
||||
}
|
||||
p := "/" + strings.Repeat("层级/", 20) + "说明.pdf"
|
||||
if got := knowledgeFileName("资料库", p); got != "资料库"+p {
|
||||
t.Fatalf("deep filename was truncated: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExternalIDAndFingerprint(t *testing.T) {
|
||||
if got := externalID(testRepoID, "/产品/a:b.pdf"); got != "seafile:"+testRepoID+":/产品/a:b.pdf" {
|
||||
t.Fatalf("externalID = %q", got)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
oid string
|
||||
mtime, size int64
|
||||
want string
|
||||
}{
|
||||
{"abc123", 123, 456, "o:abc123|m:123|s:456"},
|
||||
{"", 0, 0, "o:|m:0|s:0"},
|
||||
} {
|
||||
if got := fingerprint(tc.oid, tc.mtime, tc.size); got != tc.want {
|
||||
t.Fatalf("fingerprint = %q, want %q", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidEntryName(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
want bool
|
||||
}{
|
||||
{"说明.pdf", true},
|
||||
{"需求: v2.docx", true},
|
||||
{"a%2Fb.pdf", true},
|
||||
{".hidden.pdf", true},
|
||||
{" spaced .pdf", true},
|
||||
{"", false},
|
||||
{".", false},
|
||||
{"..", false},
|
||||
{"../outside.pdf", false},
|
||||
{"/absolute.pdf", false},
|
||||
{"a/b.pdf", false},
|
||||
{"a\\b.pdf", false},
|
||||
{"a\x00b.pdf", false},
|
||||
{"a\nb.pdf", false},
|
||||
{"a\rb.pdf", false},
|
||||
{"a\tb.pdf", false},
|
||||
{"a\x7fb.pdf", false},
|
||||
} {
|
||||
if got := validEntryName(tc.name); got != tc.want {
|
||||
t.Errorf("validEntryName(%q) = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
"academy/internal/utils"
|
||||
)
|
||||
|
||||
// checkpointEvery bounds how many cursor mutations may be lost on a crash.
|
||||
const checkpointEvery = 50
|
||||
|
||||
// syncRun holds the state of one FetchStream / FetchFullStream execution.
|
||||
type syncRun struct {
|
||||
ctx context.Context
|
||||
client *client
|
||||
h datasource.StreamHandler
|
||||
cur cursor
|
||||
repoID string
|
||||
// repoName is frozen in the cursor on the first run so folder names stay
|
||||
// stable when the library is renamed.
|
||||
repoName string
|
||||
limit int64
|
||||
// seen records every supported file listed this run; anything known to
|
||||
// the cursor but not seen is a deletion candidate.
|
||||
seen map[string]bool
|
||||
unsaved int
|
||||
}
|
||||
|
||||
func (c *Connector) runSync(
|
||||
ctx context.Context, ds *types.DataSourceConfig, old *types.SyncCursor,
|
||||
h datasource.StreamHandler, forceFull bool,
|
||||
) (*types.SyncCursor, error) {
|
||||
cfg, err := parseConfig(ds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repoID, roots, err := collapseRoots(ds.ResourceIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cur, changed, err := prepareCursor(old, repoID, forceFull)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := &syncRun{ctx: ctx, client: newClient(cfg), h: h, cur: cur, repoID: repoID, seen: make(map[string]bool)}
|
||||
if changed {
|
||||
r.unsaved++
|
||||
}
|
||||
|
||||
// Nothing has been fetched yet, so failures here return without saving:
|
||||
// a cursor must not bind to a library that was never confirmed to exist.
|
||||
repos, err := r.client.listRepos(ctx)
|
||||
if err != nil {
|
||||
return nil, r.canceledOr(err)
|
||||
}
|
||||
repo, err := selectedRepo(repos, repoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.cur.RepoName == "" {
|
||||
r.cur.RepoName = repo.Name
|
||||
r.unsaved++
|
||||
}
|
||||
r.repoName = r.cur.RepoName
|
||||
r.limit = utils.GetMaxFileSize()
|
||||
|
||||
for _, root := range roots {
|
||||
if err := r.scanRoot(root); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := r.reconcile(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "[Seafile] sync finished: %d files in scope, %d tracked", len(r.seen), len(r.cur.Files))
|
||||
return r.cur.toSyncCursor(), nil
|
||||
}
|
||||
|
||||
// canceledOr reports cancellation as ErrSyncCanceled and passes other errors
|
||||
// through unchanged. The second branch covers a handler that failed on a
|
||||
// context of its own; applying it twice is harmless.
|
||||
func (r *syncRun) canceledOr(err error) error {
|
||||
if cause := r.ctx.Err(); cause != nil {
|
||||
return errors.Join(datasource.ErrSyncCanceled, cause)
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return errors.Join(datasource.ErrSyncCanceled, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *syncRun) canceled() error {
|
||||
if cause := r.ctx.Err(); cause != nil {
|
||||
return errors.Join(datasource.ErrSyncCanceled, cause)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// abort saves unsaved progress while the context is still valid, then
|
||||
// returns the source error. Handler errors never come through here.
|
||||
func (r *syncRun) abort(err error) error {
|
||||
if canceled := r.canceledOr(err); canceled != err {
|
||||
return canceled
|
||||
}
|
||||
if r.unsaved > 0 {
|
||||
if checkpointErr := r.checkpoint(); checkpointErr != nil {
|
||||
return errors.Join(err, checkpointErr)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *syncRun) checkpoint() error {
|
||||
if err := r.canceled(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.h.Checkpoint(r.ctx, r.cur.toSyncCursor()); err != nil {
|
||||
return err
|
||||
}
|
||||
r.unsaved = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *syncRun) mutated() error {
|
||||
r.unsaved++
|
||||
if r.unsaved >= checkpointEvery {
|
||||
return r.checkpoint()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *syncRun) emit(item types.FetchedItem) error {
|
||||
if err := r.canceled(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.h.Emit(r.ctx, item); err != nil {
|
||||
return r.canceledOr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *syncRun) listDir(p string) ([]dirent, error) {
|
||||
if err := r.canceled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := r.client.listDir(r.ctx, r.repoID, p)
|
||||
if err != nil {
|
||||
return nil, r.canceledOr(err)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// scanRoot classifies a selected root by its current type: a directory is
|
||||
// traversed, a file listed by its parent is synced alone, anything else is
|
||||
// gone.
|
||||
func (r *syncRun) scanRoot(root string) error {
|
||||
entries, err := r.listDir(root)
|
||||
if err == nil {
|
||||
return r.walkDir(root, entries)
|
||||
}
|
||||
if statusOf(err) != http.StatusNotFound || root == "/" {
|
||||
return r.abort(mapDirError(err, root))
|
||||
}
|
||||
parent := parentPath(root)
|
||||
entries, err = r.listDir(parent)
|
||||
if err != nil {
|
||||
return r.abort(mapDirError(err, parent))
|
||||
}
|
||||
if err := validateListing(parent, entries); err != nil {
|
||||
return r.abort(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name != path.Base(root) || e.Type != "file" {
|
||||
continue
|
||||
}
|
||||
if !utils.IsSupportedImportExtension(path.Ext(e.Name)) {
|
||||
return nil
|
||||
}
|
||||
return r.syncFile(root, e)
|
||||
}
|
||||
return r.abort(fmt.Errorf("%w: Seafile path %s", datasource.ErrResourceNotFound, root))
|
||||
}
|
||||
|
||||
// validateListing rejects entries the traversal cannot trust; a bad listing
|
||||
// is a directory failure so the run emits no deletions.
|
||||
func validateListing(dir string, entries []dirent) error {
|
||||
names := make(map[string]bool, len(entries))
|
||||
for _, e := range entries {
|
||||
bad := !validEntryName(e.Name) || names[e.Name] || e.Mtime < 0 ||
|
||||
(e.Type != "file" && e.Type != "dir") ||
|
||||
(e.Type == "file" && (e.Size == nil || *e.Size < 0))
|
||||
if bad {
|
||||
return fmt.Errorf("%w: %w: directory listing %s", datasource.ErrFetchFailed, errInvalidResponse, dir)
|
||||
}
|
||||
names[e.Name] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// walkDir traverses root depth-first with an explicit stack of paths. Each
|
||||
// level is listed once; files are synced before descending into
|
||||
// sub-directories, both in name order.
|
||||
func (r *syncRun) walkDir(root string, rootEntries []dirent) error {
|
||||
stack := []string{root}
|
||||
for len(stack) > 0 {
|
||||
dir := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
|
||||
entries := rootEntries
|
||||
if dir != root {
|
||||
var err error
|
||||
if entries, err = r.listDir(dir); err != nil {
|
||||
// A sub-directory that vanished mid-scan is a listing failure,
|
||||
// not a missing selection: the run stops without deletions and
|
||||
// the next run sees the new shape.
|
||||
if statusOf(err) == http.StatusNotFound {
|
||||
return r.abort(fmt.Errorf("%w: Seafile directory %s disappeared during the scan",
|
||||
datasource.ErrFetchFailed, dir))
|
||||
}
|
||||
return r.abort(mapDirError(err, dir))
|
||||
}
|
||||
}
|
||||
if err := validateListing(dir, entries); err != nil {
|
||||
return r.abort(err)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
for _, e := range entries {
|
||||
if e.Type == "file" && utils.IsSupportedImportExtension(path.Ext(e.Name)) {
|
||||
if err := r.syncFile(path.Join(dir, e.Name), e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := len(entries) - 1; i >= 0; i-- {
|
||||
if entries[i].Type == "dir" {
|
||||
stack = append(stack, path.Join(dir, entries[i].Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncFile downloads and emits one file unless its fingerprint is unchanged.
|
||||
// Every caller validated the listing, so e.Size is non-nil. The fingerprint
|
||||
// is stored only after Emit succeeds.
|
||||
func (r *syncRun) syncFile(p string, e dirent) error {
|
||||
if err := r.canceled(); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.seen[p] {
|
||||
return nil
|
||||
}
|
||||
r.seen[p] = true
|
||||
size := *e.Size
|
||||
fp := fingerprint(e.ID, e.Mtime, size)
|
||||
if previous := r.cur.Files[p]; previous != "" && previous == fp {
|
||||
return nil
|
||||
}
|
||||
if size > r.limit {
|
||||
return r.failFile(p, e, reasonFileTooLarge, 0)
|
||||
}
|
||||
|
||||
link, oid, err := r.client.downloadLink(r.ctx, r.repoID, p)
|
||||
if err != nil {
|
||||
return r.fetchError(p, e, err, linkReason(err))
|
||||
}
|
||||
if oid != "" && e.ID != "" && oid != e.ID {
|
||||
return r.failFile(p, e, reasonSourceChanged, 0)
|
||||
}
|
||||
body, err := r.client.download(r.ctx, link, size, r.limit)
|
||||
if err != nil {
|
||||
return r.fetchError(p, e, err, downloadReason(err))
|
||||
}
|
||||
if err := r.emit(r.buildItem(p, e, body)); err != nil {
|
||||
return err
|
||||
}
|
||||
r.cur.Files[p] = fp
|
||||
return r.mutated()
|
||||
}
|
||||
|
||||
func linkReason(err error) string {
|
||||
switch {
|
||||
case statusOf(err) == http.StatusForbidden:
|
||||
return reasonPermissionDenied
|
||||
case statusOf(err) == http.StatusNotFound:
|
||||
return reasonNotFound
|
||||
case errors.Is(err, errInvalidResponse):
|
||||
return reasonInvalidResponse
|
||||
default:
|
||||
return reasonFetchFailed
|
||||
}
|
||||
}
|
||||
|
||||
func downloadReason(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, errSSRFBlocked):
|
||||
return reasonSSRFBlocked
|
||||
case errors.Is(err, errTooLarge):
|
||||
return reasonFileTooLarge
|
||||
case errors.Is(err, errEmptyFile):
|
||||
return reasonEmptyFile
|
||||
case errors.Is(err, errSourceChanged):
|
||||
return reasonSourceChanged
|
||||
default:
|
||||
return reasonFetchFailed
|
||||
}
|
||||
}
|
||||
|
||||
// fetchError isolates a per-file failure as an error item, except for
|
||||
// cancellation and an over-long Retry-After, which end the run. Client
|
||||
// errors carry only the operation and status, so logging them is safe.
|
||||
func (r *syncRun) fetchError(p string, e dirent, err error, code string) error {
|
||||
if canceled := r.canceledOr(err); canceled != err {
|
||||
return canceled
|
||||
}
|
||||
if errors.Is(err, errRetryAfterTooLong) {
|
||||
return r.abort(err)
|
||||
}
|
||||
logger.Warnf(r.ctx, "[Seafile] fetch failed: repo=%s path=%s code=%s: %v", r.repoID, p, code, err)
|
||||
return r.failFile(p, e, code, statusOf(err))
|
||||
}
|
||||
|
||||
func (r *syncRun) failFile(p string, e dirent, code string, status int) error {
|
||||
if err := r.emit(r.errorItem(p, e, code, status)); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.markFailed(p)
|
||||
}
|
||||
|
||||
// markFailed keeps a known path alive with an empty fingerprint so it is
|
||||
// retried next run and still reconciled if it disappears. Paths the cursor
|
||||
// never knew stay absent.
|
||||
func (r *syncRun) markFailed(p string) error {
|
||||
value, known := r.cur.Files[p]
|
||||
_, inBaseline := r.cur.FullSyncBaseline[p]
|
||||
if (known && value != "") || (!known && inBaseline) {
|
||||
r.cur.Files[p] = ""
|
||||
return r.mutated()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconcile emits deletions for every known path not seen this run. It only
|
||||
// runs after every root enumerated successfully.
|
||||
func (r *syncRun) reconcile() error {
|
||||
if err := r.canceled(); err != nil {
|
||||
return err
|
||||
}
|
||||
missing := make(map[string]bool)
|
||||
for p := range r.cur.Files {
|
||||
if !r.seen[p] {
|
||||
missing[p] = true
|
||||
}
|
||||
}
|
||||
if r.cur.FullSync {
|
||||
for p := range r.cur.FullSyncBaseline {
|
||||
if !r.seen[p] {
|
||||
missing[p] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
paths := make([]string, 0, len(missing))
|
||||
for p := range missing {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
if len(paths) > 0 && r.unsaved > 0 {
|
||||
if err := r.checkpoint(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, p := range paths {
|
||||
if err := r.emit(r.deletedItem(p)); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(r.cur.Files, p)
|
||||
delete(r.cur.FullSyncBaseline, p)
|
||||
if err := r.mutated(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if r.cur.FullSync {
|
||||
r.cur.FullSync = false
|
||||
r.cur.FullSyncBaseline = nil
|
||||
r.unsaved++
|
||||
}
|
||||
if r.unsaved > 0 {
|
||||
return r.checkpoint()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *syncRun) identity(p string, e dirent) types.FetchedItem {
|
||||
return types.FetchedItem{
|
||||
ExternalID: externalID(r.repoID, p),
|
||||
Title: r.repoName + "/" + strings.TrimPrefix(p, "/"),
|
||||
FileName: knowledgeFileName(r.repoName, p),
|
||||
UpdatedAt: time.Unix(e.Mtime, 0).UTC(),
|
||||
SourceResourceID: encodeResourceID(r.repoID, "/"),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *syncRun) buildItem(p string, e dirent, body []byte) types.FetchedItem {
|
||||
item := r.identity(p, e)
|
||||
item.Content = body
|
||||
item.ContentType = http.DetectContentType(body)
|
||||
item.Metadata = map[string]string{
|
||||
"channel": types.ChannelSeafile,
|
||||
"source_type": "seafile",
|
||||
"seafile_repo_id": r.repoID,
|
||||
"seafile_repo_name": r.repoName,
|
||||
"seafile_path": p,
|
||||
"seafile_object_id": e.ID,
|
||||
"seafile_mtime": strconv.FormatInt(e.Mtime, 10),
|
||||
"seafile_size": strconv.FormatInt(*e.Size, 10),
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// errorItem follows the service contract for failed fetches: no content, a
|
||||
// stable reason code and English fallback text. The text is fixed so
|
||||
// credentials and signed links never reach sync logs.
|
||||
func (r *syncRun) errorItem(p string, e dirent, code string, status int) types.FetchedItem {
|
||||
item := r.identity(p, e)
|
||||
item.Metadata = map[string]string{
|
||||
"channel": types.ChannelSeafile,
|
||||
"source_type": "seafile",
|
||||
"seafile_path": p,
|
||||
"error": errorReason(code),
|
||||
"error_reason_code": code,
|
||||
"error_reason": errorReason(code),
|
||||
}
|
||||
if status > 0 {
|
||||
item.Metadata["error_reason_code_value"] = strconv.Itoa(status)
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func (r *syncRun) deletedItem(p string) types.FetchedItem {
|
||||
return types.FetchedItem{
|
||||
ExternalID: externalID(r.repoID, p),
|
||||
Title: r.repoName + "/" + strings.TrimPrefix(p, "/"),
|
||||
IsDeleted: true,
|
||||
SourceResourceID: encodeResourceID(r.repoID, "/"),
|
||||
Metadata: map[string]string{"channel": types.ChannelSeafile, "seafile_path": p},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestSyncScale(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/")
|
||||
dirTarget := 300
|
||||
if os.Getenv("SEAFILE_SCALE_TEST") == "1" {
|
||||
dirTarget = 3000
|
||||
}
|
||||
// Each group has one level-one dir, one level-two dir and eight
|
||||
// level-three dirs. All 300 (or 3000) non-root dirs have ten files.
|
||||
groups := dirTarget / 10
|
||||
for g := 0; g < groups; g++ {
|
||||
top := fmt.Sprintf("/g%03d", g)
|
||||
mid := top + "/middle"
|
||||
dirs := []string{top, mid}
|
||||
for leaf := 0; leaf < 8; leaf++ {
|
||||
dirs = append(dirs, fmt.Sprintf("%s/leaf%02d", mid, leaf))
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
addNumberedFiles(f, dir, 10)
|
||||
}
|
||||
}
|
||||
directoryCount := 0
|
||||
f.mu.Lock()
|
||||
for _, node := range f.tree[testRepoID] {
|
||||
if node.Type == "dir" {
|
||||
directoryCount++
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if directoryCount != dirTarget+1 {
|
||||
t.Fatalf("fixture has %d directories, want %d", directoryCount, dirTarget+1)
|
||||
}
|
||||
fileCount := dirTarget * 10
|
||||
full := compactRecorder()
|
||||
cur, err := run(t, c, cfg, nil, full, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(full.contentItems()) != fileCount || len(full.items) != fileCount || len(filesOf(cur)) != fileCount {
|
||||
t.Fatalf("full items=%d, total=%d, cursor=%d", len(full.contentItems()), len(full.items), len(filesOf(cur)))
|
||||
}
|
||||
h := compactRecorder()
|
||||
retain := h.onCheckpoint
|
||||
h.onCheckpoint = func(cp map[string]any) {
|
||||
retain(cp)
|
||||
if len(filesOf(&types.SyncCursor{ConnectorCursor: cp})) >= fileCount/2 {
|
||||
h.cancel()
|
||||
}
|
||||
}
|
||||
_, err = run(t, c, cfg, cur, h, true)
|
||||
if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 {
|
||||
t.Fatalf("midpoint cancel = %v, late checkpoints=%d", err, h.checkpointsAfterStop)
|
||||
}
|
||||
saved := checkpointCursor(t, h)
|
||||
savedFiles := filesOf(saved)
|
||||
// Checkpoints land every 50 mutations, and the full-sync switch is one of
|
||||
// them, so the saved batch ends within one batch of the midpoint.
|
||||
if len(savedFiles) < fileCount/2 || len(savedFiles) >= fileCount/2+checkpointEvery ||
|
||||
!mustCursor(t, saved).FullSync {
|
||||
t.Fatalf("midpoint saved %d/%d files", len(savedFiles), fileCount)
|
||||
}
|
||||
f.resetCounts()
|
||||
resumed := compactRecorder()
|
||||
cur, err = run(t, c, cfg, saved, resumed, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(resumed.contentItems()) != fileCount-len(savedFiles) || len(filesOf(cur)) != fileCount ||
|
||||
len(resumed.deletedItems()) != 0 || len(resumed.errorItems()) != 0 {
|
||||
t.Fatalf("resume content=%d, cursor=%d, deleted=%d, errors=%d",
|
||||
len(resumed.contentItems()), len(filesOf(cur)), len(resumed.deletedItems()), len(resumed.errorItems()))
|
||||
}
|
||||
for p := range savedFiles {
|
||||
if f.count("download:"+p) != 0 {
|
||||
t.Fatalf("resume downloaded saved file %s", p)
|
||||
}
|
||||
}
|
||||
f.resetCounts()
|
||||
cur, unchanged := mustRun(t, c, cfg, cur, false)
|
||||
if len(unchanged.items) != 0 || f.countPrefix("download:") != 0 ||
|
||||
f.countPrefix("dir:") != directoryCount || f.count("repos") != 1 || len(unchanged.checkpoints) > 1 {
|
||||
t.Fatalf("unchanged: items=%d, downloads=%d, dirs=%d/%d, repos=%d, checkpoints=%d",
|
||||
len(unchanged.items), f.countPrefix("download:"), f.countPrefix("dir:"), directoryCount,
|
||||
f.count("repos"), len(unchanged.checkpoints))
|
||||
}
|
||||
if os.Getenv("SEAFILE_SCALE_TEST") == "1" {
|
||||
data, err := json.Marshal(cur.ConnectorCursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("files=%d cursor_bytes=%d checkpoints: full=%d interrupted=%d resumed=%d unchanged=%d",
|
||||
fileCount, len(data), full.checkpointCalls, h.checkpointCalls, resumed.checkpointCalls,
|
||||
unchanged.checkpointCalls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,989 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
var errRecordedEmit = errors.New("recorder emit failed")
|
||||
|
||||
type recorder struct {
|
||||
items []types.FetchedItem
|
||||
checkpoints []map[string]any
|
||||
failEmitAfter int
|
||||
cancelAfter int
|
||||
cancel context.CancelFunc
|
||||
checkpointErr error
|
||||
|
||||
onEmit func(types.FetchedItem)
|
||||
onCheckpoint func(map[string]any)
|
||||
checkpointCalls int
|
||||
checkpointsAfterStop int
|
||||
stopped bool
|
||||
}
|
||||
|
||||
var _ datasource.StreamHandler = (*recorder)(nil)
|
||||
|
||||
func (h *recorder) Emit(_ context.Context, item types.FetchedItem) error {
|
||||
h.items = append(h.items, item)
|
||||
if h.onEmit != nil {
|
||||
h.onEmit(item)
|
||||
}
|
||||
if h.failEmitAfter > 0 && len(h.items) >= h.failEmitAfter {
|
||||
h.stopped = true
|
||||
return errRecordedEmit
|
||||
}
|
||||
if h.cancelAfter > 0 && len(h.items) >= h.cancelAfter {
|
||||
h.stopped = true
|
||||
h.cancel()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *recorder) Checkpoint(ctx context.Context, cur *types.SyncCursor) error {
|
||||
h.checkpointCalls++
|
||||
if h.stopped || ctx.Err() != nil {
|
||||
h.checkpointsAfterStop++
|
||||
}
|
||||
snapshot := cloneConnectorCursor(cur.ConnectorCursor)
|
||||
h.checkpoints = append(h.checkpoints, snapshot)
|
||||
if h.checkpointErr != nil {
|
||||
h.stopped = true
|
||||
return h.checkpointErr
|
||||
}
|
||||
if h.onCheckpoint != nil {
|
||||
h.onCheckpoint(snapshot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *recorder) contentItems() []types.FetchedItem {
|
||||
var out []types.FetchedItem
|
||||
for _, item := range h.items {
|
||||
if !item.IsDeleted && item.Content != nil && item.Metadata["error"] == "" {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *recorder) errorItems() []types.FetchedItem {
|
||||
var out []types.FetchedItem
|
||||
for _, item := range h.items {
|
||||
if item.Metadata["error"] != "" {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *recorder) deletedItems() []types.FetchedItem {
|
||||
var out []types.FetchedItem
|
||||
for _, item := range h.items {
|
||||
if item.IsDeleted {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *recorder) paths() []string {
|
||||
out := make([]string, 0, len(h.items))
|
||||
for _, item := range h.items {
|
||||
out = append(out, item.Metadata["seafile_path"])
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func run(
|
||||
t *testing.T, c *Connector, cfg *types.DataSourceConfig, old *types.SyncCursor, h *recorder, full bool,
|
||||
) (*types.SyncCursor, error) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
h.cancel = cancel
|
||||
if full {
|
||||
return c.FetchFullStream(ctx, cfg, old, h)
|
||||
}
|
||||
return c.FetchStream(ctx, cfg, old, h)
|
||||
}
|
||||
|
||||
func cloneConnectorCursor(m map[string]any) map[string]any {
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func filesOf(cur *types.SyncCursor) map[string]string {
|
||||
if cur == nil {
|
||||
return nil
|
||||
}
|
||||
b, err := json.Marshal(cur.ConnectorCursor["files"])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var files map[string]string
|
||||
if err := json.Unmarshal(b, &files); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func syncConfig(f *fakeSeafile, roots ...string) *types.DataSourceConfig {
|
||||
cfg := &types.DataSourceConfig{Credentials: map[string]any{
|
||||
"base_url": f.baseURL(), "api_token": testToken,
|
||||
}}
|
||||
for _, p := range roots {
|
||||
cfg.ResourceIDs = append(cfg.ResourceIDs, testRepoID+":"+p)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func syncFixture(t *testing.T, roots ...string) (*fakeSeafile, *Connector, *types.DataSourceConfig) {
|
||||
t.Helper()
|
||||
noWait(t)
|
||||
f := newFakeSeafile(t)
|
||||
f.addRepo(testRepoID, "Library", "repo", false)
|
||||
return f, NewConnector(), syncConfig(f, roots...)
|
||||
}
|
||||
|
||||
func seededCursor(t *testing.T, name string, files map[string]string) *types.SyncCursor {
|
||||
t.Helper()
|
||||
c, _, err := prepareCursor(nil, testRepoID, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.RepoName = name
|
||||
c.Files = files
|
||||
return c.toSyncCursor()
|
||||
}
|
||||
|
||||
func cursorJSON(t *testing.T, c *types.SyncCursor) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func mustCursor(t *testing.T, cur *types.SyncCursor) cursor {
|
||||
t.Helper()
|
||||
if cur == nil {
|
||||
t.Fatal("missing cursor")
|
||||
}
|
||||
c, err := decodeCursor(cur)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func checkpointCursor(t *testing.T, h *recorder) *types.SyncCursor {
|
||||
t.Helper()
|
||||
if len(h.checkpoints) == 0 {
|
||||
t.Fatal("missing checkpoint")
|
||||
}
|
||||
return &types.SyncCursor{ConnectorCursor: cloneConnectorCursor(h.checkpoints[len(h.checkpoints)-1])}
|
||||
}
|
||||
|
||||
func mustRun(
|
||||
t *testing.T, c *Connector, cfg *types.DataSourceConfig, old *types.SyncCursor, full bool,
|
||||
) (*types.SyncCursor, *recorder) {
|
||||
t.Helper()
|
||||
h := &recorder{}
|
||||
cur, err := run(t, c, cfg, old, h, full)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cur == nil {
|
||||
t.Fatal("successful run returned no cursor")
|
||||
}
|
||||
return cur, h
|
||||
}
|
||||
|
||||
func assertPaths(t *testing.T, items []types.FetchedItem, want ...string) {
|
||||
t.Helper()
|
||||
h := &recorder{items: items}
|
||||
got := h.paths()
|
||||
want = slices.Clone(want)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("paths = %v, want %v", got, want)
|
||||
}
|
||||
for _, item := range items {
|
||||
p := item.Metadata["seafile_path"]
|
||||
if item.ExternalID != "seafile:"+testRepoID+":"+p || item.SourceResourceID != testRepoID+":/" {
|
||||
t.Fatalf("item identity = %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addNumberedFiles(f *fakeSeafile, dir string, n int) {
|
||||
for i := 0; i < n; i++ {
|
||||
f.addFile(testRepoID, fmt.Sprintf("%s/%03d.pdf", dir, i), []byte("x"), 1)
|
||||
}
|
||||
}
|
||||
|
||||
// assertFullSyncCleared checks that a completed full run dropped both the
|
||||
// flag and the baseline from the persisted cursor.
|
||||
func assertFullSyncCleared(t *testing.T, cur *types.SyncCursor) {
|
||||
t.Helper()
|
||||
if cur == nil {
|
||||
t.Fatal("missing cursor")
|
||||
}
|
||||
_, flag := cur.ConnectorCursor["full_sync"]
|
||||
_, baseline := cur.ConnectorCursor["full_sync_baseline"]
|
||||
if flag || baseline {
|
||||
t.Fatalf("completed full sync kept its state: %v", cur.ConnectorCursor)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPending(t *testing.T, cur *types.SyncCursor, p string) {
|
||||
t.Helper()
|
||||
if fp, ok := filesOf(cur)[p]; !ok || fp != "" {
|
||||
t.Fatalf("%s should be retained with empty fingerprint: %v", p, filesOf(cur))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncRecursiveScopeAndMetadata(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs", "/docs/产品")
|
||||
f.addFile(testRepoID, "/docs/产品/需求: v2.docx", []byte("body"), 7)
|
||||
f.addFile(testRepoID, "/docs/map.xmind", []byte("map"), 1)
|
||||
f.addFile(testRepoID, "/docs/skip.zip", []byte("zip"), 1)
|
||||
f.addFile(testRepoID, "/docs/skip.mdx", []byte("mdx"), 1)
|
||||
f.addFile(testRepoID, "/docs-sibling/secret.pdf", []byte("secret"), 1)
|
||||
cur, h := mustRun(t, c, cfg, nil, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/产品/需求: v2.docx", "/docs/map.xmind")
|
||||
if len(h.errorItems()) != 0 || len(filesOf(cur)) != 2 || f.count("dir:/docs/产品") != 1 ||
|
||||
f.count("dir:/docs-sibling") != 0 || f.count("file:/docs/skip.zip") != 0 ||
|
||||
f.count("file:/docs/skip.mdx") != 0 {
|
||||
t.Fatalf("scope traversal: counts=%v, files=%v", f.counts(), filesOf(cur))
|
||||
}
|
||||
for _, item := range h.contentItems() {
|
||||
p := item.Metadata["seafile_path"]
|
||||
if item.FileName != knowledgeFileName("Library", p) || item.Title != "Library"+p {
|
||||
t.Fatalf("display names = %+v", item)
|
||||
}
|
||||
if item.Metadata["channel"] != "seafile" || item.Metadata["source_type"] == "" ||
|
||||
item.Metadata["seafile_repo_id"] != testRepoID || item.Metadata["seafile_repo_name"] != "Library" {
|
||||
t.Fatalf("metadata = %v", item.Metadata)
|
||||
}
|
||||
if strings.HasSuffix(p, ".docx") {
|
||||
oid := fmt.Sprintf("%x", sha1.Sum([]byte("body")))
|
||||
if string(item.Content) != "body" || item.Metadata["seafile_object_id"] != oid ||
|
||||
item.Metadata["seafile_mtime"] != "7" || item.Metadata["seafile_size"] != "4" {
|
||||
t.Fatalf("content metadata = %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
f.addFile(testRepoID, "/docs/new/deep/new.pdf", []byte("new"), 2)
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/new/deep/new.pdf")
|
||||
if len(filesOf(cur)) != 3 {
|
||||
t.Fatalf("descendant missing from cursor: %v", filesOf(cur))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSingleFileAndDisappearance(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs/a.pdf")
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
f.addFile(testRepoID, "/docs/b.pdf", []byte("b"), 1)
|
||||
f.addFile(testRepoID, "/docs/sub/c.pdf", []byte("c"), 1)
|
||||
old, h := mustRun(t, c, cfg, nil, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/a.pdf")
|
||||
// The root is probed once as a directory (404), then its parent is listed once.
|
||||
if f.count("dir:/docs") != 1 || f.count("dir:/docs/a.pdf") != 1 || f.countPrefix("dir:") != 2 ||
|
||||
f.countPrefix("download:") != 1 {
|
||||
t.Fatalf("single-file selection requests = %v", f.counts())
|
||||
}
|
||||
before := cursorJSON(t, old)
|
||||
f.removePath(testRepoID, "/docs/a.pdf")
|
||||
h = &recorder{}
|
||||
cur, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, datasource.ErrResourceNotFound) || len(h.deletedItems()) != 0 {
|
||||
t.Fatalf("selected file disappeared: %v, items=%+v", err, h.items)
|
||||
}
|
||||
if cursorJSON(t, old) != before {
|
||||
t.Fatal("failed run mutated the old cursor")
|
||||
}
|
||||
if cur != nil {
|
||||
if _, ok := filesOf(cur)["/docs/a.pdf"]; !ok {
|
||||
t.Fatal("returned cursor forgot the selected file")
|
||||
}
|
||||
}
|
||||
for _, cp := range h.checkpoints {
|
||||
if _, ok := filesOf(&types.SyncCursor{ConnectorCursor: cp})["/docs/a.pdf"]; !ok {
|
||||
t.Fatal("checkpoint forgot the selected file")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncUnsupportedFileRootIsSkipped(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs/archive.zip", "/docs/sub")
|
||||
f.addFile(testRepoID, "/docs/archive.zip", []byte("zip"), 1)
|
||||
f.addFile(testRepoID, "/docs/sub/a.pdf", []byte("a"), 1)
|
||||
cur, h := mustRun(t, c, cfg, nil, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/sub/a.pdf")
|
||||
if len(h.errorItems()) != 0 || f.count("file:/docs/archive.zip") != 0 || len(filesOf(cur)) != 1 {
|
||||
t.Fatalf("unsupported file root: items=%+v, counts=%v, files=%v", h.items, f.counts(), filesOf(cur))
|
||||
}
|
||||
// A selected directory replaced by an extensionless file loses its
|
||||
// children through reconciliation instead of importing the replacement.
|
||||
f.removePath(testRepoID, "/docs/sub")
|
||||
f.addFile(testRepoID, "/docs/sub", []byte("blob"), 2)
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems())
|
||||
assertPaths(t, h.deletedItems(), "/docs/sub/a.pdf")
|
||||
if f.count("file:/docs/sub") != 0 || len(filesOf(cur)) != 0 {
|
||||
t.Fatalf("directory replaced by unsupported file: counts=%v, files=%v", f.counts(), filesOf(cur))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncFileReplacedByDirectory(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/docs/a.pdf")
|
||||
f.addFile(testRepoID, "/docs/a.pdf/child.pdf", []byte("child"), 2)
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/a.pdf/child.pdf")
|
||||
assertPaths(t, h.deletedItems(), "/docs/a.pdf")
|
||||
if len(filesOf(cur)) != 1 || f.count("dir:/docs/a.pdf") != 1 {
|
||||
t.Fatalf("directory without size not traversed: %v, %v", filesOf(cur), f.counts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncNoChangeAndMtimeOnly(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/")
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
f.addFile(testRepoID, "/docs/sub/b.pdf", []byte("b"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.resetCounts()
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
if len(h.items) != 0 || f.countPrefix("download:") != 0 || f.countPrefix("dir:") != 3 ||
|
||||
f.count("repos") != 1 || len(h.checkpoints) > 1 {
|
||||
t.Fatalf("unchanged run: counts=%v, items=%d, checkpoints=%d", f.counts(), len(h.items), len(h.checkpoints))
|
||||
}
|
||||
f.touch(testRepoID, "/docs/a.pdf")
|
||||
f.resetCounts()
|
||||
next, h := mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/a.pdf")
|
||||
if f.count("download:/docs/a.pdf") != 1 || filesOf(next)["/docs/a.pdf"] == filesOf(cur)["/docs/a.pdf"] {
|
||||
t.Fatal("mtime-only change did not re-download and update the fingerprint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncFileFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, code string
|
||||
status int
|
||||
inject func(*fakeSeafile, string)
|
||||
}{
|
||||
{"forbidden", "seafile_permission_denied", 403, func(f *fakeSeafile, p string) { f.fail("file:"+p, 403, -1) }},
|
||||
{"missing", "seafile_not_found", 404, func(f *fakeSeafile, p string) { f.fail("file:"+p, 404, -1) }},
|
||||
{"server error", "seafile_fetch_failed", 500, func(f *fakeSeafile, p string) { f.fail("file:"+p, 500, -1) }},
|
||||
{"empty", "seafile_empty_file", 0, func(f *fakeSeafile, p string) { f.setBody(testRepoID, p, nil) }},
|
||||
{"listed oversize", "seafile_file_too_large", 0, func(f *fakeSeafile, p string) {
|
||||
f.setBody(testRepoID, p, []byte(strings.Repeat("x", (1<<20)+1)))
|
||||
}},
|
||||
{"chunked oversize", "seafile_file_too_large", 0, func(f *fakeSeafile, p string) {
|
||||
f.chunkedOversize[p] = (1 << 20) + 1
|
||||
}},
|
||||
{"changed object", "seafile_source_changed", 0, func(f *fakeSeafile, p string) {
|
||||
f.linkOID[p] = "different-object"
|
||||
}},
|
||||
{"malformed link", "seafile_invalid_response", 0, func(f *fakeSeafile, p string) {
|
||||
f.rawBody["file:"+p] = "{"
|
||||
}},
|
||||
{"SSRF", "seafile_ssrf_blocked", 0, func(f *fakeSeafile, p string) {
|
||||
f.linkURL[p] = "http://169.254.169.254/blocked"
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
for _, known := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/known=%v", tc.name, known), func(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
// GetMaxFileSize reads this environment variable without caching.
|
||||
t.Setenv("MAX_FILE_SIZE_MB", "1")
|
||||
p := "/docs/a.pdf"
|
||||
f.addFile(testRepoID, p, []byte("body"), 1)
|
||||
var old *types.SyncCursor
|
||||
if known {
|
||||
old, _ = mustRun(t, c, cfg, nil, false)
|
||||
f.touch(testRepoID, p)
|
||||
}
|
||||
tc.inject(f, p)
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
assertPaths(t, h.errorItems(), p)
|
||||
if len(h.items) != 1 {
|
||||
t.Fatalf("failure emitted extra items: %+v", h.items)
|
||||
}
|
||||
item := h.errorItems()[0]
|
||||
if item.Content != nil || item.IsDeleted || item.Metadata["error_reason_code"] != tc.code ||
|
||||
item.Metadata["error_reason"] == "" {
|
||||
t.Fatalf("error item = %+v", item)
|
||||
}
|
||||
if value := item.Metadata["error_reason_code_value"]; tc.status != 0 && value != fmt.Sprint(tc.status) {
|
||||
t.Fatalf("HTTP reason value = %q, status=%d", value, tc.status)
|
||||
}
|
||||
if known {
|
||||
assertPending(t, cur, p)
|
||||
} else if _, ok := filesOf(cur)[p]; ok {
|
||||
t.Fatalf("unknown failure entered cursor: %v", filesOf(cur))
|
||||
}
|
||||
f.mu.Lock()
|
||||
delete(f.failures, "file:"+p)
|
||||
delete(f.chunkedOversize, p)
|
||||
delete(f.linkOID, p)
|
||||
delete(f.linkURL, p)
|
||||
delete(f.rawBody, "file:"+p)
|
||||
f.mu.Unlock()
|
||||
f.setBody(testRepoID, p, []byte("recovered"))
|
||||
f.resetCounts()
|
||||
next, retry := mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, retry.contentItems(), p)
|
||||
if filesOf(next)[p] == "" || f.count("download:"+p) != 1 {
|
||||
t.Fatalf("pending file not retried: %v, %v", filesOf(next), f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncExactSizeLimit(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
t.Setenv("MAX_FILE_SIZE_MB", "1")
|
||||
body := []byte(strings.Repeat("x", 1<<20))
|
||||
f.addFile(testRepoID, "/docs/exact.pdf", body, 1)
|
||||
_, h := mustRun(t, c, cfg, nil, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/exact.pdf")
|
||||
if len(h.contentItems()[0].Content) != len(body) || len(h.errorItems()) != 0 {
|
||||
t.Fatal("file exactly at limit was not accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncCheckpointCadenceAndResume(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
addNumberedFiles(f, "/docs", 120)
|
||||
cur, h := mustRun(t, c, cfg, nil, false)
|
||||
if len(h.contentItems()) != 120 || len(h.checkpoints) < 3 {
|
||||
t.Fatalf("items=%d, checkpoints=%d", len(h.contentItems()), len(h.checkpoints))
|
||||
}
|
||||
previous := 0
|
||||
for _, cp := range h.checkpoints {
|
||||
n := len(filesOf(&types.SyncCursor{ConnectorCursor: cp}))
|
||||
if n < previous || n-previous > 50 {
|
||||
t.Fatalf("checkpoint sizes: previous=%d, current=%d", previous, n)
|
||||
}
|
||||
previous = n
|
||||
}
|
||||
if previous != 120 || len(filesOf(cur)) != 120 {
|
||||
t.Fatalf("final checkpoint=%d, files=%d", previous, len(filesOf(cur)))
|
||||
}
|
||||
// From an initialized cursor every mutation is a file, so the first
|
||||
// checkpoint lands exactly on the 50th file.
|
||||
h = &recorder{}
|
||||
h.onCheckpoint = func(cp map[string]any) {
|
||||
if len(filesOf(&types.SyncCursor{ConnectorCursor: cp})) >= 50 {
|
||||
h.cancel()
|
||||
}
|
||||
}
|
||||
_, err := run(t, c, cfg, seededCursor(t, "Library", map[string]string{}), h, false)
|
||||
if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 {
|
||||
t.Fatalf("checkpoint cancellation = %v; late checkpoints=%d", err, h.checkpointsAfterStop)
|
||||
}
|
||||
saved := checkpointCursor(t, h)
|
||||
savedFiles := filesOf(saved)
|
||||
if len(savedFiles) != 50 {
|
||||
t.Fatalf("first progress checkpoint saved %d files", len(savedFiles))
|
||||
}
|
||||
f.resetCounts()
|
||||
cur, resumed := mustRun(t, c, cfg, saved, false)
|
||||
if len(resumed.contentItems()) != 70 || len(filesOf(cur)) != 120 {
|
||||
t.Fatalf("resume items=%d, files=%d", len(resumed.contentItems()), len(filesOf(cur)))
|
||||
}
|
||||
for p := range savedFiles {
|
||||
if f.count("download:"+p) != 0 {
|
||||
t.Fatalf("saved file downloaded again: %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Known-file failures flip fingerprints to empty; those mutations must
|
||||
// respect the same 50-change checkpoint bound as successful downloads.
|
||||
func TestSyncKnownFailuresCheckpointCadence(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
addNumberedFiles(f, "/docs", 120)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
for i := 0; i < 120; i++ {
|
||||
p := fmt.Sprintf("/docs/%03d.pdf", i)
|
||||
f.touch(testRepoID, p)
|
||||
f.fail("file:"+p, 500, -1)
|
||||
}
|
||||
pending := func(cp map[string]any) int {
|
||||
n := 0
|
||||
for _, fp := range filesOf(&types.SyncCursor{ConnectorCursor: cp}) {
|
||||
if fp == "" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
h := &recorder{}
|
||||
h.onCheckpoint = func(cp map[string]any) {
|
||||
if pending(cp) >= 50 {
|
||||
h.cancel()
|
||||
}
|
||||
}
|
||||
_, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 {
|
||||
t.Fatalf("failure cadence = %v; late checkpoints=%d", err, h.checkpointsAfterStop)
|
||||
}
|
||||
if got := pending(h.checkpoints[len(h.checkpoints)-1]); got != 50 || len(h.errorItems()) != 50 {
|
||||
t.Fatalf("first failure checkpoint saved %d pending paths after %d error items", got, len(h.errorItems()))
|
||||
}
|
||||
|
||||
h = &recorder{checkpointErr: errors.New("checkpoint unavailable")}
|
||||
if _, err := run(t, c, cfg, old, h, false); !errors.Is(err, h.checkpointErr) || len(h.errorItems()) != 50 {
|
||||
t.Fatalf("checkpoint failure on the failure path = %v after %d error items", err, len(h.errorItems()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncHandlerFailuresStopImmediately(t *testing.T) {
|
||||
checkpointFailure := errors.New("checkpoint unavailable")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
handler *recorder
|
||||
want error
|
||||
emits, checkpoints int
|
||||
}{
|
||||
{"early cancel", &recorder{cancelAfter: 1}, context.Canceled, 1, 0},
|
||||
{"cancel after progress", &recorder{cancelAfter: 51}, context.Canceled, 51, 1},
|
||||
{"emit failure", &recorder{failEmitAfter: 51}, errRecordedEmit, 51, 1},
|
||||
{"checkpoint failure", &recorder{checkpointErr: checkpointFailure}, checkpointFailure, 50, 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
addNumberedFiles(f, "/docs", 120)
|
||||
_, err := run(t, c, cfg, seededCursor(t, "Library", map[string]string{}), tc.handler, false)
|
||||
h := tc.handler
|
||||
if !errors.Is(err, tc.want) || len(h.items) != tc.emits || len(h.checkpoints) != tc.checkpoints ||
|
||||
h.checkpointsAfterStop != 0 || f.countPrefix("download:") != tc.emits ||
|
||||
f.countPrefix("file:") != tc.emits {
|
||||
t.Fatalf("err=%v, emits=%d, checkpoints=%d, late=%d, counts=%v",
|
||||
err, len(h.items), len(h.checkpoints), h.checkpointsAfterStop, f.counts())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncDeletionAndCheckpointBeforeDeletion(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/gone.pdf", []byte("gone"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/docs/gone.pdf")
|
||||
f.addFile(testRepoID, "/docs/new.pdf", []byte("new"), 1)
|
||||
h := &recorder{}
|
||||
h.onEmit = func(item types.FetchedItem) {
|
||||
if item.IsDeleted {
|
||||
saved := filesOf(checkpointCursor(t, h))
|
||||
if saved["/docs/new.pdf"] == "" || saved["/docs/gone.pdf"] == "" {
|
||||
t.Fatalf("pre-deletion checkpoint lost progress/baseline: %v", saved)
|
||||
}
|
||||
}
|
||||
}
|
||||
cur, err := run(t, c, cfg, old, h, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPaths(t, h.deletedItems(), "/docs/gone.pdf")
|
||||
assertPaths(t, h.contentItems(), "/docs/new.pdf")
|
||||
if len(filesOf(cur)) != 1 {
|
||||
t.Fatalf("deletion not reflected in cursor: %v", filesOf(cur))
|
||||
}
|
||||
_, again := mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, again.deletedItems())
|
||||
}
|
||||
|
||||
// Cancellation raised inside a handler callback during reconciliation must stop
|
||||
// the connector itself: no further deletion is emitted and nothing is saved.
|
||||
func TestSyncCancelDuringReconciliationStopsImmediately(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
wire func(h *recorder)
|
||||
emits int
|
||||
}{
|
||||
{"pre-deletion checkpoint", func(h *recorder) {
|
||||
h.onCheckpoint = func(map[string]any) { h.cancel() }
|
||||
}, 1},
|
||||
{"first deletion", func(h *recorder) {
|
||||
h.onEmit = func(item types.FetchedItem) {
|
||||
if item.IsDeleted {
|
||||
h.cancel()
|
||||
}
|
||||
}
|
||||
}, 2},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/gone-a.pdf", []byte("a"), 1)
|
||||
f.addFile(testRepoID, "/docs/gone-b.pdf", []byte("b"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/docs/gone-a.pdf")
|
||||
f.removePath(testRepoID, "/docs/gone-b.pdf")
|
||||
f.addFile(testRepoID, "/docs/new.pdf", []byte("new"), 1)
|
||||
h := &recorder{}
|
||||
tc.wire(h)
|
||||
_, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, context.Canceled) || len(h.items) != tc.emits || len(h.checkpoints) != 1 {
|
||||
t.Fatalf("cancel in %s = %v, items=%d, checkpoints=%d", tc.name, err, len(h.items), len(h.checkpoints))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncDirectoryFailuresKeepProgressAndSuppressDeletion(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
inject func(*fakeSeafile)
|
||||
want error
|
||||
reason string
|
||||
}{
|
||||
{"500", func(f *fakeSeafile) { f.fail("dir:/z", 500, -1) }, datasource.ErrFetchFailed, ""},
|
||||
{"503 exhausted", func(f *fakeSeafile) { f.fail("dir:/z", 503, -1) }, datasource.ErrFetchFailed, ""},
|
||||
{"subdir forbidden", func(f *fakeSeafile) {
|
||||
f.addDir(testRepoID, "/z/private")
|
||||
f.forbidden["/z/private"] = true
|
||||
}, datasource.ErrFetchFailed, "seafile_permission_denied"},
|
||||
{"malformed entry", func(f *fakeSeafile) {
|
||||
f.rawBody["dir:/z"] = `[{"id":"bad","name":"../outside.pdf","type":"file","size":1,"mtime":1}]`
|
||||
}, datasource.ErrFetchFailed, ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/a", "/z")
|
||||
f.addFile(testRepoID, "/a/gone.pdf", []byte("gone"), 1)
|
||||
f.addFile(testRepoID, "/z/keep.pdf", []byte("keep"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/a/gone.pdf")
|
||||
f.addFile(testRepoID, "/a/new.pdf", []byte("new"), 1)
|
||||
tc.inject(f)
|
||||
h := &recorder{}
|
||||
_, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, tc.want) || (tc.reason != "" && !strings.Contains(err.Error(), tc.reason)) {
|
||||
t.Fatalf("directory failure = %v, want %v / %s", err, tc.want, tc.reason)
|
||||
}
|
||||
assertPaths(t, h.deletedItems())
|
||||
assertPaths(t, h.contentItems(), "/a/new.pdf")
|
||||
saved := filesOf(checkpointCursor(t, h))
|
||||
for _, p := range []string{"/a/gone.pdf", "/a/new.pdf", "/z/keep.pdf"} {
|
||||
if saved[p] == "" {
|
||||
t.Fatalf("directory failure lost %s: %v", p, saved)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncFileFailureDoesNotSuppressOtherDeletions(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/fail.pdf", []byte("fail"), 1)
|
||||
f.addFile(testRepoID, "/docs/gone.pdf", []byte("gone"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.touch(testRepoID, "/docs/fail.pdf")
|
||||
f.fail("file:/docs/fail.pdf", 500, -1)
|
||||
f.removePath(testRepoID, "/docs/gone.pdf")
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
assertPaths(t, h.errorItems(), "/docs/fail.pdf")
|
||||
assertPaths(t, h.deletedItems(), "/docs/gone.pdf")
|
||||
assertPending(t, cur, "/docs/fail.pdf")
|
||||
if len(filesOf(cur)) != 1 {
|
||||
t.Fatalf("cursor = %v", filesOf(cur))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLongRetryAfterAborts(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/a", "/b", "/z")
|
||||
f.addFile(testRepoID, "/a/gone.pdf", []byte("gone"), 1)
|
||||
f.addDir(testRepoID, "/b")
|
||||
f.addFile(testRepoID, "/z/later.pdf", []byte("later"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/a/gone.pdf")
|
||||
f.addFile(testRepoID, "/a/progress.pdf", []byte("progress"), 1)
|
||||
f.addFile(testRepoID, "/b/stop.pdf", []byte("stop"), 1)
|
||||
f.addFile(testRepoID, "/b/zz-later.pdf", []byte("later"), 1)
|
||||
f.failWithRetryAfter("file:/b/stop.pdf", 429, -1, "120")
|
||||
f.resetCounts()
|
||||
h := &recorder{}
|
||||
var atAbort map[string]int
|
||||
h.onCheckpoint = func(map[string]any) { atAbort = f.counts() }
|
||||
_, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, datasource.ErrFetchFailed) || f.count("file:/b/stop.pdf") != 1 ||
|
||||
f.count("download:/b/stop.pdf") != 0 || f.count("dir:/z") != 0 ||
|
||||
f.countPrefix("file:") != 2 || f.countPrefix("download:") != 1 {
|
||||
t.Fatalf("Retry-After abort = %v, counts=%v", err, f.counts())
|
||||
}
|
||||
assertPaths(t, h.deletedItems())
|
||||
saved := filesOf(checkpointCursor(t, h))
|
||||
if saved["/a/progress.pdf"] == "" || saved["/a/gone.pdf"] == "" ||
|
||||
!reflect.DeepEqual(atAbort, f.counts()) {
|
||||
t.Fatalf("abort checkpoint or subsequent requests: saved=%v, before=%v, after=%v", saved, atAbort, f.counts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncMoveDuringScan(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/A", "/B")
|
||||
f.addFile(testRepoID, "/A/first.pdf", []byte("first"), 1)
|
||||
f.addFile(testRepoID, "/B/moving.pdf", []byte("moving"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.touch(testRepoID, "/A/first.pdf")
|
||||
f.resetCounts()
|
||||
h := &recorder{}
|
||||
moved := false
|
||||
h.onEmit = func(item types.FetchedItem) {
|
||||
if item.Metadata["seafile_path"] == "/A/first.pdf" && item.Content != nil {
|
||||
if f.count("dir:/B") != 0 {
|
||||
t.Fatal("B was listed before the move")
|
||||
}
|
||||
f.movePath(testRepoID, "/B/moving.pdf", "/A/moving.pdf")
|
||||
moved = true
|
||||
}
|
||||
}
|
||||
cur, err := run(t, c, cfg, old, h, false)
|
||||
if err != nil || !moved {
|
||||
t.Fatalf("move during scan = %v, moved=%v", err, moved)
|
||||
}
|
||||
assertPaths(t, h.contentItems(), "/A/first.pdf")
|
||||
assertPaths(t, h.deletedItems(), "/B/moving.pdf")
|
||||
_, next := mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, next.contentItems(), "/A/moving.pdf")
|
||||
assertPaths(t, next.deletedItems())
|
||||
}
|
||||
|
||||
func TestSyncRenameAndMoveOutOfScope(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/old.pdf", []byte("body"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.movePath(testRepoID, "/docs/old.pdf", "/docs/new.pdf")
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/new.pdf")
|
||||
assertPaths(t, h.deletedItems(), "/docs/old.pdf")
|
||||
f.movePath(testRepoID, "/docs/new.pdf", "/elsewhere/new.pdf")
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems())
|
||||
assertPaths(t, h.deletedItems(), "/docs/new.pdf")
|
||||
if len(filesOf(cur)) != 0 || f.count("dir:/elsewhere") != 0 {
|
||||
t.Fatalf("move out of scope: files=%v, counts=%v", filesOf(cur), f.counts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncScopeShrinkAndExpand(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/a/one.pdf", []byte("one"), 1)
|
||||
f.addFile(testRepoID, "/docs/b/two.pdf", []byte("two"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
cfg.ResourceIDs = []string{testRepoID + ":/docs/a"}
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
assertPaths(t, h.deletedItems(), "/docs/b/two.pdf")
|
||||
assertPaths(t, h.contentItems())
|
||||
cfg.ResourceIDs = []string{testRepoID + ":/docs"}
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/b/two.pdf")
|
||||
assertPaths(t, h.deletedItems())
|
||||
if len(filesOf(cur)) != 2 {
|
||||
t.Fatalf("expanded cursor = %v", filesOf(cur))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSelectedDirectoryDisappears(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/docs")
|
||||
h := &recorder{}
|
||||
cur, err := run(t, c, cfg, old, h, false)
|
||||
if !errors.Is(err, datasource.ErrResourceNotFound) {
|
||||
t.Fatalf("missing selected directory = %v", err)
|
||||
}
|
||||
assertPaths(t, h.deletedItems())
|
||||
if filesOf(old)["/docs/a.pdf"] == "" {
|
||||
t.Fatal("lost the old directory's file")
|
||||
}
|
||||
if cur != nil && filesOf(cur)["/docs/a.pdf"] == "" {
|
||||
t.Fatal("returned cursor lost the old directory's file")
|
||||
}
|
||||
for _, cp := range h.checkpoints {
|
||||
if filesOf(&types.SyncCursor{ConnectorCursor: cp})["/docs/a.pdf"] == "" {
|
||||
t.Fatal("checkpoint lost the old directory's file")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncForcedFullCancelResumeAndUnionDeletions(t *testing.T) {
|
||||
for _, addedThenRemoved := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("added-then-removed=%v", addedThenRemoved), func(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
addNumberedFiles(f, "/docs", 65)
|
||||
f.addFile(testRepoID, "/docs/vanished.pdf", []byte("gone"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
before := cursorJSON(t, old)
|
||||
f.removePath(testRepoID, "/docs/vanished.pdf")
|
||||
if addedThenRemoved {
|
||||
f.addFile(testRepoID, "/docs/000-new.pdf", []byte("new"), 1)
|
||||
}
|
||||
f.resetCounts()
|
||||
h := &recorder{}
|
||||
h.onCheckpoint = func(map[string]any) { h.cancel() }
|
||||
_, err := run(t, c, cfg, old, h, true)
|
||||
if !errors.Is(err, context.Canceled) || h.checkpointsAfterStop != 0 {
|
||||
t.Fatalf("full cancel = %v, late checkpoints=%d", err, h.checkpointsAfterStop)
|
||||
}
|
||||
saved := checkpointCursor(t, h)
|
||||
active := mustCursor(t, saved)
|
||||
// Switching into full sync is itself a mutation, so the first batch
|
||||
// holds 49 files.
|
||||
batch := len(active.Files)
|
||||
if !active.FullSync || !reflect.DeepEqual(active.FullSyncBaseline, filesOf(old)) ||
|
||||
batch != 49 || len(h.contentItems()) != batch || f.countPrefix("download:") != batch {
|
||||
t.Fatalf("full checkpoint files=%d downloads=%d", batch, f.countPrefix("download:"))
|
||||
}
|
||||
if cursorJSON(t, old) != before {
|
||||
t.Fatal("forced full mutated its input baseline")
|
||||
}
|
||||
wantDeleted := []string{"/docs/vanished.pdf"}
|
||||
if addedThenRemoved {
|
||||
if active.Files["/docs/000-new.pdf"] == "" {
|
||||
t.Fatal("new file was not saved before cancellation")
|
||||
}
|
||||
f.removePath(testRepoID, "/docs/000-new.pdf")
|
||||
wantDeleted = append(wantDeleted, "/docs/000-new.pdf")
|
||||
}
|
||||
f.resetCounts()
|
||||
cur, resumed := mustRun(t, c, cfg, saved, false)
|
||||
assertPaths(t, resumed.deletedItems(), wantDeleted...)
|
||||
expectedRemaining := 65 - len(active.Files)
|
||||
if addedThenRemoved {
|
||||
expectedRemaining++
|
||||
}
|
||||
if len(resumed.contentItems()) != expectedRemaining {
|
||||
t.Fatalf("resume content=%d, want %d", len(resumed.contentItems()), expectedRemaining)
|
||||
}
|
||||
for p := range active.Files {
|
||||
if f.count("download:"+p) != 0 {
|
||||
t.Fatalf("full resume downloaded saved file %s", p)
|
||||
}
|
||||
}
|
||||
assertFullSyncCleared(t, cur)
|
||||
if len(filesOf(cur)) != 65 {
|
||||
t.Fatalf("full completion files = %d", len(filesOf(cur)))
|
||||
}
|
||||
_, next := mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, next.items)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncFullDirectoryFailureResumesIncrementally(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/a", "/z")
|
||||
f.addFile(testRepoID, "/a/one.pdf", []byte("one"), 1)
|
||||
f.addFile(testRepoID, "/z/two.pdf", []byte("two"), 1)
|
||||
f.addFile(testRepoID, "/z/gone.pdf", []byte("gone"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.removePath(testRepoID, "/z/gone.pdf")
|
||||
f.fail("dir:/z", 500, -1)
|
||||
h := &recorder{}
|
||||
_, err := run(t, c, cfg, old, h, true)
|
||||
if !errors.Is(err, datasource.ErrFetchFailed) {
|
||||
t.Fatalf("full directory failure = %v", err)
|
||||
}
|
||||
assertPaths(t, h.contentItems(), "/a/one.pdf")
|
||||
assertPaths(t, h.deletedItems())
|
||||
saved := checkpointCursor(t, h)
|
||||
active := mustCursor(t, saved)
|
||||
if !active.FullSync || !reflect.DeepEqual(active.FullSyncBaseline, filesOf(old)) ||
|
||||
active.Files["/a/one.pdf"] == "" {
|
||||
t.Fatalf("interrupted full cursor = %+v", active)
|
||||
}
|
||||
f.fail("dir:/z", 500, 0)
|
||||
f.resetCounts()
|
||||
cur, resumed := mustRun(t, c, cfg, saved, false)
|
||||
assertPaths(t, resumed.contentItems(), "/z/two.pdf")
|
||||
assertPaths(t, resumed.deletedItems(), "/z/gone.pdf")
|
||||
assertFullSyncCleared(t, cur)
|
||||
if f.count("download:/a/one.pdf") != 0 || len(filesOf(cur)) != 2 {
|
||||
t.Fatalf("completed cursor=%v, requests=%v", filesOf(cur), f.counts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncLibraryRenameKeepsFolderName(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
f.addFile(testRepoID, "/docs/a.pdf", []byte("a"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.renameRepo(testRepoID, "Renamed library")
|
||||
f.resetCounts()
|
||||
cur, h := mustRun(t, c, cfg, old, false)
|
||||
if len(h.items) != 0 || f.countPrefix("download:") != 0 || mustCursor(t, cur).RepoName != "Library" {
|
||||
t.Fatalf("library rename caused churn: items=%+v, counts=%v, cursor=%+v", h.items, f.counts(), cur)
|
||||
}
|
||||
f.addFile(testRepoID, "/docs/b.pdf", []byte("b"), 1)
|
||||
_, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.contentItems(), "/docs/b.pdf")
|
||||
if h.contentItems()[0].FileName != "Library/docs/b.pdf" {
|
||||
t.Fatalf("renamed library changed destination folder: %q", h.contentItems()[0].FileName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncFullFailureRetainsPendingThenRetriesAndDeletes(t *testing.T) {
|
||||
f, c, cfg := syncFixture(t, "/docs")
|
||||
p := "/docs/a.pdf"
|
||||
f.addFile(testRepoID, p, []byte("body"), 1)
|
||||
old, _ := mustRun(t, c, cfg, nil, false)
|
||||
f.fail("file:"+p, 500, -1)
|
||||
cur, h := mustRun(t, c, cfg, old, true)
|
||||
assertPaths(t, h.errorItems(), p)
|
||||
assertPaths(t, h.deletedItems())
|
||||
assertPending(t, cur, p)
|
||||
assertFullSyncCleared(t, cur)
|
||||
f.resetCounts()
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.errorItems(), p)
|
||||
assertPending(t, cur, p)
|
||||
if f.count("file:"+p) == 0 {
|
||||
t.Fatal("incremental did not retry the empty fingerprint")
|
||||
}
|
||||
f.removePath(testRepoID, p)
|
||||
cur, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.deletedItems(), p)
|
||||
if len(filesOf(cur)) != 0 {
|
||||
t.Fatalf("deleted pending path remains: %v", filesOf(cur))
|
||||
}
|
||||
_, h = mustRun(t, c, cfg, cur, false)
|
||||
assertPaths(t, h.deletedItems())
|
||||
}
|
||||
|
||||
func compactRecorder() *recorder {
|
||||
h := &recorder{}
|
||||
// Scale runs need the latest resume point, not hundreds of full maps.
|
||||
// Each callback still receives a JSON-deep-copied snapshot.
|
||||
h.onCheckpoint = func(cp map[string]any) {
|
||||
h.checkpoints = []map[string]any{cp}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// Package seafile implements the Academy data source connector for Seafile
|
||||
// Server (community edition 10.0.1, api2). A data source selects nodes of a
|
||||
// single library; the connector scans the selected scope one directory level
|
||||
// at a time, downloads files through the two-step link + fileserver flow and
|
||||
// reconciles deletions against a per-file fingerprint cursor.
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// config is the parsed credential set. The selection lives entirely in
|
||||
// resource_ids, so Settings carry no Seafile-specific keys and are ignored;
|
||||
// a stale key left over from another connector type does no harm.
|
||||
type config struct {
|
||||
baseURL string
|
||||
token string
|
||||
}
|
||||
|
||||
func parseConfig(ds *types.DataSourceConfig) (config, error) {
|
||||
if ds == nil {
|
||||
return config{}, fmt.Errorf("%w: seafile config is nil", datasource.ErrInvalidConfig)
|
||||
}
|
||||
rawBase, _ := ds.Credentials["base_url"].(string)
|
||||
rawToken, _ := ds.Credentials["api_token"].(string)
|
||||
|
||||
token := strings.TrimSpace(rawToken)
|
||||
if token == "" || strings.ContainsFunc(token, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || unicode.IsControl(r)
|
||||
}) {
|
||||
return config{}, fmt.Errorf("%w: api_token is required and must not contain whitespace",
|
||||
datasource.ErrInvalidConfig)
|
||||
}
|
||||
|
||||
baseURL, err := normalizeBaseURL(rawBase)
|
||||
if err != nil {
|
||||
return config{}, err
|
||||
}
|
||||
return config{baseURL: baseURL, token: token}, nil
|
||||
}
|
||||
|
||||
// normalizeBaseURL trims the URL, defaults the scheme to https, drops the
|
||||
// trailing slash and keeps any deployment path prefix.
|
||||
func normalizeBaseURL(raw string) (string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return "", fmt.Errorf("%w: base_url is required", datasource.ErrInvalidConfig)
|
||||
}
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "https://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") ||
|
||||
u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
|
||||
return "", fmt.Errorf("%w: base_url must be an http(s) URL without credentials, query or fragment",
|
||||
datasource.ErrInvalidConfig)
|
||||
}
|
||||
base := strings.TrimRight(u.String(), "/")
|
||||
if err := datasource.ValidateConnectorBaseURL(base); err != nil {
|
||||
return "", fmt.Errorf("%w: %v", datasource.ErrInvalidConfig, err)
|
||||
}
|
||||
return base, nil
|
||||
}
|
||||
|
||||
// Resource IDs are "<repo_id>:<absolute path>"; the library root is
|
||||
// "<repo_id>:/". The split happens at the first colon so paths may contain
|
||||
// colons. IDs are never URL-decoded.
|
||||
|
||||
var repoIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
|
||||
func parseResourceID(id string) (repoID, path string, err error) {
|
||||
repoID, rawPath, ok := strings.Cut(id, ":")
|
||||
if !ok || !repoIDPattern.MatchString(repoID) {
|
||||
return "", "", fmt.Errorf("%w: seafile resource id must be <repo_id>:<absolute path>",
|
||||
datasource.ErrInvalidConfig)
|
||||
}
|
||||
path, err = normalizePath(rawPath)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return repoID, path, nil
|
||||
}
|
||||
|
||||
func encodeResourceID(repoID, path string) string {
|
||||
return repoID + ":" + path
|
||||
}
|
||||
|
||||
// normalizePath collapses repeated slashes, strips the trailing slash (except
|
||||
// for the root) and rejects dot segments, backslashes and control characters.
|
||||
func normalizePath(p string) (string, error) {
|
||||
if !strings.HasPrefix(p, "/") || strings.Contains(p, "\\") || strings.ContainsFunc(p, unicode.IsControl) {
|
||||
return "", fmt.Errorf("%w: seafile path must be absolute without backslashes or control characters",
|
||||
datasource.ErrInvalidConfig)
|
||||
}
|
||||
segments := make([]string, 0, 8)
|
||||
for _, segment := range strings.Split(p, "/") {
|
||||
switch segment {
|
||||
case "":
|
||||
continue
|
||||
case ".", "..":
|
||||
return "", fmt.Errorf("%w: seafile path must not contain dot segments", datasource.ErrInvalidConfig)
|
||||
}
|
||||
segments = append(segments, segment)
|
||||
}
|
||||
return "/" + strings.Join(segments, "/"), nil
|
||||
}
|
||||
|
||||
// collapseRoots dedupes and sorts the selection, requires a single library
|
||||
// and drops every path whose ancestor directory is also selected. "/a" does
|
||||
// not cover "/ab".
|
||||
func collapseRoots(ids []string) (repoID string, roots []string, err error) {
|
||||
if len(ids) == 0 {
|
||||
return "", nil, fmt.Errorf("%w: seafile requires at least one selected resource", datasource.ErrInvalidConfig)
|
||||
}
|
||||
selected := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
repo, p, err := parseResourceID(id)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if repoID != "" && repo != repoID {
|
||||
return "", nil, fmt.Errorf("%w: seafile selections must belong to one library", datasource.ErrInvalidConfig)
|
||||
}
|
||||
repoID = repo
|
||||
selected[p] = true
|
||||
}
|
||||
sorted := make([]string, 0, len(selected))
|
||||
for p := range selected {
|
||||
sorted = append(sorted, p)
|
||||
}
|
||||
sort.Strings(sorted)
|
||||
for _, p := range sorted {
|
||||
if !hasSelectedAncestor(p, selected) {
|
||||
roots = append(roots, p)
|
||||
}
|
||||
}
|
||||
return repoID, roots, nil
|
||||
}
|
||||
|
||||
func hasSelectedAncestor(p string, selected map[string]bool) bool {
|
||||
for p != "/" {
|
||||
p = parentPath(p)
|
||||
if selected[p] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parentPath returns the parent of a normalized absolute path ("/" for
|
||||
// top-level entries).
|
||||
func parentPath(p string) string {
|
||||
if i := strings.LastIndex(p, "/"); i > 0 {
|
||||
return p[:i]
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
// ancestorIDs lists the resource IDs a lazy picker must expand to reveal id:
|
||||
// "<repo>:/a/b/c" yields "<repo>:/", "<repo>:/a", "<repo>:/a/b". Unparsable
|
||||
// IDs and the root yield nothing.
|
||||
func ancestorIDs(id string) []string {
|
||||
repoID, p, err := parseResourceID(id)
|
||||
if err != nil || p == "/" {
|
||||
return nil
|
||||
}
|
||||
out := []string{encodeResourceID(repoID, "/")}
|
||||
for i := 1; i < len(p); i++ {
|
||||
if p[i] == '/' {
|
||||
out = append(out, encodeResourceID(repoID, p[:i]))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// repoInfo is one row of GET /api2/repos/. seahub 10.0.1 exposes no reliable
|
||||
// "virtual" marker, so it is deliberately not decoded.
|
||||
type repoInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Encrypted bool `json:"encrypted"`
|
||||
Permission string `json:"permission"`
|
||||
}
|
||||
|
||||
// dirent is one entry of GET /api2/repos/{id}/dir/. Only file entries carry
|
||||
// a size key.
|
||||
type dirent struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Mtime int64 `json:"mtime"`
|
||||
Size *int64 `json:"size,omitempty"`
|
||||
Permission string `json:"permission"`
|
||||
}
|
||||
|
||||
// Error reason codes surfaced on error items; the frontend localises them via
|
||||
// datasource.syncError.<code>.
|
||||
const (
|
||||
reasonPermissionDenied = "seafile_permission_denied"
|
||||
reasonNotFound = "seafile_not_found"
|
||||
reasonFileTooLarge = "seafile_file_too_large"
|
||||
reasonEmptyFile = "seafile_empty_file"
|
||||
reasonSourceChanged = "seafile_source_changed"
|
||||
reasonInvalidResponse = "seafile_invalid_response"
|
||||
reasonSSRFBlocked = "seafile_ssrf_blocked"
|
||||
reasonFetchFailed = "seafile_fetch_failed"
|
||||
)
|
||||
|
||||
var reasonText = map[string]string{
|
||||
reasonPermissionDenied: "Permission to access the Seafile resource was denied",
|
||||
reasonNotFound: "The Seafile resource was not found",
|
||||
reasonFileTooLarge: "The Seafile file exceeds the configured size limit",
|
||||
reasonEmptyFile: "The Seafile file is empty",
|
||||
reasonSourceChanged: "The Seafile file changed while it was being fetched",
|
||||
reasonInvalidResponse: "Seafile returned an unexpected response",
|
||||
reasonSSRFBlocked: "The Seafile download URL was blocked by the SSRF policy",
|
||||
reasonFetchFailed: "Failed to fetch the file from Seafile",
|
||||
}
|
||||
|
||||
// errorReason returns the English fallback text for a reason code.
|
||||
func errorReason(code string) string {
|
||||
if text, ok := reasonText[code]; ok {
|
||||
return text
|
||||
}
|
||||
return reasonText[reasonFetchFailed]
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package seafile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/datasource"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
testRepoID = "01234567-89ab-cdef-0123-456789abcdef"
|
||||
otherRepoID = "fedcba98-7654-3210-fedc-ba9876543210"
|
||||
testToken = "seafile-secret-token-do-not-echo"
|
||||
)
|
||||
|
||||
func TestParseResourceID(t *testing.T) {
|
||||
for _, tc := range []struct{ input, want string }{
|
||||
{"/", "/"},
|
||||
{"////", "/"},
|
||||
{"//a///b/", "/a/b"},
|
||||
{"/a:b/c:d", "/a:b/c:d"},
|
||||
{"/产品/说明.pdf", "/产品/说明.pdf"},
|
||||
{"/%2e%2e/a%2Fb", "/%2e%2e/a%2Fb"},
|
||||
{"/ spaced /file ", "/ spaced /file "},
|
||||
} {
|
||||
t.Run(tc.input, func(t *testing.T) {
|
||||
repo, p, err := parseResourceID(testRepoID + ":" + tc.input)
|
||||
if err != nil || repo != testRepoID || p != tc.want {
|
||||
t.Fatalf("parse = (%q, %q, %v), want path %q", repo, p, err, tc.want)
|
||||
}
|
||||
againRepo, againPath, err := parseResourceID(encodeResourceID(repo, p))
|
||||
if err != nil || againRepo != repo || againPath != p {
|
||||
t.Fatalf("round trip = (%q, %q, %v)", againRepo, againPath, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, id := range []string{
|
||||
"", testRepoID, testRepoID + ":", testRepoID + ":relative",
|
||||
testRepoID + ":/a/../b", testRepoID + ":/./a", testRepoID + ":/a/..",
|
||||
testRepoID + ":/a\\b", testRepoID + ":/a\nb", testRepoID + ":/a\x00b",
|
||||
strings.ToUpper(testRepoID) + ":/", "123:/", testRepoID + "0:/",
|
||||
} {
|
||||
t.Run("invalid "+id, func(t *testing.T) {
|
||||
if _, _, err := parseResourceID(id); !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("expected ErrInvalidConfig, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollapseRoots(t *testing.T) {
|
||||
input := []string{
|
||||
testRepoID + ":/ab", testRepoID + ":/a/c", testRepoID + ":/a-b",
|
||||
testRepoID + ":/a/", testRepoID + ":/a", testRepoID + ":/z/deep",
|
||||
}
|
||||
want := []string{"/a", "/a-b", "/ab", "/z/deep"}
|
||||
for i := 0; i < len(input); i++ {
|
||||
repo, roots, err := collapseRoots(input)
|
||||
if err != nil || repo != testRepoID || !slices.Equal(roots, want) {
|
||||
t.Fatalf("collapse(%v) = (%q, %v, %v)", input, repo, roots, err)
|
||||
}
|
||||
input = append(input[1:], input[0])
|
||||
}
|
||||
_, roots, err := collapseRoots(append(input, testRepoID+":/"))
|
||||
if err != nil || !slices.Equal(roots, []string{"/"}) {
|
||||
t.Fatalf("root collapse = (%v, %v)", roots, err)
|
||||
}
|
||||
for _, ids := range [][]string{
|
||||
nil,
|
||||
{},
|
||||
{testRepoID + ":/", otherRepoID + ":/a"},
|
||||
{testRepoID + ":/", "invalid"},
|
||||
{testRepoID + ":/a", testRepoID + ":/../b"},
|
||||
} {
|
||||
if _, _, err := collapseRoots(ids); !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("collapse(%v): expected ErrInvalidConfig, got %v", ids, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfig(t *testing.T) {
|
||||
for _, settings := range []map[string]any{nil, {}, {"edition": "server"}} {
|
||||
cfg, err := parseConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]any{"base_url": " localhost/seafile/// ", "api_token": " " + testToken + " "},
|
||||
Settings: settings,
|
||||
})
|
||||
if err != nil || cfg.baseURL != "https://localhost/seafile" || cfg.token != testToken {
|
||||
t.Fatalf("parseConfig = (%+v, %v)", cfg, err)
|
||||
}
|
||||
}
|
||||
for _, token := range []any{"", " ", "a b", "a\tb", "a\nb", "a\x00b", 123, nil} {
|
||||
_, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]any{
|
||||
"base_url": "http://localhost", "api_token": token,
|
||||
}})
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("token %q accepted: %v", token, err)
|
||||
}
|
||||
}
|
||||
for _, base := range []any{
|
||||
"", 123, "ftp://localhost", "https://", "http://169.254.169.254",
|
||||
"http://user:" + testToken + "@localhost", "http://localhost/?token=" + testToken,
|
||||
"http://localhost/#fragment",
|
||||
} {
|
||||
_, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]any{
|
||||
"base_url": base, "api_token": testToken,
|
||||
}})
|
||||
if !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("base_url %q accepted: %v", base, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), testToken) {
|
||||
t.Fatalf("config error leaked the token: %v", err)
|
||||
}
|
||||
}
|
||||
for _, ds := range []*types.DataSourceConfig{nil, {}} {
|
||||
if _, err := parseConfig(ds); !errors.Is(err, datasource.ErrInvalidConfig) {
|
||||
t.Fatalf("empty config accepted: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAncestorIDs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
id string
|
||||
want []string
|
||||
}{
|
||||
{testRepoID + ":/a/b/c", []string{testRepoID + ":/", testRepoID + ":/a", testRepoID + ":/a/b"}},
|
||||
{testRepoID + ":/a:b/c", []string{testRepoID + ":/", testRepoID + ":/a:b"}},
|
||||
{testRepoID + ":/", nil},
|
||||
{testRepoID + ":/../a", nil},
|
||||
{"invalid", nil},
|
||||
} {
|
||||
if got := ancestorIDs(tc.id); !slices.Equal(got, tc.want) {
|
||||
t.Fatalf("ancestorIDs(%q) = %v, want %v", tc.id, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorReason(t *testing.T) {
|
||||
for _, code := range []string{
|
||||
reasonPermissionDenied, reasonNotFound, reasonFileTooLarge, reasonEmptyFile,
|
||||
reasonSourceChanged, reasonInvalidResponse, reasonSSRFBlocked, reasonFetchFailed,
|
||||
} {
|
||||
if errorReason(code) == "" {
|
||||
t.Fatalf("no fallback text for %s", code)
|
||||
}
|
||||
}
|
||||
if errorReason("unknown") != errorReason(reasonFetchFailed) {
|
||||
t.Fatal("unknown code should fall back to the generic text")
|
||||
}
|
||||
}
|
||||
|
||||
func FuzzResourceID(f *testing.F) {
|
||||
for _, id := range []string{testRepoID + ":/", testRepoID + ":/a:b//产品/", testRepoID + ":/../a", ""} {
|
||||
f.Add(id)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, id string) {
|
||||
repo, p, err := parseResourceID(id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
againRepo, againPath, err := parseResourceID(encodeResourceID(repo, p))
|
||||
if err != nil || againRepo != repo || againPath != p {
|
||||
t.Fatalf("unstable resource id %q", id)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user