feat(ticket): make thread mutations idempotent

go
codex 2 weeks ago
parent a249c8abea
commit a2ec556c8f

@ -15,6 +15,7 @@ use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketEvent;
use App\Services\Ticket\TicketNotificationDispatcher;
use App\Services\Ticket\TicketIdempotencyConflict;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
use App\Services\Ticket\TicketViewer;
@ -103,22 +104,31 @@ class TicketController extends AdminController
(int) $status,
$request,
null,
true
true,
trim((string) $request->getHeaderLine('Idempotency-Key'))
));
} catch (\Throwable $exception) {
error_log('Admin ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
$payload = [
'ret' => 0,
'msg' => $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单回复保存失败',
]);
];
if ($exception instanceof TicketIdempotencyConflict) {
$response = $response->withStatus(409);
$response->getBody()->write((string) json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
}
return $this->echoJson($response, $payload);
}
if ($result === null) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']);
}
(new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result));
if ($result->wasCreated) {
(new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result));
}
$res['ret'] = 1;
$res['msg'] = "提交成功";

@ -35,6 +35,7 @@ use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketThreadService;
use App\Services\Ticket\TicketEvent;
use App\Services\Ticket\TicketNotificationDispatcher;
use App\Services\Ticket\TicketIdempotencyConflict;
use App\Services\Ticket\TicketQueueQuery;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
@ -659,16 +660,24 @@ class UserController extends BaseController
is_scalar($request->getParam('priority'))
? (string) $request->getParam('priority') : '',
$instanceInput === null || $instanceInput === '' ? null : (int) $instanceInput,
$request
$request,
trim((string) $request->getHeaderLine('Idempotency-Key'))
));
} catch (\Throwable $exception) {
error_log('Ticket creation failed: ' . $exception->getMessage());
$message = $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单保存失败';
if ($exception instanceof TicketIdempotencyConflict) {
$response = $response->withStatus(409);
$response->getBody()->write((string) json_encode(['ret' => 0, 'msg' => $message], JSON_UNESCAPED_UNICODE));
return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
}
return $this->echoJson($response, ['ret' => 0, 'msg' => $message]);
}
(new TicketNotificationDispatcher())->dispatch(TicketEvent::created($result));
if ($result->wasCreated) {
(new TicketNotificationDispatcher())->dispatch(TicketEvent::created($result));
}
return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']);
}
@ -690,21 +699,31 @@ class UserController extends BaseController
$content,
(int) $status,
$request,
(int) $this->user->id
(int) $this->user->id,
false,
trim((string) $request->getHeaderLine('Idempotency-Key'))
));
} catch (\Throwable $exception) {
error_log('User ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
$payload = [
'ret' => 0,
'msg' => $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单回复保存失败',
]);
];
if ($exception instanceof TicketIdempotencyConflict) {
$response = $response->withStatus(409);
$response->getBody()->write((string) json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
}
return $this->echoJson($response, $payload);
}
if ($result === null) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']);
}
(new TicketNotificationDispatcher())->dispatch(TicketEvent::userReply($result));
if ($result->wasCreated) {
(new TicketNotificationDispatcher())->dispatch(TicketEvent::userReply($result));
}
return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']);
}

@ -0,0 +1,9 @@
<?php
namespace App\Models;
final class TicketWriteRequest extends Model
{
protected $connection = 'default';
protected $table = 'ticket_write_requests';
}

@ -11,7 +11,8 @@ final readonly class OpenTicketCommand
public string $type,
public string $priority,
public ?int $instanceId,
public mixed $request
public mixed $request,
public string $requestKey
) {
}
}

@ -11,7 +11,8 @@ final readonly class ReplyTicketCommand
public int $status,
public mixed $request,
public ?int $ownerId = null,
public bool $actorIsAdmin = false
public bool $actorIsAdmin = false,
public string $requestKey = ''
) {
}
}

@ -0,0 +1,11 @@
<?php
namespace App\Services\Ticket;
final class TicketIdempotencyConflict extends \RuntimeException
{
public function __construct()
{
parent::__construct('请求幂等标识已用于其他工单内容', 409);
}
}

