Merge pull request 'Store answers atomically and limit word cloud input' (#31) from fix/atomic-votes into main
CI / Deploy / test (push) Successful in 52s
CI / Deploy / deploy (push) Successful in 4s

Reviewed-on: #31
This commit was merged in pull request #31.
This commit is contained in:
gnilebein committed 2026-11-08 22:35:42 +01:00
commit 6912d045cf
11 files changed
+224 -50

No files matched your search

+5 -3
View File
@@ -7,7 +7,8 @@ use Cake\Cache\Cache;
/**
* Very small fixed-window rate limiter backed by the "throttle" cache config.
* Used to limit poll creation and recovery mails per client IP.
* Used to limit poll creation and recovery mails per client IP (per hour) and
* participant answers per client IP (per minute).
*/
class ThrottleService
{
@@ -19,9 +20,10 @@ class ThrottleService
* @param string $bucket Logical action, e.g. "create"
* @param string $identifier Client identifier, e.g. IP address
* @param int $limit Allowed hits per window; <= 0 disables throttling
* @param int $windowSeconds Length of the window
* @return bool
*/
public function attempt(string $bucket, string $identifier, int $limit): bool
public function attempt(string $bucket, string $identifier, int $limit, int $windowSeconds = self::WINDOW_SECONDS): bool
{
if ($limit <= 0) {
return true;
@@ -31,7 +33,7 @@ class ThrottleService
$now = time();
/** @var array{start: int, hits: int}|null $state */
$state = Cache::read($key, 'throttle');
if (!is_array($state) || $state['start'] + self::WINDOW_SECONDS <= $now) {
if (!is_array($state) || $state['start'] + $windowSeconds <= $now) {
$state = ['start' => $now, 'hits' => 0];
}
if ($state['hits'] >= $limit) {
+87 -28
View File
@@ -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));
}