@interopio/search-api 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/changelog.md +20 -0
- package/dist/search-api.es.js +2344 -0
- package/dist/search-api.es.js.map +1 -0
- package/dist/search-api.umd.js +2352 -0
- package/dist/search-api.umd.js.map +1 -0
- package/license.md +9 -0
- package/package.json +52 -0
- package/search.d.ts +105 -0
- package/src/controllers/client.ts +352 -0
- package/src/controllers/glue.ts +154 -0
- package/src/controllers/main.ts +85 -0
- package/src/controllers/provider.ts +475 -0
- package/src/facade.ts +69 -0
- package/src/index.ts +19 -0
- package/src/models/client-query.ts +83 -0
- package/src/models/provider-query.ts +84 -0
- package/src/models/provider.ts +91 -0
- package/src/services/limits-tracker.ts +75 -0
- package/src/services/model-factory.ts +41 -0
- package/src/services/publisher.ts +178 -0
- package/src/services/sequelizer.ts +48 -0
- package/src/shared/constants.ts +11 -0
- package/src/shared/decoders.ts +123 -0
- package/src/shared/ioc.ts +118 -0
- package/src/shared/protocol.ts +71 -0
- package/src/shared/types.ts +103 -0
- package/src/shared/utils.ts +9 -0
|
@@ -0,0 +1,2344 @@
|
|
|
1
|
+
/******************************************************************************
|
|
2
|
+
Copyright (c) Microsoft Corporation.
|
|
3
|
+
|
|
4
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
5
|
+
purpose with or without fee is hereby granted.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
8
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
9
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
10
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
11
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
+
***************************************************************************** */
|
|
15
|
+
|
|
16
|
+
function __awaiter(thisArg, _arguments, P, generator) {
|
|
17
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
18
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
19
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
20
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
21
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
22
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let nanoid = (size = 21) =>
|
|
27
|
+
crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
|
|
28
|
+
byte &= 63;
|
|
29
|
+
if (byte < 36) {
|
|
30
|
+
id += byte.toString(36);
|
|
31
|
+
} else if (byte < 62) {
|
|
32
|
+
id += (byte - 26).toString(36).toUpperCase();
|
|
33
|
+
} else if (byte > 62) {
|
|
34
|
+
id += '-';
|
|
35
|
+
} else {
|
|
36
|
+
id += '_';
|
|
37
|
+
}
|
|
38
|
+
return id
|
|
39
|
+
}, '');
|
|
40
|
+
|
|
41
|
+
function createRegistry(options) {
|
|
42
|
+
if (options && options.errorHandling
|
|
43
|
+
&& typeof options.errorHandling !== "function"
|
|
44
|
+
&& options.errorHandling !== "log"
|
|
45
|
+
&& options.errorHandling !== "silent"
|
|
46
|
+
&& options.errorHandling !== "throw") {
|
|
47
|
+
throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
|
|
48
|
+
}
|
|
49
|
+
var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
|
|
50
|
+
var callbacks = {};
|
|
51
|
+
function add(key, callback, replayArgumentsArr) {
|
|
52
|
+
var callbacksForKey = callbacks[key];
|
|
53
|
+
if (!callbacksForKey) {
|
|
54
|
+
callbacksForKey = [];
|
|
55
|
+
callbacks[key] = callbacksForKey;
|
|
56
|
+
}
|
|
57
|
+
callbacksForKey.push(callback);
|
|
58
|
+
if (replayArgumentsArr) {
|
|
59
|
+
setTimeout(function () {
|
|
60
|
+
replayArgumentsArr.forEach(function (replayArgument) {
|
|
61
|
+
var _a;
|
|
62
|
+
if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
|
|
63
|
+
try {
|
|
64
|
+
if (Array.isArray(replayArgument)) {
|
|
65
|
+
callback.apply(undefined, replayArgument);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
callback.apply(undefined, [replayArgument]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
_handleError(err, key);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}, 0);
|
|
77
|
+
}
|
|
78
|
+
return function () {
|
|
79
|
+
var allForKey = callbacks[key];
|
|
80
|
+
if (!allForKey) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
allForKey = allForKey.reduce(function (acc, element, index) {
|
|
84
|
+
if (!(element === callback && acc.length === index)) {
|
|
85
|
+
acc.push(element);
|
|
86
|
+
}
|
|
87
|
+
return acc;
|
|
88
|
+
}, []);
|
|
89
|
+
if (allForKey.length === 0) {
|
|
90
|
+
delete callbacks[key];
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
callbacks[key] = allForKey;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function execute(key) {
|
|
98
|
+
var argumentsArr = [];
|
|
99
|
+
for (var _i = 1; _i < arguments.length; _i++) {
|
|
100
|
+
argumentsArr[_i - 1] = arguments[_i];
|
|
101
|
+
}
|
|
102
|
+
var callbacksForKey = callbacks[key];
|
|
103
|
+
if (!callbacksForKey || callbacksForKey.length === 0) {
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
var results = [];
|
|
107
|
+
callbacksForKey.forEach(function (callback) {
|
|
108
|
+
try {
|
|
109
|
+
var result = callback.apply(undefined, argumentsArr);
|
|
110
|
+
results.push(result);
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
results.push(undefined);
|
|
114
|
+
_handleError(err, key);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
return results;
|
|
118
|
+
}
|
|
119
|
+
function _handleError(exceptionArtifact, key) {
|
|
120
|
+
var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact);
|
|
121
|
+
if (_userErrorHandler) {
|
|
122
|
+
_userErrorHandler(errParam);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack;
|
|
126
|
+
if (options) {
|
|
127
|
+
switch (options.errorHandling) {
|
|
128
|
+
case "log":
|
|
129
|
+
return console.error(msg);
|
|
130
|
+
case "silent":
|
|
131
|
+
return;
|
|
132
|
+
case "throw":
|
|
133
|
+
throw new Error(msg);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
console.error(msg);
|
|
137
|
+
}
|
|
138
|
+
function clear() {
|
|
139
|
+
callbacks = {};
|
|
140
|
+
}
|
|
141
|
+
function clearKey(key) {
|
|
142
|
+
var callbacksForKey = callbacks[key];
|
|
143
|
+
if (!callbacksForKey) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
delete callbacks[key];
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
add: add,
|
|
150
|
+
execute: execute,
|
|
151
|
+
clear: clear,
|
|
152
|
+
clearKey: clearKey
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
createRegistry.default = createRegistry;
|
|
156
|
+
var lib = createRegistry;
|
|
157
|
+
|
|
158
|
+
const SEARCH_QUERY_STATUSES = {
|
|
159
|
+
done: "done",
|
|
160
|
+
inProgress: "in-progress",
|
|
161
|
+
error: "error"
|
|
162
|
+
};
|
|
163
|
+
const CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS = {
|
|
164
|
+
info: "info",
|
|
165
|
+
search: "search",
|
|
166
|
+
cancel: "cancel"
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Wraps values in an `Ok` type.
|
|
171
|
+
*
|
|
172
|
+
* Example: `ok(5) // => {ok: true, result: 5}`
|
|
173
|
+
*/
|
|
174
|
+
var ok = function (result) { return ({ ok: true, result: result }); };
|
|
175
|
+
/**
|
|
176
|
+
* Wraps errors in an `Err` type.
|
|
177
|
+
*
|
|
178
|
+
* Example: `err('on fire') // => {ok: false, error: 'on fire'}`
|
|
179
|
+
*/
|
|
180
|
+
var err = function (error) { return ({ ok: false, error: error }); };
|
|
181
|
+
/**
|
|
182
|
+
* Create a `Promise` that either resolves with the result of `Ok` or rejects
|
|
183
|
+
* with the error of `Err`.
|
|
184
|
+
*/
|
|
185
|
+
var asPromise = function (r) {
|
|
186
|
+
return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* Unwraps a `Result` and returns either the result of an `Ok`, or
|
|
190
|
+
* `defaultValue`.
|
|
191
|
+
*
|
|
192
|
+
* Example:
|
|
193
|
+
* ```
|
|
194
|
+
* Result.withDefault(5, number().run(json))
|
|
195
|
+
* ```
|
|
196
|
+
*
|
|
197
|
+
* It would be nice if `Decoder` had an instance method that mirrored this
|
|
198
|
+
* function. Such a method would look something like this:
|
|
199
|
+
* ```
|
|
200
|
+
* class Decoder<A> {
|
|
201
|
+
* runWithDefault = (defaultValue: A, json: any): A =>
|
|
202
|
+
* Result.withDefault(defaultValue, this.run(json));
|
|
203
|
+
* }
|
|
204
|
+
*
|
|
205
|
+
* number().runWithDefault(5, json)
|
|
206
|
+
* ```
|
|
207
|
+
* Unfortunately, the type of `defaultValue: A` on the method causes issues
|
|
208
|
+
* with type inference on the `object` decoder in some situations. While these
|
|
209
|
+
* inference issues can be solved by providing the optional type argument for
|
|
210
|
+
* `object`s, the extra trouble and confusion doesn't seem worth it.
|
|
211
|
+
*/
|
|
212
|
+
var withDefault = function (defaultValue, r) {
|
|
213
|
+
return r.ok === true ? r.result : defaultValue;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Return the successful result, or throw an error.
|
|
217
|
+
*/
|
|
218
|
+
var withException = function (r) {
|
|
219
|
+
if (r.ok === true) {
|
|
220
|
+
return r.result;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
throw r.error;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Apply `f` to the result of an `Ok`, or pass the error through.
|
|
228
|
+
*/
|
|
229
|
+
var map = function (f, r) {
|
|
230
|
+
return r.ok === true ? ok(f(r.result)) : r;
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* Apply `f` to the result of two `Ok`s, or pass an error through. If both
|
|
234
|
+
* `Result`s are errors then the first one is returned.
|
|
235
|
+
*/
|
|
236
|
+
var map2 = function (f, ar, br) {
|
|
237
|
+
return ar.ok === false ? ar :
|
|
238
|
+
br.ok === false ? br :
|
|
239
|
+
ok(f(ar.result, br.result));
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Apply `f` to the error of an `Err`, or pass the success through.
|
|
243
|
+
*/
|
|
244
|
+
var mapError = function (f, r) {
|
|
245
|
+
return r.ok === true ? r : err(f(r.error));
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* Chain together a sequence of computations that may fail, similar to a
|
|
249
|
+
* `Promise`. If the first computation fails then the error will propagate
|
|
250
|
+
* through. If it succeeds, then `f` will be applied to the value, returning a
|
|
251
|
+
* new `Result`.
|
|
252
|
+
*/
|
|
253
|
+
var andThen = function (f, r) {
|
|
254
|
+
return r.ok === true ? f(r.result) : r;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/*! *****************************************************************************
|
|
258
|
+
Copyright (c) Microsoft Corporation.
|
|
259
|
+
|
|
260
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
261
|
+
purpose with or without fee is hereby granted.
|
|
262
|
+
|
|
263
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
264
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
265
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
266
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
267
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
268
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
269
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
270
|
+
***************************************************************************** */
|
|
271
|
+
/* global Reflect, Promise */
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
var __assign = function() {
|
|
276
|
+
__assign = Object.assign || function __assign(t) {
|
|
277
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
278
|
+
s = arguments[i];
|
|
279
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
|
280
|
+
}
|
|
281
|
+
return t;
|
|
282
|
+
};
|
|
283
|
+
return __assign.apply(this, arguments);
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
function __rest(s, e) {
|
|
287
|
+
var t = {};
|
|
288
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
289
|
+
t[p] = s[p];
|
|
290
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
291
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
292
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
293
|
+
t[p[i]] = s[p[i]];
|
|
294
|
+
}
|
|
295
|
+
return t;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function isEqual(a, b) {
|
|
299
|
+
if (a === b) {
|
|
300
|
+
return true;
|
|
301
|
+
}
|
|
302
|
+
if (a === null && b === null) {
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
if (typeof (a) !== typeof (b)) {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
if (typeof (a) === 'object') {
|
|
309
|
+
// Array
|
|
310
|
+
if (Array.isArray(a)) {
|
|
311
|
+
if (!Array.isArray(b)) {
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
if (a.length !== b.length) {
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
for (var i = 0; i < a.length; i++) {
|
|
318
|
+
if (!isEqual(a[i], b[i])) {
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
// Hash table
|
|
325
|
+
var keys = Object.keys(a);
|
|
326
|
+
if (keys.length !== Object.keys(b).length) {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
for (var i = 0; i < keys.length; i++) {
|
|
330
|
+
if (!b.hasOwnProperty(keys[i])) {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
if (!isEqual(a[keys[i]], b[keys[i]])) {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/*
|
|
341
|
+
* Helpers
|
|
342
|
+
*/
|
|
343
|
+
var isJsonArray = function (json) { return Array.isArray(json); };
|
|
344
|
+
var isJsonObject = function (json) {
|
|
345
|
+
return typeof json === 'object' && json !== null && !isJsonArray(json);
|
|
346
|
+
};
|
|
347
|
+
var typeString = function (json) {
|
|
348
|
+
switch (typeof json) {
|
|
349
|
+
case 'string':
|
|
350
|
+
return 'a string';
|
|
351
|
+
case 'number':
|
|
352
|
+
return 'a number';
|
|
353
|
+
case 'boolean':
|
|
354
|
+
return 'a boolean';
|
|
355
|
+
case 'undefined':
|
|
356
|
+
return 'undefined';
|
|
357
|
+
case 'object':
|
|
358
|
+
if (json instanceof Array) {
|
|
359
|
+
return 'an array';
|
|
360
|
+
}
|
|
361
|
+
else if (json === null) {
|
|
362
|
+
return 'null';
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
return 'an object';
|
|
366
|
+
}
|
|
367
|
+
default:
|
|
368
|
+
return JSON.stringify(json);
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
var expectedGot = function (expected, got) {
|
|
372
|
+
return "expected " + expected + ", got " + typeString(got);
|
|
373
|
+
};
|
|
374
|
+
var printPath = function (paths) {
|
|
375
|
+
return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
|
|
376
|
+
};
|
|
377
|
+
var prependAt = function (newAt, _a) {
|
|
378
|
+
var at = _a.at, rest = __rest(_a, ["at"]);
|
|
379
|
+
return (__assign({ at: newAt + (at || '') }, rest));
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* Decoders transform json objects with unknown structure into known and
|
|
383
|
+
* verified forms. You can create objects of type `Decoder<A>` with either the
|
|
384
|
+
* primitive decoder functions, such as `boolean()` and `string()`, or by
|
|
385
|
+
* applying higher-order decoders to the primitives, such as `array(boolean())`
|
|
386
|
+
* or `dict(string())`.
|
|
387
|
+
*
|
|
388
|
+
* Each of the decoder functions are available both as a static method on
|
|
389
|
+
* `Decoder` and as a function alias -- for example the string decoder is
|
|
390
|
+
* defined at `Decoder.string()`, but is also aliased to `string()`. Using the
|
|
391
|
+
* function aliases exported with the library is recommended.
|
|
392
|
+
*
|
|
393
|
+
* `Decoder` exposes a number of 'run' methods, which all decode json in the
|
|
394
|
+
* same way, but communicate success and failure in different ways. The `map`
|
|
395
|
+
* and `andThen` methods modify decoders without having to call a 'run' method.
|
|
396
|
+
*
|
|
397
|
+
* Alternatively, the main decoder `run()` method returns an object of type
|
|
398
|
+
* `Result<A, DecoderError>`. This library provides a number of helper
|
|
399
|
+
* functions for dealing with the `Result` type, so you can do all the same
|
|
400
|
+
* things with a `Result` as with the decoder methods.
|
|
401
|
+
*/
|
|
402
|
+
var Decoder = /** @class */ (function () {
|
|
403
|
+
/**
|
|
404
|
+
* The Decoder class constructor is kept private to separate the internal
|
|
405
|
+
* `decode` function from the external `run` function. The distinction
|
|
406
|
+
* between the two functions is that `decode` returns a
|
|
407
|
+
* `Partial<DecoderError>` on failure, which contains an unfinished error
|
|
408
|
+
* report. When `run` is called on a decoder, the relevant series of `decode`
|
|
409
|
+
* calls is made, and then on failure the resulting `Partial<DecoderError>`
|
|
410
|
+
* is turned into a `DecoderError` by filling in the missing information.
|
|
411
|
+
*
|
|
412
|
+
* While hiding the constructor may seem restrictive, leveraging the
|
|
413
|
+
* provided decoder combinators and helper functions such as
|
|
414
|
+
* `andThen` and `map` should be enough to build specialized decoders as
|
|
415
|
+
* needed.
|
|
416
|
+
*/
|
|
417
|
+
function Decoder(decode) {
|
|
418
|
+
var _this = this;
|
|
419
|
+
this.decode = decode;
|
|
420
|
+
/**
|
|
421
|
+
* Run the decoder and return a `Result` with either the decoded value or a
|
|
422
|
+
* `DecoderError` containing the json input, the location of the error, and
|
|
423
|
+
* the error message.
|
|
424
|
+
*
|
|
425
|
+
* Examples:
|
|
426
|
+
* ```
|
|
427
|
+
* number().run(12)
|
|
428
|
+
* // => {ok: true, result: 12}
|
|
429
|
+
*
|
|
430
|
+
* string().run(9001)
|
|
431
|
+
* // =>
|
|
432
|
+
* // {
|
|
433
|
+
* // ok: false,
|
|
434
|
+
* // error: {
|
|
435
|
+
* // kind: 'DecoderError',
|
|
436
|
+
* // input: 9001,
|
|
437
|
+
* // at: 'input',
|
|
438
|
+
* // message: 'expected a string, got 9001'
|
|
439
|
+
* // }
|
|
440
|
+
* // }
|
|
441
|
+
* ```
|
|
442
|
+
*/
|
|
443
|
+
this.run = function (json) {
|
|
444
|
+
return mapError(function (error) { return ({
|
|
445
|
+
kind: 'DecoderError',
|
|
446
|
+
input: json,
|
|
447
|
+
at: 'input' + (error.at || ''),
|
|
448
|
+
message: error.message || ''
|
|
449
|
+
}); }, _this.decode(json));
|
|
450
|
+
};
|
|
451
|
+
/**
|
|
452
|
+
* Run the decoder as a `Promise`.
|
|
453
|
+
*/
|
|
454
|
+
this.runPromise = function (json) { return asPromise(_this.run(json)); };
|
|
455
|
+
/**
|
|
456
|
+
* Run the decoder and return the value on success, or throw an exception
|
|
457
|
+
* with a formatted error string.
|
|
458
|
+
*/
|
|
459
|
+
this.runWithException = function (json) { return withException(_this.run(json)); };
|
|
460
|
+
/**
|
|
461
|
+
* Construct a new decoder that applies a transformation to the decoded
|
|
462
|
+
* result. If the decoder succeeds then `f` will be applied to the value. If
|
|
463
|
+
* it fails the error will propagated through.
|
|
464
|
+
*
|
|
465
|
+
* Example:
|
|
466
|
+
* ```
|
|
467
|
+
* number().map(x => x * 5).run(10)
|
|
468
|
+
* // => {ok: true, result: 50}
|
|
469
|
+
* ```
|
|
470
|
+
*/
|
|
471
|
+
this.map = function (f) {
|
|
472
|
+
return new Decoder(function (json) { return map(f, _this.decode(json)); });
|
|
473
|
+
};
|
|
474
|
+
/**
|
|
475
|
+
* Chain together a sequence of decoders. The first decoder will run, and
|
|
476
|
+
* then the function will determine what decoder to run second. If the result
|
|
477
|
+
* of the first decoder succeeds then `f` will be applied to the decoded
|
|
478
|
+
* value. If it fails the error will propagate through.
|
|
479
|
+
*
|
|
480
|
+
* This is a very powerful method -- it can act as both the `map` and `where`
|
|
481
|
+
* methods, can improve error messages for edge cases, and can be used to
|
|
482
|
+
* make a decoder for custom types.
|
|
483
|
+
*
|
|
484
|
+
* Example of adding an error message:
|
|
485
|
+
* ```
|
|
486
|
+
* const versionDecoder = valueAt(['version'], number());
|
|
487
|
+
* const infoDecoder3 = object({a: boolean()});
|
|
488
|
+
*
|
|
489
|
+
* const decoder = versionDecoder.andThen(version => {
|
|
490
|
+
* switch (version) {
|
|
491
|
+
* case 3:
|
|
492
|
+
* return infoDecoder3;
|
|
493
|
+
* default:
|
|
494
|
+
* return fail(`Unable to decode info, version ${version} is not supported.`);
|
|
495
|
+
* }
|
|
496
|
+
* });
|
|
497
|
+
*
|
|
498
|
+
* decoder.run({version: 3, a: true})
|
|
499
|
+
* // => {ok: true, result: {a: true}}
|
|
500
|
+
*
|
|
501
|
+
* decoder.run({version: 5, x: 'abc'})
|
|
502
|
+
* // =>
|
|
503
|
+
* // {
|
|
504
|
+
* // ok: false,
|
|
505
|
+
* // error: {... message: 'Unable to decode info, version 5 is not supported.'}
|
|
506
|
+
* // }
|
|
507
|
+
* ```
|
|
508
|
+
*
|
|
509
|
+
* Example of decoding a custom type:
|
|
510
|
+
* ```
|
|
511
|
+
* // nominal type for arrays with a length of at least one
|
|
512
|
+
* type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
|
|
513
|
+
*
|
|
514
|
+
* const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
|
|
515
|
+
* array(values).andThen(arr =>
|
|
516
|
+
* arr.length > 0
|
|
517
|
+
* ? succeed(createNonEmptyArray(arr))
|
|
518
|
+
* : fail(`expected a non-empty array, got an empty array`)
|
|
519
|
+
* );
|
|
520
|
+
* ```
|
|
521
|
+
*/
|
|
522
|
+
this.andThen = function (f) {
|
|
523
|
+
return new Decoder(function (json) {
|
|
524
|
+
return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
|
|
525
|
+
});
|
|
526
|
+
};
|
|
527
|
+
/**
|
|
528
|
+
* Add constraints to a decoder _without_ changing the resulting type. The
|
|
529
|
+
* `test` argument is a predicate function which returns true for valid
|
|
530
|
+
* inputs. When `test` fails on an input, the decoder fails with the given
|
|
531
|
+
* `errorMessage`.
|
|
532
|
+
*
|
|
533
|
+
* ```
|
|
534
|
+
* const chars = (length: number): Decoder<string> =>
|
|
535
|
+
* string().where(
|
|
536
|
+
* (s: string) => s.length === length,
|
|
537
|
+
* `expected a string of length ${length}`
|
|
538
|
+
* );
|
|
539
|
+
*
|
|
540
|
+
* chars(5).run('12345')
|
|
541
|
+
* // => {ok: true, result: '12345'}
|
|
542
|
+
*
|
|
543
|
+
* chars(2).run('HELLO')
|
|
544
|
+
* // => {ok: false, error: {... message: 'expected a string of length 2'}}
|
|
545
|
+
*
|
|
546
|
+
* chars(12).run(true)
|
|
547
|
+
* // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
|
|
548
|
+
* ```
|
|
549
|
+
*/
|
|
550
|
+
this.where = function (test, errorMessage) {
|
|
551
|
+
return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Decoder primitive that validates strings, and fails on all other input.
|
|
556
|
+
*/
|
|
557
|
+
Decoder.string = function () {
|
|
558
|
+
return new Decoder(function (json) {
|
|
559
|
+
return typeof json === 'string'
|
|
560
|
+
? ok(json)
|
|
561
|
+
: err({ message: expectedGot('a string', json) });
|
|
562
|
+
});
|
|
563
|
+
};
|
|
564
|
+
/**
|
|
565
|
+
* Decoder primitive that validates numbers, and fails on all other input.
|
|
566
|
+
*/
|
|
567
|
+
Decoder.number = function () {
|
|
568
|
+
return new Decoder(function (json) {
|
|
569
|
+
return typeof json === 'number'
|
|
570
|
+
? ok(json)
|
|
571
|
+
: err({ message: expectedGot('a number', json) });
|
|
572
|
+
});
|
|
573
|
+
};
|
|
574
|
+
/**
|
|
575
|
+
* Decoder primitive that validates booleans, and fails on all other input.
|
|
576
|
+
*/
|
|
577
|
+
Decoder.boolean = function () {
|
|
578
|
+
return new Decoder(function (json) {
|
|
579
|
+
return typeof json === 'boolean'
|
|
580
|
+
? ok(json)
|
|
581
|
+
: err({ message: expectedGot('a boolean', json) });
|
|
582
|
+
});
|
|
583
|
+
};
|
|
584
|
+
Decoder.constant = function (value) {
|
|
585
|
+
return new Decoder(function (json) {
|
|
586
|
+
return isEqual(json, value)
|
|
587
|
+
? ok(value)
|
|
588
|
+
: err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
|
|
589
|
+
});
|
|
590
|
+
};
|
|
591
|
+
Decoder.object = function (decoders) {
|
|
592
|
+
return new Decoder(function (json) {
|
|
593
|
+
if (isJsonObject(json) && decoders) {
|
|
594
|
+
var obj = {};
|
|
595
|
+
for (var key in decoders) {
|
|
596
|
+
if (decoders.hasOwnProperty(key)) {
|
|
597
|
+
var r = decoders[key].decode(json[key]);
|
|
598
|
+
if (r.ok === true) {
|
|
599
|
+
// tslint:disable-next-line:strict-type-predicates
|
|
600
|
+
if (r.result !== undefined) {
|
|
601
|
+
obj[key] = r.result;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
else if (json[key] === undefined) {
|
|
605
|
+
return err({ message: "the key '" + key + "' is required but was not present" });
|
|
606
|
+
}
|
|
607
|
+
else {
|
|
608
|
+
return err(prependAt("." + key, r.error));
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return ok(obj);
|
|
613
|
+
}
|
|
614
|
+
else if (isJsonObject(json)) {
|
|
615
|
+
return ok(json);
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
return err({ message: expectedGot('an object', json) });
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
};
|
|
622
|
+
Decoder.array = function (decoder) {
|
|
623
|
+
return new Decoder(function (json) {
|
|
624
|
+
if (isJsonArray(json) && decoder) {
|
|
625
|
+
var decodeValue_1 = function (v, i) {
|
|
626
|
+
return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
|
|
627
|
+
};
|
|
628
|
+
return json.reduce(function (acc, v, i) {
|
|
629
|
+
return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
|
|
630
|
+
}, ok([]));
|
|
631
|
+
}
|
|
632
|
+
else if (isJsonArray(json)) {
|
|
633
|
+
return ok(json);
|
|
634
|
+
}
|
|
635
|
+
else {
|
|
636
|
+
return err({ message: expectedGot('an array', json) });
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
};
|
|
640
|
+
Decoder.tuple = function (decoders) {
|
|
641
|
+
return new Decoder(function (json) {
|
|
642
|
+
if (isJsonArray(json)) {
|
|
643
|
+
if (json.length !== decoders.length) {
|
|
644
|
+
return err({
|
|
645
|
+
message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
var result = [];
|
|
649
|
+
for (var i = 0; i < decoders.length; i++) {
|
|
650
|
+
var nth = decoders[i].decode(json[i]);
|
|
651
|
+
if (nth.ok) {
|
|
652
|
+
result[i] = nth.result;
|
|
653
|
+
}
|
|
654
|
+
else {
|
|
655
|
+
return err(prependAt("[" + i + "]", nth.error));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return ok(result);
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
};
|
|
665
|
+
Decoder.union = function (ad, bd) {
|
|
666
|
+
var decoders = [];
|
|
667
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
668
|
+
decoders[_i - 2] = arguments[_i];
|
|
669
|
+
}
|
|
670
|
+
return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
|
|
671
|
+
};
|
|
672
|
+
Decoder.intersection = function (ad, bd) {
|
|
673
|
+
var ds = [];
|
|
674
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
675
|
+
ds[_i - 2] = arguments[_i];
|
|
676
|
+
}
|
|
677
|
+
return new Decoder(function (json) {
|
|
678
|
+
return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
|
|
679
|
+
});
|
|
680
|
+
};
|
|
681
|
+
/**
|
|
682
|
+
* Escape hatch to bypass validation. Always succeeds and types the result as
|
|
683
|
+
* `any`. Useful for defining decoders incrementally, particularly for
|
|
684
|
+
* complex objects.
|
|
685
|
+
*
|
|
686
|
+
* Example:
|
|
687
|
+
* ```
|
|
688
|
+
* interface User {
|
|
689
|
+
* name: string;
|
|
690
|
+
* complexUserData: ComplexType;
|
|
691
|
+
* }
|
|
692
|
+
*
|
|
693
|
+
* const userDecoder: Decoder<User> = object({
|
|
694
|
+
* name: string(),
|
|
695
|
+
* complexUserData: anyJson()
|
|
696
|
+
* });
|
|
697
|
+
* ```
|
|
698
|
+
*/
|
|
699
|
+
Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
|
|
700
|
+
/**
|
|
701
|
+
* Decoder identity function which always succeeds and types the result as
|
|
702
|
+
* `unknown`.
|
|
703
|
+
*/
|
|
704
|
+
Decoder.unknownJson = function () {
|
|
705
|
+
return new Decoder(function (json) { return ok(json); });
|
|
706
|
+
};
|
|
707
|
+
/**
|
|
708
|
+
* Decoder for json objects where the keys are unknown strings, but the values
|
|
709
|
+
* should all be of the same type.
|
|
710
|
+
*
|
|
711
|
+
* Example:
|
|
712
|
+
* ```
|
|
713
|
+
* dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
|
|
714
|
+
* // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
|
|
715
|
+
* ```
|
|
716
|
+
*/
|
|
717
|
+
Decoder.dict = function (decoder) {
|
|
718
|
+
return new Decoder(function (json) {
|
|
719
|
+
if (isJsonObject(json)) {
|
|
720
|
+
var obj = {};
|
|
721
|
+
for (var key in json) {
|
|
722
|
+
if (json.hasOwnProperty(key)) {
|
|
723
|
+
var r = decoder.decode(json[key]);
|
|
724
|
+
if (r.ok === true) {
|
|
725
|
+
obj[key] = r.result;
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
return err(prependAt("." + key, r.error));
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return ok(obj);
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
return err({ message: expectedGot('an object', json) });
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
};
|
|
739
|
+
/**
|
|
740
|
+
* Decoder for values that may be `undefined`. This is primarily helpful for
|
|
741
|
+
* decoding interfaces with optional fields.
|
|
742
|
+
*
|
|
743
|
+
* Example:
|
|
744
|
+
* ```
|
|
745
|
+
* interface User {
|
|
746
|
+
* id: number;
|
|
747
|
+
* isOwner?: boolean;
|
|
748
|
+
* }
|
|
749
|
+
*
|
|
750
|
+
* const decoder: Decoder<User> = object({
|
|
751
|
+
* id: number(),
|
|
752
|
+
* isOwner: optional(boolean())
|
|
753
|
+
* });
|
|
754
|
+
* ```
|
|
755
|
+
*/
|
|
756
|
+
Decoder.optional = function (decoder) {
|
|
757
|
+
return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
|
|
758
|
+
};
|
|
759
|
+
/**
|
|
760
|
+
* Decoder that attempts to run each decoder in `decoders` and either succeeds
|
|
761
|
+
* with the first successful decoder, or fails after all decoders have failed.
|
|
762
|
+
*
|
|
763
|
+
* Note that `oneOf` expects the decoders to all have the same return type,
|
|
764
|
+
* while `union` creates a decoder for the union type of all the input
|
|
765
|
+
* decoders.
|
|
766
|
+
*
|
|
767
|
+
* Examples:
|
|
768
|
+
* ```
|
|
769
|
+
* oneOf(string(), number().map(String))
|
|
770
|
+
* oneOf(constant('start'), constant('stop'), succeed('unknown'))
|
|
771
|
+
* ```
|
|
772
|
+
*/
|
|
773
|
+
Decoder.oneOf = function () {
|
|
774
|
+
var decoders = [];
|
|
775
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
776
|
+
decoders[_i] = arguments[_i];
|
|
777
|
+
}
|
|
778
|
+
return new Decoder(function (json) {
|
|
779
|
+
var errors = [];
|
|
780
|
+
for (var i = 0; i < decoders.length; i++) {
|
|
781
|
+
var r = decoders[i].decode(json);
|
|
782
|
+
if (r.ok === true) {
|
|
783
|
+
return r;
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
errors[i] = r.error;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
var errorsList = errors
|
|
790
|
+
.map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
|
|
791
|
+
.join('", "');
|
|
792
|
+
return err({
|
|
793
|
+
message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
|
|
794
|
+
});
|
|
795
|
+
});
|
|
796
|
+
};
|
|
797
|
+
/**
|
|
798
|
+
* Decoder that always succeeds with either the decoded value, or a fallback
|
|
799
|
+
* default value.
|
|
800
|
+
*/
|
|
801
|
+
Decoder.withDefault = function (defaultValue, decoder) {
|
|
802
|
+
return new Decoder(function (json) {
|
|
803
|
+
return ok(withDefault(defaultValue, decoder.decode(json)));
|
|
804
|
+
});
|
|
805
|
+
};
|
|
806
|
+
/**
|
|
807
|
+
* Decoder that pulls a specific field out of a json structure, instead of
|
|
808
|
+
* decoding and returning the full structure. The `paths` array describes the
|
|
809
|
+
* object keys and array indices to traverse, so that values can be pulled out
|
|
810
|
+
* of a nested structure.
|
|
811
|
+
*
|
|
812
|
+
* Example:
|
|
813
|
+
* ```
|
|
814
|
+
* const decoder = valueAt(['a', 'b', 0], string());
|
|
815
|
+
*
|
|
816
|
+
* decoder.run({a: {b: ['surprise!']}})
|
|
817
|
+
* // => {ok: true, result: 'surprise!'}
|
|
818
|
+
*
|
|
819
|
+
* decoder.run({a: {x: 'cats'}})
|
|
820
|
+
* // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
|
|
821
|
+
* ```
|
|
822
|
+
*
|
|
823
|
+
* Note that the `decoder` is ran on the value found at the last key in the
|
|
824
|
+
* path, even if the last key is not found. This allows the `optional`
|
|
825
|
+
* decoder to succeed when appropriate.
|
|
826
|
+
* ```
|
|
827
|
+
* const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
|
|
828
|
+
*
|
|
829
|
+
* optionalDecoder.run({a: {b: {c: 'surprise!'}}})
|
|
830
|
+
* // => {ok: true, result: 'surprise!'}
|
|
831
|
+
*
|
|
832
|
+
* optionalDecoder.run({a: {b: 'cats'}})
|
|
833
|
+
* // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
|
|
834
|
+
*
|
|
835
|
+
* optionalDecoder.run({a: {b: {z: 1}}})
|
|
836
|
+
* // => {ok: true, result: undefined}
|
|
837
|
+
* ```
|
|
838
|
+
*/
|
|
839
|
+
Decoder.valueAt = function (paths, decoder) {
|
|
840
|
+
return new Decoder(function (json) {
|
|
841
|
+
var jsonAtPath = json;
|
|
842
|
+
for (var i = 0; i < paths.length; i++) {
|
|
843
|
+
if (jsonAtPath === undefined) {
|
|
844
|
+
return err({
|
|
845
|
+
at: printPath(paths.slice(0, i + 1)),
|
|
846
|
+
message: 'path does not exist'
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
|
|
850
|
+
return err({
|
|
851
|
+
at: printPath(paths.slice(0, i + 1)),
|
|
852
|
+
message: expectedGot('an object', jsonAtPath)
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
|
|
856
|
+
return err({
|
|
857
|
+
at: printPath(paths.slice(0, i + 1)),
|
|
858
|
+
message: expectedGot('an array', jsonAtPath)
|
|
859
|
+
});
|
|
860
|
+
}
|
|
861
|
+
else {
|
|
862
|
+
jsonAtPath = jsonAtPath[paths[i]];
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
return mapError(function (error) {
|
|
866
|
+
return jsonAtPath === undefined
|
|
867
|
+
? { at: printPath(paths), message: 'path does not exist' }
|
|
868
|
+
: prependAt(printPath(paths), error);
|
|
869
|
+
}, decoder.decode(jsonAtPath));
|
|
870
|
+
});
|
|
871
|
+
};
|
|
872
|
+
/**
|
|
873
|
+
* Decoder that ignores the input json and always succeeds with `fixedValue`.
|
|
874
|
+
*/
|
|
875
|
+
Decoder.succeed = function (fixedValue) {
|
|
876
|
+
return new Decoder(function (json) { return ok(fixedValue); });
|
|
877
|
+
};
|
|
878
|
+
/**
|
|
879
|
+
* Decoder that ignores the input json and always fails with `errorMessage`.
|
|
880
|
+
*/
|
|
881
|
+
Decoder.fail = function (errorMessage) {
|
|
882
|
+
return new Decoder(function (json) { return err({ message: errorMessage }); });
|
|
883
|
+
};
|
|
884
|
+
/**
|
|
885
|
+
* Decoder that allows for validating recursive data structures. Unlike with
|
|
886
|
+
* functions, decoders assigned to variables can't reference themselves
|
|
887
|
+
* before they are fully defined. We can avoid prematurely referencing the
|
|
888
|
+
* decoder by wrapping it in a function that won't be called until use, at
|
|
889
|
+
* which point the decoder has been defined.
|
|
890
|
+
*
|
|
891
|
+
* Example:
|
|
892
|
+
* ```
|
|
893
|
+
* interface Comment {
|
|
894
|
+
* msg: string;
|
|
895
|
+
* replies: Comment[];
|
|
896
|
+
* }
|
|
897
|
+
*
|
|
898
|
+
* const decoder: Decoder<Comment> = object({
|
|
899
|
+
* msg: string(),
|
|
900
|
+
* replies: lazy(() => array(decoder))
|
|
901
|
+
* });
|
|
902
|
+
* ```
|
|
903
|
+
*/
|
|
904
|
+
Decoder.lazy = function (mkDecoder) {
|
|
905
|
+
return new Decoder(function (json) { return mkDecoder().decode(json); });
|
|
906
|
+
};
|
|
907
|
+
return Decoder;
|
|
908
|
+
}());
|
|
909
|
+
|
|
910
|
+
/* tslint:disable:variable-name */
|
|
911
|
+
/** See `Decoder.string` */
|
|
912
|
+
var string = Decoder.string;
|
|
913
|
+
/** See `Decoder.number` */
|
|
914
|
+
var number = Decoder.number;
|
|
915
|
+
/** See `Decoder.boolean` */
|
|
916
|
+
Decoder.boolean;
|
|
917
|
+
/** See `Decoder.anyJson` */
|
|
918
|
+
var anyJson = Decoder.anyJson;
|
|
919
|
+
/** See `Decoder.unknownJson` */
|
|
920
|
+
Decoder.unknownJson;
|
|
921
|
+
/** See `Decoder.constant` */
|
|
922
|
+
var constant = Decoder.constant;
|
|
923
|
+
/** See `Decoder.object` */
|
|
924
|
+
var object = Decoder.object;
|
|
925
|
+
/** See `Decoder.array` */
|
|
926
|
+
var array = Decoder.array;
|
|
927
|
+
/** See `Decoder.tuple` */
|
|
928
|
+
Decoder.tuple;
|
|
929
|
+
/** See `Decoder.dict` */
|
|
930
|
+
Decoder.dict;
|
|
931
|
+
/** See `Decoder.optional` */
|
|
932
|
+
var optional = Decoder.optional;
|
|
933
|
+
/** See `Decoder.oneOf` */
|
|
934
|
+
var oneOf = Decoder.oneOf;
|
|
935
|
+
/** See `Decoder.union` */
|
|
936
|
+
Decoder.union;
|
|
937
|
+
/** See `Decoder.intersection` */
|
|
938
|
+
Decoder.intersection;
|
|
939
|
+
/** See `Decoder.withDefault` */
|
|
940
|
+
Decoder.withDefault;
|
|
941
|
+
/** See `Decoder.valueAt` */
|
|
942
|
+
Decoder.valueAt;
|
|
943
|
+
/** See `Decoder.succeed` */
|
|
944
|
+
Decoder.succeed;
|
|
945
|
+
/** See `Decoder.fail` */
|
|
946
|
+
Decoder.fail;
|
|
947
|
+
/** See `Decoder.lazy` */
|
|
948
|
+
Decoder.lazy;
|
|
949
|
+
|
|
950
|
+
const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
|
|
951
|
+
const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
|
|
952
|
+
const searchTypeDecoder = object({
|
|
953
|
+
name: nonEmptyStringDecoder,
|
|
954
|
+
displayName: optional(nonEmptyStringDecoder)
|
|
955
|
+
});
|
|
956
|
+
const providerData = object({
|
|
957
|
+
id: nonEmptyStringDecoder,
|
|
958
|
+
interopId: nonEmptyStringDecoder,
|
|
959
|
+
name: nonEmptyStringDecoder,
|
|
960
|
+
appName: optional(nonEmptyStringDecoder),
|
|
961
|
+
types: optional(array(searchTypeDecoder))
|
|
962
|
+
});
|
|
963
|
+
const providerLimitsDecoder = object({
|
|
964
|
+
maxResults: optional(nonNegativeNumberDecoder),
|
|
965
|
+
maxResultsPerType: optional(nonNegativeNumberDecoder)
|
|
966
|
+
});
|
|
967
|
+
const queryConfigDecoder = object({
|
|
968
|
+
search: nonEmptyStringDecoder,
|
|
969
|
+
providers: optional(array(providerData)),
|
|
970
|
+
types: optional(array(searchTypeDecoder)),
|
|
971
|
+
providerLimits: optional(providerLimitsDecoder)
|
|
972
|
+
});
|
|
973
|
+
const providerRegistrationConfig = object({
|
|
974
|
+
name: nonEmptyStringDecoder,
|
|
975
|
+
types: optional(array(searchTypeDecoder))
|
|
976
|
+
});
|
|
977
|
+
const operationDecoder = oneOf(constant("cancel"), constant("info"), constant("search"));
|
|
978
|
+
const queryStatusDecoder = oneOf(constant("done"), constant("in-progress"), constant("error"));
|
|
979
|
+
const searchCancelRequestDecoder = object({
|
|
980
|
+
id: nonEmptyStringDecoder
|
|
981
|
+
});
|
|
982
|
+
const mainActionDecoder = object({
|
|
983
|
+
method: nonEmptyStringDecoder,
|
|
984
|
+
target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
|
|
985
|
+
params: optional(anyJson())
|
|
986
|
+
});
|
|
987
|
+
const secondaryActionDecoder = object({
|
|
988
|
+
name: nonEmptyStringDecoder,
|
|
989
|
+
method: nonEmptyStringDecoder,
|
|
990
|
+
target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
|
|
991
|
+
params: optional(anyJson())
|
|
992
|
+
});
|
|
993
|
+
const queryResultDecoder = object({
|
|
994
|
+
type: searchTypeDecoder,
|
|
995
|
+
id: optional(nonEmptyStringDecoder),
|
|
996
|
+
displayName: optional(nonEmptyStringDecoder),
|
|
997
|
+
description: optional(nonEmptyStringDecoder),
|
|
998
|
+
iconURL: optional(nonEmptyStringDecoder),
|
|
999
|
+
metadata: optional(anyJson()),
|
|
1000
|
+
action: optional(mainActionDecoder),
|
|
1001
|
+
secondaryActions: optional(array(secondaryActionDecoder))
|
|
1002
|
+
});
|
|
1003
|
+
const legacySearchResultItemDecoder = object({
|
|
1004
|
+
type: string(),
|
|
1005
|
+
category: optional(string()),
|
|
1006
|
+
id: optional(string()),
|
|
1007
|
+
displayName: optional(string()),
|
|
1008
|
+
description: optional(string()),
|
|
1009
|
+
iconURL: optional(string()),
|
|
1010
|
+
action: optional(mainActionDecoder)
|
|
1011
|
+
});
|
|
1012
|
+
const protocolSearchResultsBatchDecoder = object({
|
|
1013
|
+
items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
|
|
1014
|
+
provider: optional(providerData),
|
|
1015
|
+
queryId: nonEmptyStringDecoder,
|
|
1016
|
+
status: constant("in-progress")
|
|
1017
|
+
});
|
|
1018
|
+
const protocolSearchCompletedDecoder = object({
|
|
1019
|
+
items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
|
|
1020
|
+
queryId: nonEmptyStringDecoder,
|
|
1021
|
+
status: constant("done")
|
|
1022
|
+
});
|
|
1023
|
+
const protocolProviderErrorDecoder = object({
|
|
1024
|
+
items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
|
|
1025
|
+
provider: optional(providerData),
|
|
1026
|
+
queryId: nonEmptyStringDecoder,
|
|
1027
|
+
errorMessage: nonEmptyStringDecoder,
|
|
1028
|
+
status: constant("error")
|
|
1029
|
+
});
|
|
1030
|
+
|
|
1031
|
+
class ClientController {
|
|
1032
|
+
constructor(logger, glueController, modelFactory) {
|
|
1033
|
+
this.logger = logger;
|
|
1034
|
+
this.glueController = glueController;
|
|
1035
|
+
this.modelFactory = modelFactory;
|
|
1036
|
+
this.registry = lib();
|
|
1037
|
+
this.activeQueryLookup = {};
|
|
1038
|
+
this.queryIdToMasterIdLookup = {};
|
|
1039
|
+
this.pendingDebounce = [];
|
|
1040
|
+
this.debounceMS = 0;
|
|
1041
|
+
}
|
|
1042
|
+
setDebounceMS(data) {
|
|
1043
|
+
this.logger.info(`[${data.commandId}] Setting the debounceMS to: ${data.milliseconds}`);
|
|
1044
|
+
this.debounceMS = data.milliseconds;
|
|
1045
|
+
this.logger.info(`[${data.commandId}] debounceMS set to: ${data.milliseconds}`);
|
|
1046
|
+
}
|
|
1047
|
+
getDebounceMS(data) {
|
|
1048
|
+
this.logger.info(`[${data.commandId}] Getting the debounceMS`);
|
|
1049
|
+
return this.debounceMS;
|
|
1050
|
+
}
|
|
1051
|
+
query(data, skipDebounce) {
|
|
1052
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1053
|
+
if (this.debounceMS && !skipDebounce) {
|
|
1054
|
+
return this.debounceQuery(data);
|
|
1055
|
+
}
|
|
1056
|
+
yield this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));
|
|
1057
|
+
const { queryConfig, commandId } = data;
|
|
1058
|
+
this.logger.info(`[${commandId}] Initiating a query request`);
|
|
1059
|
+
let allProvidersInfo = yield this.glueController.getAllProvidersInfo();
|
|
1060
|
+
this.logger.trace(`[${commandId}] Got all available providers: ${JSON.stringify(allProvidersInfo)}`);
|
|
1061
|
+
if (queryConfig.providers) {
|
|
1062
|
+
this.logger.info(`[${commandId}] Filtering providers by explicitly allowed providers.`);
|
|
1063
|
+
allProvidersInfo = this.filterProvidersByAllowList(allProvidersInfo, queryConfig.providers);
|
|
1064
|
+
}
|
|
1065
|
+
if (queryConfig.types) {
|
|
1066
|
+
this.logger.info(`[${commandId}] Filtering providers by explicitly allowed types.`);
|
|
1067
|
+
allProvidersInfo = this.filterProvidersByAllowedTypes(allProvidersInfo, queryConfig.types);
|
|
1068
|
+
}
|
|
1069
|
+
if (!allProvidersInfo.length) {
|
|
1070
|
+
this.logger.warn(`[${commandId}] There are no providers that can handle the query for ${data.queryConfig.search}`);
|
|
1071
|
+
}
|
|
1072
|
+
this.logger.info(`[${commandId}] Sending query request to providers: ${JSON.stringify(allProvidersInfo)}`);
|
|
1073
|
+
const allQueryResponses = yield this.glueController.sendQueryRequest(queryConfig, allProvidersInfo);
|
|
1074
|
+
this.logger.info(`[${commandId}] Received responses from the providers: ${JSON.stringify(allQueryResponses)}`);
|
|
1075
|
+
const masterQueryId = this.generateMasterQueryId();
|
|
1076
|
+
const queryModel = this.modelFactory.buildClientQueryModel(masterQueryId, this);
|
|
1077
|
+
this.logger.info(`[${commandId}] The query is in progress with master id: ${masterQueryId}`);
|
|
1078
|
+
this.activeQueryLookup[masterQueryId] = {
|
|
1079
|
+
servers: allQueryResponses,
|
|
1080
|
+
model: queryModel
|
|
1081
|
+
};
|
|
1082
|
+
allQueryResponses.forEach((response) => {
|
|
1083
|
+
this.queryIdToMasterIdLookup[response.queryId] = masterQueryId;
|
|
1084
|
+
});
|
|
1085
|
+
if (!allQueryResponses.length) {
|
|
1086
|
+
setTimeout(() => {
|
|
1087
|
+
this.registry.execute(`on-query-completed-${masterQueryId}`);
|
|
1088
|
+
this.cleanUpQuery(masterQueryId);
|
|
1089
|
+
}, 0);
|
|
1090
|
+
}
|
|
1091
|
+
return queryModel.exposeFacade();
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
cancelQuery(masterQueryId, commandId) {
|
|
1095
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1096
|
+
const activeQuery = this.activeQueryLookup[masterQueryId];
|
|
1097
|
+
if (!activeQuery) {
|
|
1098
|
+
throw new Error(`[${commandId}] Cannot cancel query: ${masterQueryId}, because this query does not exist`);
|
|
1099
|
+
}
|
|
1100
|
+
const interopIds = activeQuery.servers;
|
|
1101
|
+
this.logger.info(`[${commandId}] Sending cancel query requests`);
|
|
1102
|
+
yield Promise.all(interopIds.map((serverId) => {
|
|
1103
|
+
this.logger.trace(`[${commandId}] Sending cancel query request to ${serverId.interopId} with queryId: ${serverId.queryId}`);
|
|
1104
|
+
return this.glueController.sendQueryCancelRequest({ id: serverId.queryId }, { instance: serverId.interopId });
|
|
1105
|
+
}));
|
|
1106
|
+
this.logger.info(`[${commandId}] The query was cancelled`);
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
processClientOnResults(data) {
|
|
1110
|
+
return this.registry.add(`on-query-results-${data.masterQueryId}`, data.callback);
|
|
1111
|
+
}
|
|
1112
|
+
processClientOnCompleted(data) {
|
|
1113
|
+
return this.registry.add(`on-query-completed-${data.masterQueryId}`, data.callback);
|
|
1114
|
+
}
|
|
1115
|
+
processClientOnError(data) {
|
|
1116
|
+
return this.registry.add(`on-query-error-${data.masterQueryId}`, data.callback);
|
|
1117
|
+
}
|
|
1118
|
+
handleProviderCall(args) {
|
|
1119
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1120
|
+
const { status } = args;
|
|
1121
|
+
const validatedOperation = queryStatusDecoder.runWithException(status);
|
|
1122
|
+
const commandId = nanoid(10);
|
|
1123
|
+
switch (validatedOperation) {
|
|
1124
|
+
case SEARCH_QUERY_STATUSES.done:
|
|
1125
|
+
return this.handleQueryCompleted({ completedConfig: args, commandId });
|
|
1126
|
+
case SEARCH_QUERY_STATUSES.inProgress:
|
|
1127
|
+
return this.handleQueryResults({ resultsBatch: args, commandId });
|
|
1128
|
+
case SEARCH_QUERY_STATUSES.error:
|
|
1129
|
+
return this.handleQueryError({ error: args, commandId });
|
|
1130
|
+
default:
|
|
1131
|
+
throw new Error(`Unrecognized status: ${status}`);
|
|
1132
|
+
}
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
handleQueryResults(data) {
|
|
1136
|
+
var _a, _b;
|
|
1137
|
+
const { resultsBatch, commandId } = data;
|
|
1138
|
+
this.logger.trace(`[${commandId}] Processing a results batch from provider: ${(_a = resultsBatch.provider) === null || _a === void 0 ? void 0 : _a.name} with id: ${(_b = resultsBatch.provider) === null || _b === void 0 ? void 0 : _b.id}`);
|
|
1139
|
+
const verifiedResultsBatch = protocolSearchResultsBatchDecoder.runWithException(resultsBatch);
|
|
1140
|
+
const masterQueryId = this.queryIdToMasterIdLookup[verifiedResultsBatch.queryId];
|
|
1141
|
+
if (!masterQueryId) {
|
|
1142
|
+
this.logger.warn(`[${commandId}] Received results for an unknown query. Provider ${JSON.stringify(verifiedResultsBatch.provider)}, items: ${JSON.stringify(verifiedResultsBatch.items)}`);
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
this.logger.trace(`[${commandId}] The results batch is validated, forwarding to the callbacks`);
|
|
1146
|
+
const translatedResults = this.checkTransformLegacyResults(verifiedResultsBatch.items);
|
|
1147
|
+
const results = {
|
|
1148
|
+
provider: verifiedResultsBatch.provider,
|
|
1149
|
+
results: translatedResults
|
|
1150
|
+
};
|
|
1151
|
+
this.registry.execute(`on-query-results-${masterQueryId}`, results);
|
|
1152
|
+
}
|
|
1153
|
+
handleQueryCompleted(data) {
|
|
1154
|
+
const { completedConfig, commandId } = data;
|
|
1155
|
+
this.logger.trace(`[${commandId}] Processing a query completed message from query id: ${completedConfig.queryId}`);
|
|
1156
|
+
const verifiedCompleteConfig = protocolSearchCompletedDecoder.runWithException(completedConfig);
|
|
1157
|
+
const masterQueryId = this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
|
|
1158
|
+
if (!masterQueryId) {
|
|
1159
|
+
this.logger.warn(`[${commandId}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(verifiedCompleteConfig.queryId)}`);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
if (verifiedCompleteConfig.items.length) {
|
|
1163
|
+
const translatedResults = this.checkTransformLegacyResults(verifiedCompleteConfig.items);
|
|
1164
|
+
const results = {
|
|
1165
|
+
results: translatedResults
|
|
1166
|
+
};
|
|
1167
|
+
this.registry.execute(`on-query-results-${masterQueryId}`, results);
|
|
1168
|
+
}
|
|
1169
|
+
delete this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
|
|
1170
|
+
const activeQuery = this.activeQueryLookup[masterQueryId];
|
|
1171
|
+
activeQuery.servers = activeQuery.servers.filter((server) => server.queryId !== verifiedCompleteConfig.queryId);
|
|
1172
|
+
if (activeQuery.servers.length) {
|
|
1173
|
+
this.logger.trace(`[${commandId}] Waiting for more providers to complete`);
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
this.logger.trace(`[${commandId}] All providers are done, marking this query as completed`);
|
|
1177
|
+
this.registry.execute(`on-query-completed-${masterQueryId}`);
|
|
1178
|
+
this.cleanUpQuery(masterQueryId);
|
|
1179
|
+
}
|
|
1180
|
+
handleQueryError(data) {
|
|
1181
|
+
const { error, commandId } = data;
|
|
1182
|
+
this.logger.trace(`[${commandId}] Processing an error message from query: ${error.queryId}`);
|
|
1183
|
+
const validatedError = protocolProviderErrorDecoder.runWithException(error);
|
|
1184
|
+
const masterQueryId = this.queryIdToMasterIdLookup[validatedError.queryId];
|
|
1185
|
+
if (!masterQueryId) {
|
|
1186
|
+
this.logger.warn(`[${commandId}] Received error message for an unknown query. Provider query id: ${JSON.stringify(validatedError.queryId)} and message: ${JSON.stringify(validatedError.errorMessage)}`);
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
const queryError = {
|
|
1190
|
+
error: validatedError.errorMessage,
|
|
1191
|
+
provider: validatedError.provider
|
|
1192
|
+
};
|
|
1193
|
+
this.registry.execute(`on-query-error-${masterQueryId}`, queryError);
|
|
1194
|
+
}
|
|
1195
|
+
filterProvidersByAllowList(servers, allowed) {
|
|
1196
|
+
const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
|
|
1197
|
+
lookup[allowedEntry.id] = true;
|
|
1198
|
+
return lookup;
|
|
1199
|
+
}, {});
|
|
1200
|
+
return servers.filter((server) => {
|
|
1201
|
+
const serverProviders = server.info.providers;
|
|
1202
|
+
return serverProviders.some((provider) => allowedLookup[provider.id]);
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
filterProvidersByAllowedTypes(servers, allowed) {
|
|
1206
|
+
const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
|
|
1207
|
+
lookup[allowedEntry.name] = true;
|
|
1208
|
+
return lookup;
|
|
1209
|
+
}, {});
|
|
1210
|
+
return servers.filter((server) => {
|
|
1211
|
+
const allTypes = server.info.supportedTypes;
|
|
1212
|
+
if (allTypes.some((searchType) => searchType === "*")) {
|
|
1213
|
+
return true;
|
|
1214
|
+
}
|
|
1215
|
+
if (!allTypes || !allTypes.length) {
|
|
1216
|
+
return true;
|
|
1217
|
+
}
|
|
1218
|
+
return allTypes.some((supportedType) => allowedLookup[supportedType]);
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
generateMasterQueryId() {
|
|
1222
|
+
const queryId = nanoid(10);
|
|
1223
|
+
if (this.activeQueryLookup[queryId]) {
|
|
1224
|
+
return this.generateMasterQueryId();
|
|
1225
|
+
}
|
|
1226
|
+
return queryId;
|
|
1227
|
+
}
|
|
1228
|
+
cleanUpQuery(masterQueryId) {
|
|
1229
|
+
this.registry.clearKey(`on-query-results-${masterQueryId}`);
|
|
1230
|
+
this.registry.clearKey(`on-query-completed-${masterQueryId}`);
|
|
1231
|
+
this.registry.clearKey(`on-query-error-${masterQueryId}`);
|
|
1232
|
+
delete this.activeQueryLookup[masterQueryId];
|
|
1233
|
+
}
|
|
1234
|
+
debounceQuery(data) {
|
|
1235
|
+
return new Promise((res, rej) => {
|
|
1236
|
+
clearTimeout(this.debounceTimer);
|
|
1237
|
+
this.debounceTimer = setTimeout(() => {
|
|
1238
|
+
const currentPending = [...this.pendingDebounce];
|
|
1239
|
+
this.pendingDebounce = [];
|
|
1240
|
+
this.query(data, true)
|
|
1241
|
+
.then((query) => currentPending.forEach(({ resolve }) => resolve(query)))
|
|
1242
|
+
.catch((error) => currentPending.forEach(({ reject }) => reject(error)));
|
|
1243
|
+
}, this.debounceMS);
|
|
1244
|
+
this.pendingDebounce.push({ resolve: res, reject: rej });
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
checkTransformLegacyResults(items) {
|
|
1248
|
+
if (!items.length) {
|
|
1249
|
+
return [];
|
|
1250
|
+
}
|
|
1251
|
+
const sampleItem = items[0];
|
|
1252
|
+
if (!sampleItem || typeof sampleItem.type === "object") {
|
|
1253
|
+
return items;
|
|
1254
|
+
}
|
|
1255
|
+
return items.map((item) => {
|
|
1256
|
+
return {
|
|
1257
|
+
type: { name: item.type, displayName: item.category },
|
|
1258
|
+
id: item.id,
|
|
1259
|
+
displayName: item.displayName,
|
|
1260
|
+
description: item.description,
|
|
1261
|
+
iconURL: item.iconURL,
|
|
1262
|
+
action: item.action
|
|
1263
|
+
};
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
const MAIN_PROVIDER_METHOD_NAME = "T42.Search.Provider";
|
|
1269
|
+
const MAIN_CLIENT_METHOD_NAME = "T42.Search.Client";
|
|
1270
|
+
const SEQUELIZER_INTERVAL_MS = 10;
|
|
1271
|
+
const FLUSH_SEQUELIZER_INTERVAL_MS = 10;
|
|
1272
|
+
const FLUSH_TIMEOUT_MS = 100;
|
|
1273
|
+
const STALE_QUERY_TIMEOUT_MS = 900000;
|
|
1274
|
+
|
|
1275
|
+
class GlueController {
|
|
1276
|
+
constructor(glue) {
|
|
1277
|
+
this.glue = glue;
|
|
1278
|
+
}
|
|
1279
|
+
get myAppName() {
|
|
1280
|
+
return this.glue.interop.instance.applicationName;
|
|
1281
|
+
}
|
|
1282
|
+
get myInteropId() {
|
|
1283
|
+
return this.glue.interop.instance.instance;
|
|
1284
|
+
}
|
|
1285
|
+
registerMainProviderMethod(handler) {
|
|
1286
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1287
|
+
const mainMethodStatus = this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME);
|
|
1288
|
+
if (mainMethodStatus.exists) {
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
yield this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME, handler);
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
registerMainClientMethod(handler) {
|
|
1295
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1296
|
+
const mainMethodStatus = this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME);
|
|
1297
|
+
if (mainMethodStatus.exists) {
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
yield this.glue.interop.register(MAIN_CLIENT_METHOD_NAME, handler);
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
clearMainProviderMethod() {
|
|
1304
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1305
|
+
yield this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME);
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
sendClientResultsBatch(batch, clientInstanceId, queryId) {
|
|
1309
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1310
|
+
const interopArguments = {
|
|
1311
|
+
items: batch.results,
|
|
1312
|
+
provider: batch.provider,
|
|
1313
|
+
queryId,
|
|
1314
|
+
status: SEARCH_QUERY_STATUSES.inProgress
|
|
1315
|
+
};
|
|
1316
|
+
yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
sendClientQueueCompleted(clientInstanceId, queryId) {
|
|
1320
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1321
|
+
const interopArguments = {
|
|
1322
|
+
items: [],
|
|
1323
|
+
queryId,
|
|
1324
|
+
status: SEARCH_QUERY_STATUSES.done
|
|
1325
|
+
};
|
|
1326
|
+
yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
sendClientErrorMessage(error, clientInstanceId, queryId, provider) {
|
|
1330
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1331
|
+
const interopArguments = {
|
|
1332
|
+
items: [],
|
|
1333
|
+
provider,
|
|
1334
|
+
errorMessage: error,
|
|
1335
|
+
queryId,
|
|
1336
|
+
status: SEARCH_QUERY_STATUSES.error
|
|
1337
|
+
};
|
|
1338
|
+
yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
sendQueryRequest(queryConfig, instances) {
|
|
1342
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1343
|
+
if (!instances.length) {
|
|
1344
|
+
return [];
|
|
1345
|
+
}
|
|
1346
|
+
const target = instances.map((inst) => ({ instance: inst.interopId }));
|
|
1347
|
+
const invokeArgs = Object.assign({ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search, apiVersion: "1" }, queryConfig);
|
|
1348
|
+
const response = yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, invokeArgs, target);
|
|
1349
|
+
const allReturned = response.all_return_values || [];
|
|
1350
|
+
return allReturned.map((returnValue) => {
|
|
1351
|
+
var _a;
|
|
1352
|
+
return {
|
|
1353
|
+
interopId: (_a = returnValue.executed_by) === null || _a === void 0 ? void 0 : _a.instance,
|
|
1354
|
+
queryId: returnValue.returned.id
|
|
1355
|
+
};
|
|
1356
|
+
});
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
sendQueryCancelRequest(request, instance) {
|
|
1360
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1361
|
+
const args = {
|
|
1362
|
+
operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,
|
|
1363
|
+
id: request.id
|
|
1364
|
+
};
|
|
1365
|
+
yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, instance);
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
getAllProvidersInfo() {
|
|
1369
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1370
|
+
if (this.glue.interop.methods().every((method) => method.name !== MAIN_PROVIDER_METHOD_NAME)) {
|
|
1371
|
+
return [];
|
|
1372
|
+
}
|
|
1373
|
+
const args = {
|
|
1374
|
+
operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info
|
|
1375
|
+
};
|
|
1376
|
+
const response = yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, "all");
|
|
1377
|
+
const allReturned = response.all_return_values || [];
|
|
1378
|
+
return allReturned.map((returnValue) => {
|
|
1379
|
+
var _a, _b, _c, _d, _e;
|
|
1380
|
+
const isLegacy = typeof returnValue.returned.apiVersion === "undefined";
|
|
1381
|
+
const info = isLegacy ? {
|
|
1382
|
+
supportedTypes: returnValue.returned.supportedTypes,
|
|
1383
|
+
apiVersion: returnValue.returned.apiVersion,
|
|
1384
|
+
providers: [{
|
|
1385
|
+
interopId: (_a = returnValue.executed_by) === null || _a === void 0 ? void 0 : _a.instance,
|
|
1386
|
+
id: (_b = returnValue.executed_by) === null || _b === void 0 ? void 0 : _b.instance,
|
|
1387
|
+
name: (_c = returnValue.executed_by) === null || _c === void 0 ? void 0 : _c.instance,
|
|
1388
|
+
appName: (_d = response.executed_by) === null || _d === void 0 ? void 0 : _d.application,
|
|
1389
|
+
types: returnValue.returned.supportedTypes.map((t) => ({ name: t }))
|
|
1390
|
+
}]
|
|
1391
|
+
} : returnValue.returned;
|
|
1392
|
+
return {
|
|
1393
|
+
interopId: (_e = returnValue.executed_by) === null || _e === void 0 ? void 0 : _e.instance,
|
|
1394
|
+
info
|
|
1395
|
+
};
|
|
1396
|
+
});
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
checkMyMethodExists(methodName) {
|
|
1400
|
+
const myMethods = this.glue.interop.methodsForInstance({ instance: this.glue.interop.instance.instance });
|
|
1401
|
+
return { exists: myMethods.some((method) => method.name === methodName) };
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
class MainController {
|
|
1406
|
+
constructor(logger, glueController, clientController, providerController) {
|
|
1407
|
+
this.logger = logger;
|
|
1408
|
+
this.glueController = glueController;
|
|
1409
|
+
this.clientController = clientController;
|
|
1410
|
+
this.providerController = providerController;
|
|
1411
|
+
}
|
|
1412
|
+
setDebounceMS(data) {
|
|
1413
|
+
this.logger.info(`[${data.commandId}] Starting setDebounceMS operation with duration ${data.milliseconds}`);
|
|
1414
|
+
this.clientController.setDebounceMS(data);
|
|
1415
|
+
this.logger.info(`[${data.commandId}] Operation setDebounceMS with duration ${data.milliseconds} completed`);
|
|
1416
|
+
}
|
|
1417
|
+
getDebounceMS(data) {
|
|
1418
|
+
this.logger.info(`[${data.commandId}] Starting getDebounceMS operation.`);
|
|
1419
|
+
return this.clientController.getDebounceMS(data);
|
|
1420
|
+
}
|
|
1421
|
+
query(data) {
|
|
1422
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1423
|
+
this.logger.info(`[${data.commandId}] Starting query operation with config ${JSON.stringify(data.queryConfig)}`);
|
|
1424
|
+
if (Array.isArray(data.queryConfig.providers) && !data.queryConfig.providers.length) {
|
|
1425
|
+
throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");
|
|
1426
|
+
}
|
|
1427
|
+
if (Array.isArray(data.queryConfig.types) && !data.queryConfig.types.length) {
|
|
1428
|
+
throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");
|
|
1429
|
+
}
|
|
1430
|
+
const query = yield this.clientController.query(data);
|
|
1431
|
+
this.logger.info(`[${data.commandId}] Operation query with config ${JSON.stringify(data.queryConfig)} completed.`);
|
|
1432
|
+
return query;
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
registerProvider(data) {
|
|
1436
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1437
|
+
this.logger.info(`[${data.commandId}] Starting registerProvider operation with config ${JSON.stringify(data.config)}`);
|
|
1438
|
+
const provider = yield this.providerController.processRegisterProvider(data);
|
|
1439
|
+
this.logger.info(`[${data.commandId}] Operation registerProvider with config ${JSON.stringify(data.config)} completed.`);
|
|
1440
|
+
return provider;
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
providers(data) {
|
|
1444
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1445
|
+
this.logger.info(`[${data.commandId}] Starting providers operation.`);
|
|
1446
|
+
const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
|
|
1447
|
+
const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
|
|
1448
|
+
this.logger.info(`[${data.commandId}] Operation providers completed.`);
|
|
1449
|
+
return allProvidersData;
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
types(data) {
|
|
1453
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1454
|
+
this.logger.info(`[${data.commandId}] Starting types operation.`);
|
|
1455
|
+
const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
|
|
1456
|
+
const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
|
|
1457
|
+
const allSupportedTypes = allProvidersData.filter((provData) => !!provData.types).flatMap((provData) => provData.types);
|
|
1458
|
+
const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
|
|
1459
|
+
this.logger.info(`[${data.commandId}] Operation types completed.`);
|
|
1460
|
+
return uniqueSupportedTypes;
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
const extractErrorMsg = (error) => {
|
|
1466
|
+
const stringError = typeof error === "string" ?
|
|
1467
|
+
error :
|
|
1468
|
+
error.message ? JSON.stringify(error.message) :
|
|
1469
|
+
JSON.stringify(error);
|
|
1470
|
+
return stringError;
|
|
1471
|
+
};
|
|
1472
|
+
|
|
1473
|
+
class ProviderController {
|
|
1474
|
+
constructor(logger, glueController, sequelizer, limitsTracker, modelsFactory) {
|
|
1475
|
+
this.logger = logger;
|
|
1476
|
+
this.glueController = glueController;
|
|
1477
|
+
this.sequelizer = sequelizer;
|
|
1478
|
+
this.limitsTracker = limitsTracker;
|
|
1479
|
+
this.modelsFactory = modelsFactory;
|
|
1480
|
+
this.registry = lib();
|
|
1481
|
+
this.providersModels = {};
|
|
1482
|
+
this.activeQueries = {};
|
|
1483
|
+
}
|
|
1484
|
+
processRegisterProvider(data) {
|
|
1485
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1486
|
+
const { config, commandId } = data;
|
|
1487
|
+
this.logger.info(`[${commandId}] enqueueing the provider registration process with config: ${JSON.stringify(config)}`);
|
|
1488
|
+
const result = yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
1489
|
+
const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
|
|
1490
|
+
const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
|
|
1491
|
+
if (allProvidersData.some((providerData) => providerData && providerData.name === config.name)) {
|
|
1492
|
+
throw new Error(`Cannot register a new provider with name: ${config.name}, because there already is a provider with this name`);
|
|
1493
|
+
}
|
|
1494
|
+
yield this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));
|
|
1495
|
+
const modelData = {
|
|
1496
|
+
id: nanoid(10),
|
|
1497
|
+
name: config.name,
|
|
1498
|
+
interopId: this.glueController.myInteropId,
|
|
1499
|
+
appName: this.glueController.myAppName,
|
|
1500
|
+
types: config.types
|
|
1501
|
+
};
|
|
1502
|
+
const model = this.modelsFactory.buildProviderModel(modelData, this);
|
|
1503
|
+
this.providersModels[modelData.id] = model;
|
|
1504
|
+
return model.exposeFacade();
|
|
1505
|
+
}));
|
|
1506
|
+
this.logger.info(`[${commandId}] the provider with name: ${config.name} has been registered.`);
|
|
1507
|
+
return result;
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
processProviderOnQuery(data) {
|
|
1511
|
+
return this.registry.add(`on-search-query-${data.id}`, data.callback);
|
|
1512
|
+
}
|
|
1513
|
+
processProviderOnQueryCancel(data) {
|
|
1514
|
+
return this.registry.add(`on-cancel-query-${data.id}`, data.callback);
|
|
1515
|
+
}
|
|
1516
|
+
processProviderUnregister(data) {
|
|
1517
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1518
|
+
this.logger.info(`[${data.commandId}] enqueueing the provider un-registration with id: ${data.id}`);
|
|
1519
|
+
yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
1520
|
+
this.cleanUpProvider(data.id, data.commandId);
|
|
1521
|
+
if (Object.keys(this.providersModels).length) {
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
yield this.glueController.clearMainProviderMethod();
|
|
1525
|
+
}));
|
|
1526
|
+
this.logger.info(`[${data.commandId}] the provider un-registration with id: ${data.id} completed`);
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
processProviderQueryDone(command) {
|
|
1530
|
+
var _a;
|
|
1531
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1532
|
+
const { commandId, identification } = command;
|
|
1533
|
+
(_a = this.activeQueries[identification.queryId]) === null || _a === void 0 ? void 0 : _a.publisher.syncSuspendProvider(identification.providerId, commandId);
|
|
1534
|
+
yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
1535
|
+
this.logger.trace(`[${commandId}] Processing a query done command with identification: ${JSON.stringify(identification)}`);
|
|
1536
|
+
const activeQuery = this.activeQueries[identification.queryId];
|
|
1537
|
+
if (!activeQuery) {
|
|
1538
|
+
this.logger.warn(`[${commandId}] Cannot mark provider: ${identification.providerId} done with query ${identification.queryId}, because there is no active query with this id`);
|
|
1539
|
+
return;
|
|
1540
|
+
}
|
|
1541
|
+
yield this.cleanUpProviderQuery(identification.queryId, identification.providerId, commandId);
|
|
1542
|
+
if (activeQuery.providersAtWork.length) {
|
|
1543
|
+
this.logger.trace(`[${commandId}] Query done command completed, but there are more providers still at work.`);
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
this.cleanUpQuery(identification.queryId, commandId);
|
|
1547
|
+
this.logger.trace(`[${commandId}] Query is completed, signalling.`);
|
|
1548
|
+
}));
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
processProviderQueryError(command) {
|
|
1552
|
+
var _a;
|
|
1553
|
+
const { commandId, identification, error } = command;
|
|
1554
|
+
this.logger.warn(`[${commandId}] Processing an error sent by provider: ${identification.providerId} for query id: ${identification.queryId} -> ${error}`);
|
|
1555
|
+
(_a = this.activeQueries[identification.queryId]) === null || _a === void 0 ? void 0 : _a.publisher.markProviderError(command);
|
|
1556
|
+
return this.processProviderQueryDone(command);
|
|
1557
|
+
}
|
|
1558
|
+
processProviderQueryResult(command) {
|
|
1559
|
+
const { commandId, identification } = command;
|
|
1560
|
+
const activeQuery = this.activeQueries[identification.queryId];
|
|
1561
|
+
if (!activeQuery) {
|
|
1562
|
+
const errorMessage = `Will not send this result to the client, because there is no active query with id ${identification.queryId}. Most likely this query was cancelled.`;
|
|
1563
|
+
this.logger.warn(`[${command}] ${errorMessage}`);
|
|
1564
|
+
throw new Error(errorMessage);
|
|
1565
|
+
}
|
|
1566
|
+
if (activeQuery.publisher.checkProviderSuspended(identification.providerId)) {
|
|
1567
|
+
const errorMessage = `Will not send this result to the client, because there is no info about this provider in the active query with id ${identification.queryId}. Most likely this query was marked as done by this provider already.`;
|
|
1568
|
+
this.logger.warn(`[${command}] ${errorMessage}`);
|
|
1569
|
+
throw new Error(errorMessage);
|
|
1570
|
+
}
|
|
1571
|
+
const requestedTypes = activeQuery.requestedTypes;
|
|
1572
|
+
if (requestedTypes && requestedTypes.every((searchType) => searchType.name !== command.result.type.name)) {
|
|
1573
|
+
const errorMessage = `Will not send this result to the client, because this result has a defined type: ${command.result.type.name} which is not in the explicitly requested list of types by the client.`;
|
|
1574
|
+
this.logger.warn(`[${command}] ${errorMessage}`);
|
|
1575
|
+
throw new Error(errorMessage);
|
|
1576
|
+
}
|
|
1577
|
+
const testResult = this.limitsTracker.testResultLimit(command);
|
|
1578
|
+
if (testResult === null || testResult === void 0 ? void 0 : testResult.maxLimitHit) {
|
|
1579
|
+
const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit set by the client. This provider cannot send more result, marking it as done.`;
|
|
1580
|
+
this.logger.info(errorMessage);
|
|
1581
|
+
setTimeout(() => this.processProviderQueryDone(command), 0);
|
|
1582
|
+
throw new Error(errorMessage);
|
|
1583
|
+
}
|
|
1584
|
+
if (testResult === null || testResult === void 0 ? void 0 : testResult.maxLimitPerTypeHit) {
|
|
1585
|
+
const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit per type as set by the client.`;
|
|
1586
|
+
this.logger.info(errorMessage);
|
|
1587
|
+
throw new Error(errorMessage);
|
|
1588
|
+
}
|
|
1589
|
+
this.logger.trace(`[${commandId}] An active query for query ${identification.queryId} was found and the provider is within limits, queueing the result`);
|
|
1590
|
+
this.limitsTracker.update(command);
|
|
1591
|
+
activeQuery.publisher.queueResult(command);
|
|
1592
|
+
this.logger.trace(`[${commandId}] The query result was queued successfully.`);
|
|
1593
|
+
}
|
|
1594
|
+
handleSearchQueryRequest(args, caller) {
|
|
1595
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1596
|
+
const { operation } = args;
|
|
1597
|
+
const validatedOperation = operationDecoder.runWithException(operation);
|
|
1598
|
+
const commandId = nanoid(10);
|
|
1599
|
+
switch (validatedOperation) {
|
|
1600
|
+
case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:
|
|
1601
|
+
return this.handleInfoOperation({ commandId });
|
|
1602
|
+
case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:
|
|
1603
|
+
return this.handleSearchOperation({ args, commandId }, caller);
|
|
1604
|
+
case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:
|
|
1605
|
+
return this.handleCancelOperation({ args, commandId });
|
|
1606
|
+
default:
|
|
1607
|
+
throw new Error(`Unrecognized operation: ${operation}`);
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
}
|
|
1611
|
+
handleInfoOperation(request) {
|
|
1612
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1613
|
+
this.logger.info(`[${request.commandId}] handling an info operation`);
|
|
1614
|
+
const allSupportedTypes = Object.values(this.providersModels).flatMap((providerModel) => providerModel.myProviderData.types || []);
|
|
1615
|
+
const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
|
|
1616
|
+
const hasWildCardTypeProvider = Object.values(this.providersModels).some((providerModel) => !providerModel.myProviderData.types);
|
|
1617
|
+
if (hasWildCardTypeProvider) {
|
|
1618
|
+
uniqueSupportedTypes.push({ name: "*" });
|
|
1619
|
+
}
|
|
1620
|
+
const providers = Object.values(this.providersModels).map((providerModel) => providerModel.myProviderData);
|
|
1621
|
+
const response = {
|
|
1622
|
+
supportedTypes: uniqueSupportedTypes.map((supportedType) => supportedType.name),
|
|
1623
|
+
providers: providers,
|
|
1624
|
+
apiVersion: "1"
|
|
1625
|
+
};
|
|
1626
|
+
this.logger.info(`[${request.commandId}] responding to an info operation with: ${JSON.stringify(response)}`);
|
|
1627
|
+
return response;
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
handleSearchOperation(request, caller) {
|
|
1631
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1632
|
+
const commandId = request.commandId;
|
|
1633
|
+
const queryId = this.generateQueryId();
|
|
1634
|
+
this.logger.info(`[${commandId}] Processing search operation with queryId: ${queryId} request details: ${JSON.stringify(request.args)}`);
|
|
1635
|
+
const isLegacyRequest = this.checkRequestLegacy(request.args);
|
|
1636
|
+
const validatedRequest = this.prepareRequest(request.args, isLegacyRequest, commandId);
|
|
1637
|
+
this.logger.info(`[${commandId}] Search operation with queryId: ${queryId} is validated. Creating an active query and enqueueing calling the providers.`);
|
|
1638
|
+
this.activeQueries[queryId] = {
|
|
1639
|
+
queryId,
|
|
1640
|
+
callerInstanceId: caller.instance,
|
|
1641
|
+
providersAtWork: [],
|
|
1642
|
+
requestedTypes: validatedRequest.types,
|
|
1643
|
+
publisher: this.modelsFactory.buildPublisher(caller.instance, queryId, isLegacyRequest),
|
|
1644
|
+
staleTimer: this.setClearStaleQueryTimer(queryId)
|
|
1645
|
+
};
|
|
1646
|
+
if (validatedRequest.providerLimits) {
|
|
1647
|
+
this.limitsTracker.enableTracking(validatedRequest.providerLimits, queryId);
|
|
1648
|
+
}
|
|
1649
|
+
setTimeout(() => {
|
|
1650
|
+
this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
1651
|
+
try {
|
|
1652
|
+
this.logger.info(`[${commandId}] Calling the providers.`);
|
|
1653
|
+
this.callProviders(validatedRequest, queryId, commandId);
|
|
1654
|
+
}
|
|
1655
|
+
catch (error) {
|
|
1656
|
+
this.logger.error(`[${commandId}] Error calling the providers: ${extractErrorMsg(error)}`);
|
|
1657
|
+
}
|
|
1658
|
+
}));
|
|
1659
|
+
}, 0);
|
|
1660
|
+
this.logger.info(`[${commandId}] Search operation with queryID: ${queryId} processed successfully.`);
|
|
1661
|
+
return { id: queryId };
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
handleCancelOperation(request) {
|
|
1665
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1666
|
+
yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
1667
|
+
const validation = searchCancelRequestDecoder.run(request.args);
|
|
1668
|
+
if (!validation.ok) {
|
|
1669
|
+
const errorMsg = `Cannot process a cancel request, because of validation error: ${JSON.stringify(validation.error)}`;
|
|
1670
|
+
this.logger.warn(`[${request.commandId}] ${errorMsg}`);
|
|
1671
|
+
throw new Error(errorMsg);
|
|
1672
|
+
}
|
|
1673
|
+
const validatedRequest = validation.result;
|
|
1674
|
+
const activeQuery = this.activeQueries[validatedRequest.id];
|
|
1675
|
+
if (!activeQuery) {
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
clearTimeout(activeQuery.staleTimer);
|
|
1679
|
+
activeQuery.publisher.cancel(request.commandId);
|
|
1680
|
+
delete this.activeQueries[validatedRequest.id];
|
|
1681
|
+
activeQuery.providersAtWork.forEach((provider) => this.registry.execute(`on-cancel-query-${provider.myProviderData.id}`, { id: validatedRequest.id }));
|
|
1682
|
+
}));
|
|
1683
|
+
});
|
|
1684
|
+
}
|
|
1685
|
+
generateQueryId() {
|
|
1686
|
+
const queryId = nanoid(10);
|
|
1687
|
+
if (this.activeQueries[queryId]) {
|
|
1688
|
+
return this.generateQueryId();
|
|
1689
|
+
}
|
|
1690
|
+
return queryId;
|
|
1691
|
+
}
|
|
1692
|
+
translateLegacySearchRequest(legacyRequest) {
|
|
1693
|
+
var _a;
|
|
1694
|
+
return {
|
|
1695
|
+
search: legacyRequest.search,
|
|
1696
|
+
types: (_a = legacyRequest.types) === null || _a === void 0 ? void 0 : _a.map((searchType) => ({ name: searchType })),
|
|
1697
|
+
providerLimits: {
|
|
1698
|
+
maxResults: legacyRequest.limit,
|
|
1699
|
+
maxResultsPerType: legacyRequest.categoryLimit
|
|
1700
|
+
}
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
checkRequestLegacy(searchRequest) {
|
|
1704
|
+
return typeof searchRequest.apiVersion === "undefined";
|
|
1705
|
+
}
|
|
1706
|
+
callProviders(validatedRequest, queryId, commandId) {
|
|
1707
|
+
let providers = validatedRequest.providers ?
|
|
1708
|
+
this.getFilteredProviderModels(validatedRequest.providers)
|
|
1709
|
+
: Object.values(this.providersModels);
|
|
1710
|
+
this.logger.trace(`[${commandId}] initial providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
|
|
1711
|
+
providers = validatedRequest.types ? this.getFilteredProvidersBySearchTypes(providers, validatedRequest.types) : providers;
|
|
1712
|
+
this.logger.trace(`[${commandId}] search type providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
|
|
1713
|
+
this.activeQueries[queryId].publisher.configureProviders(providers);
|
|
1714
|
+
this.activeQueries[queryId].providersAtWork.push(...providers);
|
|
1715
|
+
providers.forEach((provider) => this.callProvider(provider, validatedRequest, queryId, commandId));
|
|
1716
|
+
}
|
|
1717
|
+
callProvider(provider, validatedRequest, queryId, commandId) {
|
|
1718
|
+
const queryModel = this.modelsFactory.buildProviderQueryModel(validatedRequest, { queryId, providerId: provider.myProviderData.id }, this);
|
|
1719
|
+
const queryFacade = queryModel.exposeFacade();
|
|
1720
|
+
this.logger.info(`[${commandId}] The query facade for provider: ${provider.myProviderData.id} with name ${provider.myProviderData.name} is ready, raising the event for query ID: ${queryId}.`);
|
|
1721
|
+
this.registry.execute(`on-search-query-${provider.myProviderData.id}`, queryFacade);
|
|
1722
|
+
}
|
|
1723
|
+
getFilteredProviderModels(providers) {
|
|
1724
|
+
const filtered = providers.reduce((providers, provider) => {
|
|
1725
|
+
if (this.providersModels[provider.id]) {
|
|
1726
|
+
providers.push(this.providersModels[provider.id]);
|
|
1727
|
+
}
|
|
1728
|
+
return providers;
|
|
1729
|
+
}, []);
|
|
1730
|
+
return filtered;
|
|
1731
|
+
}
|
|
1732
|
+
getFilteredProvidersBySearchTypes(providers, searchTypes) {
|
|
1733
|
+
const filtered = providers.filter((provider) => {
|
|
1734
|
+
var _a;
|
|
1735
|
+
if (!provider.myProviderData.types || !provider.myProviderData.types.length) {
|
|
1736
|
+
return true;
|
|
1737
|
+
}
|
|
1738
|
+
return (_a = provider.myProviderData.types) === null || _a === void 0 ? void 0 : _a.some((providerSearchType) => searchTypes.some((searchType) => searchType.name === providerSearchType.name));
|
|
1739
|
+
});
|
|
1740
|
+
return filtered;
|
|
1741
|
+
}
|
|
1742
|
+
setClearStaleQueryTimer(queryId) {
|
|
1743
|
+
return setTimeout(() => {
|
|
1744
|
+
const commandId = nanoid(10);
|
|
1745
|
+
this.logger.info(`[${commandId}] Stale query timer is activated for queryId: ${queryId}`);
|
|
1746
|
+
const activeQuery = this.activeQueries[queryId];
|
|
1747
|
+
if (!activeQuery) {
|
|
1748
|
+
this.logger.info(`[${commandId}] No active query was found, this was a false activation.`);
|
|
1749
|
+
return;
|
|
1750
|
+
}
|
|
1751
|
+
this.logger.info(`[${commandId}] force-marking the query as done`);
|
|
1752
|
+
this.cleanUpQuery(queryId, commandId);
|
|
1753
|
+
this.logger.info(`[${commandId}] the stale query was cleared.`);
|
|
1754
|
+
}, STALE_QUERY_TIMEOUT_MS);
|
|
1755
|
+
}
|
|
1756
|
+
prepareRequest(searchRequest, isLegacyRequest, commandId) {
|
|
1757
|
+
const parsedRequest = isLegacyRequest ? this.translateLegacySearchRequest(searchRequest) : searchRequest;
|
|
1758
|
+
const validation = queryConfigDecoder.run(parsedRequest);
|
|
1759
|
+
if (!validation.ok) {
|
|
1760
|
+
const errorMsg = `Cannot process a search request, because of validation error: ${JSON.stringify(validation.error)}`;
|
|
1761
|
+
this.logger.warn(`[${commandId}] ${errorMsg}`);
|
|
1762
|
+
throw new Error(errorMsg);
|
|
1763
|
+
}
|
|
1764
|
+
const validatedRequest = validation.result;
|
|
1765
|
+
return validatedRequest;
|
|
1766
|
+
}
|
|
1767
|
+
cleanUpQuery(queryId, commandId) {
|
|
1768
|
+
const activeQuery = this.activeQueries[queryId];
|
|
1769
|
+
clearTimeout(activeQuery.staleTimer);
|
|
1770
|
+
activeQuery.publisher.cleanPublisher(commandId);
|
|
1771
|
+
delete this.activeQueries[queryId];
|
|
1772
|
+
this.limitsTracker.cleanTracking(queryId);
|
|
1773
|
+
}
|
|
1774
|
+
cleanUpProvider(providerId, commandId) {
|
|
1775
|
+
this.registry.clearKey(`on-search-query-${providerId}`);
|
|
1776
|
+
this.registry.clearKey(`on-cancel-query-${providerId}`);
|
|
1777
|
+
delete this.providersModels[providerId];
|
|
1778
|
+
const queriesWithProvider = Object.values(this.activeQueries).filter((query) => !query.publisher.checkProviderSuspended(providerId));
|
|
1779
|
+
queriesWithProvider.forEach((query) => {
|
|
1780
|
+
this.processProviderQueryDone({
|
|
1781
|
+
identification: {
|
|
1782
|
+
queryId: query.queryId,
|
|
1783
|
+
providerId
|
|
1784
|
+
},
|
|
1785
|
+
commandId
|
|
1786
|
+
});
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
cleanUpProviderQuery(queryId, providerId, commandId) {
|
|
1790
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1791
|
+
const activeQuery = this.activeQueries[queryId];
|
|
1792
|
+
if (!activeQuery) {
|
|
1793
|
+
this.logger.warn(`[${commandId}] Cannot clean up a provider query ${queryId} for provider ${providerId} because there is no such active query`);
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
activeQuery.providersAtWork = activeQuery.providersAtWork.filter((provider) => provider.myProviderData.id !== providerId);
|
|
1797
|
+
yield activeQuery.publisher.markProviderDone(providerId, commandId);
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
var version = "2.0.1";
|
|
1803
|
+
|
|
1804
|
+
class SearchFacade {
|
|
1805
|
+
constructor(main) {
|
|
1806
|
+
this.main = main;
|
|
1807
|
+
}
|
|
1808
|
+
exposeApi() {
|
|
1809
|
+
const api = {
|
|
1810
|
+
version,
|
|
1811
|
+
setDebounceMS: this.setDebounceMS.bind(this),
|
|
1812
|
+
getDebounceMS: this.getDebounceMS.bind(this),
|
|
1813
|
+
listProviders: this.providers.bind(this),
|
|
1814
|
+
listTypes: this.types.bind(this),
|
|
1815
|
+
query: this.query.bind(this),
|
|
1816
|
+
registerProvider: this.registerProvider.bind(this)
|
|
1817
|
+
};
|
|
1818
|
+
return Object.freeze(api);
|
|
1819
|
+
}
|
|
1820
|
+
setDebounceMS(milliseconds) {
|
|
1821
|
+
nonNegativeNumberDecoder.runWithException(milliseconds);
|
|
1822
|
+
const commandId = nanoid(10);
|
|
1823
|
+
return this.main.setDebounceMS({ milliseconds, commandId });
|
|
1824
|
+
}
|
|
1825
|
+
getDebounceMS() {
|
|
1826
|
+
const commandId = nanoid(10);
|
|
1827
|
+
return this.main.getDebounceMS({ commandId });
|
|
1828
|
+
}
|
|
1829
|
+
providers() {
|
|
1830
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1831
|
+
const commandId = nanoid(10);
|
|
1832
|
+
return this.main.providers({ commandId });
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
types() {
|
|
1836
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1837
|
+
const commandId = nanoid(10);
|
|
1838
|
+
return this.main.types({ commandId });
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
query(queryConfig) {
|
|
1842
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1843
|
+
const verifiedConfig = queryConfigDecoder.runWithException(queryConfig);
|
|
1844
|
+
const commandId = nanoid(10);
|
|
1845
|
+
return this.main.query({ queryConfig: verifiedConfig, commandId });
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
registerProvider(config) {
|
|
1849
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1850
|
+
const verifiedConfig = providerRegistrationConfig.runWithException(config);
|
|
1851
|
+
const commandId = nanoid(10);
|
|
1852
|
+
return this.main.registerProvider({ config: verifiedConfig, commandId });
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
class AsyncSequelizer {
|
|
1858
|
+
constructor(minSequenceInterval = 0) {
|
|
1859
|
+
this.minSequenceInterval = minSequenceInterval;
|
|
1860
|
+
this.queue = [];
|
|
1861
|
+
this.isExecutingQueue = false;
|
|
1862
|
+
}
|
|
1863
|
+
enqueue(action) {
|
|
1864
|
+
return new Promise((resolve, reject) => {
|
|
1865
|
+
this.queue.push({ action, resolve, reject });
|
|
1866
|
+
this.executeQueue();
|
|
1867
|
+
});
|
|
1868
|
+
}
|
|
1869
|
+
executeQueue() {
|
|
1870
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1871
|
+
if (this.isExecutingQueue) {
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
this.isExecutingQueue = true;
|
|
1875
|
+
while (this.queue.length) {
|
|
1876
|
+
const operation = this.queue.shift();
|
|
1877
|
+
if (!operation) {
|
|
1878
|
+
this.isExecutingQueue = false;
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
try {
|
|
1882
|
+
const actionResult = yield operation.action();
|
|
1883
|
+
operation.resolve(actionResult);
|
|
1884
|
+
}
|
|
1885
|
+
catch (error) {
|
|
1886
|
+
operation.reject(error);
|
|
1887
|
+
}
|
|
1888
|
+
yield this.intervalBreak();
|
|
1889
|
+
}
|
|
1890
|
+
this.isExecutingQueue = false;
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
intervalBreak() {
|
|
1894
|
+
return new Promise((res) => setTimeout(res, this.minSequenceInterval));
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
class LimitsTracker {
|
|
1899
|
+
constructor() {
|
|
1900
|
+
this.limitsLookup = {};
|
|
1901
|
+
this.limitsData = {};
|
|
1902
|
+
}
|
|
1903
|
+
enableTracking(limits, queryId) {
|
|
1904
|
+
this.limitsLookup[queryId] = {};
|
|
1905
|
+
this.limitsData[queryId] = {
|
|
1906
|
+
maxResults: limits.maxResults ? limits.maxResults : Number.MAX_SAFE_INTEGER,
|
|
1907
|
+
maxResultsPerType: limits.maxResultsPerType ? limits.maxResultsPerType : Number.MAX_SAFE_INTEGER
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
testResultLimit(command) {
|
|
1911
|
+
const foundLookup = this.limitsLookup[command.identification.queryId];
|
|
1912
|
+
const limitData = this.limitsData[command.identification.queryId];
|
|
1913
|
+
if (!foundLookup || !limitData) {
|
|
1914
|
+
return;
|
|
1915
|
+
}
|
|
1916
|
+
let providerStateLookup = foundLookup[command.identification.providerId];
|
|
1917
|
+
if (!providerStateLookup) {
|
|
1918
|
+
providerStateLookup = { total: 0 };
|
|
1919
|
+
foundLookup[command.identification.providerId] = providerStateLookup;
|
|
1920
|
+
}
|
|
1921
|
+
if ((providerStateLookup.total + 1) > limitData.maxResults) {
|
|
1922
|
+
return { maxLimitHit: true };
|
|
1923
|
+
}
|
|
1924
|
+
const resultTypeName = command.result.type.name;
|
|
1925
|
+
if (!resultTypeName) {
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1928
|
+
const currentResultTypeCount = providerStateLookup[resultTypeName] || 0;
|
|
1929
|
+
if ((currentResultTypeCount + 1) > limitData.maxResultsPerType) {
|
|
1930
|
+
return { maxLimitPerTypeHit: true };
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
update(command) {
|
|
1934
|
+
const foundLookup = this.limitsLookup[command.identification.queryId];
|
|
1935
|
+
const limitData = this.limitsData[command.identification.queryId];
|
|
1936
|
+
if (!foundLookup || !limitData) {
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
const providerStateLookup = foundLookup[command.identification.providerId];
|
|
1940
|
+
providerStateLookup.total += 1;
|
|
1941
|
+
const resultTypeName = command.result.type.name;
|
|
1942
|
+
if (!resultTypeName) {
|
|
1943
|
+
return;
|
|
1944
|
+
}
|
|
1945
|
+
providerStateLookup[resultTypeName] = providerStateLookup[resultTypeName] ? providerStateLookup[resultTypeName] + 1 : 1;
|
|
1946
|
+
}
|
|
1947
|
+
cleanTracking(queryId) {
|
|
1948
|
+
delete this.limitsLookup[queryId];
|
|
1949
|
+
delete this.limitsData[queryId];
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
class ClientQuery {
|
|
1954
|
+
constructor(controller, logger, masterQueryId) {
|
|
1955
|
+
this.controller = controller;
|
|
1956
|
+
this.logger = logger;
|
|
1957
|
+
this.masterQueryId = masterQueryId;
|
|
1958
|
+
}
|
|
1959
|
+
exposeFacade() {
|
|
1960
|
+
const providerQueryFacade = {
|
|
1961
|
+
cancel: this.cancel.bind(this),
|
|
1962
|
+
onResults: this.onResults.bind(this),
|
|
1963
|
+
onCompleted: this.onCompleted.bind(this),
|
|
1964
|
+
onError: this.onError.bind(this)
|
|
1965
|
+
};
|
|
1966
|
+
return Object.freeze(providerQueryFacade);
|
|
1967
|
+
}
|
|
1968
|
+
cancel() {
|
|
1969
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1970
|
+
const commandId = nanoid(10);
|
|
1971
|
+
this.logger.info(`[${commandId}] received a valid query cancel request, forwarding to the controller.`);
|
|
1972
|
+
yield this.controller.cancelQuery(this.masterQueryId, commandId);
|
|
1973
|
+
this.logger.info(`[${commandId}] the cancel request was completed.`);
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
onResults(callback) {
|
|
1977
|
+
if (typeof callback !== "function") {
|
|
1978
|
+
throw new Error("onQuery requires a callback of type function");
|
|
1979
|
+
}
|
|
1980
|
+
const commandId = nanoid(10);
|
|
1981
|
+
this.logger.info(`[${commandId}] received a valid query onResults request, forwarding to the controller.`);
|
|
1982
|
+
const unsubscribe = this.controller.processClientOnResults({ callback, masterQueryId: this.masterQueryId, commandId });
|
|
1983
|
+
this.logger.info(`[${commandId}] the onResults request was completed.`);
|
|
1984
|
+
return unsubscribe;
|
|
1985
|
+
}
|
|
1986
|
+
onCompleted(callback) {
|
|
1987
|
+
if (typeof callback !== "function") {
|
|
1988
|
+
throw new Error("onQuery requires a callback of type function");
|
|
1989
|
+
}
|
|
1990
|
+
const commandId = nanoid(10);
|
|
1991
|
+
this.logger.info(`[${commandId}] received a valid query onCompleted request, forwarding to the controller.`);
|
|
1992
|
+
const unsubscribe = this.controller.processClientOnCompleted({ callback, masterQueryId: this.masterQueryId, commandId });
|
|
1993
|
+
this.logger.info(`[${commandId}] the onCompleted request was completed.`);
|
|
1994
|
+
return unsubscribe;
|
|
1995
|
+
}
|
|
1996
|
+
onError(callback) {
|
|
1997
|
+
if (typeof callback !== "function") {
|
|
1998
|
+
throw new Error("onQuery requires a callback of type function");
|
|
1999
|
+
}
|
|
2000
|
+
const commandId = nanoid(10);
|
|
2001
|
+
this.logger.info(`[${commandId}] received a valid query onError request, forwarding to the controller.`);
|
|
2002
|
+
const unsubscribe = this.controller.processClientOnError({ callback, masterQueryId: this.masterQueryId, commandId });
|
|
2003
|
+
this.logger.info(`[${commandId}] the onError request was completed.`);
|
|
2004
|
+
return unsubscribe;
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
class ProviderModel {
|
|
2009
|
+
constructor(myData, controller, logger) {
|
|
2010
|
+
this.myData = myData;
|
|
2011
|
+
this.controller = controller;
|
|
2012
|
+
this.logger = logger;
|
|
2013
|
+
}
|
|
2014
|
+
get id() {
|
|
2015
|
+
return this.myData.id;
|
|
2016
|
+
}
|
|
2017
|
+
get name() {
|
|
2018
|
+
return this.myData.name;
|
|
2019
|
+
}
|
|
2020
|
+
get appName() {
|
|
2021
|
+
return this.myData.appName;
|
|
2022
|
+
}
|
|
2023
|
+
get types() {
|
|
2024
|
+
return this.myData.types;
|
|
2025
|
+
}
|
|
2026
|
+
get myProviderData() {
|
|
2027
|
+
return Object.assign({}, this.myData);
|
|
2028
|
+
}
|
|
2029
|
+
exposeFacade() {
|
|
2030
|
+
const providerFacade = {
|
|
2031
|
+
interopId: this.myData.interopId,
|
|
2032
|
+
id: this.id,
|
|
2033
|
+
name: this.name,
|
|
2034
|
+
appName: this.appName,
|
|
2035
|
+
types: this.types,
|
|
2036
|
+
onQuery: this.onQuery.bind(this),
|
|
2037
|
+
onQueryCancel: this.onQueryCancel.bind(this),
|
|
2038
|
+
unregister: this.unregister.bind(this)
|
|
2039
|
+
};
|
|
2040
|
+
return Object.freeze(providerFacade);
|
|
2041
|
+
}
|
|
2042
|
+
onQuery(callback) {
|
|
2043
|
+
if (typeof callback !== "function") {
|
|
2044
|
+
throw new Error("onQuery requires a callback of type function");
|
|
2045
|
+
}
|
|
2046
|
+
const commandId = nanoid(10);
|
|
2047
|
+
this.logger.info(`[${commandId}] received a valid onQuery request, forwarding to the controller.`);
|
|
2048
|
+
const unsubscribe = this.controller.processProviderOnQuery({ callback, id: this.id, commandId });
|
|
2049
|
+
this.logger.info(`[${commandId}] the onQuery request was completed.`);
|
|
2050
|
+
return unsubscribe;
|
|
2051
|
+
}
|
|
2052
|
+
onQueryCancel(callback) {
|
|
2053
|
+
if (typeof callback !== "function") {
|
|
2054
|
+
throw new Error("onQuery requires a callback of type function");
|
|
2055
|
+
}
|
|
2056
|
+
const commandId = nanoid(10);
|
|
2057
|
+
this.logger.info(`[${commandId}] received a valid onQueryCancel request, forwarding to the controller.`);
|
|
2058
|
+
const unsubscribe = this.controller.processProviderOnQueryCancel({ callback, id: this.id, commandId });
|
|
2059
|
+
this.logger.info(`[${commandId}] the onQueryCancel request was completed.`);
|
|
2060
|
+
return unsubscribe;
|
|
2061
|
+
}
|
|
2062
|
+
unregister() {
|
|
2063
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
2064
|
+
const commandId = nanoid(10);
|
|
2065
|
+
this.logger.info(`[${commandId}] received a valid unregister request, forwarding to the controller.`);
|
|
2066
|
+
yield this.controller.processProviderUnregister({ id: this.id, commandId });
|
|
2067
|
+
this.logger.info(`[${commandId}] the unregister request was completed.`);
|
|
2068
|
+
});
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
class ProviderQueryModel {
|
|
2073
|
+
constructor(myData, controller, logger, identification) {
|
|
2074
|
+
this.myData = myData;
|
|
2075
|
+
this.controller = controller;
|
|
2076
|
+
this.logger = logger;
|
|
2077
|
+
this.identification = identification;
|
|
2078
|
+
}
|
|
2079
|
+
get id() {
|
|
2080
|
+
return this.identification.queryId;
|
|
2081
|
+
}
|
|
2082
|
+
get search() {
|
|
2083
|
+
return this.myData.search;
|
|
2084
|
+
}
|
|
2085
|
+
get providers() {
|
|
2086
|
+
return this.myData.providers;
|
|
2087
|
+
}
|
|
2088
|
+
get types() {
|
|
2089
|
+
return this.myData.types;
|
|
2090
|
+
}
|
|
2091
|
+
get providerLimits() {
|
|
2092
|
+
return this.myData.providerLimits;
|
|
2093
|
+
}
|
|
2094
|
+
get myQueryData() {
|
|
2095
|
+
return Object.assign({}, this.myData);
|
|
2096
|
+
}
|
|
2097
|
+
exposeFacade() {
|
|
2098
|
+
const providerQueryFacade = {
|
|
2099
|
+
id: this.id,
|
|
2100
|
+
search: this.search,
|
|
2101
|
+
providers: this.providers,
|
|
2102
|
+
types: this.types,
|
|
2103
|
+
providerLimits: this.providerLimits,
|
|
2104
|
+
sendResult: this.sendResult.bind(this),
|
|
2105
|
+
error: this.error.bind(this),
|
|
2106
|
+
done: this.done.bind(this)
|
|
2107
|
+
};
|
|
2108
|
+
return Object.freeze(providerQueryFacade);
|
|
2109
|
+
}
|
|
2110
|
+
sendResult(result) {
|
|
2111
|
+
queryResultDecoder.runWithException(result);
|
|
2112
|
+
const commandId = nanoid(10);
|
|
2113
|
+
this.logger.trace(`[${commandId}] Received a valid result, forwarding to the controller`);
|
|
2114
|
+
return this.controller.processProviderQueryResult({ identification: this.identification, result, commandId });
|
|
2115
|
+
}
|
|
2116
|
+
error(error) {
|
|
2117
|
+
const commandId = nanoid(10);
|
|
2118
|
+
nonEmptyStringDecoder.runWithException(error);
|
|
2119
|
+
this.logger.trace(`[${commandId}] Received a valid error, forwarding to the controller`);
|
|
2120
|
+
this.controller.processProviderQueryError({ identification: this.identification, error, commandId }).catch((error) => this.logger.warn(`Error processing the error signal for this provider: ${this.id}, error: ${extractErrorMsg(error)}`));
|
|
2121
|
+
}
|
|
2122
|
+
done() {
|
|
2123
|
+
const commandId = nanoid(10);
|
|
2124
|
+
this.logger.trace(`[${commandId}] Received a valid done, forwarding to the controller`);
|
|
2125
|
+
this.controller.processProviderQueryDone({ identification: this.identification, commandId }).catch((error) => this.logger.warn(`Error processing the done signal for this provider: ${this.identification.providerId}, error: ${extractErrorMsg(error)}`));
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
class QueryResultsPublisher {
|
|
2130
|
+
constructor(sequelizer, glueController, logger, clientInstanceId, queryId, isLegacy) {
|
|
2131
|
+
this.sequelizer = sequelizer;
|
|
2132
|
+
this.glueController = glueController;
|
|
2133
|
+
this.logger = logger;
|
|
2134
|
+
this.clientInstanceId = clientInstanceId;
|
|
2135
|
+
this.queryId = queryId;
|
|
2136
|
+
this.isLegacy = isLegacy;
|
|
2137
|
+
this.queues = {};
|
|
2138
|
+
}
|
|
2139
|
+
checkProviderSuspended(providerId) {
|
|
2140
|
+
return this.queues[providerId] ? !!this.queues[providerId].suspended : false;
|
|
2141
|
+
}
|
|
2142
|
+
syncSuspendProvider(providerId, commandId) {
|
|
2143
|
+
const providerQueue = this.queues[providerId];
|
|
2144
|
+
if (!providerQueue) {
|
|
2145
|
+
this.logger.warn(`[${commandId}] Cannot suspend provider: ${providerId}, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
|
|
2146
|
+
return;
|
|
2147
|
+
}
|
|
2148
|
+
providerQueue.suspended = true;
|
|
2149
|
+
}
|
|
2150
|
+
configureProviders(providers) {
|
|
2151
|
+
providers.forEach((provider) => {
|
|
2152
|
+
this.queues[provider.myProviderData.id] = {
|
|
2153
|
+
providerData: provider,
|
|
2154
|
+
pendingResults: []
|
|
2155
|
+
};
|
|
2156
|
+
});
|
|
2157
|
+
}
|
|
2158
|
+
queueResult(command) {
|
|
2159
|
+
const { commandId, identification } = command;
|
|
2160
|
+
this.logger.trace(`[${commandId}] Queuing a new result from provider: ${identification.providerId}`);
|
|
2161
|
+
const providerQueue = this.queues[identification.providerId];
|
|
2162
|
+
if (!providerQueue) {
|
|
2163
|
+
this.logger.warn(`[${commandId}] Cannot queue this result, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
|
|
2164
|
+
return;
|
|
2165
|
+
}
|
|
2166
|
+
const result = this.isLegacy ? this.translateLegacySearchItem(command.result) : command.result;
|
|
2167
|
+
providerQueue.pendingResults.push(result);
|
|
2168
|
+
clearTimeout(providerQueue.flushTimer);
|
|
2169
|
+
if (providerQueue.pendingResults.length === 10) {
|
|
2170
|
+
this.logger.trace(`[${commandId}] Reached the limit in the queue buffer, flushing to the client.`);
|
|
2171
|
+
this.flushProviderQueue(identification.providerId, commandId);
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
this.logger.trace(`[${commandId}] The limit in the queue buffer is not reached yet, setting a flush timer.`);
|
|
2175
|
+
providerQueue.flushTimer = setTimeout(() => {
|
|
2176
|
+
this.logger.trace(`[${commandId}] Reached the time limit in the queue buffer, flushing to the client.`);
|
|
2177
|
+
this.flushProviderQueue(identification.providerId, commandId);
|
|
2178
|
+
}, FLUSH_TIMEOUT_MS);
|
|
2179
|
+
}
|
|
2180
|
+
cancel(commandId) {
|
|
2181
|
+
this.logger.trace(`[${commandId}] Cancelling queue ${this.queryId}.`);
|
|
2182
|
+
Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
|
|
2183
|
+
this.queues = {};
|
|
2184
|
+
this.logger.trace(`[${commandId}] Queue ${this.queryId} publisher cancelled.`);
|
|
2185
|
+
}
|
|
2186
|
+
markProviderDone(providerId, commandId) {
|
|
2187
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
2188
|
+
this.logger.trace(`[${commandId}] Marking provider ${providerId} as done.`);
|
|
2189
|
+
const providerQueue = this.queues[providerId];
|
|
2190
|
+
if (!providerQueue) {
|
|
2191
|
+
this.logger.info(`[${commandId}] Cannot mark this queue as done, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent an error`);
|
|
2192
|
+
return;
|
|
2193
|
+
}
|
|
2194
|
+
clearTimeout(providerQueue.flushTimer);
|
|
2195
|
+
yield this.flushProviderQueue(providerId, commandId);
|
|
2196
|
+
delete this.queues[providerId];
|
|
2197
|
+
this.logger.trace(`[${commandId}] Provider ${providerId} marked as done.`);
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
markProviderError(command) {
|
|
2201
|
+
const providerQueue = this.queues[command.identification.providerId];
|
|
2202
|
+
if (!providerQueue) {
|
|
2203
|
+
this.logger.warn(`[${command.commandId}] Cannot mark this provider as errored, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
this.glueController.sendClientErrorMessage(command.error, this.clientInstanceId, this.queryId, providerQueue.providerData.myProviderData)
|
|
2207
|
+
.catch((error) => this.logger.warn(`[${command.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
|
|
2208
|
+
}
|
|
2209
|
+
cleanPublisher(commandId) {
|
|
2210
|
+
Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
|
|
2211
|
+
this.queues = {};
|
|
2212
|
+
this.glueController.sendClientQueueCompleted(this.clientInstanceId, this.queryId)
|
|
2213
|
+
.catch((error) => this.logger.warn(`[${commandId}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
|
|
2214
|
+
}
|
|
2215
|
+
flushProviderQueue(providerId, commandId) {
|
|
2216
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
2217
|
+
yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
|
|
2218
|
+
const providerQueue = this.queues[providerId];
|
|
2219
|
+
if (!providerQueue) {
|
|
2220
|
+
this.logger.warn(`[${commandId}] Cannot flush this queue, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
if (!providerQueue.pendingResults.length) {
|
|
2224
|
+
this.logger.info(`[${commandId}] This provider does not have any pending results to flush.`);
|
|
2225
|
+
return;
|
|
2226
|
+
}
|
|
2227
|
+
const resultBatch = {
|
|
2228
|
+
results: providerQueue.pendingResults,
|
|
2229
|
+
provider: providerQueue.providerData.myProviderData
|
|
2230
|
+
};
|
|
2231
|
+
providerQueue.pendingResults = [];
|
|
2232
|
+
try {
|
|
2233
|
+
yield this.glueController.sendClientResultsBatch(resultBatch, this.clientInstanceId, this.queryId);
|
|
2234
|
+
}
|
|
2235
|
+
catch (error) {
|
|
2236
|
+
this.logger.warn(`[${commandId}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(error)}`);
|
|
2237
|
+
}
|
|
2238
|
+
}));
|
|
2239
|
+
});
|
|
2240
|
+
}
|
|
2241
|
+
translateLegacySearchItem(searchResult) {
|
|
2242
|
+
return {
|
|
2243
|
+
type: searchResult.type.name,
|
|
2244
|
+
category: searchResult.type.displayName,
|
|
2245
|
+
id: searchResult.id,
|
|
2246
|
+
displayName: searchResult.displayName,
|
|
2247
|
+
description: searchResult.description,
|
|
2248
|
+
iconURL: searchResult.iconURL,
|
|
2249
|
+
action: searchResult.action
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
class ModelFactory {
|
|
2255
|
+
constructor(glueController, glue, flushSequelizer) {
|
|
2256
|
+
this.glueController = glueController;
|
|
2257
|
+
this.glue = glue;
|
|
2258
|
+
this.flushSequelizer = flushSequelizer;
|
|
2259
|
+
}
|
|
2260
|
+
buildProviderModel(providerData, controller) {
|
|
2261
|
+
return new ProviderModel(providerData, controller, this.glue.logger.subLogger(`search.provider.model.${providerData.name}`));
|
|
2262
|
+
}
|
|
2263
|
+
buildProviderQueryModel(queryConfig, identification, controller) {
|
|
2264
|
+
return new ProviderQueryModel(queryConfig, controller, this.glue.logger.subLogger(`search.provider.${identification.providerId}.query.${identification.queryId}`), identification);
|
|
2265
|
+
}
|
|
2266
|
+
buildPublisher(clientInstanceId, queryId, isLegacy) {
|
|
2267
|
+
return new QueryResultsPublisher(this.flushSequelizer, this.glueController, this.glue.logger.subLogger(`search.results.publisher.${queryId}`), clientInstanceId, queryId, isLegacy);
|
|
2268
|
+
}
|
|
2269
|
+
buildClientQueryModel(masterQueryId, controller) {
|
|
2270
|
+
return new ClientQuery(controller, this.glue.logger.subLogger(`search.provider.model.${masterQueryId}`), masterQueryId);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
class IoC {
|
|
2275
|
+
constructor(glue, config) {
|
|
2276
|
+
this.glue = glue;
|
|
2277
|
+
this.config = config;
|
|
2278
|
+
}
|
|
2279
|
+
get glueController() {
|
|
2280
|
+
if (!this._glueController) {
|
|
2281
|
+
this._glueController = new GlueController(this.glue);
|
|
2282
|
+
}
|
|
2283
|
+
return this._glueController;
|
|
2284
|
+
}
|
|
2285
|
+
get main() {
|
|
2286
|
+
if (!this._mainController) {
|
|
2287
|
+
this._mainController = new MainController(this.glue.logger.subLogger("search.main.controller"), this.glueController, this.clientController, this.providerController);
|
|
2288
|
+
}
|
|
2289
|
+
return this._mainController;
|
|
2290
|
+
}
|
|
2291
|
+
get clientController() {
|
|
2292
|
+
if (!this._clientController) {
|
|
2293
|
+
this._clientController = new ClientController(this.glue.logger.subLogger("search.client.controller"), this.glueController, this.modelFactory);
|
|
2294
|
+
}
|
|
2295
|
+
return this._clientController;
|
|
2296
|
+
}
|
|
2297
|
+
get providerController() {
|
|
2298
|
+
if (!this._providerController) {
|
|
2299
|
+
this._providerController = new ProviderController(this.glue.logger.subLogger("search.provider.controller"), this.glueController, this.sequelizer, this.limitsTracker, this.modelFactory);
|
|
2300
|
+
}
|
|
2301
|
+
return this._providerController;
|
|
2302
|
+
}
|
|
2303
|
+
get facade() {
|
|
2304
|
+
if (!this._facade) {
|
|
2305
|
+
this._facade = new SearchFacade(this.main);
|
|
2306
|
+
}
|
|
2307
|
+
return this._facade;
|
|
2308
|
+
}
|
|
2309
|
+
get sequelizer() {
|
|
2310
|
+
if (!this._asyncSequelizer) {
|
|
2311
|
+
this._asyncSequelizer = new AsyncSequelizer(SEQUELIZER_INTERVAL_MS);
|
|
2312
|
+
}
|
|
2313
|
+
return this._asyncSequelizer;
|
|
2314
|
+
}
|
|
2315
|
+
get flushSequelizer() {
|
|
2316
|
+
if (!this._flushSequelizer) {
|
|
2317
|
+
this._flushSequelizer = new AsyncSequelizer(FLUSH_SEQUELIZER_INTERVAL_MS);
|
|
2318
|
+
}
|
|
2319
|
+
return this._flushSequelizer;
|
|
2320
|
+
}
|
|
2321
|
+
get limitsTracker() {
|
|
2322
|
+
if (!this._limitsTracker) {
|
|
2323
|
+
this._limitsTracker = new LimitsTracker();
|
|
2324
|
+
}
|
|
2325
|
+
return this._limitsTracker;
|
|
2326
|
+
}
|
|
2327
|
+
get modelFactory() {
|
|
2328
|
+
if (!this._modelFactory) {
|
|
2329
|
+
this._modelFactory = new ModelFactory(this.glueController, this.glue, this.flushSequelizer);
|
|
2330
|
+
}
|
|
2331
|
+
return this._modelFactory;
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
const factoryFunction = (io, config) => __awaiter(void 0, void 0, void 0, function* () {
|
|
2336
|
+
const ioc = new IoC(io, config);
|
|
2337
|
+
io.search = ioc.facade.exposeApi();
|
|
2338
|
+
});
|
|
2339
|
+
if (typeof window !== "undefined") {
|
|
2340
|
+
window.IOSearch = factoryFunction;
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
export { factoryFunction as default };
|
|
2344
|
+
//# sourceMappingURL=search-api.es.js.map
|