1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16
17 package server
18
19 import (
20 "errors"
21 "fmt"
22
23 "perkeep.org/internal/lru"
24 "perkeep.org/pkg/blob"
25 "perkeep.org/pkg/sorted"
26 )
27
28 const memLRUSize = 1024
29
30 var errCacheMiss = errors.New("not in cache")
31
32
33
34
35
36
37
38
39
40 type ThumbMeta struct {
41 mem *lru.Cache
42 kv sorted.KeyValue
43 }
44
45
46
47
48 func NewThumbMeta(kv sorted.KeyValue) *ThumbMeta {
49 return &ThumbMeta{
50 mem: lru.New(memLRUSize),
51 kv: kv,
52 }
53 }
54
55 func (m *ThumbMeta) Get(key string) (blob.Ref, error) {
56 var br blob.Ref
57 if v, ok := m.mem.Get(key); ok {
58 return v.(blob.Ref), nil
59 }
60 if m.kv != nil {
61 v, err := m.kv.Get(key)
62 if err == sorted.ErrNotFound {
63 return br, errCacheMiss
64 }
65 if err != nil {
66 return br, err
67 }
68 br, ok := blob.Parse(v)
69 if !ok {
70 return br, fmt.Errorf("Invalid blobref %q found for key %q in thumbnail mea", v, key)
71 }
72 m.mem.Add(key, br)
73 return br, nil
74 }
75 return br, errCacheMiss
76 }
77
78 func (m *ThumbMeta) Put(key string, br blob.Ref) error {
79 m.mem.Add(key, br)
80 if m.kv != nil {
81 return m.kv.Set(key, br.String())
82 }
83 return nil
84 }