1package cache
2
3import (
4 "fmt"
5 "io"
6 "io/ioutil"
7 "os"
8 "strconv"
9 "sync"
10
11 "github.com/MichaelMure/git-bug/entities/bug"
12 "github.com/MichaelMure/git-bug/entities/identity"
13 "github.com/MichaelMure/git-bug/entity"
14 "github.com/MichaelMure/git-bug/repository"
15 "github.com/MichaelMure/git-bug/util/process"
16)
17
18// 1: original format
19// 2: added cache for identities with a reference in the bug cache
20// 3: no more legacy identity
21// 4: entities make their IDs from data, not git commit
22const formatVersion = 4
23
24// The maximum number of bugs loaded in memory. After that, eviction will be done.
25const defaultMaxLoadedBugs = 1000
26
27var _ repository.RepoCommon = &RepoCache{}
28var _ repository.RepoConfig = &RepoCache{}
29var _ repository.RepoKeyring = &RepoCache{}
30
31// RepoCache is a cache for a Repository. This cache has multiple functions:
32//
33// 1. After being loaded, a Bug is kept in memory in the cache, allowing for fast
34// access later.
35// 2. The cache maintain in memory and on disk a pre-digested excerpt for each bug,
36// allowing for fast querying the whole set of bugs without having to load
37// them individually.
38// 3. The cache guarantee that a single instance of a Bug is loaded at once, avoiding
39// loss of data that we could have with multiple copies in the same process.
40// 4. The same way, the cache maintain in memory a single copy of the loaded identities.
41//
42// The cache also protect the on-disk data by locking the git repository for its
43// own usage, by writing a lock file. Of course, normal git operations are not
44// affected, only git-bug related one.
45type RepoCache struct {
46 // the underlying repo
47 repo repository.ClockedRepo
48
49 // the name of the repository, as defined in the MultiRepoCache
50 name string
51
52 // resolvers for all known entities
53 resolvers entity.Resolvers
54
55 // maximum number of loaded bugs
56 maxLoadedBugs int
57
58 muBug sync.RWMutex
59 // excerpt of bugs data for all bugs
60 bugExcerpts map[entity.Id]*BugExcerpt
61 // bug loaded in memory
62 bugs map[entity.Id]*BugCache
63 // loadedBugs is an LRU cache that records which bugs the cache has loaded in
64 loadedBugs *LRUIdCache
65
66 muIdentity sync.RWMutex
67 // excerpt of identities data for all identities
68 identitiesExcerpts map[entity.Id]*IdentityExcerpt
69 // identities loaded in memory
70 identities map[entity.Id]*IdentityCache
71
72 // the user identity's id, if known
73 userIdentityId entity.Id
74}
75
76func NewRepoCache(r repository.ClockedRepo) (*RepoCache, error) {
77 return NewNamedRepoCache(r, "")
78}
79
80func NewNamedRepoCache(r repository.ClockedRepo, name string) (*RepoCache, error) {
81 c := &RepoCache{
82 repo: r,
83 name: name,
84 maxLoadedBugs: defaultMaxLoadedBugs,
85 bugs: make(map[entity.Id]*BugCache),
86 loadedBugs: NewLRUIdCache(),
87 identities: make(map[entity.Id]*IdentityCache),
88 }
89
90 c.resolvers = makeResolvers(c)
91
92 err := c.lock()
93 if err != nil {
94 return &RepoCache{}, err
95 }
96
97 err = c.load()
98 if err == nil {
99 return c, nil
100 }
101
102 // Cache is either missing, broken or outdated. Rebuilding.
103 err = c.buildCache()
104 if err != nil {
105 return nil, err
106 }
107
108 return c, c.write()
109}
110
111// setCacheSize change the maximum number of loaded bugs
112func (c *RepoCache) setCacheSize(size int) {
113 c.maxLoadedBugs = size
114 c.evictIfNeeded()
115}
116
117// load will try to read from the disk all the cache files
118func (c *RepoCache) load() error {
119 err := c.loadBugCache()
120 if err != nil {
121 return err
122 }
123
124 return c.loadIdentityCache()
125}
126
127// write will serialize on disk all the cache files
128func (c *RepoCache) write() error {
129 err := c.writeBugCache()
130 if err != nil {
131 return err
132 }
133 return c.writeIdentityCache()
134}
135
136func (c *RepoCache) lock() error {
137 err := repoIsAvailable(c.repo)
138 if err != nil {
139 return err
140 }
141
142 f, err := c.repo.LocalStorage().Create(lockfile)
143 if err != nil {
144 return err
145 }
146
147 pid := fmt.Sprintf("%d", os.Getpid())
148 _, err = f.Write([]byte(pid))
149 if err != nil {
150 return err
151 }
152
153 return f.Close()
154}
155
156func (c *RepoCache) Close() error {
157 c.muBug.Lock()
158 defer c.muBug.Unlock()
159 c.muIdentity.Lock()
160 defer c.muIdentity.Unlock()
161
162 c.identities = make(map[entity.Id]*IdentityCache)
163 c.identitiesExcerpts = nil
164 c.bugs = make(map[entity.Id]*BugCache)
165 c.bugExcerpts = nil
166
167 err := c.repo.Close()
168 if err != nil {
169 return err
170 }
171
172 return c.repo.LocalStorage().Remove(lockfile)
173}
174
175func (c *RepoCache) buildCache() error {
176 _, _ = fmt.Fprintf(os.Stderr, "Building identity cache... ")
177
178 c.identitiesExcerpts = make(map[entity.Id]*IdentityExcerpt)
179
180 allIdentities := identity.ReadAllLocal(c.repo)
181
182 for i := range allIdentities {
183 if i.Err != nil {
184 return i.Err
185 }
186
187 c.identitiesExcerpts[i.Identity.Id()] = NewIdentityExcerpt(i.Identity)
188 }
189
190 _, _ = fmt.Fprintln(os.Stderr, "Done.")
191
192 _, _ = fmt.Fprintf(os.Stderr, "Building bug cache... ")
193
194 c.bugExcerpts = make(map[entity.Id]*BugExcerpt)
195
196 allBugs := bug.ReadAllWithResolver(c.repo, c.resolvers)
197
198 // wipe the index just to be sure
199 err := c.repo.ClearBleveIndex("bug")
200 if err != nil {
201 return err
202 }
203
204 for b := range allBugs {
205 if b.Err != nil {
206 return b.Err
207 }
208
209 snap := b.Bug.Compile()
210 c.bugExcerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, snap)
211
212 if err := c.addBugToSearchIndex(snap); err != nil {
213 return err
214 }
215 }
216
217 _, _ = fmt.Fprintln(os.Stderr, "Done.")
218
219 return nil
220}
221
222// repoIsAvailable check is the given repository is locked by a Cache.
223// Note: this is a smart function that will clean the lock file if the
224// corresponding process is not there anymore.
225// If no error is returned, the repo is free to edit.
226func repoIsAvailable(repo repository.RepoStorage) error {
227 // Todo: this leave way for a racey access to the repo between the test
228 // if the file exist and the actual write. It's probably not a problem in
229 // practice because using a repository will be done from user interaction
230 // or in a context where a single instance of git-bug is already guaranteed
231 // (say, a server with the web UI running). But still, that might be nice to
232 // have a mutex or something to guard that.
233
234 // Todo: this will fail if somehow the filesystem is shared with another
235 // computer. Should add a configuration that prevent the cleaning of the
236 // lock file
237
238 f, err := repo.LocalStorage().Open(lockfile)
239 if err != nil && !os.IsNotExist(err) {
240 return err
241 }
242
243 if err == nil {
244 // lock file already exist
245 buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
246 if err != nil {
247 return err
248 }
249 if len(buf) == 10 {
250 return fmt.Errorf("the lock file should be < 10 bytes")
251 }
252
253 pid, err := strconv.Atoi(string(buf))
254 if err != nil {
255 return err
256 }
257
258 if process.IsRunning(pid) {
259 return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
260 }
261
262 // The lock file is just laying there after a crash, clean it
263
264 fmt.Println("A lock file is present but the corresponding process is not, removing it.")
265 err = f.Close()
266 if err != nil {
267 return err
268 }
269
270 err = repo.LocalStorage().Remove(lockfile)
271 if err != nil {
272 return err
273 }
274 }
275
276 return nil
277}