refactor(ticket): centralize thread mutations

go
codex 2 weeks ago
parent 281c36e990
commit f97e935fc0

@ -6,14 +6,14 @@ use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\User;
use voku\helper\AntiXSS;
use App\Services\Auth;
use App\Services\AdminDataMasker;
use App\Services\AdminPermission;
use App\Services\TicketTelegramConfig;
use App\Services\TicketTelegramNotifier;
use App\Services\TicketReplyService;
use App\Services\AdminCsrf;
use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
use App\Services\Ticket\TicketViewer;
@ -97,16 +97,16 @@ class TicketController extends AdminController
return $this->echoJson($response, $res);
}
$antiXss = new AntiXSS();
$cleanContent = $antiXss->xss_clean($content);
try {
$result = TicketReplyService::create(
$result = (new TicketThreadService())->reply(new ReplyTicketCommand(
(int) $id,
(int) Auth::getUser()->id,
$cleanContent,
$content,
(int) $status,
$request
);
$request,
null,
true
));
} catch (\Throwable $exception) {
error_log('Admin ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
@ -120,7 +120,7 @@ class TicketController extends AdminController
return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']);
}
$ticketMain = $result['root'];
$ticketMain = $result->root;
try {
$user = User::where('id', (int) $ticketMain->userid)->first();
if ($user !== null && trim((string) $user->email) !== '') {

@ -13,8 +13,6 @@ use App\Utils\Hash;
use App\Utils\Totp;
use App\Utils\Tools;
use voku\helper\AntiXSS;
use App\Models\User;
use App\Models\Configurations;
use App\Models\Code;
@ -34,7 +32,9 @@ use App\Services\Payment\UsdtConfig;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\PaytaroConfig;
use App\Services\TicketAttachmentService;
use App\Services\TicketReplyService;
use App\Services\Ticket\OpenTicketCommand;
use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketQueueQuery;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
@ -641,44 +641,27 @@ class UserController extends BaseController
}
$title = $request->getParam('title');
$content = $request->getParam('content');
$ticketType = $this->ticketType($request->getParam('ticket_type'));
$priority = $this->ticketPriority($request->getParam('priority'));
$instanceId = $this->ticketInstanceId($request->getParam('instance_id'));
$instanceInput = $request->getParam('instance_id');
if ($instanceInput !== null && $instanceInput !== '' && $instanceId === null) {
if ($instanceInput !== null && $instanceInput !== ''
&& (!is_scalar($instanceInput) || !ctype_digit((string) $instanceInput))) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '关联实例不存在或无权访问']);
}
if (!is_string($title) || !is_string($content) || trim($title) === '' || trim($content) === '') {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全工单主题和内容']);
}
$cleaner = new AntiXSS();
$ticket = new Ticket();
$ticket->title = $cleaner->xss_clean($title);
$ticket->content = $cleaner->xss_clean($content);
$ticket->rootid = 0;
$ticket->userid = $this->user->id;
$ticket->datetime = time();
$ticket->status = 1;
$ticket->ticket_type = $ticketType;
$ticket->priority = $priority;
$ticket->instance_id = $instanceId;
$connection = $ticket->getConnection();
$createdPaths = [];
try {
$connection->transaction(function () use ($ticket, $request, &$createdPaths) {
if (!$ticket->save()) {
throw new \RuntimeException('工单保存失败');
}
TicketAttachmentService::store(
$request,
(int) $ticket->id,
(int) $ticket->id,
(int) $this->user->id,
$createdPaths
);
}, 1);
$result = (new TicketThreadService())->open(new OpenTicketCommand(
(int) $this->user->id,
$title,
$content,
is_scalar($request->getParam('ticket_type'))
? (string) $request->getParam('ticket_type') : '',
is_scalar($request->getParam('priority'))
? (string) $request->getParam('priority') : '',
$instanceInput === null || $instanceInput === '' ? null : (int) $instanceInput,
$request
));
} catch (\Throwable $exception) {
TicketAttachmentService::discardPaths($createdPaths);
error_log('Ticket creation failed: ' . $exception->getMessage());
$message = $exception instanceof \InvalidArgumentException
? $exception->getMessage()
@ -688,7 +671,7 @@ class UserController extends BaseController
try {
// The ticket is already committed; notification failure must not
// make the client retry and create a duplicate thread.
$this->notifyTicketCreated($ticket);
$this->notifyTicketCreated($result->root);
} catch (\Throwable $exception) {
error_log('Ticket creation notification failed: ' . $exception->getMessage());
}
@ -706,16 +689,15 @@ class UserController extends BaseController
if (!is_string($content) || trim($content) === '' || !in_array((string) $status, ['0', '1'], true)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全']);
}
$cleanContent = (new AntiXSS())->xss_clean($content);
try {
$result = TicketReplyService::create(
$result = (new TicketThreadService())->reply(new ReplyTicketCommand(
(int) $args['id'],
(int) $this->user->id,
$cleanContent,
$content,
(int) $status,
$request,
(int) $this->user->id
);
));
} catch (\Throwable $exception) {
error_log('User ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
@ -732,7 +714,7 @@ class UserController extends BaseController
// Notifications are best-effort and deliberately happen only
// after the reply transaction has committed. A mail/Telegram
// outage must not make the client retry an already saved reply.
$this->notifyTicketAdmins($result['event'], $result['root'], $result['reply']->content);
$this->notifyTicketAdmins($result->event, $result->root, $result->message->content);
} catch (\Throwable $exception) {
error_log('Ticket administrator notification failed: ' . $exception->getMessage());
}
@ -816,33 +798,6 @@ class UserController extends BaseController
}
}
private function ticketType($value): string
{
$value = is_scalar($value) ? (string) $value : '';
return in_array($value, ['pre_sales', 'after_sales', 'technical', 'finance'], true)
? $value : 'technical';
}
private function ticketPriority($value): string
{
$value = is_scalar($value) ? (string) $value : '';
return in_array($value, ['high', 'medium', 'low'], true) ? $value : 'medium';
}
private function ticketInstanceId($value): ?int
{
if (!is_scalar($value) || $value === null || $value === '' || !ctype_digit((string) $value)) {
return null;
}
try {
$instance = CloudInstance::where('id', (int) $value)->where('user_id', (int) $this->user->id)
->where('status', '<>', 'deleted')->first();
return $instance === null ? null : (int) $instance->id;
} catch (\Throwable $exception) {
return null;
}
}
protected function streamTicketAttachment($response, $attachment)
{
if (!$attachment instanceof TicketAttachment) {

@ -0,0 +1,17 @@
<?php
namespace App\Services\Ticket;
final readonly class OpenTicketCommand
{
public function __construct(
public int $actorId,
public string $title,
public string $content,
public string $type,
public string $priority,
public ?int $instanceId,
public mixed $request
) {
}
}

@ -0,0 +1,17 @@
<?php
namespace App\Services\Ticket;
final readonly class ReplyTicketCommand
{
public function __construct(
public int $ticketId,
public int $actorId,
public string $content,
public int $status,
public mixed $request,
public ?int $ownerId = null,
public bool $actorIsAdmin = false
) {
}
}

@ -0,0 +1,149 @@
<?php
namespace App\Services\Ticket;
use App\Models\CloudInstance;
use App\Models\Ticket;
use App\Services\TicketAttachmentService;
use voku\helper\AntiXSS;
/**
* Owns the complete ticket thread mutation contract.
*
* The HTTP adapters only translate requests and responses. Validation,
* sanitization, ownership, row locking, status transitions, attachment rows
* and rollback cleanup remain atomic behind this interface.
*/
final class TicketThreadService
{
public function open(OpenTicketCommand $command): TicketWriteResult
{
$title = $this->cleanRequired($command->title, '请填全工单主题和内容');
$content = $this->cleanRequired($command->content, '请填全工单主题和内容');
$type = in_array($command->type, ['pre_sales', 'after_sales', 'technical', 'finance'], true)
? $command->type : 'technical';
$priority = in_array($command->priority, ['high', 'medium', 'low'], true)
? $command->priority : 'medium';
$instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId);
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$command,
$title,
$content,
$type,
$priority,
$instanceId,
&$createdPaths
): TicketWriteResult {
$ticket = new Ticket();
$ticket->title = $title;
$ticket->content = $content;
$ticket->rootid = 0;
$ticket->userid = $command->actorId;
$ticket->datetime = time();
$ticket->status = 1;
$ticket->ticket_type = $type;
$ticket->priority = $priority;
$ticket->instance_id = $instanceId;
if (!$ticket->save()) {
throw new \RuntimeException('工单保存失败');
}
$attachments = TicketAttachmentService::store(
$command->request,
(int) $ticket->id,
(int) $ticket->id,
$command->actorId,
$createdPaths
);
return new TicketWriteResult($ticket, $ticket, '新工单', $attachments);
}, 1);
} catch (\Throwable $exception) {
TicketAttachmentService::discardPaths($createdPaths);
throw $exception;
}
}
public function reply(ReplyTicketCommand $command): ?TicketWriteResult
{
if (!in_array($command->status, [0, 1], true)) {
throw new \InvalidArgumentException('工单状态无效');
}
$content = $this->cleanRequired($command->content, '请填写回复内容');
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$command,
$content,
&$createdPaths
): ?TicketWriteResult {
$query = Ticket::where('id', $command->ticketId)->where('rootid', 0);
if ($command->ownerId !== null) {
$query->where('userid', $command->ownerId);
}
$root = $query->lockForUpdate()->first();
if ($root === null) {
return null;
}
$event = $command->status === 1 && (int) $root->status !== 1
? '工单重新开启'
: ($command->actorIsAdmin ? '管理员回复工单' : '用户回复工单');
$reply = new Ticket();
$reply->title = (string) $root->title;
$reply->content = $content;
$reply->rootid = (int) $root->id;
$reply->userid = $command->actorId;
$reply->datetime = time();
$reply->status = $command->status;
$reply->ticket_type = (string) $root->ticket_type;
$reply->priority = (string) $root->priority;
$reply->instance_id = $root->instance_id;
$root->status = $command->status;
if (!$root->save() || !$reply->save()) {
throw new \RuntimeException('工单回复保存失败');
}
$attachments = TicketAttachmentService::store(
$command->request,
(int) $root->id,
(int) $reply->id,
$command->actorId,
$createdPaths
);
return new TicketWriteResult($root, $reply, $event, $attachments);
}, 1);
} catch (\Throwable $exception) {
TicketAttachmentService::discardPaths($createdPaths);
throw $exception;
}
}
private function cleanRequired(string $value, string $message): string
{
if (trim($value) === '') {
throw new \InvalidArgumentException($message);
}
$clean = trim((string) (new AntiXSS())->xss_clean($value));
if ($clean === '') {
throw new \InvalidArgumentException($message);
}
return $clean;
}
private function ownedInstanceId(int $userId, ?int $instanceId): ?int
{
if ($instanceId === null) {
return null;
}
$instance = CloudInstance::where('id', $instanceId)->where('user_id', $userId)
->where('status', '<>', 'deleted')->first();
if ($instance === null) {
throw new \InvalidArgumentException('关联实例不存在或无权访问');
}
return (int) $instance->id;
}
}

