This repository has been archived by the owner on Oct 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbinding.cpp
1532 lines (1375 loc) · 56 KB
/
binding.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
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
#include "binding.hpp"
#include <sstream>
#include <cmath>
#include <cassert>
#include <limits>
#include <algorithm>
#include <memory>
#include <protozero/pbf_writer.hpp>
#include <protozero/pbf_reader.hpp>
namespace carmen {
using namespace v8;
Nan::Persistent<FunctionTemplate> Cache::constructor;
inline std::string shard(uint64_t level, uint64_t id) {
if (level == 0) return "0";
unsigned int bits = 52 - (static_cast<unsigned int>(level) * 4);
unsigned int shard_id = static_cast<unsigned int>(std::floor(id / static_cast<double>(std::pow(2, bits))));
return std::to_string(shard_id);
}
inline std::vector<unsigned> arrayToVector(Local<Array> const& array) {
std::vector<unsigned> cpp_array;
cpp_array.reserve(array->Length());
for (uint32_t i = 0; i < array->Length(); i++) {
int64_t js_value = array->Get(i)->IntegerValue();
if (js_value < 0 || js_value >= std::numeric_limits<unsigned>::max()) {
std::stringstream s;
s << "value in array too large (cannot fit '" << js_value << "' in unsigned)";
throw std::runtime_error(s.str());
}
cpp_array.emplace_back(static_cast<unsigned>(js_value));
}
return cpp_array;
}
inline Local<Array> vectorToArray(Cache::intarray const& vector) {
std::size_t size = vector.size();
Local<Array> array = Nan::New<Array>(static_cast<int>(size));
for (uint32_t i = 0; i < size; i++) {
array->Set(i, Nan::New<Number>(vector[i]));
}
return array;
}
inline Local<Object> mapToObject(std::map<std::uint64_t,std::uint64_t> const& map) {
Local<Object> object = Nan::New<Object>();
for (auto const& item : map) {
object->Set(Nan::New<Number>(item.first), Nan::New<Number>(item.second));
}
return object;
}
inline std::string cacheGet(Cache const* c, std::string const& key) {
Cache::message_cache const& messages = c->msg_;
Cache::message_cache::const_iterator mitr = messages.find(key);
return mitr->second->second;
}
inline bool cacheHas(Cache const* c, std::string const& key) {
Cache::message_cache const& messages = c->msg_;
Cache::message_cache::const_iterator mitr = messages.find(key);
return mitr != messages.end();
}
inline void cacheInsert(Cache & c, std::string const& key, const char * data, std::size_t data_size) {
Cache::message_cache &messages = c.msg_;
Cache::message_cache::iterator mitr = messages.find(key);
if (mitr == messages.end()) {
Cache::message_list &list = c.msglist_;
list.emplace_front(key, std::string(data,data_size));
messages.emplace(key, list.begin());
if (list.size() > c.cachesize) {
messages.erase(list.back().first);
list.pop_back();
}
}
}
inline bool cacheRemove(Cache * c, std::string const& key) {
Cache::message_list &list = c->msglist_;
Cache::message_cache &messages = c->msg_;
Cache::message_cache::iterator mitr = messages.find(key);
if (mitr != messages.end()) {
list.erase(mitr->second);
messages.erase(mitr);
return true;
} else {
return false;
}
}
Cache::intarray __get(Cache const* c, std::string const& type, std::string const& shard, uint64_t id) {
std::string key = type + "-" + shard;
Cache::memcache const& mem = c->cache_;
Cache::memcache::const_iterator itr = mem.find(key);
Cache::intarray array;
if (itr == mem.end()) {
if (!cacheHas(c, key)) return array;
std::string ref = cacheGet(c, key);
protozero::pbf_reader message(ref);
while (message.next(CACHE_MESSAGE)) {
protozero::pbf_reader item = message.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
if (key_id != id) break;
item.next();
auto vals = item.get_packed_uint64();
uint64_t lastval = 0;
// delta decode values.
for (auto it = vals.first; it != vals.second; ++it) {
if (lastval == 0) {
lastval = *it;
array.emplace_back(lastval);
} else {
lastval = lastval - *it;
array.emplace_back(lastval);
}
}
return array;
}
}
return array;
} else {
Cache::arraycache::const_iterator aitr = itr->second.find(id);
if (aitr == itr->second.end()) {
return array;
} else {
return aitr->second;
}
}
}
Cache::intarray __getTruncated(Cache const* c, std::string const& type, std::string const& shard, uint64_t id, uint64_t truncate) {
std::string key = type + "-" + shard;
Cache::memcache const& mem = c->cache_;
Cache::memcache::const_iterator itr = mem.find(key);
Cache::intarray array;
if (itr == mem.end()) {
if (!cacheHas(c, key)) return array;
std::string ref = cacheGet(c, key);
protozero::pbf_reader message(ref);
while (message.next(CACHE_MESSAGE)) {
protozero::pbf_reader item = message.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
if (key_id != id) break;
item.next();
auto vals = item.get_packed_uint64();
uint64_t lastval = 0;
uint64_t length = 0;
// delta decode values.
for (auto it = vals.first; it != vals.second; ++it) {
if (lastval == 0) {
lastval = *it;
array.emplace_back(lastval);
} else {
lastval = lastval - *it;
array.emplace_back(lastval);
}
length++;
if (length >= truncate) break;
}
return array;
}
}
return array;
} else {
Cache::arraycache::const_iterator aitr = itr->second.find(id);
if (aitr == itr->second.end()) {
return array;
} else {
return aitr->second;
}
}
}
void Cache::Initialize(Handle<Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(Cache::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Cache").ToLocalChecked());
Nan::SetPrototypeMethod(t, "has", has);
Nan::SetPrototypeMethod(t, "loadSync", loadSync);
Nan::SetPrototypeMethod(t, "pack", pack);
Nan::SetPrototypeMethod(t, "merge", merge);
Nan::SetPrototypeMethod(t, "list", list);
Nan::SetPrototypeMethod(t, "_set", _set);
Nan::SetPrototypeMethod(t, "_get", _get);
Nan::SetPrototypeMethod(t, "unload", unload);
Nan::SetMethod(t, "coalesce", coalesce);
target->Set(Nan::New("Cache").ToLocalChecked(), t->GetFunction());
constructor.Reset(t);
}
Cache::Cache()
: ObjectWrap(),
cache_(),
msg_() {}
Cache::~Cache() { }
NAN_METHOD(Cache::pack)
{
if (info.Length() < 1) {
return Nan::ThrowTypeError("expected two info: 'type', 'shard'");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first argument must be a String");
}
if (!info[1]->IsNumber()) {
return Nan::ThrowTypeError("second arg must be an Integer");
}
try {
std::string type = *String::Utf8Value(info[0]->ToString());
std::string shard = *String::Utf8Value(info[1]->ToString());
std::string key = type + "-" + shard;
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::memcache const& mem = c->cache_;
Cache::memcache::const_iterator itr = mem.find(key);
if (itr != mem.end()) {
std::string message;
// Optimization idea: pre-pass on arrays to assemble guess about
// how long the final message will be in order to be able to call
// message.reserve(<length>)
protozero::pbf_writer writer(message);
for (auto const& item : itr->second) {
std::size_t array_size = item.second.size();
if (array_size > 0) {
protozero::pbf_writer item_writer(writer,1);
item_writer.add_uint64(1,item.first);
// make copy of intarray so we can sort without
// modifying the original array
Cache::intarray varr = item.second;
// delta-encode values, sorted in descending order.
std::sort(varr.begin(), varr.end(), std::greater<uint64_t>());
// Using new (in protozero 1.3.0) packed writing API
// https://github.com/mapbox/protozero/commit/4e7e32ac5350ea6d3dcf78ff5e74faeee513a6e1
protozero::packed_field_uint64 field{item_writer, 2};
uint64_t lastval = 0;
for (auto const& vitem : varr) {
if (lastval == 0) {
field.add_element(static_cast<uint64_t>(vitem));
} else {
field.add_element(static_cast<uint64_t>(lastval - vitem));
}
lastval = vitem;
}
}
}
if (message.empty()) {
return Nan::ThrowTypeError("pack: invalid message ByteSize encountered");
} else {
info.GetReturnValue().Set(Nan::CopyBuffer(message.data(), message.size()).ToLocalChecked());
return;
}
} else {
if (!cacheHas(c, key)) {
return Nan::ThrowTypeError("pack: cannot pack empty data");
} else {
std::string ref = cacheGet(c, key);
Local<Object> buf = Nan::CopyBuffer((char*)ref.data(), ref.size()).ToLocalChecked();
info.GetReturnValue().Set(buf);
return;
}
}
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::Undefined());
return;
}
struct MergeBaton : carmen::noncopyable {
uv_work_t request;
std::unique_ptr<std::string> pbf3;
const char * pbf1_data;
const char * pbf2_data;
std::string method;
std::string error;
Nan::Persistent<v8::Function> callback;
Nan::Persistent<v8::Object> buffer1;
Nan::Persistent<v8::Object> buffer2;
std::size_t pbf1_size;
std::size_t pbf2_size;
MergeBaton(Local<Object> obj1,
Local<Object> obj2,
Local<Value> cb,
std::string const& meth)
: pbf1_data(node::Buffer::Data(obj1)),
pbf1_size(node::Buffer::Length(obj1)),
pbf2_data(node::Buffer::Data(obj2)),
pbf2_size(node::Buffer::Length(obj2)),
pbf3(std::make_unique<std::string>()),
method(meth)
{
this->request.data = this;
callback.Reset(cb.As<Function>());
buffer1.Reset(obj1);
buffer2.Reset(obj2);
// Reserve memory at least at pbf1_size. TODO: should we reserve more?
pbf3.get()->reserve(pbf1_size);
}
~MergeBaton() {
callback.Reset();
buffer1.Reset();
buffer2.Reset();
}
};
void mergeQueue(uv_work_t* req) {
MergeBaton *baton = static_cast<MergeBaton *>(req->data);
std::string const& method = baton->method;
// Ids that have been seen
std::map<uint64_t,bool> ids1;
std::map<uint64_t,bool> ids2;
std::string & merged = *baton->pbf3.get();
try {
protozero::pbf_writer writer(merged);
// Store ids from 1
protozero::pbf_reader pre1(baton->pbf1_data,baton->pbf1_size);
while (pre1.next(CACHE_MESSAGE)) {
protozero::pbf_reader item = pre1.get_message();
while (item.next(CACHE_ITEM)) {
ids1.emplace(item.get_uint64(), true);
}
}
// Store ids from 2
protozero::pbf_reader pre2(baton->pbf2_data,baton->pbf2_size);
while (pre2.next(CACHE_MESSAGE)) {
protozero::pbf_reader item = pre2.get_message();
while (item.next(CACHE_ITEM)) {
ids2.emplace(item.get_uint64(), true);
}
}
// No delta writes from message1
protozero::pbf_reader message1(baton->pbf1_data,baton->pbf1_size);
while (message1.next(CACHE_MESSAGE)) {
protozero::pbf_writer item_writer(writer,1);
protozero::pbf_reader item = message1.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
// Skip this id if also in message 2
if (ids2.find(key_id) != ids2.end()) break;
item_writer.add_uint64(1,key_id);
item.next();
protozero::packed_field_uint64 field{item_writer, 2};
auto vals = item.get_packed_uint64();
for (auto it = vals.first; it != vals.second; ++it) {
field.add_element(static_cast<uint64_t>(*it));
}
}
}
// No delta writes from message2
protozero::pbf_reader message2(baton->pbf2_data,baton->pbf2_size);
while (message2.next(CACHE_MESSAGE)) {
protozero::pbf_writer item_writer(writer,1);
protozero::pbf_reader item = message2.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
// Skip this id if also in message 2
if (ids1.find(key_id) != ids1.end()) break;
item_writer.add_uint64(1,key_id);
item.next();
protozero::packed_field_uint64 field{item_writer, 2};
auto vals = item.get_packed_uint64();
for (auto it = vals.first; it != vals.second; ++it) {
field.add_element(static_cast<uint64_t>(*it));
}
}
}
// Delta writes for ids in both message1 and message2
protozero::pbf_reader overlap1(baton->pbf1_data,baton->pbf1_size);
while (overlap1.next(CACHE_MESSAGE)) {
protozero::pbf_writer item_writer(writer,1);
protozero::pbf_reader item = overlap1.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
// Skip ids that are only in one or the other lists
if (ids1.find(key_id) == ids1.end() || ids2.find(key_id) == ids2.end()) break;
item_writer.add_uint64(1,key_id);
item.next();
uint64_t lastval = 0;
Cache::intarray varr;
// Add values from pbf1
auto vals = item.get_packed_uint64();
for (auto it = vals.first; it != vals.second; ++it) {
if (method == "freq") {
varr.emplace_back(*it);
break;
} else if (lastval == 0) {
lastval = *it;
varr.emplace_back(lastval);
} else {
lastval = lastval - *it;
varr.emplace_back(lastval);
}
}
// Check pbf2 for this id and merge its items if found
protozero::pbf_reader overlap2(baton->pbf2_data,baton->pbf2_size);
while (overlap2.next(CACHE_MESSAGE)) {
protozero::pbf_reader item2 = overlap2.get_message();
while (item2.next(CACHE_ITEM)) {
uint64_t key_id2 = item2.get_uint64();
if (key_id2 != key_id) break;
item2.next();
lastval = 0;
auto vals2 = item2.get_packed_uint64();
for (auto it = vals2.first; it != vals2.second; ++it) {
if (method == "freq") {
if (key_id2 == 1) {
varr[0] = varr[0] > *it ? varr[0] : *it;
} else {
varr[0] = varr[0] + *it;
}
break;
} else if (lastval == 0) {
lastval = *it;
varr.emplace_back(lastval);
} else {
lastval = lastval - *it;
varr.emplace_back(lastval);
}
}
}
}
// Sort for proper delta encoding
std::sort(varr.begin(), varr.end(), std::greater<uint64_t>());
// Write varr to merged protobuf
protozero::packed_field_uint64 field{item_writer, 2};
lastval = 0;
for (auto const& vitem : varr) {
if (lastval == 0) {
field.add_element(static_cast<uint64_t>(vitem));
} else {
field.add_element(static_cast<uint64_t>(lastval - vitem));
}
lastval = vitem;
}
}
}
} catch (std::exception const& ex) {
baton->error = ex.what();
}
}
void mergeAfter(uv_work_t* req) {
Nan::HandleScope scope;
MergeBaton *baton = static_cast<MergeBaton *>(req->data);
if (!baton->error.empty()) {
v8::Local<v8::Value> argv[1] = { Nan::Error(baton->error.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(baton->callback), 1, argv);
} else {
std::string & merged = *baton->pbf3.get();
baton->pbf3.release();
v8::Local<v8::Value> argv[2] = { Nan::Null(),
Nan::NewBuffer(&merged[0],
merged.size(),
[](char *, void * hint) {
delete reinterpret_cast<std::string*>(hint);
},
baton->pbf3.get()
).ToLocalChecked()
};
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(baton->callback), 2, argv);
}
delete baton;
}
NAN_METHOD(Cache::list)
{
if (info.Length() < 1) {
return Nan::ThrowTypeError("expected at least one arg: 'type' and optional a 'shard'");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first argument must be a String");
}
try {
std::string type = *String::Utf8Value(info[0]->ToString());
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::memcache const& mem = c->cache_;
Cache::message_cache const& messages = c->msg_;
Local<Array> ids = Nan::New<Array>();
if (info.Length() == 1) {
unsigned idx = 0;
std::size_t type_size = type.size();
for (auto const& item : mem) {
std::size_t item_size = item.first.size();
if (item_size > type_size && item.first.substr(0,type_size) == type) {
std::string shard = item.first.substr(type_size+1,item_size);
ids->Set(idx++, Nan::New(Nan::New(shard.c_str()).ToLocalChecked()->NumberValue()));
}
}
for (auto const& item : messages) {
std::size_t item_size = item.first.size();
if (item_size > type_size && item.first.substr(0,type_size) == type) {
std::string shard = item.first.substr(type_size+1,item_size);
ids->Set(idx++, Nan::New(Nan::New(shard.c_str()).ToLocalChecked()->NumberValue()));
}
}
info.GetReturnValue().Set(ids);
return;
} else if (info.Length() == 2) {
std::string shard = *String::Utf8Value(info[1]->ToString());
std::string key = type + "-" + shard;
Cache::memcache::const_iterator itr = mem.find(key);
unsigned idx = 0;
if (itr != mem.end()) {
for (auto const& item : itr->second) {
ids->Set(idx++,Nan::New<Number>(item.first)->ToString());
}
}
// parse message for ids
if (cacheHas(c, key)) {
std::string ref = cacheGet(c, key);
protozero::pbf_reader message(ref);
while (message.next(CACHE_MESSAGE)) {
protozero::pbf_reader item = message.get_message();
while (item.next(CACHE_ITEM)) {
uint64_t key_id = item.get_uint64();
ids->Set(idx++, Nan::New<Number>(key_id)->ToString());
}
}
}
info.GetReturnValue().Set(ids);
return;
}
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::Undefined());
return;
}
NAN_METHOD(Cache::merge)
{
if (!info[0]->IsObject()) return Nan::ThrowTypeError("argument 1 must be a Buffer");
if (!info[1]->IsObject()) return Nan::ThrowTypeError("argument 2 must be a Buffer");
if (!info[2]->IsString()) return Nan::ThrowTypeError("argument 3 must be a String");
if (!info[3]->IsFunction()) return Nan::ThrowTypeError("argument 3 must be a callback function");
Local<Object> obj1 = info[0]->ToObject();
Local<Object> obj2 = info[1]->ToObject();
Local<Value> callback = info[3];
std::string method = *String::Utf8Value(info[2]->ToString());
if (obj1->IsNull() || obj1->IsUndefined() || !node::Buffer::HasInstance(obj1)) return Nan::ThrowTypeError("argument 1 must be a Buffer");
if (obj2->IsNull() || obj2->IsUndefined() || !node::Buffer::HasInstance(obj2)) return Nan::ThrowTypeError("argument 2 must be a Buffer");
MergeBaton *baton = new MergeBaton(obj1,obj2,callback,method);
uv_queue_work(uv_default_loop(), &baton->request, mergeQueue, (uv_after_work_cb)mergeAfter);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
NAN_METHOD(Cache::_set)
{
if (info.Length() < 3) {
return Nan::ThrowTypeError("expected four info: 'type', 'shard', 'id', 'data'");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first argument must be a String");
}
if (!info[1]->IsNumber()) {
return Nan::ThrowTypeError("second arg must be an Integer");
}
if (!info[2]->IsNumber()) {
return Nan::ThrowTypeError("third arg must be an Integer");
}
if (!info[3]->IsArray()) {
return Nan::ThrowTypeError("fourth arg must be an Array");
}
Local<Array> data = Local<Array>::Cast(info[3]);
if (data->IsNull() || data->IsUndefined()) {
return Nan::ThrowTypeError("an array expected for fourth argument");
}
try {
std::string type = *String::Utf8Value(info[0]->ToString());
std::string shard = *String::Utf8Value(info[1]->ToString());
std::string key = type + "-" + shard;
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::memcache & mem = c->cache_;
Cache::memcache::const_iterator itr = mem.find(key);
if (itr == mem.end()) {
c->cache_.emplace(key,Cache::arraycache());
}
Cache::arraycache & arrc = c->cache_[key];
Cache::arraycache::key_type key_id = static_cast<Cache::arraycache::key_type>(info[2]->IntegerValue());
Cache::arraycache::iterator itr2 = arrc.find(key_id);
if (itr2 == arrc.end()) {
arrc.emplace(key_id,Cache::intarray());
}
Cache::intarray & vv = arrc[key_id];
unsigned array_size = data->Length();
if (info[4]->IsBoolean() && info[4]->BooleanValue()) {
vv.reserve(vv.size() + array_size);
} else {
if (itr2 != arrc.end()) vv.clear();
vv.reserve(array_size);
}
for (unsigned i=0;i<array_size;++i) {
vv.emplace_back(static_cast<uint64_t>(data->Get(i)->NumberValue()));
}
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::Undefined());
return;
}
/*
Note: This function will not override data for keys already inserted into the cache
*/
NAN_METHOD(Cache::loadSync)
{
if (info.Length() < 2) {
return Nan::ThrowTypeError("expected at least three args: 'buffer', 'type', and 'shard'");
}
if (!info[0]->IsObject()) {
return Nan::ThrowTypeError("first argument must be a Buffer");
}
Local<Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined()) {
return Nan::ThrowTypeError("a buffer expected for first argument");
}
if (!node::Buffer::HasInstance(obj)) {
return Nan::ThrowTypeError("first argument must be a Buffer");
}
if (!info[1]->IsString()) {
return Nan::ThrowTypeError("second arg 'type' must be a String");
}
if (!info[2]->IsNumber()) {
return Nan::ThrowTypeError("third arg 'shard' must be an Integer");
}
try {
std::string type = *String::Utf8Value(info[1]->ToString());
std::string shard = *String::Utf8Value(info[2]->ToString());
std::string key = type + "-" + shard;
Cache & c = *node::ObjectWrap::Unwrap<Cache>(info.This());
cacheInsert(c, key, node::Buffer::Data(obj), node::Buffer::Length(obj));
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::Undefined());
return;
}
NAN_METHOD(Cache::has)
{
if (info.Length() < 2) {
return Nan::ThrowTypeError("expected two info: 'type' and 'shard'");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first arg must be a String");
}
if (!info[1]->IsNumber()) {
return Nan::ThrowTypeError("second arg must be an Integer");
}
try {
std::string type = *String::Utf8Value(info[0]->ToString());
std::string shard = *String::Utf8Value(info[1]->ToString());
std::string key = type + "-" + shard;
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::memcache const& mem = c->cache_;
Cache::memcache::const_iterator itr = mem.find(key);
if (itr != mem.end()) {
info.GetReturnValue().Set(Nan::True());
return;
} else {
if (cacheHas(c, key)) {
info.GetReturnValue().Set(Nan::True());
return;
} else {
info.GetReturnValue().Set(Nan::False());
return;
}
}
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
}
NAN_METHOD(Cache::_get)
{
if (info.Length() < 3) {
return Nan::ThrowTypeError("expected three info: type, shard, and id");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first arg must be a String");
}
if (!info[1]->IsNumber()) {
return Nan::ThrowTypeError("second arg must be an Integer");
}
if (!info[2]->IsNumber()) {
return Nan::ThrowTypeError("third arg must be a positive Integer");
}
try {
std::string type = *String::Utf8Value(info[0]->ToString());
std::string shard = *String::Utf8Value(info[1]->ToString());
int64_t id = info[2]->IntegerValue();
if (id < 0) {
return Nan::ThrowTypeError("third arg must be a positive Integer");
}
uint64_t id2 = static_cast<uint64_t>(id);
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::intarray vector = __get(c, type, shard, id2);
if (!vector.empty()) {
info.GetReturnValue().Set(vectorToArray(vector));
return;
} else {
info.GetReturnValue().Set(Nan::Undefined());
return;
}
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
}
NAN_METHOD(Cache::unload)
{
if (info.Length() < 2) {
return Nan::ThrowTypeError("expected at least two info: 'type' and 'shard'");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first arg must be a String");
}
if (!info[1]->IsNumber()) {
return Nan::ThrowTypeError("second arg must be an Integer");
}
bool hit = false;
try {
std::string type = *String::Utf8Value(info[0]->ToString());
std::string shard = *String::Utf8Value(info[1]->ToString());
std::string key = type + "-" + shard;
Cache* c = node::ObjectWrap::Unwrap<Cache>(info.This());
Cache::memcache & mem = c->cache_;
Cache::memcache::iterator itr = mem.find(key);
if (itr != mem.end()) {
hit = true;
mem.erase(itr);
}
hit = hit || cacheRemove(c, key);
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::New<Boolean>(hit));
return;
}
NAN_METHOD(Cache::New)
{
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Cannot call constructor as function, you need to use 'new' keyword");
}
try {
if (info.Length() < 1) {
return Nan::ThrowTypeError("expected 'id' argument");
}
if (!info[0]->IsString()) {
return Nan::ThrowTypeError("first argument 'id' must be a String");
}
Cache* im = new Cache();
if (info[1]->IsNumber()) {
im->cachesize = static_cast<unsigned>(info[1]->NumberValue());
}
im->Wrap(info.This());
info.This()->Set(Nan::New("id").ToLocalChecked(), info[0]);
info.GetReturnValue().Set(info.This());
return;
} catch (std::exception const& ex) {
return Nan::ThrowTypeError(ex.what());
}
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//relev = 5 bits
//count = 3 bits
//reason = 12 bits
//* 1 bit gap
//id = 32 bits
constexpr double _pow(double x, int y)
{
return y == 0 ? 1.0 : x * _pow(x, y-1);
}
constexpr uint64_t POW2_51 = static_cast<uint64_t>(_pow(2.0,51));
constexpr uint64_t POW2_48 = static_cast<uint64_t>(_pow(2.0,48));
constexpr uint64_t POW2_34 = static_cast<uint64_t>(_pow(2.0,34));
constexpr uint64_t POW2_28 = static_cast<uint64_t>(_pow(2.0,28));
constexpr uint64_t POW2_25 = static_cast<uint64_t>(_pow(2.0,25));
constexpr uint64_t POW2_20 = static_cast<uint64_t>(_pow(2.0,20));
constexpr uint64_t POW2_14 = static_cast<uint64_t>(_pow(2.0,14));
constexpr uint64_t POW2_3 = static_cast<uint64_t>(_pow(2.0,3));
constexpr uint64_t POW2_2 = static_cast<uint64_t>(_pow(2.0,2));
struct PhrasematchSubq {
carmen::Cache *cache;
double weight;
uint64_t phrase;
unsigned short idx;
unsigned short zoom;
unsigned short mask;
};
struct Cover {
double relev;
uint32_t id;
uint32_t tmpid;
unsigned short x;
unsigned short y;
unsigned short score;
unsigned short idx;
unsigned short mask;
unsigned distance;
double scoredist;
};
struct Context {
std::vector<Cover> coverList;
unsigned mask;
double relev;
Context(Cover && cov,
unsigned mask,
double relev)
: coverList(),
mask(mask),
relev(relev) {
coverList.emplace_back(std::move(cov));
}
Context& operator=(Context && c) {
coverList = std::move(c.coverList);
mask = std::move(c.mask);
relev = std::move(c.relev);
return *this;
}
Context(std::vector<Cover> && cl,
unsigned mask,
double relev)
: coverList(std::move(cl)),
mask(mask),
relev(relev) {}
Context(Context && c)
: coverList(std::move(c.coverList)),
mask(std::move(c.mask)),
relev(std::move(c.relev)) {}
};
Cover numToCover(uint64_t num) {
Cover cover;
assert(((num >> 34) % POW2_14) <= static_cast<double>(std::numeric_limits<unsigned short>::max()));
assert(((num >> 34) % POW2_14) >= static_cast<double>(std::numeric_limits<unsigned short>::min()));
unsigned short y = static_cast<unsigned short>((num >> 34) % POW2_14);
assert(((num >> 20) % POW2_14) <= static_cast<double>(std::numeric_limits<unsigned short>::max()));
assert(((num >> 20) % POW2_14) >= static_cast<double>(std::numeric_limits<unsigned short>::min()));
unsigned short x = static_cast<unsigned short>((num >> 20) % POW2_14);
assert(((num >> 48) % POW2_3) <= static_cast<double>(std::numeric_limits<unsigned short>::max()));
assert(((num >> 48) % POW2_3) >= static_cast<double>(std::numeric_limits<unsigned short>::min()));
unsigned short score = static_cast<unsigned short>((num >> 48) % POW2_3);
uint32_t id = static_cast<uint32_t>(num % POW2_20);
cover.x = x;
cover.y = y;
double relev = 0.4 + (0.2 * static_cast<double>((num >> 51) % POW2_2));
cover.relev = relev;
cover.score = score;
cover.id = id;
// These are not derived from decoding the input num but by
// external values after initialization.
cover.idx = 0;
cover.mask = 0;
cover.tmpid = 0;
cover.distance = 0;
return cover;
};
struct ZXY {
unsigned z;
unsigned x;
unsigned y;
};
ZXY pxy2zxy(unsigned z, unsigned x, unsigned y, unsigned target_z) {
ZXY zxy;
zxy.z = target_z;
// Interval between parent and target zoom level
unsigned zDist = target_z - z;
unsigned zMult = zDist - 1;
if (zDist == 0) {
zxy.x = x;
zxy.y = y;
return zxy;
}
// Midpoint length @ z for a tile at parent zoom level
unsigned pMid_d = static_cast<unsigned>(std::pow(2,zDist) / 2);
assert(pMid_d <= static_cast<double>(std::numeric_limits<unsigned>::max()));
assert(pMid_d >= static_cast<double>(std::numeric_limits<unsigned>::min()));
unsigned pMid = static_cast<unsigned>(pMid_d);
zxy.x = (x * zMult) + pMid;
zxy.y = (y * zMult) + pMid;
return zxy;
}
ZXY bxy2zxy(unsigned z, unsigned x, unsigned y, unsigned target_z, bool max=false) {
ZXY zxy;
zxy.z = target_z;
// Interval between parent and target zoom level
signed zDist = target_z - z;
if (zDist == 0) {
zxy.x = x;
zxy.y = y;
return zxy;
}
// zoom conversion multiplier
float mult = static_cast<float>(std::pow(2,zDist));
// zoom in min
if (zDist > 0 && !max) {
zxy.x = static_cast<unsigned>(static_cast<float>(x) * mult);
zxy.y = static_cast<unsigned>(static_cast<float>(y) * mult);
return zxy;
}
// zoom in max
else if (zDist > 0 && max) {
zxy.x = static_cast<unsigned>(static_cast<float>(x) * mult + (mult - 1));
zxy.y = static_cast<unsigned>(static_cast<float>(y) * mult + (mult - 1));
return zxy;
}
// zoom out
else {
unsigned mod = static_cast<unsigned>(std::pow(2,target_z));
unsigned xDiff = x % mod;
unsigned yDiff = y % mod;
unsigned newX = x - xDiff;
unsigned newY = y - yDiff;
zxy.x = static_cast<unsigned>(static_cast<float>(newX) * mult);
zxy.y = static_cast<unsigned>(static_cast<float>(newY) * mult);
return zxy;
}
}
inline bool coverSortByRelev(Cover const& a, Cover const& b) noexcept {
if (b.relev > a.relev) return false;
else if (b.relev < a.relev) return true;
else if (b.scoredist > a.scoredist) return false;
else if (b.scoredist < a.scoredist) return true;
else if (b.idx < a.idx) return false;
else if (b.idx > a.idx) return true;
else if (b.id < a.id) return false;
else if (b.id > a.id) return true;
// sorting by x and y is arbitrary but provides a more deterministic output order