-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_log.go
92 lines (73 loc) · 1.67 KB
/
request_log.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
package mongodata
import (
"context"
"errors"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type RequestLog struct {
collection *Collection[request]
}
type RequestID string
func (i RequestID) String() string { return string(i) }
type request struct {
ID RequestID `bson:"_id"`
Time time.Time `bson:"time"`
}
func NewRequestLog(
collection *mongo.Collection,
) *RequestLog {
return &RequestLog{
collection: NewCollection[request](collection),
}
}
func (r *RequestLog) Insert(ctx context.Context, requestID string, t time.Time) error {
return r.collection.Insert(ctx, requestID, &request{
ID: RequestID(requestID),
Time: t,
})
}
func (r *RequestLog) Purge(ctx context.Context, t time.Time) error {
f := bson.M{
"time": bson.M{
"lt": t}}
_, err := r.collection.collection.DeleteMany(ctx, f)
return err
}
func (r *RequestLog) Test(ctx context.Context, requestID string) (bool, error) {
_, err := r.collection.Get(ctx, requestID)
if errors.Is(err, ErrNotFound) {
return true, nil
}
return false, err
}
func (r *RequestLog) Transaction(ctx context.Context, requestID string, t time.Time, tx func() error) (err error) {
ok, err := r.Test(ctx, requestID)
if err != nil {
return err
}
if !ok {
return nil
}
session, err := r.collection.collection.Database().Client().StartSession()
if err != nil {
return err
}
if err := session.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
err = errors.Join(err, session.AbortTransaction(ctx))
} else {
err = session.CommitTransaction(ctx)
}
}()
err = tx()
if err != nil {
return err
}
err = r.Insert(ctx, requestID, t)
return
}