aboutsummaryrefslogtreecommitdiff
path: root/src/zenremotestore/builds/buildstoragecache.cpp
blob: 00765903dcffa56ae3164a2521d2ee49197ffd31 (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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenremotestore/builds/buildstoragecache.h>

#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinaryvalidation.h>
#include <zencore/fmtutils.h>
#include <zencore/scopeguard.h>
#include <zencore/timer.h>
#include <zencore/trace.h>
#include <zencore/workthreadpool.h>
#include <zenhttp/httpclient.h>
#include <zenhttp/packageformat.h>

ZEN_THIRD_PARTY_INCLUDES_START
#include <tsl/robin_map.h>
#include <tsl/robin_set.h>
ZEN_THIRD_PARTY_INCLUDES_END

namespace zen {

using namespace std::literals;

class ZenBuildStorageCache : public BuildStorageCache
{
public:
	explicit ZenBuildStorageCache(HttpClient&					 HttpClient,
								  BuildStorageCache::Statistics& Stats,
								  std::string_view				 Namespace,
								  std::string_view				 Bucket,
								  const std::filesystem::path&	 TempFolderPath,
								  WorkerThreadPool&				 BackgroundWorkerPool)
	: m_HttpClient(HttpClient)
	, m_Stats(Stats)
	, m_Namespace(Namespace.empty() ? "none" : Namespace)
	, m_Bucket(Bucket.empty() ? "none" : Bucket)
	, m_TempFolderPath(std::filesystem::path(TempFolderPath).make_preferred())
	, m_BackgroundWorkPool(BackgroundWorkerPool)
	, m_PendingBackgroundWorkCount(1)
	, m_CancelBackgroundWork(false)
	{
	}

	virtual ~ZenBuildStorageCache()
	{
		try
		{
			m_CancelBackgroundWork.store(true);
			if (!IsFlushed)
			{
				m_PendingBackgroundWorkCount.CountDown();
				m_PendingBackgroundWorkCount.Wait();
			}
		}
		catch (const std::exception& Ex)
		{
			ZEN_ERROR("~ZenBuildStorageCache() failed with: {}", Ex.what());
		}
	}

	void ScheduleBackgroundWork(std::function<void()>&& Work)
	{
		m_PendingBackgroundWorkCount.AddCount(1);
		try
		{
			m_BackgroundWorkPool.ScheduleWork(
				[this, Work = std::move(Work)]() {
					ZEN_TRACE_CPU("ZenBuildStorageCache::BackgroundWork");
					auto _ = MakeGuard([this]() { m_PendingBackgroundWorkCount.CountDown(); });
					if (!m_CancelBackgroundWork)
					{
						try
						{
							Work();
						}
						catch (const std::exception& Ex)
						{
							ZEN_ERROR("Failed executing background upload to build cache. Reason: {}", Ex.what());
						}
					}
				},
				WorkerThreadPool::EMode::EnableBacklog);
		}
		catch (const std::exception& Ex)
		{
			m_PendingBackgroundWorkCount.CountDown();
			ZEN_ERROR("Failed scheduling background upload to build cache. Reason: {}", Ex.what());
		}
	}

	virtual void PutBuildBlob(const Oid&			 BuildId,
							  const IoHash&			 RawHash,
							  ZenContentType		 ContentType,
							  const CompositeBuffer& Payload) override
	{
		ZEN_ASSERT(!IsFlushed);
		ZEN_ASSERT(ContentType == ZenContentType::kCompressedBinary);

		// Move all segments in Payload to be file handle based so if Payload is materialized it does not affect buffers in queue
		std::vector<SharedBuffer>	  FileBasedSegments;
		std::span<const SharedBuffer> Segments = Payload.GetSegments();
		FileBasedSegments.reserve(Segments.size());
		{
			tsl::robin_map<void*, std::filesystem::path> HandleToPath;
			for (const SharedBuffer& Segment : Segments)
			{
				std::filesystem::path FilePath;
				IoBufferFileReference Ref;
				if (Segment.AsIoBuffer().GetFileReference(Ref))
				{
					if (auto It = HandleToPath.find(Ref.FileHandle); It != HandleToPath.end())
					{
						FilePath = It->second;
					}
					else
					{
						std::error_code		  Ec;
						std::filesystem::path Path = PathFromHandle(Ref.FileHandle, Ec);
						if (!Ec && !Path.empty())
						{
							HandleToPath.insert_or_assign(Ref.FileHandle, Path);
							FilePath = std::move(Path);
						}
					}
				}

				if (!FilePath.empty())
				{
					IoBuffer BufferFromFile = IoBufferBuilder::MakeFromFile(FilePath, Ref.FileChunkOffset, Ref.FileChunkSize);
					if (BufferFromFile)
					{
						FileBasedSegments.push_back(SharedBuffer(std::move(BufferFromFile)));
					}
					else
					{
						FileBasedSegments.push_back(Segment);
					}
				}
				else
				{
					FileBasedSegments.push_back(Segment);
				}
			}
		}

		CompositeBuffer FilePayload(std::move(FileBasedSegments));

		ScheduleBackgroundWork([this, BuildId = Oid(BuildId), RawHash = IoHash(RawHash), ContentType, Payload = std::move(FilePayload)]() {
			ZEN_TRACE_CPU("ZenBuildStorageCache::PutBuildBlob");
			Stopwatch ExecutionTimer;
			auto	  _ = MakeGuard([&]() { m_Stats.TotalExecutionTimeUs += ExecutionTimer.GetElapsedTimeUs(); });

			HttpClient::Response CacheResponse =
				m_HttpClient.Upload(fmt::format("/builds/{}/{}/{}/blobs/{}", m_Namespace, m_Bucket, BuildId, RawHash),
									Payload,
									ContentType);

			m_Stats.PutBlobCount++;
			m_Stats.PutBlobByteCount += Payload.GetSize();

			AddStatistic(CacheResponse);
			if (!CacheResponse.IsSuccess())
			{
				ZEN_DEBUG("Failed posting blob to cache: {}", CacheResponse.ErrorMessage(""sv));
			}
		});
	}

	virtual IoBuffer GetBuildBlob(const Oid& BuildId, const IoHash& RawHash, uint64_t RangeOffset, uint64_t RangeBytes) override
	{
		ZEN_TRACE_CPU("ZenBuildStorageCache::GetBuildBlob");

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

		HttpClient::KeyValueMap Headers;
		if (RangeOffset != 0 || RangeBytes != (uint64_t)-1)
		{
			Headers.Entries.insert({"Range", fmt::format("bytes={}-{}", RangeOffset, RangeOffset + RangeBytes - 1)});
		}
		CreateDirectories(m_TempFolderPath);
		HttpClient::Response CacheResponse =
			m_HttpClient.Download(fmt::format("/builds/{}/{}/{}/blobs/{}", m_Namespace, m_Bucket, BuildId, RawHash),
								  m_TempFolderPath,
								  Headers);
		AddStatistic(CacheResponse);
		if (CacheResponse.IsSuccess())
		{
			return CacheResponse.ResponsePayload;
		}
		return {};
	}

	virtual BuildBlobRanges GetBuildBlobRanges(const Oid&									  BuildId,
											   const IoHash&								  RawHash,
											   std::span<const std::pair<uint64_t, uint64_t>> Ranges) override
	{
		ZEN_TRACE_CPU("ZenBuildStorageCache::GetBuildBlobRanges");

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

		CbObjectWriter Writer;
		Writer.BeginArray("ranges"sv);
		{
			for (const std::pair<uint64_t, uint64_t>& Range : Ranges)
			{
				Writer.BeginObject();
				{
					Writer.AddInteger("offset"sv, Range.first);
					Writer.AddInteger("length"sv, Range.second);
				}
				Writer.EndObject();
			}
		}
		Writer.EndArray();	// ranges

		CreateDirectories(m_TempFolderPath);
		HttpClient::Response CacheResponse =
			m_HttpClient.Post(fmt::format("/builds/{}/{}/{}/blobs/{}", m_Namespace, m_Bucket, BuildId, RawHash),
							  Writer.Save(),
							  HttpClient::Accept(ZenContentType::kCbPackage));
		AddStatistic(CacheResponse);
		if (CacheResponse.IsSuccess())
		{
			CbPackage	 ResponsePackage = ParsePackageMessage(CacheResponse.ResponsePayload);
			CbObjectView ResponseObject	 = ResponsePackage.GetObject();

			CbArrayView RangeArray = ResponseObject["ranges"sv].AsArrayView();

			std::vector<std::pair<uint64_t, uint64_t>> ReceivedRanges;
			ReceivedRanges.reserve(RangeArray.Num());

			uint64_t OffsetInPayloadRanges = 0;

			for (CbFieldView View : RangeArray)
			{
				CbObjectView RangeView = View.AsObjectView();
				uint64_t	 Offset	   = RangeView["offset"sv].AsUInt64();
				uint64_t	 Length	   = RangeView["length"sv].AsUInt64();

				const std::pair<uint64_t, uint64_t>& Range = Ranges[ReceivedRanges.size()];

				if (Offset != Range.first || Length != Range.second)
				{
					return {};
				}
				ReceivedRanges.push_back(std::make_pair(OffsetInPayloadRanges, Length));
				OffsetInPayloadRanges += Length;
			}

			const CbAttachment* DataAttachment = ResponsePackage.FindAttachment(RawHash);
			if (DataAttachment)
			{
				SharedBuffer PayloadRanges = DataAttachment->AsBinary();
				return BuildBlobRanges{.PayloadBuffer = PayloadRanges.AsIoBuffer(), .Ranges = std::move(ReceivedRanges)};
			}
		}
		return {};
	}

	virtual void PutBlobMetadatas(const Oid& BuildId, std::span<const IoHash> BlobHashes, std::span<const CbObject> MetaDatas) override
	{
		ZEN_ASSERT(!IsFlushed);
		ScheduleBackgroundWork([this,
								BuildId		  = Oid(BuildId),
								BlobRawHashes = std::vector<IoHash>(BlobHashes.begin(), BlobHashes.end()),
								MetaDatas	  = std::vector<CbObject>(MetaDatas.begin(), MetaDatas.end())]() {
			ZEN_TRACE_CPU("ZenBuildStorageCache::PutBlobMetadatas");

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

			const uint64_t BlobCount = BlobRawHashes.size();

			CbPackage							   RequestPackage;
			std::vector<CbAttachment>			   Attachments;
			tsl::robin_set<IoHash, IoHash::Hasher> AttachmentHashes;
			Attachments.reserve(BlobCount);
			AttachmentHashes.reserve(BlobCount);
			{
				CbObjectWriter RequestWriter;
				RequestWriter.BeginArray("blobHashes");
				for (size_t BlockHashIndex = 0; BlockHashIndex < BlobRawHashes.size(); BlockHashIndex++)
				{
					RequestWriter.AddHash(BlobRawHashes[BlockHashIndex]);
				}
				RequestWriter.EndArray();  // blobHashes

				RequestWriter.BeginArray("metadatas");
				for (size_t BlockHashIndex = 0; BlockHashIndex < BlobRawHashes.size(); BlockHashIndex++)
				{
					const IoHash ObjectHash = MetaDatas[BlockHashIndex].GetHash();
					RequestWriter.AddBinaryAttachment(ObjectHash);
					if (!AttachmentHashes.contains(ObjectHash))
					{
						Attachments.push_back(CbAttachment(MetaDatas[BlockHashIndex], ObjectHash));
						AttachmentHashes.insert(ObjectHash);
					}
				}

				RequestWriter.EndArray();  // metadatas

				RequestPackage.SetObject(RequestWriter.Save());
			}
			RequestPackage.AddAttachments(Attachments);

			CompositeBuffer RpcRequestBuffer = FormatPackageMessageBuffer(RequestPackage);

			HttpClient::Response CacheResponse =
				m_HttpClient.Post(fmt::format("/builds/{}/{}/{}/blobs/putBlobMetadata", m_Namespace, m_Bucket, BuildId),
								  RpcRequestBuffer,
								  ZenContentType::kCbPackage);
			AddStatistic(CacheResponse);
			if (!CacheResponse.IsSuccess())
			{
				ZEN_DEBUG("Failed posting blob metadata to cache: {}", CacheResponse.ErrorMessage(""sv));
			}
		});
	}

	virtual std::vector<CbObject> GetBlobMetadatas(const Oid& BuildId, std::span<const IoHash> BlobHashes) override
	{
		ZEN_TRACE_CPU("ZenBuildStorageCache::GetBlobMetadatas");

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

		CbObjectWriter Request;

		Request.BeginArray("blobHashes"sv);
		for (const IoHash& BlobHash : BlobHashes)
		{
			Request.AddHash(BlobHash);
		}
		Request.EndArray();

		IoBuffer Payload = Request.Save().GetBuffer().AsIoBuffer();
		Payload.SetContentType(ZenContentType::kCbObject);

		HttpClient::Response Response =
			m_HttpClient.Post(fmt::format("/builds/{}/{}/{}/blobs/getBlobMetadata", m_Namespace, m_Bucket, BuildId),
							  Payload,
							  HttpClient::Accept(ZenContentType::kCbObject));
		AddStatistic(Response);
		if (Response.IsSuccess())
		{
			std::vector<CbObject> Result;

			CbPackage ResponsePackage = ParsePackageMessage(Response.ResponsePayload);
			CbObject  ResponseObject  = ResponsePackage.GetObject();

			CbArrayView BlobHashArray  = ResponseObject["blobHashes"sv].AsArrayView();
			CbArrayView MetadatasArray = ResponseObject["metadatas"sv].AsArrayView();
			Result.reserve(MetadatasArray.Num());
			auto BlobHashesIt	 = BlobHashes.begin();
			auto BlobHashArrayIt = begin(BlobHashArray);
			auto MetadataArrayIt = begin(MetadatasArray);
			while (MetadataArrayIt != end(MetadatasArray))
			{
				const IoHash BlobHash = (*BlobHashArrayIt).AsHash();
				while (BlobHash != *BlobHashesIt)
				{
					ZEN_ASSERT(BlobHashesIt != BlobHashes.end());
					BlobHashesIt++;
				}

				ZEN_ASSERT(BlobHash == *BlobHashesIt);

				const IoHash		MetaHash	   = (*MetadataArrayIt).AsAttachment();
				const CbAttachment* MetaAttachment = ResponsePackage.FindAttachment(MetaHash);
				ZEN_ASSERT(MetaAttachment);

				CbObject Metadata = MetaAttachment->AsObject();
				Result.emplace_back(std::move(Metadata));

				BlobHashArrayIt++;
				MetadataArrayIt++;
				BlobHashesIt++;
			}
			return Result;
		}
		return {};
	}

	virtual std::vector<BlobExistsResult> BlobsExists(const Oid& BuildId, std::span<const IoHash> BlobHashes) override
	{
		ZEN_TRACE_CPU("ZenBuildStorageCache::BlobsExists");

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

		CbObjectWriter Request;

		Request.BeginArray("blobHashes"sv);
		for (const IoHash& BlobHash : BlobHashes)
		{
			Request.AddHash(BlobHash);
		}
		Request.EndArray();

		IoBuffer Payload = Request.Save().GetBuffer().AsIoBuffer();
		Payload.SetContentType(ZenContentType::kCbObject);

		HttpClient::Response Response = m_HttpClient.Post(fmt::format("/builds/{}/{}/{}/blobs/exists", m_Namespace, m_Bucket, BuildId),
														  Payload,
														  HttpClient::Accept(ZenContentType::kCbObject));
		AddStatistic(Response);
		if (Response.IsSuccess())
		{
			CbObject ResponseObject = LoadCompactBinaryObject(Response.ResponsePayload);
			if (!ResponseObject)
			{
				throw std::runtime_error("BlobExists reponse is invalid, failed to load payload as compact binary object");
			}
			CbArrayView BlobsExistsArray = ResponseObject["blobExists"sv].AsArrayView();
			if (!BlobsExistsArray)
			{
				throw std::runtime_error("BlobExists reponse is invalid, 'blobExists' array is missing");
			}
			if (BlobsExistsArray.Num() != BlobHashes.size())
			{
				throw std::runtime_error(fmt::format("BlobExists reponse is invalid, 'blobExists' array contains {} entries, expected {}",
													 BlobsExistsArray.Num(),
													 BlobHashes.size()));
			}

			CbArrayView MetadatasExistsArray = ResponseObject["metadataExists"sv].AsArrayView();
			if (!MetadatasExistsArray)
			{
				throw std::runtime_error("BlobExists reponse is invalid, 'metadataExists' array is missing");
			}
			if (MetadatasExistsArray.Num() != BlobHashes.size())
			{
				throw std::runtime_error(
					fmt::format("BlobExists reponse is invalid, 'metadataExists' array contains {} entries, expected {}",
								MetadatasExistsArray.Num(),
								BlobHashes.size()));
			}

			std::vector<BlobExistsResult> Result;
			Result.reserve(BlobHashes.size());
			auto BlobExistsIt	  = begin(BlobsExistsArray);
			auto MetadataExistsIt = begin(MetadatasExistsArray);
			while (BlobExistsIt != end(BlobsExistsArray))
			{
				ZEN_ASSERT(MetadataExistsIt != end(MetadatasExistsArray));

				const bool HasBody	   = (*BlobExistsIt).AsBool();
				const bool HasMetadata = (*MetadataExistsIt).AsBool();

				Result.push_back({.HasBody = HasBody, .HasMetadata = HasMetadata});

				BlobExistsIt++;
				MetadataExistsIt++;
			}
			return Result;
		}
		return {};
	}

	virtual void Flush(int32_t UpdateIntervalMS, std::function<bool(intptr_t Remaining)>&& UpdateCallback) override
	{
		if (IsFlushed)
		{
			return;
		}
		if (!IsFlushed)
		{
			m_PendingBackgroundWorkCount.CountDown();
			IsFlushed = true;
		}
		if (m_PendingBackgroundWorkCount.Wait(100))
		{
			return;
		}
		while (true)
		{
			intptr_t Remaining = m_PendingBackgroundWorkCount.Remaining();
			if (!UpdateCallback(Remaining))
			{
				m_CancelBackgroundWork.store(true);
			}
			if (m_PendingBackgroundWorkCount.Wait(UpdateIntervalMS))
			{
				break;
			}
		}
		UpdateCallback(0);
	}

private:
	void AddStatistic(const HttpClient::Response& Result)
	{
		m_Stats.TotalBytesWritten += Result.UploadedBytes;
		m_Stats.TotalBytesRead += Result.DownloadedBytes;
		m_Stats.TotalRequestTimeUs += uint64_t(Result.ElapsedSeconds * 1000000.0);
		m_Stats.TotalRequestCount++;
		SetAtomicMax(m_Stats.PeakSentBytes, Result.UploadedBytes);
		SetAtomicMax(m_Stats.PeakReceivedBytes, Result.DownloadedBytes);
		if (Result.ElapsedSeconds > 0.0)
		{
			uint64_t BytesPerSec = uint64_t((Result.UploadedBytes + Result.DownloadedBytes) / Result.ElapsedSeconds);
			SetAtomicMax(m_Stats.PeakBytesPerSec, BytesPerSec);
		}
	}

	HttpClient&					   m_HttpClient;
	BuildStorageCache::Statistics& m_Stats;
	const std::string			   m_Namespace;
	const std::string			   m_Bucket;
	const std::filesystem::path	   m_TempFolderPath;
	bool						   IsFlushed = false;

	WorkerThreadPool& m_BackgroundWorkPool;
	Latch			  m_PendingBackgroundWorkCount;
	std::atomic<bool> m_CancelBackgroundWork;
};

std::unique_ptr<BuildStorageCache>
CreateZenBuildStorageCache(HttpClient&					  HttpClient,
						   BuildStorageCache::Statistics& Stats,
						   std::string_view				  Namespace,
						   std::string_view				  Bucket,
						   const std::filesystem::path&	  TempFolderPath,
						   WorkerThreadPool&			  BackgroundWorkerPool)
{
	return std::make_unique<ZenBuildStorageCache>(HttpClient, Stats, Namespace, Bucket, TempFolderPath, BackgroundWorkerPool);
}

#if ZEN_WITH_TESTS

class InMemoryBuildStorageCache : public BuildStorageCache
{
public:
	// MaxRangeSupported == 0 : no range requests are accepted, always return full blob
	// MaxRangeSupported == 1 : single range is supported, multi range returns full blob
	// MaxRangeSupported > 1 : multirange is supported up to MaxRangeSupported, more ranges returns empty blob (bad request)
	explicit InMemoryBuildStorageCache(uint64_t						  MaxRangeSupported,
									   BuildStorageCache::Statistics& Stats,
									   double						  LatencySec	= 0.0,
									   double						  DelayPerKBSec = 0.0)
	: m_MaxRangeSupported(MaxRangeSupported)
	, m_Stats(Stats)
	, m_LatencySec(LatencySec)
	, m_DelayPerKBSec(DelayPerKBSec)
	{
	}
	void PutBuildBlob(const Oid&, const IoHash& RawHash, ZenContentType, const CompositeBuffer& Payload) override
	{
		IoBuffer Buf = Payload.Flatten().AsIoBuffer();
		Buf.MakeOwned();
		const uint64_t SentBytes	 = Buf.Size();
		uint64_t	   ReceivedBytes = 0;
		SimulateLatency(SentBytes, 0);
		auto	  _ = MakeGuard([&]() { SimulateLatency(0, ReceivedBytes); });
		Stopwatch ExecutionTimer;
		auto	  __ = MakeGuard([&]() { AddStatistic(ExecutionTimer.GetElapsedTimeUs(), ReceivedBytes, SentBytes); });
		{
			std::lock_guard Lock(m_Mutex);
			m_Entries[RawHash] = std::move(Buf);
		}
		m_Stats.PutBlobCount.fetch_add(1);
		m_Stats.PutBlobByteCount.fetch_add(SentBytes);
	}

	IoBuffer GetBuildBlob(const Oid&, const IoHash& RawHash, uint64_t RangeOffset = 0, uint64_t RangeBytes = (uint64_t)-1) override
	{
		uint64_t SentBytes	   = 0;
		uint64_t ReceivedBytes = 0;
		SimulateLatency(SentBytes, 0);
		auto	  _ = MakeGuard([&]() { SimulateLatency(0, ReceivedBytes); });
		Stopwatch ExecutionTimer;
		auto	  __ = MakeGuard([&]() { AddStatistic(ExecutionTimer.GetElapsedTimeUs(), ReceivedBytes, SentBytes); });
		IoBuffer  FullPayload;
		{
			std::lock_guard Lock(m_Mutex);
			auto			It = m_Entries.find(RawHash);
			if (It == m_Entries.end())
			{
				return {};
			}
			FullPayload = It->second;
		}

		if (RangeOffset != 0 || RangeBytes != (uint64_t)-1)
		{
			if (m_MaxRangeSupported == 0)
			{
				ReceivedBytes = FullPayload.Size();
				return FullPayload;
			}
			else
			{
				ReceivedBytes = (RangeBytes == (uint64_t)-1) ? FullPayload.Size() - RangeOffset : RangeBytes;
				return IoBuffer(FullPayload, RangeOffset, RangeBytes);
			}
		}
		else
		{
			ReceivedBytes = FullPayload.Size();
			return FullPayload;
		}
	}

	BuildBlobRanges GetBuildBlobRanges(const Oid&, const IoHash& RawHash, std::span<const std::pair<uint64_t, uint64_t>> Ranges) override
	{
		ZEN_ASSERT(!Ranges.empty());
		uint64_t SentBytes	   = 0;
		uint64_t ReceivedBytes = 0;
		SimulateLatency(SentBytes, 0);
		auto	  _ = MakeGuard([&]() { SimulateLatency(0, ReceivedBytes); });
		Stopwatch ExecutionTimer;
		auto	  __ = MakeGuard([&]() { AddStatistic(ExecutionTimer.GetElapsedTimeUs(), ReceivedBytes, SentBytes); });
		if (m_MaxRangeSupported > 1 && Ranges.size() > m_MaxRangeSupported)
		{
			return {};
		}
		IoBuffer FullPayload;
		{
			std::lock_guard Lock(m_Mutex);
			auto			It = m_Entries.find(RawHash);
			if (It == m_Entries.end())
			{
				return {};
			}
			FullPayload = It->second;
		}

		if (Ranges.size() > m_MaxRangeSupported)
		{
			// An empty Ranges signals to the caller: "full buffer given, use it for all requested ranges".
			ReceivedBytes = FullPayload.Size();
			return {.PayloadBuffer = FullPayload};
		}
		else
		{
			uint64_t								   PayloadStart = Ranges.front().first;
			uint64_t								   PayloadSize	= Ranges.back().first + Ranges.back().second - PayloadStart;
			IoBuffer								   RangeBuffer	= IoBuffer(FullPayload, PayloadStart, PayloadSize);
			std::vector<std::pair<uint64_t, uint64_t>> PayloadRanges;
			PayloadRanges.reserve(Ranges.size());
			for (const std::pair<uint64_t, uint64_t>& Range : Ranges)
			{
				PayloadRanges.push_back(std::make_pair(Range.first - PayloadStart, Range.second));
			}
			ReceivedBytes = PayloadSize;
			return {.PayloadBuffer = RangeBuffer, .Ranges = std::move(PayloadRanges)};
		}
	}

	void PutBlobMetadatas(const Oid&, std::span<const IoHash>, std::span<const CbObject>) override {}

	std::vector<CbObject> GetBlobMetadatas(const Oid&, std::span<const IoHash> Hashes) override
	{
		return std::vector<CbObject>(Hashes.size());
	}

	std::vector<BlobExistsResult> BlobsExists(const Oid&, std::span<const IoHash> Hashes) override
	{
		std::lock_guard				  Lock(m_Mutex);
		std::vector<BlobExistsResult> Result;
		Result.reserve(Hashes.size());
		for (const IoHash& Hash : Hashes)
		{
			auto It = m_Entries.find(Hash);
			Result.push_back({.HasBody = (It != m_Entries.end() && It->second)});
		}
		return Result;
	}

	void Flush(int32_t, std::function<bool(intptr_t)>&&) override {}

private:
	void AddStatistic(uint64_t ElapsedTimeUs, uint64_t ReceivedBytes, uint64_t SentBytes)
	{
		m_Stats.TotalBytesWritten += SentBytes;
		m_Stats.TotalBytesRead += ReceivedBytes;
		m_Stats.TotalExecutionTimeUs += ElapsedTimeUs;
		m_Stats.TotalRequestCount++;
		SetAtomicMax(m_Stats.PeakSentBytes, SentBytes);
		SetAtomicMax(m_Stats.PeakReceivedBytes, ReceivedBytes);
		if (ElapsedTimeUs > 0)
		{
			SetAtomicMax(m_Stats.PeakBytesPerSec, (ReceivedBytes + SentBytes) * 1000000 / ElapsedTimeUs);
		}
	}

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

	uint64_t											 m_MaxRangeSupported = 0;
	BuildStorageCache::Statistics&						 m_Stats;
	const double										 m_LatencySec	 = 0.0;
	const double										 m_DelayPerKBSec = 0.0;
	std::mutex											 m_Mutex;
	std::unordered_map<IoHash, IoBuffer, IoHash::Hasher> m_Entries;
};

std::unique_ptr<BuildStorageCache>
CreateInMemoryBuildStorageCache(uint64_t MaxRangeSupported, BuildStorageCache::Statistics& Stats, double LatencySec, double DelayPerKBSec)
{
	return std::make_unique<InMemoryBuildStorageCache>(MaxRangeSupported, Stats, LatencySec, DelayPerKBSec);
}
#endif	// ZEN_WITH_TESTS

ZenCacheEndpointTestResult
TestZenCacheEndpoint(std::string_view BaseUrl, const bool AssumeHttp2, const bool HttpVerbose)
{
	HttpClientSettings	 TestClientSettings{.LogCategory	= "httpcacheclient",
											.ConnectTimeout = std::chrono::milliseconds{2000},
											.Timeout		= std::chrono::milliseconds{3000},
											.AssumeHttp2	= AssumeHttp2,
											.AllowResume	= true,
											.RetryCount		= 1,
											.Verbose		= HttpVerbose};
	HttpClient			 TestHttpClient(BaseUrl, TestClientSettings);
	HttpClient::Response TestResponse = TestHttpClient.Get("/status/builds");
	if (TestResponse.IsSuccess())
	{
		uint64_t MaxRangeCountPerRequest = 1;
		CbObject StatusResponse			 = TestResponse.AsObject();
		if (StatusResponse["ok"].AsBool())
		{
			MaxRangeCountPerRequest = StatusResponse["capabilities"].AsObjectView()["maxrangecountperrequest"].AsUInt64(1);

			LatencyTestResult LatencyResult = MeasureLatency(TestHttpClient, "/health");

			if (!LatencyResult.Success)
			{
				return {.Success = false, .FailureReason = LatencyResult.FailureReason};
			}

			return {.Success = true, .LatencySeconds = LatencyResult.LatencySeconds, .MaxRangeCountPerRequest = MaxRangeCountPerRequest};
		}
		else
		{
			return {.Success	   = false,
					.FailureReason = fmt::format("ZenCache endpoint {}/status/builds did not respond with \"ok\"", BaseUrl)};
		}
	}
	return {.Success = false, .FailureReason = TestResponse.ErrorMessage("")};
}

}  // namespace zen