@ -4,6 +4,8 @@ namespace App\Services\Ticket;
use App\Models\CloudInstance;
use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\TicketWriteRequest;
use App\Services\TicketAttachmentService;
use voku\helper\AntiXSS;
@ -24,7 +26,13 @@ final class TicketThreadService
? $command->type : 'technical';
$priority = in_array($command->priority, ['high', 'medium', 'low'], true)
? $command->priority : 'medium';
$instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId);
$requestHash = $this->requestHash('open', [
'title' => $title,
'content' => $content,
'type' => $type,
'priority' => $priority,
'instance_id' => $command->instanceId,
], $command->request, $command->requestKey);
$connection = (new Ticket())->getConnection();
$createdPaths = [];
@ -35,9 +43,20 @@ final class TicketThreadService
$content,
$type,
$priority,
$instanceId,
$requestHash,
&$createdPaths
): TicketWriteResult {
[$intent, $replay] = $this->claimIntent(
$command->actorId,
$command->requestKey,
$requestHash,
'open',
'新工单'
);
if ($replay !== null) {
return $replay;
}
$instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId);
$ticket = new Ticket();
$ticket->title = $title;
$ticket->content = $content;
@ -58,6 +77,7 @@ final class TicketThreadService
$command->actorId,
$createdPaths
);
$this->completeIntent($intent, (int) $ticket->id, (int) $ticket->id);
return new TicketWriteResult($ticket, $ticket, '新工单', $attachments);
}, 1);
} catch (\Throwable $exception) {
@ -72,26 +92,45 @@ final class TicketThreadService
throw new \InvalidArgumentException('工单状态无效');
}
$content = $this->cleanRequired($command->content, '请填写回复内容');
$event = $command->actorIsAdmin ? '管理员回复工单' : '用户回复工单';
$requestHash = $this->requestHash('reply', [
'ticket_id' => $command->ticketId,
'content' => $content,
'status' => $command->status,
], $command->request, $command->requestKey);
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$command,
$content,
$event,
$requestHash,
&$createdPaths
): ?TicketWriteResult {
[$intent, $replay] = $this->claimIntent(
$command->actorId,
$command->requestKey,
$requestHash,
'reply',
$event
);
if ($replay !== null) {
return $replay;
}
$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) {
$intent->delete();
return null;
}
$event = $command->status === 1 && (int) $root->status !== 1
? '工单重新开启'
: ($command->actorIsAdmin ? '管理员回复工单' : '用户回复工单');
: $event;
$reply = new Ticket();
$reply->title = (string) $root->title;
$reply->content = $content;
@ -114,6 +153,7 @@ final class TicketThreadService
$command->actorId,
$createdPaths
);
$this->completeIntent($intent, (int) $root->id, (int) $reply->id);
return new TicketWriteResult($root, $reply, $event, $attachments);
}, 1);
} catch (\Throwable $exception) {
@ -122,6 +162,85 @@ final class TicketThreadService
}
}
private function requestHash(
string $operation,
array $payload,
mixed $request,
string $requestKey
): string {
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1) {
throw new \InvalidArgumentException('请求幂等标识无效');
}
$encoded = json_encode([
'operation' => $operation,
'payload' => $payload,
'attachments' => TicketAttachmentService::fingerprints($request),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($encoded)) {
throw new \RuntimeException('工单请求摘要生成失败');
}
return hash('sha256', $encoded);
}
/**
* @return array{TicketWriteRequest, TicketWriteResult|null}
*/
private function claimIntent(
int $actorId,
string $requestKey,
string $requestHash,
string $operation,
string $event
): array {
$connection = (new TicketWriteRequest())->getConnection();
$inserted = $connection->table('ticket_write_requests')->insertOrIgnore([
'actor_user_id' => $actorId,
'request_key' => $requestKey,
'request_hash' => $requestHash,
'operation' => $operation,
'ticket_id' => null,
'message_id' => null,
'created_at' => time(),
]);
$intent = TicketWriteRequest::where('actor_user_id', $actorId)
->where('request_key', $requestKey)->lockForUpdate()->first();
if ($intent === null) {
throw new \RuntimeException('工单写入意图保存失败');
}
if ((string) $intent->request_hash !== $requestHash
|| (string) $intent->operation !== $operation) {
throw new TicketIdempotencyConflict();
}
if ((int) $inserted === 0) {
if ($intent->ticket_id === null || $intent->message_id === null) {
throw new \RuntimeException('工单写入意图结果不完整');
}
return [$intent, $this->replayResult($intent, $event)];
}
return [$intent, null];
}
private function completeIntent(TicketWriteRequest $intent, int $ticketId, int $messageId): void
{
$intent->ticket_id = $ticketId;
$intent->message_id = $messageId;
if (!$intent->save()) {
throw new \RuntimeException('工单写入结果保存失败');
}
}
private function replayResult(TicketWriteRequest $intent, string $event): TicketWriteResult
{
$root = Ticket::where('id', (int) $intent->ticket_id)->where('rootid', 0)->first();
$message = Ticket::where('id', (int) $intent->message_id)->first();
if ($root === null || $message === null) {
throw new \RuntimeException('工单写入结果已不存在');
}
$attachments = TicketAttachment::where('ticket_id', (int) $root->id)
->where('message_id', (int) $message->id)->orderBy('id')->get()->all();
return new TicketWriteResult($root, $message, $event, $attachments, false);
}
private function cleanRequired(string $value, string $message): string
{
if (trim($value) === '') {

@ -21,6 +21,41 @@ final class TicketAttachmentService
'image/webp' => 'webp',
];
/**
* Validate and fingerprint uploaded files without consuming or moving
* them. The ordered result is part of the ticket idempotency hash.
*/
public static function fingerprints($request): array
{
$files = self::files($request);
if (count($files) > self::MAX_FILES) {
throw new \InvalidArgumentException('最多上传 5 张图片');
}
$total = 0;
$fingerprints = [];
foreach ($files as $file) {
$meta = self::validate($file);
$total += $meta['bytes'];
if ($total > self::MAX_TOTAL_BYTES) {
throw new \InvalidArgumentException('图片总大小不能超过 15 MB');
}
$tmp = is_array($file)
? (string) ($file['tmp_name'] ?? '')
: (string) $file->getStream()->getMetadata('uri');
$sha256 = $tmp === '' ? false : hash_file('sha256', $tmp);
if (!is_string($sha256) || preg_match('/^[a-f0-9]{64}$/', $sha256) !== 1) {
throw new \RuntimeException('图片校验失败');
}
$fingerprints[] = [
'name' => $meta['name'],
'mime' => $meta['mime'],
'bytes' => $meta['bytes'],
'sha256' => $sha256,
];
}
return $fingerprints;
}
/**
* Store uploaded attachments and optionally expose every path created by
* this call to the surrounding transaction coordinator.

@ -50,7 +50,40 @@
return token ? { "X-Admin-CSRF-Token": token } : {};
}
function submitMultipart(url, method, fields, files) {
function createRequestKey() {
if (window.crypto && typeof window.crypto.randomUUID === "function") {
return window.crypto.randomUUID();
}
var bytes = new Uint8Array(16);
if (window.crypto && typeof window.crypto.getRandomValues === "function") {
window.crypto.getRandomValues(bytes);
} else {
for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
}
return "ticket-" + Array.prototype.map.call(bytes, function (value) {
return value.toString(16).padStart(2, "0");
}).join("");
}
function requestFingerprint(fields, files) {
return JSON.stringify({
fields: fields,
files: (files || []).map(function (file) {
return [file.name, file.size, file.type, file.lastModified || 0];
})
});
}
function requestKey(state, fields, files) {
var fingerprint = requestFingerprint(fields, files);
if (!state.key || state.fingerprint !== fingerprint) {
state.key = createRequestKey();
state.fingerprint = fingerprint;
}
return state.key;
}
function submitMultipart(url, method, fields, files, idempotencyKey) {
var body = new FormData();
Object.keys(fields || {}).forEach(function (key) {
body.append(key, fields[key] == null ? "" : String(fields[key]));
@ -61,7 +94,10 @@
return fetch(url, {
method: method,
credentials: "same-origin",
headers: Object.assign({ "X-Requested-With": "XMLHttpRequest" }, csrfHeaders()),
headers: Object.assign({
"X-Requested-With": "XMLHttpRequest",
"Idempotency-Key": idempotencyKey
}, csrfHeaders()),
body: body
}).then(parseResponse);
}
@ -240,6 +276,7 @@
function bindCreate() {
var form = qs("#supportTicketCreate");
var attachments;
var requestState = { key: "", fingerprint: "" };
if (!form) return;
attachments = bindAttachments(form);
form.addEventListener("submit", function (event) {
@ -253,14 +290,18 @@
}
inlineMessage("", "");
var done = setBusy(button, "提交中...");
submitMultipart("/user/ticket", "POST", {
var fields = {
title: title,
content: content,
ticket_type: readValue(form, "[name='ticket_type']"),
priority: readValue(form, "[name='priority']:checked") || readValue(form, "[name='priority']"),
instance_id: readValue(form, "[name='instance_id']")
}, attachments.files).then(function (data) {
done();
};
submitMultipart(
"/user/ticket", "POST", fields, attachments.files,
requestKey(requestState, fields, attachments.files)
).then(function (data) {
if (!data.ret) done();
notify(data.msg || "操作完成", data.ret ? "success" : "error", data.ret ? "提交成功" : "提交失败").then(function () {
if (data.ret) setTimeout(function () { window.location.href = "/user/ticket"; }, delay());
});
@ -274,6 +315,7 @@
function bindReply() {
var form = qs("#supportTicketReply");
var attachments;
var requestState = { key: "", fingerprint: "" };
if (!form) return;
attachments = bindAttachments(form);
qsa("[data-support-status]", form).forEach(function (button) {
@ -288,11 +330,16 @@
}
inlineMessage("", "");
var done = setBusy(buttons, "提交中...");
submitMultipart("/user/ticket/" + encodeURIComponent(ticketId) + "/reply", "POST", {
var fields = {
content: content,
status: status
}, attachments.files).then(function (data) {
done();
};
submitMultipart(
"/user/ticket/" + encodeURIComponent(ticketId) + "/reply",
"POST", fields, attachments.files,
requestKey(requestState, fields, attachments.files)
).then(function (data) {
if (!data.ret) done();
notify(data.msg || "操作完成", data.ret ? "success" : "error", data.ret ? "提交成功" : "提交失败").then(function () {
if (data.ret) setTimeout(function () { window.location.reload(); }, delay());
});

@ -47,10 +47,11 @@
{literal}<script>
(function () {
var form=document.getElementById('adminTicketReply'), content=document.getElementById('adminTicketContent'), files=document.getElementById('adminTicketAttachments'), preview=document.getElementById('adminTicketPreview'), submit=document.getElementById('adminTicketSubmit'), close=document.getElementById('adminTicketClose'), hint=document.getElementById('adminTicketHint'), toast=document.getElementById('ticketToast');
var csrf=form.getAttribute('data-csrf-token') || '', endpoint=form.getAttribute('data-endpoint') || '';
var csrf=form.getAttribute('data-csrf-token') || '', endpoint=form.getAttribute('data-endpoint') || '', requestKey='', requestFingerprint='';
function idempotencyKey(status){var selected=Array.prototype.map.call(files.files||[],function(file){return [file.name,file.size,file.type,file.lastModified||0];});var fingerprint=JSON.stringify([String(status),content.value.trim(),selected]);if(!requestKey||requestFingerprint!==fingerprint){requestFingerprint=fingerprint;requestKey=(window.crypto&&window.crypto.randomUUID)?window.crypto.randomUUID():'ticket-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,14);}return requestKey;}
function notify(message,error){toast.textContent=message;toast.className='admin-toast is-show'+(error?' is-error':'');window.setTimeout(function(){toast.className='admin-toast';},2600);}
files.addEventListener('change',function(){preview.innerHTML='';Array.prototype.forEach.call(files.files||[],function(file){var item=document.createElement('span');item.className='admin-ticket-preview-item';item.textContent=file.name;preview.appendChild(item);});});
function send(status){if(submit.disabled||!content.value.trim()){if(!submit.disabled){notify('请填写回复内容',true);content.focus();}return;}var data=new FormData(form);data.set('status',String(status));submit.disabled=close.disabled=true;hint.textContent='正在提交…';fetch(endpoint,{method:'POST',credentials:'same-origin',headers:{'X-Admin-CSRF-Token':csrf,'X-Requested-With':'XMLHttpRequest'},body:data}).then(function(response){return response.text().then(function(text){var result={};try{result=JSON.parse(text);}catch(error){result={ret:0,msg:'服务器返回格式异常(HTTP '+response.status+')'};}if(!response.ok||!result.ret)throw new Error(result.msg||'提交失败');return result;});}).then(function(result){notify(result.msg||'回复已提交',false);window.setTimeout(function(){window.location.reload();},650);}).catch(function(error){notify(error.message||'提交失败',true);submit.disabled=close.disabled=false;hint.textContent='回复后用户会收到邮件提醒。';});}
function send(status){if(submit.disabled||!content.value.trim()){if(!submit.disabled){notify('请填写回复内容',true);content.focus();}return;}var data=new FormData(form);data.set('status',String(status));submit.disabled=close.disabled=true;hint.textContent='正在提交…';fetch(endpoint,{method:'POST',credentials:'same-origin',headers:{'X-Admin-CSRF-Token':csrf,'X-Requested-With':'XMLHttpRequest','Idempotency-Key':idempotencyKey(status)},body:data}).then(function(response){return response.text().then(function(text){var result={};try{result=JSON.parse(text);}catch(error){result={ret:0,msg:'服务器返回格式异常(HTTP '+response.status+')'};}if(!response.ok||!result.ret)throw new Error(result.msg||'提交失败');return result;});}).then(function(result){notify(result.msg||'回复已提交',false);window.setTimeout(function(){window.location.reload();},650);}).catch(function(error){notify(error.message||'提交失败',true);submit.disabled=close.disabled=false;hint.textContent='回复后用户会收到邮件提醒。';});}
form.addEventListener('submit',function(event){event.preventDefault();send(1);});close.addEventListener('click',function(){send(0);});
})();
</script>

@ -0,0 +1,97 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Ticket\OpenTicketCommand;
use App\Services\Ticket\TicketIdempotencyConflict;
use App\Services\Ticket\TicketThreadService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
if (!defined('BASE_PATH')) {
define('BASE_PATH', sys_get_temp_dir() . '/virt-ticket-idempotency-' . bin2hex(random_bytes(5)));
}
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$request = static function (): object {
return new class {
public function getUploadedFiles(): array { return []; }
};
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->getConnection('default')->getSchemaBuilder();
$schema->create('ticket', static function (Blueprint $table): void {
$table->increments('id');
$table->text('title');
$table->text('content');
$table->integer('rootid')->default(0);
$table->integer('userid');
$table->integer('datetime');
$table->integer('status')->default(1);
$table->string('ticket_type')->default('technical');
$table->string('priority')->default('medium');
$table->integer('instance_id')->nullable();
});
$schema->create('ticket_attachments', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('ticket_id');
$table->integer('message_id');
$table->integer('user_id');
$table->string('storage_key');
$table->string('original_name');
$table->string('mime_type');
$table->integer('bytes');
$table->string('sha256');
$table->integer('created_at');
});
$schema->create('ticket_write_requests', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('actor_user_id');
$table->string('request_key');
$table->string('request_hash');
$table->string('operation');
$table->integer('ticket_id')->nullable();
$table->integer('message_id')->nullable();
$table->integer('created_at');
$table->unique(['actor_user_id', 'request_key']);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->string('status');
});
$service = new TicketThreadService();
$key = 'ticket-open-1234567890';
$command = new OpenTicketCommand(
7, 'Network issue', 'Cannot connect', 'technical', 'high', null, $request(), $key
);
$first = $service->open($command);
$again = $service->open($command);
$assert($first->wasCreated && !$again->wasCreated,
'An idempotent replay is not distinguished from the original write.');
$assert($again->root->id === $first->root->id && $again->message->id === $first->message->id,
'An idempotent replay did not return the original result.');
$assert(Capsule::table('ticket')->count() === 1
&& Capsule::table('ticket_write_requests')->count() === 1,
'An idempotent replay duplicated the ticket or intent.');
try {
$service->open(new OpenTicketCommand(
7, 'Changed title', 'Cannot connect', 'technical', 'high', null, $request(), $key
));
throw new RuntimeException('A changed request reused an existing idempotency key.');
} catch (TicketIdempotencyConflict $exception) {
$assert($exception->getCode() === 409, 'Idempotency conflict is not an HTTP 409 domain error.');
}
echo "Ticket idempotency checks passed.\n";

@ -0,0 +1,23 @@
<?php
$javascript = file_get_contents(dirname(__DIR__) . '/public/theme/venix/js/ticket-page.js');
$userController = file_get_contents(dirname(__DIR__) . '/app/Controllers/UserController.php');
$adminController = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/TicketController.php');
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$assert(str_contains($javascript, 'Idempotency-Key')
&& str_contains($javascript, 'requestFingerprint'),
'User ticket submissions do not retain a logical request key across retries.');
$assert(str_contains($javascript, 'if (!data.ret) done()')
|| str_contains($javascript, 'if (!data.ret) {') && str_contains($javascript, 'done();'),
'A successful ticket submission still re-enables its controls before navigation.');
$assert(str_contains($userController, "getHeaderLine('Idempotency-Key')")
&& str_contains($adminController, "getHeaderLine('Idempotency-Key')"),
'A ticket HTTP adapter does not pass the idempotency key into the write module.');
echo "Ticket page idempotency contract passed.\n";

@ -57,6 +57,17 @@ $schema->create('ticket_attachments', static function (Blueprint $table): void {
$table->string('sha256');
$table->integer('created_at');
});
$schema->create('ticket_write_requests', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('actor_user_id');
$table->string('request_key');
$table->string('request_hash');
$table->string('operation');
$table->integer('ticket_id')->nullable();
$table->integer('message_id')->nullable();
$table->integer('created_at');
$table->unique(['actor_user_id', 'request_key']);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
@ -106,7 +117,7 @@ $request = static function (array $files): object {
// public behavior used by the HTTP adapter to return "ticket not found"
// without revealing another user's ticket.
$foreignResult = $service->reply(new ReplyTicketCommand(
1, 8, 'must not be saved', 0, $request([]), 8
1, 8, 'must not be saved', 0, $request([]), 8, false, 'foreign-reply-1234'
));
$assert($foreignResult === null, 'A foreign user was able to reply to the ticket.');
$assert(Capsule::table('ticket')->where('rootid', 1)->count() === 0,
@ -125,7 +136,8 @@ $second = [
];
try {
$service->reply(new ReplyTicketCommand(
1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7
1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7,
false, 'rollback-reply-1234'
));
throw new RuntimeException('Invalid attachment unexpectedly succeeded.');
} catch (InvalidArgumentException $exception) {
@ -142,7 +154,8 @@ $assert(glob(BASE_PATH . '/storage/ticket-attachments/*') === [],
@unlink($secondPath);
$result = $service->reply(new ReplyTicketCommand(
1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7
1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7,
false, 'success-reply-1234'
));
$assert($result !== null && $result->message->rootid == 1, 'Successful reply was not created.');
$assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 0,
@ -159,7 +172,9 @@ $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 = $service->reply(new ReplyTicketCommand(1, 7, 'reopen', 1, $request([]), 7));
$reopened = $service->reply(new ReplyTicketCommand(
1, 7, 'reopen', 1, $request([]), 7, false, 'reopen-reply-1234'
));
$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,
@ -193,7 +208,8 @@ $opened = $service->open(new OpenTicketCommand(
'technical',
'high',
31,
$request([])
$request([]),
'open-ticket-123456'
));
$assert($opened->root->rootid == 0 && $opened->message->id === $opened->root->id,
'Opening a ticket did not create the root thread message.');
@ -203,7 +219,8 @@ $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([])
8, 'Foreign instance', 'Must fail', 'technical', 'medium', 31, $request([]),
'foreign-open-12345'
));
throw new RuntimeException('Foreign instance association unexpectedly succeeded.');
} catch (InvalidArgumentException $exception) {

Loading…
Cancel
Save