aboutsummaryrefslogtreecommitdiff
path: root/zenserver/cache/structuredcachestore.h
blob: e6e9942bb053411a00e336760ceb3595da2ee698 (plain) (blame)
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/compactbinary.h>
#include <zencore/iobuffer.h>
#include <zencore/iohash.h>
#include <zencore/thread.h>
#include <zencore/uid.h>
#include <zenstore/blockstore.h>
#include <zenstore/caslog.h>
#include <zenstore/gc.h>

ZEN_THIRD_PARTY_INCLUDES_START
#include <tsl/robin_map.h>
ZEN_THIRD_PARTY_INCLUDES_END

#include <atomic>
#include <compare>
#include <filesystem>
#include <unordered_map>

#define ZEN_USE_CACHE_TRACKER 0

namespace zen {

class PathBuilderBase;
class GcManager;
class ZenCacheTracker;
class ScrubContext;

/******************************************************************************

  /$$$$$$$$                        /$$$$$$                   /$$
 |_____ $$                        /$$__  $$                 | $$
	  /$$/  /$$$$$$ /$$$$$$$     | $$  \__/ /$$$$$$  /$$$$$$| $$$$$$$  /$$$$$$
	 /$$/  /$$__  $| $$__  $$    | $$      |____  $$/$$_____| $$__  $$/$$__  $$
	/$$/  | $$$$$$$| $$  \ $$    | $$       /$$$$$$| $$     | $$  \ $| $$$$$$$$
   /$$/   | $$_____| $$  | $$    | $$    $$/$$__  $| $$     | $$  | $| $$_____/
  /$$$$$$$|  $$$$$$| $$  | $$    |  $$$$$$|  $$$$$$|  $$$$$$| $$  | $|  $$$$$$$
 |________/\_______|__/  |__/     \______/ \_______/\_______|__/  |__/\_______/

  Cache store for UE5. Restricts keys to "{bucket}/{hash}" pairs where the hash
  is 40 (hex) chars in size. Values may be opaque blobs or structured objects
  which can in turn contain references to other objects (or blobs).

******************************************************************************/

namespace access_tracking {

	struct KeyAccessTime
	{
		IoHash		  Key;
		GcClock::Tick LastAccess{};
	};

	struct AccessTimes
	{
		std::unordered_map<std::string, std::vector<KeyAccessTime>> Buckets;
	};
};	// namespace access_tracking

struct ZenCacheValue
{
	IoBuffer Value;
	CbObject IndexData;
};

//////////////////////////////////////////////////////////////////////////

#pragma pack(push)
#pragma pack(1)

struct DiskLocation
{
	inline DiskLocation() = default;

	inline DiskLocation(uint64_t ValueSize, uint8_t Flags) : Flags(Flags | kStandaloneFile) { Location.StandaloneSize = ValueSize; }

	inline DiskLocation(const BlockStoreLocation& Location, uint64_t PayloadAlignment, uint8_t Flags) : Flags(Flags & ~kStandaloneFile)
	{
		this->Location.BlockLocation = BlockStoreDiskLocation(Location, PayloadAlignment);
	}

	inline BlockStoreLocation GetBlockLocation(uint64_t PayloadAlignment) const
	{
		ZEN_ASSERT(!(Flags & kStandaloneFile));
		return Location.BlockLocation.Get(PayloadAlignment);
	}

	inline uint64_t		  Size() const { return (Flags & kStandaloneFile) ? Location.StandaloneSize : Location.BlockLocation.GetSize(); }
	inline uint8_t		  IsFlagSet(uint64_t Flag) const { return Flags & Flag; }
	inline uint8_t		  GetFlags() const { return Flags; }
	inline ZenContentType GetContentType() const
	{
		ZenContentType ContentType = ZenContentType::kBinary;

		if (IsFlagSet(kStructured))
		{
			ContentType = ZenContentType::kCbObject;
		}

		if (IsFlagSet(kCompressed))
		{
			ContentType = ZenContentType::kCompressedBinary;
		}

		return ContentType;
	}

	union
	{
		BlockStoreDiskLocation BlockLocation;		// 10 bytes
		uint64_t			   StandaloneSize = 0;	// 8 bytes
	} Location;

	static const uint8_t kStandaloneFile = 0x80u;  // Stored as a separate file
	static const uint8_t kStructured	 = 0x40u;  // Serialized as compact binary
	static const uint8_t kTombStone		 = 0x20u;  // Represents a deleted key/value
	static const uint8_t kCompressed	 = 0x10u;  // Stored in compressed buffer format

