/
locker.go
50 lines (44 loc) · 917 Bytes
/
locker.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
package migrationsmongo
import (
"context"
"errors"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type lockerPK struct {
ID string `bson:"_id"`
}
type lockerModel struct {
ID string `bson:"_id"`
LockID *string `bson:"lock_id"`
}
type mgLocker struct {
db *mongo.Database
collectionName string
lockID string
}
func (p *mgLocker) Unlock() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) // TODO Make this configurable
defer cancel()
lockCollection := p.db.Collection(p.collectionName)
err := lockCollection.FindOneAndUpdate(ctx,
lockerPK{"lock"},
bson.D{
{
"$set",
bson.D{
{"lock_id", nil},
},
},
},
).Err()
switch {
case errors.Is(err, mongo.ErrNoDocuments):
return nil
case err != nil:
return fmt.Errorf("failed unlocking migration: %w", err)
}
return nil
}