-
Notifications
You must be signed in to change notification settings - Fork 0
/
memrepo.go
90 lines (81 loc) · 1.78 KB
/
memrepo.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
package provider
import (
"errors"
"sync"
pb "github.com/andrescosta/jobico/internal/api/types"
)
type MemRepo struct {
mutex *sync.RWMutex
mapFile map[string]map[string][]byte
mapMeta map[string]map[string]*Metadata
}
func NewMemRepo() *MemRepo {
return &MemRepo{
mapFile: make(map[string]map[string][]byte),
mapMeta: make(map[string]map[string]*Metadata),
mutex: &sync.RWMutex{},
}
}
func (m *MemRepo) Add(tenant string, name string, fileType int32, bytes []byte) error {
m.mutex.Lock()
defer m.mutex.Unlock()
td, ok := m.mapFile[tenant]
if !ok {
td = make(map[string][]byte)
m.mapFile[tenant] = td
}
_, ok = td[name]
if !ok {
td[name] = bytes
}
tm, ok := m.mapMeta[tenant]
if !ok {
tm = make(map[string]*Metadata)
m.mapMeta[tenant] = tm
}
_, ok = tm[name]
if !ok {
tm[name] = &Metadata{FileType: fileType}
}
return nil
}
var ErrNotFound = errors.New("not found")
func (m *MemRepo) File(tenant string, name string) ([]byte, error) {
m.mutex.RLock()
defer m.mutex.RUnlock()
td, ok := m.mapFile[tenant]
if !ok {
return nil, ErrNotFound
}
tf, ok := td[name]
if !ok {
return nil, ErrNotFound
}
return tf, nil
}
func (m *MemRepo) GetMetadataForFile(tenant string, name string) (*Metadata, error) {
m.mutex.RLock()
defer m.mutex.RUnlock()
td, ok := m.mapMeta[tenant]
if !ok {
return nil, ErrNotFound
}
tm, ok := td[name]
if !ok {
return nil, ErrNotFound
}
return tm, nil
}
func (m *MemRepo) Files() ([]*pb.TenantFiles, error) {
m.mutex.RLock()
defer m.mutex.RUnlock()
ts := make([]*pb.TenantFiles, 0)
for kt, vf := range m.mapMeta {
fs := make([]*pb.File, 0)
for kf, vm := range vf {
fs = append(fs, &pb.File{Name: kf, Type: pb.File_FileType(vm.FileType)})
}
ts = append(ts, &pb.TenantFiles{Tenant: kt, Files: fs})
}
return ts, nil
}