/
aclapistorage.go
83 lines (73 loc) · 1.8 KB
/
aclapistorage.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
// Copyright 2023 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mongodb
import (
"context"
"sync"
"github.com/tsuru/acl-api/storage"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
_ storage.ACLAPIStorage = &aclapiStorage{}
aclapiOnce sync.Once
)
type aclapiStorage struct {
*mongoStorage
}
func (s *aclapiStorage) getACLAPIColl() *mongo.Collection {
coll := s.getCollection("acl_aclapi")
aclapiOnce.Do(func() {
coll.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
Keys: bson.D{
{Key: "ruleid", Value: 1},
},
Options: options.Index().SetUnique(true),
})
})
return coll
}
func (s *aclapiStorage) Find(ruleID string) (storage.ACLAPISyncedRule, error) {
coll := s.getACLAPIColl()
var r storage.ACLAPISyncedRule
result := coll.FindOne(context.TODO(), bson.M{"ruleid": ruleID})
err := result.Err()
if err != nil {
if err == mongo.ErrNoDocuments {
return r, storage.ErrACLAPISyncedRuleNotFound
}
return r, err
}
err = result.Decode(&r)
return r, err
}
func (s *aclapiStorage) Add(ruleID string, aclIDs []storage.ACLIdPair) error {
coll := s.getACLAPIColl()
_, err := coll.UpdateOne(context.TODO(),
bson.M{"ruleid": ruleID},
bson.M{
"$addToSet": bson.M{
"aclids": bson.M{"$each": aclIDs},
},
},
options.Update().SetUpsert(true),
)
return err
}
func (s *aclapiStorage) Remove(ruleID string, aclIDs []storage.ACLIdPair) error {
coll := s.getACLAPIColl()
_, err := coll.UpdateOne(context.TODO(),
bson.M{"ruleid": ruleID},
bson.M{
"$pullAll": bson.M{
"aclids": aclIDs,
},
},
)
if err == mongo.ErrNoDocuments {
err = storage.ErrACLAPISyncedRuleNotFound
}
return err
}