/** * Static JSON cache helpers. * * The cache is written through the R2 S3 API and served from the assets domain * (there is no backend route for it), so tests read the versioned public URL: * slots ${assetsDomain}slots/v-/slots.json * availability ${assetsDomain}av-/availability.json * products ${assetsDomain}${apiCacheKey}/v-/products.json * store detail ${assetsDomain}${apiCacheKey}/v-/stores/.json * * Versions come from common.essentialConsts. */ import { apiClient } from './api' export interface EssentialConsts { assetsDomain: string apiCacheKey: string cacheVersion: number slotsVersionNum: number availabilityVersionNum: number [key: string]: unknown } export async function essentialConsts(): Promise { const consts = (await apiClient().common.essentialConsts.query()) as EssentialConsts if (!consts?.assetsDomain || !consts?.apiCacheKey) { throw new Error( `[api-tests] common.essentialConsts is missing assetsDomain/apiCacheKey: ${JSON.stringify(consts)}` ) } return consts } export const slotsCacheUrl = (c: EssentialConsts, version: number) => `${c.assetsDomain}slots/v-${version}/slots.json` export const availabilityCacheUrl = (c: EssentialConsts, version: number) => `${c.assetsDomain}av-${version}/availability.json` export const productsCacheUrl = (c: EssentialConsts, version: number) => `${c.assetsDomain}${c.apiCacheKey}/v-${version}/products.json` export const storesCacheUrl = (c: EssentialConsts, version: number) => `${c.assetsDomain}${c.apiCacheKey}/v-${version}/stores.json` export const essentialConstsCacheUrl = (c: EssentialConsts, version: number) => `${c.assetsDomain}${c.apiCacheKey}/v-${version}/essential-consts.json` export const storeDetailCacheUrl = (c: EssentialConsts, version: number, storeId: number) => `${c.assetsDomain}${c.apiCacheKey}/v-${version}/stores/${storeId}.json` /** GET a cache file and parse it; throws with the status on a non-2xx. */ export async function fetchCacheJson(url: string): Promise { const res = await fetch(url) if (!res.ok) { throw new Error(`[api-tests] ${res.status} ${res.statusText} fetching cache file ${url}`) } return (await res.json()) as T } /** * Retry `fn` until it returns a value or the timeout elapses. Used for the * eventual products/stores cache (regenerated ~30s later by the CACHE_CREATOR * Durable Object). */ export async function pollUntil( label: string, fn: () => Promise, options: { timeoutMs?: number; intervalMs?: number } = {} ): Promise { const timeoutMs = options.timeoutMs ?? 90_000 const intervalMs = options.intervalMs ?? 5_000 const deadline = Date.now() + timeoutMs let lastError: unknown = null for (;;) { try { const value = await fn() if (value) return value } catch (error) { lastError = error } if (Date.now() >= deadline) { throw new Error( `[api-tests] timed out after ${timeoutMs}ms waiting for: ${label}` + (lastError ? ` (last error: ${(lastError as Error).message})` : '') ) } await new Promise((resolve) => setTimeout(resolve, intervalMs)) } }