Answer a retried feedback submission with the one already saved #24

Merged
Paddy merged 2 commits from fix/feedback-submission-idempotency into master 2026-11-16 17:28:37 +00:00
4 changed files with 38 additions and 13 deletions
Showing only changes of commit adf723419d - Show all commits

No files matched your search

@@ -7,8 +7,11 @@
-- sees an error and taps "absenden" again; the API now finds the stored token
-- and answers with the original submission instead of saving a copy.
--
-- Unique per event, not globally: one visit can switch to another concert's
-- form in the same tab, and that event's submission must still save.
--
-- NULL for every row written before this migration and for any client that
-- sends no token; a UNIQUE index allows any number of NULLs.
ALTER TABLE submissions
ADD COLUMN client_token CHAR(36) NULL AFTER ip_hash,
ADD UNIQUE KEY uq_sub_client_token (client_token);
ADD UNIQUE KEY uq_sub_event_client_token (event_id, client_token);
@@ -59,7 +59,7 @@
* clientToken:
* type: string
* format: uuid
* description: Generated once per form and resent on every retry. A retry whose token is already stored returns the original submissionId instead of saving a duplicate. Optional; a value that isn't a UUID is ignored.
* description: Generated once per form and resent on every retry. A retry whose token is already stored for this event returns the original submissionId instead of saving a duplicate. Optional; a value that isn't a UUID is ignored.
* SubmissionResponse:
* type: object
* properties:
@@ -149,10 +149,16 @@ export const normalizeClientToken = (token: unknown): string | null => {
return typeof token === 'string' && CLIENT_TOKEN_RE.test(token) ? token.toLowerCase() : null;
};
const findSubmissionIdByClientToken = async (clientToken: string): Promise<number | null> => {
// Scoped to the event: the token is per form visit, and one visit can move
// on to another concert's form, so a match for a different event is not a
// retry of this one.
const findSubmissionIdByClientToken = async (clientToken: string, slug: string): Promise<number | null> => {
const conn = await NachklangFeedbackDB.getConnection();
try {
const rows = await conn.query('SELECT submission_id FROM submissions WHERE client_token = ?', [clientToken]);
const rows = await conn.query(
'SELECT s.submission_id FROM submissions s JOIN events e ON e.event_id = s.event_id WHERE s.client_token = ? AND e.slug = ?',
[clientToken, slug]
);
return rows.length > 0 ? rows[0].submission_id : null;
} finally {
await conn.end();
@@ -185,7 +191,7 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
// Checked before eligibility, so a retry still succeeds if the feedback
// window closed in the seconds after the original saved.
if (clientToken) {
const existingId = await findSubmissionIdByClientToken(clientToken);
const existingId = await findSubmissionIdByClientToken(clientToken, slug);
if (existingId !== null) {
logger.info('Feedback submission retry answered with the stored submission', {submissionId: existingId});
return {status: 'OK', submissionId: existingId, newsletterDropped};
@@ -259,9 +265,9 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
} catch (err: any) {
await conn.rollback();
// Two copies of the same retry both got past the lookup above; the
// unique index on client_token let only one of them commit.
// unique index on (event_id, client_token) let only one of them commit.
if (clientToken && err?.code === 'ER_DUP_ENTRY') {
const existingId = await findSubmissionIdByClientToken(clientToken);
const existingId = await findSubmissionIdByClientToken(clientToken, slug);
if (existingId !== null) {
return {status: 'OK', submissionId: existingId, newsletterDropped};
}
+22 -6
View File
@@ -23,12 +23,16 @@ const mockGetEventConfigBySlug = getEventConfigBySlug as Mock;
const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f';
const BODY = {answers: [{eventQuestionId: 26, text: 'Danke!'}], clientToken: TOKEN};
const SLUG = 'sommerkonzert-2026';
const LOOKUP_SQL = 'SELECT s.submission_id FROM submissions s';
// One fake connection serves every query; `existingId` is what a lookup by
// client_token finds, and `insertError` makes the submissions INSERT throw.
const makeConn = ({existingId = null, insertError = null}: {existingId?: number | null; insertError?: any} = {}) => ({
query: vi.fn(async (sql: string) => {
if (sql.startsWith('SELECT submission_id FROM submissions')) {
return existingId === null ? [] : [{submission_id: existingId}];
// client_token finds when it was stored for `existingSlug`, and
// `insertError` makes the submissions INSERT throw.
const makeConn = ({existingId = null, existingSlug = SLUG, insertError = null}: {existingId?: number | null; existingSlug?: string; insertError?: any} = {}) => ({
query: vi.fn(async (sql: string, params: any[] = []) => {
if (sql.startsWith(LOOKUP_SQL)) {
return existingId === null || params[1] !== existingSlug ? [] : [{submission_id: existingId}];
}
if (sql.startsWith('INSERT INTO submissions')) {
if (insertError) throw insertError;
@@ -88,13 +92,25 @@ describe('submitFeedback - client token idempotency', () => {
expect(insert[1]).toContain(TOKEN);
});
it('saves a new submission when the token was only ever used for a different event', async () => {
// Same browser tab, two concerts: the token must not make the second
// event's feedback come back as the first event's submission.
const conn = makeConn({existingId: 82, existingSlug: 'winterkonzert-2026'});
mockGetConnection.mockResolvedValue(conn);
const result = await submitFeedback(SLUG, BODY, 'hash');
expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false});
expect(allQueries(conn).find(([sql]) => sql.startsWith(LOOKUP_SQL))![1]).toEqual([TOKEN, SLUG]);
});
it('ignores a malformed token: no lookup, and the row is stored without one', async () => {
const conn = makeConn();
mockGetConnection.mockResolvedValue(conn);
await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: 'not-a-uuid'}, 'hash');
expect(allQueries(conn).some(([sql]) => sql.startsWith('SELECT submission_id FROM submissions'))).toBe(false);
expect(allQueries(conn).some(([sql]) => sql.startsWith(LOOKUP_SQL))).toBe(false);
const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
expect(insert[1]).not.toContain('not-a-uuid');
expect(insert[1][insert[1].length - 1]).toBeNull();