From 3c25bb5d61bbfb8dee6405ae5c90e7ba505be742 Mon Sep 17 00:00:00 2001 From: truewhile <62226914+truewhile@users.noreply.github.com> Date: Thu, 27 Aug 2026 13:40:46 +0800 Subject: [PATCH] 3 --- internal/service/cloud115/sha1.go | 4 +++- internal/service/cloud115/upload_test.go | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/service/cloud115/sha1.go b/internal/service/cloud115/sha1.go index f8a2cb4..645d4f1 100644 --- a/internal/service/cloud115/sha1.go +++ b/internal/service/cloud115/sha1.go @@ -40,7 +40,9 @@ func FileSHA1Partial(path string, start, end int64) (string, error) { } length := end - start + 1 h := sha1.New() - if _, err := io.CopyN(h, f, length); err != nil { + // io.CopyN 在文件不足 length 字节时会返回 io.EOF,导致小文件(如小于 128 KiB 的 + // 元数据图片)无法上传。这里只拷贝实际读到的字节,文件尾对齐到区间终点即可。 + if _, err := io.CopyN(h, f, length); err != nil && err != io.EOF { return "", err } return hex.EncodeToString(h.Sum(nil)), nil diff --git a/internal/service/cloud115/upload_test.go b/internal/service/cloud115/upload_test.go index 5664e1f..20cc9b7 100644 --- a/internal/service/cloud115/upload_test.go +++ b/internal/service/cloud115/upload_test.go @@ -39,6 +39,26 @@ func TestFileSHA1Partial(t *testing.T) { } } +// TestFileSHA1PartialSmallerThanWindow 回归测试:经典 bug 是 io.CopyN 在文件不足 +// length 字节时返回 io.EOF。115 上传固定用 [0,128*1024-1] 窗口计算 preid,导致所有 +// 小于 128 KiB 的元数据文件(如海报/缩略图)上传必然失败。 +func TestFileSHA1PartialSmallerThanWindow(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "small.bin") + // 6 字节小文件,不足 128 KiB 窗口 + if err := os.WriteFile(path, []byte("abcdef"), 0o644); err != nil { + t.Fatal(err) + } + sum, err := FileSHA1Partial(path, 0, 128*1024-1) + if err != nil { + t.Fatalf("compute partial sha1 for small file should not fail: %v", err) + } + // 应等于整个文件(6 字节)的 sha1 + if sum != "1f8ac10f23c5b5bc1167bda84b833e5c057a77d2" { + t.Errorf("unexpected partial sha1: %s", sum) + } +} + func TestParseSignCheckRange(t *testing.T) { rng, err := parseSignCheckRange("0-131071") if err != nil {