@ -0,0 +1,17 @@
<?php
namespace App\Services\Ticket;
use App\Models\Ticket;
final readonly class TicketWriteResult
{
public function __construct(
public Ticket $root,
public Ticket $message,
public string $event,
public array $attachments,
public bool $wasCreated = true
) {
}
}

@ -1,103 +0,0 @@
<?php
namespace App\Services;
use App\Models\Ticket;
/**
* Atomically append a message to an existing ticket thread.
*
* A ticket thread has one root row whose status is the source of truth. The
* root row is therefore selected with a row lock inside the same transaction
* that writes the reply and its attachment rows. Filesystem paths created by
* the attachment writer are explicitly discarded if the transaction cannot
* commit; a database rollback alone cannot remove those files.
*/
final class TicketReplyService
{
/**
* @param mixed $request PSR-7 request, including uploaded files
* @param int|null $ownerId Restrict the root to this user for user replies
* @return array{root: Ticket, reply: Ticket, event: string, attachments: array}|null
*/
public static function create(
int $ticketId,
int $actorId,
string $content,
int $status,
$request,
?int $ownerId = null
): ?array {
if (!in_array($status, [0, 1], true)) {
throw new \InvalidArgumentException('工单状态无效');
}
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$ticketId,
$actorId,
$content,
$status,
$request,
$ownerId,
&$createdPaths
) {
// This query must be inside the transaction. A lock acquired
// in autocommit mode would be released before the reply save.
$query = Ticket::where('id', $ticketId)->where('rootid', 0);
if ($ownerId !== null) {
$query->where('userid', $ownerId);
}
$root = $query->lockForUpdate()->first();
if ($root === null) {
return null;
}
$event = $status === 1 && (int) $root->status !== 1
? '工单重新开启'
: '用户回复工单';
$reply = new Ticket();
$reply->title = (string) $root->title;
$reply->content = $content;
$reply->rootid = (int) $root->id;
$reply->userid = $actorId;
$reply->datetime = time();
$reply->status = $status;
$reply->ticket_type = (string) $root->ticket_type;
$reply->priority = (string) $root->priority;
$reply->instance_id = $root->instance_id;
$root->status = $status;
if (!$root->save() || !$reply->save()) {
throw new \RuntimeException('工单回复保存失败');
}
// Keep attachment rows in this transaction. The service also
// records every newly-created path for commit-failure cleanup.
$attachments = TicketAttachmentService::store(
$request,
(int) $root->id,
(int) $reply->id,
$actorId,
$createdPaths
);
return [
'root' => $root,
'reply' => $reply,
'event' => $event,
'attachments' => $attachments,
];
}, 1);
} catch (\Throwable $exception) {
// The DB transaction has already rolled back (or failed to
// commit) when control reaches here. Only remove files created by
// this request; never delete pre-existing ticket attachments.
TicketAttachmentService::discardPaths($createdPaths);
throw $exception;
}
}
}

