aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/filebuildstorage.cpp
blob: cee9cbfc4020e330ebd225a583e8486005206394 (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
608
609
610
611
612
613
614
615
616
617
618
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenutil/filebuildstorage.h>

#include <zencore/basicfile.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinaryvalidation.h>
#include <zencore/fmtutils.h>
#include <zencore/scopeguard.h>
#include <zencore/timer.h>

namespace zen {

using namespace std::literals;

class FileBuildStorage : public BuildStorage
{
public:
	explicit FileBuildStorage(const std::filesystem::path& StoragePath,
							  BuildStorage::Statistics&	   Stats,
							  bool						   EnableJsonOutput,
							  double					   LatencySec,
							  double					   DelayPerKBSec)
	: m_StoragePath(StoragePath)
	, m_Stats(Stats)
	, m_EnableJsonOutput(EnableJsonOutput)
	, m_LatencySec(LatencySec)
	, m_DelayPerKBSec(DelayPerKBSec)
	{
		CreateDirectories(GetBuildsFolder());
		CreateDirectories(GetBlobsFolder());
		CreateDirectories(GetBlobsMetadataFolder());
	}

	virtual ~FileBuildStorage() {}

	virtual CbObject ListBuilds(CbObject Query) override
	{
		ZEN_UNUSED(Query);

		SimulateLatency(Query.GetSize(), 0);

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BuildFolder = GetBuildsFolder();
		DirectoryContent			Content;
		GetDirectoryContent(BuildFolder, DirectoryContentFlags::IncludeDirs, Content);
		CbObjectWriter Writer;
		Writer.BeginArray("results");
		{
			for (const std::filesystem::path& BuildPath : Content.Directories)
			{
				Oid BuildId = Oid::TryFromHexString(BuildPath.stem().string());
				if (BuildId != Oid::Zero)
				{
					Writer.BeginObject();
					{
						Writer.AddObjectId("buildId", BuildId);
						Writer.AddObject("metadata", ReadBuild(BuildId)["metadata"sv].AsObjectView());
					}
					Writer.EndObject();
				}
			}
		}
		Writer.EndArray();	// builds
		Writer.Save();
		SimulateLatency(Writer.GetSaveSize(), 0);
		return Writer.Save();
	}

	virtual CbObject PutBuild(const Oid& BuildId, const CbObject& MetaData) override
	{
		SimulateLatency(MetaData.GetSize(), 0);

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		CbObjectWriter BuildObject;
		BuildObject.AddObject("metadata", MetaData);
		BuildObject.AddInteger("chunkSize"sv, 32u * 1024u * 1024u);
		WriteBuild(BuildId, BuildObject.Save());

		CbObjectWriter BuildResponse;
		BuildResponse.AddInteger("chunkSize"sv, 32u * 1024u * 1024u);
		BuildResponse.Save();

		SimulateLatency(0, BuildResponse.GetSaveSize());
		return BuildResponse.Save();
	}

	virtual CbObject GetBuild(const Oid& BuildId) override
	{
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		CbObject Build = ReadBuild(BuildId);
		SimulateLatency(0, Build.GetSize());
		return Build;
	}

	virtual void FinalizeBuild(const Oid& BuildId) override
	{
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		ZEN_UNUSED(BuildId);
		SimulateLatency(0, 0);
	}

	virtual std::pair<IoHash, eastl::vector<IoHash>> PutBuildPart(const Oid&	   BuildId,
																  const Oid&	   BuildPartId,
																  std::string_view PartName,
																  const CbObject&  MetaData) override
	{
		SimulateLatency(MetaData.GetSize(), 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BuildPartDataPath = GetBuildPartPath(BuildId, BuildPartId);
		CreateDirectories(BuildPartDataPath.parent_path());

		TemporaryFile::SafeWriteFile(BuildPartDataPath, MetaData.GetView());
		m_WrittenBytes += MetaData.GetSize();
		WriteAsJson(BuildPartDataPath, MetaData);

		IoHash RawHash = IoHash::HashBuffer(MetaData.GetView());

		CbObjectWriter Writer;
		{
			CbObject	 BuildObject  = ReadBuild(BuildId);
			CbObjectView PartsObject  = BuildObject["parts"sv].AsObjectView();
			CbObjectView MetaDataView = BuildObject["metadata"sv].AsObjectView();

			Writer.AddObject("metadata"sv, MetaDataView);
			Writer.BeginObject("parts"sv);
			{
				for (CbFieldView PartView : PartsObject)
				{
					if (PartView.GetName() != PartName)
					{
						Writer.AddObjectId(PartView.GetName(), PartView.AsObjectId());
					}
				}
				Writer.AddObjectId(PartName, BuildPartId);
			}
			Writer.EndObject();	 // parts
		}
		WriteBuild(BuildId, Writer.Save());

		eastl::vector<IoHash> NeededAttachments = GetNeededAttachments(MetaData);

		SimulateLatency(0, sizeof(IoHash) * NeededAttachments.size());

		return std::make_pair(RawHash, std::move(NeededAttachments));
	}

	virtual CbObject GetBuildPart(const Oid& BuildId, const Oid& BuildPartId) override
	{
		SimulateLatency(0, 0);

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BuildPartDataPath = GetBuildPartPath(BuildId, BuildPartId);

		IoBuffer Payload = ReadFile(BuildPartDataPath).Flatten();
		m_Stats.TotalBytesRead += Payload.GetSize();

		ZEN_ASSERT(ValidateCompactBinary(Payload.GetView(), CbValidateMode::Default) == CbValidateError::None);

		CbObject BuildPartObject = CbObject(SharedBuffer(Payload));

		SimulateLatency(0, BuildPartObject.GetSize());

		return BuildPartObject;
	}

	virtual eastl::vector<IoHash> FinalizeBuildPart(const Oid& BuildId, const Oid& BuildPartId, const IoHash& PartHash) override
	{
		SimulateLatency(0, 0);

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BuildPartDataPath = GetBuildPartPath(BuildId, BuildPartId);
		IoBuffer					Payload			  = ReadFile(BuildPartDataPath).Flatten();
		m_Stats.TotalBytesRead += Payload.GetSize();
		IoHash RawHash = IoHash::HashBuffer(Payload.GetView());
		if (RawHash != PartHash)
		{
			throw std::runtime_error(
				fmt::format("Failed finalizing build part {}: Expected hash {}, got {}", BuildPartId, PartHash, RawHash));
		}

		CbObject			  BuildPartObject = CbObject(SharedBuffer(Payload));
		eastl::vector<IoHash> NeededAttachments(GetNeededAttachments(BuildPartObject));

		SimulateLatency(0, NeededAttachments.size() * sizeof(IoHash));

		return NeededAttachments;
	}

	virtual void PutBuildBlob(const Oid&			 BuildId,
							  const IoHash&			 RawHash,
							  ZenContentType		 ContentType,
							  const CompositeBuffer& Payload) override
	{
		ZEN_UNUSED(BuildId);
		ZEN_ASSERT(ContentType == ZenContentType::kCompressedBinary);
		SimulateLatency(Payload.GetSize(), 0);

		ZEN_ASSERT_SLOW(ValidateCompressedBuffer(RawHash, Payload));

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BlockPath = GetBlobPayloadPath(RawHash);
		if (!std::filesystem::is_regular_file(BlockPath))
		{
			CreateDirectories(BlockPath.parent_path());
			TemporaryFile::SafeWriteFile(BlockPath, Payload.Flatten().GetView());
		}
		m_Stats.TotalBytesWritten += Payload.GetSize();
		SimulateLatency(0, 0);
	}

	virtual eastl::vector<std::function<void()>> PutLargeBuildBlob(const Oid&												 BuildId,
																   const IoHash&											 RawHash,
																   ZenContentType											 ContentType,
																   uint64_t													 PayloadSize,
																   std::function<IoBuffer(uint64_t Offset, uint64_t Size)>&& Transmitter,
																   std::function<void(uint64_t, bool)>&& OnSentBytes) override
	{
		ZEN_UNUSED(BuildId);
		ZEN_UNUSED(ContentType);
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BlockPath = GetBlobPayloadPath(RawHash);
		if (!std::filesystem::is_regular_file(BlockPath))
		{
			CreateDirectories(BlockPath.parent_path());

			struct WorkloadData
			{
				std::function<IoBuffer(uint64_t Offset, uint64_t Size)> Transmitter;
				std::function<void(uint64_t, bool)>						OnSentBytes;
				TemporaryFile											TempFile;
				std::atomic<size_t>										PartsLeft;
			};

			std::shared_ptr<WorkloadData> Workload(std::make_shared<WorkloadData>());
			Workload->Transmitter = std::move(Transmitter);
			Workload->OnSentBytes = std::move(OnSentBytes);
			std::error_code Ec;
			Workload->TempFile.CreateTemporary(BlockPath.parent_path(), Ec);

			if (Ec)
			{
				throw std::runtime_error(
					fmt::format("Failed opening temporary file '{}': {} ({})", Workload->TempFile.GetPath(), Ec.message(), Ec.value()));
			}

			eastl::vector<std::function<void()>> WorkItems;
			uint64_t							 Offset = 0;
			while (Offset < PayloadSize)
			{
				uint64_t Size = Min(32u * 1024u * 1024u, PayloadSize - Offset);

				WorkItems.push_back([this, RawHash, BlockPath, Workload, Offset, Size]() {
					IoBuffer PartPayload = Workload->Transmitter(Offset, Size);
					SimulateLatency(PartPayload.GetSize(), 0);

					std::error_code Ec;
					Workload->TempFile.Write(PartPayload, Offset, Ec);
					if (Ec)
					{
						throw std::runtime_error(fmt::format("Failed writing to temporary file '{}': {} ({})",
															 Workload->TempFile.GetPath(),
															 Ec.message(),
															 Ec.value()));
					}
					uint64_t BytesWritten = PartPayload.GetSize();
					m_Stats.TotalBytesWritten += BytesWritten;
					const bool IsLastPart = Workload->PartsLeft.fetch_sub(1) == 1;
					if (IsLastPart)
					{
						Workload->TempFile.Flush();
						ZEN_ASSERT_SLOW(ValidateCompressedBuffer(RawHash, CompositeBuffer(Workload->TempFile.ReadAll())));
						Workload->TempFile.MoveTemporaryIntoPlace(BlockPath, Ec);
						if (Ec)
						{
							throw std::runtime_error(fmt::format("Failed moving temporary file '{}' to '{}': {} ({})",
																 Workload->TempFile.GetPath(),
																 BlockPath,
																 Ec.message(),
																 Ec.value()));
						}
					}
					Workload->OnSentBytes(BytesWritten, IsLastPart);
					SimulateLatency(0, 0);
				});

				Offset += Size;
			}
			Workload->PartsLeft.store(WorkItems.size());

			SimulateLatency(0, 0);
			return WorkItems;
		}
		SimulateLatency(0, 0);
		return {};
	}

	virtual IoBuffer GetBuildBlob(const Oid& BuildId, const IoHash& RawHash) override
	{
		ZEN_UNUSED(BuildId);
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BlockPath = GetBlobPayloadPath(RawHash);
		if (std::filesystem::is_regular_file(BlockPath))
		{
			BasicFile File(BlockPath, BasicFile::Mode::kRead);
			IoBuffer  Payload = File.ReadAll();
			ZEN_ASSERT_SLOW(ValidateCompressedBuffer(RawHash, CompositeBuffer(SharedBuffer(Payload))));
			m_Stats.TotalBytesRead += Payload.GetSize();
			Payload.SetContentType(ZenContentType::kCompressedBinary);
			SimulateLatency(0, Payload.GetSize());
			return Payload;
		}
		SimulateLatency(0, 0);
		return IoBuffer{};
	}

	virtual eastl::vector<std::function<void()>> GetLargeBuildBlob(
		const Oid&																			   BuildId,
		const IoHash&																		   RawHash,
		uint64_t																			   ChunkSize,
		std::function<void(uint64_t Offset, const IoBuffer& Chunk, uint64_t BytesRemaining)>&& Receiver) override
	{
		ZEN_UNUSED(BuildId);
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BlockPath = GetBlobPayloadPath(RawHash);
		if (std::filesystem::is_regular_file(BlockPath))
		{
			struct WorkloadData
			{
				std::atomic<uint64_t>																 BytesRemaining;
				BasicFile																			 BlobFile;
				std::function<void(uint64_t Offset, const IoBuffer& Chunk, uint64_t BytesRemaining)> Receiver;
			};

			std::shared_ptr<WorkloadData> Workload(std::make_shared<WorkloadData>());
			Workload->BlobFile.Open(BlockPath, BasicFile::Mode::kRead);
			const uint64_t BlobSize = Workload->BlobFile.FileSize();

			Workload->Receiver		 = std::move(Receiver);
			Workload->BytesRemaining = BlobSize;

			eastl::vector<std::function<void()>> WorkItems;
			uint64_t							 Offset = 0;
			while (Offset < BlobSize)
			{
				uint64_t Size = Min(ChunkSize, BlobSize - Offset);
				WorkItems.push_back([this, BlockPath, Workload, Offset, Size]() {
					SimulateLatency(0, 0);
					IoBuffer PartPayload(Size);
					Workload->BlobFile.Read(PartPayload.GetMutableView().GetData(), Size, Offset);
					m_Stats.TotalBytesRead += PartPayload.GetSize();
					uint64_t ByteRemaning = Workload->BytesRemaining.fetch_sub(Size);
					Workload->Receiver(Offset, PartPayload, ByteRemaning);
					SimulateLatency(Size, PartPayload.GetSize());
				});

				Offset += Size;
			}
			SimulateLatency(0, 0);
			return WorkItems;
		}
		return {};
	}

	virtual void PutBlockMetadata(const Oid& BuildId, const IoHash& BlockRawHash, const CbObject& MetaData) override
	{
		ZEN_UNUSED(BuildId);

		SimulateLatency(MetaData.GetSize(), 0);

		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		const std::filesystem::path BlockMetaDataPath = GetBlobMetadataPath(BlockRawHash);
		CreateDirectories(BlockMetaDataPath.parent_path());
		TemporaryFile::SafeWriteFile(BlockMetaDataPath, MetaData.GetView());
		m_Stats.TotalBytesWritten += MetaData.GetSize();
		WriteAsJson(BlockMetaDataPath, MetaData);
		SimulateLatency(0, 0);
	}

	virtual eastl::vector<ChunkBlockDescription> FindBlocks(const Oid& BuildId) override
	{
		ZEN_UNUSED(BuildId);
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		DirectoryContent Content;
		GetDirectoryContent(GetBlobsMetadataFolder(), DirectoryContentFlags::IncludeFiles, Content);
		eastl::vector<ChunkBlockDescription> Result;
		for (const std::filesystem::path& MetaDataFile : Content.Files)
		{
			IoHash ChunkHash;
			if (IoHash::TryParse(MetaDataFile.stem().string(), ChunkHash))
			{
				std::filesystem::path BlockPath = GetBlobPayloadPath(ChunkHash);
				if (std::filesystem::is_regular_file(BlockPath))
				{
					IoBuffer BlockMetaDataPayload = ReadFile(MetaDataFile).Flatten();

					m_Stats.TotalBytesRead += BlockMetaDataPayload.GetSize();

					CbObject BlockObject = CbObject(SharedBuffer(BlockMetaDataPayload));
					Result.emplace_back(ParseChunkBlockDescription(BlockObject));
				}
			}
		}
		SimulateLatency(0, sizeof(IoHash) * Result.size());
		return Result;
	}

	virtual eastl::vector<ChunkBlockDescription> GetBlockMetadata(const Oid& BuildId, eastl::span<const IoHash> BlockHashes) override
	{
		ZEN_UNUSED(BuildId);
		SimulateLatency(0, 0);
		Stopwatch ExecutionTimer;
		auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });
		m_Stats.TotalRequestCount++;

		eastl::vector<ChunkBlockDescription> Result;
		for (const IoHash& BlockHash : BlockHashes)
		{
			std::filesystem::path MetaDataFile = GetBlobMetadataPath(BlockHash);
			if (std::filesystem::is_regular_file(MetaDataFile))
			{
				IoBuffer BlockMetaDataPayload = ReadFile(MetaDataFile).Flatten();

				m_Stats.TotalBytesRead += BlockMetaDataPayload.GetSize();

				CbObject BlockObject = CbObject(SharedBuffer(BlockMetaDataPayload));
				Result.emplace_back(ParseChunkBlockDescription(BlockObject));
			}
		}
		SimulateLatency(sizeof(BlockHashes) * BlockHashes.size(), sizeof(ChunkBlockDescription) * Result.size());
		return Result;
	}

protected:
	std::filesystem::path GetBuildsFolder() const { return m_StoragePath / "builds"; }
	std::filesystem::path GetBlobsFolder() const { return m_StoragePath / "blobs"; }
	std::filesystem::path GetBlobsMetadataFolder() const { return m_StoragePath / "blocks"; }
	std::filesystem::path GetBuildFolder(const Oid& BuildId) const { return GetBuildsFolder() / BuildId.ToString(); }

	std::filesystem::path GetBuildPath(const Oid& BuildId) const { return GetBuildFolder(BuildId) / "metadata.cb"; }

	std::filesystem::path GetBuildPartFolder(const Oid& BuildId, const Oid& BuildPartId) const
	{
		return GetBuildFolder(BuildId) / "parts" / BuildPartId.ToString();
	}

	std::filesystem::path GetBuildPartPath(const Oid& BuildId, const Oid& BuildPartId) const
	{
		return GetBuildPartFolder(BuildId, BuildPartId) / "metadata.cb";
	}

	std::filesystem::path GetBlobPayloadPath(const IoHash& RawHash) const { return GetBlobsFolder() / fmt::format("{}.cbz", RawHash); }

	std::filesystem::path GetBlobMetadataPath(const IoHash& RawHash) const
	{
		return GetBlobsMetadataFolder() / fmt::format("{}.cb", RawHash);
	}

	void SimulateLatency(uint64_t ReceiveSize, uint64_t SendSize)
	{
		double SleepSec = m_LatencySec;
		if (m_DelayPerKBSec > 0.0)
		{
			SleepSec += m_DelayPerKBSec * (double(SendSize + ReceiveSize) / 1024u);
		}
		if (SleepSec > 0)
		{
			Sleep(int(SleepSec * 1000));
		}
	}

	void WriteAsJson(const std::filesystem::path& OriginalPath, CbObjectView Data) const
	{
		if (m_EnableJsonOutput)
		{
			ExtendableStringBuilder<128> SB;
			CompactBinaryToJson(Data, SB);
			std::filesystem::path JsonPath = OriginalPath;
			JsonPath.replace_extension(".json");
			std::string_view JsonMetaData = SB.ToView();
			TemporaryFile::SafeWriteFile(JsonPath, MemoryView(JsonMetaData.data(), JsonMetaData.length()));
		}
	}

	void WriteBuild(const Oid& BuildId, CbObjectView Data)
	{
		const std::filesystem::path BuildDataPath = GetBuildPath(BuildId);
		CreateDirectories(BuildDataPath.parent_path());
		TemporaryFile::SafeWriteFile(BuildDataPath, Data.GetView());
		m_Stats.TotalBytesWritten += Data.GetSize();
		WriteAsJson(BuildDataPath, Data);
	}

	CbObject ReadBuild(const Oid& BuildId)
	{
		const std::filesystem::path BuildDataPath = GetBuildPath(BuildId);
		FileContents				Content		  = ReadFile(BuildDataPath);
		if (Content.ErrorCode)
		{
			throw std::runtime_error(fmt::format("Failed reading build '{}' from '{}': {} ({})",
												 BuildId,
												 BuildDataPath,
												 Content.ErrorCode.message(),
												 Content.ErrorCode.value()));
		}
		IoBuffer Payload = Content.Flatten();
		m_Stats.TotalBytesRead += Payload.GetSize();
		ZEN_ASSERT(ValidateCompactBinary(Payload.GetView(), CbValidateMode::Default) == CbValidateError::None);
		CbObject BuildObject = CbObject(SharedBuffer(Payload));
		return BuildObject;
	}

	eastl::vector<IoHash> GetNeededAttachments(CbObjectView BuildPartObject)
	{
		eastl::vector<IoHash> NeededAttachments;
		BuildPartObject.IterateAttachments([&](CbFieldView FieldView) {
			const IoHash				AttachmentHash = FieldView.AsBinaryAttachment();
			const std::filesystem::path BlockPath	   = GetBlobPayloadPath(AttachmentHash);
			if (!std::filesystem::is_regular_file(BlockPath))
			{
				NeededAttachments.push_back(AttachmentHash);
			}
		});
		return NeededAttachments;
	}

	bool ValidateCompressedBuffer(const IoHash& RawHash, const CompositeBuffer& Payload)
	{
		IoHash			 VerifyHash;
		uint64_t		 VerifySize;
		CompressedBuffer ValidateBuffer = CompressedBuffer::FromCompressed(Payload, VerifyHash, VerifySize);
		if (!ValidateBuffer)
		{
			return false;
		}
		if (VerifyHash != RawHash)
		{
			return false;
		}
		CompositeBuffer Decompressed = ValidateBuffer.DecompressToComposite();
		if (!Decompressed)
		{
			return false;
		}
		IoHash Hash = IoHash::HashBuffer(Decompressed);
		if (Hash != RawHash)
		{
			return false;
		}
		return true;
	}

private:
	const std::filesystem::path m_StoragePath;
	BuildStorage::Statistics&	m_Stats;
	const bool					m_EnableJsonOutput = false;
	std::atomic<uint64_t>		m_WrittenBytes;

	const double m_LatencySec	 = 0.0;
	const double m_DelayPerKBSec = 0.0;
};

std::unique_ptr<BuildStorage>
CreateFileBuildStorage(const std::filesystem::path& StoragePath,
					   BuildStorage::Statistics&	Stats,
					   bool							EnableJsonOutput,
					   double						LatencySec,
					   double						DelayPerKBSec)
{
	return std::make_unique<FileBuildStorage>(StoragePath, Stats, EnableJsonOutput, LatencySec, DelayPerKBSec);
}

}  // namespace zen