-
Notifications
You must be signed in to change notification settings - Fork 25
/
kv-store.cpp
507 lines (409 loc) · 15.7 KB
/
kv-store.cpp
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
#include <algorithm>
#include <cstring>
#include <iostream>
#include <optional>
#include <string>
// TODO: remove these once the warnings are fixed
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"
#include "js/experimental/TypedData.h"
#pragma clang diagnostic pop
#include "js/ArrayBuffer.h"
#include "js/Stream.h"
#include "builtin.h"
#include "builtins/kv-store.h"
#include "builtins/native-stream-source.h"
#include "builtins/shared/url.h"
#include "core/encode.h"
#include "core/event_loop.h"
#include "host_interface/host_api.h"
#include "js-compute-builtins.h"
namespace builtins {
namespace {
std::string_view bad_chars{"#?*[]\n\r"};
std::optional<char> find_invalid_character_for_kv_store_key(const char *str) {
std::optional<char> res;
std::string_view view{str, strlen(str)};
auto it = std::find_if(view.begin(), view.end(),
[](auto c) { return bad_chars.find(c) != std::string_view::npos; });
if (it != view.end()) {
res = *it;
}
return res;
}
} // namespace
template <RequestOrResponse::BodyReadResult result_type>
bool KVStoreEntry::bodyAll(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(0)
return RequestOrResponse::bodyAll<result_type>(cx, args, self);
}
bool KVStoreEntry::body_get(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(0)
if (!JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::HasBody)).isBoolean()) {
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::HasBody), JS::BooleanValue(false));
}
return RequestOrResponse::body_get(cx, args, self, true);
}
bool KVStoreEntry::bodyUsed_get(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(0)
if (!JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::BodyUsed)).isBoolean()) {
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyUsed), JS::BooleanValue(false));
}
args.rval().setBoolean(RequestOrResponse::body_used(self));
return true;
}
const JSFunctionSpec KVStoreEntry::static_methods[] = {
JS_FS_END,
};
const JSPropertySpec KVStoreEntry::static_properties[] = {
JS_PS_END,
};
const JSFunctionSpec KVStoreEntry::methods[] = {
JS_FN("arrayBuffer", bodyAll<RequestOrResponse::BodyReadResult::ArrayBuffer>, 0,
JSPROP_ENUMERATE),
JS_FN("json", bodyAll<RequestOrResponse::BodyReadResult::JSON>, 0, JSPROP_ENUMERATE),
JS_FN("text", bodyAll<RequestOrResponse::BodyReadResult::Text>, 0, JSPROP_ENUMERATE),
JS_FS_END,
};
const JSPropertySpec KVStoreEntry::properties[] = {
JS_PSG("body", body_get, JSPROP_ENUMERATE),
JS_PSG("bodyUsed", bodyUsed_get, JSPROP_ENUMERATE),
JS_PS_END,
};
bool KVStoreEntry::constructor(JSContext *cx, unsigned argc, JS::Value *vp) {
JS_ReportErrorUTF8(cx, "KVStoreEntry can't be instantiated directly");
return false;
}
JSObject *KVStoreEntry::create(JSContext *cx, host_api::HttpBody body_handle) {
JS::RootedObject kvStoreEntry(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj));
if (!kvStoreEntry)
return nullptr;
JS::SetReservedSlot(kvStoreEntry, static_cast<uint32_t>(Slots::Body),
JS::Int32Value(body_handle.handle));
JS::SetReservedSlot(kvStoreEntry, static_cast<uint32_t>(Slots::BodyStream), JS::NullValue());
JS::SetReservedSlot(kvStoreEntry, static_cast<uint32_t>(Slots::HasBody), JS::BooleanValue(true));
JS::SetReservedSlot(kvStoreEntry, static_cast<uint32_t>(Slots::BodyUsed), JS::FalseValue());
return kvStoreEntry;
}
bool KVStoreEntry::init_class(JSContext *cx, JS::HandleObject global) {
return init_class_impl(cx, global);
}
namespace {
host_api::ObjectStore kv_store_handle(JSObject *obj) {
JS::Value val = JS::GetReservedSlot(obj, static_cast<uint32_t>(KVStore::Slots::KVStore));
return host_api::ObjectStore(val.toInt32());
}
bool parse_and_validate_key(JSContext *cx, const char *key, size_t len) {
// If the converted string has a length of 0 then we throw an Error
// because KVStore Keys have to be at-least 1 character.
if (len == 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_EMPTY);
return false;
}
// If the converted string has a length of more than 1024 then we throw an Error
// because KVStore Keys have to be less than 1025 characters.
if (len > 1024) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_TOO_LONG);
return false;
}
auto key_chars = key;
auto res = find_invalid_character_for_kv_store_key(key_chars);
if (res.has_value()) {
std::string character;
switch (res.value()) {
case '\n':
character = "newline";
break;
case '\r':
character = "carriage return";
break;
case '[':
character = '[';
break;
case ']':
character = ']';
break;
case '*':
character = '*';
break;
case '?':
character = '?';
break;
case '#':
character = '#';
break;
}
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_INVALID_CHARACTER,
character.c_str());
return false;
}
auto acme_challenge = ".well-known/acme-challenge/";
if (strncmp(key_chars, acme_challenge, strlen(acme_challenge)) == 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_ACME);
return false;
}
if (strcmp(key_chars, ".") == 0 || strcmp(key_chars, "..") == 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_KEY_RELATIVE);
return false;
}
return true;
}
} // namespace
bool KVStore::process_pending_kv_store_delete(JSContext *cx, int32_t handle,
JS::HandleObject context, JS::HandleObject promise) {
host_api::ObjectStorePendingDelete pending_lookup(handle);
auto res = pending_lookup.wait();
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return RejectPromiseWithPendingError(cx, promise);
}
JS::ResolvePromise(cx, promise, JS::UndefinedHandleValue);
return true;
}
bool KVStore::delete_(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER_WITH_NAME(1, "delete");
JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr));
if (!result_promise) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::RootedValue key(cx, args.get(0));
// Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring
auto key_chars = core::encode(cx, key);
if (!key_chars) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto res = kv_store_handle(self).delete_async(key_chars);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto ret = res.unwrap();
auto task = core::AsyncTask::create(cx, ret.handle, self, result_promise,
KVStore::process_pending_kv_store_delete);
if (!core::EventLoop::queue_async_task(task)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
args.rval().setObject(*result_promise);
return true;
}
bool KVStore::process_pending_kv_store_lookup(JSContext *cx, int32_t handle,
JS::HandleObject context, JS::HandleObject promise) {
host_api::ObjectStorePendingLookup pending_lookup(handle);
auto res = pending_lookup.wait();
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return RejectPromiseWithPendingError(cx, promise);
}
auto ret = res.unwrap();
// When no entry is found, we are going to resolve the Promise with `null`.
if (!ret.has_value()) {
JS::RootedValue result(cx);
result.setNull();
JS::ResolvePromise(cx, promise, result);
} else {
JS::RootedObject entry(cx, KVStoreEntry::create(cx, ret.value()));
if (!entry) {
return false;
}
JS::RootedValue result(cx);
result.setObject(*entry);
JS::ResolvePromise(cx, promise, result);
}
return true;
}
bool KVStore::get(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(1)
JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr));
if (!result_promise) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::RootedValue key(cx, args.get(0));
// Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring
auto key_chars = core::encode(cx, key);
if (!key_chars) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto res = kv_store_handle(self).lookup_async(key_chars);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto ret = res.unwrap();
auto task = core::AsyncTask::create(cx, ret.handle, self, result_promise,
KVStore::process_pending_kv_store_lookup);
if (!core::EventLoop::queue_async_task(std::move(task))) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
args.rval().setObject(*result_promise);
return true;
}
bool KVStore::put(JSContext *cx, unsigned argc, JS::Value *vp) {
METHOD_HEADER(2)
JS::RootedObject result_promise(cx, JS::NewPromiseObject(cx, nullptr));
if (!result_promise) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::RootedValue key(cx, args.get(0));
// Convert the key argument into a String following https://tc39.es/ecma262/#sec-tostring
auto key_chars = core::encode(cx, key);
if (!key_chars) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
if (!parse_and_validate_key(cx, key_chars.begin(), key_chars.len)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::HandleValue body_val = args.get(1);
// We currently support five types of body inputs:
// - byte sequence
// - buffer source
// - USV strings
// - URLSearchParams
// - ReadableStream
// After the other other options are checked explicitly, all other inputs are
// encoded to a UTF8 string to be treated as a USV string.
// TODO: Support the other possible inputs to Body.
JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr);
if (body_obj && JS::IsReadableStream(body_obj)) {
if (RequestOrResponse::body_unusable(cx, body_obj)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_READABLE_STREAM_LOCKED_OR_DISTRUBED);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
// If the body stream is backed by a Fastly Compute body handle, we can directly pipe
// that handle into the kv store.
if (builtins::NativeStreamSource::stream_is_body(cx, body_obj)) {
JS::RootedObject stream_source(cx,
builtins::NativeStreamSource::get_stream_source(cx, body_obj));
JS::RootedObject source_owner(cx, builtins::NativeStreamSource::owner(stream_source));
auto body = RequestOrResponse::body_handle(source_owner);
auto res = kv_store_handle(self).insert(key_chars, body);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
// The insert was successful so we return a Promise which resolves to undefined
JS::RootedValue rval(cx);
rval.setUndefined();
JS::ResolvePromise(cx, result_promise, rval);
args.rval().setObject(*result_promise);
return true;
} else {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_PUT_CONTENT_STREAM);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
} else {
auto result = convertBodyInit(cx, body_val);
if (result.isErr()) {
return false;
}
size_t length;
JS::UniqueChars data;
std::tie(data, length) = result.unwrap();
// 30MB in bytes is the max size allowed for KVStore.
if (length > 30 * 1024 * 1024) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_PUT_OVER_30_MB);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto make_res = host_api::HttpBody::make();
if (auto *err = make_res.to_err()) {
HANDLE_ERROR(cx, *err);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto body = make_res.unwrap();
if (!body.valid()) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto write_res = body.write_all_back(reinterpret_cast<uint8_t *>(data.get()), length);
if (auto *err = write_res.to_err()) {
HANDLE_ERROR(cx, *err);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
auto insert_res = kv_store_handle(self).insert(key_chars, body);
if (auto *err = insert_res.to_err()) {
// Ensure that we throw an exception for all unexpected host errors.
HANDLE_ERROR(cx, *err);
return RejectPromiseWithPendingError(cx, result_promise);
}
// The insert was successful so we return a Promise which resolves to undefined
JS::RootedValue rval(cx);
rval.setUndefined();
JS::ResolvePromise(cx, result_promise, rval);
args.rval().setObject(*result_promise);
return true;
}
return false;
}
const JSFunctionSpec KVStore::static_methods[] = {
JS_FS_END,
};
const JSPropertySpec KVStore::static_properties[] = {
JS_PS_END,
};
const JSFunctionSpec KVStore::methods[] = {
JS_FN("delete", delete_, 1, JSPROP_ENUMERATE),
JS_FN("get", get, 1, JSPROP_ENUMERATE),
JS_FN("put", put, 1, JSPROP_ENUMERATE),
JS_FS_END,
};
const JSPropertySpec KVStore::properties[] = {
JS_PS_END,
};
bool KVStore::constructor(JSContext *cx, unsigned argc, JS::Value *vp) {
REQUEST_HANDLER_ONLY("The KVStore builtin");
CTOR_HEADER("KVStore", 1);
JS::HandleValue name_arg = args.get(0);
// Convert into a String following https://tc39.es/ecma262/#sec-tostring
auto name = core::encode(cx, name_arg);
if (!name) {
return false;
}
// If the converted string has a length of 0 then we throw an Error
// because KVStore names have to be at-least 1 character.
if (name.len == 0) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_NAME_EMPTY);
return false;
}
// If the converted string has a length of more than 255 then we throw an Error
// because KVStore names have to be less than 255 characters.
if (name.len > 255) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_NAME_TOO_LONG);
return false;
}
if (std::any_of(name.begin(), name.end(), [](auto character) {
return std::iscntrl(static_cast<unsigned char>(character)) != 0;
})) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_KV_STORE_NAME_NO_CONTROL_CHARACTERS);
return false;
}
auto res = host_api::ObjectStore::open(name);
if (auto *err = res.to_err()) {
if (host_api::error_is_invalid_argument(*err)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_KV_STORE_DOES_NOT_EXIST,
name.begin());
return false;
} else {
HANDLE_ERROR(cx, *err);
return false;
}
}
JS::RootedObject kv_store(cx, JS_NewObjectForConstructor(cx, &class_, args));
if (!kv_store) {
return false;
}
JS::SetReservedSlot(kv_store, static_cast<uint32_t>(Slots::KVStore),
JS::Int32Value(res.unwrap().handle));
args.rval().setObject(*kv_store);
return true;
}
bool KVStore::init_class(JSContext *cx, JS::HandleObject global) {
return init_class_impl(cx, global);
}
} // namespace builtins