diff --git a/internal/application/service/tenant_skill_bundle.go b/internal/application/service/tenant_skill_bundle.go index 81696ba8..a4a01b7d 100644 --- a/internal/application/service/tenant_skill_bundle.go +++ b/internal/application/service/tenant_skill_bundle.go @@ -81,6 +81,47 @@ func ParseSkillBundleWithOptions(archive []byte, opts SkillBundleParseOptions) ( } func unzipSkillArchive(archive []byte) (map[string][]byte, error) { + entries, err := skillZipEntries(archive) + if err != nil { + return nil, err + } + + raw := make(map[string][]byte, len(entries)) + var totalBytes int64 + for _, item := range entries { + entryBytes := item.size + if totalBytes+entryBytes > maxSkillBundleTotalBytes { + return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid) + } + totalBytes += entryBytes + content, err := readLimitedZipEntry(item.file) + if err != nil { + return nil, err + } + if int64(len(content)) > entryBytes { + actualExcess := int64(len(content)) - entryBytes + if totalBytes+actualExcess > maxSkillBundleTotalBytes { + return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid) + } + totalBytes += actualExcess + } + raw[item.name] = content + } + return raw, nil +} + +// errSkillFileMissing means the zip is a valid skill archive but the requested +// path is not in it. The browser maps this to 404; every other zip problem is +// still ErrSkillBundleInvalid. +var errSkillFileMissing = errors.New("skill file not found") + +type skillZipEntry struct { + file *zip.File + name string + size int64 +} + +func skillZipEntries(archive []byte) ([]skillZipEntry, error) { reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) if err != nil { return nil, fmt.Errorf("%w: not a readable zip archive: %v", ErrSkillBundleInvalid, err) @@ -90,54 +131,130 @@ func unzipSkillArchive(archive []byte) (map[string][]byte, error) { ErrSkillBundleInvalid, maxSkillBundleFiles) } - raw := make(map[string][]byte, len(reader.File)) + out := make([]skillZipEntry, 0, len(reader.File)) var totalBytes int64 for _, entry := range reader.File { - if entry.FileInfo().IsDir() { - continue - } - if entry.FileInfo().Mode()&os.ModeSymlink != 0 { - return nil, fmt.Errorf("%w: entry %q is a symlink", ErrSkillBundleInvalid, entry.Name) - } - name := path.Clean(entry.Name) - if name == "." || strings.HasPrefix(name, "..") || - path.IsAbs(name) || strings.Contains(name, "../") { - return nil, fmt.Errorf("%w: entry %q escapes the archive root", - ErrSkillBundleInvalid, entry.Name) - } - if err := validateSkillEntryName(name); err != nil { + name, skip, err := inspectSkillZipEntry(entry) + if err != nil { return nil, err } - if entry.FileInfo().Size() > maxSkillBundleFileBytes { - return nil, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name) + if skip { + continue } - entryBytes := entry.FileInfo().Size() - if totalBytes+entryBytes > maxSkillBundleTotalBytes { + size := entry.FileInfo().Size() + if totalBytes+size > maxSkillBundleTotalBytes { return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid) } - totalBytes += entryBytes - rc, err := entry.Open() - if err != nil { - return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err) - } - content, err := io.ReadAll(io.LimitReader(rc, maxSkillBundleFileBytes+1)) - _ = rc.Close() - if err != nil { - return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err) - } - if len(content) > maxSkillBundleFileBytes { - return nil, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name) - } - if int64(len(content)) > entryBytes { - actualExcess := int64(len(content)) - entryBytes - if totalBytes+actualExcess > maxSkillBundleTotalBytes { - return nil, fmt.Errorf("%w: archive is too large", ErrSkillBundleInvalid) - } - totalBytes += actualExcess - } - raw[name] = content + totalBytes += size + out = append(out, skillZipEntry{file: entry, name: name, size: size}) } - return raw, nil + return out, nil +} + +func inspectSkillZipEntry(entry *zip.File) (name string, skip bool, err error) { + if entry.FileInfo().IsDir() { + return "", true, nil + } + if entry.FileInfo().Mode()&os.ModeSymlink != 0 { + return "", false, fmt.Errorf("%w: entry %q is a symlink", ErrSkillBundleInvalid, entry.Name) + } + name = path.Clean(entry.Name) + if name == "." || strings.HasPrefix(name, "..") || + path.IsAbs(name) || strings.Contains(name, "../") { + return "", false, fmt.Errorf("%w: entry %q escapes the archive root", + ErrSkillBundleInvalid, entry.Name) + } + if err := validateSkillEntryName(name); err != nil { + return "", false, err + } + if entry.FileInfo().Size() > maxSkillBundleFileBytes { + return "", false, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name) + } + return name, false, nil +} + +func readLimitedZipEntry(entry *zip.File) ([]byte, error) { + rc, err := entry.Open() + if err != nil { + return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err) + } + content, err := io.ReadAll(io.LimitReader(rc, maxSkillBundleFileBytes+1)) + _ = rc.Close() + if err != nil { + return nil, fmt.Errorf("%w: cannot read %q: %v", ErrSkillBundleInvalid, entry.Name, err) + } + if len(content) > maxSkillBundleFileBytes { + return nil, fmt.Errorf("%w: entry %q is too large", ErrSkillBundleInvalid, entry.Name) + } + return content, nil +} + +// listSkillZipFiles returns skill-root-relative paths and declared uncompressed +// sizes from the zip central directory. It does not inflate file bodies. +func listSkillZipFiles(archive []byte) ([]SkillFileEntry, error) { + index, err := skillZipFileIndex(archive) + if err != nil { + return nil, err + } + names := make([]string, 0, len(index)) + for name := range index { + names = append(names, name) + } + sort.Strings(names) + out := make([]SkillFileEntry, 0, len(names)) + for _, name := range names { + out = append(out, SkillFileEntry{Path: name, Size: index[name].size}) + } + return out, nil +} + +// readSkillZipFile inflates one skill-root-relative path and leaves the rest +// of the archive compressed. +func readSkillZipFile(archive []byte, rel string) ([]byte, error) { + index, err := skillZipFileIndex(archive) + if err != nil { + return nil, err + } + item, ok := index[rel] + if !ok { + return nil, errSkillFileMissing + } + return readLimitedZipEntry(item.file) +} + +func skillZipFileIndex(archive []byte) (map[string]skillZipEntry, error) { + entries, err := skillZipEntries(archive) + if err != nil { + return nil, err + } + raw := make(map[string][]byte, len(entries)) + byArchiveName := make(map[string]skillZipEntry, len(entries)) + for _, item := range entries { + raw[item.name] = nil + byArchiveName[item.name] = item + } + opts := SkillBundleParseOptions{} + stripped, err := stripSkillRootPrefix(raw, opts) + if err != nil { + return nil, err + } + prefix, err := skillRootPrefix(raw, opts) + if err != nil { + return nil, err + } + out := make(map[string]skillZipEntry, len(stripped)) + for rel := range stripped { + archiveName := rel + if prefix != "" { + archiveName = prefix + "/" + rel + } + item, ok := byArchiveName[archiveName] + if !ok { + return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid) + } + out[rel] = item + } + return out, nil } func skillBundleFromFiles(archive []byte, files map[string][]byte) (*SkillBundle, error) { diff --git a/internal/application/service/tenant_skill_bundle_test.go b/internal/application/service/tenant_skill_bundle_test.go index a31a1a9a..27ac13f4 100644 --- a/internal/application/service/tenant_skill_bundle_test.go +++ b/internal/application/service/tenant_skill_bundle_test.go @@ -333,3 +333,24 @@ Use scripts/extract.py to pull text out of a PDF. require.Equal(t, a.SHA256, b.SHA256) }) } + +func TestListSkillZipFilesDoesNotInflateBodies(t *testing.T) { + data := zipBundle(t, map[string]string{ + "pdf-tools/SKILL.md": validSkillMD, + "pdf-tools/scripts/extract.py": "print('hi')\n", + }) + + files, err := listSkillZipFiles(data) + require.NoError(t, err) + require.Equal(t, []SkillFileEntry{ + {Path: "SKILL.md", Size: int64(len(validSkillMD))}, + {Path: "scripts/extract.py", Size: int64(len("print('hi')\n"))}, + }, files) + + body, err := readSkillZipFile(data, "scripts/extract.py") + require.NoError(t, err) + require.Equal(t, []byte("print('hi')\n"), body) + + _, err = readSkillZipFile(data, "missing.txt") + require.ErrorIs(t, err, errSkillFileMissing) +} diff --git a/internal/application/service/tenant_skill_files.go b/internal/application/service/tenant_skill_files.go index 3341a791..b564cbc2 100644 --- a/internal/application/service/tenant_skill_files.go +++ b/internal/application/service/tenant_skill_files.go @@ -4,14 +4,16 @@ import ( "bytes" "context" "encoding/base64" + "errors" "fmt" "io" "path" - "sort" "strings" + "sync" "unicode/utf8" apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/types" ) // skillFileTextLimit is how much of a text file the admin browser is given. @@ -26,6 +28,12 @@ const ( skillFileEncodingUTF8 = "utf-8" skillFileEncodingBase64 = "base64" skillFileEncodingBinary = "binary" + + // The settings drawer lists the tree then immediately opens SKILL.md, and + // every later click is another read of the same zip. A handful of recent + // archives covers that without holding a 256 MiB upload in RAM. + skillBundleArchiveCacheSlots = 8 + skillBundleArchiveCacheBytes = 64 << 20 // 64 MiB across cached zips ) // SkillFileEntry is one path in an installed skill's stored archive. @@ -51,20 +59,11 @@ type SkillFileContent struct { func (s *TenantSkillService) ListSkillFiles( ctx context.Context, tenantID uint64, configID, skillID string, ) ([]SkillFileEntry, error) { - files, err := s.skillBundleFiles(ctx, tenantID, configID, skillID) + archive, err := s.skillBundleArchive(ctx, tenantID, configID, skillID) if err != nil { return nil, err } - names := make([]string, 0, len(files)) - for name := range files { - names = append(names, name) - } - sort.Strings(names) - out := make([]SkillFileEntry, 0, len(names)) - for _, name := range names { - out = append(out, SkillFileEntry{Path: name, Size: int64(len(files[name]))}) - } - return out, nil + return listSkillZipFiles(archive) } // ReadSkillFile returns one file from the stored archive. Binary files are @@ -77,20 +76,23 @@ func (s *TenantSkillService) ReadSkillFile( if err != nil { return nil, apperrors.NewBadRequestError(err.Error()) } - files, err := s.skillBundleFiles(ctx, tenantID, configID, skillID) + archive, err := s.skillBundleArchive(ctx, tenantID, configID, skillID) if err != nil { return nil, err } - body, ok := files[clean] - if !ok { - return nil, apperrors.NewNotFoundError("skill file not found") + body, err := readSkillZipFile(archive, clean) + if err != nil { + if errors.Is(err, errSkillFileMissing) { + return nil, apperrors.NewNotFoundError("skill file not found") + } + return nil, err } return projectSkillFileContent(clean, body), nil } -func (s *TenantSkillService) skillBundleFiles( +func (s *TenantSkillService) skillBundleArchive( ctx context.Context, tenantID uint64, configID, skillID string, -) (map[string][]byte, error) { +) ([]byte, error) { skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID) if err != nil { return nil, err @@ -102,6 +104,36 @@ func (s *TenantSkillService) skillBundleFiles( if ref == "" { return nil, apperrors.NewNotFoundError("skill files are not available") } + key := skillBundleCacheKey(tenantID, skill) + if cached := s.cachedSkillBundle(key); cached != nil { + return cached, nil + } + + v, err, _ := s.bundleLoad.Do(key, func() (interface{}, error) { + if cached := s.cachedSkillBundle(key); cached != nil { + return cached, nil + } + archive, err := s.downloadSkillBundle(ctx, tenantID, skill) + if err != nil { + return nil, err + } + s.storeSkillBundle(key, archive) + return archive, nil + }) + if err != nil { + return nil, err + } + archive, ok := v.([]byte) + if !ok { + return nil, fmt.Errorf("download bundle of skill %s: unexpected cache result", skill.Name) + } + return archive, nil +} + +func (s *TenantSkillService) downloadSkillBundle( + ctx context.Context, tenantID uint64, skill *types.TenantSkillEntity, +) ([]byte, error) { + ref := strings.TrimSpace(skill.BundleRef) fs, err := s.fileServiceForTenant(ctx, tenantID) if err != nil { return nil, err @@ -118,11 +150,90 @@ func (s *TenantSkillService) skillBundleFiles( if len(archive) > maxSkillBundleTotalBytes { return nil, fmt.Errorf("skill bundle %s is larger than the upload limit", ref) } - bundle, err := ParseSkillBundle(archive) - if err != nil { - return nil, err + return archive, nil +} + +func skillBundleCacheKey(tenantID uint64, skill *types.TenantSkillEntity) string { + id := strings.TrimSpace(skill.BundleSHA256) + if id == "" { + id = strings.TrimSpace(skill.BundleRef) } - return bundle.Files, nil + return fmt.Sprintf("%d:%s", tenantID, id) +} + +func (s *TenantSkillService) cachedSkillBundle(key string) []byte { + if s == nil || s.bundleCache == nil { + return nil + } + return s.bundleCache.get(key) +} + +func (s *TenantSkillService) storeSkillBundle(key string, archive []byte) { + if s == nil || s.bundleCache == nil { + return + } + s.bundleCache.put(key, archive) +} + +type skillBundleArchiveCache struct { + mu sync.Mutex + entries []cachedSkillArchive +} + +type cachedSkillArchive struct { + key string + archive []byte +} + +func newSkillBundleArchiveCache() *skillBundleArchiveCache { + return &skillBundleArchiveCache{} +} + +func (c *skillBundleArchiveCache) get(key string) []byte { + if c == nil || key == "" { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + for i, entry := range c.entries { + if entry.key != key { + continue + } + c.entries = append(c.entries[:i], c.entries[i+1:]...) + c.entries = append([]cachedSkillArchive{entry}, c.entries...) + return entry.archive + } + return nil +} + +func (c *skillBundleArchiveCache) put(key string, archive []byte) { + if c == nil || key == "" { + return + } + if len(archive) > skillBundleArchiveCacheBytes { + return + } + c.mu.Lock() + defer c.mu.Unlock() + for i, entry := range c.entries { + if entry.key != key { + continue + } + c.entries = append(c.entries[:i], c.entries[i+1:]...) + break + } + c.entries = append([]cachedSkillArchive{{key: key, archive: archive}}, c.entries...) + for len(c.entries) > skillBundleArchiveCacheSlots || c.cachedBytes() > skillBundleArchiveCacheBytes { + c.entries = c.entries[:len(c.entries)-1] + } +} + +func (c *skillBundleArchiveCache) cachedBytes() int { + total := 0 + for _, entry := range c.entries { + total += len(entry.archive) + } + return total } // safeSkillFilePath normalises a caller-supplied relative path and refuses diff --git a/internal/application/service/tenant_skill_files_test.go b/internal/application/service/tenant_skill_files_test.go index f3290092..386b8c86 100644 --- a/internal/application/service/tenant_skill_files_test.go +++ b/internal/application/service/tenant_skill_files_test.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/base64" + "sync" "testing" "github.com/stretchr/testify/require" @@ -56,6 +57,71 @@ func TestReadSkillFileReturnsTextContent(t *testing.T) { require.False(t, file.Binary) } +func TestListAndReadSkillFilesDownloadTheBundleOnce(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + files, err := fx.svc.ListSkillFiles(context.Background(), 7, "cfg-1", "sk-1") + require.NoError(t, err) + require.NotEmpty(t, files) + + _, err = fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "SKILL.md") + require.NoError(t, err) + _, err = fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "scripts/extract.py") + require.NoError(t, err) + + require.Equal(t, int32(1), fx.getFileCalls.Load()) +} + +func TestListAndReadSkillFilesCoalesceConcurrentDownloads(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + var wg sync.WaitGroup + errCh := make(chan error, 3) + wg.Add(3) + go func() { + defer wg.Done() + _, err := fx.svc.ListSkillFiles(context.Background(), 7, "cfg-1", "sk-1") + errCh <- err + }() + go func() { + defer wg.Done() + _, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "SKILL.md") + errCh <- err + }() + go func() { + defer wg.Done() + _, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "scripts/extract.py") + errCh <- err + }() + wg.Wait() + close(errCh) + for err := range errCh { + require.NoError(t, err) + } + require.Equal(t, int32(1), fx.getFileCalls.Load()) +} + +func TestListSkillFilesStripsAWrapDirectory(t *testing.T) { + fx := newInstallFixture(t) + fx.storeSkillBundle(t, "sk-1", zipBundle(t, map[string]string{ + "pdf-tools/SKILL.md": validSkillMD, + "pdf-tools/scripts/extract.py": "print('hi')\n", + })) + + files, err := fx.svc.ListSkillFiles(context.Background(), 7, "cfg-1", "sk-1") + require.NoError(t, err) + require.Equal(t, []SkillFileEntry{ + {Path: "SKILL.md", Size: int64(len(validSkillMD))}, + {Path: "scripts/extract.py", Size: int64(len("print('hi')\n"))}, + }, files) + + file, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "scripts/extract.py") + require.NoError(t, err) + require.Equal(t, "print('hi')\n", file.Content) +} + func TestReadSkillFileRejectsPathTraversal(t *testing.T) { fx := newInstallFixture(t) fx.seedStoredSkillBundle(t) diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index bd4b8e37..93fe9fb1 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -14,6 +14,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "testing" "time" @@ -1208,6 +1209,7 @@ type installFixture struct { // storedBundles is what GetFile serves back, keyed by the SaveBytes // reference, so ListSkillFiles / ReadSkillFile can open a stored archive. storedBundles map[string][]byte + getFileCalls atomic.Int32 } func newInstallFixture(t *testing.T) *installFixture { @@ -2228,6 +2230,7 @@ func (s installFileService) SaveBytes(_ context.Context, data []byte, _ uint64, } func (s installFileService) GetFile(_ context.Context, ref string) (io.ReadCloser, error) { if s.fx != nil { + s.fx.getFileCalls.Add(1) if data, ok := s.fx.storedBundles[ref]; ok { return io.NopCloser(bytes.NewReader(data)), nil } diff --git a/internal/application/service/tenant_skill_service.go b/internal/application/service/tenant_skill_service.go index 20dc5bd0..247775cc 100644 --- a/internal/application/service/tenant_skill_service.go +++ b/internal/application/service/tenant_skill_service.go @@ -9,6 +9,7 @@ import ( "github.com/redis/go-redis/v9" "github.com/robfig/cron/v3" + "golang.org/x/sync/singleflight" "github.com/Tencent/WeKnora/internal/application/repository" "github.com/Tencent/WeKnora/internal/common/redislock" @@ -99,6 +100,11 @@ type TenantSkillService struct { // process; multi-replica deployments require Redis for cross-process safety. localLocks *keyedMutex + // bundleCache keeps recently downloaded skill zips so the admin file + // browser (list + N reads) does not hit object storage on every click. + bundleCache *skillBundleArchiveCache + bundleLoad singleflight.Group + cron *cron.Cron cronMu sync.Mutex started bool @@ -139,6 +145,7 @@ func NewTenantSkillService( snapshotRetention: skillSnapshotRetention, installHeartbeat: skillInstallHeartbeatInterval, localLocks: newKeyedMutex(), + bundleCache: newSkillBundleArchiveCache(), cron: cron.New(cron.WithSeconds(), cron.WithChain( cron.Recover(cron.DefaultLogger), )),