@interopio/search-api 2.2.1 → 2.2.2

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.
@@ -1,42 +1,18 @@
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
- }
1
+ const urlAlphabet =
2
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
3
+
4
+ let nanoid = (size = 21) => {
5
+ let id = '';
6
+ let bytes = crypto.getRandomValues(new Uint8Array(size));
7
+ while (size--) {
8
+ id += urlAlphabet[bytes[size] & 63];
9
+ }
10
+ return id
11
+ };
25
12
 
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
- }, '');
13
+ function getDefaultExportFromCjs (x) {
14
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
15
+ }
40
16
 
41
17
  function createRegistry(options) {
42
18
  if (options && options.errorHandling
@@ -155,15 +131,18 @@ function createRegistry(options) {
155
131
  createRegistry.default = createRegistry;
156
132
  var lib = createRegistry;
157
133
 
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"
134
+
135
+ var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib);
136
+
137
+ const SEARCH_QUERY_STATUSES = {
138
+ done: "done",
139
+ inProgress: "in-progress",
140
+ error: "error"
141
+ };
142
+ const CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS = {
143
+ info: "info",
144
+ search: "search",
145
+ cancel: "cancel"
167
146
  };
168
147
 
169
148
  /**
@@ -947,1397 +926,1372 @@ Decoder.fail;
947
926
  /** See `Decoder.lazy` */
948
927
  Decoder.lazy;
949
928
 
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")
929
+ const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
930
+ const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
931
+ const searchTypeDecoder = object({
932
+ name: nonEmptyStringDecoder,
933
+ displayName: optional(nonEmptyStringDecoder)
934
+ });
935
+ const providerData = object({
936
+ id: nonEmptyStringDecoder,
937
+ interopId: nonEmptyStringDecoder,
938
+ name: nonEmptyStringDecoder,
939
+ appName: optional(nonEmptyStringDecoder),
940
+ types: optional(array(searchTypeDecoder))
941
+ });
942
+ const providerLimitsDecoder = object({
943
+ maxResults: optional(nonNegativeNumberDecoder),
944
+ maxResultsPerType: optional(nonNegativeNumberDecoder)
945
+ });
946
+ const queryConfigDecoder = object({
947
+ search: nonEmptyStringDecoder,
948
+ providers: optional(array(providerData)),
949
+ types: optional(array(searchTypeDecoder)),
950
+ providerLimits: optional(providerLimitsDecoder)
951
+ });
952
+ const providerRegistrationConfig = object({
953
+ name: nonEmptyStringDecoder,
954
+ types: optional(array(searchTypeDecoder))
955
+ });
956
+ const operationDecoder = oneOf(constant("cancel"), constant("info"), constant("search"));
957
+ const queryStatusDecoder = oneOf(constant("done"), constant("in-progress"), constant("error"));
958
+ const searchCancelRequestDecoder = object({
959
+ id: nonEmptyStringDecoder
960
+ });
961
+ const mainActionDecoder = object({
962
+ method: nonEmptyStringDecoder,
963
+ target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
964
+ params: optional(anyJson())
965
+ });
966
+ const secondaryActionDecoder = object({
967
+ name: nonEmptyStringDecoder,
968
+ method: nonEmptyStringDecoder,
969
+ target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
970
+ params: optional(anyJson())
971
+ });
972
+ const queryResultDecoder = object({
973
+ type: searchTypeDecoder,
974
+ id: optional(nonEmptyStringDecoder),
975
+ displayName: optional(nonEmptyStringDecoder),
976
+ description: optional(nonEmptyStringDecoder),
977
+ iconURL: optional(nonEmptyStringDecoder),
978
+ metadata: optional(anyJson()),
979
+ action: optional(mainActionDecoder),
980
+ secondaryActions: optional(array(secondaryActionDecoder))
981
+ });
982
+ const legacySearchResultItemDecoder = object({
983
+ type: string(),
984
+ category: optional(string()),
985
+ id: optional(string()),
986
+ displayName: optional(string()),
987
+ description: optional(string()),
988
+ iconURL: optional(string()),
989
+ action: optional(mainActionDecoder)
990
+ });
991
+ const protocolSearchResultsBatchDecoder = object({
992
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
993
+ provider: optional(providerData),
994
+ queryId: nonEmptyStringDecoder,
995
+ status: constant("in-progress")
996
+ });
997
+ const protocolSearchCompletedDecoder = object({
998
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
999
+ queryId: nonEmptyStringDecoder,
1000
+ status: constant("done")
1001
+ });
1002
+ const protocolProviderErrorDecoder = object({
1003
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1004
+ provider: optional(providerData),
1005
+ queryId: nonEmptyStringDecoder,
1006
+ errorMessage: nonEmptyStringDecoder,
1007
+ status: constant("error")
1029
1008
  });
1030
1009
 
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
- }
1010
+ class ClientController {
1011
+ logger;
1012
+ glueController;
1013
+ modelFactory;
1014
+ registry = CallbackRegistryFactory();
1015
+ activeQueryLookup = {};
1016
+ queryIdToMasterIdLookup = {};
1017
+ pendingDebounce = [];
1018
+ debounceTimer;
1019
+ debounceMS = 0;
1020
+ constructor(logger, glueController, modelFactory) {
1021
+ this.logger = logger;
1022
+ this.glueController = glueController;
1023
+ this.modelFactory = modelFactory;
1024
+ }
1025
+ setDebounceMS(data) {
1026
+ this.logger.info(`[${data.commandId}] Setting the debounceMS to: ${data.milliseconds}`);
1027
+ this.debounceMS = data.milliseconds;
1028
+ this.logger.info(`[${data.commandId}] debounceMS set to: ${data.milliseconds}`);
1029
+ }
1030
+ getDebounceMS(data) {
1031
+ this.logger.info(`[${data.commandId}] Getting the debounceMS`);
1032
+ return this.debounceMS;
1033
+ }
1034
+ async query(data, skipDebounce) {
1035
+ if (this.debounceMS && !skipDebounce) {
1036
+ return this.debounceQuery(data);
1037
+ }
1038
+ await this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));
1039
+ const { queryConfig, commandId } = data;
1040
+ this.logger.info(`[${commandId}] Initiating a query request`);
1041
+ let allProvidersInfo = await this.glueController.getAllProvidersInfo();
1042
+ this.logger.trace(`[${commandId}] Got all available providers: ${JSON.stringify(allProvidersInfo)}`);
1043
+ if (queryConfig.providers) {
1044
+ this.logger.info(`[${commandId}] Filtering providers by explicitly allowed providers.`);
1045
+ allProvidersInfo = this.filterProvidersByAllowList(allProvidersInfo, queryConfig.providers);
1046
+ }
1047
+ if (queryConfig.types) {
1048
+ this.logger.info(`[${commandId}] Filtering providers by explicitly allowed types.`);
1049
+ allProvidersInfo = this.filterProvidersByAllowedTypes(allProvidersInfo, queryConfig.types);
1050
+ }
1051
+ if (!allProvidersInfo.length) {
1052
+ this.logger.warn(`[${commandId}] There are no providers that can handle the query for ${data.queryConfig.search}`);
1053
+ }
1054
+ this.logger.info(`[${commandId}] Sending query request to providers: ${JSON.stringify(allProvidersInfo)}`);
1055
+ const allQueryResponses = await this.glueController.sendQueryRequest(queryConfig, allProvidersInfo);
1056
+ this.logger.info(`[${commandId}] Received responses from the providers: ${JSON.stringify(allQueryResponses)}`);
1057
+ const masterQueryId = this.generateMasterQueryId();
1058
+ const queryModel = this.modelFactory.buildClientQueryModel(masterQueryId, this);
1059
+ this.logger.info(`[${commandId}] The query is in progress with master id: ${masterQueryId}`);
1060
+ this.activeQueryLookup[masterQueryId] = {
1061
+ servers: allQueryResponses,
1062
+ model: queryModel
1063
+ };
1064
+ allQueryResponses.forEach((response) => {
1065
+ this.queryIdToMasterIdLookup[response.queryId] = masterQueryId;
1066
+ });
1067
+ if (!allQueryResponses.length) {
1068
+ setTimeout(() => {
1069
+ this.registry.execute(`on-query-completed-${masterQueryId}`);
1070
+ this.cleanUpQuery(masterQueryId);
1071
+ }, 0);
1072
+ }
1073
+ return queryModel.exposeFacade();
1074
+ }
1075
+ async cancelQuery(masterQueryId, commandId) {
1076
+ const activeQuery = this.activeQueryLookup[masterQueryId];
1077
+ if (!activeQuery) {
1078
+ throw new Error(`[${commandId}] Cannot cancel query: ${masterQueryId}, because this query does not exist`);
1079
+ }
1080
+ const interopIds = activeQuery.servers;
1081
+ this.logger.info(`[${commandId}] Sending cancel query requests`);
1082
+ await Promise.all(interopIds.map((serverId) => {
1083
+ this.logger.trace(`[${commandId}] Sending cancel query request to ${serverId.interopId} with queryId: ${serverId.queryId}`);
1084
+ return this.glueController.sendQueryCancelRequest({ id: serverId.queryId }, { instance: serverId.interopId });
1085
+ }));
1086
+ this.logger.info(`[${commandId}] The query was cancelled`);
1087
+ }
1088
+ processClientOnResults(data) {
1089
+ return this.registry.add(`on-query-results-${data.masterQueryId}`, data.callback);
1090
+ }
1091
+ processClientOnCompleted(data) {
1092
+ return this.registry.add(`on-query-completed-${data.masterQueryId}`, data.callback);
1093
+ }
1094
+ processClientOnError(data) {
1095
+ return this.registry.add(`on-query-error-${data.masterQueryId}`, data.callback);
1096
+ }
1097
+ async handleProviderCall(args) {
1098
+ const { status } = args;
1099
+ const validatedOperation = queryStatusDecoder.runWithException(status);
1100
+ const commandId = nanoid(10);
1101
+ switch (validatedOperation) {
1102
+ case SEARCH_QUERY_STATUSES.done:
1103
+ return this.handleQueryCompleted({ completedConfig: args, commandId });
1104
+ case SEARCH_QUERY_STATUSES.inProgress:
1105
+ return this.handleQueryResults({ resultsBatch: args, commandId });
1106
+ case SEARCH_QUERY_STATUSES.error:
1107
+ return this.handleQueryError({ error: args, commandId });
1108
+ default:
1109
+ throw new Error(`Unrecognized status: ${status}`);
1110
+ }
1111
+ }
1112
+ handleQueryResults(data) {
1113
+ const { resultsBatch, commandId } = data;
1114
+ this.logger.trace(`[${commandId}] Processing a results batch from provider: ${resultsBatch.provider?.name} with id: ${resultsBatch.provider?.id}`);
1115
+ const verifiedResultsBatch = protocolSearchResultsBatchDecoder.runWithException(resultsBatch);
1116
+ const masterQueryId = this.queryIdToMasterIdLookup[verifiedResultsBatch.queryId];
1117
+ if (!masterQueryId) {
1118
+ this.logger.warn(`[${commandId}] Received results for an unknown query. Provider ${JSON.stringify(verifiedResultsBatch.provider)}, items: ${JSON.stringify(verifiedResultsBatch.items)}`);
1119
+ return;
1120
+ }
1121
+ this.logger.trace(`[${commandId}] The results batch is validated, forwarding to the callbacks`);
1122
+ const translatedResults = this.checkTransformLegacyResults(verifiedResultsBatch.items);
1123
+ const results = {
1124
+ provider: verifiedResultsBatch.provider,
1125
+ results: translatedResults
1126
+ };
1127
+ this.registry.execute(`on-query-results-${masterQueryId}`, results);
1128
+ }
1129
+ handleQueryCompleted(data) {
1130
+ const { completedConfig, commandId } = data;
1131
+ this.logger.trace(`[${commandId}] Processing a query completed message from query id: ${completedConfig.queryId}`);
1132
+ const verifiedCompleteConfig = protocolSearchCompletedDecoder.runWithException(completedConfig);
1133
+ const masterQueryId = this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1134
+ if (!masterQueryId) {
1135
+ this.logger.warn(`[${commandId}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(verifiedCompleteConfig.queryId)}`);
1136
+ return;
1137
+ }
1138
+ if (verifiedCompleteConfig.items.length) {
1139
+ const translatedResults = this.checkTransformLegacyResults(verifiedCompleteConfig.items);
1140
+ const results = {
1141
+ results: translatedResults
1142
+ };
1143
+ this.registry.execute(`on-query-results-${masterQueryId}`, results);
1144
+ }
1145
+ delete this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1146
+ const activeQuery = this.activeQueryLookup[masterQueryId];
1147
+ activeQuery.servers = activeQuery.servers.filter((server) => server.queryId !== verifiedCompleteConfig.queryId);
1148
+ if (activeQuery.servers.length) {
1149
+ this.logger.trace(`[${commandId}] Waiting for more providers to complete`);
1150
+ return;
1151
+ }
1152
+ this.logger.trace(`[${commandId}] All providers are done, marking this query as completed`);
1153
+ this.registry.execute(`on-query-completed-${masterQueryId}`);
1154
+ this.cleanUpQuery(masterQueryId);
1155
+ }
1156
+ handleQueryError(data) {
1157
+ const { error, commandId } = data;
1158
+ this.logger.trace(`[${commandId}] Processing an error message from query: ${error.queryId}`);
1159
+ const validatedError = protocolProviderErrorDecoder.runWithException(error);
1160
+ const masterQueryId = this.queryIdToMasterIdLookup[validatedError.queryId];
1161
+ if (!masterQueryId) {
1162
+ this.logger.warn(`[${commandId}] Received error message for an unknown query. Provider query id: ${JSON.stringify(validatedError.queryId)} and message: ${JSON.stringify(validatedError.errorMessage)}`);
1163
+ return;
1164
+ }
1165
+ const queryError = {
1166
+ error: validatedError.errorMessage,
1167
+ provider: validatedError.provider
1168
+ };
1169
+ this.registry.execute(`on-query-error-${masterQueryId}`, queryError);
1170
+ }
1171
+ filterProvidersByAllowList(servers, allowed) {
1172
+ const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1173
+ lookup[allowedEntry.id] = true;
1174
+ return lookup;
1175
+ }, {});
1176
+ return servers.filter((server) => {
1177
+ const serverProviders = server.info.providers;
1178
+ return serverProviders.some((provider) => allowedLookup[provider.id]);
1179
+ });
1180
+ }
1181
+ filterProvidersByAllowedTypes(servers, allowed) {
1182
+ const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1183
+ lookup[allowedEntry.name] = true;
1184
+ return lookup;
1185
+ }, {});
1186
+ return servers.filter((server) => {
1187
+ const allTypes = server.info.supportedTypes;
1188
+ if (allTypes.some((searchType) => searchType === "*")) {
1189
+ return true;
1190
+ }
1191
+ if (!allTypes || !allTypes.length) {
1192
+ return true;
1193
+ }
1194
+ return allTypes.some((supportedType) => allowedLookup[supportedType]);
1195
+ });
1196
+ }
1197
+ generateMasterQueryId() {
1198
+ const queryId = nanoid(10);
1199
+ if (this.activeQueryLookup[queryId]) {
1200
+ return this.generateMasterQueryId();
1201
+ }
1202
+ return queryId;
1203
+ }
1204
+ cleanUpQuery(masterQueryId) {
1205
+ this.registry.clearKey(`on-query-results-${masterQueryId}`);
1206
+ this.registry.clearKey(`on-query-completed-${masterQueryId}`);
1207
+ this.registry.clearKey(`on-query-error-${masterQueryId}`);
1208
+ delete this.activeQueryLookup[masterQueryId];
1209
+ }
1210
+ debounceQuery(data) {
1211
+ return new Promise((res, rej) => {
1212
+ clearTimeout(this.debounceTimer);
1213
+ this.debounceTimer = setTimeout(() => {
1214
+ const currentPending = [...this.pendingDebounce];
1215
+ this.pendingDebounce = [];
1216
+ this.query(data, true)
1217
+ .then((query) => currentPending.forEach(({ resolve }) => resolve(query)))
1218
+ .catch((error) => currentPending.forEach(({ reject }) => reject(error)));
1219
+ }, this.debounceMS);
1220
+ this.pendingDebounce.push({ resolve: res, reject: rej });
1221
+ });
1222
+ }
1223
+ checkTransformLegacyResults(items) {
1224
+ if (!items.length) {
1225
+ return [];
1226
+ }
1227
+ const sampleItem = items[0];
1228
+ if (!sampleItem || typeof sampleItem.type === "object") {
1229
+ return items;
1230
+ }
1231
+ return items.map((item) => {
1232
+ return {
1233
+ type: { name: item.type, displayName: item.category },
1234
+ id: item.id,
1235
+ displayName: item.displayName,
1236
+ description: item.description,
1237
+ iconURL: item.iconURL,
1238
+ action: item.action
1239
+ };
1240
+ });
1241
+ }
1266
1242
  }
