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