-
Notifications
You must be signed in to change notification settings - Fork 2
/
mongo.go
215 lines (183 loc) · 5.44 KB
/
mongo.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
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
package mongo
import (
"context"
"errors"
"math"
"time"
"github.com/creativecreature/pulse"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Constants for the collection names.
const (
daily = "daily"
weekly = "weekly"
monthly = "monthly"
yearly = "yearly"
)
type DB struct {
uri string
database string
client *mongo.Client
}
func New(uri, database string) (db *DB, disconnect func()) {
db = &DB{
uri: uri,
database: database,
}
disconnect = db.Connect()
return db, disconnect
}
func (m *DB) Connect() func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.uri))
// We should be able to connect to the database. If we can't there isn't much
// that we are able to do.
if err != nil {
panic(err)
}
m.client = client
return func() {
errDisconnect := client.Disconnect(ctx)
if errDisconnect != nil {
panic(errDisconnect)
}
}
}
func createDateFilter(minDate, maxDate int64) primitive.D {
return bson.D{
{
Key: "$and",
Value: bson.A{
bson.D{{Key: "date", Value: bson.D{{Key: "$gte", Value: minDate}}}},
bson.D{{Key: "date", Value: bson.D{{Key: "$lte", Value: maxDate}}}},
},
},
}
}
func createDateSortOptions() *options.FindOptions {
return options.Find().SetSort(bson.D{{Key: "date", Value: 1}})
}
func dateRange(sessions []pulse.AggregatedSession) (minDate, maxDate int64) {
minDate = math.MaxInt64
maxDate = math.MinInt64
for _, s := range sessions {
minDate, maxDate = min(minDate, s.Date), max(maxDate, s.Date)
}
return minDate, maxDate
}
func (m *DB) getByDateRange(minDate, maxDate int64) (pulse.AggregatedSessions, error) {
filter := createDateFilter(minDate, maxDate)
sortOptions := createDateSortOptions()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cursor, err := m.client.Database(m.database).
Collection(daily).
Find(ctx, filter, sortOptions)
if err != nil {
return pulse.AggregatedSessions{}, err
}
results := make([]pulse.AggregatedSession, 0)
err = cursor.All(context.Background(), &results)
if err != nil {
return pulse.AggregatedSessions{}, err
}
return results, nil
}
func (m *DB) deleteByDateRange(minDate, maxDate int64) error {
filter := createDateFilter(minDate, maxDate)
_, err := m.client.Database(m.database).
Collection(daily).
DeleteMany(context.Background(), filter)
return err
}
func (m *DB) insertAll(collection string, sessions []pulse.AggregatedSession) error {
documents := make([]interface{}, 0)
for _, session := range sessions {
documents = append(documents, session)
}
_, err := m.client.Database(m.database).
Collection(collection).
InsertMany(context.Background(), documents)
return err
}
// Write writes daily coding sessions to a mongodb collection.
func (m *DB) Write(sessions []pulse.AggregatedSession) error {
// We might aggregate sessions from the temp storage several times a day.
// Therefore, we have to fetch any previous sessions for the same timeframe
// and if we have any we'll have to merge them with the new ones.
minDate, maxDate := dateRange(sessions)
previousSessionsForRange, err := m.getByDateRange(minDate, maxDate)
if err != nil {
return err
}
// There were no previous sessions for this range of dates
if len(previousSessionsForRange) == 0 {
return m.insertAll(daily, sessions)
}
// We have already aggregated sessions for this day. We'll have to merge them.
combinedSessions := make(pulse.AggregatedSessions, 0)
combinedSessions = append(combinedSessions, previousSessionsForRange...)
combinedSessions = append(combinedSessions, sessions...)
mergedSessions := combinedSessions.MergeByDay()
// Delete the previously stored sessions for this range
err = m.deleteByDateRange(minDate, maxDate)
if err != nil {
return err
}
// Update this range of sessions with the merged ones
return m.insertAll(daily, mergedSessions)
}
func (m *DB) readAll() (pulse.AggregatedSessions, error) {
sortOptions := createDateSortOptions()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cursor, err := m.client.Database(m.database).
Collection(daily).
Find(ctx, bson.M{}, sortOptions)
if err != nil {
return pulse.AggregatedSessions{}, err
}
results := make([]pulse.AggregatedSession, 0)
err = cursor.All(context.Background(), &results)
if err != nil {
return pulse.AggregatedSessions{}, err
}
return results, nil
}
func (m *DB) deleteCollection(collection string) error {
return m.client.Database(m.database).
Collection(collection).
Drop(context.Background())
}
func (m *DB) Aggregate(timePeriod pulse.Period) error {
dailySessions, err := m.readAll()
if err != nil {
return err
}
sessions, collection := pulse.AggregatedSessions{}, ""
switch tPeriod := timePeriod; tPeriod {
case pulse.Day:
return errors.New("cannot aggregate by day")
case pulse.Week:
sessions = dailySessions.MergeByWeek()
collection = weekly
case pulse.Month:
sessions = dailySessions.MergeByMonth()
collection = monthly
case pulse.Year:
sessions = dailySessions.MergeByYear()
collection = yearly
}
if len(sessions) == 0 {
return errors.New("no sessions to aggregate for the given time period")
}
err = m.deleteCollection(collection)
if err != nil {
return err
}
return m.insertAll(collection, sessions)
}