1267
1243
 
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;
1244
+ const MAIN_PROVIDER_METHOD_NAME = "T42.Search.Provider";
1245
+ const MAIN_CLIENT_METHOD_NAME = "T42.Search.Client";
1246
+ const SEQUELIZER_INTERVAL_MS = 10;
1247
+ const FLUSH_SEQUELIZER_INTERVAL_MS = 10;
1248
+ const FLUSH_TIMEOUT_MS = 100;
1273
1249
  const STALE_QUERY_TIMEOUT_MS = 900000;
1274
1250
 
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
- }
1251
+ class GlueController {
1252
+ glue;
1253
+ constructor(glue) {
1254
+ this.glue = glue;
1255
+ }
1256
+ get myAppName() {
1257
+ return this.glue.interop.instance.applicationName;
1258
+ }
1259
+ get myInteropId() {
1260
+ return this.glue.interop.instance.instance;
1261
+ }
1262
+ async registerMainProviderMethod(handler) {
1263
+ const mainMethodStatus = this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME);
1264
+ if (mainMethodStatus.exists) {
1265
+ return;
1266
+ }
1267
+ await this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME, handler);
1268
+ }
1269
+ async registerMainClientMethod(handler) {
1270
+ const mainMethodStatus = this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME);
1271
+ if (mainMethodStatus.exists) {
1272
+ return;
1273
+ }
1274
+ await this.glue.interop.register(MAIN_CLIENT_METHOD_NAME, handler);
1275
+ }
1276
+ async clearMainProviderMethod() {
1277
+ await this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME);
1278
+ }
1279
+ async sendClientResultsBatch(batch, clientInstanceId, queryId) {
1280
+ const interopArguments = {
1281
+ items: batch.results,
1282
+ provider: batch.provider,
1283
+ queryId,
1284
+ status: SEARCH_QUERY_STATUSES.inProgress
1285
+ };
1286
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1287
+ }
1288
+ async sendClientQueueCompleted(clientInstanceId, queryId) {
1289
+ const interopArguments = {
1290
+ items: [],
1291
+ queryId,
1292
+ status: SEARCH_QUERY_STATUSES.done
1293
+ };
1294
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1295
+ }
1296
+ async sendClientErrorMessage(error, clientInstanceId, queryId, provider) {
1297
+ const interopArguments = {
1298
+ items: [],
1299
+ provider,
1300
+ errorMessage: error,
1301
+ queryId,
1302
+ status: SEARCH_QUERY_STATUSES.error
1303
+ };
1304
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1305
+ }
1306
+ async sendQueryRequest(queryConfig, instances) {
1307
+ if (!instances.length) {
1308
+ return [];
1309
+ }
1310
+ const target = instances.map((inst) => ({ instance: inst.interopId }));
1311
+ const invokeArgs = {
1312
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search,
1313
+ apiVersion: "1",
1314
+ ...queryConfig
1315
+ };
1316
+ const response = await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, invokeArgs, target);
1317
+ const allReturned = response.all_return_values || [];
1318
+ return allReturned.map((returnValue) => {
1319
+ return {
1320
+ interopId: returnValue.executed_by?.instance,
1321
+ queryId: returnValue.returned.id
1322
+ };
1323
+ });
1324
+ }
1325
+ async sendQueryCancelRequest(request, instance) {
1326
+ const args = {
1327
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,
1328
+ id: request.id
1329
+ };
1330
+ await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, instance);
1331
+ }
1332
+ async getAllProvidersInfo() {
1333
+ if (this.glue.interop.methods().every((method) => method.name !== MAIN_PROVIDER_METHOD_NAME)) {
1334
+ return [];
1335
+ }
1336
+ const args = {
1337
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info
1338
+ };
1339
+ const response = await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, "all");
1340
+ const allReturned = response.all_return_values || [];
1341
+ return allReturned.map((returnValue) => {
1342
+ const isLegacy = typeof returnValue.returned.apiVersion === "undefined";
1343
+ const info = isLegacy ? {
1344
+ supportedTypes: returnValue.returned.supportedTypes,
1345
+ apiVersion: returnValue.returned.apiVersion,
1346
+ providers: [{
1347
+ interopId: returnValue.executed_by?.instance,
1348
+ id: returnValue.executed_by?.instance,
1349
+ name: returnValue.executed_by?.instance,
1350
+ appName: response.executed_by?.application,
1351
+ types: returnValue.returned.supportedTypes.map((t) => ({ name: t }))
1352
+ }]
1353
+ } : returnValue.returned;
1354
+ return {
1355
+ interopId: returnValue.executed_by?.instance,
1356
+ info
1357
+ };
1358
+ });
1359
+ }
1360
+ checkMyMethodExists(methodName) {
1361
+ const myMethods = this.glue.interop.methodsForInstance({ instance: this.glue.interop.instance.instance });
1362
+ return { exists: myMethods.some((method) => method.name === methodName) };
1363
+ }
1403
1364
  }
