-
Notifications
You must be signed in to change notification settings - Fork 22
/
query_mediator.js
1005 lines (891 loc) Β· 29.5 KB
/
query_mediator.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
/**
* Created by rchyla on 3/30/14.
*/
/**
* Mediator to coordinate UI-query exchange
*/
define([
'underscore',
'jquery',
'cache',
'js/components/generic_module',
'js/mixins/dependon',
'js/mixins/add_secondary_sort',
'js/components/api_request',
'js/components/api_response',
'js/components/api_query_updater',
'js/components/api_feedback',
'js/components/json_response',
'js/components/api_targets',
'js/components/api_query',
'js/components/alerts',
'utils',
'analytics',
], function(
_,
$,
Cache,
GenericModule,
Dependon,
SecondarySort,
ApiRequest,
ApiResponse,
ApiQueryUpdater,
ApiFeedback,
JsonResponse,
ApiTargets,
ApiQuery,
Alerts,
utils,
analytics
) {
var QueryMediator = GenericModule.extend({
initialize: function(options) {
options = options || {};
this._cache = null;
this.debug = options.debug || false;
this.queryUpdater = new ApiQueryUpdater('QueryMediator');
this.failedRequestsCache = this._getNewCache({
expiresAfterWrite: 5,
});
this.maxRetries = options.maxRetries || 3;
this.recoveryDelayInMs = _.isNumber(options.recoveryDelayInMs)
? options.recoveryDelayInMs
: 700;
this.__searchCycle = {
waiting: {},
inprogress: {},
done: {},
failed: {},
};
this.shortDelayInMs = _.isNumber(options.shortDelayInMs)
? options.shortDelayInMs
: 300;
this.longDelayInMs = _.isNumber(options.longDelayInMs)
? options.longDelayInMs
: 100;
this.monitoringDelayInMs = _.isNumber(options.monitoringDelayInMs)
? options.monitoringDelayInMs
: 200;
this.mostRecentQuery = new ApiQuery();
},
activateCache: function(options) {
this._cache = this._getNewCache((options || {}).cache);
},
_getNewCache: function(options) {
return new Cache(
_.extend(
{
maximumSize: 100,
expiresAfterWrite: 60 * 30, // 30 mins
},
_.isObject(options) ? options : {}
)
);
},
/**
* Starts listening on the PubSub
*
* @param beehive - the full access instance; we excpect PubSub to be
* present
*/
activate: function(beehive, app) {
this.setBeeHive(beehive);
this.setApp(app);
var pubsub = this.getPubSub();
// if you run discovery-mediator; this signal may be removed from the
// queue (and instead, the discovery mediator will serve the request)
pubsub.subscribe(
pubsub.START_SEARCH,
_.bind(this.getQueryAndStartSearchCycle, this)
);
pubsub.subscribe(
pubsub.DELIVERING_REQUEST,
_.bind(this.receiveRequests, this)
);
pubsub.subscribe(
pubsub.EXECUTE_REQUEST,
_.bind(this.executeRequest, this)
);
pubsub.subscribe(pubsub.GET_QTREE, _.bind(this.getQTree, this));
},
getQTree: function(apiQuery, senderKey) {
var apiRequest = new ApiRequest({
query: apiQuery,
target: ApiTargets.QTREE,
});
this._executeRequest(apiRequest, senderKey);
},
doQueryTranslation: function(q) {
var d = $.Deferred();
var pubsub = this.getPubSub();
var options = {
type: 'POST',
contentType: 'application/json',
};
// Send the entire query to the "query" endpoint of the "object_service" micro service
// this endpoint will grab the "object:<expression>" from the query string and send back
// a translated query string which will have "simbid:<expression with SIMBAD identifiers>"
// instead of the "object:" part
var request = new ApiRequest({
target: ApiTargets.SERVICE_OBJECTS_QUERY,
query: new ApiQuery({
query: q,
}),
options: options,
});
// when the promise gets resolved, it will have the JSON response of the micro service
// which will have the translated object query
pubsub.subscribeOnce(pubsub.DELIVERING_RESPONSE, function(response) {
d.resolve(response.toJSON());
});
pubsub.publish(pubsub.EXECUTE_REQUEST, request);
return d.promise();
},
getQueryAndStartSearchCycle: function(apiQuery, senderKey) {
var that = this;
var ps = this.getPubSub();
// modifies apiQuery in place
SecondarySort.addSecondarySort(apiQuery);
// Watch for simbid references and use a masked version of the
// query to generate the url if any are found.
if (
this.original_url &&
apiQuery.get('q') &&
apiQuery.get('q')[0].indexOf('simbid') !== -1
) {
var newQ = apiQuery.clone();
var origQ = apiQuery.get('q')[0];
if (apiQuery.has('__original_query')) {
origQ = apiQuery.get('__original_query')[0];
}
// Use the old query for the clone's query string, then get url
newQ.set('q', origQ);
this.original_url = this.queryUpdater.clean(newQ).url();
} else {
this.original_url = this.queryUpdater.clean(apiQuery).url();
}
this.original_query = apiQuery.get('q');
// checking if it's a new big query
if (apiQuery.get('__bigquery')) {
apiQuery.set(
'bigquery',
'bibcode\n' + apiQuery.get('__bigquery').join('\n')
);
// don't need this anymore
apiQuery.unset('__bigquery');
// query might have a q, otherwise q is everything
if (!apiQuery.get('q')) apiQuery.set('q', '*:*');
// bigquery endpoint needs this value set
apiQuery.add('fq', '{!bitset}');
var request = new ApiRequest({
target: ApiTargets.MYADS_STORAGE + '/query',
query: apiQuery,
options: {
type: 'POST',
contentType: 'application/json',
done: function(response) {
var newQuery = new ApiQuery({
q: apiQuery.get('q'),
__qid: response.qid,
});
var bigquerySource = apiQuery.get('__bigquerySource');
if (bigquerySource) {
newQuery.set('__bigquerySource', bigquerySource[0]);
}
if (apiQuery.get('sort')) {
newQuery.set('sort', apiQuery.get('sort'));
}
that.startSearchCycle(newQuery, senderKey);
},
fail: function(jqXHR, textStatus, errorThrown) {
console.warn(
'bigquery failed:',
[].slice.apply(arguments).join(',')
);
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_FAILED_TO_START,
error: {
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown,
},
})
);
},
},
});
// it needs to be a bigquery, we need to formulate the query
this.getBeeHive()
.getService('Api')
.request(request);
}
// check if this is an "object:" query
else if (apiQuery.get('q')[0].indexOf('object:') > -1) {
// we have an "object:" query as part of the query
// first define a callback function to process the response of the micro service
// and bind it to "this" so that we can use the trigger
var callback = function(v) {
apiQuery.set({
q: v.query,
});
this.startSearchCycle(apiQuery, senderKey);
}.bind(this);
// call the callback function when the promise has been resolved
this.doQueryTranslation(apiQuery.get('q')[0]).done(callback);
} else {
this.startSearchCycle.apply(this, arguments);
}
},
/**
* Happens at the beginning of the new search cycle. This is the 'race started' signal
*/
startSearchCycle: function(apiQuery, senderKey) {
this.resetFailures();
// we have to clear selected records in app storage here too
if (this.getBeeHive().getObject('AppStorage')) {
this.getBeeHive()
.getObject('AppStorage')
.clearSelectedPapers();
}
// clear bigqueries by default when a new search cycle is started, unless
// explicitly saved by using "__saveBigQuery" flag
if (
apiQuery.has('__saveBigQuery') &&
this.mostRecentQuery.has('__qid') &&
!apiQuery.has('__qid')
) {
this.mostRecentQuery.set('q', apiQuery.get('q'));
apiQuery = this.mostRecentQuery;
}
this.mostRecentQuery = apiQuery;
if (this.debug) {
console.log(
'[QM]: received query:',
this.hasApp()
? this.getApp().getPluginOrWidgetName(senderKey.getId()) ||
senderKey.getId()
: senderKey.getId(),
apiQuery.url()
);
}
if (apiQuery.keys().length <= 0) {
console.error('[QM] : received empty query (huh?!)');
return;
}
if (apiQuery.get('q')[0].indexOf('simbid') > -1) {
apiQuery.add('__original_url', this.original_url);
apiQuery.add('__original_query', this.original_query);
}
var ps = this.getPubSub();
if (
this.__searchCycle.running &&
this.__searchCycle.waiting &&
_.keys(this.__searchCycle.waiting)
) {
console.error(
'The previous search cycle did not finish, and there already comes the next!'
);
// mark all current waiting requests with a STALE flag
_.forEach(
_.extend(
{},
this.__searchCycle.waiting,
this.__searchCycle.inprogress
),
function(psks) {
psks.request.__STALE = true;
}
);
}
this.reset();
this.__searchCycle.initiator = senderKey.getId();
this.__searchCycle.collectingRequests = true;
this.__searchCycle.query = apiQuery.clone();
// we will protect the query -- in the future i can consider removing 'unlock' to really
// cement the fact the query MUST NOT be changed (we want to receive a modified version)
var q = apiQuery.clone();
// q = this.queryUpdater.clean(q);
// since widgets are dirty bastards, we will remove the fl parameter (to avoid cross-
// contamination)
q.unset('fl');
q.lock();
ps.publish(ps.INVITING_REQUEST, q);
// give widgets some time to submit their requests
var self = this;
var startExecuting = function() {
self.__searchCycle.collectingRequests = false;
self.startExecutingQueries() && self.monitorExecution();
};
this.shortDelayInMs
? setTimeout(startExecuting, this.shortDelayInMs)
: startExecuting();
},
/**
* Starts executing queries from the search cycle
*
* Return value indicates whether the process starter;
* if 'true', then you can start monitoring
*
* @param force
*/
startExecutingQueries: function(force) {
var self = this;
var cycle = this.__searchCycle;
if (cycle.running) return; // safety barrier
if (_.isEmpty(cycle.waiting)) return;
if (!this.hasBeeHive()) return;
cycle.running = true;
var data;
var beehive = this.getBeeHive();
var api = beehive.getService('Api');
var ps = this.getPubSub();
if (!(ps && api)) return; // application is gone
var app = this.getApp();
var pskToExecuteFirst;
if ((pskToExecuteFirst = app.getPskOfPluginOrWidget('widget:Results'))) {
// pick a request that will be executed first
if (cycle.waiting[pskToExecuteFirst]) {
data = cycle.waiting[pskToExecuteFirst];
delete cycle.waiting[pskToExecuteFirst];
}
}
if (!data && cycle.waiting[cycle.initiator]) {
// grab the query/request which started the cycle
data = cycle.waiting[cycle.initiator];
delete cycle.waiting[cycle.initiator];
}
if (!data) {
if (this.debug)
console.warn(
'DynamicConfig does not tell us which request to execute first (grabbing random one).'
);
var kx;
data = cycle.waiting[(kx = _.keys(cycle.waiting)[0])];
delete cycle.waiting[kx];
}
// execute the first search (if it succeeds, fire the rest)
var firstReqKey = data.key.getId();
cycle.inprogress[firstReqKey] = data;
this._executeRequest(data.request, data.key)
.done(function(resOrPromise) {
const sendStartCycleEvent = (response) => {
if (data.request.__STALE) {
return;
}
cycle.done[firstReqKey] = data;
delete cycle.inprogress[firstReqKey];
var numFound;
if (response.response && response.response.numFound) {
numFound = response.response.numFound;
}
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_STARTED,
query: cycle.query,
request: data.request,
numFound: numFound,
cycle: cycle,
response: response, // this is a raw response (and it is save to send, cause it was already copied by the first 'done' callback
})
);
self.displayTugboatMessages();
};
if (resOrPromise.then) {
Promise.resolve(resOrPromise).then((response) => {
sendStartCycleEvent(response);
});
} else {
sendStartCycleEvent(resOrPromise);
}
// after we are done with the first query, start executing other queries
var f = function() {
_.each(_.keys(cycle.waiting), function(k) {
data = cycle.waiting[k];
delete cycle.waiting[k];
cycle.inprogress[k] = data;
var psk = k;
self._executeRequest
.call(self, data.request, data.key)
.done(function() {
if (data.request.__STALE) {
return;
}
cycle.done[psk] = cycle.inprogress[psk];
delete cycle.inprogress[psk];
})
.fail(function() {
if (data.request.__STALE) {
return;
}
cycle.failed[psk] = cycle.inprogress[psk];
delete cycle.inprogress[psk];
})
.always(function() {
if (cycle.finished) return;
if (_.isEmpty(cycle.inprogress)) {
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_FINISHED,
cycle: cycle,
})
);
cycle.finished = true;
}
});
});
};
// for the display experience, it is better to introduce delays
if (self.longDelayInMs && self.longDelayInMs > 0) {
setTimeout(function() {
f();
}, self.longDelayInMs);
} else {
f();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
self.__searchCycle.error = true;
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_FAILED_TO_START,
cycle: cycle,
request: this.request,
error: {
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown,
},
})
);
});
return true; // means that the process can be monitored
},
monitorExecution: function() {
if (!this.hasBeeHive()) return; // app is closed
var self = this;
var ps = this.getPubSub();
if (!ps) return; // application is gone
this.__searchCycle.monitor += 1;
if (this.__searchCycle.monitor > 100) {
console.warn('Stopping monitoring of queries, it is running too long');
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_STOP_MONITORING,
cycle: this.__searchCycle,
})
);
return;
}
if (
this.__searchCycle.inprogress &&
_.isEmpty(this.__searchCycle.inprogress)
) {
if (this.__searchCycle.finished) return; // it was already signalled
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_FINISHED,
cycle: this.__searchCycle,
})
);
return;
}
var lenToDo = _.keys(this.__searchCycle.waiting).length;
var lenDone = _.keys(this.__searchCycle.done).length;
var lenInProgress = _.keys(this.__searchCycle.inprogress).length;
var lenFailed = _.keys(this.__searchCycle.failed).length;
var total = lenToDo + lenDone + lenInProgress + lenFailed;
ps.publish(
ps.FEEDBACK,
new ApiFeedback({
code: ApiFeedback.CODES.SEARCH_CYCLE_PROGRESS,
msg: lenToDo / total,
total: total,
todo: lenToDo,
cycle: this.__searchCycle,
})
);
setTimeout(function() {
self.monitorExecution();
}, self.monitoringDelayInMs);
},
/**
* This method harvest requests from the PubSub and stores them inside internal
* datastruct
*
* @param apiRequest
* @param senderKey
*/
receiveRequests: function(apiRequest, senderKey) {
if (this.debug) {
console.log(
'[QM]: received request:',
this.hasApp()
? this.getApp().getPluginOrWidgetName(senderKey.getId()) ||
senderKey.getId()
: senderKey.getId(),
apiRequest.url()
);
}
if (this.__searchCycle.collectingRequests) {
this.__searchCycle.waiting[senderKey.getId()] = {
request: apiRequest,
key: senderKey,
};
} else {
this.executeRequest(apiRequest, senderKey);
}
},
/**
* This method executes a request, we check
* the local cache and also prepare context for the done/fail callbacks
*
* @param apiRequest
* @param senderKey
*/
executeRequest: function(apiRequest, senderKey) {
if (!(apiRequest instanceof ApiRequest)) {
throw new Error(
'Sir, I belive you forgot to send me a valid ApiRequest!'
);
} else if (!senderKey) {
throw new Error('Request executed, but no widget id provided!');
}
return this._executeRequest(apiRequest, senderKey);
},
getFailCacheValue(key) {
const failCache = this.failedRequestsCache;
return (
(failCache && failCache.getSync(key)) ||
(failCache._cache[key] && failCache._cache[key].value)
);
},
_executeRequest: function(apiRequest, senderKey) {
// for altering widget queries
// from regular solr requests to execute_query requests
// if bigquery is being used
// it's a bigquery
if (apiRequest.get('query') && apiRequest.get('query').get('__qid')) {
var qid = apiRequest.get('query').get('__qid')[0];
apiRequest.set(
'target',
ApiTargets.MYADS_STORAGE + '/execute_query/' + qid
);
}
var ps = this.getPubSub();
var api = this.getBeeHive().getService('Api');
var requestKey = this._getCacheKey(apiRequest);
var maxTry = this.getFailCacheValue(requestKey) || 0;
if (maxTry >= this.maxRetries) {
this.onApiRequestFailure.apply(
{
request: apiRequest,
key: senderKey,
requestKey: requestKey,
qm: this,
},
[
{ status: ApiFeedback.CODES.TOO_MANY_FAILURES },
'Error',
'This request has reached maximum number of failures (wait before retrying)',
]
);
var d = $.Deferred();
return d.reject();
}
if (this._cache) {
var resp = this._cache.getSync(requestKey);
var self = this;
if (resp && resp.promise) {
// we have already created ajax request
resp.done(function() {
self._cache.put(requestKey, arguments);
self.onApiResponse.apply(
{
request: apiRequest,
key: senderKey,
requestKey: requestKey,
qm: self,
},
arguments
);
});
resp.fail(function() {
self._cache.invalidate(requestKey);
self.onApiRequestFailure.apply(
{
request: apiRequest,
pubsub: ps,
key: senderKey,
requestKey: requestKey,
qm: self,
},
arguments
);
});
return resp;
}
if (resp) {
// we already have data (in the cache)
var defer = $.Deferred();
defer.done(function() {
self.onApiResponse.apply(
{
request: apiRequest,
key: senderKey,
requestKey: requestKey,
qm: self,
},
resp
);
});
defer.resolve();
return defer.promise();
}
// create a new query
var promise = api.request(apiRequest, {
done: function() {
self._cache.put(requestKey, arguments);
self.onApiResponse.apply(this, arguments);
},
fail: function() {
self._cache.invalidate(requestKey);
self.onApiRequestFailure.apply(this, arguments);
},
context: {
request: apiRequest,
key: senderKey,
requestKey: requestKey,
qm: self,
},
});
this._cache.put(requestKey, promise);
return promise;
}
return api.request(apiRequest, {
done: this.onApiResponse,
fail: this.onApiRequestFailure,
context: {
request: apiRequest,
key: senderKey,
requestKey: requestKey,
qm: this,
},
});
},
onApiResponse: function(data, textStatus, jqXHR) {
var qm = this.qm;
if (this.request.__STALE) {
return;
}
// TODO: check the status responses
var response =
data.responseHeader && data.responseHeader.params
? new ApiResponse(data)
: new JsonResponse(data);
response.setApiQuery(this.request.get('query'));
if (qm.debug) {
console.log(
'[QM]: sending response:',
qm.hasApp()
? qm.getApp().getPluginOrWidgetName(this.key.getId()) ||
this.key.getId()
: this.key.getId(),
data
);
}
var pubsub = qm.getBeeHive().getService('PubSub'); // we cant use getPubSub() as we are sending the key
if (pubsub)
pubsub.publish(
this.key,
pubsub.DELIVERING_RESPONSE + this.key.getId(),
response
);
if (qm.failedRequestsCache.getIfPresent(this.requestKey)) {
qm.failedRequestsCache.invalidate(this.requestKey);
}
},
onApiRequestFailure: function(jqXHR, textStatus, errorThrown) {
var qm = this.qm;
if (this.request.__STALE) {
return;
}
var query = this.request.get('query');
if (qm.debug) {
console.warn('[QM]: request failed', jqXHR, textStatus, errorThrown);
}
var errCount = qm.getFailCacheValue(this.requestKey) || 0;
qm.failedRequestsCache.put(this.requestKey, errCount + 1);
if (qm.tryToRecover.apply(this, arguments)) {
console.warn('[QM]: attempting recovery');
return true; // means we are trying to recover
}
var feedback = new ApiFeedback({
code: ApiFeedback.CODES.API_REQUEST_ERROR,
msg: textStatus,
request: this.request,
error: jqXHR,
psk: this.key,
errorThrown: errorThrown,
text: textStatus,
});
var pubsub = qm.getBeeHive().getService('PubSub');
if (pubsub) pubsub.publish(this.key, pubsub.FEEDBACK, feedback);
return false; // means: we gave up
},
/**
* Method that receives the same arguments as the error callback. It can try to
* recover (re-issue) the request. Note: it doesn't need to check whether the
* recovery is needed - if we are here, it means 'do what you can to recover'
*
* This method MUST return 'true' when the request was resent. If it doesn't
* return 'true' the sender will be notified about the error.
*
* If it returns a Feedback object, the sender will be notified using it
*
* @param jqXHR
* @param textStatus
* @param errorThrown
*/
tryToRecover: function(jqXHR, textStatus, errorThrown) {
var qm = this.qm; // QueryMediator
var senderKey = this.key;
var request = this.request;
var requestKey = this.requestKey;
var status = jqXHR.status;
if (status) {
switch (status) {
case 408: // proxy timeout
case 409: // conflict
case 500: // server error
case 502: // bad gateway
case 503: // service unavailable
case 504: // gateway timeout
analytics('send', 'event', 'introspection', 'retrying', status);
setTimeout(function() {
// we can remove the entry from the cache, because
// if they eventually succeed, sender will receive
// its data (because the promise object inside the
// cache contains the function to call delivery
if (qm._cache) {
var resp = qm._cache.getSync(requestKey);
if (resp && resp.promise) {
qm._cache.invalidate(requestKey);
} else if (resp) {
// it must have succeeded, good!
return;
}
}
// re-send the query
qm._executeRequest.call(qm, request, senderKey);
}, qm.recoveryDelayInMs);
return true;
break;
default:
analytics(
'send',
'event',
'introspection',
'not-retrying',
status,
JSON.stringify(qm.mostRecentQuery.toJSON())
);
}
}
},
/**
* Creates a unique, cleaned key from the request and the apiQuery
* @param apiRequest
*/
_getCacheKey: function(apiRequest) {
var oldQ = apiRequest.get('query');
var newQ = this.queryUpdater.clean(oldQ);
apiRequest.set('query', newQ);
var key = apiRequest.url();
apiRequest.set('query', oldQ);
return key;
},
reset: function() {
this.__searchCycle = {
waiting: {},
inprogress: {},
done: {},
failed: {},
}; // reset the datastruct
if (this._cache) {
this._cache.invalidateAll();
}
},
getAlerter: function() {
return this.getApp().getController(
this.alertsController || 'AlertsController'
);
},
// display tugboat messages if they exist
displayTugboatMessages: function() {
var TUGBOAT_MESSAGES = {
AUTHOR_ANDED_WARNING:
'Author search terms combined with AND rather than OR',
ENTRY_DATE_OFFSET_ERROR:
'Can not combine a date and offset (negative value) for the Entry Date',
ENTRY_DATE_NON_NUMERIC_ERROR:
'Found a non numeric value in the Entry Date',
UNRECOGNIZABLE_VALUE: 'Invalid value for {} supplied',
};
if (!this.original_url) {
// without the original url there can be no messages to display
return;
}
var messages = [].concat(
utils.qs('error_message', this.original_url, false) || [],
utils.qs('warning_message', this.original_url, false) || []
);
var uParams =
utils.qs('unprocessed_parameter', this.original_url, false) || [];
messages = _.reduce(
messages,
function(acc, msg) {
msg = msg.toUpperCase();
if (_.has(TUGBOAT_MESSAGES, msg)) {
var updatedMsg = TUGBOAT_MESSAGES[msg];
if (msg === 'UNRECOGNIZABLE_VALUE' && uParams.length > 0) {
var param = encodeURIComponent(uParams.pop());
updatedMsg = updatedMsg.replace(
'{}',
/^\w+$/.test(param) ? param : 'parameter'
);
}
acc.push(updatedMsg);
}
return acc;
},
[]
);
var message;
if (messages.length > 0) {
messages.push(
'See our <a style="text-decoration: underline; font-weight: bold" href="/help/faq/#classic-search-translator">docs</a> for more information'
);
message = messages.join('<br/>');
this.getAlerter().alert(
new ApiFeedback({
type: Alerts.TYPE.INFO,
msg: message,
})
);
}
},
resetFailures: function() {
this.failedRequestsCache.invalidateAll();
},