-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
db.go
205 lines (163 loc) · 4.36 KB
/
db.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
201
202
203
204
205
package utils
import (
"context"
"os"
"errors"
"sync"
"time"
"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/mongo/writeconcern"
)
var client *mongo.Client
func DB() error {
if(GetMainConfig().DisableUserManagement) {
return errors.New("User Management is disabled")
}
mongoURL := GetMainConfig().MongoDB
if(client != nil && client.Ping(context.TODO(), readpref.Primary()) == nil) {
return nil
}
Log("(Re) Connecting to the database...")
if mongoURL == "" {
return errors.New("MongoDB URL is not set, cannot connect to the database.")
}
var err error
opts := options.Client().ApplyURI(mongoURL).SetRetryWrites(true).SetWriteConcern(writeconcern.New(writeconcern.WMajority()))
client, err = mongo.Connect(context.TODO(), opts)
if err != nil {
return err
}
defer func() {
}()
// Ping the primary
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
return err
}
Log("Successfully connected to the database.")
return nil
}
func DisconnectDB() {
if err := client.Disconnect(context.TODO()); err != nil {
Fatal("DB", err)
}
client = nil
}
func GetCollection(applicationId string, collection string) (*mongo.Collection, error) {
if client == nil {
errCo := DB()
if errCo != nil {
return nil, errCo
}
}
name := os.Getenv("MONGODB_NAME"); if name == "" {
name = "COSMOS"
}
Debug("Getting collection " + applicationId + "_" + collection + " from database " + name)
c := client.Database(name).Collection(applicationId + "_" + collection)
return c, nil
}
// func query(q string) (*sql.Rows, error) {
// return db.Query(q)
// }
var (
bufferLock sync.Mutex
writeBuffer = make(map[string][]map[string]interface{})
bufferTicker = time.NewTicker(1 * time.Minute)
bufferCapacity = 100
)
func InitDBBuffers() {
go func() {
for {
select {
case <-bufferTicker.C:
flushAllBuffers()
}
}
}()
}
func flushBuffer(collectionName string) {
bufferLock.Lock()
objects, exists := writeBuffer[collectionName]
if exists && len(objects) > 0 {
collection, errG := GetCollection(GetRootAppId(), collectionName)
if errG != nil {
Error("BulkDBWritter: Error getting collection", errG)
}
if err := WriteToDatabase(collection, objects); err != nil {
Error("BulkDBWritter: Error writing to database", err)
}
writeBuffer[collectionName] = make([]map[string]interface{}, 0)
}
bufferLock.Unlock()
}
func flushAllBuffers() {
bufferLock.Lock()
for collectionName, objects := range writeBuffer {
if len(objects) > 0 {
collection, errG := GetCollection(GetRootAppId(), collectionName)
if errG != nil {
Error("BulkDBWritter: Error getting collection", errG)
}
if err := WriteToDatabase(collection, objects); err != nil {
Error("BulkDBWritter: Error writing to database: ", err)
}
writeBuffer[collectionName] = make([]map[string]interface{}, 0)
}
}
bufferLock.Unlock()
}
func BufferedDBWrite(collectionName string, object map[string]interface{}) {
bufferLock.Lock()
writeBuffer[collectionName] = append(writeBuffer[collectionName], object)
if len(writeBuffer[collectionName]) >= bufferCapacity {
flushBuffer(collectionName)
}
bufferLock.Unlock()
}
func WriteToDatabase(collection *mongo.Collection, objects []map[string]interface{}) error {
if len(objects) == 0 {
return nil // Nothing to write
}
// Convert to a slice of interface{} for insertion
interfaceSlice := make([]interface{}, len(objects))
for i, v := range objects {
interfaceSlice[i] = v
}
_, err := collection.InsertMany(context.Background(), interfaceSlice)
if err != nil {
return err
}
return nil
}
func ListAllUsers(role string) []User {
// list all users
c, errCo := GetCollection(GetRootAppId(), "users")
if errCo != nil {
Error("Database Connect", errCo)
return []User{}
}
users := []User{}
condition := map[string]interface{}{}
if role == "admin" {
condition = map[string]interface{}{
"Role": 2,
}
} else if role == "user" {
condition = map[string]interface{}{
"Role": 1,
}
}
cursor, err := c.Find(nil, condition)
if err != nil {
Error("Database: Error while getting users", err)
return []User{}
}
defer cursor.Close(nil)
if err = cursor.All(nil, &users); err != nil {
Error("Database: Error while decoding users", err)
return []User{}
}
return users
}