1404
1365
 
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
- }
1366
+ class MainController {
1367
+ logger;
1368
+ glueController;
1369
+ clientController;
1370
+ providerController;
1371
+ constructor(logger, glueController, clientController, providerController) {
1372
+ this.logger = logger;
1373
+ this.glueController = glueController;
1374
+ this.clientController = clientController;
1375
+ this.providerController = providerController;
1376
+ }
1377
+ setDebounceMS(data) {
1378
+ this.logger.info(`[${data.commandId}] Starting setDebounceMS operation with duration ${data.milliseconds}`);
1379
+ this.clientController.setDebounceMS(data);
1380
+ this.logger.info(`[${data.commandId}] Operation setDebounceMS with duration ${data.milliseconds} completed`);
1381
+ }
1382
+ getDebounceMS(data) {
1383
+ this.logger.info(`[${data.commandId}] Starting getDebounceMS operation.`);
1384
+ return this.clientController.getDebounceMS(data);
1385
+ }
1386
+ async query(data) {
1387
+ this.logger.info(`[${data.commandId}] Starting query operation with config ${JSON.stringify(data.queryConfig)}`);
1388
+ if (Array.isArray(data.queryConfig.providers) && !data.queryConfig.providers.length) {
1389
+ throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");
1390
+ }
1391
+ if (Array.isArray(data.queryConfig.types) && !data.queryConfig.types.length) {
1392
+ throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");
1393
+ }
1394
+ const query = await this.clientController.query(data);
1395
+ this.logger.info(`[${data.commandId}] Operation query with config ${JSON.stringify(data.queryConfig)} completed.`);
1396
+ return query;
1397
+ }
1398
+ async registerProvider(data) {
1399
+ this.logger.info(`[${data.commandId}] Starting registerProvider operation with config ${JSON.stringify(data.config)}`);
1400
+ const provider = await this.providerController.processRegisterProvider(data);
1401
+ this.logger.info(`[${data.commandId}] Operation registerProvider with config ${JSON.stringify(data.config)} completed.`);
1402
+ return provider;
1403
+ }
1404
+ async providers(data) {
1405
+ this.logger.info(`[${data.commandId}] Starting providers operation.`);
1406
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1407
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1408
+ this.logger.info(`[${data.commandId}] Operation providers completed.`);
1409
+ return allProvidersData;
1410
+ }
1411
+ async types(data) {
1412
+ this.logger.info(`[${data.commandId}] Starting types operation.`);
1413
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1414
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1415
+ const allSupportedTypes = allProvidersData.filter((provData) => !!provData.types).flatMap((provData) => provData.types);
1416
+ const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1417
+ this.logger.info(`[${data.commandId}] Operation types completed.`);
1418
+ return uniqueSupportedTypes;
1419
+ }
1463
1420
  }
