Answer a retried feedback submission with the one already saved
Test and deploy / test-and-deploy (pull_request) Successful in 46s
Test and deploy / test-and-deploy (pull_request) Successful in 46s
When a submission saved but its response never reached the phone, the form showed an error, the visitor tapped "Feedback absenden" again, and a second identical row was stored (seen twice in production: 82/83, 87/88). The form now sends a clientToken, one UUID per visit, on every attempt. A token that is already stored returns the original submissionId and saves nothing; the lookup runs before the eligibility check, so a retry still succeeds if the feedback window closed in between. Two concurrent retries are settled by a UNIQUE index on submissions.client_token: the loser gets ER_DUP_ENTRY, rolls back and returns the winner's id. A missing or non-UUID token behaves as before, so cached copies of the old form still submit. Migration 003 must be applied before this is deployed - the INSERT now writes client_token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
5 files changed
+202
-11
No files matched your search
@@ -0,0 +1,127 @@
|
||||
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
|
||||
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
|
||||
NachklangFeedbackDB: {getConnection: vi.fn()}
|
||||
}));
|
||||
vi.mock('../../src/models/feedback/public/events.public.service.js', () => ({
|
||||
getEventConfigBySlug: vi.fn()
|
||||
}));
|
||||
vi.mock('../../src/models/feedback/integrations/salesforce.service.js', () => ({
|
||||
syncNewsletterSignup: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('../../src/middleware/logger.js', () => ({
|
||||
__esModule: true,
|
||||
default: {info: vi.fn(), error: vi.fn()}
|
||||
}));
|
||||
|
||||
import {NachklangFeedbackDB} from '../../src/models/feedback/Feedback.db.js';
|
||||
import {getEventConfigBySlug} from '../../src/models/feedback/public/events.public.service.js';
|
||||
import {submitFeedback} from '../../src/models/feedback/public/submissions.service.js';
|
||||
|
||||
const mockGetConnection = NachklangFeedbackDB.getConnection as Mock;
|
||||
const mockGetEventConfigBySlug = getEventConfigBySlug as Mock;
|
||||
|
||||
const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f';
|
||||
const BODY = {answers: [{eventQuestionId: 26, text: 'Danke!'}], clientToken: TOKEN};
|
||||
|
||||
// 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}];
|
||||
}
|
||||
if (sql.startsWith('INSERT INTO submissions')) {
|
||||
if (insertError) throw insertError;
|
||||
return [{submission_id: 90}];
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
beginTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
commit: vi.fn().mockResolvedValue(undefined),
|
||||
rollback: vi.fn().mockResolvedValue(undefined),
|
||||
end: vi.fn().mockResolvedValue(undefined)
|
||||
});
|
||||
|
||||
const allQueries = (conn: ReturnType<typeof makeConn>): [string, any[]][] => conn.query.mock.calls as any;
|
||||
|
||||
describe('submitFeedback - client token idempotency', () => {
|
||||
beforeEach(() => {
|
||||
mockGetConnection.mockReset();
|
||||
mockGetEventConfigBySlug.mockReset();
|
||||
mockGetEventConfigBySlug.mockResolvedValue({
|
||||
status: 'OK',
|
||||
eventId: 22,
|
||||
event: {
|
||||
questions: [{eventQuestionId: 26, questionId: 4, type: 'FREE_TEXT', label: 'Sonstiges', position: 0}],
|
||||
songs: []
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the already-saved submission for a repeated token without inserting again', async () => {
|
||||
const conn = makeConn({existingId: 82});
|
||||
mockGetConnection.mockResolvedValue(conn);
|
||||
|
||||
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||
|
||||
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
|
||||
expect(allQueries(conn).some(([sql]) => sql.startsWith('INSERT'))).toBe(false);
|
||||
});
|
||||
|
||||
it('still answers a retry with the saved submission after the feedback window closed', async () => {
|
||||
mockGetConnection.mockResolvedValue(makeConn({existingId: 82}));
|
||||
mockGetEventConfigBySlug.mockResolvedValue({status: 'CLOSED'});
|
||||
|
||||
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||
|
||||
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
|
||||
});
|
||||
|
||||
it('stores a new token, lowercased, on the submissions row', async () => {
|
||||
const conn = makeConn();
|
||||
mockGetConnection.mockResolvedValue(conn);
|
||||
|
||||
const result = await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: TOKEN.toUpperCase()}, 'hash');
|
||||
|
||||
expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false});
|
||||
const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
|
||||
expect(insert[1]).toContain(TOKEN);
|
||||
});
|
||||
|
||||
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);
|
||||
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();
|
||||
});
|
||||
|
||||
it('resolves a concurrent duplicate that loses the race on the unique index to the winning submission', async () => {
|
||||
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
|
||||
const racingConn = makeConn({insertError: dupError});
|
||||
// First lookup (before the INSERT) finds nothing; the one after the
|
||||
// duplicate-key error finds the row the other request committed.
|
||||
const lookupAfterRace = makeConn({existingId: 83});
|
||||
mockGetConnection
|
||||
.mockResolvedValueOnce(makeConn())
|
||||
.mockResolvedValueOnce(racingConn)
|
||||
.mockResolvedValueOnce(lookupAfterRace);
|
||||
|
||||
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
|
||||
|
||||
expect(result).toEqual({status: 'OK', submissionId: 83, newsletterDropped: false});
|
||||
expect(racingConn.rollback).toHaveBeenCalled();
|
||||
expect(racingConn.commit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rethrows a duplicate-key error when the request carried no token', async () => {
|
||||
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
|
||||
mockGetConnection.mockResolvedValue(makeConn({insertError: dupError}));
|
||||
|
||||
await expect(submitFeedback('sommerkonzert-2026', {answers: BODY.answers}, 'hash')).rejects.toThrow('Duplicate entry');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user