aboutsummaryrefslogtreecommitdiff
path: root/zenserver/cache/structuredcache.cpp
blob: b244c881ce31caef4761f13190eef3a09073d700 (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
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinaryvalidation.h>
#include <zencore/compress.h>
#include <zencore/fmtutils.h>
#include <zencore/httpserver.h>
#include <zencore/timer.h>

#include "structuredcache.h"
#include "structuredcachestore.h"
#include "upstream/jupiter.h"
#include "zenstore/cidstore.h"

#include <spdlog/spdlog.h>
#include <filesystem>

namespace zen {

using namespace std::literals;

HttpStructuredCacheService::HttpStructuredCacheService(std::filesystem::path RootPath, zen::CasStore& InStore, zen::CidStore& InCidStore)
: m_CasStore(InStore)
, m_CacheStore(InStore, RootPath)
, m_CidStore(InCidStore)
{
	spdlog::info("initializing structured cache at '{}'", RootPath);

#if 0
	m_Cloud = new CloudCacheClient("https://jupiter.devtools.epicgames.com"sv,
								   "ue4.ddc"sv /* namespace */,
								   "https://epicgames.okta.com/oauth2/auso645ojjWVdRI3d0x7/v1/token"sv /* provider */,
								   "0oao91lrhqPiAlaGD0x7"sv /* client id */,
								   "-GBWjjenhCgOwhxL5yBKNJECVIoDPH0MK4RDuN7d"sv /* oauth secret */);
#endif
}

HttpStructuredCacheService::~HttpStructuredCacheService()
{
	spdlog::info("closing structured cache");
}

const char*
HttpStructuredCacheService::BaseUri() const
{
	return "/z$/";
}

void
HttpStructuredCacheService::HandleRequest(zen::HttpServerRequest& Request)
{
	CacheRef Ref;

	if (!ValidateUri(Request, /* out */ Ref))
	{
		return Request.WriteResponse(zen::HttpResponse::BadRequest);  // invalid URL
	}

	if (Ref.PayloadId == IoHash::Zero)
	{
		return HandleCacheRecordRequest(Request, Ref);
	}
	else
	{
		return HandleCachePayloadRequest(Request, Ref);
	}

	return;
}

void
HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Request, CacheRef& Ref)
{
	switch (auto Verb = Request.RequestVerb())
	{
		using enum zen::HttpVerb;

		case kHead:
		case kGet:
			{
				ZenCacheValue Value;
				bool		  Success = m_CacheStore.Get(Ref.BucketSegment, Ref.HashKey, /* out */ Value);

				if (!Success)
				{
					return Request.WriteResponse(zen::HttpResponse::NotFound);
				}

				if (Verb == kHead)
				{
					Request.SetSuppressResponseBody();
				}

				return Request.WriteResponse(zen::HttpResponse::OK, zen::HttpContentType::kBinary, Value.Value);
			}
			break;

		case kPut:
			{
				if (zen::IoBuffer Body = Request.ReadPayload())
				{
					if (Body.Size() == 0)
					{
						return Request.WriteResponse(zen::HttpResponse::BadRequest);
					}

					ZenCacheValue Value;
					Value.Value = Body;

					HttpContentType ContentType = Request.RequestContentType();

					bool IsCompactBinary;

					switch (ContentType)
					{
						case HttpContentType::kUnknownContentType:
						case HttpContentType::kBinary:
							IsCompactBinary = false;
							break;

						case HttpContentType::kCbObject:
							IsCompactBinary = true;
							break;

						default:
							return Request.WriteResponse(zen::HttpResponse::BadRequest);
					}

					// Compute index data

					if (IsCompactBinary)
					{
						// Validate payload before accessing it
						zen::CbValidateError ValidationResult =
							zen::ValidateCompactBinary(MemoryView(Body.Data(), Body.Size()), zen::CbValidateMode::All);

						if (ValidationResult != CbValidateError::None)
						{
							// TODO: add details in response
							return Request.WriteResponse(HttpResponse::BadRequest);
						}

						// Extract data for index
						zen::CbObjectView Cbo(Body.Data());

						std::vector<IoHash> References;
						Cbo.IterateAttachments([&](CbFieldView AttachmentView) { References.push_back(AttachmentView.AsHash()); });

						if (!References.empty())
						{
							zen::CbObjectWriter Idx;
							Idx.BeginArray("r");

							for (const IoHash& Hash : References)
							{
								Idx.AddHash(Hash);
							}

							Idx.EndArray();
						}

						// TODO: store references in index
					}

					m_CacheStore.Put(Ref.BucketSegment, Ref.HashKey, Value);

					// This is currently synchronous for simplicity and debuggability but should be
					// made asynchronous

					if (m_Cloud)
					{
						CloudCacheSession Session(m_Cloud);

						zen::Stopwatch Timer;

						try
						{
							Session.Put(Ref.BucketSegment, Ref.HashKey, Value);
							spdlog::debug("upstream PUT ({}) succeeded after {:5}!",
										  Ref.HashKey,
										  zen::NiceTimeSpanMs(Timer.getElapsedTimeMs()));
						}
						catch (std::exception& e)
						{
							spdlog::debug("upstream PUT ({}) failed after {:5}: '{}'",
										  Ref.HashKey,
										  zen::NiceTimeSpanMs(Timer.getElapsedTimeMs()),
										  e.what());

							throw;
						}
					}

					return Request.WriteResponse(zen::HttpResponse::Created);
				}
				else
				{
					return;
				}
			}
			break;

		case kPost:
			break;

		default:
			break;
	}
}

void
HttpStructuredCacheService::HandleCachePayloadRequest(zen::HttpServerRequest& Request, CacheRef& Ref)
{
	// Note: the URL references the uncompressed payload hash - so this maintains the mapping
	// from uncompressed CAS identity (aka CID/Content ID) to the stored payload hash
	//
	// this is a PITA but a consequence of the fact that the client side code is not able to
	// address data by compressed hash

	switch (auto Verb = Request.RequestVerb())
	{
		using enum zen::HttpVerb;

		case kHead:
		case kGet:
			{
				// TODO: need to map from uncompressed content address into the storage
				// (compressed) content address

				zen::IoBuffer Payload = m_CidStore.FindChunkByCid(Ref.PayloadId);

				if (!Payload)
				{
					return Request.WriteResponse(zen::HttpResponse::NotFound);
				}

				if (Verb == kHead)
				{
					Request.SetSuppressResponseBody();
				}

				return Request.WriteResponse(zen::HttpResponse::OK, zen::HttpContentType::kBinary, Payload);
			}
			break;

		case kPut:
			{
				if (zen::IoBuffer Body = Request.ReadPayload())
				{
					if (Body.Size() == 0)
					{
						return Request.WriteResponse(zen::HttpResponse::BadRequest, HttpContentType::kText, "Empty payload not permitted");
					}

					zen::IoHash ChunkHash = zen::IoHash::HashMemory(Body);

					zen::CompressedBuffer Compressed = zen::CompressedBuffer::FromCompressed(SharedBuffer(Body));

					if (!Compressed)
					{
						// All attachment payloads need to be in compressed buffer format
						return Request.WriteResponse(zen::HttpResponse::BadRequest, HttpContentType::kText, "Attachments must be compressed");
					}
					else
					{
						if (IoHash::FromBLAKE3(Compressed.GetRawHash()) != Ref.PayloadId)
						{
							// the URL specified content id and content hashes don't match!
							return Request.WriteResponse(HttpResponse::BadRequest);
						}

						zen::CasStore::InsertResult Result = m_CasStore.InsertChunk(Body, ChunkHash);

						m_CidStore.AddCompressedCid(Ref.PayloadId, ChunkHash);

						if (Result.New)
						{
							return Request.WriteResponse(zen::HttpResponse::Created);
						}
						else
						{
							return Request.WriteResponse(zen::HttpResponse::OK);
						}					
					}
				}
			}
			break;

		case kPost:
			break;

		default:
			break;
	}
}

bool
HttpStructuredCacheService::ValidateUri(zen::HttpServerRequest& Request, CacheRef& OutRef)
{
	std::string_view			Key				  = Request.RelativeUri();
	std::string_view::size_type BucketSplitOffset = Key.find_first_of('/');

	if (BucketSplitOffset == std::string_view::npos)
	{
		return false;
	}

	OutRef.BucketSegment = Key.substr(0, BucketSplitOffset);

	std::string_view HashSegment;
	std::string_view PayloadSegment;

	std::string_view::size_type PayloadSplitOffset = Key.find_last_of('/');

	// We know there is a slash so no need to check for npos return

	if (PayloadSplitOffset == BucketSplitOffset)
	{
		// Basic cache record lookup
		HashSegment = Key.substr(BucketSplitOffset + 1);
	}
	else
	{
		// Cache record + payload lookup
		HashSegment	   = Key.substr(BucketSplitOffset + 1, PayloadSplitOffset - BucketSplitOffset - 1);
		PayloadSegment = Key.substr(PayloadSplitOffset + 1);
	}

	if (HashSegment.size() != zen::IoHash::StringLength)
	{
		return false;
	}

	if (!PayloadSegment.empty() && PayloadSegment.size() == zen::IoHash::StringLength)
	{
		const bool IsOk = zen::ParseHexBytes(PayloadSegment.data(), PayloadSegment.size(), OutRef.PayloadId.Hash);

		if (!IsOk)
		{
			return false;
		}
	}
	else
	{
		OutRef.PayloadId = zen::IoHash::Zero;
	}

	const bool IsOk = zen::ParseHexBytes(HashSegment.data(), HashSegment.size(), OutRef.HashKey.Hash);

	if (!IsOk)
	{
		return false;
	}

	return true;
}
}  // namespace zen