Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 76x 76x 76x 2x 1x 1x 1x 10x 10x 10x 10x 11x 11x 11x 11x 3x 3x 3x 3x 3x 10x 11x 1x 1x 1x 1x 1x 1x 11x 10x 10x 1x 1x 1x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 4x 1x 1x 3x 3x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 114x 114x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 5x 5x 2x 2x 5x 1x 1x 1x 13x 13x 6x 6x 6x 6x 6x 6x 13x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 5x 1x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x | import { search } from '@/../config.json';
import {
supplierDisplayNames,
supplierShippingMeta,
supplierShipsTo,
} from '@/constants/supplierMeta';
import { HttpStatus } from '@/constants/httpStatus';
import { recordException } from '@/helpers/errorBuffer';
import { resolveIdentifierNames } from '@/helpers/pubchem';
import { filterRestrictedProduct } from '@/helpers/purchaseRestriction';
import {
looksLikeSmiles,
parseStructurePrefix,
resolveSmiles,
type ResolvedStructure,
} from '@/helpers/smiles';
import { mapDefined, sleep } from '@/helpers/utils';
import { Logger } from '@/utils/Logger';
import { detectTermType } from '@/utils/search-query/detectTermType';
import { extractAllPositiveTerms } from '@/utils/search-query/extractPositiveTerms';
import { parseSearchQuery } from '@/utils/search-query/parseSearchQuery';
import type { ParsedSearchQuery } from '@/utils/search-query/types';
import { incrementParseError } from '@/utils/SupplierStatsStore';
import { Queue } from 'async-await-queue';
import * as suppliers from '.';
import { SupplierBase } from './SupplierBase';
import {
getErrorMessage,
isAbortError,
isExpectedAbort,
isRateLimited,
} from '@/helpers/exceptions';
/** Constructor signature for supplier classes used by the factory */
type SupplierConstructor<P extends Product> = new (
query: string,
limit: number,
controller: AbortController,
) => SupplierBase<unknown, P>;
/**
* Options for constructing a {@link SupplierFactory}. `controller` is required; every other field
* is optional and falls back to a sensible default. Most fields mirror the corresponding
* `userSettings` value.
* @source
*/
export interface SupplierFactoryOptions {
/** Fetch controller (can be used to terminate the query). */
controller: AbortController;
/** Maximum number of results per supplier. Defaults to `search.defaultResultsLimitPerSupplier`. */
limit?: number;
/** Suppliers to query; empty (the default) queries all. */
suppliers?: Array<SupplierClassName>;
/** Whether to read from / write to the supplier caches. Defaults to true. */
caching?: boolean;
/** Fuzz-scorer name (from `FUZZ_SCORERS`) overriding each supplier's default. */
fuzzScorerOverride?: string;
/** When true, suppliers returning zero results skip writing a cache entry. Defaults to false. */
doNotCacheEmptyResults?: boolean;
/** Max age (minutes) of a query cache entry before eviction on read; 0 disables. Defaults to 0. */
cacheTtlMinutes?: number;
/** HTTP statuses that prevent a product-detail fetch from being cached. Defaults to [429]. */
noCacheStatusCodes?: number[];
/** Override (seconds) for each supplier's search-time budget. Omit to keep per-supplier defaults. */
supplierSearchTimeBudgetSec?: number;
/** When true, suppliers skip fuzzball scoring and show raw/boolean-only results. Defaults to false. */
fuzzyFilteringDisabled?: boolean;
/** User's ISO 3166-1 alpha-2 location; enables the shipping/restriction filters below. */
location?: string;
/** When true (with a `location`), drop suppliers that don't ship to the user. Defaults to false. */
excludeNonShippingSuppliers?: boolean;
/** When true, hide products the user can't buy (region/buyer restrictions). Defaults to false. */
hideRestrictedProducts?: boolean;
/** Supplier class names to exclude from the search entirely, regardless of `suppliers`. Defaults to []. */
disabledSuppliers?: Array<SupplierClassName>;
}
/**
* Factory class for querying multiple chemical suppliers simultaneously.
* This class provides a unified interface to search across multiple supplier implementations.
*
* @category Suppliers
* @example
* ```typescript
* // Create a factory to search all suppliers
* const factory = new SupplierFactory("sodium chloride", { controller: new AbortController() });
*
* // Create a factory to search specific suppliers
* const factory = new SupplierFactory("sodium chloride", {
* controller: new AbortController(),
* suppliers: ["SupplierCarolina", "SupplierLaballey"],
* });
*
* // Iterate over results from all selected suppliers
* for await (const product of factory) {
* console.log(product.supplier, product.title, product.price);
* }
* ```
* @source
*/
export class SupplierFactory<P extends Product> {
// Term being queried
private query: string;
// Abort controller for fetch control
private controller: AbortController;
// List of supplier class names to include in query results. Held as plain strings
// because it's compared against the runtime string keys of the suppliers barrel; the
// public option is typed SupplierClassName[] for authoring convenience.
private suppliers: Array<string>;
// Mirrors userSettings.disabledSuppliers. Supplier class names the user has turned
// off; excluded from every search before the include-list is even consulted, so the
// deny-list wins even when `suppliers` is empty (which otherwise means "query all").
// Held as plain strings for the same reason as `suppliers` above.
private disabledSuppliers: Array<string>;
// Maximum number of results for each supplier
private limit: number = search.defaultResultsLimitPerSupplier;
// Whether supplier caches (query + product detail) should be read from and
// written to for this search. Mirrors userSettings.caching so a user who has
// disabled caching gets fresh results every time.
private caching: boolean;
// Mirrors userSettings.doNotCacheEmptyResults. Forwarded to each supplier's
// SupplierCache so an empty-result query for a previously out-of-stock
// supplier doesn't get cached and mask future restocks.
private doNotCacheEmptyResults: boolean;
// Mirrors userSettings.cacheTtlMinutes. Forwarded to each supplier's
// SupplierCache so query cache entries older than this are evicted on read.
// 0 disables TTL expiration.
private cacheTtlMinutes: number;
// Mirrors userSettings.noCacheStatusCodes. Forwarded to each supplier so a
// product-detail fetch that hit one of these HTTP statuses (default [429])
// isn't cached, letting a later search retry it.
private noCacheStatusCodes: number[];
// Optional global fuzz-scorer override from userSettings.fuzzScorerOverride.
// When set, applied to every supplier instance before execute() runs so the
// user's Advanced-settings choice wins over each supplier class's default.
private fuzzScorerOverride?: string;
// Optional global max-search-time override (seconds) from userSettings.supplierSearchTimeBudgetSec.
// When set, applied to every supplier instance so the user's Advanced-settings value
// overrides each supplier class's default search-time budget.
private supplierSearchTimeBudgetSec?: number;
// Parsed advanced-search query, derived once from `query` and shared with every
// supplier instance so they all see the same AST.
private parsedQuery: ParsedSearchQuery;
// Mirrors userSettings.fuzzyFilteringDisabled. When true, suppliers skip
// fuzzball scoring and rely on the boolean predicate (or raw results) instead.
private fuzzyFilteringDisabled: boolean;
// User's location (ISO 3166-1 alpha-2 country code) from userSettings.location.
// Used together with excludeNonShippingSuppliers to drop suppliers that don't
// ship to the user. Empty/undefined disables shipping filtering.
private location?: string;
// Mirrors userSettings.excludeNonShippingSuppliers. When true (and a location
// is set), suppliers that don't ship to the user's location are filtered out
// before their queries run. Defaults to false so existing callers are unaffected.
private excludeNonShippingSuppliers: boolean;
// Mirrors userSettings.hideRestrictedProducts. When true (the default), each
// yielded product is run through filterRestrictedProduct: options the user can't
// buy (region/buyer/etc.) are pruned, and fully-restricted products are dropped.
private hideRestrictedProducts: boolean;
// SMILES/structure query terms resolved to chemical identifiers, keyed by the
// raw term. Resolved lazily once per search (see resolveStructuresOnce) and
// shared with every supplier instance so none of them re-hit the network.
private resolvedStructures?: ReadonlyMap<string, ResolvedStructure>;
// Logger instance
private logger: Logger;
// Set true by executeAll/executeAllStream when there were candidate suppliers
// but shipping filtering removed every one of them (i.e. no selected supplier
// ships to the user's location). Lets the UI explain an empty result set.
public shippingExcludedAll: boolean = false;
// Per-supplier exceptions from the most recent run (aborts excluded). Also
// aggregated into an AggregateError recorded to the shared error buffer.
public executionErrors: SupplierExecutionError<P>[] = [];
// Number of suppliers the most recent run actually queried, i.e. what survived
// the disabled/include lists, shipping filtering, and host-permission checks.
// Set by executeAll/executeAllStream once that set is known.
public suppliersQueried: number = 0;
// How many of those suppliers have finished (successfully, with an error, or
// aborted). Mirrors the stream's internal done counter so a caller can read a
// partial value the moment an aborted search stops draining.
public suppliersCompleted: number = 0;
/**
* Factory class for querying all suppliers.
*
* @param query - Value to query for
* @param options - Factory configuration; see {@link SupplierFactoryOptions}. `controller` is
* required, everything else is optional with sensible defaults.
* @source
*/
constructor(query: string, options: SupplierFactoryOptions) {
const {
controller,
limit = search.defaultResultsLimitPerSupplier,
suppliers = [],
caching = true,
fuzzScorerOverride,
doNotCacheEmptyResults = false,
cacheTtlMinutes = 0,
noCacheStatusCodes = [HttpStatus.TOO_MANY_REQUESTS],
supplierSearchTimeBudgetSec,
fuzzyFilteringDisabled = false,
location,
excludeNonShippingSuppliers = false,
hideRestrictedProducts = false,
disabledSuppliers = [],
} = options;
this.logger = new Logger('SupplierFactory');
this.logger.setContext({ ...Logger.getContext(), search_query: query });
this.logger.debug('SupplierFactory initialized', {
query,
limit,
controller,
suppliers,
caching,
fuzzScorerOverride,
doNotCacheEmptyResults,
cacheTtlMinutes,
noCacheStatusCodes,
supplierSearchTimeBudgetSec,
fuzzyFilteringDisabled,
location,
excludeNonShippingSuppliers,
hideRestrictedProducts,
disabledSuppliers,
});
this.query = query;
this.limit = limit;
this.controller = controller;
this.suppliers = suppliers;
this.caching = caching;
this.fuzzScorerOverride = fuzzScorerOverride;
this.doNotCacheEmptyResults = doNotCacheEmptyResults;
this.cacheTtlMinutes = cacheTtlMinutes;
this.noCacheStatusCodes = noCacheStatusCodes;
this.supplierSearchTimeBudgetSec = supplierSearchTimeBudgetSec;
this.fuzzyFilteringDisabled = fuzzyFilteringDisabled;
this.location = location;
this.excludeNonShippingSuppliers = excludeNonShippingSuppliers;
this.hideRestrictedProducts = hideRestrictedProducts;
this.disabledSuppliers = disabledSuppliers;
this.parsedQuery = parseSearchQuery(query);
}
/**
* Get the list of available supplier module names.
* Use these names when specifying which suppliers to query in the constructor.
*
* @returns Array of supplier class names that can be queried
* @example
* ```typescript
* const suppliers = SupplierFactory.supplierList();
* // Returns: ["SupplierCarolina", "SupplierLaballey", "SupplierBioFuranChem", ...]
*
* // Use these names to create a targeted factory
* const factory = new SupplierFactory("acid", { controller, suppliers });
* ```
* @source
*/
public static supplierList(): Array<SupplierClassName> {
return Object.keys(suppliers) as unknown as Array<SupplierClassName>;
}
/**
* Type guard narrowing an arbitrary string to a known {@link SupplierClassName}. Use at
* runtime boundaries (persisted values, UI inputs) where a plain string needs to be
* confirmed as one of the barrel-exported supplier names before it's stored or searched.
* @param value - Candidate string to test.
* @returns True (and narrows `value` to `SupplierClassName`) when it names an exported supplier.
* @example
* ```typescript
* ["SupplierCarolina", "Nope"].filter(SupplierFactory.isSupplierClassName);
* // => ["SupplierCarolina"]
* ```
* @source
*/
public static isSupplierClassName(value: string): value is SupplierClassName {
return SupplierFactory.supplierList().some((name) => name === value);
}
/**
* Get a map of supplier module names to their display names. Thin wrapper over
* {@link supplierDisplayNames}, which reads the dependency-free `SUPPLIER_META`
* registry — callers that only need names should use that directly rather than
* reaching through the factory.
*
* @returns Record mapping supplier class names to their supplierName property
* @source
*/
public static supplierDisplayNames(): Record<string, string> {
return supplierDisplayNames();
}
/**
* Get a map of supplier class names to whether they ship to the given location.
* Thin wrapper over {@link supplierShipsTo}, which applies the same `shipsTo`/scope
* heuristic used at search time (both go through `helpers/shipping.shipsToCountry`)
* against the dependency-free `SUPPLIER_META` registry. Lets the UI grey out
* suppliers that won't ship to the user.
*
* @param location - The user's location as an ISO 3166-1 alpha-2 country code.
* @returns Record mapping supplier class names to a ships-to boolean.
* @example
* ```typescript
* const map = SupplierFactory.supplierShipsTo("US");
* // { SupplierCarolina: true, SupplierWarchem: false, ... }
* ```
* @source
*/
public static supplierShipsTo(location: CountryCode): Record<string, boolean> {
return supplierShipsTo(location);
}
/**
* Get a map of supplier class names to their home country and shipping scope,
* the same fields stamped onto products. Lets the UI (and the search) reason
* about which suppliers are compatible with the drawer's shipping/country
* filters without querying them. Thin wrapper over {@link supplierShippingMeta},
* which reads the dependency-free `SUPPLIER_META` registry.
* @returns Record mapping supplier class names to `{ country, shipping }`.
* @example
* ```typescript
* const meta = SupplierFactory.supplierShippingMeta();
* // { SupplierCarolina: { country: "US", shipping: "domestic" }, ... }
* ```
* @source
*/
public static supplierShippingMeta(): Record<
string,
{ country: CountryCode; shipping: ShippingRange }
> {
return supplierShippingMeta();
}
/**
* Get a map of supplier class names to their required host origins, read from
* each supplier's static `requiredHosts` (derived from its static baseURL/apiURL)
* — no instances are created.
* @returns Record mapping supplier class names to their requiredHosts arrays
* @source
*/
public static supplierRequiredHosts(): Record<string, string[]> {
return Object.fromEntries(
// eslint-disable-next-line @typescript-eslint/naming-convention
Object.entries(suppliers).map(([key, SupplierClass]) => [
key,
(SupplierClass as unknown as { requiredHosts: string[] }).requiredHosts,
]),
);
}
/**
* Filters supplier instances to only those whose required host permissions
* are already granted. Uses chrome.permissions.contains() which is a passive
* check — it does not prompt the user. Permission granting should be handled
* separately in a UI flow (e.g., a settings page).
*
* @param instances - Array of supplier instances to check
* @returns Filtered array of suppliers with granted permissions
* @source
*/
private async filterByPermissions<P extends Product>(
instances: SupplierBase<unknown, P>[],
): Promise<SupplierBase<unknown, P>[]> {
const results = await Promise.all(
instances.map(async (instance) => {
if (instance.requiredHosts.length === 0) return { instance, granted: true };
try {
const granted = await chrome.permissions.contains({ origins: instance.requiredHosts });
if (!granted) {
this.logger.warn('Permission check failed for supplier', {
supplier: instance.supplierName,
requiredHosts: instance.requiredHosts,
});
}
return { instance, granted };
} catch (error) {
this.logger.error(`Permission check failed for supplier: ${getErrorMessage(error)}`, {
supplier: instance.supplierName,
error: error,
});
return { instance, granted: false };
}
}),
);
return results.filter((r) => r.granted).map((r) => r.instance);
}
/**
* Filters supplier instances to only those that ship to the user's location.
* A no-op (returns all instances) when shipping filtering is disabled or no
* location is set. Synchronous — unlike {@link filterByPermissions}, it only
* reads in-memory supplier metadata via {@link SupplierBase.shipsToCountry}.
*
* @param instances - Array of supplier instances to check.
* @returns The subset of instances that ship to the user's location.
* @source
*/
private filterByShipping<P extends Product>(
instances: SupplierBase<unknown, P>[],
): SupplierBase<unknown, P>[] {
if (!this.excludeNonShippingSuppliers || !this.location) {
return instances;
}
const location = this.location as CountryCode;
return instances.filter((instance) => instance.shipsToCountry(location));
}
/**
* Applies per-product purchase-restriction filtering to a single result. A no-op
* (returns the product unchanged) when `hideRestrictedProducts` is off; otherwise
* delegates to {@link filterRestrictedProduct}, which prunes options the user can't
* buy and returns undefined when the whole product is unbuyable.
*
* @param product - The product to filter.
* @returns The product (possibly with restricted variants pruned), or undefined to drop it.
* @source
*/
private applyRestrictionFilter<Q extends Product>(product: Q): Q | undefined {
if (this.hideRestrictedProducts !== true) {
return product;
}
return filterRestrictedProduct(product, this.location);
}
/**
* Resolves every chemical-identifier term in the query — SMILES/structure, CAS
* number, or molecular formula — to its chemical identifiers (name, CAS,
* InChIKey) exactly once, memoizing the result on the factory so it is shared
* with every supplier instead of each supplier re-hitting the network.
*
* Only positive (non-negated) identifier leaf terms are resolved: a structure
* (via {@link looksLikeSmiles} or an explicit `smiles:`/`inchikey:` prefix) via
* {@link resolveSmiles}, or a CAS/formula (via {@link detectTermType}) via
* {@link resolveIdentifierNames}. Plain name queries resolve nothing and make no
* network calls. Each unique term is resolved once; failures are logged and
* skipped so a dead resolver never blocks the search. Every supplier then swaps
* an identifier it can't search for the resolved name (see
* `SupplierBase.effectiveQuery`).
*
* @returns A map of raw search term → resolved structure (empty when none apply).
* @example
* ```typescript
* // query "CCO" -> Map { "CCO" => { name: "ethanol", cas: ["64-17-5"], ... } }
* // query "Na6O18P6" -> Map { "Na6O18P6" => { name: "Hexasodium hexametaphosphate", ... } }
* await factory.resolveStructuresOnce();
* ```
* @source
*/
private async resolveStructuresOnce(): Promise<ReadonlyMap<string, ResolvedStructure>> {
if (this.resolvedStructures) {
return this.resolvedStructures;
}
const resolved = new Map<string, ResolvedStructure>();
for (const term of extractAllPositiveTerms(this.parsedQuery.ast)) {
if (resolved.has(term)) {
continue;
}
const { mode, value } = parseStructurePrefix(term);
try {
if (mode === 'smiles' || (mode === 'auto' && looksLikeSmiles(value))) {
const structure = await resolveSmiles(value);
if (structure) {
resolved.set(term, structure);
}
continue;
}
const termType = detectTermType(value);
if (termType === 'cas' || termType === 'formula') {
const identifier = await resolveIdentifierNames(value, termType);
if (identifier) {
resolved.set(term, {
name: identifier.names[0],
names: identifier.names,
cas: identifier.cas,
source: termType === 'cas' ? 'pubchem-cas' : 'pubchem-formula',
});
}
}
} catch (error) {
this.logger.warn(`Failed to resolve identifier term; skipping: ${getErrorMessage(error)}`, {
term,
error,
});
}
}
this.resolvedStructures = resolved;
return resolved;
}
/**
* Executes the execute() method on all selected suppliers in parallel using async-await-queue.
* Results are collected and flattened into a single array.
*
* @param concurrency - Maximum number of suppliers to process in parallel (default: 3)
* @returns Promise resolving to an array of all products from all suppliers
* @example
* ```typescript
* const factory = new SupplierFactory("acetone", { limit: 5, controller: new AbortController() });
* const allProducts = await factory.executeAll(3); // 3 suppliers in parallel
* console.log(allProducts);
* ```
* @source
*/
public async executeAll(concurrency: number = 3): Promise<P[]> {
// Resolve any SMILES/structure terms once up front so every instance shares them.
await this.resolveStructuresOnce();
// 1. Instantiate supplier classes
const supplierInstances: SupplierBase<unknown, P>[] = mapDefined(
Object.entries(suppliers),
([supplierClassName, supplierClass]) => {
if (this.disabledSuppliers.includes(supplierClassName)) return;
if (!(this.suppliers.length === 0 || this.suppliers.includes(supplierClassName))) return;
this.logger.debug('Initializing supplier class', { supplierClassName });
// Trusted static supplier classes; the union of concrete constructors
// isn't structurally assignable to the generic SupplierConstructor<P>.
const ConcreteSupplierClass = supplierClass as unknown as SupplierConstructor<P>;
const instance = new ConcreteSupplierClass(this.query, this.limit, this.controller);
instance.initCache(
this.caching,
this.doNotCacheEmptyResults,
this.cacheTtlMinutes,
this.noCacheStatusCodes,
);
instance.setFuzzScorerOverride(this.fuzzScorerOverride);
instance.setSupplierSearchTimeBudgetSec(this.supplierSearchTimeBudgetSec);
instance.setParsedQuery(this.parsedQuery);
instance.setFuzzyFilteringDisabled(this.fuzzyFilteringDisabled);
instance.setResolvedStructures(this.resolvedStructures);
return instance;
},
);
// 2. Drop suppliers that don't ship to the user's location, then keep only
// those with granted host permissions.
const shippableInstances = this.filterByShipping(supplierInstances);
this.shippingExcludedAll = supplierInstances.length > 0 && shippableInstances.length === 0;
const permittedInstances = await this.filterByPermissions(shippableInstances);
this.suppliersQueried = permittedInstances.length;
this.suppliersCompleted = 0;
// 3. Use async-await-queue for parallel execution
const queue = new Queue(concurrency, 100);
const allResults: P[] = [];
const errors: SupplierExecutionError<P>[] = [];
const tasks = permittedInstances.map((supplier) =>
queue.run(async () => {
this.logger.trace('Starting supplier', { supplier: supplier.supplierName });
try {
for await (const product of supplier.execute()) {
const filtered = this.applyRestrictionFilter(product);
if (filtered !== undefined) {
allResults.push(filtered);
}
}
} catch (e) {
this.recordSupplierFailure(e, supplier);
if (!isAbortError(e)) errors.push({ error: e, supplier });
} finally {
this.suppliersCompleted++;
}
}),
);
await Promise.all(tasks);
// Aggregate any per-supplier failures into the shared error buffer.
this.reportExecutionErrors(errors);
return allResults;
}
/**
* Streams products from all selected suppliers as soon as each supplier's execute() resolves.
* Uses async-await-queue for concurrency control and yields products as they are available.
*
* @param concurrency - Maximum number of suppliers to process in parallel (default: 3)
* @returns AsyncGenerator yielding products from all suppliers as soon as they are ready
* @example
* ```typescript
* for await (const product of factory.executeAllStream(3)) {
* console.log(product);
* }
* ```
* @source
*/
public async *executeAllStream(concurrency: number = 3): AsyncGenerator<P, void, undefined> {
// Resolve any SMILES/structure terms once up front so every instance shares them.
await this.resolveStructuresOnce();
const supplierInstances: SupplierBase<unknown, P>[] = mapDefined(
Object.entries(suppliers),
([supplierClassName, supplierClass]) => {
if (this.disabledSuppliers.includes(supplierClassName)) return;
if (!(this.suppliers.length === 0 || this.suppliers.includes(supplierClassName))) return;
this.logger.debug('Initializing supplier class', { supplierClassName });
// Trusted static supplier classes; the union of concrete constructors
// isn't structurally assignable to the generic SupplierConstructor<P>.
const ConcreteSupplierClass = supplierClass as unknown as SupplierConstructor<P>;
const instance = new ConcreteSupplierClass(this.query, this.limit, this.controller);
instance.initCache(
this.caching,
this.doNotCacheEmptyResults,
this.cacheTtlMinutes,
this.noCacheStatusCodes,
);
instance.setFuzzScorerOverride(this.fuzzScorerOverride);
instance.setSupplierSearchTimeBudgetSec(this.supplierSearchTimeBudgetSec);
instance.setParsedQuery(this.parsedQuery);
instance.setFuzzyFilteringDisabled(this.fuzzyFilteringDisabled);
instance.setResolvedStructures(this.resolvedStructures);
return instance;
},
);
// Drop suppliers that don't ship to the user's location, then keep only
// those with granted host permissions.
const shippableInstances = this.filterByShipping(supplierInstances);
this.shippingExcludedAll = supplierInstances.length > 0 && shippableInstances.length === 0;
const permittedInstances = await this.filterByPermissions(shippableInstances);
this.suppliersQueried = permittedInstances.length;
this.suppliersCompleted = 0;
const queue = new Queue(concurrency, 100);
const channel: P[] = [];
const errors: SupplierExecutionError<P>[] = [];
let doneCount = 0;
permittedInstances.forEach((supplier) => {
queue.run(async () => {
this.logger.trace('Starting supplier', { supplier: supplier.supplierName });
try {
const iterator = supplier.execute();
for await (const product of iterator) {
const filtered = this.applyRestrictionFilter(product);
if (filtered !== undefined) {
channel.push(filtered);
}
}
} catch (e) {
this.recordSupplierFailure(e, supplier);
if (!isAbortError(e)) errors.push({ error: e, supplier });
} finally {
doneCount++;
this.suppliersCompleted = doneCount;
}
});
});
// Yield results as they come in, until all suppliers are done and the channel is empty
while (doneCount < permittedInstances.length || channel.length > 0) {
if (channel.length > 0) {
yield channel.shift()!;
} else {
await sleep(25);
}
}
// All suppliers have settled; partial results were already streamed, so record
// (rather than throw) any failures as one AggregateError for bug reports.
this.reportExecutionErrors(errors);
}
/**
* Records a supplier's failed `execute()`: logs it and counts it as a parse error in the supplier
* stats. A deliberate stop (the user pressing Stop, the time budget elapsing) is logged but not
* counted, since it isn't a fault of the supplier.
* @param error - The value the supplier threw.
* @param supplier - The supplier that threw it.
* @example
* ```ts
* this.recordSupplierFailure(new TypeError('bad'), supplier); // logged and counted
* this.recordSupplierFailure('user_aborted', supplier); // logged only
* ```
* @source
*/
private recordSupplierFailure(error: unknown, supplier: SupplierBase<unknown, P>): void {
this.logSupplierFailure(error, supplier);
if (!isExpectedAbort(error)) {
incrementParseError(supplier.supplierName);
}
}
/**
* Logs why a supplier's `execute()` threw. A deliberate stop (the user pressing Stop) is
* expected and logged at `debug`; anything else is a real failure and logged at `error`.
* Only the supplier's name is logged, not the whole instance.
* @param error - The value the supplier threw.
* @param supplier - The supplier that threw it.
* @example
* ```ts
* this.logSupplierFailure('user_aborted', supplier); // debug: 'Supplier stopped by abort'
* this.logSupplierFailure(new TypeError('bad'), supplier); // error: 'Error executing supplier'
* ```
* @source
*/
private logSupplierFailure(error: unknown, supplier: SupplierBase<unknown, P>): void {
const supplierName = supplier.supplierName;
if (isExpectedAbort(error)) {
this.logger.debug(`Supplier stopped by abort: ${getErrorMessage(error)}`, {
error,
supplier: supplierName,
});
return;
}
if (isRateLimited(error)) {
this.logger.warn(`Supplier is rate limiting: ${getErrorMessage(error)}`, {
error,
supplier: supplierName,
});
return;
}
this.logger.error(`Error executing supplier: ${getErrorMessage(error)}`, {
error,
supplier: supplierName,
});
}
/**
* Records the per-supplier exceptions from a search run as a single
* {@link AggregateError} in the shared error buffer, so a later bug report can
* include them, and stashes them on {@link executionErrors}. Aborts are
* excluded by the callers. A no-op when nothing failed.
* @param errors - The per-supplier execution errors collected during the run.
* @returns Nothing.
* @example
* ```ts
* this.reportExecutionErrors([{ error: new Error("boom"), supplier }]);
* ```
* @source
*/
private reportExecutionErrors(errors: SupplierExecutionError<P>[]): void {
this.executionErrors = errors;
if (errors.length === 0) return;
const names = errors.map((e) => e.supplier.supplierName).join(', ');
const aggregate = new AggregateError(
errors.map((e) => e.error),
`${errors.length} supplier(s) failed during search: ${names}`,
);
void recordException(aggregate, 'search');
}
}
|