-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta.go
93 lines (71 loc) · 1.86 KB
/
meta.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
package filecache
import (
"bytes"
"context"
"fmt"
"os"
"time"
jsoniter "github.com/json-iterator/go"
)
const (
metaSuffix = "--meta"
)
func saveMeta(ctx context.Context, meta *meta, target *os.File) error {
json := jsoniter.ConfigFastest
data, err := json.Marshal(meta)
if err != nil {
return fmt.Errorf("failed to marshal meta for key %s: %w", meta.Key, err)
}
if _, err := copyWithCtx(ctx, target, bytes.NewReader(data)); err != nil {
return fmt.Errorf("failed to save meta for key %s: %w", meta.Key, err)
}
return nil
}
func readMeta(key string, path string) (*meta, error) {
json := jsoniter.ConfigFastest
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read meta file for key %s: %w", key, err)
}
var meta *meta
if err := json.Unmarshal(data, &meta); err != nil {
return nil, fmt.Errorf("failed to unmarshal meta for key %s: %w", key, err)
}
return meta, nil
}
func newMeta(key string, options *ItemOptions, defaultTTL time.Duration) *meta {
ttl := defaultTTL
if options.TTL != 0 {
ttl = options.TTL
}
return &meta{
Key: key,
CreatedAt: time.Now(),
Name: options.Name,
TTL: ttl,
Fields: options.Fields,
}
}
func metaToOptions(meta *meta) *ItemOptions {
return &ItemOptions{
Name: meta.Name,
TTL: meta.TTL,
Fields: meta.Fields,
}
}
// meta is a metadata stored with a cache item file.
type meta struct {
// Key is a unique cache item key.
Key string `json:"k"`
// CreatedAt is a time when cache item was created.
CreatedAt time.Time `json:"c"`
// Name is a human-readable item name.
Name string `json:"n,omitempty"`
// TTL is an item's time-to-live value.
TTL time.Duration `json:"t,omitempty"`
// Fields is a map of any other metadata fields.
Fields Values `json:"f,omitempty"`
}
func (m *meta) isExpired() bool {
return isExpired(m.CreatedAt, m.TTL)
}