-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlookup.ts
366 lines (327 loc) · 12.4 KB
/
lookup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import { detectLanguageAndScript } from '@/harmonizer/language_script.ts';
import { mergeRelease } from '@/harmonizer/merge.ts';
import { defaultProviderPreferences, providers } from '@/providers/mod.ts';
import { FeatureQuality } from '@/providers/features.ts';
import { LookupError, ProviderError } from '@/utils/errors.ts';
import { ensureValidGTIN, isEqualGTIN, uniqueGtinSet } from '@/utils/gtin.ts';
import { isDefined, isNotError } from '@/utils/predicate.ts';
import { ResponseError } from 'snap-storage';
import { getLogger } from 'std/log/get_logger.ts';
import { LogLevels } from 'std/log/levels.ts';
import { zipObject } from 'utils/object/zipObject.js';
import type {
GTIN,
HarmonyRelease,
ProviderMessage,
ProviderName,
ProviderNameAndId,
ProviderPreferences,
ProviderReleaseErrorMap,
ReleaseOptions,
} from '@/harmonizer/types.ts';
import type { Logger } from 'std/log/logger.ts';
/** Parameters which can be used to lookup a release. */
export type ReleaseLookupParameters = {
/** GTIN of the release. */
gtin: GTIN | undefined;
/** Pairs of provider names (internal or display names) and provider IDs. */
providerIds: ProviderNameAndId[];
/** Provider URLs. */
urls: URL[];
};
/**
* Performs a combined lookup of a release with each of the given lookup parameters.
*
* Supports GTIN (has to be unique), provider IDs and URLs as input.
* Each provider can only be used once, IDs will be used before URLs and GTIN.
*
* All remaining supported providers will be used for GTIN lookups, unless only specific providers have been requested.
* GTIN lookups are only possible if the GTIN is available of course.
*/
export class CombinedReleaseLookup {
constructor(lookup: Partial<ReleaseLookupParameters>, options?: ReleaseOptions) {
this.log = getLogger('harmony.lookup');
// Create a deep copy, we don't want to manipulate the caller's options later on.
this.options = { ...options };
this.gtinLookupProviders = new Set(options?.providers ?? providers.internalNames);
if (lookup.providerIds?.length) {
for (const [providerName, id] of lookup.providerIds) {
this.queueLookupById(providerName, id);
}
}
if (lookup.urls?.length) {
for (const url of lookup.urls) {
this.queueLookupByUrl(url);
}
}
if (this.gtinLookupProviders.size && lookup.gtin) {
this.queueLookupsByGTIN(lookup.gtin);
}
}
/** Initiates a new lookup by provider ID and adds it to the combined lookup. */
queueLookupById(providerName: string, id: string): boolean {
const provider = providers.findByName(providerName);
if (provider) {
const displayName = provider.name;
if (this.queuedProviderNames.has(displayName)) {
this.messages.push({
type: 'error',
text: `Provider ${displayName} can only be used once per lookup, ignoring ID '${id}'`,
});
return false;
} else {
this.queuedReleases.push(provider.getRelease(id, this.options));
this.queuedProviderNames.add(displayName);
this.gtinLookupProviders.delete(provider.internalName);
return true;
}
} else {
this.messages.push({
type: 'error',
text: `There is no provider with the name "${providerName}"`,
});
return false;
}
}
/** Initiates a new lookup by provider URL and adds it to the combined lookup. */
queueLookupByUrl(url: URL): boolean {
const provider = providers.findByUrl(url);
if (provider) {
const displayName = provider.name;
if (this.queuedProviderNames.has(displayName)) {
this.messages.push({
type: 'error',
text: `Provider ${displayName} can only be used once per lookup, ignoring ${url}`,
});
return false;
} else {
this.queuedReleases.push(provider.getRelease(url, this.options));
this.queuedProviderNames.add(displayName);
this.gtinLookupProviders.delete(provider.internalName);
return true;
}
} else {
this.messages.push({
type: 'error',
text: `No provider supports ${url}`,
});
return false;
}
}
/** Initiates new lookups by GTIN (for the remaining providers) and adds them to the combined lookup. */
queueLookupsByGTIN(gtin: GTIN): boolean {
// If the GTIN is already set, trying to change it is considered an error.
if (this.gtin) {
if (isEqualGTIN(gtin, this.gtin)) return true;
this.messages.push({
type: 'error',
text: `Different GTIN '${gtin}' can not be combined with the current lookup`,
});
return false;
}
try {
ensureValidGTIN(gtin);
} catch (error) {
this.messages.push({
type: 'error',
text: (error as Error).message,
});
return false;
}
this.gtin = gtin.toString();
for (const providerName of this.gtinLookupProviders) {
const provider = providers.findByName(providerName);
if (provider) {
if (provider.getQuality('GTIN lookup') != FeatureQuality.MISSING) {
this.queuedReleases.push(provider.getRelease(['gtin', this.gtin], this.options));
this.queuedProviderNames.add(provider.name);
} else {
this.messages.push({
provider: provider.name,
type: 'warning',
text: 'GTIN lookups are not supported',
});
}
} else {
this.messages.push({
type: 'error',
text: `There is no provider with the name "${providerName}"`,
});
}
}
return true;
}
/** Finalizes all queued lookup requests and returns the provider release mapping. */
async getProviderReleaseMapping(): Promise<ProviderReleaseErrorMap> {
if (!this.queuedReleases.length) {
const lookupErrors = this.messages
.filter((message) => message.type === 'error')
.map((message) => new LookupError(message.text));
switch (lookupErrors.length) {
case 0:
throw new LookupError('No release lookups have been queued');
case 1:
throw lookupErrors[0];
default:
throw new AggregateError(lookupErrors, 'Release lookup failed');
}
}
// Exit early if our cached release map is up to date.
if (this.processedProviders === this.queuedReleases.length) {
return this.cachedReleaseMap;
}
const releaseResults = await Promise.allSettled(this.queuedReleases);
const releasesOrErrors: Array<HarmonyRelease | Error> = await Promise.all(releaseResults.map(async (result) => {
if (result.status === 'fulfilled') {
return result.value;
} else {
const { reason } = result;
if (reason instanceof Error) {
if (reason instanceof LookupError) {
// No need to log a stack trace, these are our own errors.
if (reason instanceof ProviderError) {
this.log.info(`${reason.providerName}: ${reason.message}`);
} else {
this.log.info(reason.message);
}
} else if (reason instanceof ResponseError) {
const { status, statusText } = reason.response;
this.log.warn(`${reason.message} (${status} ${statusText})`);
if (this.log.level <= LogLevels.DEBUG) {
const responseText = await reason.response.text();
if (responseText.length) {
this.log.debug(responseText.trim());
}
}
} else {
// Unexpected errors are more critical.
this.log.error(reason);
}
return reason;
} else {
return Error(reason);
}
}
}));
this.cachedReleaseMap = zipObject(Array.from(this.queuedProviderNames), releasesOrErrors);
this.processedProviders = this.queuedReleases.length;
return this.cachedReleaseMap;
}
/** Ensures that all requested providers have been looked up and returns the provider release mapping. */
async getCompleteProviderReleaseMapping(): Promise<ProviderReleaseErrorMap> {
await this.getProviderReleaseMapping();
// Exit early if our cached release map is up to date.
if (this.completelyProcessedProviders === this.queuedReleases.length) {
return this.cachedReleaseMap;
}
// We might still have providers left for which we have not done a lookup because the GTIN was not available.
if (this.gtinLookupProviders.size && !this.gtin) {
const releases = Object.values(this.cachedReleaseMap).filter(isNotError);
// Use already used or available regions of the completed release lookups instead of the standard preferences.
const usedRegions = releases.map((release) => release.info.providers[0].lookup.region).filter(isDefined);
if (usedRegions.length) {
this.options.regions = new Set(usedRegions);
} else {
const availableRegions = new Set(releases.flatMap((release) => release.availableIn ?? []));
// Remove special "worldwide" region, it is not usable for lookups.
availableRegions.delete('XW');
if (availableRegions.size) {
// Remove all preferred regions where the release is unlikely to be available.
if (this.options.regions?.size) {
const availablePreferredRegions = new Set(this.options.regions);
for (const region of availablePreferredRegions) {
if (!availableRegions.has(region)) {
availablePreferredRegions.delete(region);
}
}
this.options.regions = availablePreferredRegions;
}
// Use available regions if no (available) preferred regions remain.
if (!this.options.regions?.size) {
this.options.regions = availableRegions;
}
}
}
// Obtain GTIN candidates from the already completed release lookups.
const gtinCandidates = releases.map((release) => release.gtin).filter(isDefined);
const uniqueGtinValues = uniqueGtinSet(gtinCandidates);
switch (uniqueGtinValues.size) {
case 1:
// Queue new lookups and get the updated release mapping.
if (this.queueLookupsByGTIN(gtinCandidates[0])) {
this.cachedReleaseMap = await this.getProviderReleaseMapping();
}
break;
case 0: {
const skippedProviders = Array.from(this.gtinLookupProviders)
.map((internalName) => providers.toDisplayName(internalName) ?? internalName);
this.messages.push({
type: 'info',
text: `GTIN is unknown, lookups for the following providers were skipped: ${skippedProviders.join(', ')}`,
});
break;
}
default:
this.messages.push({
type: 'error',
text: `Providers have returned multiple different GTIN: ${gtinCandidates.join(', ')}`,
});
}
}
this.completelyProcessedProviders = this.queuedReleases.length;
return this.cachedReleaseMap;
}
/** Ensures that all requested providers have been looked up and returns the combined release. */
async getMergedRelease(providerPreferences?: ProviderPreferences | ProviderName[]): Promise<HarmonyRelease> {
const releaseMap = await this.getCompleteProviderReleaseMapping();
const release = mergeRelease(releaseMap, providerPreferences);
// Prepend error and warning messages of the combined lookup.
release.info.messages.unshift(...this.messages);
detectLanguageAndScript(release);
return release;
}
private log: Logger;
private options: ReleaseOptions;
private gtin: string | undefined;
/** Internal names of providers which will be used for GTIN lookups. */
private gtinLookupProviders: Set<string>;
private queuedReleases: Promise<HarmonyRelease>[] = [];
/** Display names of all queued providers. */
private queuedProviderNames = new Set<string>();
/** Caches the latest provider release mapping. */
private cachedReleaseMap: ProviderReleaseErrorMap = {};
/** Number of already processed providers for the cached release map. */
private processedProviders = 0;
/** Number of already completely processed providers for the cached release map. */
private completelyProcessedProviders = 0;
/** Warnings and errors from the combined lookup process. */
messages: ProviderMessage[] = [];
}
/**
* Looks up the given URL with the first matching provider.
*/
export function getReleaseByUrl(url: URL, options?: ReleaseOptions): Promise<HarmonyRelease> {
const matchingProvider = providers.findByUrl(url);
if (!matchingProvider) {
throw new LookupError(`No provider supports ${url}`);
}
return matchingProvider.getRelease(url, options);
}
/**
* Looks up the given GTIN with each provider and merges the resulting releases into one.
*/
export function getMergedReleaseByGTIN(
gtin: GTIN,
options?: ReleaseOptions,
): Promise<HarmonyRelease> {
const lookup = new CombinedReleaseLookup({ gtin }, options);
return lookup.getMergedRelease(defaultProviderPreferences);
}
/**
* Looks up the given URL with the first matching provider.
* Then tries to find that release on other providers (by GTIN) and merges the resulting data.
*/
export function getMergedReleaseByUrl(url: URL, options?: ReleaseOptions): Promise<HarmonyRelease> {
const lookup = new CombinedReleaseLookup({ urls: [url] }, options);
return lookup.getMergedRelease(defaultProviderPreferences);
}