-
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathTreeCacheManager.php
More file actions
295 lines (270 loc) Β· 9.39 KB
/
Copy pathTreeCacheManager.php
File metadata and controls
295 lines (270 loc) Β· 9.39 KB
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
<?php
/*
* Copyright (c) 2020-2024. The Nextcloud Bookmarks contributors.
*
* This file is licensed under the Affero General Public License version 3 or later. See the COPYING file.
*/
namespace OCA\Bookmarks\Service;
use OCA\Bookmarks\Db\BookmarkMapper;
use OCA\Bookmarks\Db\Folder;
use OCA\Bookmarks\Db\FolderMapper;
use OCA\Bookmarks\Db\SharedFolderMapper;
use OCA\Bookmarks\Db\ShareMapper;
use OCA\Bookmarks\Db\TagMapper;
use OCA\Bookmarks\Db\TreeMapper;
use OCA\Bookmarks\Events\ChangeEvent;
use OCA\Bookmarks\Events\MoveEvent;
use OCA\Bookmarks\Exception\UnsupportedOperation;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\ICache;
use OCP\ICacheFactory;
use Psr\Container\ContainerInterface;
use UnexpectedValueException;
/**
* @implements IEventListener<ChangeEvent>
*/
class TreeCacheManager implements IEventListener {
public const TTL = 60 * 60 * 24 * 30; // one month
public const CATEGORY_HASH = 'hashes';
public const CATEGORY_SUBFOLDERS = 'subFolders';
public const CATEGORY_DELETED_SUBFOLDERS = 'deletedSubFolders';
public const CATEGORY_FOLDERCOUNT = 'folderCount';
public const CATEGORY_CHILDREN = 'children';
public const CATEGORY_CHILDREN_LAYER = 'children_layer';
public const CATEGORY_CHILDORDER = 'childOrder';
/**
* @var bool
*/
private $enabled = true;
/**
* @var ICache[]
*/
private $caches = [];
/**
* FolderMapper constructor.
*
* @param FolderMapper $folderMapper
* @param BookmarkMapper $bookmarkMapper
* @param ShareMapper $shareMapper
* @param SharedFolderMapper $sharedFolderMapper
* @param ICacheFactory $cacheFactory
* @param ContainerInterface $appContainer
* @param TagMapper $tagMapper
*/
public function __construct(
protected FolderMapper $folderMapper,
protected BookmarkMapper $bookmarkMapper,
protected ShareMapper $shareMapper,
protected SharedFolderMapper $sharedFolderMapper,
protected ICacheFactory $cacheFactory,
protected ContainerInterface $appContainer,
protected TagMapper $tagMapper,
) {
$this->caches[self::CATEGORY_HASH] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_HASH);
$this->caches[self::CATEGORY_SUBFOLDERS] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_SUBFOLDERS);
$this->caches[self::CATEGORY_DELETED_SUBFOLDERS] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_DELETED_SUBFOLDERS);
$this->caches[self::CATEGORY_FOLDERCOUNT] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_FOLDERCOUNT);
$this->caches[self::CATEGORY_CHILDREN] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_CHILDREN);
$this->caches[self::CATEGORY_CHILDREN_LAYER] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_CHILDREN_LAYER);
$this->caches[self::CATEGORY_CHILDORDER] = $cacheFactory->createDistributed('bookmarks:' . self::CATEGORY_CHILDORDER);
}
private function getTreeMapper(): TreeMapper {
return $this->appContainer->get(TreeMapper::class);
}
/**
* @param string $type
* @param int $folderId
* @return string
*/
private function getCacheKey(string $type, int $folderId) : string {
return $type . ':' . $folderId;
}
/**
* @param string $category
* @param string $type
* @param int $id
* @return mixed
*/
public function get(string $category, string $type, int $id) {
$key = $this->getCacheKey($type, $id);
return $this->caches[$category]->get($key);
}
/**
* @param string $category
* @param string $type
* @param int $id
* @param mixed $data
* @return mixed
*/
public function set(string $category, string $type, int $id, $data) {
$key = $this->getCacheKey($type, $id);
return $this->caches[$category]->set($key, $data, self::TTL);
}
/**
* @param string $type
* @param int $id
*/
public function remove(string $type, int $id, array $previousFolders = []): void {
$key = $this->getCacheKey($type, $id);
foreach ($this->caches as $cacheType => $cache) {
if ($cacheType === self::CATEGORY_CHILDREN_LAYER && count($previousFolders) > 1) {
continue;
}
$cache->remove($key);
}
}
/**
* @param int $folderId
* @param array $previousFolders
*/
public function invalidateFolder(int $folderId, array $previousFolders = []): void {
if (in_array($folderId, $previousFolders, true)) {
// In case we have run into a folder loop
return;
}
$this->remove(TreeMapper::TYPE_FOLDER, $folderId, $previousFolders);
$previousFolders[] = $folderId;
// Invalidate parent
try {
$parentFolder = $this->getTreeMapper()->findParentOf(TreeMapper::TYPE_FOLDER, $folderId);
$this->invalidateFolder($parentFolder->getId(), $previousFolders);
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
return;
}
// Invalidate share participants
$sharedFolders = $this->sharedFolderMapper->findByFolder($folderId);
foreach ($sharedFolders as $sharedFolder) {
try {
$parentFolder = $this->getTreeMapper()->findParentOf(TreeMapper::TYPE_SHARE, $sharedFolder->getId());
$this->invalidateFolder($parentFolder->getId(), $previousFolders);
} catch (DoesNotExistException|MultipleObjectsReturnedException $e) {
continue;
}
}
}
public function invalidateBookmark(int $bookmarkId): void {
$this->remove(TreeMapper::TYPE_BOOKMARK, $bookmarkId);
// Invalidate parent
$parentFolders = $this->getTreeMapper()->findParentsOf(TreeMapper::TYPE_BOOKMARK, $bookmarkId, true);
foreach ($parentFolders as $parentFolder) {
$this->invalidateFolder($parentFolder->getId());
}
}
/**
* @param int $folderId
* @param array $fields
* @param string $userId
* @return string
* @throws DoesNotExistException
* @throws MultipleObjectsReturnedException|\JsonException
* @throws UnsupportedOperation
*/
public function hashFolder($userId, int $folderId, array $fields = ['title', 'url'], string $hashFn = 'sha256') : string {
$hash = $this->get(self::CATEGORY_HASH, TreeMapper::TYPE_FOLDER, $folderId);
$selector = $hashFn . ':' . $userId . ':' . implode(',', $fields);
if (isset($hash[$selector])) {
return $hash[$selector];
}
if (!isset($hash)) {
$hash = [];
}
/** @var Folder $entity */
$entity = $this->folderMapper->find($folderId);
$rootFolder = $this->folderMapper->findRootFolder($userId);
$children = $this->getTreeMapper()->getChildrenOrder($folderId);
$childHashes = array_map(function ($item) use ($fields, $entity, $hashFn) {
switch ($item['type']) {
case TreeMapper::TYPE_BOOKMARK:
return $this->hashBookmark($item['id'], $fields, $hashFn);
case TreeMapper::TYPE_FOLDER:
return $this->hashFolder($entity->getUserId(), $item['id'], $fields, $hashFn);
default:
throw new UnexpectedValueException('Expected bookmark or folder, but not ' . $item['type']);
}
}, $children);
$folder = [];
if ($entity->getUserId() !== $userId) {
$folder['title'] = $this->sharedFolderMapper->findByFolderAndUser($folderId, $userId)->getTitle();
} elseif ($entity->getTitle() !== null && $entity->getId() !== $rootFolder->getId()) {
$folder['title'] = $entity->getTitle();
}
$folder['children'] = $childHashes;
$hash[$selector] = hash($hashFn, json_encode($folder, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$this->set(self::CATEGORY_HASH, TreeMapper::TYPE_FOLDER, $folderId, $hash);
return $hash[$selector];
}
/**
* @param int $bookmarkId
* @param array $fields
* @return string
* @throws DoesNotExistException
* @throws MultipleObjectsReturnedException|\JsonException
* @throws UnsupportedOperation
*/
public function hashBookmark(int $bookmarkId, array $fields = ['title', 'url'], string $hashFn = 'sha256'): string {
$hash = $this->get(self::CATEGORY_HASH, TreeMapper::TYPE_BOOKMARK, $bookmarkId);
$selector = $hashFn . ':' . implode(',', $fields);
if (isset($hash[$selector])) {
return $hash[$selector];
}
if (!isset($hash)) {
$hash = [];
}
$entity = $this->bookmarkMapper->find($bookmarkId);
$bookmark = [];
foreach ($fields as $field) {
if ($field === 'tags') {
$bookmark[$field] = $this->tagMapper->findByBookmark($bookmarkId);
continue;
}
try {
$bookmark[$field] = $entity->{'get' . $field}();
} catch (\BadFunctionCallException $e) {
throw new UnsupportedOperation('Field ' . $field . ' does not exist');
}
}
$hash[$selector] = hash($hashFn, json_encode($bookmark, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$this->set(self::CATEGORY_HASH, TreeMapper::TYPE_BOOKMARK, $bookmarkId, $hash);
return $hash[$selector];
}
/**
* Handle events
*
* @param Event $event
*/
public function handle(Event $event): void {
if ($this->enabled === false) {
return;
}
if (!($event instanceof ChangeEvent)) {
return;
}
switch ($event->getType()) {
case TreeMapper::TYPE_FOLDER:
$this->invalidateFolder($event->getId());
break;
case TreeMapper::TYPE_BOOKMARK:
$this->invalidateBookmark($event->getId());
break;
}
if ($event instanceof MoveEvent) {
if ($event->getNewParent() !== null) {
$this->invalidateFolder($event->getNewParent());
}
if ($event->getOldParent() !== null) {
$this->invalidateFolder($event->getOldParent());
}
}
}
public function setInvalidationEnabled(bool $enabled): void {
$this->enabled = $enabled;
}
public function invalidateAll() {
foreach ($this->caches as $cache) {
$cache->clear();
}
}
}