-
Notifications
You must be signed in to change notification settings - Fork 10
/
datastore_mongo_events.go
100 lines (81 loc) · 2.27 KB
/
datastore_mongo_events.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
// Copyright 2022 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mongo
import (
"context"
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
mopts "go.mongodb.org/mongo-driver/mongo/options"
mstore "github.com/mendersoftware/go-lib-micro/store/v2"
"github.com/mendersoftware/iot-manager/model"
)
const (
CollNameLog = "log"
KeyEventTs = "event_ts"
KeyEventExpireTs = "expire_ts"
)
var (
eventExpiration int64
ErrFailedToGetEvents = errors.New("failed to get events")
)
func SetEventExpiration(exp int64) {
eventExpiration = exp
}
func (db *DataStoreMongo) GetEvents(
ctx context.Context,
fltr model.EventsFilter,
) ([]model.Event, error) {
var (
err error
results = []model.Event{}
)
collEvents := db.Collection(CollNameLog)
findOpts := mopts.Find().
SetSort(bson.D{{Key: KeyEventTs, Value: -1}}).
SetSkip(fltr.Skip)
if fltr.Limit > 0 {
findOpts.SetLimit(fltr.Limit)
}
cur, err := collEvents.Find(ctx,
mstore.WithTenantID(ctx, bson.D{}),
findOpts,
)
if err != nil {
return nil, errors.Wrap(err, "error executing log collection request")
}
if err = cur.All(ctx, &results); err != nil {
return nil, errors.Wrap(err, "error retrieving log collection results")
}
return results, nil
}
func (db *DataStoreMongo) SaveEvent(
ctx context.Context,
event model.Event,
) error {
now := time.Now()
event.EventTS = now
event.ExpireTS = now.Add(time.Second * time.Duration(eventExpiration))
if event.ID == uuid.Nil {
event.ID = uuid.New()
}
collEvents := db.Collection(CollNameLog)
_, err := collEvents.
InsertOne(ctx, mstore.WithTenantID(ctx, event))
if err != nil {
return errors.Wrapf(err, "failed to store an event %v", event)
}
return nil
}