-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
200 lines (163 loc) · 5.01 KB
/
store.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
package short
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
type Store interface {
// Insert adds a record to the storage.
// url, id and override are passed via an insertConfig struct.
Insert(ctx context.Context, ic *insertConfig) error
// GetUrl returns the url given an id.
GetUrl(ctx context.Context, id string) (string, error)
}
type insertConfig struct {
url string
id string
override bool
expiration *time.Time
}
type store struct {
name string
collection *mongo.Collection
}
const collectionsMapName = "collections_map"
// used as a cache to store MongoDB clients.
var mongoDbClientMap = map[string]*mongo.Client{}
var mongoDbClientMapLock sync.Mutex
func getMongoClient(ctx context.Context, mongoUri string) (*mongo.Client, error) {
mongoDbClientMapLock.Lock()
defer mongoDbClientMapLock.Unlock()
if c, ok := mongoDbClientMap[mongoUri]; ok {
return c, nil
}
c, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoUri))
if err != nil {
return nil, fmt.Errorf("failed to connect to %s: %w", mongoUri, err)
}
mongoDbClientMap[mongoUri] = c
return c, nil
}
func getMongoCollection(ctx context.Context, database *mongo.Database, name string) (*mongo.Collection, error) {
collectionsMap := database.Collection(collectionsMapName)
// Index the collectionsMap collection.
if _, err := collectionsMap.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.M{"name": 1},
Options: options.Index().SetUnique(true),
}); err != nil {
return nil, fmt.Errorf("failed to create an index for collection %s: %w", collectionsMapName, err)
}
id := uuid.New().String()
// Find the collection name in the collections map.
res := collectionsMap.FindOneAndUpdate(
ctx,
bson.M{"name": name},
bson.M{"$setOnInsert": bson.M{"collectionName": id, "name": name}},
options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After),
)
if res.Err() != nil {
return nil, fmt.Errorf("failed to find and/or insert a collection mapping for %s: %w", name, res.Err())
}
var payload struct {
CollectionName string `bson:"collectionName"`
}
if err := res.Decode(&payload); err != nil {
return nil, fmt.Errorf("failed to decode a collection mapping document for %s: %w", name, err)
}
collection := database.Collection(payload.CollectionName)
// Index the collection.
if _, err := collection.Indexes().CreateMany(ctx, []mongo.IndexModel{
{
Keys: bson.M{"url": 1},
},
{
Keys: bson.M{"id": 1},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.M{"expireAt": 1},
Options: options.Index().SetExpireAfterSeconds(0),
}}); err != nil {
return nil, fmt.Errorf("failed to create an index for collection %s: %w", payload.CollectionName, err)
}
return collection, nil
}
func newStore(mongoUri string, name string) (Store, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := getMongoClient(ctx, mongoUri)
if err != nil {
return nil, err
}
if err := client.Ping(ctx, readpref.PrimaryPreferred()); err != nil {
return nil, err
}
cs, err := connstring.Parse(mongoUri)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", mongoUri, err)
}
if cs.Database == "" {
cs.Database = "short"
}
database := client.Database(cs.Database)
collection, err := getMongoCollection(ctx, database, name)
if err != nil {
return nil, err
}
return &store{
name: name,
collection: collection,
}, nil
}
func (s *store) Insert(ctx context.Context, ic *insertConfig) error {
toSet := bson.M{"id": ic.id, "url": ic.url}
if ic.expiration != nil {
toSet["expireAt"] = ic.expiration.Unix()
}
if ic.override {
if _, err := s.collection.UpdateOne(
ctx,
bson.M{"id": ic.id},
bson.M{"$set": toSet},
options.Update().SetUpsert(true),
); err != nil {
return fmt.Errorf("failed to update or insert id %s: %w", ic.id, err)
}
return nil
}
if _, err := s.collection.InsertOne(ctx, toSet); err != nil {
if mongo.IsDuplicateKeyError(err) {
return &ConflictError{}
}
return fmt.Errorf("failed to insert id %s: %w", ic.id, err)
}
return nil
}
func (s *store) GetUrl(ctx context.Context, id string) (string, error) {
res := s.collection.FindOne(ctx, bson.M{"id": id})
if res.Err() != nil {
if errors.Is(res.Err(), mongo.ErrNoDocuments) {
return "", &IdNotFoundError{id: id}
}
return "", fmt.Errorf("error when calling FindOne in the store %s: %w", s.name, res.Err())
}
var payload struct {
Url string `bson:"url"`
ExpireAt *int64 `bson:"expireAt,omitempty"`
}
if err := res.Decode(&payload); err != nil {
return "", fmt.Errorf("failed to decode record: %w", err)
}
if payload.ExpireAt != nil && time.Now().Unix() > *payload.ExpireAt {
return "", &IdNotFoundError{id: id}
}
return payload.Url, nil
}