1464
1421
 
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;
1422
+ const extractErrorMsg = (error) => {
1423
+ const stringError = typeof error === "string" ?
1424
+ error :
1425
+ error.message ? JSON.stringify(error.message) :
1426
+ JSON.stringify(error);
1427
+ return stringError;
1471
1428
  };
1472
1429
 
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
- }
1430
+ class ProviderController {
1431
+ logger;
1432
+ glueController;
1433
+ sequelizer;
1434
+ limitsTracker;
1435
+ modelsFactory;
1436
+ registry = CallbackRegistryFactory();
1437
+ providersModels = {};
1438
+ activeQueries = {};
1439
+ constructor(logger, glueController, sequelizer, limitsTracker, modelsFactory) {
1440
+ this.logger = logger;
1441
+ this.glueController = glueController;
1442
+ this.sequelizer = sequelizer;
1443
+ this.limitsTracker = limitsTracker;
1444
+ this.modelsFactory = modelsFactory;
1445
+ }
1446
+ async processRegisterProvider(data) {
1447
+ const { config, commandId } = data;
1448
+ this.logger.info(`[${commandId}] enqueueing the provider registration process with config: ${JSON.stringify(config)}`);
1449
+ const result = await this.sequelizer.enqueue(async () => {
1450
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1451
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1452
+ if (allProvidersData.some((providerData) => providerData && providerData.name === config.name)) {
1453
+ throw new Error(`Cannot register a new provider with name: ${config.name}, because there already is a provider with this name`);
1454
+ }
1455
+ await this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));
1456
+ const modelData = {
1457
+ id: nanoid(10),
1458
+ name: config.name,
1459
+ interopId: this.glueController.myInteropId,
1460
+ appName: this.glueController.myAppName,
1461
+ types: config.types
1462
+ };
1463
+ const model = this.modelsFactory.buildProviderModel(modelData, this);
1464
+ this.providersModels[modelData.id] = model;
1465
+ return model.exposeFacade();
1466
+ });
1467
+ this.logger.info(`[${commandId}] the provider with name: ${config.name} has been registered.`);
1468
+ return result;
1469
+ }
1470
+ processProviderOnQuery(data) {
1471
+ return this.registry.add(`on-search-query-${data.id}`, data.callback);
1472
+ }
1473
+ processProviderOnQueryCancel(data) {
1474
+ return this.registry.add(`on-cancel-query-${data.id}`, data.callback);
1475
+ }
1476
+ async processProviderUnregister(data) {
1477
+ this.logger.info(`[${data.commandId}] enqueueing the provider un-registration with id: ${data.id}`);
1478
+ await this.sequelizer.enqueue(async () => {
1479
+ this.cleanUpProvider(data.id, data.commandId);
1480
+ if (Object.keys(this.providersModels).length) {
1481
+ return;
1482
+ }
1483
+ await this.glueController.clearMainProviderMethod();
1484
+ });
1485
+ this.logger.info(`[${data.commandId}] the provider un-registration with id: ${data.id} completed`);
1486
+ }
1487
+ async processProviderQueryDone(command) {
1488
+ const { commandId, identification } = command;
1489
+ this.activeQueries[identification.queryId]?.publisher.syncSuspendProvider(identification.providerId, commandId);
1490
+ await this.sequelizer.enqueue(async () => {
1491
+ this.logger.trace(`[${commandId}] Processing a query done command with identification: ${JSON.stringify(identification)}`);
1492
+ const activeQuery = this.activeQueries[identification.queryId];
1493
+ if (!activeQuery) {
1494
+ this.logger.warn(`[${commandId}] Cannot mark provider: ${identification.providerId} done with query ${identification.queryId}, because there is no active query with this id`);
1495
+ return;
1496
+ }
1497
+ await this.cleanUpProviderQuery(identification.queryId, identification.providerId, commandId);
1498
+ if (activeQuery.providersAtWork.length) {
1499
+ this.logger.trace(`[${commandId}] Query done command completed, but there are more providers still at work.`);
1500
+ return;
1501
+ }
1502
+ this.cleanUpQuery(identification.queryId, commandId);
1503
+ this.logger.trace(`[${commandId}] Query is completed, signalling.`);
1504
+ });
1505
+ }
1506
+ processProviderQueryError(command) {
1507
+ const { commandId, identification, error } = command;
1508
+ this.logger.warn(`[${commandId}] Processing an error sent by provider: ${identification.providerId} for query id: ${identification.queryId} -> ${error}`);
1509
+ this.activeQueries[identification.queryId]?.publisher.markProviderError(command);
1510
+ return this.processProviderQueryDone(command);
1511
+ }
1512
+ processProviderQueryResult(command) {
1513
+ const { commandId, identification } = command;
1514
+ const activeQuery = this.activeQueries[identification.queryId];
1515
+ if (!activeQuery) {
1516
+ 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.`;
1517
+ this.logger.warn(`[${command}] ${errorMessage}`);
1518
+ throw new Error(errorMessage);
1519
+ }
1520
+ if (activeQuery.publisher.checkProviderSuspended(identification.providerId)) {
1521
+ 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.`;
1522
+ this.logger.warn(`[${command}] ${errorMessage}`);
1523
+ throw new Error(errorMessage);
1524
+ }
1525
+ const requestedTypes = activeQuery.requestedTypes;
1526
+ if (requestedTypes && requestedTypes.every((searchType) => searchType.name !== command.result.type.name)) {
1527
+ 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.`;
1528
+ this.logger.warn(`[${command}] ${errorMessage}`);
1529
+ throw new Error(errorMessage);
1530
+ }
1531
+ const testResult = this.limitsTracker.testResultLimit(command);
1532
+ if (testResult?.maxLimitHit) {
1533
+ 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.`;
1534
+ this.logger.info(errorMessage);
1535
+ setTimeout(() => this.processProviderQueryDone(command), 0);
1536
+ throw new Error(errorMessage);
1537
+ }
1538
+ if (testResult?.maxLimitPerTypeHit) {
1539
+ 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.`;
1540
+ this.logger.info(errorMessage);
1541
+ throw new Error(errorMessage);
1542
+ }
1543
+ this.logger.trace(`[${commandId}] An active query for query ${identification.queryId} was found and the provider is within limits, queueing the result`);
1544
+ this.limitsTracker.update(command);
1545
+ activeQuery.publisher.queueResult(command);
1546
+ this.logger.trace(`[${commandId}] The query result was queued successfully.`);
1547
+ }
1548
+ async handleSearchQueryRequest(args, caller) {
1549
+ const { operation } = args;
1550
+ const validatedOperation = operationDecoder.runWithException(operation);
1551
+ const commandId = nanoid(10);
1552
+ switch (validatedOperation) {
1553
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:
1554
+ return this.handleInfoOperation({ commandId });
1555
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:
1556
+ return this.handleSearchOperation({ args, commandId }, caller);
1557
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:
1558
+ return this.handleCancelOperation({ args, commandId });
1559
+ default:
1560
+ throw new Error(`Unrecognized operation: ${operation}`);
1561
+ }
1562
+ }
1563
+ async handleInfoOperation(request) {
1564
+ this.logger.info(`[${request.commandId}] handling an info operation`);
1565
+ const allSupportedTypes = Object.values(this.providersModels).flatMap((providerModel) => providerModel.myProviderData.types || []);
1566
+ const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1567
+ const hasWildCardTypeProvider = Object.values(this.providersModels).some((providerModel) => !providerModel.myProviderData.types);
1568
+ if (hasWildCardTypeProvider) {
1569
+ uniqueSupportedTypes.push({ name: "*" });
1570
+ }
1571
+ const providers = Object.values(this.providersModels).map((providerModel) => providerModel.myProviderData);
1572
+ const response = {
1573
+ supportedTypes: uniqueSupportedTypes.map((supportedType) => supportedType.name),
1574
+ providers: providers,
1575
+ apiVersion: "1"
1576
+ };
1577
+ this.logger.info(`[${request.commandId}] responding to an info operation with: ${JSON.stringify(response)}`);
1578
+ return response;
1579
+ }
1580
+ async handleSearchOperation(request, caller) {
1581
+ const commandId = request.commandId;
1582
+ const queryId = this.generateQueryId();
1583
+ this.logger.info(`[${commandId}] Processing search operation with queryId: ${queryId} request details: ${JSON.stringify(request.args)}`);
1584
+ const isLegacyRequest = this.checkRequestLegacy(request.args);
1585
+ const validatedRequest = this.prepareRequest(request.args, isLegacyRequest, commandId);
1586
+ this.logger.info(`[${commandId}] Search operation with queryId: ${queryId} is validated. Creating an active query and enqueueing calling the providers.`);
1587
+ this.activeQueries[queryId] = {
1588
+ queryId,
1589
+ callerInstanceId: caller.instance,
1590
+ providersAtWork: [],
1591
+ requestedTypes: validatedRequest.types,
1592
+ publisher: this.modelsFactory.buildPublisher(caller.instance, queryId, isLegacyRequest),
1593
+ staleTimer: this.setClearStaleQueryTimer(queryId)
1594
+ };
1595
+ if (validatedRequest.providerLimits) {
1596
+ this.limitsTracker.enableTracking(validatedRequest.providerLimits, queryId);
1597
+ }
1598
+ setTimeout(() => {
1599
+ this.sequelizer.enqueue(async () => {
1600
+ try {
1601
+ this.logger.info(`[${commandId}] Calling the providers.`);
1602
+ this.callProviders(validatedRequest, queryId, commandId);
1603
+ }
1604
+ catch (error) {
1605
+ this.logger.error(`[${commandId}] Error calling the providers: ${extractErrorMsg(error)}`);
1606
+ }
1607
+ });
1608
+ }, 0);
1609
+ this.logger.info(`[${commandId}] Search operation with queryID: ${queryId} processed successfully.`);
1610
+ return { id: queryId };
1611
+ }
1612
+ async handleCancelOperation(request) {
1613
+ await this.sequelizer.enqueue(async () => {
1614
+ const validation = searchCancelRequestDecoder.run(request.args);
1615
+ if (!validation.ok) {
1616
+ const errorMsg = `Cannot process a cancel request, because of validation error: ${JSON.stringify(validation.error)}`;
1617
+ this.logger.warn(`[${request.commandId}] ${errorMsg}`);
1618
+ throw new Error(errorMsg);
1619
+ }
1620
+ const validatedRequest = validation.result;
1621
+ const activeQuery = this.activeQueries[validatedRequest.id];
1622
+ if (!activeQuery) {
1623
+ return;
1624
+ }
1625
+ clearTimeout(activeQuery.staleTimer);
1626
+ activeQuery.publisher.cancel(request.commandId);
1627
+ delete this.activeQueries[validatedRequest.id];
1628
+ activeQuery.providersAtWork.forEach((provider) => this.registry.execute(`on-cancel-query-${provider.myProviderData.id}`, { id: validatedRequest.id }));
1629
+ });
1630
+ }
1631
+ generateQueryId() {
1632
+ const queryId = nanoid(10);
1633
+ if (this.activeQueries[queryId]) {
1634
+ return this.generateQueryId();
1635
+ }
1636
+ return queryId;
1637
+ }
1638
+ translateLegacySearchRequest(legacyRequest) {
1639
+ return {
1640
+ search: legacyRequest.search,
1641
+ types: legacyRequest.types?.map((searchType) => ({ name: searchType })),
1642
+ providerLimits: {
1643
+ maxResults: legacyRequest.limit,
1644
+ maxResultsPerType: legacyRequest.categoryLimit
1645
+ }
1646
+ };
1647
+ }
1648
+ checkRequestLegacy(searchRequest) {
1649
+ return typeof searchRequest.apiVersion === "undefined";
1650
+ }
1651
+ callProviders(validatedRequest, queryId, commandId) {
1652
+ let providers = validatedRequest.providers ?
1653
+ this.getFilteredProviderModels(validatedRequest.providers)
1654
+ : Object.values(this.providersModels);
1655
+ this.logger.trace(`[${commandId}] initial providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1656
+ providers = validatedRequest.types ? this.getFilteredProvidersBySearchTypes(providers, validatedRequest.types) : providers;
1657
+ this.logger.trace(`[${commandId}] search type providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1658
+ this.activeQueries[queryId].publisher.configureProviders(providers);
1659
+ this.activeQueries[queryId].providersAtWork.push(...providers);
1660
+ providers.forEach((provider) => this.callProvider(provider, validatedRequest, queryId, commandId));
1661
+ }
1662
+ callProvider(provider, validatedRequest, queryId, commandId) {
1663
+ const queryModel = this.modelsFactory.buildProviderQueryModel(validatedRequest, { queryId, providerId: provider.myProviderData.id }, this);
1664
+ const queryFacade = queryModel.exposeFacade();
1665
+ 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}.`);
1666
+ this.registry.execute(`on-search-query-${provider.myProviderData.id}`, queryFacade);
1667
+ }
1668
+ getFilteredProviderModels(providers) {
1669
+ const filtered = providers.reduce((providers, provider) => {
1670
+ if (this.providersModels[provider.id]) {
1671
+ providers.push(this.providersModels[provider.id]);
1672
+ }
1673
+ return providers;
1674
+ }, []);
1675
+ return filtered;
1676
+ }
1677
+ getFilteredProvidersBySearchTypes(providers, searchTypes) {
1678
+ const filtered = providers.filter((provider) => {
1679
+ if (!provider.myProviderData.types || !provider.myProviderData.types.length) {
1680
+ return true;
1681
+ }
1682
+ return provider.myProviderData.types?.some((providerSearchType) => searchTypes.some((searchType) => searchType.name === providerSearchType.name));
1683
+ });
1684
+ return filtered;
1685
+ }
1686
+ setClearStaleQueryTimer(queryId) {
1687
+ return setTimeout(() => {
1688
+ const commandId = nanoid(10);
1689
+ this.logger.info(`[${commandId}] Stale query timer is activated for queryId: ${queryId}`);
1690
+ const activeQuery = this.activeQueries[queryId];
1691
+ if (!activeQuery) {
1692
+ this.logger.info(`[${commandId}] No active query was found, this was a false activation.`);
1693
+ return;
1694
+ }
1695
+ this.logger.info(`[${commandId}] force-marking the query as done`);
1696
+ this.cleanUpQuery(queryId, commandId);
1697
+ this.logger.info(`[${commandId}] the stale query was cleared.`);
1698
+ }, STALE_QUERY_TIMEOUT_MS);
1699
+ }
1700
+ prepareRequest(searchRequest, isLegacyRequest, commandId) {
1701
+ const parsedRequest = isLegacyRequest ? this.translateLegacySearchRequest(searchRequest) : searchRequest;
1702
+ const validation = queryConfigDecoder.run(parsedRequest);
1703
+ if (!validation.ok) {
1704
+ const errorMsg = `Cannot process a search request, because of validation error: ${JSON.stringify(validation.error)}`;
1705
+ this.logger.warn(`[${commandId}] ${errorMsg}`);
1706
+ throw new Error(errorMsg);
1707
+ }
1708
+ const validatedRequest = validation.result;
1709
+ return validatedRequest;
1710
+ }
1711
+ cleanUpQuery(queryId, commandId) {
1712
+ const activeQuery = this.activeQueries[queryId];
1713
+ clearTimeout(activeQuery.staleTimer);
1714
+ activeQuery.publisher.cleanPublisher(commandId);
1715
+ delete this.activeQueries[queryId];
1716
+ this.limitsTracker.cleanTracking(queryId);
1717
+ }
1718
+ cleanUpProvider(providerId, commandId) {
1719
+ this.registry.clearKey(`on-search-query-${providerId}`);
1720
+ this.registry.clearKey(`on-cancel-query-${providerId}`);
1721
+ delete this.providersModels[providerId];
1722
+ const queriesWithProvider = Object.values(this.activeQueries).filter((query) => !query.publisher.checkProviderSuspended(providerId));
1723
+ queriesWithProvider.forEach((query) => {
1724
+ this.processProviderQueryDone({
1725
+ identification: {
1726
+ queryId: query.queryId,
1727
+ providerId
1728
+ },
1729
+ commandId
1730
+ });
1731
+ });
1732
+ }
1733
+ async cleanUpProviderQuery(queryId, providerId, commandId) {
1734
+ const activeQuery = this.activeQueries[queryId];
1735
+ if (!activeQuery) {
1736
+ this.logger.warn(`[${commandId}] Cannot clean up a provider query ${queryId} for provider ${providerId} because there is no such active query`);
1737
+ return;
1738
+ }
1739
+ activeQuery.providersAtWork = activeQuery.providersAtWork.filter((provider) => provider.myProviderData.id !== providerId);
1740
+ await activeQuery.publisher.markProviderDone(providerId, commandId);
1741
+ }
1800
1742
  }
