475 lines
18 KiB
TypeScript
475 lines
18 KiB
TypeScript
/**
|
||
* CACHE-01..24, CACHE-115 — essential constants (catalogue §4.1).
|
||
*
|
||
* `common.essentialConsts({ boundId })` is served from the per-bound KV mirror
|
||
* (`readEssentialConstsFromKv`); the payload is a flat union of
|
||
* global + region + bound consts (+ env + identity). Every const-write path
|
||
* rebuilds the mirror before returning (`refreshGenKvForRegion` / `refreshGenKv`),
|
||
* so a change is reflected on the very next read.
|
||
*
|
||
* Rows pinned `(current)`:
|
||
* - CACHE-15/16: the KV miss/hit split is not forceable through the public API
|
||
* (all writers rebuild the mirror; a fresh region's cache build populates its
|
||
* bounds too). The reachable contract is asserted instead.
|
||
* - CACHE-17/18: the `raw`/`mf` host notice branch is unreachable — both
|
||
* `fetch` (undici) and `wrangler dev` force the `Host` to localhost.
|
||
* - CACHE-23: `assetsDomain`/`apiCacheKey` are always configured here.
|
||
*/
|
||
|
||
import {
|
||
expectTrpcError,
|
||
firstBatchResult,
|
||
rawQuery,
|
||
uniqueSuffix,
|
||
} from '../helpers/api'
|
||
import { staffClient, superadminClient } from '../helpers/sessions'
|
||
import {
|
||
getBoundSetting,
|
||
getRegionConstant,
|
||
setSuperadminBoundSetting,
|
||
setRegionConstant,
|
||
squareGeojson,
|
||
} from '../helpers/fixtures'
|
||
import {
|
||
availabilityCacheUrl,
|
||
bannersCacheUrl,
|
||
essentialConstsCacheUrl,
|
||
getEssentialConsts,
|
||
productsCacheUrl,
|
||
slotsCacheUrl,
|
||
storeDetailCacheUrl,
|
||
storesCacheUrl,
|
||
} from '../helpers/cache'
|
||
import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_REGION_ID, TEST_OTHER_REGION_ID } from '../helpers/env'
|
||
|
||
jest.setTimeout(300_000)
|
||
|
||
/** Bound defaults used by the scaffold when a numeric const is missing/blank/bad. */
|
||
const SCAFFOLD_BOUND_FALLBACKS = {
|
||
freeDeliveryThreshold: 200,
|
||
deliveryCharge: 0,
|
||
flashFreeDeliveryThreshold: 500,
|
||
flashDeliveryCharge: 69,
|
||
} as const
|
||
|
||
/** Set several bound settings, then restore every previous value. */
|
||
async function withBoundSettings<T>(
|
||
boundId: number,
|
||
values: Record<string, string | null>,
|
||
fn: () => Promise<T>
|
||
): Promise<T> {
|
||
const keys = Object.keys(values)
|
||
const previous: Record<string, string | null> = {}
|
||
for (const key of keys) previous[key] = await getBoundSetting(boundId, key)
|
||
|
||
const admin = await staffClient()
|
||
await admin.admin.region.updateBoundSettings.mutate({
|
||
boundId,
|
||
settings: keys.map((key) => ({ key, value: values[key] })),
|
||
})
|
||
try {
|
||
return await fn()
|
||
} finally {
|
||
await admin.admin.region.updateBoundSettings.mutate({
|
||
boundId,
|
||
settings: keys.map((key) => ({ key, value: previous[key] })),
|
||
})
|
||
}
|
||
}
|
||
|
||
/** Set several region consts (staff region), then restore every previous value. */
|
||
async function withRegionConsts<T>(
|
||
regionId: number,
|
||
values: Record<string, string | null>,
|
||
fn: () => Promise<T>
|
||
): Promise<T> {
|
||
const keys = Object.keys(values)
|
||
const previous: Record<string, string | null> = {}
|
||
for (const key of keys) previous[key] = await getRegionConstant(regionId, key)
|
||
|
||
for (const key of keys) await setRegionConstant(regionId, key, values[key])
|
||
try {
|
||
return await fn()
|
||
} finally {
|
||
for (const key of keys) await setRegionConstant(regionId, key, previous[key])
|
||
}
|
||
}
|
||
|
||
async function globalConsts(): Promise<Record<string, string | null>> {
|
||
const superadmin = await superadminClient()
|
||
const rows: any = await superadmin.superadmin.const.getGlobalConstants.query()
|
||
const list: Array<{ key: string; value: string | null }> = Array.isArray(rows) ? rows : []
|
||
return Object.fromEntries(list.map((row) => [row.key, row.value]))
|
||
}
|
||
|
||
describe('common.essentialConsts shape (CACHE-01..05)', () => {
|
||
it('CACHE-01: regionId/boundId/assetsDomain/apiCacheKey are present', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
expect(consts.regionId).toBe(TEST_REGION_ID)
|
||
expect(consts.boundId).toBe(TEST_BOUND_ID)
|
||
expect(typeof consts.assetsDomain).toBe('string')
|
||
expect(consts.assetsDomain.length).toBeGreaterThan(0)
|
||
expect(typeof consts.apiCacheKey).toBe('string')
|
||
expect(consts.apiCacheKey.length).toBeGreaterThan(0)
|
||
})
|
||
|
||
it('CACHE-02: global fields (versionNum/playStoreUrl/appStoreUrl/internalAppVersion) are present', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
expect(typeof consts.versionNum).toBe('string')
|
||
expect(String(consts.versionNum).length).toBeGreaterThan(0)
|
||
expect(typeof consts.playStoreUrl).toBe('string')
|
||
expect(typeof consts.appStoreUrl).toBe('string')
|
||
expect(typeof consts.internalAppVersion).toBe('number')
|
||
})
|
||
|
||
it('CACHE-03: region fields are present', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
for (const key of ['products_version_num', 'availability_version_num', 'slots_version_num'] as const) {
|
||
expect(Number.isFinite(consts[key])).toBe(true)
|
||
}
|
||
for (const key of ['popularItems', 'allItemsOrder', 'supportMobile', 'supportEmail', 'welcomeMessage']) {
|
||
expect(Object.prototype.hasOwnProperty.call(consts, key)).toBe(true)
|
||
}
|
||
})
|
||
|
||
it('CACHE-04: bound fields are numeric', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
for (const key of [
|
||
'freeDeliveryThreshold',
|
||
'deliveryCharge',
|
||
'flashFreeDeliveryThreshold',
|
||
'flashDeliveryCharge',
|
||
]) {
|
||
expect(typeof consts[key]).toBe('number')
|
||
expect(Number.isFinite(consts[key])).toBe(true)
|
||
}
|
||
})
|
||
|
||
it('CACHE-05: isFlashDeliveryEnabled is a boolean', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(typeof consts.isFlashDeliveryEnabled).toBe('boolean')
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts published URLs (CACHE-115)', () => {
|
||
it('CACHE-115: essentialUrls matches the versioned CDN files (API + KV mirror)', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
const urls = consts.essentialUrls
|
||
|
||
expect(urls).toBeTruthy()
|
||
expect(urls!.productsUrl).toBe(productsCacheUrl(consts))
|
||
expect(urls!.storesUrl).toBe(storesCacheUrl(consts))
|
||
expect(urls!.bannersUrl).toBe(bannersCacheUrl(consts))
|
||
expect(urls!.essentialConstsUrl).toBe(essentialConstsCacheUrl(consts))
|
||
expect(urls!.availabilityUrl).toBe(availabilityCacheUrl(consts))
|
||
expect(urls!.slotsUrl).toBe(slotsCacheUrl(consts))
|
||
|
||
// The per-store file cannot be a single URL: the template is completed by
|
||
// the client with the store id.
|
||
expect(urls!.storeDetailUrlTemplate).toContain('{storeId}')
|
||
expect(urls!.storeDetailUrlTemplate.replace('{storeId}', '42')).toBe(
|
||
storeDetailCacheUrl(consts, 42)
|
||
)
|
||
|
||
// Existing bucket layout: availability/slots sit outside the api cache key.
|
||
expect(urls!.availabilityUrl).not.toContain(`/${consts.apiCacheKey}/`)
|
||
expect(urls!.slotsUrl).not.toContain(`/${consts.apiCacheKey}/`)
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts fallbacks (CACHE-06..11)', () => {
|
||
it('CACHE-06: a missing numeric bound const falls back to 200/0/500/69', async () => {
|
||
await withBoundSettings(
|
||
TEST_BOUND_ID,
|
||
{
|
||
freeDeliveryThreshold: null,
|
||
deliveryCharge: null,
|
||
flashFreeDeliveryThreshold: null,
|
||
flashDeliveryCharge: null,
|
||
},
|
||
async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.freeDeliveryThreshold).toBe(SCAFFOLD_BOUND_FALLBACKS.freeDeliveryThreshold)
|
||
expect(consts.deliveryCharge).toBe(SCAFFOLD_BOUND_FALLBACKS.deliveryCharge)
|
||
expect(consts.flashFreeDeliveryThreshold).toBe(SCAFFOLD_BOUND_FALLBACKS.flashFreeDeliveryThreshold)
|
||
expect(consts.flashDeliveryCharge).toBe(SCAFFOLD_BOUND_FALLBACKS.flashDeliveryCharge)
|
||
}
|
||
)
|
||
})
|
||
|
||
it('CACHE-07: an empty-string numeric const uses the fallback', async () => {
|
||
await withBoundSettings(TEST_BOUND_ID, { freeDeliveryThreshold: '' }, async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.freeDeliveryThreshold).toBe(SCAFFOLD_BOUND_FALLBACKS.freeDeliveryThreshold)
|
||
})
|
||
})
|
||
|
||
it('CACHE-08: a non-numeric const uses the fallback', async () => {
|
||
await withBoundSettings(TEST_BOUND_ID, { freeDeliveryThreshold: 'not-a-number' }, async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.freeDeliveryThreshold).toBe(SCAFFOLD_BOUND_FALLBACKS.freeDeliveryThreshold)
|
||
})
|
||
})
|
||
|
||
it('CACHE-09: a boolean const of true/1 parses as true', async () => {
|
||
await withBoundSettings(TEST_BOUND_ID, { isFlashDeliveryEnabled: 'true' }, async () => {
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).isFlashDeliveryEnabled).toBe(true)
|
||
})
|
||
await withBoundSettings(TEST_BOUND_ID, { isFlashDeliveryEnabled: '1' }, async () => {
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).isFlashDeliveryEnabled).toBe(true)
|
||
})
|
||
})
|
||
|
||
it('CACHE-10: false/0/other parse as false', async () => {
|
||
for (const raw of ['false', '0', 'yes']) {
|
||
await withBoundSettings(TEST_BOUND_ID, { isFlashDeliveryEnabled: raw }, async () => {
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).isFlashDeliveryEnabled).toBe(false)
|
||
})
|
||
}
|
||
})
|
||
|
||
it('CACHE-11: a missing string const becomes an empty string', async () => {
|
||
await withRegionConsts(TEST_REGION_ID, { supportMobile: null }, async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.supportMobile).toBe('')
|
||
})
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts resolution (CACHE-12..14)', () => {
|
||
it('CACHE-12: an unknown bound id is 404 "Bound not found"', async () => {
|
||
const { anonClient } = await import('../helpers/sessions')
|
||
await expectTrpcError(
|
||
() => anonClient().common.essentialConsts.query({ boundId: 999_999_999 }),
|
||
'NOT_FOUND',
|
||
'Bound not found'
|
||
)
|
||
})
|
||
|
||
it('CACHE-13: a bound from another region reports that bound’s region', async () => {
|
||
const consts = await getEssentialConsts(TEST_OTHER_BOUND_ID)
|
||
|
||
expect(consts.boundId).toBe(TEST_OTHER_BOUND_ID)
|
||
expect(consts.regionId).toBe(TEST_OTHER_REGION_ID)
|
||
expect(consts.assetsDomain).toBe((await getEssentialConsts(TEST_BOUND_ID)).assetsDomain)
|
||
})
|
||
|
||
it('(current) CACHE-14: bound value wins over a global row of the same key', async () => {
|
||
// The three const tables are scope-disjoint (assertConstantKeysInScope
|
||
// enforces it), so the only observable precedence is a *global* row for a
|
||
// bound-owned key: the bound value is still what the payload reports.
|
||
const superadmin = await superadminClient()
|
||
const boundValue = (await getEssentialConsts(TEST_BOUND_ID)).deliveryCharge
|
||
const original = (await globalConsts())['deliveryCharge'] ?? null
|
||
|
||
try {
|
||
await superadmin.superadmin.const.updateGlobalConstants.mutate({
|
||
constants: [{ key: 'deliveryCharge', value: '999' }],
|
||
})
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.deliveryCharge).toBe(boundValue)
|
||
expect(consts.deliveryCharge).not.toBe(999)
|
||
} finally {
|
||
await superadmin.superadmin.const.updateGlobalConstants.mutate({
|
||
constants: [{ key: 'deliveryCharge', value: original }],
|
||
})
|
||
}
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts backwards compatibility (CACHE-25)', () => {
|
||
it('CACHE-25: no input falls back to bound 1 in region 1', async () => {
|
||
const { anonClient } = await import('../helpers/sessions')
|
||
const consts = await anonClient().common.essentialConsts.query()
|
||
|
||
expect(consts.boundId).toBe(1)
|
||
expect(consts.regionId).toBe(1)
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts KV mirror (CACHE-15..16)', () => {
|
||
it('(current) CACHE-15: a KV miss is not forceable; the payload is complete and stable', async () => {
|
||
// Every const-write path rebuilds the mirror before returning and a fresh
|
||
// region's cache build mirrors its bounds too, so the public API cannot be
|
||
// made to observe a cold KV entry. The reachable contract is that the payload
|
||
// is complete and identical across reads (the miss path backfills the same
|
||
// D1-derived payload).
|
||
const first = await getEssentialConsts(TEST_BOUND_ID)
|
||
const second = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
expect(second).toEqual(first)
|
||
expect(first.assetsDomain).toBeTruthy()
|
||
expect(first.apiCacheKey).toBeTruthy()
|
||
expect(first.regionId).toBe(TEST_REGION_ID)
|
||
})
|
||
|
||
it('(current) CACHE-16: reads are served from the mirror; a change is reflected immediately', async () => {
|
||
// A stale-KV window (a DB value ahead of the mirror) is not reachable through
|
||
// the API: the mutation that changes a bound const rebuilds the mirror in the
|
||
// same request. Assert the reachable contract: the next read already carries
|
||
// the new value, and restoring the value is reflected too.
|
||
const before = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
await withBoundSettings(TEST_BOUND_ID, { deliveryCharge: '4321' }, async () => {
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).deliveryCharge).toBe(4321)
|
||
})
|
||
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).deliveryCharge).toBe(before.deliveryCharge)
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts webview branch (CACHE-17..19)', () => {
|
||
it('(current) CACHE-17: a "raw" host cannot be simulated with fetch', async () => {
|
||
// The procedure switches on `new URL(ctx.req.url).host.includes('raw')`.
|
||
// undici (fetch) ignores a caller-supplied Host and wrangler dev forces it to
|
||
// localhost, so the update-notice branch is unreachable; the normal payload
|
||
// (webviewHtml null, closable) is returned.
|
||
const res = await rawQuery(
|
||
'common.essentialConsts',
|
||
{ boundId: TEST_BOUND_ID },
|
||
{ headers: { host: 'raw.example.com' } }
|
||
)
|
||
const data: any = firstBatchResult(res.body)
|
||
|
||
expect(data.webviewHtml).toBeNull()
|
||
expect(data.isWebviewClosable).toBe(true)
|
||
})
|
||
|
||
it('(current) CACHE-18: a "mf" host cannot be simulated with fetch', async () => {
|
||
const res = await rawQuery(
|
||
'common.essentialConsts',
|
||
{ boundId: TEST_BOUND_ID },
|
||
{ headers: { host: 'mf.example.com' } }
|
||
)
|
||
const data: any = firstBatchResult(res.body)
|
||
|
||
expect(data.webviewHtml).toBeNull()
|
||
expect(data.isWebviewClosable).toBe(true)
|
||
})
|
||
|
||
it('CACHE-19: a normal host returns webviewHtml null and closable true', async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.webviewHtml).toBeNull()
|
||
expect(consts.isWebviewClosable).toBe(true)
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts refresh (CACHE-20..22)', () => {
|
||
it('CACHE-20: a region-const update is reflected in the mirror', async () => {
|
||
const mobile = `9${String(Date.now()).slice(-9)}`
|
||
const email = `e2e-cache-${uniqueSuffix()}@example.com`
|
||
|
||
await withRegionConsts(
|
||
TEST_REGION_ID,
|
||
{ supportMobile: mobile, supportEmail: email },
|
||
async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.supportMobile).toBe(mobile)
|
||
expect(consts.supportEmail).toBe(email)
|
||
}
|
||
)
|
||
})
|
||
|
||
it('CACHE-21: a bound-setting update is reflected in the mirror', async () => {
|
||
await withBoundSettings(
|
||
TEST_BOUND_ID,
|
||
{ deliveryCharge: '77', freeDeliveryThreshold: '777' },
|
||
async () => {
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
expect(consts.deliveryCharge).toBe(77)
|
||
expect(consts.freeDeliveryThreshold).toBe(777)
|
||
}
|
||
)
|
||
})
|
||
|
||
it('CACHE-22: a global-const update is reflected in every bound’s mirror', async () => {
|
||
const superadmin = await superadminClient()
|
||
const original = (await globalConsts())['playStoreUrl'] ?? null
|
||
const next = `https://e2e-${uniqueSuffix()}.example.com/app`
|
||
|
||
try {
|
||
await superadmin.superadmin.const.updateGlobalConstants.mutate({
|
||
constants: [{ key: 'playStoreUrl', value: next }],
|
||
})
|
||
|
||
expect((await getEssentialConsts(TEST_BOUND_ID)).playStoreUrl).toBe(next)
|
||
expect((await getEssentialConsts(TEST_OTHER_BOUND_ID)).playStoreUrl).toBe(next)
|
||
} finally {
|
||
await superadmin.superadmin.const.updateGlobalConstants.mutate({
|
||
constants: [{ key: 'playStoreUrl', value: original }],
|
||
})
|
||
}
|
||
})
|
||
})
|
||
|
||
describe('common.essentialConsts environment + bounds (CACHE-23..24)', () => {
|
||
it('(current) CACHE-23: the env is always configured here (missing-env branch unreachable)', async () => {
|
||
// `getAssetsDomain()` / `getApiCacheKey()` read process env at request time;
|
||
// the live backend always has them, so the "null/empty + actionable message"
|
||
// branch cannot be exercised. Assert the precondition the cache suite needs.
|
||
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
||
|
||
expect(typeof consts.assetsDomain).toBe('string')
|
||
expect(consts.assetsDomain).not.toBe('')
|
||
expect(typeof consts.apiCacheKey).toBe('string')
|
||
expect(consts.apiCacheKey).not.toBe('')
|
||
expect(productsCacheUrl(consts)).toContain(`/regions/${TEST_REGION_ID}/`)
|
||
})
|
||
|
||
it('CACHE-24: a deleted bound drops its KV key and a new bound serves fresh defaults', async () => {
|
||
const superadmin = await superadminClient()
|
||
const geojson = squareGeojson(16.75, 78.02)
|
||
// A high priority keeps the probe bounds out of the region's effective bound.
|
||
const priorityA = String(Date.now())
|
||
const priorityC = String(Date.now() + 1)
|
||
let boundA: number | null = null
|
||
let boundC: number | null = null
|
||
|
||
try {
|
||
const createdA: any = await superadmin.superadmin.regions.createBound.mutate({
|
||
regionId: TEST_REGION_ID,
|
||
description: 'CACHE-24 probe A',
|
||
geojson,
|
||
priority: priorityA,
|
||
})
|
||
boundA = Number(createdA.id)
|
||
|
||
await setSuperadminBoundSetting(boundA, 'deliveryCharge', '555')
|
||
expect((await getEssentialConsts(boundA)).deliveryCharge).toBe(555)
|
||
|
||
await superadmin.superadmin.regions.deleteBound.mutate({ id: boundA })
|
||
// The KV entry is gone and the D1 row is gone: the bound no longer resolves.
|
||
await expectTrpcError(
|
||
() => getEssentialConsts(boundA as number),
|
||
'NOT_FOUND',
|
||
'Bound not found'
|
||
)
|
||
boundA = null
|
||
|
||
const createdC: any = await superadmin.superadmin.regions.createBound.mutate({
|
||
regionId: TEST_REGION_ID,
|
||
description: 'CACHE-24 probe C',
|
||
geojson,
|
||
priority: priorityC,
|
||
})
|
||
boundC = Number(createdC.id)
|
||
|
||
const fresh = await getEssentialConsts(boundC)
|
||
// The new bound serves its seeded defaults, not the deleted bound's 555.
|
||
expect(fresh.boundId).toBe(boundC)
|
||
expect(fresh.deliveryCharge).toBe(20)
|
||
expect(fresh.deliveryCharge).not.toBe(555)
|
||
} finally {
|
||
if (boundC != null) {
|
||
await superadmin.superadmin.regions.deleteBound.mutate({ id: boundC }).catch(() => undefined)
|
||
}
|
||
if (boundA != null) {
|
||
await superadmin.superadmin.regions.deleteBound.mutate({ id: boundA }).catch(() => undefined)
|
||
}
|
||
}
|
||
})
|
||
})
|