	uint8_t Flags	 = 0;
	uint8_t Reserved = 0;
};

struct DiskIndexEntry
{
	IoHash		 Key;		// 20 bytes
	DiskLocation Location;	// 12 bytes
};
#pragma pack(pop)

static_assert(sizeof(DiskIndexEntry) == 32);

/** In-memory cache storage

	Intended for small values which are frequently accessed

	This should have a better memory management policy to maintain reasonable
	footprint.

 */
class ZenCacheMemoryLayer
{
public:
	struct Configuration
	{
		uint64_t TargetFootprintBytes = 16 * 1024 * 1024;
		uint64_t ScavengeThreshold	  = 4 * 1024 * 1024;
	};

	struct BucketInfo
	{
		uint64_t EntryCount = 0;
		uint64_t TotalSize	= 0;
	};

	struct Info
	{
		Configuration			 Config;
		std::vector<std::string> BucketNames;
		uint64_t				 EntryCount = 0;
		uint64_t				 TotalSize	= 0;
	};

	ZenCacheMemoryLayer();
	~ZenCacheMemoryLayer();

	bool	 Get(std::string_view Bucket, const IoHash& HashKey, ZenCacheValue& OutValue);
	void	 Put(std::string_view Bucket, const IoHash& HashKey, const ZenCacheValue& Value);
	void	 Drop();
	bool	 DropBucket(std::string_view Bucket);
	void	 Scrub(ScrubContext& Ctx);
	void	 GatherAccessTimes(zen::access_tracking::AccessTimes& AccessTimes);
	void	 Reset();
	uint64_t TotalSize() const;

	Info					  GetInfo() const;
	std::optional<BucketInfo> GetBucketInfo(std::string_view Bucket) const;

	const Configuration& GetConfiguration() const { return m_Configuration; }
	void				 SetConfiguration(const Configuration& NewConfig) { m_Configuration = NewConfig; }

private:
	struct CacheBucket
	{
		struct BucketValue
		{
			IoBuffer			Payload;
			std::atomic_int64_t LastAccess;

			BucketValue() : Payload(), LastAccess() {}
			BucketValue(IoBuffer Value, const int64_t Timestamp) : Payload(Value), LastAccess(Timestamp) {}
			BucketValue(const BucketValue& V) : Payload(V.Payload), LastAccess(V.LastAccess.load(std::memory_order_relaxed)) {}
			BucketValue(BucketValue&& V) : Payload(std::move(V.Payload)), LastAccess(V.LastAccess.load(std::memory_order_relaxed)) {}

			BucketValue& operator=(const BucketValue& V) { return *this = BucketValue(V); }
			BucketValue& operator=(BucketValue&& V)
			{
				Payload = std::move(V.Payload);
				LastAccess.store(V.LastAccess.load(), std::memory_order_relaxed);
				return *this;
			}
		};

		mutable RwLock						m_BucketLock;
		tsl::robin_map<IoHash, BucketValue> m_CacheMap;
		std::atomic_uint64_t				m_TotalSize{};

		bool			Get(const IoHash& HashKey, ZenCacheValue& OutValue);
		void			Put(const IoHash& HashKey, const ZenCacheValue& Value);
		void			Drop();
		void			Scrub(ScrubContext& Ctx);
		void			GatherAccessTimes(std::vector<zen::access_tracking::KeyAccessTime>& AccessTimes);
		inline uint64_t TotalSize() const { return m_TotalSize; }
		uint64_t		EntryCount() const;
	};

	mutable RwLock												  m_Lock;
	std::unordered_map<std::string, std::unique_ptr<CacheBucket>> m_Buckets;
	std::vector<std::unique_ptr<CacheBucket>>					  m_DroppedBuckets;
	Configuration												  m_Configuration;

	ZenCacheMemoryLayer(const ZenCacheMemoryLayer&) = delete;
	ZenCacheMemoryLayer& operator=(const ZenCacheMemoryLayer&) = delete;
};

class ZenCacheDiskLayer
{
public:
	struct Configuration
	{
		std::filesystem::path RootDir;
	};

	struct BucketInfo
	{
		uint64_t EntryCount = 0;
		uint64_t TotalSize	= 0;
	};

	struct Info
	{
		Configuration			 Config;
		std::vector<std::string> BucketNames;
		uint64_t				 EntryCount = 0;
		uint64_t				 TotalSize	= 0;
	};

	explicit ZenCacheDiskLayer(const std::filesystem::path& RootDir);
	~ZenCacheDiskLayer();

	bool Get(std::string_view Bucket, const IoHash& HashKey, ZenCacheValue& OutValue);
	void Put(std::string_view Bucket, const IoHash& HashKey, const ZenCacheValue& Value);
	bool Drop();
	bool DropBucket(std::string_view Bucket);
	void Flush();
	void Scrub(ScrubContext& Ctx);
	void GatherReferences(GcContext& GcCtx);
	void CollectGarbage(GcContext& GcCtx);
	void UpdateAccessTimes(const zen::access_tracking::AccessTimes& AccessTimes);
	// void IterateBuckets(const std::function<void(std::string_view Bucket)>& Callback) const;