1801
1743
 
1802
- var version = "2.2.1";
1744
+ var version = "2.2.2";
1803
1745
 
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
- }
1746
+ class SearchFacade {
1747
+ main;
1748
+ constructor(main) {
1749
+ this.main = main;
1750
+ }
1751
+ exposeApi() {
1752
+ const api = {
1753
+ version,
1754
+ setDebounceMS: this.setDebounceMS.bind(this),
1755
+ getDebounceMS: this.getDebounceMS.bind(this),
1756
+ listProviders: this.providers.bind(this),
1757
+ listTypes: this.types.bind(this),
1758
+ query: this.query.bind(this),
1759
+ registerProvider: this.registerProvider.bind(this)
1760
+ };
1761
+ return Object.freeze(api);
1762
+ }
1763
+ setDebounceMS(milliseconds) {
1764
+ nonNegativeNumberDecoder.runWithException(milliseconds);
1765
+ const commandId = nanoid(10);
1766
+ return this.main.setDebounceMS({ milliseconds, commandId });
1767
+ }
1768
+ getDebounceMS() {
1769
+ const commandId = nanoid(10);
1770
+ return this.main.getDebounceMS({ commandId });
1771
+ }
1772
+ async providers() {
1773
+ const commandId = nanoid(10);
1774
+ return this.main.providers({ commandId });
1775
+ }
1776
+ async types() {
1777
+ const commandId = nanoid(10);
1778
+ return this.main.types({ commandId });
1779
+ }
1780
+ async query(queryConfig) {
1781
+ const verifiedConfig = queryConfigDecoder.runWithException(queryConfig);
1782
+ const commandId = nanoid(10);
1783
+ return this.main.query({ queryConfig: verifiedConfig, commandId });
1784
+ }
1785
+ async registerProvider(config) {
1786
+ const verifiedConfig = providerRegistrationConfig.runWithException(config);
1787
+ const commandId = nanoid(10);
1788
+ return this.main.registerProvider({ config: verifiedConfig, commandId });
1789
+ }
1855
1790
  }
