-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcache.go
105 lines (87 loc) · 2.11 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package gguf_parser
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/gpustack/gguf-parser-go/util/json"
"github.com/gpustack/gguf-parser-go/util/osx"
"github.com/gpustack/gguf-parser-go/util/stringx"
)
var (
ErrGGUFFileCacheDisabled = errors.New("GGUF file cache disabled")
ErrGGUFFileCacheMissed = errors.New("GGUF file cache missed")
ErrGGUFFileCacheCorrupted = errors.New("GGUF file cache corrupted")
)
type GGUFFileCache string
func (c GGUFFileCache) getKeyPath(key string) string {
k := stringx.SumByFNV64a(key)
p := filepath.Join(string(c), k[:1], k)
return p
}
func (c GGUFFileCache) Get(key string, exp time.Duration) (*GGUFFile, error) {
if c == "" {
return nil, ErrGGUFFileCacheDisabled
}
if key == "" {
return nil, ErrGGUFFileCacheMissed
}
p := c.getKeyPath(key)
if !osx.Exists(p, func(stat os.FileInfo) bool {
if !stat.Mode().IsRegular() {
return false
}
return time.Since(stat.ModTime()) < exp
}) {
return nil, ErrGGUFFileCacheMissed
}
var gf GGUFFile
{
bs, err := os.ReadFile(p)
if err != nil {
return nil, fmt.Errorf("GGUF file cache get: %w", err)
}
if err = json.Unmarshal(bs, &gf); err != nil {
return nil, fmt.Errorf("GGUF file cache get: %w", err)
}
}
if len(gf.Header.MetadataKV) == 0 || len(gf.TensorInfos) == 0 {
_ = os.Remove(p)
return nil, ErrGGUFFileCacheCorrupted
}
return &gf, nil
}
func (c GGUFFileCache) Put(key string, gf *GGUFFile) error {
if c == "" {
return ErrGGUFFileCacheDisabled
}
if key == "" || gf == nil {
return nil
}
bs, err := json.Marshal(gf)
if err != nil {
return fmt.Errorf("GGUF file cache put: %w", err)
}
p := c.getKeyPath(key)
if err = osx.WriteFile(p, bs, 0o600); err != nil {
return fmt.Errorf("GGUF file cache put: %w", err)
}
return nil
}
func (c GGUFFileCache) Delete(key string) error {
if c == "" {
return ErrGGUFFileCacheDisabled
}
if key == "" {
return ErrGGUFFileCacheMissed
}
p := c.getKeyPath(key)
if !osx.ExistsFile(p) {
return ErrGGUFFileCacheMissed
}
if err := os.Remove(p); err != nil {
return fmt.Errorf("GGUF file cache delete: %w", err)
}
return nil
}