@metamask-previews/assets-controller 9.0.2-preview-2a256aff2 → 9.0.2-preview-8633f7f2a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/AssetsController.cjs +6 -15
- package/dist/AssetsController.cjs.map +1 -1
- package/dist/AssetsController.d.cts.map +1 -1
- package/dist/AssetsController.d.mts.map +1 -1
- package/dist/AssetsController.mjs +6 -15
- package/dist/AssetsController.mjs.map +1 -1
- package/dist/data-sources/PriceDataSource.cjs +64 -13
- package/dist/data-sources/PriceDataSource.cjs.map +1 -1
- package/dist/data-sources/PriceDataSource.d.cts +13 -0
- package/dist/data-sources/PriceDataSource.d.cts.map +1 -1
- package/dist/data-sources/PriceDataSource.d.mts +13 -0
- package/dist/data-sources/PriceDataSource.d.mts.map +1 -1
- package/dist/data-sources/PriceDataSource.mjs +64 -13
- package/dist/data-sources/PriceDataSource.mjs.map +1 -1
- package/dist/utils/dedupingBatchFetcher.cjs +157 -0
- package/dist/utils/dedupingBatchFetcher.cjs.map +1 -0
- package/dist/utils/dedupingBatchFetcher.d.cts +65 -0
- package/dist/utils/dedupingBatchFetcher.d.cts.map +1 -0
- package/dist/utils/dedupingBatchFetcher.d.mts +65 -0
- package/dist/utils/dedupingBatchFetcher.d.mts.map +1 -0
- package/dist/utils/dedupingBatchFetcher.mjs +153 -0
- package/dist/utils/dedupingBatchFetcher.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PriceDataSource.mjs","sourceRoot":"","sources":["../../src/data-sources/PriceDataSource.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,OAAO,EAAE,iBAAiB,EAAE,+BAA+B;AAC3D,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,sBAAkB;AAC9D,OAAO,EAAE,YAAY,EAAE,qBAAiB;AAS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,CAAC;oBACH,CAAC;oBACD,QAAQ,CAAC,GAAG,CAAC,OAAwB,CAAC,CAAC;gBACzC,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC;AAtRe,8BAAc,GAAG,eAAe,AAAlB,CAAmB","sourcesContent":["import type {\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\nimport { parseCaipAssetType } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from '../logger';\nimport { forDataTypes } from '../types';\nimport type {\n Caip19AssetId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n AssetsControllerStateInternal,\n} from '../types';\nimport { fetchWithTimeout } from '../utils';\nimport type { SubscriptionRequest } from './AbstractDataSource';\nimport { reduceInBatchesSerially } from './evm-rpc-services';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\n\n/** Maximum number of asset IDs per Price API request. */\nconst PRICE_API_BATCH_SIZE = 50;\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\n/** Optional configuration for PriceDataSource. */\nexport type PriceDataSourceConfig = {\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\n /**\n * Timeout in ms for a single Price API call (default: 15000). When it fires,\n * the batch rejects so the caller can proceed without prices.\n */\n fetchTimeoutMs?: number;\n};\n\nexport type PriceDataSourceOptions = PriceDataSourceConfig & {\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Function returning the currently-active ISO 4217 currency code */\n getSelectedCurrency: () => SupportedCurrency;\n};\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\n/**\n * Asset reference patterns that should NOT be sent to the Price API.\n * These are internal resource tracking values without market prices.\n */\nconst NON_PRICEABLE_ASSET_PATTERNS = [\n // Synthetic slip44 staking-position assets: the Price API only knows about\n // pure numeric coin-type references (e.g. slip44:195). Any suffix after the\n // number (e.g. slip44:195-ready-for-withdrawal, slip44:195-in-lock-period,\n // slip44:195-staking-rewards, slip44:195-staked-for-…) is a MetaMask-internal\n // synthetic asset that has no market price.\n /\\/slip44:\\d+-/u,\n // Tron non-price resource assets (bandwidth, energy)\n /\\/slip44:bandwidth$/u,\n /\\/slip44:energy$/u,\n /\\/slip44:maximum-bandwidth$/u,\n /\\/slip44:maximum-energy$/u,\n];\n\n/**\n * Check if an asset ID represents a priceable asset.\n * Filters out internal resource tracking values that don't have market prices.\n *\n * @param assetId - The CAIP-19 asset ID to check.\n * @returns True if the asset has market price data.\n */\nfunction isPriceableAsset(assetId: Caip19AssetId): boolean {\n return !NON_PRICEABLE_ASSET_PATTERNS.some((pattern) => pattern.test(assetId));\n}\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<\n FungibleAssetPrice,\n 'lastUpdated' | 'assetPriceType'\n>;\n\n/**\n * Type guard to check if market data has a valid price\n *\n * @param data - The data to check.\n * @returns True if data is valid SpotPriceMarketData.\n */\nfunction isValidMarketData(data: unknown): data is SpotPriceMarketData {\n return (\n typeof data === 'object' &&\n data !== null &&\n typeof (data as Record<string, unknown>).price === 'number'\n );\n}\n\n// ============================================================================\n// PRICE DATA SOURCE\n// ============================================================================\n\n/**\n * PriceDataSource fetches asset prices from the Price API.\n *\n * This data source:\n * - Fetches prices from Price API v3 spot-prices endpoint\n * - Supports one-time fetch and subscription-based polling\n * - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices\n *\n * Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.\n */\nexport class PriceDataSource {\n static readonly controllerName = CONTROLLER_NAME;\n\n getName(): string {\n return PriceDataSource.controllerName;\n }\n\n readonly #getSelectedCurrency: () => SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\n\n readonly #fetchTimeoutMs: number;\n\n /** Active subscriptions by ID */\n readonly #activeSubscriptions: Map<\n string,\n {\n cleanup: () => void;\n request: DataRequest;\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n getAssetsState?: () => AssetsControllerStateInternal;\n }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#getSelectedCurrency = options.getSelectedCurrency;\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Extracts the response from context\n * 2. Fetches prices for detected assets (assets without metadata)\n * 3. Enriches the response with fetched prices\n * 4. Calls next() at the end to continue the middleware chain\n *\n * Note: This middleware ONLY fetches prices for detected assets.\n * For fetching prices for all assets, use the subscription mechanism\n * which polls prices for all assets in the balance state.\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n // Extract response from context\n const { response, request } = ctx;\n\n // Only fetch prices for detected assets (assets without metadata)\n // The subscription handles fetching prices for all existing assets\n if (!response.detectedAssets && !request.assetsForPriceUpdate?.length) {\n return next(ctx);\n }\n\n const assetIds = new Set<Caip19AssetId>();\n for (const detectedAccountAssets of Object.values(\n response.detectedAssets ?? {},\n )) {\n for (const assetId of detectedAccountAssets) {\n assetIds.add(assetId);\n }\n }\n\n for (const assetId of request.assetsForPriceUpdate ?? []) {\n assetIds.add(assetId);\n }\n\n if (assetIds.size === 0) {\n return next(ctx);\n }\n\n // Filter to only priceable assets\n const priceableAssetIds = [...assetIds].filter(isPriceableAsset);\n\n if (priceableAssetIds.length === 0) {\n return next(ctx);\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(priceableAssetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices via middleware', { error });\n }\n\n // Call next() at the end to continue the middleware chain\n return next(ctx);\n });\n }\n\n // ============================================================================\n // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices for a single batch of asset IDs (must be ≤ PRICE_API_BATCH_SIZE).\n *\n * @param assetIds - Array of CAIP-19 asset IDs (already within batch size limit).\n * @param selectedCurrency - The user's selected display currency.\n * @returns Raw spot-prices responses for the selected currency and USD.\n */\n async #fetchSpotPricesBatch(\n assetIds: string[],\n selectedCurrency: SupportedCurrency,\n ): Promise<{\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n }> {\n if (selectedCurrency === 'usd') {\n const selectedCurrencyPrices = await fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n );\n return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };\n }\n\n const [selectedCurrencyPrices, usdPrices] = await Promise.all([\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: 'usd',\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n ]);\n\n return { selectedCurrencyPrices, usdPrices };\n }\n\n /**\n * Fetch spot prices for all provided asset IDs, splitting into batches of\n * PRICE_API_BATCH_SIZE to respect API limits.\n *\n * @param assetIds - Array of CAIP-19 asset IDs\n * @returns Spot prices response\n */\n async #fetchSpotPrices(\n assetIds: string[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const selectedCurrency = this.#getSelectedCurrency();\n\n type BatchResult = {\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n };\n\n const batchResults = await reduceInBatchesSerially<string, BatchResult[]>({\n values: assetIds,\n batchSize: PRICE_API_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const result = await this.#fetchSpotPricesBatch(\n batch,\n selectedCurrency,\n );\n return [...(workingResult as BatchResult[]), result];\n },\n initialResult: [],\n });\n\n const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};\n\n for (const { selectedCurrencyPrices, usdPrices } of batchResults) {\n for (const [assetId, marketData] of Object.entries(\n selectedCurrencyPrices,\n )) {\n const usdMarketData = usdPrices[assetId];\n\n if (\n !isValidMarketData(marketData) ||\n !isValidMarketData(usdMarketData)\n ) {\n continue;\n }\n\n const caipAssetId = assetId as Caip19AssetId;\n prices[caipAssetId] = {\n ...marketData,\n assetPriceType: 'fungible',\n usdPrice: usdMarketData.price,\n lastUpdated: Date.now(),\n };\n }\n }\n\n return prices;\n }\n\n /**\n * Get unique asset IDs from the assetsBalance state.\n * Filters by accounts and chains from the request.\n *\n * @param request - Data request with accounts and chainIds filters.\n * @param getAssetsState - State access; when omitted, returns [].\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Caip19AssetId[] {\n if (!getAssetsState) {\n return [];\n }\n try {\n const state = getAssetsState();\n const assetIds = new Set<Caip19AssetId>();\n\n const accountIds = request.accountsWithSupportedChains.map(\n (a) => a.account.id,\n );\n const accountFilter =\n accountIds.length > 0 ? new Set(accountIds) : undefined;\n const chainFilter =\n request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;\n\n if (state?.assetsBalance) {\n for (const [accountId, accountBalances] of Object.entries(\n state.assetsBalance,\n )) {\n // Filter by account if specified\n if (accountFilter && !accountFilter.has(accountId)) {\n continue;\n }\n\n for (const assetId of Object.keys(\n accountBalances as Record<string, unknown>,\n )) {\n // Filter by chain if specified; skip malformed asset IDs for this entry only\n if (chainFilter) {\n try {\n const { chainId } = parseCaipAssetType(\n assetId as Caip19AssetId,\n );\n if (!chainFilter.has(chainId)) {\n continue;\n }\n } catch (error) {\n log('Skipping malformed asset ID in balance state', {\n assetId,\n error,\n });\n continue;\n }\n }\n assetIds.add(assetId as Caip19AssetId);\n }\n }\n }\n\n return [...assetIds];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for assets held by the accounts and chains in the request.\n * When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.\n *\n * @param request - The data request specifying accounts and chains.\n * @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).\n * @returns DataResponse containing asset prices.\n */\n async fetch(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Promise<DataResponse> {\n const response: DataResponse = {};\n\n // Get asset IDs from balance state when state access is provided\n const rawAssetIds = this.#getAssetIdsFromBalanceState(\n request,\n getAssetsState,\n );\n\n // Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)\n const assetIds = rawAssetIds.filter(isPriceableAsset);\n\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices([...assetIds]);\n\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices', { error });\n }\n\n return response;\n }\n\n // ============================================================================\n // SUBSCRIBE\n // ============================================================================\n\n /**\n * Subscribe to price updates.\n * Sets up polling that fetches prices for all assets in assetsBalance state.\n *\n * @param subscriptionRequest - The subscription request configuration.\n */\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Handle subscription update - just update the request\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\n return;\n }\n }\n\n // Clean up existing subscription\n await this.unsubscribe(subscriptionId);\n\n const pollInterval = request.updateInterval ?? this.#pollInterval;\n\n // Create poll function - fetches prices using getAssetsState from subscription\n const pollFn = async (): Promise<void> => {\n try {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n // Fetch prices for all assets in balance state (uses subscription's getAssetsState)\n const fetchResponse = await this.fetch(\n subscription.request,\n subscription.getAssetsState,\n );\n\n // Only report if we got prices\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await subscription.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n } catch (error) {\n log('Subscription poll failed', { subscriptionId, error });\n }\n };\n\n // Set up polling\n const timer = setInterval(() => {\n pollFn().catch(console.error);\n }, pollInterval);\n\n // Store subscription (getAssetsState from request for balance-based pricing)\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n getAssetsState: subscriptionRequest.getAssetsState,\n });\n\n // Initial fetch\n await pollFn();\n }\n\n /**\n * Unsubscribe from price updates.\n *\n * @param subscriptionId - The ID of the subscription to cancel.\n */\n async unsubscribe(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (subscription) {\n subscription.cleanup();\n this.#activeSubscriptions.delete(subscriptionId);\n }\n }\n\n /**\n * Destroy the data source and clean up all subscriptions.\n */\n destroy(): void {\n for (const subscription of this.#activeSubscriptions.values()) {\n subscription.cleanup();\n }\n this.#activeSubscriptions.clear();\n }\n}\n"]}
|
|
1
|
+
{"version":3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,QAAQ,CAAC,GAAG,CAAC,OAAwB,CAAC,CAAC;gBACzC,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7D,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC;AArTe,8BAAc,GAAG,eAAe,AAAlB,CAAmB","sourcesContent":["import type {\n SupportedCurrency,\n V3SpotPricesResponse,\n} from '@metamask/core-backend';\nimport { ApiPlatformClient } from '@metamask/core-backend';\nimport { parseCaipAssetType } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from '../logger';\nimport { forDataTypes } from '../types';\nimport type {\n Caip19AssetId,\n DataRequest,\n DataResponse,\n FungibleAssetPrice,\n Middleware,\n AssetsControllerStateInternal,\n} from '../types';\nimport { fetchWithTimeout } from '../utils';\nimport { DedupingBatchFetcher } from '../utils/dedupingBatchFetcher';\nimport type { SubscriptionRequest } from './AbstractDataSource';\nimport { reduceInBatchesSerially } from './evm-rpc-services';\n\n// ============================================================================\n// CONSTANTS\n// ============================================================================\n\nconst CONTROLLER_NAME = 'PriceDataSource';\nconst DEFAULT_POLL_INTERVAL = 60_000; // 1 minute for price updates\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\n\n/**\n * Fraction of the poll interval used to cap the freshness TTL. Kept strictly\n * below 1 so an asset fetched on one poll is reliably stale by the next poll;\n * the margin absorbs network latency and timer jitter (see the cap in\n * `subscribe`).\n */\nconst FRESHNESS_TTL_POLL_RATIO = 0.9;\n\n/** Maximum number of asset IDs per Price API request. */\nconst PRICE_API_BATCH_SIZE = 50;\n\nconst log = createModuleLogger(projectLogger, CONTROLLER_NAME);\n\n// ============================================================================\n// OPTIONS\n// ============================================================================\n\n/** Optional configuration for PriceDataSource. */\nexport type PriceDataSourceConfig = {\n /** Polling interval in ms (default: 60000) */\n pollInterval?: number;\n /**\n * Timeout in ms for a single Price API call (default: 15000). When it fires,\n * the batch rejects so the caller can proceed without prices.\n */\n fetchTimeoutMs?: number;\n /**\n * Minimum age (ms) before a price is considered stale and re-fetched.\n * Assets fetched more recently than this are skipped to avoid redundant\n * API calls from overlapping middleware / subscription / manual triggers.\n * Defaults to pollInterval (60 000 ms).\n */\n priceFreshnessTtlMs?: number;\n};\n\nexport type PriceDataSourceOptions = PriceDataSourceConfig & {\n /** ApiPlatformClient for API calls with caching */\n queryApiClient: ApiPlatformClient;\n /** Function returning the currently-active ISO 4217 currency code */\n getSelectedCurrency: () => SupportedCurrency;\n};\n\n// ============================================================================\n// HELPER FUNCTIONS\n// ============================================================================\n\n/**\n * Asset reference patterns that should NOT be sent to the Price API.\n * These are internal resource tracking values without market prices.\n */\nconst NON_PRICEABLE_ASSET_PATTERNS = [\n // Synthetic slip44 staking-position assets: the Price API only knows about\n // pure numeric coin-type references (e.g. slip44:195). Any suffix after the\n // number (e.g. slip44:195-ready-for-withdrawal, slip44:195-in-lock-period,\n // slip44:195-staking-rewards, slip44:195-staked-for-…) is a MetaMask-internal\n // synthetic asset that has no market price.\n /\\/slip44:\\d+-/u,\n // Tron non-price resource assets (bandwidth, energy)\n /\\/slip44:bandwidth$/u,\n /\\/slip44:energy$/u,\n /\\/slip44:maximum-bandwidth$/u,\n /\\/slip44:maximum-energy$/u,\n];\n\n/**\n * Check if an asset ID represents a priceable asset.\n * Filters out internal resource tracking values that don't have market prices.\n *\n * @param assetId - The CAIP-19 asset ID to check.\n * @returns True if the asset has market price data.\n */\nfunction isPriceableAsset(assetId: Caip19AssetId): boolean {\n return !NON_PRICEABLE_ASSET_PATTERNS.some((pattern) => pattern.test(assetId));\n}\n\n/** Market data item from spot prices response (same as FungibleAssetPrice without lastUpdated) */\ntype SpotPriceMarketData = Omit<\n FungibleAssetPrice,\n 'lastUpdated' | 'assetPriceType'\n>;\n\n/**\n * Type guard to check if market data has a valid price\n *\n * @param data - The data to check.\n * @returns True if data is valid SpotPriceMarketData.\n */\nfunction isValidMarketData(data: unknown): data is SpotPriceMarketData {\n return (\n typeof data === 'object' &&\n data !== null &&\n typeof (data as Record<string, unknown>).price === 'number'\n );\n}\n\n// ============================================================================\n// PRICE DATA SOURCE\n// ============================================================================\n\n/**\n * PriceDataSource fetches asset prices from the Price API.\n *\n * This data source:\n * - Fetches prices from Price API v3 spot-prices endpoint\n * - Supports one-time fetch and subscription-based polling\n * - In subscribe mode, uses getAssetsState from SubscriptionRequest to read assetsBalance and fetch prices\n *\n * Usage: Create with queryApiClient; subscribe() requires getAssetsState in the request for balance-based pricing.\n */\nexport class PriceDataSource {\n static readonly controllerName = CONTROLLER_NAME;\n\n getName(): string {\n return PriceDataSource.controllerName;\n }\n\n readonly #getSelectedCurrency: () => SupportedCurrency;\n\n readonly #pollInterval: number;\n\n /** ApiPlatformClient for cached API calls */\n readonly #apiClient: ApiPlatformClient;\n\n readonly #fetchTimeoutMs: number;\n\n /**\n * Deduplicates price fetches by asset ID: skips assets fetched within the\n * freshness TTL and joins concurrent in-flight fetches for the same asset so\n * overlapping triggers (middleware + subscription poll) don't issue duplicate\n * API requests.\n */\n readonly #deduper: DedupingBatchFetcher<Caip19AssetId, FungibleAssetPrice>;\n\n /** Active subscriptions by ID */\n readonly #activeSubscriptions: Map<\n string,\n {\n cleanup: () => void;\n request: DataRequest;\n onAssetsUpdate: (response: DataResponse) => void | Promise<void>;\n getAssetsState?: () => AssetsControllerStateInternal;\n }\n > = new Map();\n\n constructor(options: PriceDataSourceOptions) {\n this.#getSelectedCurrency = options.getSelectedCurrency;\n this.#pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;\n this.#apiClient = options.queryApiClient;\n this.#fetchTimeoutMs = options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n this.#deduper = new DedupingBatchFetcher({\n fetchBatch: (\n assetIds,\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> =>\n this.#executeBatchFetch(assetIds),\n freshnessTtlMs: options.priceFreshnessTtlMs ?? this.#pollInterval,\n });\n }\n\n // ============================================================================\n // MIDDLEWARE\n // ============================================================================\n\n /**\n * Get the middleware for enriching responses with price data.\n *\n * This middleware:\n * 1. Extracts the response from context\n * 2. Fetches prices for detected assets (assets without metadata)\n * 3. Enriches the response with fetched prices\n * 4. Calls next() at the end to continue the middleware chain\n *\n * Note: This middleware ONLY fetches prices for detected assets.\n * For fetching prices for all assets, use the subscription mechanism\n * which polls prices for all assets in the balance state.\n *\n * @returns The middleware function for the assets pipeline.\n */\n get assetsMiddleware(): Middleware {\n return forDataTypes(['price'], async (ctx, next) => {\n // Extract response from context\n const { response, request } = ctx;\n\n // Only fetch prices for detected assets (assets without metadata)\n // The subscription handles fetching prices for all existing assets\n if (!response.detectedAssets && !request.assetsForPriceUpdate?.length) {\n return next(ctx);\n }\n\n const assetIds = new Set<Caip19AssetId>();\n for (const detectedAccountAssets of Object.values(\n response.detectedAssets ?? {},\n )) {\n for (const assetId of detectedAccountAssets) {\n assetIds.add(assetId);\n }\n }\n\n for (const assetId of request.assetsForPriceUpdate ?? []) {\n assetIds.add(assetId);\n }\n\n if (assetIds.size === 0) {\n return next(ctx);\n }\n\n // Filter to only priceable assets\n const priceableAssetIds = [...assetIds].filter(isPriceableAsset);\n\n if (priceableAssetIds.length === 0) {\n return next(ctx);\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices(priceableAssetIds);\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices via middleware', { error });\n }\n\n // Call next() at the end to continue the middleware chain\n return next(ctx);\n });\n }\n\n // ============================================================================\n // HELPERS\n // ============================================================================\n\n /**\n * Fetch spot prices for a single batch of asset IDs (must be ≤ PRICE_API_BATCH_SIZE).\n *\n * @param assetIds - Array of CAIP-19 asset IDs (already within batch size limit).\n * @param selectedCurrency - The user's selected display currency.\n * @returns Raw spot-prices responses for the selected currency and USD.\n */\n async #fetchSpotPricesBatch(\n assetIds: string[],\n selectedCurrency: SupportedCurrency,\n ): Promise<{\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n }> {\n if (selectedCurrency === 'usd') {\n const selectedCurrencyPrices = await fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n );\n return { selectedCurrencyPrices, usdPrices: selectedCurrencyPrices };\n }\n\n const [selectedCurrencyPrices, usdPrices] = await Promise.all([\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: selectedCurrency,\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n fetchWithTimeout(\n () =>\n this.#apiClient.prices.fetchV3SpotPrices(assetIds, {\n currency: 'usd',\n includeMarketData: true,\n }),\n this.#fetchTimeoutMs,\n ),\n ]);\n\n return { selectedCurrencyPrices, usdPrices };\n }\n\n /**\n * Execute the actual batched API call for a set of asset IDs and return\n * parsed price results. Used as the `fetchBatch` callback for the deduper,\n * so it does NOT check freshness or inflight state — that is handled by\n * {@link DedupingBatchFetcher}.\n *\n * @param assetIds - Asset IDs to fetch (already filtered/deduplicated).\n * @returns Parsed prices keyed by CAIP-19 asset ID.\n */\n async #executeBatchFetch(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n const selectedCurrency = this.#getSelectedCurrency();\n\n type BatchResult = {\n selectedCurrencyPrices: V3SpotPricesResponse;\n usdPrices: V3SpotPricesResponse;\n };\n\n const batchResults = await reduceInBatchesSerially<string, BatchResult[]>({\n values: assetIds,\n batchSize: PRICE_API_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const result = await this.#fetchSpotPricesBatch(\n batch,\n selectedCurrency,\n );\n return [...(workingResult as BatchResult[]), result];\n },\n initialResult: [],\n });\n\n const fetchedAt = Date.now();\n const prices: Record<Caip19AssetId, FungibleAssetPrice> = {};\n\n for (const { selectedCurrencyPrices, usdPrices } of batchResults) {\n for (const [assetId, marketData] of Object.entries(\n selectedCurrencyPrices,\n )) {\n const usdMarketData = usdPrices[assetId];\n\n if (\n !isValidMarketData(marketData) ||\n !isValidMarketData(usdMarketData)\n ) {\n continue;\n }\n\n prices[assetId as Caip19AssetId] = {\n ...marketData,\n assetPriceType: 'fungible',\n usdPrice: usdMarketData.price,\n lastUpdated: fetchedAt,\n };\n }\n }\n\n return prices;\n }\n\n /**\n * Fetch spot prices for all provided asset IDs, deduplicating via the\n * deduper (freshness TTL + per-asset inflight coalescing).\n *\n * @param assetIds - Array of CAIP-19 asset IDs.\n * @returns Spot prices response (only contains entries for assets that were\n * actually fetched or joined from inflight).\n */\n async #fetchSpotPrices(\n assetIds: Caip19AssetId[],\n ): Promise<Record<Caip19AssetId, FungibleAssetPrice>> {\n return this.#deduper.fetch(assetIds);\n }\n\n /**\n * Get unique asset IDs from the assetsBalance state.\n * Filters by accounts and chains from the request.\n *\n * @param request - Data request with accounts and chainIds filters.\n * @param getAssetsState - State access; when omitted, returns [].\n * @returns Array of CAIP-19 asset IDs from balance state.\n */\n #getAssetIdsFromBalanceState(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Caip19AssetId[] {\n if (!getAssetsState) {\n return [];\n }\n try {\n const state = getAssetsState();\n const assetIds = new Set<Caip19AssetId>();\n\n const accountIds = request.accountsWithSupportedChains.map(\n (a) => a.account.id,\n );\n const accountFilter =\n accountIds.length > 0 ? new Set(accountIds) : undefined;\n const chainFilter =\n request.chainIds.length > 0 ? new Set(request.chainIds) : undefined;\n\n if (state?.assetsBalance) {\n for (const [accountId, accountBalances] of Object.entries(\n state.assetsBalance,\n )) {\n // Filter by account if specified\n if (accountFilter && !accountFilter.has(accountId)) {\n continue;\n }\n\n for (const assetId of Object.keys(\n accountBalances as Record<string, unknown>,\n )) {\n // Filter by chain if specified; skip malformed asset IDs for this entry only\n if (chainFilter) {\n try {\n const { chainId } = parseCaipAssetType(\n assetId as Caip19AssetId,\n );\n if (!chainFilter.has(chainId)) {\n continue;\n }\n } catch (error) {\n log('Skipping malformed asset ID in balance state', {\n assetId,\n error,\n });\n continue;\n }\n }\n assetIds.add(assetId as Caip19AssetId);\n }\n }\n }\n\n return [...assetIds];\n } catch (error) {\n log('Failed to get asset IDs from balance state', { error });\n return [];\n }\n }\n\n // ============================================================================\n // FETCH\n // ============================================================================\n\n /**\n * Fetch prices for assets held by the accounts and chains in the request.\n * When getAssetsState is provided, gets asset IDs from balance state; otherwise returns empty.\n *\n * @param request - The data request specifying accounts and chains.\n * @param getAssetsState - Optional state access (e.g. from SubscriptionRequest).\n * @returns DataResponse containing asset prices.\n */\n async fetch(\n request: DataRequest,\n getAssetsState?: () => AssetsControllerStateInternal,\n ): Promise<DataResponse> {\n const response: DataResponse = {};\n\n // Get asset IDs from balance state when state access is provided\n const rawAssetIds = this.#getAssetIdsFromBalanceState(\n request,\n getAssetsState,\n );\n\n // Filter out non-priceable assets (e.g., Tron bandwidth/energy resources)\n const assetIds = rawAssetIds.filter(isPriceableAsset);\n\n if (assetIds.length === 0) {\n return response;\n }\n\n try {\n const spotPrices = await this.#fetchSpotPrices([...assetIds]);\n\n response.assetsPrice = {\n ...(response.assetsPrice ?? {}),\n ...spotPrices,\n };\n } catch (error) {\n log('Failed to fetch prices', { error });\n }\n\n return response;\n }\n\n // ============================================================================\n // SUBSCRIBE\n // ============================================================================\n\n /**\n * Subscribe to price updates.\n * Sets up polling that fetches prices for all assets in assetsBalance state.\n *\n * @param subscriptionRequest - The subscription request configuration.\n */\n async subscribe(subscriptionRequest: SubscriptionRequest): Promise<void> {\n const { request, subscriptionId, isUpdate } = subscriptionRequest;\n\n // Handle subscription update - just update the request\n if (isUpdate) {\n const existing = this.#activeSubscriptions.get(subscriptionId);\n if (existing) {\n existing.request = request;\n return;\n }\n }\n\n // Clean up existing subscription\n await this.unsubscribe(subscriptionId);\n\n const pollInterval = request.updateInterval ?? this.#pollInterval;\n\n // Cap the freshness TTL strictly below the effective poll interval.\n // `fetchedAt` is stamped when a fetch completes (slightly after the tick\n // that triggered it), so a TTL equal to the poll interval would leave the\n // asset still \"fresh\" at the next tick, making the subscription re-fetch\n // only every other poll. The margin also absorbs network latency / jitter.\n this.#deduper.freshnessTtlMs = Math.min(\n this.#deduper.freshnessTtlMs,\n Math.floor(pollInterval * FRESHNESS_TTL_POLL_RATIO),\n );\n\n // Create poll function - fetches prices using getAssetsState from subscription.\n // The freshness TTL naturally gates re-fetches: assets fetched less than\n // `priceFreshnessTtlMs` ago are skipped, preventing duplicates when middleware\n // or other triggers already fetched the same assets between polls.\n // Concurrent middleware calls will join the inflight promise rather than\n // issuing duplicate requests.\n const pollFn = async (): Promise<void> => {\n try {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (!subscription) {\n return;\n }\n\n const fetchResponse = await this.fetch(\n subscription.request,\n subscription.getAssetsState,\n );\n\n // Only report if we got prices\n if (\n fetchResponse.assetsPrice &&\n Object.keys(fetchResponse.assetsPrice).length > 0\n ) {\n await subscription.onAssetsUpdate({\n ...fetchResponse,\n updateMode: 'merge',\n });\n }\n } catch (error) {\n log('Subscription poll failed', { subscriptionId, error });\n }\n };\n\n // Set up polling\n const timer = setInterval(() => {\n pollFn().catch(console.error);\n }, pollInterval);\n\n // Store subscription (getAssetsState from request for balance-based pricing)\n this.#activeSubscriptions.set(subscriptionId, {\n cleanup: () => {\n clearInterval(timer);\n },\n request,\n onAssetsUpdate: subscriptionRequest.onAssetsUpdate,\n getAssetsState: subscriptionRequest.getAssetsState,\n });\n\n // Initial fetch\n await pollFn();\n }\n\n /**\n * Unsubscribe from price updates.\n *\n * @param subscriptionId - The ID of the subscription to cancel.\n */\n async unsubscribe(subscriptionId: string): Promise<void> {\n const subscription = this.#activeSubscriptions.get(subscriptionId);\n if (subscription) {\n subscription.cleanup();\n this.#activeSubscriptions.delete(subscriptionId);\n }\n }\n\n /**\n * Invalidate the price freshness cache, forcing the next fetch to call the\n * API regardless of TTL. Use when external state changes (e.g. selected\n * currency) require a full refresh.\n */\n invalidatePriceCache(): void {\n this.#deduper.invalidate();\n }\n\n /**\n * Destroy the data source and clean up all subscriptions.\n */\n destroy(): void {\n for (const subscription of this.#activeSubscriptions.values()) {\n subscription.cleanup();\n }\n this.#activeSubscriptions.clear();\n this.#deduper.destroy();\n }\n}\n"]}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _DedupingBatchFetcher_instances, _DedupingBatchFetcher_fetchBatch, _DedupingBatchFetcher_freshnessTtlMs, _DedupingBatchFetcher_fetchedAt, _DedupingBatchFetcher_inflight, _DedupingBatchFetcher_partition, _DedupingBatchFetcher_isFresh, _DedupingBatchFetcher_startBatchFetch, _DedupingBatchFetcher_joinInflight;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.DedupingBatchFetcher = void 0;
|
|
16
|
+
/**
|
|
17
|
+
* Deduplicates batched fetches by key across two dimensions:
|
|
18
|
+
*
|
|
19
|
+
* 1. **Freshness TTL** — keys fetched within `freshnessTtlMs` are skipped
|
|
20
|
+
* entirely. Note the freshness window only starts once a fetch *completes*,
|
|
21
|
+
* so it does not cover requests that are still in flight.
|
|
22
|
+
* 2. **Inflight coalescing** — if a fetch is already in progress for a key,
|
|
23
|
+
* concurrent callers join the existing promise instead of issuing a new
|
|
24
|
+
* request. This covers the request-in-flight window the freshness TTL
|
|
25
|
+
* structurally cannot.
|
|
26
|
+
*
|
|
27
|
+
* Both layers are per-key, so a call for a partially-overlapping set of keys
|
|
28
|
+
* reuses the fresh/inflight keys and only fetches the genuinely-missing ones.
|
|
29
|
+
*
|
|
30
|
+
* The fetch is batched: all stale, not-inflight keys from a single `fetch()`
|
|
31
|
+
* call are passed to `fetchBatch` together, then split into per-key results so
|
|
32
|
+
* each key can be joined independently.
|
|
33
|
+
*/
|
|
34
|
+
class DedupingBatchFetcher {
|
|
35
|
+
constructor(options) {
|
|
36
|
+
_DedupingBatchFetcher_instances.add(this);
|
|
37
|
+
_DedupingBatchFetcher_fetchBatch.set(this, void 0);
|
|
38
|
+
_DedupingBatchFetcher_freshnessTtlMs.set(this, void 0);
|
|
39
|
+
/** Tracks the last successful fetch time per key (freshness gating). */
|
|
40
|
+
_DedupingBatchFetcher_fetchedAt.set(this, new Map());
|
|
41
|
+
/**
|
|
42
|
+
* Per-key inflight fetch promises. Each resolves to the value, or `undefined`
|
|
43
|
+
* if the batch failed or returned no data for that key.
|
|
44
|
+
*/
|
|
45
|
+
_DedupingBatchFetcher_inflight.set(this, new Map());
|
|
46
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_fetchBatch, options.fetchBatch, "f");
|
|
47
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_freshnessTtlMs, options.freshnessTtlMs, "f");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Minimum age (ms) before a key is re-fetched.
|
|
51
|
+
*
|
|
52
|
+
* @returns The current freshness TTL in milliseconds.
|
|
53
|
+
*/
|
|
54
|
+
get freshnessTtlMs() {
|
|
55
|
+
return __classPrivateFieldGet(this, _DedupingBatchFetcher_freshnessTtlMs, "f");
|
|
56
|
+
}
|
|
57
|
+
set freshnessTtlMs(ms) {
|
|
58
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_freshnessTtlMs, ms, "f");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Fetch values for the given keys, deduplicating against fresh and inflight
|
|
62
|
+
* fetches.
|
|
63
|
+
*
|
|
64
|
+
* @param keys - The keys to fetch.
|
|
65
|
+
* @returns Values keyed by key. Only contains entries for keys that were
|
|
66
|
+
* actually fetched (or joined from inflight) and had a value.
|
|
67
|
+
*/
|
|
68
|
+
async fetch(keys) {
|
|
69
|
+
const { staleKeys, inflightKeys } = __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_partition).call(this, keys);
|
|
70
|
+
if (staleKeys.length === 0 && inflightKeys.length === 0) {
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
// Start a fetch for stale keys and join any fetches already in progress.
|
|
74
|
+
const batchPromise = staleKeys.length > 0 ? __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_startBatchFetch).call(this, staleKeys) : undefined;
|
|
75
|
+
const values = await __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_joinInflight).call(this, inflightKeys);
|
|
76
|
+
if (batchPromise) {
|
|
77
|
+
Object.assign(values, await batchPromise);
|
|
78
|
+
}
|
|
79
|
+
return values;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Clear the freshness cache, forcing the next fetch to re-request every key
|
|
83
|
+
* regardless of TTL. Does not affect inflight fetches.
|
|
84
|
+
*/
|
|
85
|
+
invalidate() {
|
|
86
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").clear();
|
|
87
|
+
}
|
|
88
|
+
/** Clear all freshness and inflight state. */
|
|
89
|
+
destroy() {
|
|
90
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").clear();
|
|
91
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").clear();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
exports.DedupingBatchFetcher = DedupingBatchFetcher;
|
|
95
|
+
_DedupingBatchFetcher_fetchBatch = new WeakMap(), _DedupingBatchFetcher_freshnessTtlMs = new WeakMap(), _DedupingBatchFetcher_fetchedAt = new WeakMap(), _DedupingBatchFetcher_inflight = new WeakMap(), _DedupingBatchFetcher_instances = new WeakSet(), _DedupingBatchFetcher_partition = function _DedupingBatchFetcher_partition(keys) {
|
|
96
|
+
const now = Date.now();
|
|
97
|
+
const staleKeys = [];
|
|
98
|
+
const inflightKeys = [];
|
|
99
|
+
for (const key of keys) {
|
|
100
|
+
if (__classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_isFresh).call(this, key, now)) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").has(key)) {
|
|
104
|
+
inflightKeys.push(key);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
staleKeys.push(key);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { staleKeys, inflightKeys };
|
|
111
|
+
}, _DedupingBatchFetcher_isFresh = function _DedupingBatchFetcher_isFresh(key, now) {
|
|
112
|
+
const fetchedAt = __classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").get(key);
|
|
113
|
+
return fetchedAt !== undefined && now - fetchedAt < __classPrivateFieldGet(this, _DedupingBatchFetcher_freshnessTtlMs, "f");
|
|
114
|
+
}, _DedupingBatchFetcher_startBatchFetch = function _DedupingBatchFetcher_startBatchFetch(staleKeys) {
|
|
115
|
+
const batchPromise = __classPrivateFieldGet(this, _DedupingBatchFetcher_fetchBatch, "f").call(this, staleKeys).then((values) => {
|
|
116
|
+
const fetchedAt = Date.now();
|
|
117
|
+
for (const key of staleKeys) {
|
|
118
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").set(key, fetchedAt);
|
|
119
|
+
}
|
|
120
|
+
return values;
|
|
121
|
+
});
|
|
122
|
+
for (const key of staleKeys) {
|
|
123
|
+
const perKey = batchPromise.then((values) => values[key], () => undefined);
|
|
124
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").set(key, perKey);
|
|
125
|
+
}
|
|
126
|
+
// Clean up inflight entries once the batch settles (success or failure).
|
|
127
|
+
// Rejection is already surfaced to the caller via the returned batchPromise.
|
|
128
|
+
batchPromise
|
|
129
|
+
.finally(() => {
|
|
130
|
+
for (const key of staleKeys) {
|
|
131
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").delete(key);
|
|
132
|
+
}
|
|
133
|
+
})
|
|
134
|
+
.catch(() => undefined);
|
|
135
|
+
return batchPromise;
|
|
136
|
+
}, _DedupingBatchFetcher_joinInflight =
|
|
137
|
+
/**
|
|
138
|
+
* Join the inflight fetches for the given keys and collect their values. Keys
|
|
139
|
+
* whose inflight fetch produced no value are omitted.
|
|
140
|
+
*
|
|
141
|
+
* @param inflightKeys - Keys whose fetches are already in progress.
|
|
142
|
+
* @returns Values keyed by key.
|
|
143
|
+
*/
|
|
144
|
+
async function _DedupingBatchFetcher_joinInflight(inflightKeys) {
|
|
145
|
+
const values = {};
|
|
146
|
+
const results = await Promise.all(inflightKeys.map(async (key) => {
|
|
147
|
+
const value = await __classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").get(key);
|
|
148
|
+
return [key, value];
|
|
149
|
+
}));
|
|
150
|
+
for (const [key, value] of results) {
|
|
151
|
+
if (value !== undefined) {
|
|
152
|
+
values[key] = value;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return values;
|
|
156
|
+
};
|
|
157
|
+
//# sourceMappingURL=dedupingBatchFetcher.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dedupingBatchFetcher.cjs","sourceRoot":"","sources":["../../src/utils/dedupingBatchFetcher.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,oBAAoB;IAc/B,YAAY,OAAgD;;QAbnD,mDAAsC;QAE/C,uDAAwB;QAExB,wEAAwE;QAC/D,0CAAa,IAAI,GAAG,EAAe,EAAC;QAE7C;;;WAGG;QACM,yCAAY,IAAI,GAAG,EAAmC,EAAC;QAG9D,uBAAA,IAAI,oCAAe,OAAO,CAAC,UAAU,MAAA,CAAC;QACtC,uBAAA,IAAI,wCAAmB,OAAO,CAAC,cAAc,MAAA,CAAC;IAChD,CAAC;IAED;;;;OAIG;IACH,IAAI,cAAc;QAChB,OAAO,uBAAA,IAAI,4CAAgB,CAAC;IAC9B,CAAC;IAED,IAAI,cAAc,CAAC,EAAU;QAC3B,uBAAA,IAAI,wCAAmB,EAAE,MAAA,CAAC;IAC5B,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,KAAK,CAAC,IAAW;QACrB,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,GAAG,uBAAA,IAAI,wEAAW,MAAf,IAAI,EAAY,IAAI,CAAC,CAAC;QAE1D,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxD,OAAO,EAAwB,CAAC;QAClC,CAAC;QAED,yEAAyE;QACzE,MAAM,YAAY,GAChB,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,uBAAA,IAAI,8EAAiB,MAArB,IAAI,EAAkB,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACtE,MAAM,MAAM,GAAG,MAAM,uBAAA,IA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AC5C,OAAO,CAAC,GAAG,EAAE,KAAK,CAAU,CAAC;IAC/B,CAAC,CAAC,CACH,CAAC;IAEF,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;QACnC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACtB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Executes the underlying batched fetch for a set of keys. Only keys that have\n * a value need to be present in the returned record; keys the source had no\n * data for are simply omitted (they are still marked fresh — see\n * {@link DedupingBatchFetcher.fetch}).\n *\n * @param keys - The keys to fetch (already filtered to stale, not-inflight keys).\n * @returns The fetched values keyed by key.\n */\nexport type BatchFetchFn<Key extends string, Value> = (\n keys: Key[],\n) => Promise<Record<Key, Value>>;\n\nexport type DedupingBatchFetcherOptions<Key extends string, Value> = {\n /** Performs the actual batched fetch for stale, not-inflight keys. */\n fetchBatch: BatchFetchFn<Key, Value>;\n /**\n * Minimum age (ms) before a key is considered stale and re-fetched. Keys\n * fetched more recently than this are skipped entirely.\n */\n freshnessTtlMs: number;\n};\n\n/**\n * Deduplicates batched fetches by key across two dimensions:\n *\n * 1. **Freshness TTL** — keys fetched within `freshnessTtlMs` are skipped\n * entirely. Note the freshness window only starts once a fetch *completes*,\n * so it does not cover requests that are still in flight.\n * 2. **Inflight coalescing** — if a fetch is already in progress for a key,\n * concurrent callers join the existing promise instead of issuing a new\n * request. This covers the request-in-flight window the freshness TTL\n * structurally cannot.\n *\n * Both layers are per-key, so a call for a partially-overlapping set of keys\n * reuses the fresh/inflight keys and only fetches the genuinely-missing ones.\n *\n * The fetch is batched: all stale, not-inflight keys from a single `fetch()`\n * call are passed to `fetchBatch` together, then split into per-key results so\n * each key can be joined independently.\n */\nexport class DedupingBatchFetcher<Key extends string, Value> {\n readonly #fetchBatch: BatchFetchFn<Key, Value>;\n\n #freshnessTtlMs: number;\n\n /** Tracks the last successful fetch time per key (freshness gating). */\n readonly #fetchedAt = new Map<Key, number>();\n\n /**\n * Per-key inflight fetch promises. Each resolves to the value, or `undefined`\n * if the batch failed or returned no data for that key.\n */\n readonly #inflight = new Map<Key, Promise<Value | undefined>>();\n\n constructor(options: DedupingBatchFetcherOptions<Key, Value>) {\n this.#fetchBatch = options.fetchBatch;\n this.#freshnessTtlMs = options.freshnessTtlMs;\n }\n\n /**\n * Minimum age (ms) before a key is re-fetched.\n *\n * @returns The current freshness TTL in milliseconds.\n */\n get freshnessTtlMs(): number {\n return this.#freshnessTtlMs;\n }\n\n set freshnessTtlMs(ms: number) {\n this.#freshnessTtlMs = ms;\n }\n\n /**\n * Fetch values for the given keys, deduplicating against fresh and inflight\n * fetches.\n *\n * @param keys - The keys to fetch.\n * @returns Values keyed by key. Only contains entries for keys that were\n * actually fetched (or joined from inflight) and had a value.\n */\n async fetch(keys: Key[]): Promise<Record<Key, Value>> {\n const { staleKeys, inflightKeys } = this.#partition(keys);\n\n if (staleKeys.length === 0 && inflightKeys.length === 0) {\n return {} as Record<Key, Value>;\n }\n\n // Start a fetch for stale keys and join any fetches already in progress.\n const batchPromise =\n staleKeys.length > 0 ? this.#startBatchFetch(staleKeys) : undefined;\n const values = await this.#joinInflight(inflightKeys);\n\n if (batchPromise) {\n Object.assign(values, await batchPromise);\n }\n\n return values;\n }\n\n /**\n * Clear the freshness cache, forcing the next fetch to re-request every key\n * regardless of TTL. Does not affect inflight fetches.\n */\n invalidate(): void {\n this.#fetchedAt.clear();\n }\n\n /** Clear all freshness and inflight state. */\n destroy(): void {\n this.#fetchedAt.clear();\n this.#inflight.clear();\n }\n\n /**\n * Split keys into those that need a fresh fetch and those already being\n * fetched by another caller. Keys still within the freshness TTL are dropped.\n *\n * @param keys - The keys to classify.\n * @returns `staleKeys` (need fetching) and `inflightKeys` (join existing fetch).\n */\n #partition(keys: Key[]): { staleKeys: Key[]; inflightKeys: Key[] } {\n const now = Date.now();\n const staleKeys: Key[] = [];\n const inflightKeys: Key[] = [];\n\n for (const key of keys) {\n if (this.#isFresh(key, now)) {\n continue;\n }\n if (this.#inflight.has(key)) {\n inflightKeys.push(key);\n } else {\n staleKeys.push(key);\n }\n }\n\n return { staleKeys, inflightKeys };\n }\n\n /**\n * Returns true if the key's last fetch is still within the freshness TTL.\n *\n * @param key - The key to check.\n * @param now - Current timestamp (avoids repeated clock reads).\n * @returns True if the key was fetched within the freshness TTL.\n */\n #isFresh(key: Key, now: number): boolean {\n const fetchedAt = this.#fetchedAt.get(key);\n return fetchedAt !== undefined && now - fetchedAt < this.#freshnessTtlMs;\n }\n\n /**\n * Launch a batch fetch and register a per-key inflight promise for each key\n * so concurrent callers can join. On success, all requested keys are marked\n * fresh — including keys the source returned no value for, since the absence\n * of a value is itself a valid answer that should not be re-asked until the\n * TTL expires. A failed batch leaves keys stale so they are retried.\n *\n * @param staleKeys - Keys to fetch (none of which are already inflight).\n * @returns The batch fetch promise.\n */\n #startBatchFetch(staleKeys: Key[]): Promise<Record<Key, Value>> {\n const batchPromise = this.#fetchBatch(staleKeys).then((values) => {\n const fetchedAt = Date.now();\n for (const key of staleKeys) {\n this.#fetchedAt.set(key, fetchedAt);\n }\n return values;\n });\n\n for (const key of staleKeys) {\n const perKey = batchPromise.then(\n (values) => values[key],\n () => undefined,\n );\n this.#inflight.set(key, perKey);\n }\n\n // Clean up inflight entries once the batch settles (success or failure).\n // Rejection is already surfaced to the caller via the returned batchPromise.\n batchPromise\n .finally(() => {\n for (const key of staleKeys) {\n this.#inflight.delete(key);\n }\n })\n .catch(() => undefined);\n\n return batchPromise;\n }\n\n /**\n * Join the inflight fetches for the given keys and collect their values. Keys\n * whose inflight fetch produced no value are omitted.\n *\n * @param inflightKeys - Keys whose fetches are already in progress.\n * @returns Values keyed by key.\n */\n async #joinInflight(inflightKeys: Key[]): Promise<Record<Key, Value>> {\n const values = {} as Record<Key, Value>;\n\n const results = await Promise.all(\n inflightKeys.map(async (key) => {\n const value = await this.#inflight.get(key);\n return [key, value] as const;\n }),\n );\n\n for (const [key, value] of results) {\n if (value !== undefined) {\n values[key] = value;\n }\n }\n\n return values;\n }\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Executes the underlying batched fetch for a set of keys. Only keys that have
|
|
3
|
+
* a value need to be present in the returned record; keys the source had no
|
|
4
|
+
* data for are simply omitted (they are still marked fresh — see
|
|
5
|
+
* {@link DedupingBatchFetcher.fetch}).
|
|
6
|
+
*
|
|
7
|
+
* @param keys - The keys to fetch (already filtered to stale, not-inflight keys).
|
|
8
|
+
* @returns The fetched values keyed by key.
|
|
9
|
+
*/
|
|
10
|
+
export type BatchFetchFn<Key extends string, Value> = (keys: Key[]) => Promise<Record<Key, Value>>;
|
|
11
|
+
export type DedupingBatchFetcherOptions<Key extends string, Value> = {
|
|
12
|
+
/** Performs the actual batched fetch for stale, not-inflight keys. */
|
|
13
|
+
fetchBatch: BatchFetchFn<Key, Value>;
|
|
14
|
+
/**
|
|
15
|
+
* Minimum age (ms) before a key is considered stale and re-fetched. Keys
|
|
16
|
+
* fetched more recently than this are skipped entirely.
|
|
17
|
+
*/
|
|
18
|
+
freshnessTtlMs: number;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Deduplicates batched fetches by key across two dimensions:
|
|
22
|
+
*
|
|
23
|
+
* 1. **Freshness TTL** — keys fetched within `freshnessTtlMs` are skipped
|
|
24
|
+
* entirely. Note the freshness window only starts once a fetch *completes*,
|
|
25
|
+
* so it does not cover requests that are still in flight.
|
|
26
|
+
* 2. **Inflight coalescing** — if a fetch is already in progress for a key,
|
|
27
|
+
* concurrent callers join the existing promise instead of issuing a new
|
|
28
|
+
* request. This covers the request-in-flight window the freshness TTL
|
|
29
|
+
* structurally cannot.
|
|
30
|
+
*
|
|
31
|
+
* Both layers are per-key, so a call for a partially-overlapping set of keys
|
|
32
|
+
* reuses the fresh/inflight keys and only fetches the genuinely-missing ones.
|
|
33
|
+
*
|
|
34
|
+
* The fetch is batched: all stale, not-inflight keys from a single `fetch()`
|
|
35
|
+
* call are passed to `fetchBatch` together, then split into per-key results so
|
|
36
|
+
* each key can be joined independently.
|
|
37
|
+
*/
|
|
38
|
+
export declare class DedupingBatchFetcher<Key extends string, Value> {
|
|
39
|
+
#private;
|
|
40
|
+
constructor(options: DedupingBatchFetcherOptions<Key, Value>);
|
|
41
|
+
/**
|
|
42
|
+
* Minimum age (ms) before a key is re-fetched.
|
|
43
|
+
*
|
|
44
|
+
* @returns The current freshness TTL in milliseconds.
|
|
45
|
+
*/
|
|
46
|
+
get freshnessTtlMs(): number;
|
|
47
|
+
set freshnessTtlMs(ms: number);
|
|
48
|
+
/**
|
|
49
|
+
* Fetch values for the given keys, deduplicating against fresh and inflight
|
|
50
|
+
* fetches.
|
|
51
|
+
*
|
|
52
|
+
* @param keys - The keys to fetch.
|
|
53
|
+
* @returns Values keyed by key. Only contains entries for keys that were
|
|
54
|
+
* actually fetched (or joined from inflight) and had a value.
|
|
55
|
+
*/
|
|
56
|
+
fetch(keys: Key[]): Promise<Record<Key, Value>>;
|
|
57
|
+
/**
|
|
58
|
+
* Clear the freshness cache, forcing the next fetch to re-request every key
|
|
59
|
+
* regardless of TTL. Does not affect inflight fetches.
|
|
60
|
+
*/
|
|
61
|
+
invalidate(): void;
|
|
62
|
+
/** Clear all freshness and inflight state. */
|
|
63
|
+
destroy(): void;
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=dedupingBatchFetcher.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dedupingBatchFetcher.d.cts","sourceRoot":"","sources":["../../src/utils/dedupingBatchFetcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,IAAI,CACpD,IAAI,EAAE,GAAG,EAAE,KACR,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AAEjC,MAAM,MAAM,2BAA2B,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,IAAI;IACnE,sEAAsE;IACtE,UAAU,EAAE,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,oBAAoB,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK;;gBAc7C,OAAO,EAAE,2BAA2B,CAAC,GAAG,EAAE,KAAK,CAAC;IAK5D;;;;OAIG;IACH,IAAI,cAAc,IAAI,MAAM,CAE3B;IAED,IAAI,cAAc,CAAC,EAAE,EAAE,MAAM,EAE5B;IAED;;;;;;;OAOG;IACG,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAmBrD;;;OAGG;IACH,UAAU,IAAI,IAAI;IAIlB,8CAA8C;IAC9C,OAAO,IAAI,IAAI;CA4GhB"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Executes the underlying batched fetch for a set of keys. Only keys that have
|
|
3
|
+
* a value need to be present in the returned record; keys the source had no
|
|
4
|
+
* data for are simply omitted (they are still marked fresh — see
|
|
5
|
+
* {@link DedupingBatchFetcher.fetch}).
|
|
6
|
+
*
|
|
7
|
+
* @param keys - The keys to fetch (already filtered to stale, not-inflight keys).
|
|
8
|
+
* @returns The fetched values keyed by key.
|
|
9
|
+
*/
|
|
10
|
+
export type BatchFetchFn<Key extends string, Value> = (keys: Key[]) => Promise<Record<Key, Value>>;
|
|
11
|
+
export type DedupingBatchFetcherOptions<Key extends string, Value> = {
|
|
12
|
+
/** Performs the actual batched fetch for stale, not-inflight keys. */
|
|
13
|
+
fetchBatch: BatchFetchFn<Key, Value>;
|
|
14
|
+
/**
|
|
15
|
+
* Minimum age (ms) before a key is considered stale and re-fetched. Keys
|
|
16
|
+
* fetched more recently than this are skipped entirely.
|
|
17
|
+
*/
|
|
18
|
+
freshnessTtlMs: number;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Deduplicates batched fetches by key across two dimensions:
|
|
22
|
+
*
|
|
23
|
+
* 1. **Freshness TTL** — keys fetched within `freshnessTtlMs` are skipped
|
|
24
|
+
* entirely. Note the freshness window only starts once a fetch *completes*,
|
|
25
|
+
* so it does not cover requests that are still in flight.
|
|
26
|
+
* 2. **Inflight coalescing** — if a fetch is already in progress for a key,
|
|
27
|
+
* concurrent callers join the existing promise instead of issuing a new
|
|
28
|
+
* request. This covers the request-in-flight window the freshness TTL
|
|
29
|
+
* structurally cannot.
|
|
30
|
+
*
|
|
31
|
+
* Both layers are per-key, so a call for a partially-overlapping set of keys
|
|
32
|
+
* reuses the fresh/inflight keys and only fetches the genuinely-missing ones.
|
|
33
|
+
*
|
|
34
|
+
* The fetch is batched: all stale, not-inflight keys from a single `fetch()`
|
|
35
|
+
* call are passed to `fetchBatch` together, then split into per-key results so
|
|
36
|
+
* each key can be joined independently.
|
|
37
|
+
*/
|
|
38
|
+
export declare class DedupingBatchFetcher<Key extends string, Value> {
|
|
39
|
+
#private;
|
|
40
|
+
constructor(options: DedupingBatchFetcherOptions<Key, Value>);
|
|
41
|
+
/**
|
|
42
|
+
* Minimum age (ms) before a key is re-fetched.
|
|
43
|
+
*
|
|
44
|
+
* @returns The current freshness TTL in milliseconds.
|
|
45
|
+
*/
|
|
46
|
+
get freshnessTtlMs(): number;
|
|
47
|
+
set freshnessTtlMs(ms: number);
|
|
48
|
+
/**
|
|
49
|
+
* Fetch values for the given keys, deduplicating against fresh and inflight
|
|
50
|
+
* fetches.
|
|
51
|
+
*
|
|
52
|
+
* @param keys - The keys to fetch.
|
|
53
|
+
* @returns Values keyed by key. Only contains entries for keys that were
|
|
54
|
+
* actually fetched (or joined from inflight) and had a value.
|
|
55
|
+
*/
|
|
56
|
+
fetch(keys: Key[]): Promise<Record<Key, Value>>;
|
|
57
|
+
/**
|
|
58
|
+
* Clear the freshness cache, forcing the next fetch to re-request every key
|
|
59
|
+
* regardless of TTL. Does not affect inflight fetches.
|
|
60
|
+
*/
|
|
61
|
+
invalidate(): void;
|
|
62
|
+
/** Clear all freshness and inflight state. */
|
|
63
|
+
destroy(): void;
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=dedupingBatchFetcher.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dedupingBatchFetcher.d.mts","sourceRoot":"","sources":["../../src/utils/dedupingBatchFetcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,IAAI,CACpD,IAAI,EAAE,GAAG,EAAE,KACR,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AAEjC,MAAM,MAAM,2BAA2B,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,IAAI;IACnE,sEAAsE;IACtE,UAAU,EAAE,YAAY,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,oBAAoB,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK;;gBAc7C,OAAO,EAAE,2BAA2B,CAAC,GAAG,EAAE,KAAK,CAAC;IAK5D;;;;OAIG;IACH,IAAI,cAAc,IAAI,MAAM,CAE3B;IAED,IAAI,cAAc,CAAC,EAAE,EAAE,MAAM,EAE5B;IAED;;;;;;;OAOG;IACG,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAmBrD;;;OAGG;IACH,UAAU,IAAI,IAAI;IAIlB,8CAA8C;IAC9C,OAAO,IAAI,IAAI;CA4GhB"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
12
|
+
var _DedupingBatchFetcher_instances, _DedupingBatchFetcher_fetchBatch, _DedupingBatchFetcher_freshnessTtlMs, _DedupingBatchFetcher_fetchedAt, _DedupingBatchFetcher_inflight, _DedupingBatchFetcher_partition, _DedupingBatchFetcher_isFresh, _DedupingBatchFetcher_startBatchFetch, _DedupingBatchFetcher_joinInflight;
|
|
13
|
+
/**
|
|
14
|
+
* Deduplicates batched fetches by key across two dimensions:
|
|
15
|
+
*
|
|
16
|
+
* 1. **Freshness TTL** — keys fetched within `freshnessTtlMs` are skipped
|
|
17
|
+
* entirely. Note the freshness window only starts once a fetch *completes*,
|
|
18
|
+
* so it does not cover requests that are still in flight.
|
|
19
|
+
* 2. **Inflight coalescing** — if a fetch is already in progress for a key,
|
|
20
|
+
* concurrent callers join the existing promise instead of issuing a new
|
|
21
|
+
* request. This covers the request-in-flight window the freshness TTL
|
|
22
|
+
* structurally cannot.
|
|
23
|
+
*
|
|
24
|
+
* Both layers are per-key, so a call for a partially-overlapping set of keys
|
|
25
|
+
* reuses the fresh/inflight keys and only fetches the genuinely-missing ones.
|
|
26
|
+
*
|
|
27
|
+
* The fetch is batched: all stale, not-inflight keys from a single `fetch()`
|
|
28
|
+
* call are passed to `fetchBatch` together, then split into per-key results so
|
|
29
|
+
* each key can be joined independently.
|
|
30
|
+
*/
|
|
31
|
+
export class DedupingBatchFetcher {
|
|
32
|
+
constructor(options) {
|
|
33
|
+
_DedupingBatchFetcher_instances.add(this);
|
|
34
|
+
_DedupingBatchFetcher_fetchBatch.set(this, void 0);
|
|
35
|
+
_DedupingBatchFetcher_freshnessTtlMs.set(this, void 0);
|
|
36
|
+
/** Tracks the last successful fetch time per key (freshness gating). */
|
|
37
|
+
_DedupingBatchFetcher_fetchedAt.set(this, new Map());
|
|
38
|
+
/**
|
|
39
|
+
* Per-key inflight fetch promises. Each resolves to the value, or `undefined`
|
|
40
|
+
* if the batch failed or returned no data for that key.
|
|
41
|
+
*/
|
|
42
|
+
_DedupingBatchFetcher_inflight.set(this, new Map());
|
|
43
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_fetchBatch, options.fetchBatch, "f");
|
|
44
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_freshnessTtlMs, options.freshnessTtlMs, "f");
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Minimum age (ms) before a key is re-fetched.
|
|
48
|
+
*
|
|
49
|
+
* @returns The current freshness TTL in milliseconds.
|
|
50
|
+
*/
|
|
51
|
+
get freshnessTtlMs() {
|
|
52
|
+
return __classPrivateFieldGet(this, _DedupingBatchFetcher_freshnessTtlMs, "f");
|
|
53
|
+
}
|
|
54
|
+
set freshnessTtlMs(ms) {
|
|
55
|
+
__classPrivateFieldSet(this, _DedupingBatchFetcher_freshnessTtlMs, ms, "f");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Fetch values for the given keys, deduplicating against fresh and inflight
|
|
59
|
+
* fetches.
|
|
60
|
+
*
|
|
61
|
+
* @param keys - The keys to fetch.
|
|
62
|
+
* @returns Values keyed by key. Only contains entries for keys that were
|
|
63
|
+
* actually fetched (or joined from inflight) and had a value.
|
|
64
|
+
*/
|
|
65
|
+
async fetch(keys) {
|
|
66
|
+
const { staleKeys, inflightKeys } = __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_partition).call(this, keys);
|
|
67
|
+
if (staleKeys.length === 0 && inflightKeys.length === 0) {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
// Start a fetch for stale keys and join any fetches already in progress.
|
|
71
|
+
const batchPromise = staleKeys.length > 0 ? __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_startBatchFetch).call(this, staleKeys) : undefined;
|
|
72
|
+
const values = await __classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_joinInflight).call(this, inflightKeys);
|
|
73
|
+
if (batchPromise) {
|
|
74
|
+
Object.assign(values, await batchPromise);
|
|
75
|
+
}
|
|
76
|
+
return values;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Clear the freshness cache, forcing the next fetch to re-request every key
|
|
80
|
+
* regardless of TTL. Does not affect inflight fetches.
|
|
81
|
+
*/
|
|
82
|
+
invalidate() {
|
|
83
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").clear();
|
|
84
|
+
}
|
|
85
|
+
/** Clear all freshness and inflight state. */
|
|
86
|
+
destroy() {
|
|
87
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").clear();
|
|
88
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").clear();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
_DedupingBatchFetcher_fetchBatch = new WeakMap(), _DedupingBatchFetcher_freshnessTtlMs = new WeakMap(), _DedupingBatchFetcher_fetchedAt = new WeakMap(), _DedupingBatchFetcher_inflight = new WeakMap(), _DedupingBatchFetcher_instances = new WeakSet(), _DedupingBatchFetcher_partition = function _DedupingBatchFetcher_partition(keys) {
|
|
92
|
+
const now = Date.now();
|
|
93
|
+
const staleKeys = [];
|
|
94
|
+
const inflightKeys = [];
|
|
95
|
+
for (const key of keys) {
|
|
96
|
+
if (__classPrivateFieldGet(this, _DedupingBatchFetcher_instances, "m", _DedupingBatchFetcher_isFresh).call(this, key, now)) {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").has(key)) {
|
|
100
|
+
inflightKeys.push(key);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
staleKeys.push(key);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { staleKeys, inflightKeys };
|
|
107
|
+
}, _DedupingBatchFetcher_isFresh = function _DedupingBatchFetcher_isFresh(key, now) {
|
|
108
|
+
const fetchedAt = __classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").get(key);
|
|
109
|
+
return fetchedAt !== undefined && now - fetchedAt < __classPrivateFieldGet(this, _DedupingBatchFetcher_freshnessTtlMs, "f");
|
|
110
|
+
}, _DedupingBatchFetcher_startBatchFetch = function _DedupingBatchFetcher_startBatchFetch(staleKeys) {
|
|
111
|
+
const batchPromise = __classPrivateFieldGet(this, _DedupingBatchFetcher_fetchBatch, "f").call(this, staleKeys).then((values) => {
|
|
112
|
+
const fetchedAt = Date.now();
|
|
113
|
+
for (const key of staleKeys) {
|
|
114
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_fetchedAt, "f").set(key, fetchedAt);
|
|
115
|
+
}
|
|
116
|
+
return values;
|
|
117
|
+
});
|
|
118
|
+
for (const key of staleKeys) {
|
|
119
|
+
const perKey = batchPromise.then((values) => values[key], () => undefined);
|
|
120
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").set(key, perKey);
|
|
121
|
+
}
|
|
122
|
+
// Clean up inflight entries once the batch settles (success or failure).
|
|
123
|
+
// Rejection is already surfaced to the caller via the returned batchPromise.
|
|
124
|
+
batchPromise
|
|
125
|
+
.finally(() => {
|
|
126
|
+
for (const key of staleKeys) {
|
|
127
|
+
__classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").delete(key);
|
|
128
|
+
}
|
|
129
|
+
})
|
|
130
|
+
.catch(() => undefined);
|
|
131
|
+
return batchPromise;
|
|
132
|
+
}, _DedupingBatchFetcher_joinInflight =
|
|
133
|
+
/**
|
|
134
|
+
* Join the inflight fetches for the given keys and collect their values. Keys
|
|
135
|
+
* whose inflight fetch produced no value are omitted.
|
|
136
|
+
*
|
|
137
|
+
* @param inflightKeys - Keys whose fetches are already in progress.
|
|
138
|
+
* @returns Values keyed by key.
|
|
139
|
+
*/
|
|
140
|
+
async function _DedupingBatchFetcher_joinInflight(inflightKeys) {
|
|
141
|
+
const values = {};
|
|
142
|
+
const results = await Promise.all(inflightKeys.map(async (key) => {
|
|
143
|
+
const value = await __classPrivateFieldGet(this, _DedupingBatchFetcher_inflight, "f").get(key);
|
|
144
|
+
return [key, value];
|
|
145
|
+
}));
|
|
146
|
+
for (const [key, value] of results) {
|
|
147
|
+
if (value !== undefined) {
|
|
148
|
+
values[key] = value;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return values;
|
|
152
|
+
};
|
|
153
|
+
//# sourceMappingURL=dedupingBatchFetcher.mjs.map
|