1856
1791
 
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
- }
1792
+ class AsyncSequelizer {
1793
+ minSequenceInterval;
1794
+ queue = [];
1795
+ isExecutingQueue = false;
1796
+ constructor(minSequenceInterval = 0) {
1797
+ this.minSequenceInterval = minSequenceInterval;
1798
+ }
1799
+ enqueue(action) {
1800
+ return new Promise((resolve, reject) => {
1801
+ this.queue.push({ action, resolve, reject });
1802
+ this.executeQueue();
1803
+ });
1804
+ }
1805
+ async executeQueue() {
1806
+ if (this.isExecutingQueue) {
1807
+ return;
1808
+ }
1809
+ this.isExecutingQueue = true;
1810
+ while (this.queue.length) {
1811
+ const operation = this.queue.shift();
1812
+ if (!operation) {
1813
+ this.isExecutingQueue = false;
1814
+ return;
1815
+ }
1816
+ try {
1817
+ const actionResult = await operation.action();
1818
+ operation.resolve(actionResult);
1819
+ }
1820
+ catch (error) {
1821
+ operation.reject(error);
1822
+ }
1823
+ await this.intervalBreak();
1824
+ }
1825
+ this.isExecutingQueue = false;
1826
+ }
1827
+ intervalBreak() {
1828
+ return new Promise((res) => setTimeout(res, this.minSequenceInterval));
1829
+ }
1896
1830
  }
1897
1831
 
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
- }
1832
+ class LimitsTracker {
1833
+ limitsLookup = {};
1834
+ limitsData = {};
1835
+ enableTracking(limits, queryId) {
1836
+ this.limitsLookup[queryId] = {};
1837
+ this.limitsData[queryId] = {
1838
+ maxResults: limits.maxResults ? limits.maxResults : Number.MAX_SAFE_INTEGER,
1839
+ maxResultsPerType: limits.maxResultsPerType ? limits.maxResultsPerType : Number.MAX_SAFE_INTEGER
1840
+ };
1841
+ }
1842
+ testResultLimit(command) {
1843
+ const foundLookup = this.limitsLookup[command.identification.queryId];
1844
+ const limitData = this.limitsData[command.identification.queryId];
1845
+ if (!foundLookup || !limitData) {
1846
+ return;
1847
+ }
1848
+ let providerStateLookup = foundLookup[command.identification.providerId];
1849
+ if (!providerStateLookup) {
1850
+ providerStateLookup = { total: 0 };
1851
+ foundLookup[command.identification.providerId] = providerStateLookup;
1852
+ }
1853
+ if ((providerStateLookup.total + 1) > limitData.maxResults) {
1854
+ return { maxLimitHit: true };
1855
+ }
1856
+ const resultTypeName = command.result.type.name;
1857
+ if (!resultTypeName) {
1858
+ return;
1859
+ }
1860
+ const currentResultTypeCount = providerStateLookup[resultTypeName] || 0;
1861
+ if ((currentResultTypeCount + 1) > limitData.maxResultsPerType) {
1862
+ return { maxLimitPerTypeHit: true };
1863
+ }
1864
+ }
1865
+ update(command) {
1866
+ const foundLookup = this.limitsLookup[command.identification.queryId];
1867
+ const limitData = this.limitsData[command.identification.queryId];
1868
+ if (!foundLookup || !limitData) {
1869
+ return;
1870
+ }
1871
+ const providerStateLookup = foundLookup[command.identification.providerId];
1872
+ providerStateLookup.total += 1;
1873
+ const resultTypeName = command.result.type.name;
1874
+ if (!resultTypeName) {
1875
+ return;
1876
+ }
1877
+ providerStateLookup[resultTypeName] = providerStateLookup[resultTypeName] ? providerStateLookup[resultTypeName] + 1 : 1;
1878
+ }
1879
+ cleanTracking(queryId) {
1880
+ delete this.limitsLookup[queryId];
1881
+ delete this.limitsData[queryId];
1882
+ }
1951
1883
  }
1952
1884
 
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
- }
1885
+ class ClientQuery {
1886
+ controller;
1887
+ logger;
1888
+ masterQueryId;
1889
+ constructor(controller, logger, masterQueryId) {
1890
+ this.controller = controller;
1891
+ this.logger = logger;
1892
+ this.masterQueryId = masterQueryId;
1893
+ }
1894
+ exposeFacade() {
1895
+ const providerQueryFacade = {
1896
+ cancel: this.cancel.bind(this),
1897
+ onResults: this.onResults.bind(this),
1898
+ onCompleted: this.onCompleted.bind(this),
1899
+ onError: this.onError.bind(this)
1900
+ };
1901
+ return Object.freeze(providerQueryFacade);
1902
+ }
1903
+ async cancel() {
1904
+ const commandId = nanoid(10);
1905
+ this.logger.info(`[${commandId}] received a valid query cancel request, forwarding to the controller.`);
1906
+ await this.controller.cancelQuery(this.masterQueryId, commandId);
1907
+ this.logger.info(`[${commandId}] the cancel request was completed.`);
1908
+ }
1909
+ onResults(callback) {
1910
+ if (typeof callback !== "function") {
1911
+ throw new Error("onQuery requires a callback of type function");
1912
+ }
1913
+ const commandId = nanoid(10);
1914
+ this.logger.info(`[${commandId}] received a valid query onResults request, forwarding to the controller.`);
1915
+ const unsubscribe = this.controller.processClientOnResults({ callback, masterQueryId: this.masterQueryId, commandId });
1916
+ this.logger.info(`[${commandId}] the onResults request was completed.`);
1917
+ return unsubscribe;
1918
+ }
1919
+ onCompleted(callback) {
1920
+ if (typeof callback !== "function") {
1921
+ throw new Error("onQuery requires a callback of type function");
1922
+ }
1923
+ const commandId = nanoid(10);
1924
+ this.logger.info(`[${commandId}] received a valid query onCompleted request, forwarding to the controller.`);
1925
+ const unsubscribe = this.controller.processClientOnCompleted({ callback, masterQueryId: this.masterQueryId, commandId });
1926
+ this.logger.info(`[${commandId}] the onCompleted request was completed.`);
1927
+ return unsubscribe;
1928
+ }
1929
+ onError(callback) {
1930
+ if (typeof callback !== "function") {
1931
+ throw new Error("onQuery requires a callback of type function");
1932
+ }
1933
+ const commandId = nanoid(10);
1934
+ this.logger.info(`[${commandId}] received a valid query onError request, forwarding to the controller.`);
1935
+ const unsubscribe = this.controller.processClientOnError({ callback, masterQueryId: this.masterQueryId, commandId });
1936
+ this.logger.info(`[${commandId}] the onError request was completed.`);
1937
+ return unsubscribe;
1938
+ }
2006
1939
  }
