Store answers atomically and limit word cloud input
- Run the checks and the insert of VoteService::submit() in one transaction with the slide row locked, so double clicks or retries cannot store a vote twice (also covers the Q&A upvote budget and word cloud duplicates). - Limit word cloud terms per request and per participant, and throttle answers per IP and minute (THROTTLE_VOTES_PER_MINUTE, 429 with message). - Treat array values in text fields as empty instead of storing "Array". - Move the throttle helper to AppController for reuse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8b0e82d806
commit
9c532d164f
11 files changed
+224
-50
No files matched your search
+87
-28
@@ -6,6 +6,7 @@ namespace App\Service;
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use Cake\Database\Expression\IdentifierExpression;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
@@ -21,6 +22,9 @@ use Cake\Utility\Security;
|
||||
* exists in the cloud is an upvote – both are stored as the same row.
|
||||
* `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing
|
||||
* word of someone else. Each participant rates a word only once (up or down).
|
||||
* At most MAX_WORDS_PER_REQUEST terms per request and MAX_WORDS per participant and slide.
|
||||
* - checks and insert run in one transaction with the slide row locked (see lockSlide()),
|
||||
* so concurrent or repeated requests cannot store an answer twice.
|
||||
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
|
||||
* includes the deadline of a timed quiz).
|
||||
* - Q&A (see QaService for the stages): `question` (text) only while collecting,
|
||||
@@ -40,6 +44,12 @@ class VoteService
|
||||
public const MAX_TEXT_LENGTH = 500;
|
||||
public const MAX_QA_QUESTIONS = 10;
|
||||
|
||||
/**
|
||||
* Word cloud: terms per request and terms a participant may name or upvote per slide.
|
||||
*/
|
||||
public const MAX_WORDS_PER_REQUEST = 10;
|
||||
public const MAX_WORDS = 50;
|
||||
|
||||
/**
|
||||
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
|
||||
*/
|
||||
@@ -97,31 +107,71 @@ class VoteService
|
||||
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
|
||||
});
|
||||
}
|
||||
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) {
|
||||
throw new VoteException(__('Du hast bereits abgestimmt.'));
|
||||
}
|
||||
// Checks (answered already, upvote budget, duplicates) and the insert run as one unit,
|
||||
// so a double click or a retried request cannot store an answer twice.
|
||||
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $data): void {
|
||||
$this->lockSlide($slide);
|
||||
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) {
|
||||
throw new VoteException(__('Du hast bereits abgestimmt.'));
|
||||
}
|
||||
|
||||
$rows = match ($slide->type) {
|
||||
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
|
||||
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
|
||||
Slide::TYPE_OPEN => $this->openRows($data),
|
||||
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
|
||||
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
|
||||
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
|
||||
Slide::TYPE_ORDER => $this->orderRows($slide, $data),
|
||||
default => throw new VoteException(__('Unbekannter Folientyp.')),
|
||||
};
|
||||
$rows = match ($slide->type) {
|
||||
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
|
||||
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
|
||||
Slide::TYPE_OPEN => $this->openRows($data),
|
||||
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
|
||||
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
|
||||
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
|
||||
Slide::TYPE_ORDER => $this->orderRows($slide, $data),
|
||||
default => throw new VoteException(__('Unbekannter Folientyp.')),
|
||||
};
|
||||
|
||||
$entities = [];
|
||||
foreach ($rows as $row) {
|
||||
$entities[] = $this->Responses->newEntity($row + [
|
||||
'slide_id' => $slide->id,
|
||||
'participant_hash' => $participantHash,
|
||||
]);
|
||||
}
|
||||
if ($entities !== []) {
|
||||
$this->Responses->saveManyOrFail($entities);
|
||||
}
|
||||
$entities = [];
|
||||
foreach ($rows as $row) {
|
||||
$entities[] = $this->Responses->newEntity($row + [
|
||||
'slide_id' => $slide->id,
|
||||
'participant_hash' => $participantHash,
|
||||
]);
|
||||
}
|
||||
if ($entities !== []) {
|
||||
$this->Responses->saveManyOrFail($entities);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialises answers to one slide for the rest of the transaction.
|
||||
*
|
||||
* A no-op write on the slide row (`position = position`) is the portable lock: MySQL/MariaDB
|
||||
* and PostgreSQL lock the row until commit, SQLite takes its write lock before anything is
|
||||
* read. Must be the first statement of the transaction, so later reads see committed answers
|
||||
* of concurrent requests. Neither `modified` nor any value changes.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return void
|
||||
*/
|
||||
protected function lockSlide(Slide $slide): void
|
||||
{
|
||||
$this->fetchTable('Slides')->updateQuery()
|
||||
->set(['position' => new IdentifierExpression('position')])
|
||||
->where(['id' => $slide->id])
|
||||
->execute()
|
||||
->closeCursor();
|
||||
}
|
||||
|
||||
/**
|
||||
* A request field as string; arrays and other non-scalar values count as empty
|
||||
* (instead of being stored as "Array").
|
||||
*
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @param string $key Field
|
||||
* @return string
|
||||
*/
|
||||
protected static function stringField(array $data, string $key): string
|
||||
{
|
||||
$value = $data[$key] ?? '';
|
||||
|
||||
return is_scalar($value) ? (string)$value : '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,7 +277,7 @@ class VoteService
|
||||
if ($stage !== Slide::QA_COLLECT) {
|
||||
throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.'));
|
||||
}
|
||||
$text = trim((string)preg_replace('/\s+/u', ' ', (string)($data['question'] ?? '')));
|
||||
$text = trim((string)preg_replace('/\s+/u', ' ', self::stringField($data, 'question')));
|
||||
if ($text === '') {
|
||||
throw new VoteException(__('Bitte gib eine Frage ein.'));
|
||||
}
|
||||
@@ -328,10 +378,16 @@ class VoteService
|
||||
$existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up'])));
|
||||
$downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true);
|
||||
if (($data['vote'] ?? null) === 'down') {
|
||||
return $this->downvoteRows($slide, (string)($data['word'] ?? ''), $existing, $downvoted);
|
||||
return $this->downvoteRows($slide, self::stringField($data, 'word'), $existing, $downvoted);
|
||||
}
|
||||
|
||||
$input = array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? []));
|
||||
$input = array_filter(
|
||||
array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? [])),
|
||||
fn($word) => is_scalar($word) && trim((string)$word) !== '',
|
||||
);
|
||||
if (count($input) > self::MAX_WORDS_PER_REQUEST) {
|
||||
throw new VoteException(__('Bitte gib höchstens {0} Begriffe auf einmal ein.', self::MAX_WORDS_PER_REQUEST));
|
||||
}
|
||||
$seen = array_fill_keys($existing, true);
|
||||
|
||||
$words = [];
|
||||
@@ -362,6 +418,9 @@ class VoteService
|
||||
default => __('Bitte gib einen Begriff ein.'),
|
||||
});
|
||||
}
|
||||
if (count($existing) + count($words) > self::MAX_WORDS) {
|
||||
throw new VoteException(__('Du kannst bei dieser Frage höchstens {0} Begriffe nennen oder unterstützen.', self::MAX_WORDS));
|
||||
}
|
||||
|
||||
return array_map(fn(string $word) => ['text_value' => $word], $words);
|
||||
}
|
||||
@@ -399,7 +458,7 @@ class VoteService
|
||||
*/
|
||||
protected function openRows(array $data): array
|
||||
{
|
||||
$text = trim((string)($data['text'] ?? ''));
|
||||
$text = trim(self::stringField($data, 'text'));
|
||||
if ($text === '') {
|
||||
throw new VoteException(__('Bitte gib eine Antwort ein.'));
|
||||
}
|
||||
@@ -424,7 +483,7 @@ class VoteService
|
||||
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
|
||||
}
|
||||
// The optional comment is stored in the same row; ignored if the slide has no comment field.
|
||||
$comment = $slide->hasComments() ? trim((string)($data['comment'] ?? '')) : '';
|
||||
$comment = $slide->hasComments() ? trim(self::stringField($data, 'comment')) : '';
|
||||
if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) {
|
||||
throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user