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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
|
package cache
import (
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"sync"
"github.com/MichaelMure/git-bug/entities/bug"
"github.com/MichaelMure/git-bug/entities/identity"
"github.com/MichaelMure/git-bug/entity"
"github.com/MichaelMure/git-bug/repository"
"github.com/MichaelMure/git-bug/util/multierr"
"github.com/MichaelMure/git-bug/util/process"
)
// 1: original format
// 2: added cache for identities with a reference in the bug cache
// 3: no more legacy identity
// 4: entities make their IDs from data, not git commit
const formatVersion = 4
// The maximum number of bugs loaded in memory. After that, eviction will be done.
const defaultMaxLoadedBugs = 1000
var _ repository.RepoCommon = &RepoCache{}
var _ repository.RepoConfig = &RepoCache{}
var _ repository.RepoKeyring = &RepoCache{}
type cacheMgmt interface {
Typename() string
Load() error
Write() error
Build() error
Close() error
}
// RepoCache is a cache for a Repository. This cache has multiple functions:
//
// 1. After being loaded, a Bug is kept in memory in the cache, allowing for fast
// access later.
// 2. The cache maintain in memory and on disk a pre-digested excerpt for each bug,
// allowing for fast querying the whole set of bugs without having to load
// them individually.
// 3. The cache guarantee that a single instance of a Bug is loaded at once, avoiding
// loss of data that we could have with multiple copies in the same process.
// 4. The same way, the cache maintain in memory a single copy of the loaded identities.
//
// The cache also protect the on-disk data by locking the git repository for its
// own usage, by writing a lock file. Of course, normal git operations are not
// affected, only git-bug related one.
type RepoCache struct {
// the underlying repo
repo repository.ClockedRepo
// the name of the repository, as defined in the MultiRepoCache
name string
// resolvers for all known entities
resolvers entity.Resolvers
bugs *RepoCacheBug
identities *RepoCacheIdentity
subcaches []cacheMgmt
// the user identity's id, if known
userIdentityId entity.Id
}
func NewRepoCache(r repository.ClockedRepo) (*RepoCache, chan BuildEvent, error) {
return NewNamedRepoCache(r, "")
}
func NewNamedRepoCache(r repository.ClockedRepo, name string) (*RepoCache, chan BuildEvent, error) {
c := &RepoCache{
repo: r,
name: name,
}
bugs := NewSubCache[*BugExcerpt, *BugCache, bug.Interface](r,
c.getResolvers, c.GetUserIdentity,
"bug", "bugs",
formatVersion, defaultMaxLoadedBugs)
c.subcaches = append(c.subcaches, bugs)
c.bugs = &RepoCacheBug{SubCache: *bugs}
c.resolvers = entity.Resolvers{
&IdentityCache{}: entity.ResolverFunc((func(id entity.Id) (entity.Interface, error)(c.identities.Resolve)),
&BugCache{}: c.bugs,
}
err := c.lock()
if err != nil {
return &RepoCache{}, nil, err
}
err = c.load()
if err == nil {
return c, nil, nil
}
// Cache is either missing, broken or outdated. Rebuilding.
err = c.buildCache()
if err != nil {
return nil, err
}
return c, c.write()
}
// Bugs gives access to the Bug entities
func (c *RepoCache) Bugs() *RepoCacheBug {
return c.bugs
}
// Identities gives access to the Identity entities
func (c *RepoCache) Identities() *RepoCacheIdentity {
return c.identities
}
func (c *RepoCache) getResolvers() entity.Resolvers {
return c.resolvers
}
// setCacheSize change the maximum number of loaded bugs
func (c *RepoCache) setCacheSize(size int) {
c.maxLoadedBugs = size
c.evictIfNeeded()
}
// load will try to read from the disk all the cache files
func (c *RepoCache) load() error {
var errWait multierr.ErrWaitGroup
for _, mgmt := range c.subcaches {
errWait.Go(mgmt.Load)
}
return errWait.Wait()
}
// write will serialize on disk all the cache files
func (c *RepoCache) write() error {
var errWait multierr.ErrWaitGroup
for _, mgmt := range c.subcaches {
errWait.Go(mgmt.Write)
}
return errWait.Wait()
}
func (c *RepoCache) lock() error {
err := repoIsAvailable(c.repo)
if err != nil {
return err
}
f, err := c.repo.LocalStorage().Create(lockfile)
if err != nil {
return err
}
pid := fmt.Sprintf("%d", os.Getpid())
_, err = f.Write([]byte(pid))
if err != nil {
return err
}
return f.Close()
}
func (c *RepoCache) Close() error {
var errWait multierr.ErrWaitGroup
for _, mgmt := range c.subcaches {
errWait.Go(mgmt.Close)
}
err := errWait.Wait()
if err != nil {
return err
}
err = c.repo.Close()
if err != nil {
return err
}
return c.repo.LocalStorage().Remove(lockfile)
}
type BuildEventType int
const (
_ BuildEventType = iota
BuildEventStarted
BuildEventFinished
)
type BuildEvent struct {
Typename string
Event BuildEventType
Err error
}
func (c *RepoCache) buildCache() chan BuildEvent {
out := make(chan BuildEvent)
go func() {
defer close(out)
var wg sync.WaitGroup
for _, subcache := range c.subcaches {
wg.Add(1)
go func(subcache cacheMgmt) {
defer wg.Done()
out <- BuildEvent{
Typename: subcache.Typename(),
Event: BuildEventStarted,
}
err := subcache.Build()
if err != nil {
out <- BuildEvent{
Typename: subcache.Typename(),
Err: err,
}
return
}
out <- BuildEvent{
Typename: subcache.Typename(),
Event: BuildEventFinished,
}
}(subcache)
}
wg.Wait()
}()
return out
_, _ = fmt.Fprintf(os.Stderr, "Building identity cache... ")
c.identitiesExcerpts = make(map[entity.Id]*IdentityExcerpt)
allIdentities := identity.ReadAllLocal(c.repo)
for i := range allIdentities {
if i.Err != nil {
return i.Err
}
c.identitiesExcerpts[i.Identity.Id()] = NewIdentityExcerpt(i.Identity)
}
_, _ = fmt.Fprintln(os.Stderr, "Done.")
_, _ = fmt.Fprintf(os.Stderr, "Building bug cache... ")
c.bugExcerpts = make(map[entity.Id]*BugExcerpt)
allBugs := bug.ReadAllWithResolver(c.repo, c.resolvers)
// wipe the index just to be sure
err := c.repo.ClearBleveIndex("bug")
if err != nil {
return err
}
for b := range allBugs {
if b.Err != nil {
return b.Err
}
snap := b.Bug.Compile()
c.bugExcerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, snap)
if err := c.addBugToSearchIndex(snap); err != nil {
return err
}
}
_, _ = fmt.Fprintln(os.Stderr, "Done.")
return nil
}
// repoIsAvailable check is the given repository is locked by a Cache.
// Note: this is a smart function that will clean the lock file if the
// corresponding process is not there anymore.
// If no error is returned, the repo is free to edit.
func repoIsAvailable(repo repository.RepoStorage) error {
// Todo: this leave way for a racey access to the repo between the test
// if the file exist and the actual write. It's probably not a problem in
// practice because using a repository will be done from user interaction
// or in a context where a single instance of git-bug is already guaranteed
// (say, a server with the web UI running). But still, that might be nice to
// have a mutex or something to guard that.
// Todo: this will fail if somehow the filesystem is shared with another
// computer. Should add a configuration that prevent the cleaning of the
// lock file
f, err := repo.LocalStorage().Open(lockfile)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
// lock file already exist
buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
if err != nil {
return err
}
if len(buf) == 10 {
return fmt.Errorf("the lock file should be < 10 bytes")
}
pid, err := strconv.Atoi(string(buf))
if err != nil {
return err
}
if process.IsRunning(pid) {
return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
}
// The lock file is just laying there after a crash, clean it
fmt.Println("A lock file is present but the corresponding process is not, removing it.")
err = f.Close()
if err != nil {
return err
}
err = repo.LocalStorage().Remove(lockfile)
if err != nil {
return err
}
}
return nil
}
|