2007
1940
 
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
- }
1941
+ class ProviderModel {
1942
+ myData;
1943
+ controller;
1944
+ logger;
1945
+ constructor(myData, controller, logger) {
1946
+ this.myData = myData;
1947
+ this.controller = controller;
1948
+ this.logger = logger;
1949
+ }
1950
+ get id() {
1951
+ return this.myData.id;
1952
+ }
1953
+ get name() {
1954
+ return this.myData.name;
1955
+ }
1956
+ get appName() {
1957
+ return this.myData.appName;
1958
+ }
1959
+ get types() {
1960
+ return this.myData.types;
1961
+ }
1962
+ get myProviderData() {
1963
+ return Object.assign({}, this.myData);
1964
+ }
1965
+ exposeFacade() {
1966
+ const providerFacade = {
1967
+ interopId: this.myData.interopId,
1968
+ id: this.id,
1969
+ name: this.name,
1970
+ appName: this.appName,
1971
+ types: this.types,
1972
+ onQuery: this.onQuery.bind(this),
1973
+ onQueryCancel: this.onQueryCancel.bind(this),
1974
+ unregister: this.unregister.bind(this)
1975
+ };
1976
+ return Object.freeze(providerFacade);
1977
+ }
1978
+ onQuery(callback) {
1979
+ if (typeof callback !== "function") {
1980
+ throw new Error("onQuery requires a callback of type function");
1981
+ }
1982
+ const commandId = nanoid(10);
1983
+ this.logger.info(`[${commandId}] received a valid onQuery request, forwarding to the controller.`);
1984
+ const unsubscribe = this.controller.processProviderOnQuery({ callback, id: this.id, commandId });
1985
+ this.logger.info(`[${commandId}] the onQuery request was completed.`);
1986
+ return unsubscribe;
1987
+ }
1988
+ onQueryCancel(callback) {
1989
+ if (typeof callback !== "function") {
1990
+ throw new Error("onQuery requires a callback of type function");
1991
+ }
1992
+ const commandId = nanoid(10);
1993
+ this.logger.info(`[${commandId}] received a valid onQueryCancel request, forwarding to the controller.`);
1994
+ const unsubscribe = this.controller.processProviderOnQueryCancel({ callback, id: this.id, commandId });
1995
+ this.logger.info(`[${commandId}] the onQueryCancel request was completed.`);
1996
+ return unsubscribe;
1997
+ }
1998
+ async unregister() {
1999
+ const commandId = nanoid(10);
2000
+ this.logger.info(`[${commandId}] received a valid unregister request, forwarding to the controller.`);
2001
+ await this.controller.processProviderUnregister({ id: this.id, commandId });
2002
+ this.logger.info(`[${commandId}] the unregister request was completed.`);
2003
+ }
2070
2004
  }
2071
2005
 
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
- }
2006
+ class ProviderQueryModel {
2007
+ myData;
2008
+ controller;
2009
+ logger;
2010
+ identification;
2011
+ constructor(myData, controller, logger, identification) {
2012
+ this.myData = myData;
2013
+ this.controller = controller;
2014
+ this.logger = logger;
2015
+ this.identification = identification;
2016
+ }
2017
+ get id() {
2018
+ return this.identification.queryId;
2019
+ }
2020
+ get search() {
2021
+ return this.myData.search;
2022
+ }
2023
+ get providers() {
2024
+ return this.myData.providers;
2025
+ }
2026
+ get types() {
2027
+ return this.myData.types;
2028
+ }
2029
+ get providerLimits() {
2030
+ return this.myData.providerLimits;
2031
+ }
2032
+ get myQueryData() {
2033
+ return Object.assign({}, this.myData);
2034
+ }
2035
+ exposeFacade() {
2036
+ const providerQueryFacade = {
2037
+ id: this.id,
2038
+ search: this.search,
2039
+ providers: this.providers,
2040
+ types: this.types,
2041
+ providerLimits: this.providerLimits,
2042
+ sendResult: this.sendResult.bind(this),
2043
+ error: this.error.bind(this),
2044
+ done: this.done.bind(this)
2045
+ };
2046
+ return Object.freeze(providerQueryFacade);
2047
+ }
2048
+ sendResult(result) {
2049
+ queryResultDecoder.runWithException(result);
2050
+ const commandId = nanoid(10);
2051
+ this.logger.trace(`[${commandId}] Received a valid result, forwarding to the controller`);
2052
+ return this.controller.processProviderQueryResult({ identification: this.identification, result, commandId });
2053
+ }
2054
+ error(error) {
2055
+ const commandId = nanoid(10);
2056
+ nonEmptyStringDecoder.runWithException(error);
2057
+ this.logger.trace(`[${commandId}] Received a valid error, forwarding to the controller`);
2058
+ 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)}`));
2059
+ }
2060
+ done() {
2061
+ const commandId = nanoid(10);
2062
+ this.logger.trace(`[${commandId}] Received a valid done, forwarding to the controller`);
2063
+ 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)}`));
2064
+ }
2127
2065
  }