@ -6,8 +6,10 @@
// same failure boundary.
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\TicketReplyService;
use App\Services\TicketAttachmentService;
use App\Services\Ticket\OpenTicketCommand;
use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -55,6 +57,13 @@ $schema->create('ticket_attachments', static function (Blueprint $table): void {
$table->string('sha256');
$table->integer('created_at');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->string('status');
});
$service = new TicketThreadService();
Capsule::table('ticket')->insert([
'id' => 1,
@ -96,7 +105,9 @@ $request = static function (array $files): object {
// A user may only mutate a thread that they own. The missing result is the
// public behavior used by the HTTP adapter to return "ticket not found"
// without revealing another user's ticket.
$foreignResult = TicketReplyService::create(1, 8, 'must not be saved', 0, $request([]), 8);
$foreignResult = $service->reply(new ReplyTicketCommand(
1, 8, 'must not be saved', 0, $request([]), 8
));
$assert($foreignResult === null, 'A foreign user was able to reply to the ticket.');
$assert(Capsule::table('ticket')->where('rootid', 1)->count() === 0,
'The rejected foreign reply wrote a message row.');
@ -113,7 +124,9 @@ $second = [
'size' => filesize($secondPath), 'type' => 'image/png',
];
try {
TicketReplyService::create(1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7);
$service->reply(new ReplyTicketCommand(
1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7
));
throw new RuntimeException('Invalid attachment unexpectedly succeeded.');
} catch (InvalidArgumentException $exception) {
// Expected validation failure; the assertions below verify the rollback.
@ -128,8 +141,10 @@ $assert(glob(BASE_PATH . '/storage/ticket-attachments/*') === [],
'A partially stored attachment file survived rollback.');
@unlink($secondPath);
$result = TicketReplyService::create(1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7);
$assert(is_array($result) && $result['reply']->rootid == 1, 'Successful reply was not created.');
$result = $service->reply(new ReplyTicketCommand(
1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7
));
$assert($result !== null && $result->message->rootid == 1, 'Successful reply was not created.');
$assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 0,
'Root status was not updated by a successful reply.');
$assert(Capsule::table('ticket')->where('rootid', 1)->count() === 1,
@ -144,14 +159,14 @@ $assert(is_file(BASE_PATH . '/storage/ticket-attachments/' . $attachment->storag
// Closing and reopening are observable thread behaviors. Reopening a closed
// thread has its own event so notification adapters can explain the change.
$reopened = TicketReplyService::create(1, 7, 'reopen', 1, $request([]), 7);
$assert(is_array($reopened) && $reopened['event'] === '工单重新开启',
$reopened = $service->reply(new ReplyTicketCommand(1, 7, 'reopen', 1, $request([]), 7));
$assert($reopened !== null && $reopened->event === '工单重新开启',
'A closed ticket did not emit the reopen event.');
$assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 1,
'The reopened ticket root is not open.');
// The lock must be acquired in the transaction, not by a preflight query.
$serviceSource = file_get_contents(dirname(__DIR__) . '/app/Services/TicketReplyService.php');
$serviceSource = file_get_contents(dirname(__DIR__) . '/app/Services/Ticket/TicketThreadService.php');
$assert(str_contains($serviceSource, 'transaction(function')
&& str_contains($serviceSource, 'lockForUpdate()->first()')
&& str_contains($serviceSource, 'TicketAttachmentService::store'),
@ -165,11 +180,37 @@ foreach ([
dirname(__DIR__) . '/app/Controllers/Admin/TicketController.php',
] as $controllerPath) {
$controllerSource = file_get_contents($controllerPath);
$assert(str_contains($controllerSource, 'TicketReplyService::create')
$assert(str_contains($controllerSource, 'TicketThreadService')
&& !str_contains($controllerSource, '$previousStatus'),
'A ticket controller still uses the stale-status compensation flow.');
}
Capsule::table('cloud_instances')->insert(['id' => 31, 'user_id' => 7, 'status' => 'running']);
$opened = $service->open(new OpenTicketCommand(
7,
'<b>Provisioning issue</b>',
'<script>alert(1)</script>Cannot boot',
'technical',
'high',
31,
$request([])
));
$assert($opened->root->rootid == 0 && $opened->message->id === $opened->root->id,
'Opening a ticket did not create the root thread message.');
$assert((int) $opened->root->instance_id === 31,
'Opening a ticket lost the owned instance association.');
$assert(!str_contains((string) $opened->root->content, '<script>'),
'Opening a ticket did not sanitize active content.');
try {
$service->open(new OpenTicketCommand(
8, 'Foreign instance', 'Must fail', 'technical', 'medium', 31, $request([])
));
throw new RuntimeException('Foreign instance association unexpectedly succeeded.');
} catch (InvalidArgumentException $exception) {
$assert($exception->getMessage() === '关联实例不存在或无权访问',
'Foreign instance rejection returned the wrong public error.');
}
TicketAttachmentService::discardPaths([
BASE_PATH . '/storage/ticket-attachments/' . $attachment->storage_key,
]);

@ -82,8 +82,8 @@ $assert($first !== null && (int) $first->id === 1,
$userController = file_get_contents(dirname(__DIR__) . '/app/Controllers/UserController.php');
$adminController = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/TicketController.php');
$createTransaction = strpos($userController, '$connection->transaction');
$createNotification = strpos($userController, '$this->notifyTicketCreated($ticket)');
$createTransaction = strpos($userController, '(new TicketThreadService())->open');
$createNotification = strpos($userController, '$this->notifyTicketCreated($result->root)');
$assert($createTransaction !== false && $createNotification !== false
&& $createTransaction < $createNotification,
'Ticket creation notifications are not visibly ordered after persistence.');

Loading…
Cancel
Save