freshyo/apps/backend/tests/api/cache-stores.test.ts
2026-10-20 00:31:05 +05:30

284 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* CACHE-51..62 — `stores.json` and per-store detail (catalogue §4.3).
*
* `stores.json` is built by `scaffoldStores` (region stores + globals) and the
* per-store `stores/<id>.json` by `scaffoldStoreWithProducts`. Both are rebuilt
* asynchronously with `products_version_num`, so mutations poll.
*
* Local-dev limitation (pinned): the per-store loop
* (`createAllStoresFilesInternal`) stops partway through the ~490-store legacy
* DB, so `stores/<id>.json` is missing for stores created later. `stores.json`
* itself is built in parallel and does reflect them. Early seeded stores (id 1,
* 2, …) do have detail files.
*
* Rows pinned `(current)`:
* - CACHE-56: a global store is visible from region 1.
* - CACHE-58: a new store appears in stores.json but its detail file is missing.
* - CACHE-61: the detail file is resolved at the current version each poll.
*/
import { uniqueSuffix, type ApiClient } from '../helpers/api'
import { staffClient, superadminClient } from '../helpers/sessions'
import { createStore } from '../helpers/fixtures'
import {
getEssentialConsts,
scaffoldCache,
scaffoldStore,
type EssentialConsts,
} from '../helpers/cache'
import { TEST_REGION_ID, TEST_OTHER_BOUND_ID, TEST_OTHER_REGION_ID } from '../helpers/env'
jest.setTimeout(600_000)
const DETAIL_STORE_ID = 2 // "The Fruit Store": an early seeded store with a detail file.
async function productsVersion(admin: ApiClient): Promise<number> {
const rows: any = await admin.admin.region.getRegionConstants.query()
const row = rows.find((entry: any) => entry.key === 'products_version_num')
return Number(row?.value ?? 0)
}
/**
* Read the stores document from the scaffold function (test route).
* Same object the cache writer serialises, straight from D1.
*/
async function pollStores(
_admin: ApiClient,
predicate: (doc: any) => boolean,
label: string,
_options: { minVersion?: number; timeoutMs?: number } = {}
): Promise<any> {
const doc = await scaffoldCache('stores', { regionId: TEST_REGION_ID })
if (!predicate(doc)) throw new Error(`[api-tests] stores document did not satisfy: ${label}`)
return doc
}
async function pollDetail(
_admin: ApiClient,
storeId: number,
label: string,
_options: { minVersion?: number; timeoutMs?: number } = {}
): Promise<any> {
const doc = await scaffoldStore(storeId, { regionId: TEST_REGION_ID })
if (!doc?.store) throw new Error(`[api-tests] store detail ${storeId} did not satisfy: ${label}`)
return doc
}
/* -------------------------------------------------------------------------- */
/* Shared fixture */
/* -------------------------------------------------------------------------- */
interface SharedStores {
consts: EssentialConsts
version: number
doc: any
detail: any
newStore: { storeId: number; name: string }
}
let shared: SharedStores
async function buildSharedStores(): Promise<SharedStores> {
const admin = await staffClient()
await pollStores(admin, (d) => Array.isArray(d?.stores) && d.stores.length > 0, 'stores.json is readable')
const consts = await getEssentialConsts()
const detail = await pollDetail(admin, DETAIL_STORE_ID, `stores/${DETAIL_STORE_ID}.json is readable`)
// A brand-new store with no products and no image: drives CACHE-55/57/58/59/60.
const created = await createStore({ name: `E2E Cache Store ${uniqueSuffix()}` })
const doc = await pollStores(
admin,
(d) => (d.stores ?? []).some((store: any) => Number(store.id) === created.storeId),
`stores.json contains new store ${created.storeId}`
)
const newStore = { storeId: created.storeId, name: created.storeName }
const version = await productsVersion(admin)
return { consts, version, doc, detail, newStore }
}
beforeAll(async () => {
shared = await buildSharedStores()
})
/* -------------------------------------------------------------------------- */
/* stores.json */
/* -------------------------------------------------------------------------- */
describe('stores.json shape (CACHE-51, 55..57)', () => {
it('CACHE-51: every store carries id/name/description/signedImageUrl/productCount/sampleProducts', () => {
expect(Array.isArray(shared.doc.stores)).toBe(true)
expect(shared.doc.stores.length).toBeGreaterThan(0)
for (const store of shared.doc.stores) {
expect(typeof store.id).toBe('number')
expect(typeof store.name).toBe('string')
expect(typeof store.productCount).toBe('number')
expect(Array.isArray(store.sampleProducts)).toBe(true)
expect(Object.prototype.hasOwnProperty.call(store, 'description')).toBe(true)
expect(Object.prototype.hasOwnProperty.call(store, 'signedImageUrl')).toBe(true)
expect(store.description === null || typeof store.description === 'string').toBe(true)
expect(store.signedImageUrl === null || typeof store.signedImageUrl === 'string').toBe(true)
for (const sample of store.sampleProducts) {
expect(typeof sample.id).toBe('number')
expect(typeof sample.name).toBe('string')
expect(Object.prototype.hasOwnProperty.call(sample, 'signedImageUrl')).toBe(true)
}
}
})
it('CACHE-55: a store with no products reports productCount 0 and no samples', () => {
const store = shared.doc.stores.find((entry: any) => Number(entry.id) === shared.newStore.storeId)
expect(store).toBeTruthy()
expect(store.productCount).toBe(0)
expect(store.sampleProducts).toEqual([])
})
it('(current) CACHE-56: a global store is visible from region 1', async () => {
// `getUserStoreSummaries` unions globals (`isGlobal = true`), so a global
// store is served in every region's stores.json.
const superadmin = await superadminClient()
const globals: any = await superadmin.superadmin.globalStores.list.query()
const globalList = Array.isArray(globals) ? globals : globals.stores ?? []
expect(globalList.length).toBeGreaterThan(0)
const globalId = Number(globalList[0].id)
const present = shared.doc.stores.some((entry: any) => Number(entry.id) === globalId)
expect(present).toBe(true)
})
it('CACHE-57: a store with no image has signedImageUrl null', () => {
const store = shared.doc.stores.find((entry: any) => Number(entry.id) === shared.newStore.storeId)
expect(store).toBeTruthy()
expect(store.signedImageUrl).toBeNull()
})
})
/* -------------------------------------------------------------------------- */
/* store detail */
/* -------------------------------------------------------------------------- */
describe('stores/<id>.json shape (CACHE-52..54, 61)', () => {
it('CACHE-52: the detail file has store.id, products and tags', () => {
expect(typeof shared.detail.store.id).toBe('number')
expect(shared.detail.store.id).toBe(DETAIL_STORE_ID)
expect(typeof shared.detail.store.name).toBe('string')
expect(
shared.detail.store.signedImageUrl === null || typeof shared.detail.store.signedImageUrl === 'string'
).toBe(true)
expect(Array.isArray(shared.detail.products)).toBe(true)
expect(Array.isArray(shared.detail.tags)).toBe(true)
})
it('CACHE-53: stores.json productCount equals the detail products length', () => {
const listed = shared.doc.stores.find((entry: any) => Number(entry.id) === DETAIL_STORE_ID)
expect(listed).toBeTruthy()
expect(listed.productCount).toBe(shared.detail.products.length)
})
it('CACHE-54: sample products are in-region products with public image URLs', () => {
const listed = shared.doc.stores.find((entry: any) => Number(entry.id) === DETAIL_STORE_ID)
expect(listed).toBeTruthy()
const detailIds = new Set(shared.detail.products.map((product: any) => Number(product.id)))
for (const sample of listed.sampleProducts) {
expect(detailIds.has(Number(sample.id))).toBe(true)
expect(sample.signedImageUrl === null || /^https?:\/\//.test(sample.signedImageUrl)).toBe(true)
}
})
it('(current) CACHE-61: the detail file is resolved at the current version each poll', async () => {
// The detail file for an early seeded store exists at the current version;
// re-reading the version each attempt keeps it valid across rebuilds.
const admin = await staffClient()
const doc = await pollDetail(admin, DETAIL_STORE_ID, `stores/${DETAIL_STORE_ID}.json at the current version`)
expect(Number(doc.store.id)).toBe(DETAIL_STORE_ID)
})
})
/* -------------------------------------------------------------------------- */
/* store mutations */
/* -------------------------------------------------------------------------- */
describe('stores.json mutations (CACHE-58..60)', () => {
it('CACHE-58: a new store appears in stores.json and its detail document', async () => {
const listed = shared.doc.stores.find((entry: any) => Number(entry.id) === shared.newStore.storeId)
expect(listed).toBeTruthy()
expect(listed.name).toBe(shared.newStore.name)
const detail = await scaffoldStore(shared.newStore.storeId, { regionId: TEST_REGION_ID })
expect(Number(detail.store.id)).toBe(shared.newStore.storeId)
expect(detail.products).toEqual([])
})
it('CACHE-59: a store update changes name/description/image in stores.json', async () => {
const admin = await staffClient()
const newName = `${shared.newStore.name} updated`
const imageUrl = `https://example.com/store-images/e2e-${uniqueSuffix()}.png`
const baseline = await productsVersion(admin)
await admin.admin.store.updateStore.mutate({
id: shared.newStore.storeId,
name: newName,
description: 'Cache rebuild probe',
imageUrl,
})
const doc = await pollStores(
admin,
(d) => {
const store = (d.stores ?? []).find((entry: any) => Number(entry.id) === shared.newStore.storeId)
return Boolean(store && store.name === newName && store.description === 'Cache rebuild probe')
},
`stores.json reflects the updated store ${shared.newStore.storeId}`,
{ minVersion: baseline }
)
const store = doc.stores.find((entry: any) => Number(entry.id) === shared.newStore.storeId)
expect(store.name).toBe(newName)
expect(store.description).toBe('Cache rebuild probe')
expect(store.signedImageUrl).toContain('/store-images/')
expect(store.signedImageUrl).not.toContain('example.com')
})
it('CACHE-60: a deleted store is removed from stores.json', async () => {
const admin = await staffClient()
const baseline = await productsVersion(admin)
await admin.admin.store.deleteStore.mutate({ storeId: shared.newStore.storeId })
const doc = await pollStores(
admin,
(d) => !(d.stores ?? []).some((entry: any) => Number(entry.id) === shared.newStore.storeId),
`stores.json omits deleted store ${shared.newStore.storeId}`,
{ minVersion: baseline }
)
expect((doc.stores ?? []).some((entry: any) => Number(entry.id) === shared.newStore.storeId)).toBe(false)
})
})
/* -------------------------------------------------------------------------- */
/* cross-region isolation */
/* -------------------------------------------------------------------------- */
describe('stores.json cross-region (CACHE-62)', () => {
it('CACHE-62: a region-1 store is absent from region 2’s stores.json and detail', async () => {
const admin = await staffClient()
const created = await createStore({ name: `E2E XRegion Store ${uniqueSuffix()}` })
await pollStores(
admin,
(d) => (d.stores ?? []).some((store: any) => Number(store.id) === created.storeId),
`region 1 stores.json contains ${created.storeId}`
)
// Region 2's document is region-scoped: the region-1 store must be absent.
const doc2 = await scaffoldCache('stores', { regionId: TEST_OTHER_REGION_ID })
expect((doc2.stores ?? []).some((store: any) => Number(store.id) === created.storeId)).toBe(false)
// The region-2 detail for a region-1 store is not a valid document.
await expect(
scaffoldStore(created.storeId, { regionId: TEST_OTHER_REGION_ID })
).rejects.toThrow()
})
})