	void	 DiscoverBuckets();
	uint64_t TotalSize() const;

	Info					  GetInfo() const;
	std::optional<BucketInfo> GetBucketInfo(std::string_view Bucket) const;

private:
	/** A cache bucket manages a single directory containing
		metadata and data for that bucket
	  */
	struct CacheBucket
	{
		CacheBucket(std::string BucketName);
		~CacheBucket();

		bool OpenOrCreate(std::filesystem::path BucketDir, bool AllowCreate = true);
		bool Get(const IoHash& HashKey, ZenCacheValue& OutValue);
		void Put(const IoHash& HashKey, const ZenCacheValue& Value);
		bool Drop();
		void Flush();
		void Scrub(ScrubContext& Ctx);
		void GatherReferences(GcContext& GcCtx);
		void CollectGarbage(GcContext& GcCtx);
		void UpdateAccessTimes(const std::vector<zen::access_tracking::KeyAccessTime>& AccessTimes);

		inline uint64_t TotalSize() const { return m_TotalStandaloneSize.load(std::memory_order::relaxed) + m_BlockStore.TotalSize(); }
		uint64_t		EntryCount() const;

	private:
		const uint64_t MaxBlockSize		  = 1ull << 30;
		uint64_t	   m_PayloadAlignment = 1ull << 4;

		std::string			  m_BucketName;
		std::filesystem::path m_BucketDir;
		std::filesystem::path m_BlocksBasePath;
		BlockStore			  m_BlockStore;
		Oid					  m_BucketId;
		uint64_t			  m_LargeObjectThreshold = 128 * 1024;

		// These files are used to manage storage of small objects for this bucket

		TCasLogFile<DiskIndexEntry> m_SlogFile;
		uint64_t					m_LogFlushPosition = 0;

		struct IndexEntry
		{
			DiskLocation		Location;
			std::atomic_int64_t LastAccess;

			IndexEntry() : Location(), LastAccess() {}
			IndexEntry(const DiskLocation& Loc, const int64_t Timestamp) : Location(Loc), LastAccess(Timestamp) {}
			IndexEntry(const IndexEntry& E) : Location(E.Location), LastAccess(E.LastAccess.load(std::memory_order_relaxed)) {}
			IndexEntry(IndexEntry&& E) noexcept : Location(std::move(E.Location)), LastAccess(E.LastAccess.load(std::memory_order_relaxed))
			{
			}

			IndexEntry& operator=(const IndexEntry& E) { return *this = IndexEntry(E); }
			IndexEntry& operator=(IndexEntry&& E) noexcept
			{
				Location = std::move(E.Location);
				LastAccess.store(E.LastAccess.load(), std::memory_order_relaxed);
				return *this;
			}
		};

		using IndexMap = tsl::robin_map<IoHash, IndexEntry, IoHash::Hasher>;

		mutable RwLock m_IndexLock;
		IndexMap	   m_Index;

		std::atomic_uint64_t m_TotalStandaloneSize{};

		void	 BuildPath(PathBuilderBase& Path, const IoHash& HashKey);
		void	 PutStandaloneCacheValue(const IoHash& HashKey, const ZenCacheValue& Value);
		bool	 GetStandaloneCacheValue(const DiskLocation& Loc, const IoHash& HashKey, ZenCacheValue& OutValue);
		void	 PutInlineCacheValue(const IoHash& HashKey, const ZenCacheValue& Value);
		bool	 GetInlineCacheValue(const DiskLocation& Loc, ZenCacheValue& OutValue);
		void	 MakeIndexSnapshot();
		uint64_t ReadIndexFile();
		uint64_t ReadLog(uint64_t LogPosition);
		void	 OpenLog(const std::filesystem::path& BucketDir, const bool IsNew);
		void	 SaveManifest();

		// These locks are here to avoid contention on file creation, therefore it's sufficient
		// that we take the same lock for the same hash
		//
		// These locks are small and should really be spaced out so they don't share cache lines,
		// but we don't currently access them at particularly high frequency so it should not be
		// an issue in practice

		RwLock		   m_ShardedLocks[256];
		inline RwLock& LockForHash(const IoHash& Hash) { return m_ShardedLocks[Hash.Hash[19]]; }
	};

	std::filesystem::path										  m_RootDir;
	mutable RwLock												  m_Lock;
	std::unordered_map<std::string, std::unique_ptr<CacheBucket>> m_Buckets;  // TODO: make this case insensitive
	std::vector<std::unique_ptr<CacheBucket>>					  m_DroppedBuckets;

