-
Notifications
You must be signed in to change notification settings - Fork 113
/
sharecache.go
214 lines (189 loc) · 6.29 KB
/
sharecache.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
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package sharecache
import (
"context"
"encoding/json"
"path"
"path/filepath"
"time"
"github.com/cs3org/reva/v2/pkg/appctx"
"github.com/cs3org/reva/v2/pkg/errtypes"
"github.com/cs3org/reva/v2/pkg/share/manager/jsoncs3/shareid"
"github.com/cs3org/reva/v2/pkg/storage/utils/metadata"
"github.com/cs3org/reva/v2/pkg/utils"
)
// Cache caches the list of share ids for users/groups
// It functions as an in-memory cache with a persistence layer
// The storage is sharded by user/group
type Cache struct {
UserShares map[string]*UserShareCache
storage metadata.Storage
namespace string
filename string
ttl time.Duration
}
// UserShareCache holds the space/share map for one user
type UserShareCache struct {
Mtime time.Time
UserShares map[string]*SpaceShareIDs
nextSync time.Time
}
// SpaceShareIDs holds the unique list of share ids for a space
type SpaceShareIDs struct {
Mtime time.Time
IDs map[string]struct{}
}
// New returns a new Cache instance
func New(s metadata.Storage, namespace, filename string, ttl time.Duration) Cache {
return Cache{
UserShares: map[string]*UserShareCache{},
storage: s,
namespace: namespace,
filename: filename,
ttl: ttl,
}
}
// Add adds a share to the cache
func (c *Cache) Add(ctx context.Context, userid, shareID string) error {
storageid, spaceid, _ := shareid.Decode(shareID)
ssid := storageid + shareid.IDDelimiter + spaceid
now := time.Now()
if c.UserShares[userid] == nil {
c.UserShares[userid] = &UserShareCache{
UserShares: map[string]*SpaceShareIDs{},
}
}
if c.UserShares[userid].UserShares[ssid] == nil {
c.UserShares[userid].UserShares[ssid] = &SpaceShareIDs{
IDs: map[string]struct{}{},
}
}
// add share id
c.UserShares[userid].Mtime = now
c.UserShares[userid].UserShares[ssid].Mtime = now
c.UserShares[userid].UserShares[ssid].IDs[shareID] = struct{}{}
return c.Persist(ctx, userid)
}
// Remove removes a share for the given user
func (c *Cache) Remove(ctx context.Context, userid, shareID string) error {
storageid, spaceid, _ := shareid.Decode(shareID)
ssid := storageid + shareid.IDDelimiter + spaceid
now := time.Now()
if c.UserShares[userid] == nil {
c.UserShares[userid] = &UserShareCache{
Mtime: now,
UserShares: map[string]*SpaceShareIDs{},
}
}
if c.UserShares[userid].UserShares[ssid] != nil {
// remove share id
c.UserShares[userid].Mtime = now
c.UserShares[userid].UserShares[ssid].Mtime = now
delete(c.UserShares[userid].UserShares[ssid].IDs, shareID)
}
return c.Persist(ctx, userid)
}
// List return the list of spaces/shares for the given user/group
func (c *Cache) List(userid string) map[string]SpaceShareIDs {
r := map[string]SpaceShareIDs{}
if c.UserShares[userid] == nil {
return r
}
for ssid, cached := range c.UserShares[userid].UserShares {
r[ssid] = SpaceShareIDs{
Mtime: cached.Mtime,
IDs: cached.IDs,
}
}
return r
}
// Sync updates the in-memory data with the data from the storage if it is outdated
func (c *Cache) Sync(ctx context.Context, userID string) error {
log := appctx.GetLogger(ctx).With().Str("userID", userID).Logger()
log.Debug().Msg("Syncing share cache...")
var mtime time.Time
// - do we have a cached list of created shares for the user in memory?
if usc := c.UserShares[userID]; usc != nil {
if time.Now().Before(c.UserShares[userID].nextSync) {
log.Debug().Msg("Skipping share cache sync, it was just recently synced...")
return nil
}
c.UserShares[userID].nextSync = time.Now().Add(c.ttl)
mtime = usc.Mtime
// - y: set If-Modified-Since header to only download if it changed
} else {
mtime = time.Time{} // Set zero time so that data from storage always takes precedence
}
userCreatedPath := c.userCreatedPath(userID)
info, err := c.storage.Stat(ctx, userCreatedPath)
if err != nil {
if _, ok := err.(errtypes.NotFound); ok {
return nil // Nothing to sync against
}
log.Error().Err(err).Msg("Failed to stat the share cache")
return err
}
// check mtime of /users/{userid}/created.json
if utils.TSToTime(info.Mtime).After(mtime) {
log.Debug().Msg("Updating share cache...")
// - update cached list of created shares for the user in memory if changed
createdBlob, err := c.storage.SimpleDownload(ctx, userCreatedPath)
if err != nil {
log.Error().Err(err).Msg("Failed to download the share cache")
return err
}
newShareCache := &UserShareCache{}
err = json.Unmarshal(createdBlob, newShareCache)
if err != nil {
log.Error().Err(err).Msg("Failed to unmarshal the share cache")
return err
}
newShareCache.Mtime = utils.TSToTime(info.Mtime)
c.UserShares[userID] = newShareCache
}
log.Debug().Msg("Share cache is up to date")
return nil
}
// Persist persists the data for one user/group to the storage
func (c *Cache) Persist(ctx context.Context, userid string) error {
oldMtime := c.UserShares[userid].Mtime
c.UserShares[userid].Mtime = time.Now()
createdBytes, err := json.Marshal(c.UserShares[userid])
if err != nil {
c.UserShares[userid].Mtime = oldMtime
return err
}
jsonPath := c.userCreatedPath(userid)
if err := c.storage.MakeDirIfNotExist(ctx, path.Dir(jsonPath)); err != nil {
c.UserShares[userid].Mtime = oldMtime
return err
}
if err = c.storage.Upload(ctx, metadata.UploadRequest{
Path: jsonPath,
Content: createdBytes,
IfUnmodifiedSince: c.UserShares[userid].Mtime,
}); err != nil {
c.UserShares[userid].Mtime = oldMtime
return err
}
return nil
}
func (c *Cache) userCreatedPath(userid string) string {
return filepath.Join("/", c.namespace, userid, c.filename)
}