aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/projectstore/projectstore.h
blob: 77aa326811940c9d097f42b55578020f74527b96 (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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/compactbinarybuilder.h>
#include <zencore/compositebuffer.h>
#include <zencore/uid.h>
#include <zencore/xxhash.h>
#include <zenhttp/httpserver.h>
#include <zenstore/gc.h>

ZEN_THIRD_PARTY_INCLUDES_START
#include <tsl/robin_map.h>
ZEN_THIRD_PARTY_INCLUDES_END

#include <map>
#include <unordered_map>

namespace zen {

class CbPackage;
class CidStore;
class AuthMgr;
class ScrubContext;
class JobQueue;
class OpenProcessCache;

/** Project Store

	A project store consists of a number of Projects.

	Each project contains a number of oplogs (short for "operation log"). UE uses
	one oplog per target platform to store the output of the cook process.

	An oplog consists of a sequence of "op" entries. Each entry is a structured object
	containing references to attachments. Attachments are typically the serialized
	package data split into separate chunks for bulk data, exports and header
	information.
 */
class ProjectStore : public RefCounted, public GcStorage, public GcReferencer, public GcReferenceLocker
{
	struct OplogStorage;

public:
	struct Configuration
	{
	};

	ProjectStore(CidStore&			   Store,
				 std::filesystem::path BasePath,
				 GcManager&			   Gc,
				 JobQueue&			   JobQueue,
				 OpenProcessCache&	   InOpenProcessCache,
				 const Configuration&  Config);
	~ProjectStore();

	struct LogSequenceNumber
	{
		uint32_t Number = 0u;

		operator bool() const { return Number != 0u; };
		LogSequenceNumber() = default;
		explicit LogSequenceNumber(size_t InNumber) : Number(uint32_t(InNumber)) {}
					operator size_t() const { return Number; };
		inline auto operator<=>(const LogSequenceNumber& Other) const = default;

		struct Hasher
		{
			size_t operator()(const LogSequenceNumber& v) const { return std::hash<uint32_t>()(v.Number); }
		};
	};

	template<class V>
	using LsnMap = tsl::robin_map<LogSequenceNumber, V, LogSequenceNumber::Hasher>;

	struct OplogEntryAddress
	{
		uint32_t Offset;  // note: Multiple of m_OpsAlign!
		uint32_t Size;
	};

	struct OplogEntry
	{
		LogSequenceNumber OpLsn;
		OplogEntryAddress OpCoreAddress;
		uint32_t		  OpCoreHash;  // Used as checksum
		Oid				  OpKeyHash;
		uint32_t		  Reserved;

		inline bool IsTombstone() const { return OpCoreAddress.Offset == 0 && OpCoreAddress.Size == 0 && OpLsn.Number; }
		inline void MakeTombstone()
		{
			OpLsn				 = {};
			OpCoreAddress.Offset = OpCoreAddress.Size = OpCoreHash = Reserved = 0;
		}
	};

	static_assert(IsPow2(sizeof(OplogEntry)));

	struct Oplog : public RefCounted
	{
		enum class EMode
		{
			kBasicReadOnly,
			kFull
		};

		Oplog(const LoggerRef&			   Log,
			  std::string_view			   ProjectIdentifier,
			  std::string_view			   Id,
			  CidStore&					   Store,
			  const std::filesystem::path& BasePath,
			  const std::filesystem::path& MarkerPath,
			  EMode						   State);
		~Oplog();

		[[nodiscard]] static bool ExistsAt(const std::filesystem::path& BasePath);
		bool					  Exists() const;

		void Read();
		void Write();
		void Update(const std::filesystem::path& MarkerPath);
		bool Reset();
		bool CanUnload();

		struct ChunkInfo
		{
			Oid		 ChunkId;
			uint64_t ChunkSize;
		};

		struct Paging
		{
			int32_t Start = -1;
			int32_t Count = -1;
		};

		std::vector<ChunkInfo> GetAllChunksInfo(const std::filesystem::path& ProjectRootDir);
		void				   IterateChunkMap(std::function<void(const Oid&, const IoHash& Hash)>&& Fn);
		void   IterateFileMap(std::function<void(const Oid&, const std::string_view& ServerPath, const std::string_view& ClientPath)>&& Fn);
		void   IterateOplog(std::function<void(CbObjectView)>&& Fn, const Paging& EntryPaging);
		void   IterateOplogWithKey(std::function<void(LogSequenceNumber, const Oid&, CbObjectView)>&& Fn);
		void   IterateOplogWithKey(std::function<void(LogSequenceNumber, const Oid&, CbObjectView)>&& Fn, const Paging& EntryPaging);
		void   IterateOplogLocked(std::function<void(CbObjectView)>&& Fn, const Paging& EntryPaging);
		size_t GetOplogEntryCount() const;

		std::optional<CbObject> GetOpByKey(const Oid& Key);
		std::optional<CbObject> GetOpByIndex(LogSequenceNumber Index);
		LogSequenceNumber		GetOpIndexByKey(const Oid& Key);

		IoBuffer FindChunk(const std::filesystem::path& ProjectRootDir, const Oid& ChunkId, uint64_t* OptOutModificationTag);
		IoBuffer GetChunkByRawHash(const IoHash& RawHash);
		bool	 IterateChunks(std::span<IoHash>																  RawHashes,
							   bool																				  IncludeModTag,
							   const std::function<bool(size_t Index, const IoBuffer& Payload, uint64_t ModTag)>& AsyncCallback,
							   WorkerThreadPool*																  OptionalWorkerPool,
							   uint64_t																			  LargeSizeLimit);
		bool	 IterateChunks(const std::filesystem::path&														  ProjectRootDir,
							   std::span<Oid>																	  ChunkIds,
							   bool																				  IncludeModTag,
							   const std::function<bool(size_t Index, const IoBuffer& Payload, uint64_t ModTag)>& AsyncCallback,
							   WorkerThreadPool*																  OptionalWorkerPool,
							   uint64_t																			  LargeSizeLimit);

		/** Persist a new oplog entry
		 *
		 * Returns the oplog LSN assigned to the new entry, or an invalid number if the entry is rejected
		 */
		LogSequenceNumber			   AppendNewOplogEntry(CbPackage Op);
		LogSequenceNumber			   AppendNewOplogEntry(CbObjectView Core);
		std::vector<LogSequenceNumber> AppendNewOplogEntries(std::span<CbObjectView> Cores);

		const std::string& OplogId() const { return m_OplogId; }

		const std::filesystem::path& TempPath() const { return m_TempPath; }
		const std::filesystem::path& MarkerPath() const { return m_MarkerPath; }

		LoggerRef		Log() const { return m_Log; }
		void			Flush();
		void			Scrub(ScrubContext& Ctx);
		static uint64_t TotalSize(const std::filesystem::path& BasePath);
		uint64_t		TotalSize() const;

		std::size_t OplogCount() const
		{
			RwLock::SharedLockScope _(m_OplogLock);
			return m_OpToPayloadOffsetMap.size();
		}

		void ResetState();
		bool PrepareForDelete(std::filesystem::path& OutRemoveDirectory);

		void				EnableUpdateCapture();
		void				DisableUpdateCapture();
		void				CaptureAddedAttachments(std::span<const IoHash> AttachmentHashes);
		std::vector<IoHash> GetCapturedAttachmentsLocked();
		std::vector<IoHash> CheckPendingChunkReferences(std::span<const IoHash> ChunkHashes, const GcClock::Duration& RetainTime);
		void				RemovePendingChunkReferences(std::span<const IoHash> ChunkHashes);
		std::vector<IoHash> GetPendingChunkReferencesLocked();

		RwLock::SharedLockScope GetGcReferencerLock() { return RwLock::SharedLockScope(m_OplogLock); }

		uint32_t GetUnusedSpacePercent() const;
		void	 Compact(bool DryRun, bool RetainLSNs, std::string_view LogPrefix);

		void GetAttachmentsLocked(std::vector<IoHash>& OutAttachments, bool StoreMetaDataOnDisk);

		std::string_view GetOuterProjectIdentifier() const { return m_OuterProjectId; }
		void			 CompactIfUnusedExceeds(bool DryRun, uint32_t CompactUnusedThreshold, std::string_view LogPrefix);

		static std::optional<CbObject> ReadStateFile(const std::filesystem::path& BasePath, std::function<LoggerRef()>&& Log);

		struct ChunkMapping
		{
			Oid	   Id;
			IoHash Hash;
		};

		struct FileMapping
		{
			Oid			Id;
			IoHash		Hash;		 // This is either zero or a cid
			std::string ServerPath;	 // If Hash is valid then this should be empty
			std::string ClientPath;
		};

		struct ValidationResult
		{
			uint32_t								  OpCount = 0;
			LogSequenceNumber						  LSNLow;
			LogSequenceNumber						  LSNHigh;
			std::vector<std::pair<Oid, FileMapping>>  MissingFiles;
			std::vector<std::pair<Oid, ChunkMapping>> MissingChunks;
			std::vector<std::pair<Oid, ChunkMapping>> MissingMetas;
			std::vector<std::pair<Oid, IoHash>>		  MissingAttachments;
			std::vector<std::pair<Oid, std::string>>  OpKeys;

			bool IsEmpty() const
			{
				return MissingFiles.empty() && MissingChunks.empty() && MissingMetas.empty() && MissingAttachments.empty();
			}
		};

		ValidationResult Validate(const std::filesystem::path& ProjectRootDir,
								  std::atomic_bool&			   IsCancelledFlag,
								  WorkerThreadPool*			   OptionalWorkerPool);

	private:
		struct FileMapEntry
		{
			std::string ServerPath;
			std::string ClientPath;
		};

		template<class V>
		using OidMap = tsl::robin_map<Oid, V, Oid::Hasher>;

		LoggerRef					m_Log;
		const std::string			m_OuterProjectId;
		const std::string			m_OplogId;
		CidStore&					m_CidStore;
		const std::filesystem::path m_BasePath;
		std::filesystem::path		m_MarkerPath;
		const std::filesystem::path m_TempPath;
		const std::filesystem::path m_MetaPath;

		const EMode m_Mode;

		mutable RwLock		 m_OplogLock;
		OidMap<IoHash>		 m_ChunkMap;		 // output data chunk id -> CAS address
		OidMap<IoHash>		 m_MetaMap;			 // meta chunk id -> CAS address
		OidMap<FileMapEntry> m_FileMap;			 // file id -> file map entry
		int32_t				 m_ManifestVersion;	 // File system manifest version

		struct PayloadIndex
		{
			uint32_t Index = std::numeric_limits<uint32_t>::max();

			operator bool() const { return Index != std::numeric_limits<uint32_t>::max(); };
			PayloadIndex() = default;
			explicit PayloadIndex(size_t InIndex) : Index(uint32_t(InIndex)) {}
						operator size_t() const { return Index; };
			inline auto operator<=>(const PayloadIndex& Other) const = default;

			struct Hasher
			{
				size_t operator()(const PayloadIndex& v) const { return std::hash<uint32_t>()(v.Index); }
			};
		};

		struct OplogPayload
		{
			LogSequenceNumber Lsn;
			OplogEntryAddress Address;
		};

		OidMap<PayloadIndex>				  m_OpToPayloadOffsetMap;
		std::vector<OplogPayload>			  m_OpLogPayloads;
		std::unique_ptr<LsnMap<PayloadIndex>> m_LsnToPayloadOffsetMap;

		std::atomic<bool> m_MetaValid = false;

		uint32_t								   m_UpdateCaptureRefCounter = 0;
		std::unique_ptr<std::vector<Oid>>		   m_CapturedOps;
		std::unique_ptr<std::vector<IoHash>>	   m_CapturedAttachments;
		std::unordered_set<IoHash, IoHash::Hasher> m_PendingPrepOpAttachments;
		GcClock::TimePoint						   m_PendingPrepOpAttachmentsRetainEnd;

		RefPtr<OplogStorage> m_Storage;
		uint64_t			 m_LogFlushPosition = 0;
		bool				 m_IsLegacySnapshot = false;

		RefPtr<OplogStorage> GetStorage();

		/** Scan oplog and register each entry, thus updating the in-memory tracking tables
		 */
		uint32_t GetUnusedSpacePercentLocked() const;
		void	 WriteIndexSnapshot();
		void	 ReadIndexSnapshot();
		void	 RefreshLsnToPayloadOffsetMap(RwLock::ExclusiveLockScope&);

		struct OplogEntryMapping
		{
			std::vector<ChunkMapping> Chunks;
			std::vector<ChunkMapping> Meta;
			std::vector<FileMapping>  Files;
		};

		OplogEntryMapping GetMapping(CbObjectView Core);

		/** Update tracking metadata for a new oplog entry
		 *
		 * This is used during replay (and gets called as part of new op append)
		 *
		 * Returns the oplog LSN assigned to the new entry, or kInvalidOp if the entry is rejected
		 */
		LogSequenceNumber RegisterOplogEntry(RwLock::ExclusiveLockScope& OplogLock,
											 const OplogEntryMapping&	 OpMapping,
											 const OplogEntry&			 OpEntry);

		void AddFileMapping(const RwLock::ExclusiveLockScope& OplogLock,
							const Oid&						  FileId,
							const IoHash&					  Hash,
							std::string_view				  ServerPath,
							std::string_view				  ClientPath);
		void AddChunkMapping(const RwLock::ExclusiveLockScope& OplogLock, const Oid& ChunkId, const IoHash& Hash);
		void AddMetaMapping(const RwLock::ExclusiveLockScope& OplogLock, const Oid& ChunkId, const IoHash& Hash);
		void Compact(RwLock::ExclusiveLockScope& Lock, bool DryRun, bool RetainLSNs, std::string_view LogPrefix);
		void IterateCapturedOpsLocked(std::function<bool(const Oid& Key, LogSequenceNumber LSN, const CbObjectView& UpdateOp)>&& Callback);
		std::vector<PayloadIndex> GetSortedOpPayloadRangeLocked(
			const Paging&											 EntryPaging,
			tsl::robin_map<PayloadIndex, Oid, PayloadIndex::Hasher>* OutOptionalReverseKeyMap);

		friend class ProjectStoreOplogReferenceChecker;
		friend class ProjectStoreReferenceChecker;
		friend class ProjectStoreOplogReferenceValidator;
		friend struct OplogStorage;
	};

	struct Project : public RefCounted
	{
		std::string			  Identifier;
		std::filesystem::path RootDir;
		std::filesystem::path EngineRootDir;
		std::filesystem::path ProjectRootDir;
		std::filesystem::path ProjectFilePath;

		Ref<Oplog>				 NewOplog(std::string_view OplogId, const std::filesystem::path& MarkerPath);
		Ref<Oplog>				 OpenOplog(std::string_view OplogId, bool AllowCompact, bool VerifyPathOnDisk);
		Ref<Oplog>				 ReadOplog(std::string_view OplogId);
		bool					 TryUnloadOplog(std::string_view OplogId);
		bool					 DeleteOplog(std::string_view OplogId);
		bool					 RemoveOplog(std::string_view OplogId, std::filesystem::path& OutDeletePath);
		void					 IterateOplogs(std::function<void(const RwLock::SharedLockScope&, const Oplog&)>&& Fn) const;
		void					 IterateOplogs(std::function<void(const RwLock::SharedLockScope&, Oplog&)>&& Fn);
		std::vector<std::string> ScanForOplogs() const;
		bool					 IsExpired(const GcClock::TimePoint ExpireTime) const;
		bool					 IsExpired(const GcClock::TimePoint ExpireTime, const ProjectStore::Oplog& Oplog) const;
		bool					 IsExpired(const GcClock::TimePoint ExpireTime, std::string_view OplogId) const;
		bool					 IsOplogTouchedSince(const GcClock::TimePoint TouchTime, std::string_view Oplog) const;
		void					 TouchProject();
		void					 TouchOplog(std::string_view Oplog);
		GcClock::TimePoint		 LastOplogAccessTime(std::string_view Oplog) const;

		Project(ProjectStore* PrjStore, CidStore& Store, std::filesystem::path BasePath);
		virtual ~Project();

		void					  Read();
		void					  Write();
		[[nodiscard]] static bool Exists(const std::filesystem::path& BasePath);
		void					  Flush();
		void					  Scrub(ScrubContext& Ctx);
		LoggerRef				  Log() const;
		static uint64_t			  TotalSize(const std::filesystem::path& BasePath);
		uint64_t				  TotalSize() const;
		bool					  PrepareForDelete(std::filesystem::path& OutDeletePath);

		void					 EnableUpdateCapture();
		void					 DisableUpdateCapture();
		std::vector<std::string> GetCapturedOplogsLocked();

		std::vector<RwLock::SharedLockScope> GetGcReferencerLocks();

		void AddOplogToCompact(std::string_view OplogId)
		{
			m_OplogsToCompactLock.WithExclusiveLock([&]() { m_OplogsToCompact.insert(std::string(OplogId)); });
		}
		std::vector<std::string> GetOplogsToCompact()
		{
			std::vector<std::string> Result;
			m_OplogsToCompactLock.WithExclusiveLock([&]() {
				Result.reserve(m_OplogsToCompact.size());
				Result.insert(Result.end(), m_OplogsToCompact.begin(), m_OplogsToCompact.end());
				m_OplogsToCompact.clear();
			});
			return Result;
		}

	private:
		ProjectStore*									   m_ProjectStore;
		CidStore&										   m_CidStore;
		mutable RwLock									   m_ProjectLock;
		std::map<std::string, Ref<Oplog>>				   m_Oplogs;
		std::filesystem::path							   m_OplogStoragePath;
		mutable RwLock									   m_LastAccessTimesLock;
		mutable tsl::robin_map<std::string, GcClock::Tick> m_LastAccessTimes;
		uint32_t										   m_UpdateCaptureRefCounter = 0;
		std::unique_ptr<std::vector<std::string>>		   m_CapturedOplogs;

		RwLock							m_OplogsToCompactLock;
		std::unordered_set<std::string> m_OplogsToCompact;

		std::filesystem::path BasePathForOplog(std::string_view OplogId) const;
		bool IsExpired(const std::string& EntryName, const std::filesystem::path& MarkerPath, const GcClock::TimePoint ExpireTime) const;
		void WriteAccessTimes();
		void ReadAccessTimes();

		friend class ProjectStoreOplogReferenceChecker;
		friend class ProjectStoreReferenceChecker;
		friend class ProjectStoreOplogReferenceValidator;
		friend class ProjectStoreGcStoreCompactor;
	};

	Ref<Project> OpenProject(std::string_view ProjectId);
	Ref<Project> NewProject(const std::filesystem::path& BasePath,
							std::string_view			 ProjectId,
							const std::filesystem::path& RootDir,
							const std::filesystem::path& EngineRootDir,
							const std::filesystem::path& ProjectRootDir,
							const std::filesystem::path& ProjectFilePath);
	bool		 UpdateProject(std::string_view				ProjectId,
							   const std::filesystem::path& RootDir,
							   const std::filesystem::path& EngineRootDir,
							   const std::filesystem::path& ProjectRootDir,
							   const std::filesystem::path& ProjectFilePath);
	bool		 RemoveProject(std::string_view ProjectId, std::filesystem::path& OutDeletePath);
	bool		 DeleteProject(std::string_view ProjectId);
	bool		 Exists(std::string_view ProjectId);
	void		 Flush();
	void		 DiscoverProjects();
	void		 IterateProjects(std::function<void(Project& Prj)>&& Fn);

	LoggerRef					 Log() { return m_Log; }
	const std::filesystem::path& BasePath() const { return m_ProjectBasePath; }

	// GcStorage
	virtual void		  ScrubStorage(ScrubContext& Ctx) override;
	virtual GcStorageSize StorageSize() const override;

	virtual std::string						   GetGcName(GcCtx& Ctx) override;
	virtual GcStoreCompactor*				   RemoveExpiredData(GcCtx& Ctx, GcStats& Stats) override;
	virtual std::vector<GcReferenceChecker*>   CreateReferenceCheckers(GcCtx& Ctx) override;
	virtual std::vector<GcReferenceValidator*> CreateReferenceValidators(GcCtx& Ctx) override;

	virtual std::vector<RwLock::SharedLockScope> LockState(GcCtx& Ctx) override;

	CbArray			GetProjectsList();
	static CbObject GetProjectFiles(LoggerRef							   InLog,
									Project&							   Project,
									Oplog&								   Oplog,
									const std::unordered_set<std::string>& WantedFieldNames);

	static CbObject GetProjectChunkInfos(LoggerRef								InLog,
										 Project&								Project,
										 Oplog&									Oplog,
										 const std::unordered_set<std::string>& WantedFieldNames);
	static CbObject GetChunkInfo(LoggerRef InLog, Project& Project, Oplog& Oplog, const Oid& ChunkId);
	struct GetChunkRangeResult
	{
		enum class EError : uint8_t
		{
			Ok,
			NotFound,
			NotModified,
			MalformedContent,
			OutOfRange
		};
		EError			Error = EError(-1);
		std::string		ErrorDescription;
		CompositeBuffer Chunk		= CompositeBuffer();
		IoHash			RawHash		= IoHash::Zero;
		uint64_t		RawSize		= 0;
		ZenContentType	ContentType = ZenContentType::kUnknownContentType;
	};
	static GetChunkRangeResult GetChunkRange(LoggerRef		InLog,
											 Project&		Project,
											 Oplog&			Oplog,
											 const Oid&		ChunkId,
											 uint64_t		Offset,
											 uint64_t		Size,
											 ZenContentType AcceptType,
											 uint64_t*		OptionalInOutModificationTag);
	IoBuffer				   GetChunk(Project& Project, Oplog& Oplog, const IoHash& ChunkHash);

	IoBuffer GetChunk(const std::string_view ProjectId, const std::string_view OplogId, const Oid& ChunkId);

	IoBuffer GetChunk(const std::string_view ProjectId, const std::string_view OplogId, const IoHash& Cid);

	bool PutChunk(Project& Project, Oplog& Oplog, const IoHash& ChunkHash, IoBuffer&& Chunk);

	struct WriteOplogResult
	{
		int32_t				ErrorCode = 0;
		std::string			ErrorDescription;
		std::vector<IoHash> Need;
	};
	WriteOplogResult WriteOplog(Project& Project, Oplog& Oplog, const CbObject& ContainerObject);

	struct ReadOplogResult
	{
		int32_t		ErrorCode = 0;
		std::string ErrorDescription;
		CbObject	ContainerObject;
	};
	ReadOplogResult ReadOplog(Project& Project,
							  Oplog&   Oplog,
							  size_t   MaxBlockSize,
							  size_t   MaxChunkEmbedSize,
							  size_t   MaxChunksPerBlock,
							  size_t   ChunkFileSizeLimit);

	std::pair<HttpResponseCode, std::string> GetChunks(const std::string_view ProjectId,
													   const std::string_view OplogId,
													   const CbObject&		  RequestObject,
													   CbPackage&			  OutResponsePackage);

	bool Rpc(HttpServerRequest&		HttpReq,
			 const std::string_view ProjectId,
			 const std::string_view OplogId,
			 IoBuffer&&				Payload,
			 AuthMgr&				AuthManager);

	std::pair<HttpResponseCode, std::string> Export(Ref<Project> Project, Oplog& Oplog, CbObjectView&& Params, AuthMgr& AuthManager);

	std::pair<HttpResponseCode, std::string> Import(Project& Project, Oplog& Oplog, CbObjectView&& Params, AuthMgr& AuthManager);

	bool AreDiskWritesAllowed() const;

	void					 EnableUpdateCapture();
	void					 DisableUpdateCapture();
	std::vector<std::string> GetCapturedProjectsLocked();

private:
	LoggerRef								  m_Log;
	GcManager&								  m_Gc;
	CidStore&								  m_CidStore;
	JobQueue&								  m_JobQueue;
	OpenProcessCache&						  m_OpenProcessCache;
	std::filesystem::path					  m_ProjectBasePath;
	const Configuration						  m_Config;
	mutable RwLock							  m_ProjectsLock;
	std::map<std::string, Ref<Project>>		  m_Projects;
	const DiskWriteBlocker*					  m_DiskWriteBlocker		= nullptr;
	uint32_t								  m_UpdateCaptureRefCounter = 0;
	std::unique_ptr<std::vector<std::string>> m_CapturedProjects;

	std::filesystem::path BasePathForProject(std::string_view ProjectId);

	friend class ProjectStoreGcStoreCompactor;
	friend class ProjectStoreOplogReferenceChecker;
	friend class ProjectStoreReferenceChecker;
};

Oid ComputeOpKey(const CbObjectView& Op);

Oid OpKeyStringAsOid(std::string_view OpKey);

template<typename T>
Oid
OpKeyStringAsOid(std::string_view OpKey, T& TmpBuffer)
{
	using namespace std::literals;

	CbObjectWriter Writer;
	Writer << "key"sv << OpKey;
	Writer.Finalize();
	TmpBuffer.resize(Writer.GetSaveSize());
	MutableMemoryView SaveBuffer(MutableMemoryView(TmpBuffer.data(), TmpBuffer.size()));

	const Oid OpId = ComputeOpKey(Writer.Save(SaveBuffer).AsObjectView());

	return OpId;
}

void prj_forcelink();

}  // namespace zen