freshyo/apps/backend/tests/helpers/cache.ts
2026-11-05 23:33:30 +05:30

266 lines
9.3 KiB
TypeScript

/**
* Versioned public cache files.
*
* common.essentialConsts({ boundId }) is the source of truth for the versions:
*
* products ${assetsDomain}${apiCacheKey}/regions/${regionId}/v-${products_version_num}/products.json
* consts file .../v-${products_version_num}/essential-consts.json
* stores .../v-${products_version_num}/stores.json
* store detail .../v-${products_version_num}/stores/<storeId>.json
* banners .../v-${products_version_num}/banners.json
* slots ${assetsDomain}regions/${regionId}/slots/v-${slots_version_num}/slots.json
* availability ${assetsDomain}regions/${regionId}/av-${availability_version_num}/availability.json
*
* products/stores/banners are rebuilt asynchronously by the CacheCreator Durable
* Object (poll, never sleep once). slots/availability are written synchronously.
*/
import { apiClient, sleep } from './api'
import { staffSession } from './sessions'
import { API_BASE_URL, CACHE_POLL_INTERVAL_MS, CACHE_POLL_TIMEOUT_MS, TEST_BOUND_ID, TEST_REGION_ID } from './env'
import {
CACHE_FILENAMES,
availabilityCacheUrl as buildAvailabilityCacheUrl,
regionCacheUrl,
slotsCacheUrl as buildSlotsCacheUrl,
storeDetailCacheUrl as buildStoreDetailCacheUrl,
} from '@packages/shared'
export interface EssentialConsts {
regionId: number
boundId: number
assetsDomain: string
apiCacheKey: string
products_version_num: number
slots_version_num: number
availability_version_num: number
/** Published CDN URLs (absent in payloads written before this field existed). */
essentialUrls?: Record<string, string>
webviewHtml?: string | null
isWebviewClosable?: boolean
updatePrompt?: { isEnabled: boolean; isClosable: boolean }
[key: string]: unknown
}
export const CACHE_FIELDS = {
products: 'products_version_num',
slots: 'slots_version_num',
availability: 'availability_version_num',
} as const
export type CacheKind = keyof typeof CACHE_FIELDS
/**
* Test-only: run the cache rebuild synchronously instead of waiting for the
* CacheCreator debounce. Requires `ENABLE_TEST_ROUTES=true` on the server
* (set in apps/backend/.dev.vars locally). Omit `regionId` to rebuild all.
*/
export async function rebuildCache(regionId?: number): Promise<void> {
const staff = await staffSession()
const qs = regionId != null ? `?regionId=${regionId}` : ''
const res = await fetch(`${API_BASE_URL}/api/test/rebuild${qs}`, {
method: 'POST',
headers: { Authorization: `Bearer ${staff.token}` },
})
if (!res.ok) {
throw new Error(
`[api-tests] POST /api/test/rebuild${qs} failed: ${res.status} ${await res.text()}`
)
}
}
/** Cache documents that can be read straight from the scaffold functions. */
export type ScaffoldKind = 'products' | 'availability' | 'slots' | 'stores' | 'banners'
async function testRoute(path: string): Promise<any> {
const staff = await staffSession()
const res = await fetch(`${API_BASE_URL}/api/test${path}`, {
headers: { Authorization: `Bearer ${staff.token}` },
})
if (!res.ok) {
throw new Error(`[api-tests] GET /api/test${path} failed: ${res.status} ${await res.text()}`)
}
return (await res.json()).data
}
/**
* Test-only: the exact document the cache writer would serialise for `kind`,
* read from the scaffold function (no S3/CDN/KV/Durable Object).
*/
export function scaffoldCache(
kind: ScaffoldKind,
options: { regionId?: number } = {}
): Promise<any> {
const regionId = options.regionId ?? TEST_REGION_ID
return testRoute(`/cache/${kind}?regionId=${regionId}`)
}
/** Test-only: `scaffoldStoreWithProducts` output for one store. */
export function scaffoldStore(
storeId: number,
options: { regionId?: number } = {}
): Promise<any> {
const regionId = options.regionId ?? TEST_REGION_ID
return testRoute(`/cache/store/${storeId}?regionId=${regionId}`)
}
/** Test-only: `scaffoldEssentialConsts` output for one bound. */
export function scaffoldEssentialConsts(boundId: number = TEST_BOUND_ID): Promise<any> {
return testRoute(`/cache/essential-consts?boundId=${boundId}`)
}
export async function getEssentialConsts(boundId: number = TEST_BOUND_ID): Promise<EssentialConsts> {
const consts = (await apiClient().common.essentialConsts.query({ boundId })) as EssentialConsts
if (!consts?.assetsDomain) {
throw new Error(
`[api-tests] common.essentialConsts(${boundId}) returned no assetsDomain: ${JSON.stringify(consts)}`
)
}
return consts
}
export function versionOf(consts: EssentialConsts, kind: CacheKind): number {
const value = Number(consts[CACHE_FIELDS[kind]])
if (!Number.isFinite(value)) {
throw new Error(`[api-tests] ${CACHE_FIELDS[kind]} missing from essentialConsts`)
}
return value
}
const baseRegion = (c: EssentialConsts, regionId?: number) => regionId ?? c.regionId
export const productsCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.products)
export const storesCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.stores)
export const storeDetailCacheUrl = (
c: EssentialConsts,
storeId: number,
regionId?: number,
version = versionOf(c, 'products')
) =>
buildStoreDetailCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, storeId)
export const bannersCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'products')) =>
regionCacheUrl(c.assetsDomain, c.apiCacheKey, baseRegion(c, regionId), version, CACHE_FILENAMES.banners)
export const essentialConstsCacheUrl = (
c: EssentialConsts,
regionId?: number,
version = versionOf(c, 'products')
) =>
regionCacheUrl(
c.assetsDomain,
c.apiCacheKey,
baseRegion(c, regionId),
version,
CACHE_FILENAMES.essentialConsts
)
export const slotsCacheUrl = (c: EssentialConsts, regionId?: number, version = versionOf(c, 'slots')) =>
buildSlotsCacheUrl(c.assetsDomain, baseRegion(c, regionId), version)
export const availabilityCacheUrl = (
c: EssentialConsts,
regionId?: number,
version = versionOf(c, 'availability')
) => buildAvailabilityCacheUrl(c.assetsDomain, baseRegion(c, regionId), version)
/** GET a cache file and parse it; throws with the status on a non-2xx. */
export async function fetchCacheJson<T = unknown>(url: string): Promise<T> {
const res = await fetch(url, { headers: { accept: 'application/json' } })
if (!res.ok) {
throw new Error(`[api-tests] ${res.status} ${res.statusText} fetching ${url}`)
}
return (await res.json()) as T
}
/** Retry `fn` until it returns a truthy value or the timeout elapses. */
export async function pollUntil<T>(
label: string,
fn: () => Promise<T | null | undefined>,
options: { timeoutMs?: number; intervalMs?: number } = {}
): Promise<T> {
const timeoutMs = options.timeoutMs ?? CACHE_POLL_TIMEOUT_MS
const intervalMs = options.intervalMs ?? CACHE_POLL_INTERVAL_MS
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 sleep(intervalMs)
}
}
/** Poll one cache file until the predicate accepts it (tolerates 404/old data). */
export async function pollCacheJson<T = unknown>(
label: string,
url: () => string,
predicate: (value: T) => boolean,
options: { timeoutMs?: number; intervalMs?: number } = {}
): Promise<T> {
return pollUntil(
label,
async () => {
const value = await fetchCacheJson<T>(url())
return predicate(value) ? value : null
},
options
)
}
/** Wait until a version counter advances past `baseline`. */
export async function waitForVersion(
kind: CacheKind,
baseline: number,
boundId: number = TEST_BOUND_ID,
options: { timeoutMs?: number; intervalMs?: number } = {}
): Promise<number> {
return pollUntil(
`${CACHE_FIELDS[kind]} > ${baseline} (bound ${boundId})`,
async () => {
const consts = await getEssentialConsts(boundId)
const current = versionOf(consts, kind)
return current > baseline ? current : null
},
options
)
}
/** Snapshot the current versions for all three kinds. */
export async function versionSnapshot(boundId: number = TEST_BOUND_ID) {
const consts = await getEssentialConsts(boundId)
return {
consts,
products: versionOf(consts, 'products'),
slots: versionOf(consts, 'slots'),
availability: versionOf(consts, 'availability'),
}
}
/** Find an entry by id in a `{ products | slots | availability | stores: [] }` document. */
export function findBy<T extends Record<string, any>>(list: T[], id: number, key = 'id'): T | undefined {
return list.find((entry) => Number(entry[key]) === Number(id))
}
export function asArray<T = any>(value: unknown): T[] {
if (Array.isArray(value)) return value as T[]
const candidate = value as Record<string, unknown>
for (const key of ['products', 'slots', 'availability', 'stores', 'banners']) {
if (Array.isArray(candidate?.[key])) return candidate[key] as T[]
}
return []
}