-
Notifications
You must be signed in to change notification settings - Fork 53
/
cache.go
91 lines (73 loc) · 2.29 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
package patch
import (
"fmt"
"io"
"github.com/gabstv/go-bsdiff/pkg/bsdiff"
"github.com/gabstv/go-bsdiff/pkg/bspatch"
lru "github.com/hashicorp/golang-lru"
"github.com/klauspost/compress/zstd"
"google.golang.org/grpc/encoding"
"github.com/rancher/opni/pkg/util"
)
type ZstdCompressor struct{}
func (c ZstdCompressor) Compress(w io.Writer) (io.WriteCloser, error) {
return zstd.NewWriter(w)
}
func (c ZstdCompressor) Decompress(r io.Reader) (io.Reader, error) {
return zstd.NewReader(r)
}
func (c ZstdCompressor) Name() string {
return "zstd"
}
func init() {
encoding.RegisterCompressor(ZstdCompressor{})
}
type PatchCache interface {
Get(pluginName, oldRevision, newRevision string) ([]byte, error)
Put(pluginName, oldRevision, newRevision string, patch []byte) error
Key(pluginName, oldRevision, newRevision string) string
}
type InMemoryCache struct {
cache *lru.Cache
}
func (c *InMemoryCache) Key(pluginName, oldRevision, newRevision string) string {
return fmt.Sprintf("%s-%s-to-%s", pluginName, oldRevision, newRevision)
}
func NewInMemoryCache() PatchCache {
return &InMemoryCache{
cache: util.Must(lru.New(32)),
}
}
func (c *InMemoryCache) Get(pluginName, oldRevision, newRevision string) ([]byte, error) {
if v, ok := c.cache.Get(c.Key(pluginName, oldRevision, newRevision)); ok {
return v.([]byte), nil
}
return nil, fmt.Errorf("not found")
}
func (c *InMemoryCache) Put(pluginName, oldRevision, newRevision string, patch []byte) error {
c.cache.Add(c.Key(pluginName, oldRevision, newRevision), patch)
return nil
}
// writes in place the result to the patchf io.Writer
func GenerateIOStreamPatch(oldBin io.Reader, newBin io.Reader, patchf io.Writer) error {
return bsdiff.Reader(oldBin, newBin, patchf)
}
// writes in place the result to the newBin io.Writer
func ApplyIOStreamPatch(oldBin io.Reader, patchf io.Reader, newBin io.Writer) error {
return bspatch.Reader(oldBin, newBin, patchf)
}
func GeneratePatch(outdatedBytes, newestBytes []byte) ([]byte, error) {
// BSDIFF4 patch
patch, err := bsdiff.Bytes(outdatedBytes, newestBytes)
if err != nil {
return []byte{}, err
}
return patch, nil
}
func ApplyPatch(outdatedBytes, patch []byte) ([]byte, error) {
newBytes, err := bspatch.Bytes(outdatedBytes, patch)
if err != nil {
return []byte{}, err
}
return newBytes, nil
}