	ZenCacheDiskLayer(const ZenCacheDiskLayer&) = delete;
	ZenCacheDiskLayer& operator=(const ZenCacheDiskLayer&) = delete;
};

class ZenCacheNamespace final : public RefCounted, public GcStorage, public GcContributor
{
public:
	struct Configuration
	{
		std::filesystem::path RootDir;
		uint64_t			  DiskLayerThreshold = 0;
	};
	struct BucketInfo
	{
		ZenCacheDiskLayer::BucketInfo	DiskLayerInfo;
		ZenCacheMemoryLayer::BucketInfo MemoryLayerInfo;
	};
	struct Info
	{
		Configuration			  Config;
		std::vector<std::string>  BucketNames;
		ZenCacheDiskLayer::Info	  DiskLayerInfo;
		ZenCacheMemoryLayer::Info MemoryLayerInfo;
	};

	ZenCacheNamespace(GcManager& Gc, const std::filesystem::path& RootDir);
	~ZenCacheNamespace();

	bool					  Get(std::string_view Bucket, const IoHash& HashKey, ZenCacheValue& OutValue);
	void					  Put(std::string_view Bucket, const IoHash& HashKey, const ZenCacheValue& Value);
	bool					  Drop();
	bool					  DropBucket(std::string_view Bucket);
	void					  Flush();
	void					  Scrub(ScrubContext& Ctx);
	uint64_t				  DiskLayerThreshold() const { return m_DiskLayerSizeThreshold; }
	virtual void			  GatherReferences(GcContext& GcCtx) override;
	virtual void			  CollectGarbage(GcContext& GcCtx) override;
	virtual GcStorageSize	  StorageSize() const override;
	Info					  GetInfo() const;
	std::optional<BucketInfo> GetBucketInfo(std::string_view Bucket) const;

private:
	std::filesystem::path m_RootDir;
	ZenCacheMemoryLayer	  m_MemLayer;
	ZenCacheDiskLayer	  m_DiskLayer;
	uint64_t			  m_DiskLayerSizeThreshold = 1 * 1024;
	uint64_t			  m_LastScrubTime		   = 0;

#if ZEN_USE_CACHE_TRACKER
	std::unique_ptr<ZenCacheTracker> m_AccessTracker;
#endif

	ZenCacheNamespace(const ZenCacheNamespace&) = delete;
	ZenCacheNamespace& operator=(const ZenCacheNamespace&) = delete;
};

class ZenCacheStore final
{
public:
	static constexpr std::string_view DefaultNamespace =
		"!default!";  // This is intentionally not a valid namespace name and will only be used for mapping when no namespace is given
	static constexpr std::string_view NamespaceDiskPrefix = "ns_";

	struct Configuration
	{
		std::filesystem::path BasePath;
		bool				  AllowAutomaticCreationOfNamespaces = false;
	};

	struct Info
	{
		Configuration			 Config;
		std::vector<std::string> NamespaceNames;
		uint64_t				 DiskEntryCount	  = 0;
		uint64_t				 MemoryEntryCount = 0;
		GcStorageSize			 StorageSize;
	};

	ZenCacheStore(GcManager& Gc, const Configuration& Configuration);
	~ZenCacheStore();

	bool Get(std::string_view Namespace, std::string_view Bucket, const IoHash& HashKey, ZenCacheValue& OutValue);
	void Put(std::string_view Namespace, std::string_view Bucket, const IoHash& HashKey, const ZenCacheValue& Value);
	bool DropBucket(std::string_view Namespace, std::string_view Bucket);
	bool DropNamespace(std::string_view Namespace);
	void Flush();
	void Scrub(ScrubContext& Ctx);

	GcStorageSize StorageSize() const;
	//	const Configuration& GetConfiguration() const { return m_Configuration; }

	Info										 GetInfo() const;
	std::optional<ZenCacheNamespace::Info>		 GetNamespaceInfo(std::string_view Namespace);
	std::optional<ZenCacheNamespace::BucketInfo> GetBucketInfo(std::string_view Namespace, std::string_view Bucket);

private:
	const ZenCacheNamespace* FindNamespace(std::string_view Namespace) const;
	ZenCacheNamespace*		 GetNamespace(std::string_view Namespace);
	void IterateNamespaces(const std::function<void(std::string_view Namespace, ZenCacheNamespace& Store)>& Callback) const;

	typedef std::unordered_map<std::string, std::unique_ptr<ZenCacheNamespace>> NamespaceMap;

	mutable RwLock									m_NamespacesLock;
	NamespaceMap									m_Namespaces;
	std::vector<std::unique_ptr<ZenCacheNamespace>> m_DroppedNamespaces;

	GcManager&	  m_Gc;
	Configuration m_Configuration;
};

void z$_forcelink();

}  // namespace zen