/
bucket.cc
1017 lines (870 loc) · 36.6 KB
/
bucket.cc
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <algorithm>
#include <memory>
#include <mutex>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>
#include "bucket.h"
#include "error.h"
#include "js_exception.h"
#include "lang_compat.h"
#include "lcb_utils.h"
#include "retry_util.h"
#include "utils.h"
#include "v8worker.h"
std::atomic<int64_t> bucket_op_exception_count = {0};
std::atomic<int64_t> bucket_op_cachemiss_count = {0};
std::atomic<int64_t> lcb_retry_failure = {0};
BucketFactory::BucketFactory(v8::Isolate *isolate,
const v8::Local<v8::Context> &context)
: isolate_(isolate) {
v8::HandleScope handle_scope(isolate_);
context_.Reset(isolate_, context);
auto bucket_template = v8::ObjectTemplate::New(isolate_);
bucket_template->SetInternalFieldCount(BucketBinding::kInternalFieldsCount);
// Register corresponding callbacks for alphanumeric accesses on bucket
// object
bucket_template->SetHandler(v8::NamedPropertyHandlerConfiguration(
BucketBinding::BucketGetDelegate, BucketBinding::BucketSetDelegate,
nullptr, BucketBinding::BucketDeleteDelegate));
// Register corresponding callbacks for numeric accesses on bucket object
bucket_template->SetIndexedPropertyHandler(
v8::IndexedPropertyGetterCallback(BucketBinding::BucketGetDelegate),
v8::IndexedPropertySetterCallback(BucketBinding::BucketSetDelegate),
nullptr,
v8::IndexedPropertyDeleterCallback(BucketBinding::BucketDeleteDelegate));
bucket_template_.Reset(isolate_, bucket_template);
}
BucketFactory::~BucketFactory() {
context_.Reset();
bucket_template_.Reset();
}
std::pair<Error, std::unique_ptr<v8::Local<v8::Object>>>
BucketFactory::NewBucketObj() const {
v8::EscapableHandleScope handle_scope(isolate_);
const auto context = context_.Get(isolate_);
auto bucket_template = bucket_template_.Get(isolate_);
v8::Local<v8::Object> bucket_obj;
if (!TO_LOCAL(bucket_template->NewInstance(context), &bucket_obj)) {
return {std::make_unique<std::string>(
"Unable to create an instance of bucket template"),
nullptr};
}
return {nullptr, std::make_unique<v8::Local<v8::Object>>(
handle_scope.Escape(bucket_obj))};
}
Bucket::~Bucket() {
if (is_connected_) {
lcb_destroy(connection_);
}
}
Error Bucket::Connect() {
LOG(logTrace) << __func__ << " connecting to bucket " << RU(bucket_name_)
<< std::endl;
if (is_connected_) {
LOG(logError)
<< __func__
<< " Attempting to connect an already connected bucket instance"
<< std::endl;
return std::make_unique<std::string>("already connected");
}
auto utils = UnwrapData(isolate_)->utils;
auto conn_str_info = utils->GetConnectionString(bucket_name_);
if (!conn_str_info.is_valid) {
return std::make_unique<std::string>(conn_str_info.msg);
}
LOG(logInfo) << __func__
<< " connection string : " << RU(conn_str_info.conn_str)
<< std::endl;
lcb_CREATEOPTS *options;
lcb_createopts_create(&options, LCB_TYPE_BUCKET);
lcb_createopts_connstr(options, conn_str_info.conn_str.c_str(),
strlen(conn_str_info.conn_str.c_str()));
lcb_createopts_logger(options, evt_logger.base);
auto result = lcb_create(&connection_, options);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to initialize connection handle",
result);
}
lcb_createopts_destroy(options);
auto auth = lcbauth_new();
result = RetryWithFixedBackoff(5, 200, IsRetriable, lcbauth_set_callback,
auth, isolate_, GetUsernameAndPassword);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to set auth callbacks", result);
}
result = RetryWithFixedBackoff(5, 200, IsRetriable, lcbauth_set_mode, auth,
LCBAUTH_MODE_DYNAMIC);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to set auth mode to dynamic",
result);
}
lcb_set_auth(connection_, auth);
result = RetryWithFixedBackoff(5, 200, IsRetriable, lcb_connect, connection_);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to connect to bucket", result);
}
result = RetryWithFixedBackoff(5, 200, IsRetriable, lcb_wait, connection_,
LCB_WAIT_DEFAULT);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to schedule call for connect",
result);
}
lcb_install_callback(connection_, LCB_CALLBACK_GET, GetCallback);
lcb_install_callback(connection_, LCB_CALLBACK_STORE, SetCallback);
lcb_install_callback(connection_, LCB_CALLBACK_SDMUTATE, SubDocumentCallback);
lcb_install_callback(connection_, LCB_CALLBACK_REMOVE, DeleteCallback);
lcb_install_callback(connection_, LCB_CALLBACK_SDLOOKUP,
SubDocumentLookupCallback);
lcb_U32 lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
result =
RetryWithFixedBackoff(5, 200, IsRetriable, lcb_cntl, connection_,
LCB_CNTL_SET, LCB_CNTL_OP_TIMEOUT, &lcb_timeout);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to set timeout for bucket ops",
result);
}
auto enable_detailed_err_codes = true;
result = RetryWithFixedBackoff(5, 200, IsRetriable, lcb_cntl, connection_,
LCB_CNTL_SET, LCB_CNTL_DETAILED_ERRCODES,
&enable_detailed_err_codes);
if (result != LCB_SUCCESS) {
return FormatErrorAndDestroyConn("Unable to set detailed error codes",
result);
}
LOG(logTrace) << __func__ << " connected to bucket " << RU(bucket_name_)
<< " successfully" << std::endl;
is_connected_ = true;
return nullptr;
}
Error Bucket::FormatErrorAndDestroyConn(const std::string &message,
const lcb_STATUS &error) const {
auto isolate_data = UnwrapData(isolate_);
AddLcbException(isolate_data, error);
std::stringstream err_msg;
err_msg << message << ", err: " << lcb_strerror_long(error);
lcb_destroy(connection_);
LOG(logError) << __func__ << " " << err_msg.str() << std::endl;
return std::make_unique<std::string>(err_msg.str());
}
// returns true if status is auth_failure AND we were able to recreate
// connection false if either status is not auth failure OR status was failure
// but couldn't recreate
bool Bucket::MaybeRecreateConnOnAuthErr(const lcb_STATUS &status,
bool should_check_autherr) {
lcb_INSTANCE *tmp_instance;
if (status == LCB_ERR_AUTHENTICATION_FAILURE && should_check_autherr) {
if (is_connected_) {
LOG(logError) << "Got LCB_ERR_AUTHENTICATION_FAILURE for bucket: "
<< bucket_name_ << " Recreating lcb instance" << std::endl;
tmp_instance = connection_;
is_connected_ = false;
connection_ = nullptr;
}
auto create_err = Connect();
if (create_err != nullptr) {
connection_ = tmp_instance;
if (connection_ != nullptr)
is_connected_ = true;
return false;
}
if (tmp_instance != nullptr)
lcb_destroy(tmp_instance);
return true;
}
return false;
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::Get(const std::string &key) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDGET *cmd;
lcb_cmdget_create(&cmd);
lcb_cmdget_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdget_key(cmd, key.c_str(), key.length());
lcb_cmdget_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdget_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] =
TryLcbCmdWithRefreshConnIfNecessary(*cmd, max_retry, max_timeout, LcbGet);
lcb_cmdget_destroy(cmd);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
BucketCache::Fetch().Change(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key),
result);
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::GetWithMeta(const std::string &key) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_SUBDOCSPECS *specs;
lcb_subdocspecs_create(&specs, 3);
char const *path = "$document.exptime";
lcb_subdocspecs_get(specs, 0, LCB_SUBDOCSPECS_F_XATTRPATH, path,
strlen(path));
char const *path2 = "$document.datatype";
lcb_subdocspecs_get(specs, 1, LCB_SUBDOCSPECS_F_XATTRPATH, path2,
strlen(path2));
lcb_subdocspecs_get(specs, 2, 0, "", 0);
lcb_CMDSUBDOC *cmd;
lcb_cmdsubdoc_create(&cmd);
lcb_cmdsubdoc_specs(cmd, specs);
lcb_cmdsubdoc_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdsubdoc_key(cmd, key.c_str(), key.length());
lcb_cmdsubdoc_specs(cmd, specs);
lcb_cmdsubdoc_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdsubdoc_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbSubdocSet);
lcb_cmdsubdoc_destroy(cmd);
lcb_subdocspecs_destroy(specs);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
BucketCache::Fetch().Change(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key),
result);
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::CounterWithoutXattr(const std::string &key, uint64_t cas,
lcb_U32 expiry, int64_t delta) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_SUBDOCSPECS *spec;
lcb_subdocspecs_create(&spec, 1);
lcb_subdocspecs_counter(spec, 0, 0, "count", strlen("count"), delta);
lcb_CMDSUBDOC *cmd;
lcb_cmdsubdoc_create(&cmd);
lcb_cmdsubdoc_store_semantics(cmd, LCB_SUBDOC_STORE_UPSERT);
lcb_cmdsubdoc_specs(cmd, spec);
lcb_cmdsubdoc_cas(cmd, cas);
lcb_cmdsubdoc_expiry(cmd, expiry);
lcb_cmdsubdoc_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdsubdoc_key(cmd, key.c_str(), key.length());
lcb_cmdsubdoc_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdsubdoc_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbSubdocSet);
lcb_cmdsubdoc_destroy(cmd);
lcb_subdocspecs_destroy(spec);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::CounterWithXattr(const std::string &key, uint64_t cas, lcb_U32 expiry,
int64_t delta) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
lcb_SUBDOCSPECS *specs;
lcb_subdocspecs_create(&specs, 4);
auto function_instance_id = GetFunctionInstanceID(isolate_);
std::string function_instance_id_path("_eventing.fiid");
lcb_subdocspecs_dict_upsert(
specs, 0, LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTRPATH,
function_instance_id_path.c_str(), function_instance_id_path.size(),
function_instance_id.c_str(), function_instance_id.size());
std::string dcp_seqno_path("_eventing.seqno");
std::string dcp_seqno_macro(R"("${Mutation.seqno}")");
lcb_subdocspecs_dict_upsert(specs, 1,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES |
LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
dcp_seqno_path.c_str(), dcp_seqno_path.size(),
dcp_seqno_macro.c_str(), dcp_seqno_macro.size());
std::string value_crc32_path("_eventing.crc");
std::string value_crc32_macro(R"("${Mutation.value_crc32c}")");
lcb_subdocspecs_dict_upsert(
specs, 2,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
value_crc32_path.c_str(), value_crc32_path.size(),
value_crc32_macro.c_str(), value_crc32_macro.size());
lcb_subdocspecs_counter(specs, 3, 0, "count", strlen("count"), delta);
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDSUBDOC *cmd;
lcb_cmdsubdoc_create(&cmd);
lcb_cmdsubdoc_specs(cmd, specs);
lcb_cmdsubdoc_store_semantics(cmd, LCB_SUBDOC_STORE_UPSERT);
lcb_cmdsubdoc_cas(cmd, cas);
lcb_cmdsubdoc_expiry(cmd, expiry);
lcb_cmdsubdoc_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdsubdoc_key(cmd, key.c_str(), key.length());
lcb_cmdsubdoc_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdsubdoc_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbSubdocSet);
lcb_cmdsubdoc_destroy(cmd);
lcb_subdocspecs_destroy(specs);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::SetWithXattr(const std::string &key, const std::string &value,
lcb_SUBDOC_STORE_SEMANTICS op_type, lcb_U32 expiry,
uint64_t cas) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
BucketCache::Fetch().Invalidate(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key));
lcb_SUBDOCSPECS *specs;
lcb_subdocspecs_create(&specs, 4);
auto function_instance_id = GetFunctionInstanceID(isolate_);
std::string function_instance_id_path("_eventing.fiid");
lcb_subdocspecs_dict_upsert(
specs, 0, LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTRPATH,
function_instance_id_path.c_str(), function_instance_id_path.size(),
function_instance_id.c_str(), function_instance_id.size());
std::string dcp_seqno_path("_eventing.seqno");
std::string dcp_seqno_macro(R"("${Mutation.seqno}")");
lcb_subdocspecs_dict_upsert(specs, 1,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES |
LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
dcp_seqno_path.c_str(), dcp_seqno_path.size(),
dcp_seqno_macro.c_str(), dcp_seqno_macro.size());
std::string value_crc32_path("_eventing.crc");
std::string value_crc32_macro(R"("${Mutation.value_crc32c}")");
lcb_subdocspecs_dict_upsert(
specs, 2,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
value_crc32_path.c_str(), value_crc32_path.size(),
value_crc32_macro.c_str(), value_crc32_macro.size());
lcb_subdocspecs_replace(specs, 3, 0, "", 0, value.data(), value.size());
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDSUBDOC *cmd;
lcb_cmdsubdoc_create(&cmd);
lcb_cmdsubdoc_specs(cmd, specs);
lcb_cmdsubdoc_cas(cmd, cas);
lcb_cmdsubdoc_expiry(cmd, expiry);
lcb_cmdsubdoc_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdsubdoc_key(cmd, key.data(), key.size());
lcb_cmdsubdoc_store_semantics(cmd, op_type);
lcb_cmdsubdoc_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdsubdoc_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbSubdocSet);
lcb_cmdsubdoc_destroy(cmd);
lcb_subdocspecs_destroy(specs);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::SetWithoutXattr(const std::string &key, const std::string &value,
lcb_STORE_OPERATION op_type, lcb_U32 expiry,
uint64_t cas, lcb_U32 doc_type) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
BucketCache::Fetch().Invalidate(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key));
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDSTORE *cmd;
lcb_cmdstore_create(&cmd, op_type);
lcb_cmdstore_expiry(cmd, expiry);
lcb_cmdstore_cas(cmd, cas);
lcb_cmdstore_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdstore_key(cmd, key.data(), key.size());
lcb_cmdstore_value(cmd, value.data(), value.size());
lcb_cmdstore_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdstore_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] =
TryLcbCmdWithRefreshConnIfNecessary(*cmd, max_retry, max_timeout, LcbSet);
lcb_cmdstore_destroy(cmd);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::DeleteWithXattr(const std::string &key, uint64_t cas) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
BucketCache::Fetch().Invalidate(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key));
lcb_SUBDOCSPECS *specs;
lcb_subdocspecs_create(&specs, 4);
auto function_instance_id = GetFunctionInstanceID(isolate_);
std::string function_instance_id_path("_eventing.fiid");
lcb_subdocspecs_dict_upsert(
specs, 0, LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTRPATH,
function_instance_id_path.c_str(), function_instance_id_path.size(),
function_instance_id.c_str(), function_instance_id.size());
std::string dcp_seqno_path("_eventing.seqno");
std::string dcp_seqno_macro(R"("${Mutation.seqno}")");
lcb_subdocspecs_dict_upsert(specs, 1,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES |
LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
dcp_seqno_path.c_str(), dcp_seqno_path.size(),
dcp_seqno_macro.c_str(), dcp_seqno_macro.size());
std::string value_crc32_path("_eventing.crc");
std::string value_crc32_macro(R"("${Mutation.value_crc32c}")");
lcb_subdocspecs_dict_upsert(
specs, 2,
LCB_SUBDOCSPECS_F_MKINTERMEDIATES | LCB_SUBDOCSPECS_F_XATTR_MACROVALUES,
value_crc32_path.c_str(), value_crc32_path.size(),
value_crc32_macro.c_str(), value_crc32_macro.size());
lcb_subdocspecs_remove(specs, 3, 0, "", 0);
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDSUBDOC *cmd;
lcb_cmdsubdoc_create(&cmd);
lcb_cmdsubdoc_specs(cmd, specs);
lcb_cmdsubdoc_cas(cmd, cas);
lcb_cmdsubdoc_store_semantics(cmd, LCB_SUBDOC_STORE_REPLACE);
lcb_cmdsubdoc_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdsubdoc_key(cmd, key.c_str(), key.length());
lcb_cmdsubdoc_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdsubdoc_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbSubdocDelete);
lcb_cmdsubdoc_destroy(cmd);
lcb_subdocspecs_destroy(specs);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
Bucket::DeleteWithoutXattr(const std::string &key, uint64_t cas) {
if (!is_connected_) {
return {std::make_unique<std::string>("Connection is not initialized"),
nullptr, nullptr};
}
BucketCache::Fetch().Invalidate(
BucketCache::MakeKey(bucket_name_, scope_name_, collection_name_, key));
const auto max_retry = UnwrapData(isolate_)->lcb_retry_count;
const auto lcb_timeout = UnwrapData(isolate_)->lcb_timeout;
const auto max_timeout = UnwrapData(isolate_)->op_timeout;
lcb_CMDREMOVE *cmd;
lcb_cmdremove_create(&cmd);
lcb_cmdremove_cas(cmd, cas);
lcb_cmdremove_collection(cmd, scope_name_.c_str(), scope_length_,
collection_name_.c_str(), collection_length_);
lcb_cmdremove_key(cmd, key.c_str(), key.length());
lcb_cmdremove_timeout(cmd, lcb_timeout);
if (on_behalf_of_.size() != 0) {
lcb_cmdremove_on_behalf_of(cmd, on_behalf_of_.c_str(), on_behalf_of_.size());
}
auto [err_code, result] = TryLcbCmdWithRefreshConnIfNecessary(
*cmd, max_retry, max_timeout, LcbDelete);
lcb_cmdremove_destroy(cmd);
if (err_code != LCB_SUCCESS) {
++lcb_retry_failure;
return {nullptr, std::make_unique<lcb_STATUS>(err_code), nullptr};
}
return {nullptr, std::make_unique<lcb_STATUS>(err_code),
std::make_unique<Result>(std::move(result))};
}
// Performs the lcb related calls when bucket object is accessed
template <>
void BucketBinding::BucketGet<v8::Local<v8::Name>>(
const v8::Local<v8::Name> &name,
const v8::PropertyCallbackInfo<v8::Value> &info) {
auto isolate = info.GetIsolate();
auto isolate_data = UnwrapData(isolate);
auto js_exception = isolate_data->js_exception;
auto utils = isolate_data->utils;
std::lock_guard<std::mutex> guard(isolate_data->termination_lock_);
if (!isolate_data->is_executing_) {
return;
}
auto validate_info = ValidateKey(name);
if (validate_info.is_fatal) {
js_exception->ThrowEventingError(validate_info.msg);
++bucket_op_exception_count;
return;
}
v8::HandleScope handle_scope(isolate);
auto context = isolate->GetCurrentContext();
v8::String::Utf8Value utf8_key(isolate, name.As<v8::String>());
std::string key(*utf8_key);
auto bucket = UnwrapInternalField<Bucket>(info.Holder(),
InternalFields::kBucketInstance);
auto [error, err_code, result] = bucket->Get(key);
if (error != nullptr) {
js_exception->ThrowEventingError(*error);
return;
}
if (*err_code != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), *err_code);
return;
}
if (result->rc == LCB_ERR_DOCUMENT_NOT_FOUND) {
HandleEnoEnt(isolate, info, bucket->GetConnection());
return;
}
if (result->rc != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), result->rc);
return;
}
v8::Local<v8::Value> doc;
// doc is json type
if (result->datatype & JSON_DOC) {
if (!(TO_LOCAL(v8::JSON::Parse(context, v8Str(isolate, result->value)),
&doc))) {
js_exception->ThrowEventingError("Unable to parse response body as JSON");
return;
}
} else {
doc = utils->ToArrayBuffer(static_cast<void *>(result->value.data()),
result->value.length());
}
info.GetReturnValue().Set(doc);
}
// Performs the lcb related calls when bucket object is accessed
template <>
void BucketBinding::BucketSet<v8::Local<v8::Name>>(
const v8::Local<v8::Name> &name, const v8::Local<v8::Value> &value_obj,
const v8::PropertyCallbackInfo<v8::Value> &info) {
auto isolate = info.GetIsolate();
auto js_exception = UnwrapData(isolate)->js_exception;
std::string value_str;
v8::Local<v8::ArrayBuffer> array_buf;
std::lock_guard<std::mutex> guard(UnwrapData(isolate)->termination_lock_);
if (!UnwrapData(isolate)->is_executing_) {
return;
}
auto validate_info = ValidateKeyValue(name, value_obj);
if (validate_info.is_fatal) {
js_exception->ThrowEventingError(validate_info.msg);
++bucket_op_exception_count;
return;
}
auto block_mutation =
UnwrapInternalField<bool>(info.Holder(), InternalFields::kBlockMutation);
if (*block_mutation) {
++bucket_op_exception_count;
js_exception->ThrowEventingError("Writing to source bucket is forbidden");
return;
}
// TODO : Do not cast to v8::String, just use name directly
v8::String::Utf8Value utf8_key(isolate, name.As<v8::String>());
std::string key(*utf8_key);
if (value_obj->IsArrayBuffer()) {
array_buf = value_obj.As<v8::ArrayBuffer>();
auto contents = array_buf->GetContents();
value_str.assign(static_cast<const char *>(contents.Data()),
contents.ByteLength());
} else {
value_str = JSONStringify(isolate, value_obj);
}
auto bucket = UnwrapInternalField<Bucket>(info.Holder(),
InternalFields::kBucketInstance);
auto is_source_bucket =
UnwrapInternalField<bool>(info.Holder(), InternalFields::kIsSourceBucket);
auto [error, err_code, result] =
BucketSet(key, value_str, *is_source_bucket, bucket);
if (error != nullptr) {
js_exception->ThrowEventingError(*error);
return;
}
if (*err_code != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), *err_code);
return;
}
if (result->rc != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), result->rc);
return;
}
info.GetReturnValue().Set(value_obj);
}
// Performs the lcb related calls when bucket object is accessed
template <>
void BucketBinding::BucketDelete<v8::Local<v8::Name>>(
const v8::Local<v8::Name> &name,
const v8::PropertyCallbackInfo<v8::Boolean> &info) {
auto isolate = info.GetIsolate();
auto js_exception = UnwrapData(isolate)->js_exception;
std::lock_guard<std::mutex> guard(UnwrapData(isolate)->termination_lock_);
if (!UnwrapData(isolate)->is_executing_) {
return;
}
auto validate_info = ValidateKey(name);
if (validate_info.is_fatal) {
js_exception->ThrowKVError(validate_info.msg);
++bucket_op_exception_count;
return;
}
auto block_mutation = UnwrapInternalField<bool>(
info.Holder(), static_cast<int>(InternalFields::kBlockMutation));
if (*block_mutation) {
js_exception->ThrowEventingError("Delete from source bucket is forbidden");
++bucket_op_exception_count;
return;
}
v8::String::Utf8Value utf8_key(isolate, name.As<v8::String>());
std::string key(*utf8_key);
auto is_source_bucket =
UnwrapInternalField<bool>(info.Holder(), InternalFields::kIsSourceBucket);
auto bucket = UnwrapInternalField<Bucket>(info.Holder(),
InternalFields::kBucketInstance);
auto [error, err_code, result] = BucketDelete(key, is_source_bucket, bucket);
if (error != nullptr) {
js_exception->ThrowEventingError(*error);
return;
}
if (*err_code != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), *err_code);
return;
}
if (result->rc == LCB_ERR_DOCUMENT_NOT_FOUND) {
HandleEnoEnt(isolate, bucket->GetConnection());
return;
}
if (result->rc != LCB_SUCCESS) {
HandleBucketOpFailure(isolate, bucket->GetConnection(), result->rc);
return;
}
info.GetReturnValue().Set(true);
}
Error BucketBinding::InstallBinding(v8::Isolate *isolate,
const v8::Local<v8::Context> &context) {
v8::HandleScope handle_scope(isolate);
auto [err_new_obj, obj] = factory_->NewBucketObj();
if (err_new_obj != nullptr) {
return std::move(err_new_obj);
}
auto err_connect = bucket_.Connect();
if (err_connect != nullptr) {
return err_connect;
}
(*obj)->SetInternalField(InternalFields::kBlockMutation,
v8::External::New(isolate, &block_mutation_));
(*obj)->SetInternalField(InternalFields::kBucketInstance,
v8::External::New(isolate, &bucket_));
(*obj)->SetInternalField(InternalFields::kIsSourceBucket,
v8::External::New(isolate, &is_source_bucket_));
(*obj)->SetInternalField(InternalFields::kBucketBindingId,
v8Str(isolate, "Bucket-Binding"));
auto global = context->Global();
auto result = false;
if (!TO(global->Set(context, v8Str(isolate, bucket_alias_), *obj), &result) ||
!result) {
return std::make_unique<std::string>(
"Unable to install bucket binding with alias " + bucket_alias_ +
" to global scope");
}
return nullptr;
}
void BucketBinding::HandleBucketOpFailure(v8::Isolate *isolate,
lcb_INSTANCE *connection,
lcb_STATUS error) {
auto isolate_data = UnwrapData(isolate);
AddLcbException(isolate_data, error);
++bucket_op_exception_count;
auto js_exception = isolate_data->js_exception;
js_exception->ThrowKVError(connection, error);
}
// Delegates to the appropriate type of handler
template <typename T>
void BucketBinding::BucketGetDelegate(
T name, const v8::PropertyCallbackInfo<v8::Value> &info) {
BucketGet<T>(name, info);
}
template <typename T>
void BucketBinding::BucketSetDelegate(
T key, v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value> &info) {
BucketSet<T>(key, value, info);
}
template <typename T>
void BucketBinding::BucketDeleteDelegate(
T key, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
BucketDelete<T>(key, info);
}
// Specialized templates to forward the delegate to the overload doing the
// actual work
template <>
void BucketBinding::BucketGet<uint32_t>(
uint32_t key, const v8::PropertyCallbackInfo<v8::Value> &info) {
BucketGet<v8::Local<v8::Name>>(v8Name(info.GetIsolate(), key), info);
}
template <>
void BucketBinding::BucketSet<uint32_t>(
uint32_t key, const v8::Local<v8::Value> &value,
const v8::PropertyCallbackInfo<v8::Value> &info) {
BucketSet<v8::Local<v8::Name>>(v8Name(info.GetIsolate(), key), value, info);
}
template <>
void BucketBinding::BucketDelete<uint32_t>(
uint32_t key, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
BucketDelete<v8::Local<v8::Name>>(v8Name(info.GetIsolate(), key), info);
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
BucketBinding::BucketSet(const std::string &key, const std::string &value,
bool is_source_bucket, Bucket *bucket) {
if (is_source_bucket) {
return bucket->SetWithXattr(key, value);
}
return bucket->SetWithoutXattr(key, value);
}
std::tuple<Error, std::unique_ptr<lcb_STATUS>, std::unique_ptr<Result>>
BucketBinding::BucketDelete(const std::string &key, bool is_source_bucket,
Bucket *bucket) {
if (is_source_bucket) {
return bucket->DeleteWithXattr(key);
}
return bucket->DeleteWithoutXattr(key);
}
void BucketBinding::HandleEnoEnt(
v8::Isolate *isolate, const v8::PropertyCallbackInfo<v8::Value> &info,
lcb_INSTANCE *instance) {
const auto version = UnwrapData(isolate)->lang_compat->version;
if (version < LanguageCompatibility::Version::k6_5_0) {
HandleBucketOpFailure(isolate, instance, LCB_ERR_DOCUMENT_NOT_FOUND);
return;
}
info.GetReturnValue().Set(v8::Undefined(isolate));
}
void BucketBinding::HandleEnoEnt(v8::Isolate *isolate, lcb_INSTANCE *instance) {
const auto version = UnwrapData(isolate)->lang_compat->version;
if (version < LanguageCompatibility::Version::k6_5_0) {
HandleBucketOpFailure(isolate, instance, LCB_ERR_DOCUMENT_NOT_FOUND);
}
}
Info BucketBinding::ValidateKey(const v8::Local<v8::Name> &arg) {
auto info = Utils::ValidateDataType(arg);
if (info.is_fatal) {
return {true, "Invalid data type for key - " + info.msg};
}
return {false};
}
Info BucketBinding::ValidateValue(const v8::Local<v8::Value> &arg) {
auto info = Utils::ValidateDataType(arg);
if (info.is_fatal) {
return {true, "Invalid data type for value - " + info.msg};
}
return {false};
}
Info BucketBinding::ValidateKeyValue(const v8::Local<v8::Name> &key,
const v8::Local<v8::Value> &value) {
auto info = ValidateKey(key);
if (info.is_fatal) {
return info;
}
info = ValidateValue(value);
if (info.is_fatal) {
return info;
}
return {false};
}
bool BucketBinding::IsBucketObject(v8::Isolate *isolate,
const v8::Local<v8::Object> obj) {
if (obj->InternalFieldCount() != BucketBinding::kInternalFieldsCount) {
return false;
}
v8::HandleScope handle_scope(isolate);
auto binding_id = obj->GetInternalField(InternalFields::kBucketBindingId);
if (binding_id.IsEmpty() || binding_id->IsNullOrUndefined() ||
!binding_id->IsString()) {
return false;
}
v8::String::Utf8Value binding_id_utf8(isolate, binding_id);
return !strcmp(*binding_id_utf8, "Bucket-Binding");
}
Bucket *BucketBinding::GetBucket(v8::Isolate *isolate,
const v8::Local<v8::Value> obj) {
v8::HandleScope handle_scope(isolate);
auto context = isolate->GetCurrentContext();
v8::Local<v8::Object> local_obj;
TO_LOCAL(obj->ToObject(context), &local_obj);
return UnwrapInternalField<Bucket>(local_obj,
InternalFields::kBucketInstance);
}