-
Notifications
You must be signed in to change notification settings - Fork 8
/
indexer.js
1707 lines (1468 loc) · 51 KB
/
indexer.js
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
// PixlServer Storage System - Indexer Mixin
// Copyright (c) 2016 - 2020 Joseph Huckaby
// Released under the MIT License
var async = require('async');
var Class = require("pixl-class");
var Tools = require("pixl-tools");
var Perf = require("pixl-perf");
var nearley = require("nearley");
var pxql_grammar = require("./pxql.js");
var stemmer = require('porter-stemmer').stemmer;
var unidecode = require('unidecode');
var he = require('he');
var IndexerSingle = require("./indexer-single.js");
var DateIndexType = require("./index_types/Date.js");
var NumberIndexType = require("./index_types/Number.js");
module.exports = Class.create({
__mixins: [ IndexerSingle, DateIndexType, NumberIndexType ],
removeWordCache: null,
indexRecord: function(id, record, config, callback) {
// index record (transaction version)
var self = this;
// if no transactions, or transaction already in progress, jump to original func
if (!this.transactions || this.currentTransactionPath) {
return this._indexRecord(id, record, config, function(err, state) {
if (err) self.logError('index', "Indexing failed on record: " + id + ": " + err);
callback(err, state);
});
}
// use base path for transaction lock
var path = config.base_path;
// here we go
this.beginTransaction(path, function(err, clone) {
// transaction has begun
// call _indexRecord on CLONE (transaction-aware storage instance)
clone._indexRecord(id, record, config, function(err, state) {
if (err) {
// index generated an error
self.logError('index', "Indexing failed on record: " + id + ": " + err);
// emergency abort, rollback
self.abortTransaction(path, function() {
// call original callback with error that triggered rollback
if (callback) callback( err );
}); // abort
}
else {
// no error, commit transaction
self.commitTransaction(path, function(err) {
if (err) {
// commit failed, trigger automatic rollback
self.abortTransaction(path, function() {
// call original callback with commit error
if (callback) callback( err );
}); // abort
} // commit error
else {
// success! call original callback
if (callback) callback(null, state);
}
}); // commit
} // no error
}); // _indexRecord
}); // beginTransaction
},
validateIndexConfig: function(config) {
// make sure index config is kosher
// return false for success, or error on failure
if (!config || !config.fields || !Tools.isaArray(config.fields)) {
return( new Error("Invalid index configuration object.") );
}
if (Tools.findObject(config.fields, { _primary: 1 })) {
return( new Error("Invalid index configuration key: _primary") );
}
// validate each field def
for (var idx = 0, len = config.fields.length; idx < len; idx++) {
var def = config.fields[idx];
if (!def.id || !def.id.match(/^\w+$/)) {
return( new Error("Invalid index field ID: " + def.id) );
}
if (def.id.match(/^(_id|_data|_sorters|constructor|__defineGetter__|__defineSetter__|hasOwnProperty|__lookupGetter__|__lookupSetter__|isPrototypeOf|propertyIsEnumerable|toString|valueOf|__proto__|toLocaleString)$/)) {
return( new Error("Invalid index field ID: " + def.id) );
}
if (def.type && !this['prepIndex_' + def.type]) {
return( new Error("Invalid index type: " + def.type) );
}
if (def.filter && !this['filterWords_' + def.filter]) {
return( new Error("Invalid index filter: " + def.filter) );
}
} // foreach def
// validate each sorter def
if (config.sorters) {
if (!Tools.isaArray(config.sorters)) {
return( new Error("Invalid index sorters array.") );
}
for (var idx = 0, len = config.sorters.length; idx < len; idx++) {
var sorter = config.sorters[idx];
if (!sorter.id || !sorter.id.match(/^\w+$/)) {
return( new Error("Invalid index sorter ID: " + sorter.id) );
}
if (sorter.id.match(/^(_id|_data|_sorters|constructor|__defineGetter__|__defineSetter__|hasOwnProperty|__lookupGetter__|__lookupSetter__|isPrototypeOf|propertyIsEnumerable|toString|valueOf|__proto__|toLocaleString)$/)) {
return( new Error("Invalid index sorter ID: " + sorter.id) );
}
if (sorter.type && !sorter.type.match(/^(string|number)$/)) {
return( new Error("Invalid index sorter type: " + sorter.type) );
}
} // foreach sorter
} // config.sorters
return false; // no error
},
_indexRecord: function(id, record, config, callback) {
// index record (internal)
var self = this;
this.logDebug(8, "Indexing record: " + id, record);
var state = {
id: id,
config: config
};
// sanity checks
if (!id) {
if (callback) callback( new Error("Missing Record ID for indexing.") );
return;
}
// make sure ID is a string, and has some alphanumeric portion
id = '' + id;
var normal_id = this.normalizeKey(id);
if (!normal_id || !normal_id.match(/^\w/)) {
if (callback) callback( new Error("Invalid Record ID for indexing: " + id) );
return;
}
if (!record || !Tools.isaHash(record)) {
if (callback) callback( new Error("Invalid record object for index.") );
return;
}
// make sure we have a good config
var err = this.validateIndexConfig(config);
if (err) {
if (callback) callback(err);
return;
}
// generate list of fields based on available values in record
// i.e. support partial updates by only passing in those fields
var fields = [];
config.fields.forEach( function(def) {
var value = def.source.match(/\[.+\]/) ? Tools.sub(def.source, record, true) : Tools.getPath(record, def.source);
if (value === undefined) value = null;
if ((value === null) && ("default_value" in def)) value = def.default_value;
if (value !== null) fields.push(def);
} );
// start index and track perf
var pf = this.perf.begin('index');
// lock record (non-existent key, but it's record specific for the lock)
this.lock( config.base_path + '/' + id, true, function() {
// see if we've already indexed this record before
self.get( config.base_path + '/_data/' + id, function(err, idx_data) {
// check for fatal I/O error
if (err && (err.code != 'NoSuchKey')) {
self.unlock( config.base_path + '/' + id );
pf.end();
return callback(err);
}
if (!idx_data) {
idx_data = {};
state.new_record = true;
// add special index for primary ID (just a hash -- new records only)
fields.push({ _primary: 1 });
}
state.idx_data = idx_data;
state.changed = {};
// walk all fields in parallel (everything gets enqueued anyway)
async.each( fields,
function(def, callback) {
// process each index
if (def._primary) {
// primary id hash
var opts = { page_size: config.hash_page_size || 1000 };
self.hashPut( config.base_path + '/_id', id, 1, opts, callback );
return;
}
var value = def.source.match(/\[.+\]/) ? Tools.sub(def.source, record, true) : Tools.getPath(record, def.source);
if (value === undefined) value = null;
if ((value === null) && ("default_value" in def)) value = def.default_value;
if (typeof(value) == 'object') value = JSON.stringify(value);
var words = self.getWordList( ''+value, def, config );
var checksum = Tools.digestHex( words.join(' '), 'md5' );
var data = { words: words, checksum: checksum };
var old_data = idx_data[ def.id ];
self.logDebug(9, "Preparing data for index: " + def.id, {
value: value,
words: words,
checksum: checksum
});
if (def.delete) {
// special mode: delete index data
if (old_data) {
state.changed[ def.id ] = 1;
self.deleteIndex( old_data, def, state, callback );
}
else callback();
}
else if (old_data) {
// index exists, check if data has changed
if (checksum != old_data.checksum) {
// must reindex
state.changed[ def.id ] = 1;
self.updateIndex( old_data, data, ''+value, def, state, callback );
}
else {
// data not changed, no action required
self.logDebug(9, "Index value unchanged, skipping: " + def.id);
callback();
}
}
else {
// index doesn't exist for this record, create immediately
state.changed[ def.id ] = 1;
self.writeIndex( data, ''+value, def, state, callback );
}
}, // iterator
function(err) {
// everything indexed
if (err) {
self.unlock( config.base_path + '/' + id );
pf.end();
if (callback) callback(err);
return;
}
// now handle the sorters
async.eachLimit( config.sorters || [], self.concurrency,
function(sorter, callback) {
if (sorter.delete) self.deleteSorter( id, sorter, state, callback );
else self.updateSorter( record, sorter, state, callback );
},
function(err) {
// all sorters sorted
// save idx data for record
self.put( config.base_path + '/_data/' + id, idx_data, function(err) {
if (err) {
self.unlock( config.base_path + '/' + id );
pf.end();
if (callback) callback(err);
return;
}
var elapsed = pf.end();
if (!err) self.logTransaction('index', config.base_path, {
id: id,
elapsed_ms: elapsed
});
self.unlock( config.base_path + '/' + id );
if (callback) callback(err, state);
} ); // put (_data)
}
); // eachLimit (sorters)
} // done with fields
); // each (fields)
} ); // get (_data)
} ); // lock
},
unindexRecord: function(id, config, callback) {
// unindex record (transaction version)
var self = this;
// if no transactions, or transaction already in progress, jump to original func
if (!this.transactions || this.currentTransactionPath) {
return this._unindexRecord(id, config, callback);
}
// use base path for transaction lock
var path = config.base_path;
// here we go
this.beginTransaction(path, function(err, clone) {
// transaction has begun
// call _unindexRecord on CLONE (transaction-aware storage instance)
clone._unindexRecord(id, config, function(err, state) {
if (err) {
// index generated an error
// emergency abort, rollback
self.abortTransaction(path, function() {
// call original callback with error that triggered rollback
if (callback) callback( err );
}); // abort
}
else {
// no error, commit transaction
self.commitTransaction(path, function(err) {
if (err) {
// commit failed, trigger automatic rollback
self.abortTransaction(path, function() {
// call original callback with commit error
if (callback) callback( err );
}); // abort
} // commit error
else {
// success! call original callback
if (callback) callback(null, state);
}
}); // commit
} // no error
}); // _unindexRecord
}); // beginTransaction
},
_unindexRecord: function(id, config, callback) {
// unindex record (internal)
var self = this;
this.logDebug(8, "Unindexing record: " + id);
var state = {
id: id,
config: config
};
// sanity checks
if (!id) {
if (callback) callback( new Error("Invalid ID for record index.") );
return;
}
// make sure we have a good config
var err = this.validateIndexConfig(config);
if (err) {
if (callback) callback(err);
return;
}
// copy fields so we can add the special primary one
var fields = [];
for (var idx = 0, len = config.fields.length; idx < len; idx++) {
fields.push( config.fields[idx] );
}
// add special index for primary ID (just a hash)
fields.push({ _primary: 1 });
// start unindex and track perf
var pf = this.perf.begin('unindex');
// lock record (non-existent key, but it's record specific for the lock)
this.lock( config.base_path + '/' + id, true, function() {
// see if we've indexed this record before
self.get( config.base_path + '/_data/' + id, function(err, idx_data) {
// check for error
if (err) {
self.unlock( config.base_path + '/' + id );
pf.end();
return callback(err);
}
state.idx_data = idx_data;
state.changed = {};
// walk all fields in parallel (everything gets enqueued anyway)
async.each( fields,
function(def, callback) {
// primary id hash
if (def._primary) {
self.hashDelete( config.base_path + '/_id', id, callback );
return;
}
// check if index exists
var data = idx_data[ def.id ];
if (data) {
// index exists, proceed with delete
state.changed[ def.id ] = 1;
self.deleteIndex( data, def, state, callback );
}
else callback();
},
function(err) {
// everything unindexed
if (err) {
self.unlock( config.base_path + '/' + id );
pf.end();
if (callback) callback(err);
return;
}
// delete main idx data record
self.delete( config.base_path + '/_data/' + id, function(err) {
if (err) {
self.unlock( config.base_path + '/' + id );
pf.end();
if (callback) callback(err);
return;
}
// now handle the sorters
async.eachLimit( config.sorters || [], self.concurrency,
function(sorter, callback) {
self.deleteSorter( id, sorter, state, callback );
},
function(err) {
// all sorters sorted
var elapsed = pf.end();
if (!err) self.logTransaction('unindex', config.base_path, {
id: id,
elapsed_ms: elapsed
});
self.unlock( config.base_path + '/' + id );
if (callback) callback(err, state);
}
); // eachLimit (sorters)
} ); // delete (_data)
} // done (fields)
); // each (fields)
} ); // get (_data)
} ); // lock
},
writeIndex: function(data, raw_value, def, state, callback) {
// create or update single field index
var self = this;
var words = data.words;
// check for custom index prep function
if (def.type) {
var func = 'prepIndex_' + def.type;
if (self[func]) {
var result = self[func]( words, def, state );
if (result === false) {
if (callback) {
callback( new Error("Invalid data for index: " + def.id + ": " + words.join(' ')) );
}
return;
}
data.words = words = result;
}
}
this.logDebug(9, "Indexing field: " + def.id + " for record: " + state.id, words);
var base_path = state.config.base_path + '/' + def.id;
var word_hash = this.getWordHashFromList( words );
// first, save idx record (word list and checksum)
state.idx_data[ def.id ] = data;
// word list may be empty
if (!words.length && !def.master_list) {
self.logDebug(9, "Word list is empty, skipping " + def.id + " for record: " + state.id);
if (callback) callback();
return;
}
// now index each unique word
var group = {
count: Tools.numKeys(word_hash),
callback: callback || null
};
// lock index for this
self.lock( base_path, true, function() {
// update master list if applicable
if (def.master_list) {
group.count++;
self.indexEnqueue({
action: 'custom',
label: 'writeIndexSummary',
handler: self.writeIndexSummary.bind(self),
def: def,
group: group,
base_path: base_path,
word_hash: word_hash,
raw_value: raw_value
});
} // master_list
for (var word in word_hash) {
var value = word_hash[word];
var path = base_path + '/word/' + word;
self.indexEnqueue({
action: 'custom',
label: 'writeIndexWord',
handler: self.writeIndexWord.bind(self),
hash_page_size: state.config.hash_page_size || 1000,
// config: state.config,
group: group,
word: word,
id: state.id,
base_path: base_path,
path: path,
value: value
});
} // foreach word
} ); // lock
},
writeIndexWord: function(task, callback) {
// index single word, invoked from storage queue
var self = this;
var opts = { page_size: task.hash_page_size || 1000, word: task.word };
this.logDebug(10, "Indexing word: " + task.path + " for record: " + task.id);
this.hashPut( task.path, task.id, task.value, opts, function(err) {
if (err) {
// this will bubble up at the end of the group
task.group.error = "Failed to write index data: " + task.path + ": " + err.message;
self.logError('index', task.group.error);
}
// check to see if we are the last task in the group
task.group.count--;
if (!task.group.count) {
// group is complete, unlock and fire secondary callback if applicable
self.unlock(task.base_path);
if (task.group.callback) task.group.callback(task.group.error);
} // last item in group
// queue callback
callback();
} ); // hashPut
},
writeIndexSummary: function(task, callback) {
// index summary of words (record counts per word), invoked from storage queue
var self = this;
this.logDebug(10, "Updating summary index: " + task.base_path);
var path = task.base_path + '/summary';
var word_hash = task.word_hash;
this.lock( path, true, function() {
// locked
self.get( path, function(err, summary) {
if (err && (err.code != 'NoSuchKey')) {
// serious I/O error, need to bubble this up
task.group.error = "Failed to get index summary data: " + path + ": " + err.message;
self.logError('index', task.group.error);
}
if (err || !summary) {
summary = { id: task.def.id, values: {} };
}
summary.values = Tools.copyHashRemoveProto( summary.values );
summary.modified = Tools.timeNow(true);
for (var word in word_hash) {
if (!summary.values[word]) summary.values[word] = 0;
summary.values[word]++;
if (task.def.master_labels) {
if (!summary.labels) summary.labels = {};
summary.labels[word] = task.raw_value;
}
} // foreach word
// save summary back to storage
self.put( path, summary, function(err) {
self.unlock( path );
if (err) {
// this will bubble up at the end of the group
task.group.error = "Failed to write index summary data: " + path + ": " + err.message;
self.logError('index', task.group.error);
}
// check to see if we are the last task in the group
task.group.count--;
if (!task.group.count) {
// group is complete, unlock and fire secondary callback if applicable
self.unlock(task.base_path);
if (task.group.callback) task.group.callback(task.group.error);
} // last item in group
// queue callback
callback();
} ); // put
} ); // get
} ); // lock
},
deleteIndex: function(data, def, state, callback) {
// delete index
// this must be sequenced before a reindex
var self = this;
var words = data.words;
// check for custom index prep delete function
if (def.type) {
var func = 'prepDeleteIndex_' + def.type;
if (self[func]) {
self[func]( words, def, state );
}
}
this.logDebug(9, "Unindexing field: " + def.id + " for record: " + state.id, words);
var base_path = state.config.base_path + '/' + def.id;
var word_hash = this.getWordHashFromList( words );
// first, delete idx record (word list and checksum)
delete state.idx_data[ def.id ];
// word list may be empty
if (!words.length && !def.master_list) {
self.logDebug(9, "Word list is empty, skipping " + def.id + " for record: " + state.id);
if (callback) callback();
return;
}
// now unindex each unique word
var group = {
count: Tools.numKeys(word_hash),
callback: callback || null
};
// lock index for this
self.lock( base_path, true, function() {
// update master list if applicable
if (def.master_list) {
group.count++;
self.indexEnqueue({
action: 'custom',
label: 'deleteIndexSummary',
handler: self.deleteIndexSummary.bind(self),
def: def,
group: group,
base_path: base_path,
word_hash: word_hash
});
} // master_list
for (var word in word_hash) {
var path = base_path + '/word/' + word;
self.indexEnqueue({
action: 'custom',
label: 'deleteIndexWord',
handler: self.deleteIndexWord.bind(self),
group: group,
word: word,
id: state.id,
base_path: base_path,
path: path
});
} // foreach word
} ); // lock
},
deleteIndexWord: function(task, callback) {
// delete single word, invoked from storage queue
var self = this;
this.logDebug(10, "Unindexing word: " + task.path + " for record: " + task.id);
this.hashDelete( task.path, task.id, true, function(err) {
if (err) {
var err_msg = "Failed to write index data: " + task.path + ": " + err.message;
self.logError('index', err_msg);
// check for fatal I/O
if (err.code != 'NoSuchKey') {
// this will bubble up at end
task.group.error = err_msg;
}
}
// check to see if we are the last task in the group
task.group.count--;
if (!task.group.count) {
// group is complete, unlock and fire secondary callback if applicable
self.unlock(task.base_path);
if (task.group.callback) task.group.callback(task.group.error);
} // last item in group
// queue callback
callback();
} ); // hashDelete
},
deleteIndexSummary: function(task, callback) {
// delete summary of words (record counts per word), invoked from storage queue
var self = this;
this.logDebug(10, "Removing words from summary index: " + task.base_path, task.word_hash);
var path = task.base_path + '/summary';
var word_hash = task.word_hash;
this.lock( path, true, function() {
// locked
self.get( path, function(err, summary) {
if (err && (err.code != 'NoSuchKey')) {
// serious I/O error, need to bubble this up
task.group.error = "Failed to get index summary data: " + path + ": " + err.message;
self.logError('index', task.group.error);
}
if (err || !summary) {
// index summary doesn't exist, huh
self.logDebug(5, "Index summary doesn't exist: " + path);
summary = { id: task.def.id, values: {} };
}
summary.values = Tools.copyHashRemoveProto( summary.values );
summary.modified = Tools.timeNow(true);
for (var word in word_hash) {
if (summary.values[word]) summary.values[word]--;
if (!summary.values[word]) {
delete summary.values[word];
if (task.def.master_labels && summary.labels) delete summary.labels[word];
}
} // foreach word
// save summary back to storage
self.put( path, summary, function(err) {
self.unlock( path );
if (err) {
// this will bubble up at the end of the group
task.group.error = "Failed to write index summary data: " + path + ": " + err.message;
self.logError('index', task.group.error);
}
// check to see if we are the last task in the group
task.group.count--;
if (!task.group.count) {
// group is complete, unlock and fire secondary callback if applicable
self.unlock(task.base_path);
if (task.group.callback) task.group.callback(task.group.error);
} // last item in group
// queue callback
callback();
} ); // put
} ); // get
} ); // lock
},
updateIndex: function(old_data, new_data, raw_value, def, state, callback) {
// efficiently update single field index
var self = this;
var old_words = old_data.words;
var new_words = new_data.words;
// check for custom index prep function
// we only need this on the new words
if (def.type) {
var func = 'prepIndex_' + def.type;
if (self[func]) {
var result = self[func]( new_words, def, state );
if (result === false) {
if (callback) {
callback( new Error("Invalid data for index: " + def.id + ": " + new_words.join(' ')) );
}
return;
}
new_data.words = new_words = result;
}
}
this.logDebug(9, "Updating Index: " + def.id + " for record: " + state.id, new_words);
var base_path = state.config.base_path + '/' + def.id;
var old_word_hash = this.getWordHashFromList( old_words );
var new_word_hash = this.getWordHashFromList( new_words );
// calculate added, changed and removed words
var added_words = Object.create(null);
var changed_words = Object.create(null);
var removed_words = Object.create(null);
for (var new_word in new_word_hash) {
var new_value = new_word_hash[new_word];
if (!(new_word in old_word_hash)) {
// added new word
added_words[new_word] = new_value;
}
if (new_value != old_word_hash[new_word]) {
// also includes added, which is fine
changed_words[new_word] = new_value;
}
}
for (var old_word in old_word_hash) {
if (!(old_word in new_word_hash)) {
// word removed
removed_words[old_word] = 1;
}
}
// write idx record (word list and checksum)
state.idx_data[ def.id ] = new_data;
// now index each unique word
var group = {
count: Tools.numKeys(changed_words) + Tools.numKeys(removed_words),
callback: callback || null
};
if (!group.count) {
this.logDebug(9, "Actually, nothing changed in index: " + def.id + " for record: " + state.id + ", skipping updateIndex");
if (callback) callback();
return;
}
// lock index for this
self.lock( base_path, true, function() {
// update master list if applicable
if (def.master_list) {
if (Tools.numKeys(added_words) > 0) {
group.count++;
self.indexEnqueue({
action: 'custom',
label: 'writeIndexSummary',
handler: self.writeIndexSummary.bind(self),
def: def,
group: group,
base_path: base_path,
word_hash: added_words,
raw_value: raw_value
});
}
if (Tools.numKeys(removed_words) > 0) {
group.count++;
self.indexEnqueue({
action: 'custom',
label: 'deleteIndexSummary',
handler: self.deleteIndexSummary.bind(self),
def: def,
group: group,
base_path: base_path,
word_hash: removed_words
});
}
} // master_list
for (var word in changed_words) {
var value = changed_words[word];
var path = base_path + '/word/' + word;
self.indexEnqueue({
action: 'custom',
label: 'writeIndexWord',
handler: self.writeIndexWord.bind(self),
hash_page_size: state.config.hash_page_size || 1000,
// config: state.config,
group: group,
word: word,
id: state.id,
base_path: base_path,
path: path,
value: value
});
} // foreach changed word
for (var word in removed_words) {
var path = base_path + '/word/' + word;
self.indexEnqueue({
action: 'custom',
label: 'deleteIndexWord',
handler: self.deleteIndexWord.bind(self),
group: group,
word: word,
id: state.id,
base_path: base_path,
path: path
});
} // foreach removed word
} ); // lock
},
indexEnqueue: function(task) {
// special index version of enqueue()
// if we're in a transaction, call ORIGINAL enqueue() from parent
// this is because index queue items must execute right away -- they CANNOT wait until commit()
if (this.rawStorage) this.rawStorage.enqueue(task);
else this.enqueue(task);
},
updateSorter: function(record, sorter, state, callback) {
// add record to sorter index
var config = state.config;
var value = Tools.getPath(record, sorter.source);
if (value === undefined) value = null;
if ((value === null) && ("default_value" in sorter)) value = sorter.default_value;
if (value === null) {
if (state.new_record) value = ((sorter.type == 'number') ? 0 : '');
else return callback();
}
// store value in idx_data as well
if (!state.idx_data._sorters) state.idx_data._sorters = {};
else if ((sorter.id in state.idx_data._sorters) && (value == state.idx_data._sorters[sorter.id])) {
// sorter value unchanged, return immediately
this.logDebug(10, "Sorter value unchanged, skipping write: " + sorter.id + ": " + state.id + ": " + value);
return callback();
}
state.idx_data._sorters[sorter.id] = value;
var path = config.base_path + '/' + sorter.id + '/sort';
var opts = { page_size: config.sorter_page_size || 1000 };
this.logDebug(10, "Setting value in sorter: " + sorter.id + ": " + state.id + ": " + value);
this.hashPut( path, state.id, value, opts, callback );
},
deleteSorter: function(id, sorter, state, callback) {
// remove record from sorter index
var config = state.config;
var path = config.base_path + '/' + sorter.id + '/sort';
this.logDebug(10, "Removing record from sorter: " + sorter.id + ": " + id);
this.hashDelete( path, id, function(err) {
// only report actual I/O errors
if (err && (err.code != 'NoSuchKey')) {
return callback(err);
}
callback();
} );
},
filterWords_markdown: function(value) {
// filter out markdown syntax and html tags, entities
value = value.replace(/\n\`\`\`(.+?)\`\`\`/g, ''); // fenced code
return this.filterWords_html(value);
},
filterWords_html: function(value) {
// filter out html tags, entities
return he.decode( value.replace(/<.+?>/g, '') );
},
filterWords_alphanum: function(value) {
// filter out everything except alphanum + underscore
return value.replace(/\W+/g, '_').replace(/_+/g, '_');
},
filterWords_alphanum_array: function(value) {
// filter out everything except alphanum + underscore + comma, suitable for JSON arrays
return value.replace(/[\[\]\"\']+/g, '').replace(/[^\w\,]+/g, '_').replace(/_+/g, '_');
},
getWordList: function(value, def, config) {
// clean and filter text down to list of alphanumeric words
// return array of clean words
if (def.filter && this['filterWords_' + def.filter]) {
value = this['filterWords_' + def.filter]( value );
}
if (def.type && this['filterWords_' + def.type]) {
value = this['filterWords_' + def.type]( value );
}
// more text cleanup
if (!def.no_cleanup) {
value = unidecode( value ); // convert unicode to ascii
value = value.replace(/\w+\:\/\/([\w\-\.]+)\S*/g, '$1'); // index domains, not full urls
value = value.replace(/\'/g, ''); // index nancy's as nancys
value = value.replace(/\d+\.\d[\d\.]*/g, function(m) { return m.replace(/\./g, '_').replace(/_+$/, ''); }); // 2.5 --> 2_5
}