forked from gomods/athens
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.go
57 lines (51 loc) · 1.09 KB
/
mem.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
package mem
import (
"context"
"fmt"
"sync"
"time"
"github.com/gomods/athens/pkg/errors"
"github.com/gomods/athens/pkg/index"
)
// New returns a new in-memory indexer.
func New() index.Indexer {
return &indexer{}
}
type indexer struct {
mu sync.RWMutex
lines []*index.Line
}
func (i *indexer) Index(ctx context.Context, mod, ver string) error {
const op errors.Op = "mem.Index"
i.mu.Lock()
defer i.mu.Unlock()
for _, l := range i.lines {
if l.Path == mod && l.Version == ver {
return errors.E(op, fmt.Sprintf("%s@%s already indexed", mod, ver), errors.KindAlreadyExists)
}
}
i.lines = append(i.lines, &index.Line{
Path: mod,
Version: ver,
Timestamp: time.Now(),
})
return nil
}
func (i *indexer) Lines(ctx context.Context, since time.Time, limit int) ([]*index.Line, error) {
const op errors.Op = "mem.Lines"
lines := []*index.Line{}
var count int
i.mu.RLock()
defer i.mu.RUnlock()
for _, line := range i.lines {
if count >= limit {
break
}
if since.After(line.Timestamp) {
continue
}
lines = append(lines, line)
count++
}
return lines, nil
}