2128
2066
 
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
- }
2067
+ class QueryResultsPublisher {
2068
+ sequelizer;
2069
+ glueController;
2070
+ logger;
2071
+ clientInstanceId;
2072
+ queryId;
2073
+ isLegacy;
2074
+ queues = {};
2075
+ constructor(sequelizer, glueController, logger, clientInstanceId, queryId, isLegacy) {
2076
+ this.sequelizer = sequelizer;
2077
+ this.glueController = glueController;
2078
+ this.logger = logger;
2079
+ this.clientInstanceId = clientInstanceId;
2080
+ this.queryId = queryId;
2081
+ this.isLegacy = isLegacy;
2082
+ }
2083
+ checkProviderSuspended(providerId) {
2084
+ return this.queues[providerId] ? !!this.queues[providerId].suspended : false;
2085
+ }
2086
+ syncSuspendProvider(providerId, commandId) {
2087
+ const providerQueue = this.queues[providerId];
2088
+ if (!providerQueue) {
2089
+ 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`);
2090
+ return;
2091
+ }
2092
+ providerQueue.suspended = true;
2093
+ }
2094
+ configureProviders(providers) {
2095
+ providers.forEach((provider) => {
2096
+ this.queues[provider.myProviderData.id] = {
2097
+ providerData: provider,
2098
+ pendingResults: []
2099
+ };
2100
+ });
2101
+ }
2102
+ queueResult(command) {
2103
+ const { commandId, identification } = command;
2104
+ this.logger.trace(`[${commandId}] Queuing a new result from provider: ${identification.providerId}`);
2105
+ const providerQueue = this.queues[identification.providerId];
2106
+ if (!providerQueue) {
2107
+ 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`);
2108
+ return;
2109
+ }
2110
+ const result = this.isLegacy ? this.translateLegacySearchItem(command.result) : command.result;
2111
+ providerQueue.pendingResults.push(result);
2112
+ clearTimeout(providerQueue.flushTimer);
2113
+ if (providerQueue.pendingResults.length === 10) {
2114
+ this.logger.trace(`[${commandId}] Reached the limit in the queue buffer, flushing to the client.`);
2115
+ this.flushProviderQueue(identification.providerId, commandId);
2116
+ return;
2117
+ }
2118
+ this.logger.trace(`[${commandId}] The limit in the queue buffer is not reached yet, setting a flush timer.`);
2119
+ providerQueue.flushTimer = setTimeout(() => {
2120
+ this.logger.trace(`[${commandId}] Reached the time limit in the queue buffer, flushing to the client.`);
2121
+ this.flushProviderQueue(identification.providerId, commandId);
2122
+ }, FLUSH_TIMEOUT_MS);
2123
+ }
2124
+ cancel(commandId) {
2125
+ this.logger.trace(`[${commandId}] Cancelling queue ${this.queryId}.`);
2126
+ Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2127
+ this.queues = {};
2128
+ this.logger.trace(`[${commandId}] Queue ${this.queryId} publisher cancelled.`);
2129
+ }
2130
+ async markProviderDone(providerId, commandId) {
2131
+ this.logger.trace(`[${commandId}] Marking provider ${providerId} as done.`);
2132
+ const providerQueue = this.queues[providerId];
2133
+ if (!providerQueue) {
2134
+ 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`);
2135
+ return;
2136
+ }
2137
+ clearTimeout(providerQueue.flushTimer);
2138
+ await this.flushProviderQueue(providerId, commandId);
2139
+ delete this.queues[providerId];
2140
+ this.logger.trace(`[${commandId}] Provider ${providerId} marked as done.`);
2141
+ }
2142
+ markProviderError(command) {
2143
+ const providerQueue = this.queues[command.identification.providerId];
2144
+ if (!providerQueue) {
2145
+ 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`);
2146
+ return;
2147
+ }
2148
+ this.glueController.sendClientErrorMessage(command.error, this.clientInstanceId, this.queryId, providerQueue.providerData.myProviderData)
2149
+ .catch((error) => this.logger.warn(`[${command.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2150
+ }
2151
+ cleanPublisher(commandId) {
2152
+ Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2153
+ this.queues = {};
2154
+ this.glueController.sendClientQueueCompleted(this.clientInstanceId, this.queryId)
2155
+ .catch((error) => this.logger.warn(`[${commandId}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2156
+ }
2157
+ async flushProviderQueue(providerId, commandId) {
2158
+ await this.sequelizer.enqueue(async () => {
2159
+ const providerQueue = this.queues[providerId];
2160
+ if (!providerQueue) {
2161
+ 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`);
2162
+ return;
2163
+ }
2164
+ if (!providerQueue.pendingResults.length) {
2165
+ this.logger.info(`[${commandId}] This provider does not have any pending results to flush.`);
2166
+ return;
2167
+ }
2168
+ const resultBatch = {
2169
+ results: providerQueue.pendingResults,
2170
+ provider: providerQueue.providerData.myProviderData
2171
+ };
2172
+ providerQueue.pendingResults = [];
2173
+ try {
2174
+ await this.glueController.sendClientResultsBatch(resultBatch, this.clientInstanceId, this.queryId);
2175
+ }
2176
+ catch (error) {
2177
+ this.logger.warn(`[${commandId}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(error)}`);
2178
+ }
2179
+ });
2180
+ }
2181
+ translateLegacySearchItem(searchResult) {
2182
+ return {
2183
+ type: searchResult.type.name,
2184
+ category: searchResult.type.displayName,
2185
+ id: searchResult.id,
2186
+ displayName: searchResult.displayName,
2187
+ description: searchResult.description,
2188
+ iconURL: searchResult.iconURL,
2189
+ action: searchResult.action
2190
+ };
2191
+ }
2252
2192
  }
2253
2193
 
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
- }
2194
+ class ModelFactory {
2195
+ glueController;
2196
+ glue;
2197
+ flushSequelizer;
2198
+ constructor(glueController, glue, flushSequelizer) {
2199
+ this.glueController = glueController;
2200
+ this.glue = glue;
2201
+ this.flushSequelizer = flushSequelizer;
2202
+ }
2203
+ buildProviderModel(providerData, controller) {
2204
+ return new ProviderModel(providerData, controller, this.glue.logger.subLogger(`search.provider.model.${providerData.name}`));
2205
+ }
2206
+ buildProviderQueryModel(queryConfig, identification, controller) {
2207
+ return new ProviderQueryModel(queryConfig, controller, this.glue.logger.subLogger(`search.provider.${identification.providerId}.query.${identification.queryId}`), identification);
2208
+ }
2209
+ buildPublisher(clientInstanceId, queryId, isLegacy) {
2210
+ return new QueryResultsPublisher(this.flushSequelizer, this.glueController, this.glue.logger.subLogger(`search.results.publisher.${queryId}`), clientInstanceId, queryId, isLegacy);
2211
+ }
2212
+ buildClientQueryModel(masterQueryId, controller) {
2213
+ return new ClientQuery(controller, this.glue.logger.subLogger(`search.provider.model.${masterQueryId}`), masterQueryId);
2214
+ }
2272
2215
  }
2273
2216
 
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
- }
2217
+ class IoC {
2218
+ glue;
2219
+ config;
2220
+ _glueController;
2221
+ _facade;
2222
+ _mainController;
2223
+ _providerController;
2224
+ _clientController;
2225
+ _asyncSequelizer;
2226
+ _flushSequelizer;
2227
+ _limitsTracker;
2228
+ _modelFactory;
2229
+ constructor(glue, config) {
2230
+ this.glue = glue;
2231
+ this.config = config;
2232
+ }
2233
+ get glueController() {
2234
+ if (!this._glueController) {
2235
+ this._glueController = new GlueController(this.glue);
2236
+ }
2237
+ return this._glueController;
2238
+ }
2239
+ get main() {
2240
+ if (!this._mainController) {
2241
+ this._mainController = new MainController(this.glue.logger.subLogger("search.main.controller"), this.glueController, this.clientController, this.providerController);
2242
+ }
2243
+ return this._mainController;
2244
+ }
2245
+ get clientController() {
2246
+ if (!this._clientController) {
2247
+ this._clientController = new ClientController(this.glue.logger.subLogger("search.client.controller"), this.glueController, this.modelFactory);
2248
+ }
2249
+ return this._clientController;
2250
+ }
2251
+ get providerController() {
2252
+ if (!this._providerController) {
2253
+ this._providerController = new ProviderController(this.glue.logger.subLogger("search.provider.controller"), this.glueController, this.sequelizer, this.limitsTracker, this.modelFactory);
2254
+ }
2255
+ return this._providerController;
2256
+ }
2257
+ get facade() {
2258
+ if (!this._facade) {
2259
+ this._facade = new SearchFacade(this.main);
2260
+ }
2261
+ return this._facade;
2262
+ }
2263
+ get sequelizer() {
2264
+ if (!this._asyncSequelizer) {
2265
+ this._asyncSequelizer = new AsyncSequelizer(SEQUELIZER_INTERVAL_MS);
2266
+ }
2267
+ return this._asyncSequelizer;
2268
+ }
2269
+ get flushSequelizer() {
2270
+ if (!this._flushSequelizer) {
2271
+ this._flushSequelizer = new AsyncSequelizer(FLUSH_SEQUELIZER_INTERVAL_MS);
2272
+ }
2273
+ return this._flushSequelizer;
2274
+ }
2275
+ get limitsTracker() {
2276
+ if (!this._limitsTracker) {
2277
+ this._limitsTracker = new LimitsTracker();
2278
+ }
2279
+ return this._limitsTracker;
2280
+ }
2281
+ get modelFactory() {
2282
+ if (!this._modelFactory) {
2283
+ this._modelFactory = new ModelFactory(this.glueController, this.glue, this.flushSequelizer);
2284
+ }
2285
+ return this._modelFactory;
2286
+ }
2333
2287
  }
2334
2288
 
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;
2289
+ const factoryFunction = async (io, config) => {
2290
+ const ioc = new IoC(io, config);
2291
+ io.search = ioc.facade.exposeApi();
2292
+ };
2293
+ if (typeof window !== "undefined") {
2294
+ window.IOSearch = factoryFunction;
2341
2295
  }
2342
2296
 
2343
2297
  export { factoryFunction as default };