assertFieldLengths($title, $content); $this->lockUser($userId); if (Ticket::where('userid', $userId)->where('rootid', 0)->where('status', 1)->count() >= self::MAX_OPEN_TICKETS) { throw new \InvalidArgumentException('最多同时保留 5 个处理中工单,请先等待处理或关闭旧工单'); } if (Ticket::where('userid', $userId)->where('rootid', 0) ->where('datetime', '>=', time() - self::CREATE_RATE_WINDOW)->count() >= self::CREATE_RATE_COUNT) { throw new \InvalidArgumentException('工单提交过于频繁,请一小时后再试'); } $this->assertAttachmentQuota($userId, $newAttachmentBytes); } public function assertReply( int $userId, string $content, int $newAttachmentBytes, bool $actorIsAdmin ): void { $this->assertFieldLengths('', $content); if ($actorIsAdmin) { return; } $this->lockUser($userId); if (Ticket::where('userid', $userId)->where('rootid', '<>', 0) ->where('datetime', '>=', time() - self::REPLY_RATE_WINDOW)->count() >= self::REPLY_RATE_COUNT) { throw new \InvalidArgumentException('工单回复过于频繁,请稍后再试'); } $this->assertAttachmentQuota($userId, $newAttachmentBytes); } private function assertFieldLengths(string $title, string $content): void { if ($title !== '' && mb_strlen($title) > self::MAX_TITLE_CHARS) { throw new \InvalidArgumentException('工单标题不能超过 120 个字符'); } if (mb_strlen($content) > self::MAX_CONTENT_CHARS) { throw new \InvalidArgumentException('工单内容不能超过 10000 个字符'); } } private function lockUser(int $userId): void { $connection = (new Ticket())->getConnection(); $connection->table('ticket_user_guards')->insertOrIgnore([ 'user_id' => $userId, 'updated_at' => time(), ]); $guard = $connection->table('ticket_user_guards') ->where('user_id', $userId)->lockForUpdate()->first(); if ($guard === null) { throw new \RuntimeException('工单用户策略锁获取失败'); } $connection->table('ticket_user_guards')->where('user_id', $userId) ->update(['updated_at' => time()]); } private function assertAttachmentQuota(int $userId, int $newBytes): void { if ($newBytes <= 0) { return; } $used = (int) TicketAttachment::where('user_id', $userId)->sum('bytes'); if ($used + $newBytes > self::MAX_USER_ATTACHMENT_BYTES) { throw new \InvalidArgumentException('工单附件总容量不能超过 100 MiB,请联系管理员清理旧工单附件'); } } }