263 lines
10 KiB
TypeScript
263 lines
10 KiB
TypeScript
/**
|
|
* CONC-01..10 — concurrency (catalogue §11.3).
|
|
*
|
|
* Two writers are fired with `Promise.all`; the observed outcome is pinned.
|
|
* This local D1 serialises individual statements but not whole check-then-write
|
|
* handlers, and a multi-statement drizzle transaction does not always roll back,
|
|
* so several rows pin "both writers won" as `(current)`.
|
|
*/
|
|
|
|
import { apiClient, errorCode, errorMessage, uniqueSuffix, type ApiClient } from '../helpers/api'
|
|
import { staffClient, superadminClient } from '../helpers/sessions'
|
|
import {
|
|
PASSWORD,
|
|
createAddress,
|
|
createCatalogOrderFixture,
|
|
createCoupon,
|
|
createProduct,
|
|
createStore,
|
|
placeOrder,
|
|
registerThrowawayUser,
|
|
} from '../helpers/fixtures'
|
|
import { TEST_REGION_ID } from '../helpers/env'
|
|
|
|
jest.setTimeout(180_000)
|
|
|
|
const REGION_1 = TEST_REGION_ID
|
|
|
|
interface Outcome {
|
|
ok: boolean
|
|
value?: any
|
|
code?: string
|
|
message?: string
|
|
}
|
|
|
|
async function settle(promises: Array<Promise<any>>): Promise<Outcome[]> {
|
|
const results = await Promise.allSettled(promises)
|
|
return results.map((r) =>
|
|
r.status === 'fulfilled'
|
|
? { ok: true, value: r.value }
|
|
: { ok: false, code: errorCode(r.reason), message: errorMessage(r.reason) }
|
|
)
|
|
}
|
|
|
|
describe('concurrency — order capacity/stock/coupon (CONC-01..03)', () => {
|
|
it('CONC-01 (current): two orders for the same slot both persist (capacity is a boolean flag)', async () => {
|
|
const fx = await createCatalogOrderFixture()
|
|
const call = () =>
|
|
placeOrder(fx.user.token, {
|
|
addressId: fx.address.id,
|
|
skuId: fx.product.skuId,
|
|
slotId: fx.slot.slotId,
|
|
})
|
|
|
|
const outcomes = await settle([call(), call()])
|
|
expect(outcomes.every((o) => o.ok)).toBe(true)
|
|
|
|
const list: any = await apiClient(fx.user.token).user.order.getOrders.query({ page: 1, pageSize: 10 })
|
|
expect(list.pagination.totalCount).toBe(2)
|
|
})
|
|
|
|
it('CONC-02 (current): two orders for the same SKU both persist (no stock counter)', async () => {
|
|
const fx = await createCatalogOrderFixture({ price: 199 })
|
|
const call = () =>
|
|
placeOrder(fx.user.token, {
|
|
addressId: fx.address.id,
|
|
skuId: fx.product.skuId,
|
|
slotId: fx.slot.slotId,
|
|
})
|
|
|
|
const outcomes = await settle([call(), call()])
|
|
expect(outcomes.every((o) => o.ok)).toBe(true)
|
|
|
|
const list: any = await apiClient(fx.user.token).user.order.getOrders.query({ page: 1, pageSize: 10 })
|
|
expect(list.pagination.totalCount).toBe(2)
|
|
})
|
|
|
|
it('CONC-03 (current): two redemptions of a max-1 coupon are not serialised', async () => {
|
|
const fx = await createCatalogOrderFixture({ price: 199 })
|
|
const coupon = await createCoupon({ flatDiscount: 20, minOrder: 1, maxLimitForUser: 1 })
|
|
const call = () =>
|
|
placeOrder(fx.user.token, {
|
|
addressId: fx.address.id,
|
|
skuId: fx.product.skuId,
|
|
slotId: fx.slot.slotId,
|
|
couponIds: [coupon.id],
|
|
})
|
|
|
|
const outcomes = await settle([call(), call()])
|
|
// The per-user usage limit is checked at read time, so at least one request
|
|
// wins; the race can let both through (double redeem).
|
|
expect(outcomes.filter((o) => o.ok).length).toBeGreaterThanOrEqual(1)
|
|
|
|
const list: any = await apiClient(fx.user.token).user.order.getOrders.query({ page: 1, pageSize: 10 })
|
|
expect(list.pagination.totalCount).toBeGreaterThanOrEqual(1)
|
|
})
|
|
})
|
|
|
|
describe('concurrency — writes (CONC-04, 06..08)', () => {
|
|
it('CONC-04 (current): concurrent product edits are not serialised; the SKU list stays intact', async () => {
|
|
const admin = await staffClient()
|
|
const store = await createStore()
|
|
const product = await createProduct({ storeId: store.storeId, price: 199 })
|
|
const details: any = await admin.admin.product.getProductById.query({ id: product.productId })
|
|
const sku = details.product.skus[0]
|
|
|
|
const update = (name: string, price: number) =>
|
|
admin.admin.product.updateProduct.mutate({
|
|
id: product.productId,
|
|
name,
|
|
shortDescription: details.product.shortDescription ?? 'x',
|
|
storeId: product.storeId as number,
|
|
productType: 'item',
|
|
skus: [
|
|
{
|
|
id: sku.id,
|
|
name: sku.name,
|
|
price,
|
|
marketPrice: sku.marketPrice != null ? Number(sku.marketPrice) : null,
|
|
images: [],
|
|
isFlashAvailable: false,
|
|
flashPrice: null,
|
|
isOutOfStock: false,
|
|
isOffer: false,
|
|
isComboOnly: false,
|
|
isSuspended: false,
|
|
features: (sku.features ?? []).map((f: any) => ({
|
|
featureName: f.featureName,
|
|
featureValue: f.featureValue,
|
|
})),
|
|
},
|
|
],
|
|
} as any)
|
|
|
|
const nameA = `E2E CONC A ${uniqueSuffix()}`
|
|
const nameB = `E2E CONC B ${uniqueSuffix()}`
|
|
const outcomes = await settle([update(nameA, 111), update(nameB, 222)])
|
|
// (current) Concurrent edits of one product are not serialised: one writer
|
|
// can win while the other fails with a masked 500 ("Failed to update
|
|
// product") — D1 does not reliably roll back the losing transaction.
|
|
expect(outcomes.filter((o) => o.ok).length).toBeGreaterThanOrEqual(1)
|
|
|
|
const after: any = await admin.admin.product.getProductById.query({ id: product.productId })
|
|
expect([nameA, nameB]).toContain(after.product.name)
|
|
expect(after.product.skus).toHaveLength(1)
|
|
const expectedPrice = after.product.name === nameA ? 111 : 222
|
|
expect(Number(after.product.skus[0].price)).toBe(expectedPrice)
|
|
})
|
|
|
|
it('CONC-06 (current): a duplicate staff name race is a check-then-insert', async () => {
|
|
const sa = await superadminClient()
|
|
const roles: any = await sa.superadmin.staff.roles.query()
|
|
const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id)
|
|
const name = `e2e_conc_${uniqueSuffix().replace(/[^a-z0-9]/gi, '')}`
|
|
const create = () =>
|
|
sa.superadmin.staff.create.mutate({ name, password: PASSWORD, roleId, regionId: REGION_1 })
|
|
|
|
const outcomes = await settle([create(), create()])
|
|
expect(outcomes.filter((o) => o.ok).length).toBeGreaterThanOrEqual(1)
|
|
for (const o of outcomes) {
|
|
if (!o.ok) expect(['CONFLICT', 'INTERNAL_SERVER_ERROR']).toContain(o.code)
|
|
expect(o.message ?? '').not.toMatch(/UNIQUE constraint failed|SQLITE_CONSTRAINT|D1_ERROR/i)
|
|
}
|
|
})
|
|
|
|
it('CONC-07 (current): a duplicate product name race is a check-then-insert', async () => {
|
|
const admin = await staffClient()
|
|
const store = await createStore()
|
|
const name = `E2E CONC Dup ${uniqueSuffix()}`
|
|
const create = () =>
|
|
admin.admin.product.createProduct.mutate({
|
|
name,
|
|
shortDescription: 'dup race',
|
|
storeId: store.storeId,
|
|
productType: 'item',
|
|
skus: [
|
|
{
|
|
name: '1pc',
|
|
price: 100,
|
|
marketPrice: 150,
|
|
images: [],
|
|
isFlashAvailable: false,
|
|
flashPrice: null,
|
|
isOutOfStock: false,
|
|
isOffer: false,
|
|
isComboOnly: false,
|
|
isSuspended: false,
|
|
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
|
},
|
|
],
|
|
} as any)
|
|
|
|
const outcomes = await settle([create(), create()])
|
|
expect(outcomes.filter((o) => o.ok).length).toBeGreaterThanOrEqual(1)
|
|
for (const o of outcomes) {
|
|
if (!o.ok) expect(['BAD_REQUEST', 'CONFLICT', 'INTERNAL_SERVER_ERROR']).toContain(o.code)
|
|
expect(o.message ?? '').not.toMatch(/UNIQUE constraint failed|SQLITE_CONSTRAINT|D1_ERROR/i)
|
|
}
|
|
})
|
|
|
|
it('CONC-08 (current): a duplicate tag name race is a check-then-insert', async () => {
|
|
const admin = await staffClient()
|
|
const tagName = `E2E CONC Tag ${uniqueSuffix()}`
|
|
const create = () => admin.admin.product.createProductTag.mutate({ tagName } as any)
|
|
|
|
const outcomes = await settle([create(), create()])
|
|
expect(outcomes.filter((o) => o.ok).length).toBeGreaterThanOrEqual(1)
|
|
for (const o of outcomes) {
|
|
if (!o.ok) expect(['BAD_REQUEST', 'INTERNAL_SERVER_ERROR']).toContain(o.code)
|
|
expect(o.message ?? '').not.toMatch(/UNIQUE constraint failed|SQLITE_CONSTRAINT|D1_ERROR/i)
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('concurrency — scheduling/tokens/address (CONC-05, 09, 10)', () => {
|
|
it('CONC-05 (current): a regional write does not narrow the global schedule', async () => {
|
|
// Triggering a global write OOMs this seeded workerd, so the global schedule
|
|
// cannot be exercised. The reachable contract: a regional write leaves the
|
|
// superadmin's global product list intact.
|
|
const sa = await superadminClient()
|
|
const before: any = await sa.superadmin.globalProducts.list.query()
|
|
const beforeCount = (before.products ?? []).length
|
|
expect(beforeCount).toBeGreaterThan(0)
|
|
|
|
await createProduct({ price: 123 })
|
|
|
|
const after: any = await sa.superadmin.globalProducts.list.query()
|
|
expect((after.products ?? []).length).toBe(beforeCount)
|
|
})
|
|
|
|
|
|
it('CONC-10 (current): concurrent default flips can leave more than one default', async () => {
|
|
const user = await registerThrowawayUser()
|
|
const first = await createAddress(user.token)
|
|
const second = await createAddress(user.token, { isDefault: true })
|
|
|
|
const rows: any = await apiClient(user.token).user.address.getUserAddresses.query()
|
|
const byId = (id: number) => rows.data.find((a: any) => Number(a.id) === id)
|
|
const setDefault = (id: number) => {
|
|
const a = byId(id)
|
|
return apiClient(user.token).user.address.updateAddress.mutate({
|
|
id,
|
|
regionId: REGION_1,
|
|
name: a.name,
|
|
phone: a.phone,
|
|
addressLine1: a.addressLine1,
|
|
city: a.city,
|
|
state: a.state,
|
|
isDefault: true,
|
|
latitude: a.latitude,
|
|
longitude: a.longitude,
|
|
} as any)
|
|
}
|
|
|
|
const outcomes = await settle([setDefault(first.id), setDefault(second.id)])
|
|
expect(outcomes.every((o) => o.ok)).toBe(true)
|
|
|
|
const after: any = await apiClient(user.token).user.address.getUserAddresses.query()
|
|
const defaults = after.data.filter((a: any) => a.isDefault)
|
|
// clearDefaultAddress + set-one is not atomic, so the race can leave two.
|
|
expect(defaults.length).toBeGreaterThanOrEqual(1)
|
|
expect(defaults.length).toBeLessThanOrEqual(2)
|
|
})
|
|
})
|