-
Notifications
You must be signed in to change notification settings - Fork 171
/
mem_db.go
341 lines (295 loc) · 7.56 KB
/
mem_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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* Copyright (c) 2019-2021. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
// Package memory provides an in-memory basic implementation of an Endpoint, with nodes stored in a map.
package memory
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
"golang.org/x/text/unicode/norm"
"github.com/pydio/cells/v4/common/proto/tree"
"github.com/pydio/cells/v4/common/sync/model"
json "github.com/pydio/cells/v4/common/utils/jsonx"
)
type DBEvent struct {
Type string
Source string
Target string
}
type MemDB struct {
Nodes []*tree.Node
eventChannels []chan DBEvent
// Used for testing
ignores []string
testPathURI string
}
func NewMemDB() *MemDB {
db := &MemDB{}
db.CreateNode(context.Background(), &tree.Node{
Path: "/",
Type: tree.NodeType_COLLECTION,
Uuid: "root",
}, true)
return db
}
func (db *MemDB) GetEndpointInfo() model.EndpointInfo {
return model.EndpointInfo{
URI: "memdb://" + db.testPathURI,
RequiresFoldersRescan: true,
RequiresNormalization: false,
Ignores: db.ignores,
}
}
// AddIgnore register a filename to be ignored (for tests only)
func (db *MemDB) AddIgnore(s string) {
db.ignores = append(db.ignores, s)
}
func (db *MemDB) SetTestPathURI(s string) {
db.testPathURI = s
}
/*************************/
/* Event Emitter */
/*************************/
func (db *MemDB) RegisterEventChannel(out chan DBEvent) {
db.eventChannels = append(db.eventChannels, out)
}
func (db *MemDB) sendEvent(event DBEvent) {
for _, channel := range db.eventChannels {
channel <- event
}
}
/*************************/
/* Path Sync Target */
/*************************/
func (db *MemDB) LoadNode(ctx context.Context, path string, extendedStats ...bool) (node *tree.Node, err error) {
for _, node := range db.Nodes {
// fmt.Printf("Path:%s Nodes %s\n", norm.NFC.String(path), norm.NFC.String(node.Path))
if norm.NFC.String(node.Path) == norm.NFC.String(path) {
return node, nil
}
}
return nil, errors.New("Node not found")
}
func (db *MemDB) CreateNode(ctx context.Context, node *tree.Node, updateIfExists bool) (err error) {
db.Nodes = append(db.Nodes, node)
db.sendEvent(DBEvent{
Type: "Create",
Target: node.Path,
})
return nil
}
func (db *MemDB) DeleteNode(ctx context.Context, path string) (err error) {
removed := db.removeNodeNoEvent(path)
if removed != nil {
db.sendEvent(DBEvent{
Type: "Delete",
Source: removed.Path,
})
}
return nil
}
func (db *MemDB) MoveNode(ctx context.Context, oldPath string, newPath string) (err error) {
moved := false
for _, node := range db.Nodes {
if strings.HasPrefix(node.Path, oldPath+"/") || node.Path == oldPath {
node.Path = newPath + strings.TrimPrefix(node.Path, oldPath)
moved = true
}
}
if moved {
db.sendEvent(DBEvent{
Type: "Moved",
Source: oldPath,
Target: newPath,
})
}
return nil
}
/*************************/
/* Path Sync Source */
/*************************/
func (db *MemDB) Walk(ctx context.Context, walknFc model.WalkNodesFunc, root string, recursive bool) (err error) {
for _, node := range db.Nodes {
if root != "/" && !strings.HasPrefix(node.Path, root) {
continue
}
if !recursive && strings.Contains(strings.TrimPrefix(node.Path, root), "/") {
return nil
}
if er := walknFc(node.Path, node, nil); er != nil {
return er
}
}
return nil
}
func (db *MemDB) Watch(recursivePath string) (*model.WatchObject, error) {
inChan := make(chan DBEvent)
eventChan := make(chan model.EventInfo)
errorChan := make(chan error)
doneChan := make(chan bool)
// wait for doneChan to close the other channels
go func() {
<-doneChan
close(eventChan)
close(errorChan)
close(inChan)
}()
wo := &model.WatchObject{
EventInfoChan: eventChan,
ErrorChan: errorChan,
DoneChan: doneChan,
}
go func() {
defer wo.Close()
for ev := range inChan {
switch v := ev.Type; v {
case "Create":
eventChan <- model.EventInfo{
Time: time.Now().String(),
Size: 0,
Etag: "",
Path: ev.Target,
Folder: false,
Source: db,
Type: model.EventCreate,
}
case "Moved":
eventChan <- model.EventInfo{
Time: time.Now().String(),
Size: 0,
Etag: "",
Path: ev.Target,
Folder: false,
Source: db,
Type: model.EventSureMove,
}
case "Deleted":
eventChan <- model.EventInfo{
Time: time.Now().String(),
Size: 0,
Etag: "",
Path: ev.Source,
Folder: false,
Source: db,
Type: model.EventRemove,
}
}
}
}()
return wo, nil
}
/*************************/
/* Other Methods */
/*************************/
func (db *MemDB) removeNodeNoEvent(path string) (removed *tree.Node) {
var newNodes []*tree.Node
for _, node := range db.Nodes {
if !strings.HasPrefix(node.Path, path+"/") && node.Path != path {
newNodes = append(newNodes, node)
} else {
removed = node
}
}
db.Nodes = newNodes
return removed
}
func (db *MemDB) FindByHash(hash string) (node *tree.Node) {
for _, node := range db.Nodes {
if node.Etag == hash {
return node
}
}
return
}
func (db *MemDB) FindByUuid(id string) (node *tree.Node) {
for _, node := range db.Nodes {
if node.Uuid == id {
return node
}
}
return
}
func (db *MemDB) String() string {
output := ""
for _, node := range db.Nodes {
leaf := "Leaf"
if !node.IsLeaf() {
leaf = "Folder"
}
output += leaf + "\t'" + node.Path + "' (" + node.Uuid + node.Etag + ")" + "\n"
}
return output
}
func (db *MemDB) Stats() string {
var leafs, colls int
for _, node := range db.Nodes {
if node.IsLeaf() {
leafs++
} else {
colls++
}
}
return fmt.Sprintf("Snapshot contains %v files and %v folders", leafs, colls)
}
func (db *MemDB) ToJSON(name string) error {
data, _ := json.Marshal(db.Nodes)
return os.WriteFile(name, data, 0666)
}
func (db *MemDB) FromJSON(name string) error {
data, err := os.ReadFile(name)
if err != nil {
return err
}
return json.Unmarshal(data, &db.Nodes)
}
// MemDBWithCacheTest provides a structure for testing CachedBranchProvider related functions
type MemDBWithCacheTest struct {
MemDB
}
// NewMemDBWithCacheTest creates a new MemDB implementing CachedBranchProvider interface
func NewMemDBWithCacheTest() *MemDBWithCacheTest {
return &MemDBWithCacheTest{
MemDB: *NewMemDB(),
}
}
// GetCachedBranches loads branch in memory
func (m *MemDBWithCacheTest) GetCachedBranches(ctx context.Context, roots ...string) (model.PathSyncSource, error) {
memDB := NewMemDB()
// Make sure to dedup roots
rts := make(map[string]string)
for _, root := range roots {
rts[root] = root
}
for _, root := range rts {
er := m.Walk(nil, func(path string, node *tree.Node, err error) error {
if err == nil {
err = memDB.CreateNode(ctx, node, false)
}
return err
}, root, true)
if er != nil {
return nil, er
}
}
return memDB, nil
}