|
| 1 | +import { type Provider, updatePrices, waitForUpdate } from '@pydantic/genai-prices' |
| 2 | + |
| 3 | +// data will be refetched every 30 minutes |
| 4 | +const PRICE_TTL = 1000 * 60 * 30 |
| 5 | +let genaiData: Provider[] | null = null |
| 6 | +let genaiDataTimestamp: number | null = null |
| 7 | +let isFetching = false |
| 8 | +let isSetup = false |
| 9 | + |
| 10 | +export async function setupPriceAutoUpdate() { |
| 11 | + if (!isSetup) { |
| 12 | + doSetupPriceAutoUpdate() |
| 13 | + isSetup = true |
| 14 | + } |
| 15 | + |
| 16 | + // this will await the eventual fresh genai price fetching |
| 17 | + // Note: if the data is fresh, the updatePrices will immediately resolve, so there's no performance cost to always await this. |
| 18 | + await waitForUpdate() |
| 19 | +} |
| 20 | + |
| 21 | +function doSetupPriceAutoUpdate() { |
| 22 | + updatePrices(({ setProviderData, remoteDataUrl }) => { |
| 23 | + if (genaiDataTimestamp !== null) { |
| 24 | + console.debug('genai prices local storage data found') |
| 25 | + |
| 26 | + if (genaiData !== null) { |
| 27 | + setProviderData(genaiData) |
| 28 | + } |
| 29 | + |
| 30 | + if (Date.now() - genaiDataTimestamp < PRICE_TTL) { |
| 31 | + // this will be the most frequent, cheap path |
| 32 | + console.debug('genai prices local storage data is fresh') |
| 33 | + return |
| 34 | + } else { |
| 35 | + console.debug('genai prices local storage data is stale, attempting to fetch remote data') |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (isFetching) { |
| 40 | + console.debug('genai-prices data fetch already in progress, skipping') |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + console.debug('genai-prices data is stale') |
| 45 | + isFetching = true |
| 46 | + |
| 47 | + // It's important **not** to await this promise |
| 48 | + const freshDataPromise = fetch(remoteDataUrl) |
| 49 | + .then(async (response) => { |
| 50 | + if (!response.ok) { |
| 51 | + console.error('Failed fetching provider data, response status %d', response.status) |
| 52 | + return null |
| 53 | + } |
| 54 | + |
| 55 | + const freshData = (await response.json()) as Provider[] |
| 56 | + console.debug('Updated genai prices data, %d providers', freshData.length) |
| 57 | + genaiDataTimestamp = Date.now() |
| 58 | + genaiData = freshData |
| 59 | + return freshData |
| 60 | + }) |
| 61 | + .catch((error: unknown) => { |
| 62 | + console.error('Failed fetching provider data err: %o', error) |
| 63 | + return null |
| 64 | + }) |
| 65 | + .finally(() => { |
| 66 | + isFetching = false |
| 67 | + }) |
| 68 | + |
| 69 | + setProviderData(freshDataPromise) |
| 70 | + }) |
| 71 | +} |
0 commit comments