aboutsummaryrefslogtreecommitdiff
path: root/src/zenremotestore/builds/buildstoragecache.cpp
blob: faa85f81b10efbda8f0a2d48b314261da5a34e8c (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
// 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.ToHexString()),
									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.ToHexString()),
								  m_TempFolderPath,
								  Headers);
		AddStatistic(CacheResponse);
		if (CacheResponse.IsSuccess())
		{
			return CacheResponse.ResponsePayload;
		}
		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);
}

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())
	{
		LatencyTestResult LatencyResult = MeasureLatency(TestHttpClient, "/health");

		if (!LatencyResult.Success)
		{
			return {.Success = false, .FailureReason = LatencyResult.FailureReason};
		}
		return {.Success = true, .LatencySeconds = LatencyResult.LatencySeconds};
	}
	return {.Success = false, .FailureReason = TestResponse.ErrorMessage("")};
};

}  // namespace zen