This repository has been archived by the owner on Mar 24, 2024. It is now read-only.
generated from yandex-praktikum/go-musthave-devops-tpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
93 lines (70 loc) · 1.69 KB
/
memory.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
91
92
93
package storage
import (
"context"
"sync"
"github.com/alkurbatov/metrics-collector/internal/entity"
)
var _ Storage = (*MemStorage)(nil)
// MemStorage implements in-memory metrics storage.
type MemStorage struct {
Data map[string]Record `json:"records"`
sync.RWMutex
}
// NewMemStorage creates new instance of MemStorage.
func NewMemStorage() *MemStorage {
return &MemStorage{
Data: make(map[string]Record),
}
}
// Push records metric data.
func (m *MemStorage) Push(_ context.Context, key string, record Record) error {
m.Lock()
defer m.Unlock()
m.Data[key] = record
return nil
}
// PushBatch records list of metrics data.
func (m *MemStorage) PushBatch(_ context.Context, data map[string]Record) error {
m.Lock()
defer m.Unlock()
for id, record := range data {
m.Data[id] = record
}
return nil
}
// Get returns stored metrics record.
func (m *MemStorage) Get(_ context.Context, key string) (Record, error) {
m.RLock()
defer m.RUnlock()
record, ok := m.Data[key]
if !ok {
return Record{}, entity.ErrMetricNotFound
}
return record, nil
}
// GetAll returns all stored metrics.
func (m *MemStorage) GetAll(_ context.Context) ([]Record, error) {
m.RLock()
defer m.RUnlock()
rv := make([]Record, len(m.Data))
i := 0
for _, v := range m.Data {
rv[i] = v
i++
}
return rv, nil
}
// Close has no effect on in-memory storage.
func (m *MemStorage) Close(_ context.Context) error {
return nil // noop
}
// Snapshot creates independent copy of in-memory storage.
func (m *MemStorage) Snapshot() *MemStorage {
m.RLock()
defer m.RUnlock()
snapshot := make(map[string]Record, len(m.Data))
for k, v := range m.Data {
snapshot[k] = v
}
return &MemStorage{Data: snapshot}
}