diff --git a/src/features/api/payment-processing/package-pricing.ts b/src/features/api/payment-processing/package-pricing.ts index bb19b78385..83439611a2 100644 --- a/src/features/api/payment-processing/package-pricing.ts +++ b/src/features/api/payment-processing/package-pricing.ts @@ -30,7 +30,7 @@ import { } from "#shared/booking/signed-metadata.ts"; import { childIdsMatching } from "#shared/child-parents.ts"; import { - getPackageGroupById, + getPackageDisplaysByIds, loadPackageMemberPricing, } from "#shared/db/groups.ts"; import { @@ -86,8 +86,10 @@ export const loadPackagePricingByGroup = async ( intent: BookingIntent, ): Promise> => { const pricingByGroup = new Map(); - for (const groupId of lineGroupIds(intent.items)) { - if ((await getPackageGroupById(groupId)) === null) continue; + const groupIds = [...lineGroupIds(intent.items)]; + const packageDisplays = await getPackageDisplaysByIds(groupIds); + for (const groupId of groupIds) { + if (!packageDisplays.has(groupId)) continue; const pricing = await loadPackageMemberPricing(groupId); pricingByGroup.set(groupId, { dayPriceMap: pricing.dayPrices, diff --git a/src/features/public/pages.ts b/src/features/public/pages.ts index 6179f8fc52..cd4e2d0252 100644 --- a/src/features/public/pages.ts +++ b/src/features/public/pages.ts @@ -12,9 +12,8 @@ import { redirect, } from "#routes/response.ts"; import { BOTPOISON_FIELD, verifyBotpoisonSolution } from "#shared/botpoison.ts"; -import { isBotpoisonEnabled } from "#shared/config.ts"; +import { getBotpoisonPublicKey, isBotpoisonEnabled } from "#shared/config.ts"; import { - contactFormPublicKey, isContactFormActive, sendContactMessage, } from "#shared/contact-form.ts"; @@ -262,7 +261,7 @@ const renderContactPage = async (request: Request): Promise => { const flash = applyFlash(request); return htmlResponse( contactPage({ - botpoisonPublicKey: contactFormPublicKey(), + botpoisonPublicKey: getBotpoisonPublicKey(), content: settings.contactPageText || null, ...(flash.error !== undefined ? { error: flash.error } : {}), formActive, diff --git a/src/shared/boot-checks.ts b/src/shared/boot-checks.ts index 738ea83121..30b001fe9a 100644 --- a/src/shared/boot-checks.ts +++ b/src/shared/boot-checks.ts @@ -37,6 +37,5 @@ export const BOOT_CHECKS: readonly BootCheck[] = [ ]; export const validateBootChecks = (): void => { - validateEncryptionKey(); - validateOptionalMainInstanceKey(); + for (const check of BOOT_CHECKS) check.run(); }; diff --git a/src/shared/contact-form.ts b/src/shared/contact-form.ts index e99c742419..ebdc9d65a5 100644 --- a/src/shared/contact-form.ts +++ b/src/shared/contact-form.ts @@ -15,7 +15,7 @@ * submitter, with anti-spoof handling) lives here. */ -import { getBotpoisonPublicKey, getEffectiveDomain } from "#shared/config.ts"; +import { getEffectiveDomain } from "#shared/config.ts"; import { settings } from "#shared/db/settings.ts"; import { deliverMessage, @@ -34,10 +34,6 @@ import { export const isContactFormActive = (): boolean => settings.contactFormEnabled && settings.businessEmail !== ""; -/** Public Botpoison key to embed in the form for the browser widget. Empty when - * Botpoison is not configured, in which case no widget is shown. */ -export const contactFormPublicKey = (): string => getBotpoisonPublicKey(); - /** Warning prepended when the submitter claimed an address on the owner's own * business email host. */ const SPOOF_BUSINESS_WARNING = diff --git a/src/shared/cookies.ts b/src/shared/cookies.ts index 24e26a7c24..e422bcf28a 100644 --- a/src/shared/cookies.ts +++ b/src/shared/cookies.ts @@ -2,25 +2,21 @@ import { isSecureMode } from "#shared/config.ts"; import type { Flash } from "#shared/flash-context.ts"; import { SESSION_MAX_AGE_S } from "#shared/limits.ts"; -export { isSecureMode }; - const secureAttribute = (): string => (isSecureMode() ? "; Secure" : ""); -const sessionCookieName = (): string => +export const getSessionCookieName = (): string => isSecureMode() ? "__Host-session" : "session"; -export const getSessionCookieName = (): string => sessionCookieName(); - export const buildSessionCookie = ( token: string, options?: { maxAge?: number }, ): string => { const maxAge = options?.maxAge ?? SESSION_MAX_AGE_S; - return `${sessionCookieName()}=${token}; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=${maxAge}`; + return `${getSessionCookieName()}=${token}; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=${maxAge}`; }; export const clearSessionCookie = (): string => - `${sessionCookieName()}=; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=0`; + `${getSessionCookieName()}=; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=0`; /** Cookie name prefix for flash messages (keyed by per-request ID) */ const FLASH_COOKIE_PREFIX = "flash_"; diff --git a/src/shared/db/attributes.ts b/src/shared/db/attributes.ts index 40e332a0e3..c49489d5c4 100644 --- a/src/shared/db/attributes.ts +++ b/src/shared/db/attributes.ts @@ -14,6 +14,7 @@ import { inPlaceholders, nextSortOrder, queryAll, + queryIdColumn, queryOne, } from "#shared/db/client.ts"; import { @@ -198,9 +199,6 @@ const buildAttributeGroups = ( )(rows).values(), ]; -const queryIds = async (sql: string): Promise => - map((row: { id: number }) => row.id)(await queryAll<{ id: number }>(sql)); - const groupAttributeRows = async ( rows: JoinedAttributeRow[], ): Promise => @@ -245,10 +243,10 @@ export const getAttributeId = async (id: number): Promise => )?.id ?? null; export const getAttributeIdsOrdered = async (): Promise => - queryIds("SELECT id FROM attributes ORDER BY sort_order, id"); + queryIdColumn("SELECT id FROM attributes ORDER BY sort_order, id"); export const getAllAttributeOptionIds = async (): Promise> => - new Set(await queryIds("SELECT id FROM attribute_options")); + new Set(await queryIdColumn("SELECT id FROM attribute_options")); type OptionListingRow = StoredTableProjectionRow< Listing, diff --git a/src/shared/db/groups.ts b/src/shared/db/groups.ts index f0ca01dce3..f5c6b176e3 100644 --- a/src/shared/db/groups.ts +++ b/src/shared/db/groups.ts @@ -48,7 +48,11 @@ import { import { listingProjectionSql } from "#shared/db/listings/sql.ts"; import { envNameSource, queryAndMap, rowsByIds } from "#shared/db/query.ts"; import { isSlugTakenAnywhere } from "#shared/db/slug-registry.ts"; -import { col } from "#shared/db/table.ts"; +import { + col, + defineTableProjection, + type StoredTableProjectionRow, +} from "#shared/db/table.ts"; import { type PackageChildEdgeBlock, type PackageMemberBlock, @@ -123,18 +127,32 @@ const rawGroupsTable = defineIdTable("groups", { terms_and_conditions: col.encryptedText(encrypt, decrypt), }); +const packageDisplayProjection = defineTableProjection(rawGroupsTable, [ + "id", + "hide_package_listings", + "name", +]); +type StoredPackageDisplay = StoredTableProjectionRow< + Group, + typeof packageDisplayProjection.columns +>; + /** Execute a query and decrypt the resulting group rows */ const queryGroups = queryAndMap((row) => rawGroupsTable.fromDb(row), ); -const GROUP_COLUMNS = rawGroupsTable.columns.join(", "); +const GROUP_COLUMNS = rawGroupsTable.columns + .map((column) => `groupRecord.${column}`) + .join(", "); export const groups = cachedEntityTable( "groups", rawGroupsTable, { fetchAll: () => - queryGroups(`SELECT ${GROUP_COLUMNS} FROM groups ORDER BY id ASC`), + queryGroups( + `SELECT ${GROUP_COLUMNS} FROM groups AS groupRecord ORDER BY groupRecord.id ASC`, + ), idOf: (g) => g.id, keyOf: (g) => g.slug_index, ttlMs: GROUPS_CACHE_TTL_MS, @@ -191,35 +209,6 @@ export const isGroupSlugTaken = ( excludeGroupId ? { id: excludeGroupId, table: "groups" } : undefined, ); -/** WHERE fragment matching listings that are members of the given group, via the - * group_listings join table (subquery form avoids duplicate rows). */ -const IN_GROUP_SQL = - "listing.id IN (SELECT listing_id FROM group_listings WHERE group_id = ?)"; - -/** Query listings in a group with attendee counts, optionally filtering to active only */ -const queryGroupListings = ( - groupId: number, - activeOnly: boolean, -): Promise => - queryListingsWithCounts( - activeOnly - ? `WHERE listing.active = 1 AND ${IN_GROUP_SQL}` - : `WHERE ${IN_GROUP_SQL}`, - [groupId], - ); - -/** One group's members with attendee counts; `activeOnly` gates the public - * liveness view (active members only) from the full list (active + inactive). */ -const listingsInGroup = - (activeOnly: boolean) => - (groupId: number): Promise => - queryGroupListings(groupId, activeOnly); - -/** - * Get active listings in a group with attendee counts. - */ -export const getActiveListingsByGroupId = listingsInGroup(true); - /** * Members of SEVERAL groups at once, keyed by group id — the batched form of the * single-group loaders for a multi-group surface. A page with many group leaves @@ -269,6 +258,21 @@ export const getListingsByGroupIds = async ( ); }; +/** One group's entry from the shared one-or-many membership query. */ +type LoadGroupListings = (groupId: number) => Promise; + +const listingsInGroup = + (activeOnly: boolean) => + async (groupId: number): Promise => + requiredMapValue( + await getListingsByGroupIds([groupId], activeOnly), + groupId, + "Missing group listing membership", + ); + +export const getActiveListingsByGroupId: LoadGroupListings = + listingsInGroup(true); + /** Does a group row exist? The add-item revalidation's single-row check — no * name decryption, never the whole table. */ export const groupExists = (id: number): Promise => @@ -277,7 +281,7 @@ export const groupExists = (id: number): Promise => /** * Get all listings in a group with attendee counts (including inactive). */ -export const getListingsByGroupId = listingsInGroup(false); +export const getListingsByGroupId: LoadGroupListings = listingsInGroup(false); /** * Validate that a listing is compatible with a group's existing listings. @@ -480,32 +484,6 @@ export const packageMembersError = async ( * name on tickets/emails. */ export type PackageDisplay = { name: string; hideListings: boolean }; -/** The package display for a booking's PERSISTED `package_group_id`, or null when - * the id is 0 (not a package) or names a group that no longer exists or is not a - * package. Grouping on the stored id — set on every booking row of one package - * checkout — is exact: a standalone order of the same listings carries id 0, so - * it is never mistaken for the package. The group's name is decrypted on the way - * out. */ -/** Load a group by id only when it is a live package, else null. The one home - * for "this id names a package group" — a non-positive id, a missing group, or a - * non-package group all read as null. */ -export const getPackageGroupById = async ( - groupId: number, -): Promise => { - if (groupId <= 0) return null; - const group = await groups.table.findById(groupId); - return group?.is_package ? group : null; -}; - -export const getPackageDisplayById = async ( - groupId: number, -): Promise => { - const group = await getPackageGroupById(groupId); - return group === null - ? null - : { hideListings: group.hide_package_listings, name: group.name }; -}; - /** Whether any booking row is stamped with this package's group id — sold * tickets whose display (and hidden-member concealment) resolves through the * live package row. Refund placeholders (quantity 0) don't count. */ @@ -521,16 +499,28 @@ export const hasPackageBookings = (groupId: number): Promise => * the ticket view collapse each token's package rows into one card per package, * so an attendee holding both a package booking and a standalone one (e.g. after * an attendee merge) doesn't fall back to per-row cards that leak a hidden member. - * Groups are cached, so the per-id resolution is cheap. */ + * Groups are resolved together from their shared cache. */ export const getPackageDisplaysByIds = async ( groupIds: readonly number[], ): Promise> => { - const result = new Map(); - for (const id of new Set(groupIds)) { - const display = await getPackageDisplayById(id); - if (display) result.set(id, display); - } - return result; + const packageGroups = await packageDisplayProjection.readAll( + await rowsByIds( + [...new Set(groupIds)].filter((groupId) => groupId > 0), + (placeholders) => + `SELECT ${packageDisplayProjection.columnsSql("groupRecord")} + FROM groups AS groupRecord + WHERE groupRecord.id IN (${placeholders}) AND groupRecord.is_package = 1`, + ), + ); + return new Map( + packageGroups.map((group) => [ + group.id, + { + hideListings: group.hide_package_listings, + name: group.name, + }, + ]), + ); }; /** The package displays behind a set of booked rows — each row's attendee names diff --git a/src/shared/db/link-table.ts b/src/shared/db/link-table.ts index a6e5f4b526..abe8d7801f 100644 --- a/src/shared/db/link-table.ts +++ b/src/shared/db/link-table.ts @@ -154,9 +154,7 @@ export const linkTableSide = ( ), setIds: (keyId, ids) => executeBatch(replaceStatements(keyId, ids)), setIdsTx: async (tx, keyId, ids) => { - for (const stmt of replaceStatements(keyId, ids)) { - await tx.execute(stmt); - } + await tx.batch(replaceStatements(keyId, ids)); }, }; }; diff --git a/src/shared/db/questions/strings.ts b/src/shared/db/questions/strings.ts index a268c528d6..9636fb16a2 100644 --- a/src/shared/db/questions/strings.ts +++ b/src/shared/db/questions/strings.ts @@ -88,21 +88,15 @@ export const prepareStringRows = async ( ); }; -/** Run the interning statements and return the trailing SELECT's result. When a - * `tx` is given, each statement runs on the caller's open transaction via - * `tx.execute`; otherwise as one `executeBatchWithResults` write batch. Either - * way the SELECT shares the INSERT's transaction, preserving the - * read-your-writes invariant the id resolution depends on. */ +/** Run the interning statements together and return the trailing SELECT. */ const runInternStatements = async ( statements: SqlStatement[], tx?: TxScope, ): Promise => { - if (!tx) return (await executeBatchWithResults(statements)).at(-1)!; - // Run each statement on the open transaction; the trailing SELECT sees the - // rows the INSERT OR IGNORE just wrote in that same transaction. - let result: ResultSet | undefined; - for (const stmt of statements) result = await tx.execute(stmt); - return result!; + const results = await (tx + ? tx.batch(statements) + : executeBatchWithResults(statements)); + return results.at(-1)!; }; /** @@ -111,8 +105,8 @@ const runInternStatements = async ( * just-written rows: a brand-new string's id read from a replica that hasn't * replicated the insert comes back missing, so the id resolves to undefined and * the value is silently lost. When `tx` is given each statement runs on the - * caller's open transaction via `tx.execute`, so the SELECT sees the INSERT's - * rows within that transaction; otherwise one `executeBatchWithResults` write + * caller's open transaction, so the SELECT sees the INSERT's rows within that + * transaction; otherwise one `executeBatchWithResults` write * batch is a single primary-pinned transaction that holds the same invariant. * * The per-text `INSERT OR IGNORE` values are batched into one multi-row @@ -160,7 +154,7 @@ export const internStringRows = async ( * Intern a list of free-text answers, returning the `text → id` map. Encrypts * and HMAC-indexes each unique text, then inserts-or-ignores, refreshes * `created`, and reads the ids back in one atomic batch. When `tx` is given, - * every statement runs on the caller's open transaction via `tx.execute` (so + * every statement runs together on the caller's open transaction (so * the read-your-writes SELECT shares the INSERT's transaction); otherwise as * one `executeBatchWithResults` write batch. * diff --git a/src/shared/db/users.ts b/src/shared/db/users.ts index 0bba01ad41..7172b42597 100644 --- a/src/shared/db/users.ts +++ b/src/shared/db/users.ts @@ -88,7 +88,7 @@ export const onUsersInvalidated = (listener: () => void): void => { usersInvalidationListeners.push(listener); }; -const loadAllUsers = (): Promise => usersCache.getAll(); +export const getAllUsers = (): Promise => usersCache.getAll(); registerCache(() => ({ entries: usersCache.size(), name: "users" })); @@ -267,11 +267,6 @@ export const isUsernameTaken = async (username: string): Promise => { return user !== null; }; -/** - * Get all users (for admin user management page, from cache) - */ -export const getAllUsers = (): Promise => loadAllUsers(); - /** Get the minimal encrypted user fields needed to show assignable users. */ export const getUserDisplayFields = (): Promise => queryAll(USER_DISPLAY_SELECT); diff --git a/src/shared/package-privacy.ts b/src/shared/package-privacy.ts index 9805201c4d..51db148b9d 100644 --- a/src/shared/package-privacy.ts +++ b/src/shared/package-privacy.ts @@ -1,5 +1,5 @@ import { - getPackageDisplayById, + getPackageDisplaysByIds, type PackageDisplay, } from "#shared/db/groups.ts"; @@ -79,12 +79,11 @@ export const concealMemberNames = ( export const resolveNamesConcealed = async ( packageGroupIds: Iterable, ): Promise => { - for (const groupId of new Set(packageGroupIds)) { - if ((await getPackageDisplayById(groupId))?.hideListings ?? true) { - return true; - } - } - return false; + const groupIds = [...new Set(packageGroupIds)]; + const displays = await getPackageDisplaysByIds(groupIds); + return groupIds.some( + (groupId) => displays.get(groupId)?.hideListings ?? true, + ); }; /** The stand-in names concealing a page's hidden bundles, for pages selling diff --git a/src/shared/settings-nags.ts b/src/shared/settings-nags.ts index c7c63e03d1..f3015d03ef 100644 --- a/src/shared/settings-nags.ts +++ b/src/shared/settings-nags.ts @@ -8,7 +8,7 @@ import type { NagItem } from "#shared/types.ts"; * Items are returned in the order: payment-provider, business-email, domain. * An empty array means there are no pending nags. */ -export const getBaseSettingsNagItems = (): NagItem[] => { +export const getSettingsNagItems = (): NagItem[] => { const items: NagItem[] = []; if (settings.paymentProviderSetting === null) { @@ -44,10 +44,8 @@ export const getBaseSettingsNagItems = (): NagItem[] => { return items; }; -export const getSettingsNagItems = (): NagItem[] => getBaseSettingsNagItems(); - export const getSettingsNagItemsForOwner = async (): Promise => { - const items = getBaseSettingsNagItems(); + const items = getSettingsNagItems(); const superuser = await getSuperuserState(); if (superuser.available && superuser.choice === "" && !superuser.activated) { items.push({ diff --git a/test/integration/servicing/atomicity.test.ts b/test/integration/servicing/atomicity.test.ts index d3cfc8163a..222338cb37 100644 --- a/test/integration/servicing/atomicity.test.ts +++ b/test/integration/servicing/atomicity.test.ts @@ -18,7 +18,7 @@ import { createDailyTestListing, createTestListing, } from "#test-utils/db-helpers/listings.ts"; -import { withPoisonedTransactionExecute } from "#test-utils/db-poison.ts"; +import { withPoisonedTransactionWrite } from "#test-utils/db-poison.ts"; import { createServicingHold, createTestServicingEvent, @@ -32,7 +32,7 @@ import { /** Fail the FIRST `attendee_answers` write (the answer save), so the * create/update compensation runs. */ -const withAnswerSaveFailure = withPoisonedTransactionExecute( +const withAnswerSaveFailure = withPoisonedTransactionWrite( (sql) => sql.includes("attendee_answers"), "answer save boom", ); @@ -43,7 +43,7 @@ const withAnswerSaveFailure = withPoisonedTransactionExecute( * old answers, then the re-insert fails and rolls the delete back, so the * compensation must restore the WHOLE prior answer set (choice + free-text), * not just its choice half. */ -const withAnswerInsertFailure = withPoisonedTransactionExecute( +const withAnswerInsertFailure = withPoisonedTransactionWrite( (sql) => sql.includes("INSERT INTO attendee_answers"), "answer insert boom", ); diff --git a/test/lib/server-questions/listing-questions.test.ts b/test/lib/server-questions/listing-questions.test.ts index 0ad819bfa1..ffcd4e092d 100644 --- a/test/lib/server-questions/listing-questions.test.ts +++ b/test/lib/server-questions/listing-questions.test.ts @@ -11,7 +11,7 @@ import { } from "#test-utils/assertions.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; -import { withPoisonedTransactionExecute } from "#test-utils/db-poison.ts"; +import { withPoisonedTransactionWrite } from "#test-utils/db-poison.ts"; import { mockFormRequest } from "#test-utils/mocks.ts"; import { adminFormPost, @@ -101,7 +101,7 @@ describeWithEnv("server (admin questions)", { db: true }, () => { test("rolls back assign-all when saving listing links fails", async () => { const listing = await createTestListing({ name: "Rollback listing" }); const qId = await createQuestion("Rollback assignment?"); - const failLinkInsert = withPoisonedTransactionExecute( + const failLinkInsert = withPoisonedTransactionWrite( (sql) => sql.includes("INSERT INTO listing_questions"), "link insert failed", ); diff --git a/test/scripts/mutation-isolation-supervisor.test.ts b/test/scripts/mutation-isolation-supervisor.test.ts index 2c4a29be8f..022c10cdd8 100644 --- a/test/scripts/mutation-isolation-supervisor.test.ts +++ b/test/scripts/mutation-isolation-supervisor.test.ts @@ -454,13 +454,11 @@ describe("mutation isolation supervisor commands", () => { await withTempDir(async (root) => { await writeFakeMutationScript(root, "await new Promise(() => {});\n"); - const originalKill = Deno.kill; await withCapturedStopChild(async (getStopChild) => { const run = captureSimpleSnapshotMutation(root); - const record = await waitForRunningRecord(root); + await waitForRunningRecord(root); getStopChild()?.(); - originalKill(record.pid!, "SIGKILL"); await run; const finished = await readOnlyRunRecord(root); diff --git a/test/shared/contact-form.test.ts b/test/shared/contact-form.test.ts index 9e44b878e3..45d6e19071 100644 --- a/test/shared/contact-form.test.ts +++ b/test/shared/contact-form.test.ts @@ -2,7 +2,6 @@ import { expect } from "@std/expect"; import { afterEach, beforeEach, describe, it as test } from "@std/testing/bdd"; import { setEffectiveDomainForTest } from "#shared/config.ts"; import { - contactFormPublicKey, isContactFormActive, sendContactMessage, } from "#shared/contact-form.ts"; @@ -61,16 +60,6 @@ describe("contact form availability", () => { }); expect(isContactFormActive()).toBe(false); }); - - test("contactFormPublicKey returns the public env key when set", () => { - sandbox.setEnv(BOTH_KEYS); - expect(contactFormPublicKey()).toBe("pk_test_public"); - }); - - test("contactFormPublicKey is empty when Botpoison is not configured", () => { - sandbox.setEnv(NO_KEYS); - expect(contactFormPublicKey()).toBe(""); - }); }); describe("sendContactMessage", () => { diff --git a/test/shared/cookies.test.ts b/test/shared/cookies.test.ts index 77b6a4ad2b..92e61ef890 100644 --- a/test/shared/cookies.test.ts +++ b/test/shared/cookies.test.ts @@ -2,6 +2,7 @@ import { expect } from "@std/expect"; import { afterEach, describe, it as test } from "@std/testing/bdd"; import { parseCookies } from "#routes/url.ts"; import { + isSecureMode, resetEffectiveDomain, seedEffectiveDomainHost, setEffectiveDomainForTest, @@ -12,7 +13,6 @@ import { clearFlashCookie, clearSessionCookie, getSessionCookieName, - isSecureMode, parseFlashValue, } from "#shared/cookies.ts"; diff --git a/test/shared/db/groups.test.ts b/test/shared/db/groups.test.ts index 857711e290..36222aebd7 100644 --- a/test/shared/db/groups.test.ts +++ b/test/shared/db/groups.test.ts @@ -20,7 +20,7 @@ import { getGroupPackagePrices, getGroupPackagePricesByGroupIds, getListingsByGroupIds, - getPackageDisplayById, + getPackageDisplaysByIds, groups, isGroupSlugTaken, listingGroups, @@ -32,6 +32,7 @@ import { describeWithEnv } from "#test-utils/db.ts"; import { bookAttendee } from "#test-utils/db-helpers/attendee-payments.ts"; import { createTestGroup } from "#test-utils/db-helpers/groups.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; +import { runAndCountRoundTrips } from "#test-utils/query-log.ts"; describeWithEnv("db > groups", { db: true, triggers: true }, () => { /** Create a capped group with two listings (each with listing-level max of 10). */ @@ -648,44 +649,79 @@ describeWithEnv("db > groups", { db: true, triggers: true }, () => { }); }); - describe("getPackageDisplayById", () => { - test("returns the package display for an is_package group id", async () => { + describe("getPackageDisplaysByIds", () => { + test("loads several package displays in one round trip", async () => { const pkg = await createTestGroup({ isPackage: true, name: "Bundle", slug: "bundle-disp", }); - expect(await getPackageDisplayById(pkg.id)).toEqual({ - hideListings: false, - name: "Bundle", - }); - }); - - test("carries the group's hide-listings flag", async () => { - const pkg = await createTestGroup({ + const hidden = await createTestGroup({ isPackage: true, name: "Hidden Bundle", slug: "hidden-bundle-disp", }); - await groups.table.update(pkg.id, { hidePackageListings: true }); - expect(await getPackageDisplayById(pkg.id)).toEqual({ - hideListings: true, - name: "Hidden Bundle", - }); + await groups.table.update(hidden.id, { hidePackageListings: true }); + const regular = await createTestGroup({ + name: "Regular", + slug: "regular-disp", + }); + const { roundTrips, value } = await runAndCountRoundTrips(() => + getPackageDisplaysByIds([ + pkg.id, + hidden.id, + regular.id, + pkg.id, + 0, + -1, + 987654, + ]), + ); + + expect(roundTrips).toBe(1); + expect(value).toEqual( + new Map([ + [pkg.id, { hideListings: false, name: "Bundle" }], + [hidden.id, { hideListings: true, name: "Hidden Bundle" }], + ]), + ); }); - test("returns null for 0 (not a package) and negative ids", async () => { - expect(await getPackageDisplayById(0)).toBeNull(); - expect(await getPackageDisplayById(-1)).toBeNull(); + test("returns no displays when no ids are requested", async () => { + const { roundTrips, value } = await runAndCountRoundTrips(() => + getPackageDisplaysByIds([]), + ); + + expect(roundTrips).toBe(0); + expect(value).toEqual(new Map()); }); - test("returns null for a non-package group", async () => { - const regular = await createTestGroup({ name: "Reg", slug: "reg-disp" }); - expect(await getPackageDisplayById(regular.id)).toBeNull(); + test("does not query for standalone package markers", async () => { + const { roundTrips, value } = await runAndCountRoundTrips(() => + getPackageDisplaysByIds([0, 0, -1]), + ); + + expect(roundTrips).toBe(0); + expect(value).toEqual(new Map()); }); - test("returns null for a group id that no longer exists", async () => { - expect(await getPackageDisplayById(987654)).toBeNull(); + test("reflects package changes after cache invalidation", async () => { + const pkg = await createTestGroup({ + isPackage: true, + name: "Changed Bundle", + slug: "changed-bundle-disp", + }); + expect((await getPackageDisplaysByIds([pkg.id])).get(pkg.id)).toEqual({ + hideListings: false, + name: "Changed Bundle", + }); + + await groups.table.update(pkg.id, { hidePackageListings: true }); + + expect((await getPackageDisplaysByIds([pkg.id])).get(pkg.id)).toEqual({ + hideListings: true, + name: "Changed Bundle", + }); }); }); diff --git a/test/shared/db/questions/attendee-answers.test.ts b/test/shared/db/questions/attendee-answers.test.ts index e54e392fc9..58be03dfc4 100644 --- a/test/shared/db/questions/attendee-answers.test.ts +++ b/test/shared/db/questions/attendee-answers.test.ts @@ -13,7 +13,7 @@ import { nowIso } from "#shared/now.ts"; import { getTestPrivateKey } from "#test-utils/crypto.ts"; import { describeWithEnv } from "#test-utils/db.ts"; import { createTestListing } from "#test-utils/db-helpers/listings.ts"; -import { withPoisonedTransactionExecute } from "#test-utils/db-poison.ts"; +import { withPoisonedTransactionWrite } from "#test-utils/db-poison.ts"; import { expectRejects } from "#test-utils/servicing.ts"; import { addAnswer, @@ -169,7 +169,7 @@ describeWithEnv("custom questions", { db: true }, () => { const { a1, a2, att } = await seedColourAttendeeWithRed(); expect(await choiceAnswersFor(att)).toEqual([a1.id]); - await withPoisonedTransactionExecute( + await withPoisonedTransactionWrite( (sql) => sql.includes("INSERT INTO attendee_answers"), "insert boom", )(async () => { @@ -198,7 +198,7 @@ describeWithEnv("custom questions", { db: true }, () => { "Keep me", ); - await withPoisonedTransactionExecute( + await withPoisonedTransactionWrite( (sql) => sql.includes("INSERT INTO attendee_answers"), "insert boom", )(async () => { diff --git a/test/test-utils/db-poison.ts b/test/test-utils/db-poison.ts index b35c104f13..d7f06cbd98 100644 --- a/test/test-utils/db-poison.ts +++ b/test/test-utils/db-poison.ts @@ -1,8 +1,8 @@ import { getDb } from "#shared/db/client.ts"; /** - * Reject the first transactional `tx.execute` whose SQL matches `matches`, then - * delegate every subsequent execute to the real tx — so the failure lands + * Reject the first transactional statement whose SQL matches `matches`, then + * delegate every subsequent write to the real tx — so the failure lands * mid-flow (after the in-transaction DELETE ran, for `saveAttendeeAnswers`) and * the caller's rollback/compensation runs against a working client. * @@ -10,10 +10,9 @@ import { getDb } from "#shared/db/client.ts"; * frozen, but the client instance's method is configurable), then restores it * in `finally`. `saveAttendeeAnswers` runs its DELETE + string interning + * INSERT inside one `withTransaction`, so a poison that intercepts - * `db.transaction`'s `execute` is what reaches its writes; a `db.batch` poison - * would no longer fire because the answer save stopped batching. + * `db.transaction` is what reaches its writes. */ -export const withPoisonedTransactionExecute = +export const withPoisonedTransactionWrite = (matches: (sql: string) => boolean, message: string) => async (body: () => Promise): Promise => { const db = getDb(); @@ -21,7 +20,16 @@ export const withPoisonedTransactionExecute = let poisoned = true; db.transaction = (async (mode: "read" | "write" = "write") => { const tx = await realTransaction(mode); + const realBatch = tx.batch.bind(tx); const realExecute = tx.execute.bind(tx); + tx.batch = ((statements: Array<{ sql: string }>) => { + const matched = statements.find((statement) => matches(statement.sql)); + if (poisoned && matched) { + poisoned = false; + return Promise.reject(new Error(message)); + } + return realBatch(statements as never); + }) as typeof tx.batch; tx.execute = ((stmt: { sql: string }) => { if (poisoned && matches(stmt.sql)) { poisoned = false;