You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserCopy/UserCopyAdminService.php

820 lines
30 KiB
PHTML

<?php
namespace App\Services\UserCopy;
use App\Services\LocaleCode;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\ConnectionInterface;
/**
* Administrator editing and publication Module for user-interface copy.
*
* The database is an authoring and audit ledger. Runtime activation happens
* only through UserCopyPublicationStore's atomic current.json switch.
*/
final class UserCopyAdminService
{
/** @var array<string,mixed> */
private readonly array $manifest;
private readonly UserCopySourceCatalog $source;
private readonly UserCopyCatalogCompiler $compiler;
private readonly UserCopyManifestProjectionGuard $projectionGuard;
private readonly UserCopyWorkspaceReader $workspaceReader;
public function __construct(
private readonly ConnectionInterface $database,
array $manifest,
private readonly UserCopyPublicationStore $store
) {
$this->manifest = UserCopyManifest::validate($manifest);
$this->source = new UserCopySourceCatalog($this->manifest);
$this->compiler = new UserCopyCatalogCompiler($this->source);
$this->projectionGuard = new UserCopyManifestProjectionGuard(
$this->manifest
);
$this->workspaceReader = new UserCopyWorkspaceReader(
$this->database,
$this->manifest,
$this->store,
$this->projectionGuard
);
}
public static function fromApplication(): self
{
$webRoot = dirname(__DIR__, 3);
$manifest = UserCopyManifest::load();
return new self(
DB::connection('default'),
$manifest,
new UserCopyPublicationStore(
$webRoot . '/storage/framework/user-copy'
)
);
}
/** Backward-compatible factory name for command-side callers. */
public static function makeDefault(): self
{
return self::fromApplication();
}
/** @return array<string,mixed> */
public function synchronize(array $actor): array
{
$actorId = $this->authorize($actor);
return (new UserCopyManifestSynchronizer(
$this->database,
$this->manifest
))->synchronize($actorId);
}
/**
* Read model for the administrator workspace.
*
* @param array<string,mixed> $query
* @return array<string,mixed>
*/
public function workspace(array $query = []): array
{
return $this->workspaceReader->workspace($query);
}
/** @return array<string,mixed> */
public function history(
string $localeOrCopyKey,
?string $legacyLocale = null
): array {
return $this->workspaceReader->history(
$localeOrCopyKey,
$legacyLocale
);
}
/** @return array<string,mixed> */
public function saveLocale(
array $actor,
string $locale,
string $displayName,
bool $enabled = true
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
if ($locale === 'zh-CN') {
throw new UserCopyAdminException(
'中文源语言由 Manifest 管理,不能在翻译后台修改。',
409
);
}
$displayName = $this->displayName($displayName);
$localeDto = $this->database->transaction(function () use (
$actorId,
$locale,
$displayName,
$enabled
): array {
$now = time();
$row = $this->database->table('ui_copy_locales')
->where('locale', $locale)
->lockForUpdate()
->first();
$values = [
'display_name' => $displayName,
'enabled' => $enabled ? 1 : 0,
'source_claim' => null,
'updated_by' => $actorId,
'updated_at' => $now,
];
if ($row === null) {
$id = (int) $this->database->table('ui_copy_locales')
->insertGetId($values + [
'locale' => $locale,
'created_by' => $actorId,
'created_at' => $now,
]);
} else {
if ($row->source_claim !== null) {
throw new UserCopyAdminException(
'源语言登记不能改为目标语言。',
409
);
}
$id = (int) $row->id;
$this->database->table('ui_copy_locales')
->where('id', $id)
->update($values);
}
return $this->localeDto(
$this->database->table('ui_copy_locales')->where('id', $id)->first()
);
});
try {
$this->store->configureLocale(
$localeDto['locale'],
$localeDto['display_name'],
$localeDto['enabled']
);
} catch (UserCopyCatalogException $exception) {
throw new UserCopyAdminException(
'语言已保存,但运行目录同步失败;请使用相同内容重试。',
503,
$exception
);
}
return $localeDto;
}
/** @return array<string,mixed> */
public function saveDraft(
array $actor,
string $copyKey,
string $locale,
string $text,
string $visibility,
int $expectedVersion
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if ($expectedVersion < 0) {
throw new UserCopyAdminException('草稿版本无效。', 400);
}
if (!in_array($visibility, ['visible', 'hidden'], true)) {
throw new UserCopyAdminException('草稿可见性无效。', 400);
}
if (!mb_check_encoding($text, 'UTF-8')) {
throw new UserCopyAdminException('草稿必须是有效的 UTF-8 文本。', 422);
}
return $this->database->transaction(function () use (
$actorId,
$copyKey,
$locale,
$text,
$visibility,
$expectedVersion
): array {
$localeRow = $this->targetLocale($locale, true);
$entry = $this->database->table('ui_copy_entries')
->where('copy_key', $copyKey)
->where('state', 'active')
->lockForUpdate()
->first();
if ($entry === null) {
throw new UserCopyAdminException(
'词条不存在、已孤立或尚未同步。',
404
);
}
if ($visibility === 'hidden'
&& ((int) $entry->allow_hide !== 1
|| (int) $entry->required === 1
|| (string) $entry->criticality !== 'normal')) {
throw new UserCopyAdminException(
'必需或高风险词条不能隐藏。',
422
);
}
$draft = $this->database->table('ui_copy_drafts')
->where('entry_id', (int) $entry->id)
->where('locale_id', (int) $localeRow->id)
->lockForUpdate()
->first();
$actualVersion = $draft === null
? 0 : (int) $draft->draft_version;
if ($actualVersion !== $expectedVersion) {
throw new UserCopyAdminException(
'草稿已被其他管理员修改,请重新加载。',
409
);
}
$errors = $this->validateDraft(
$copyKey,
$locale,
$text,
$visibility
);
$now = time();
$values = [
'draft_text' => $text,
'draft_hash' => hash('sha256', $text),
'visibility' => $visibility,
'translated_source_hash_zh' => (string) $entry->source_hash_zh,
'translated_placeholder_hash' => (string) $entry->placeholder_hash,
'draft_version' => $actualVersion + 1,
'validation_state' => $errors === [] ? 'valid' : 'invalid',
'validation_errors_json' => UserCopySourceCatalog::canonicalJson(
$errors
),
'updated_by' => $actorId,
'updated_at' => $now,
];
if ($draft === null) {
$id = (int) $this->database->table('ui_copy_drafts')
->insertGetId($values + [
'entry_id' => (int) $entry->id,
'locale_id' => (int) $localeRow->id,
'created_by' => $actorId,
'created_at' => $now,
]);
} else {
$id = (int) $draft->id;
$this->database->table('ui_copy_drafts')
->where('id', $id)
->update($values);
}
return $this->draftDto(
$this->database->table('ui_copy_drafts')->where('id', $id)->first()
);
});
}
/** @return array<string,mixed> */
public function publish(
array $actor,
string $locale,
string $requestIdempotencyKey
): array {
$actorId = $this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if (preg_match('/\A[a-f0-9]{64}\z/D', $requestIdempotencyKey) !== 1) {
throw new UserCopyAdminException('发布幂等标识无效。', 400);
}
$prepared = $this->database->transaction(function () use (
$actorId,
$locale,
$requestIdempotencyKey
): array {
$localeRow = $this->targetLocale($locale, true);
$localeMetadata = [
'display_name' => (string) $localeRow->display_name,
'enabled' => (bool) $localeRow->enabled,
];
$existingRequest = $this->database->table('ui_copy_publications')
->where('requested_by', $actorId)
->where('request_idempotency_key', $requestIdempotencyKey)
->lockForUpdate()
->first();
[$entries, $translations, $draftVersions] =
$this->publicationInputs((int) $localeRow->id);
$compiled = $this->compiler->compile($locale, $translations);
$fingerprint = hash(
'sha256',
UserCopySourceCatalog::canonicalJson([
'locale' => $locale,
'generation' => $compiled->generation,
])
);
if ($existingRequest !== null) {
if (!hash_equals(
(string) $existingRequest->request_fingerprint,
$fingerprint
)) {
throw new UserCopyAdminException(
'发布幂等标识已用于其他内容。',
409
);
}
if ((string) $existingRequest->state === 'ready') {
return [
'existing' => true,
'publication' => $existingRequest,
'compiled' => $compiled,
'locale_metadata' => $localeMetadata,
];
}
if (!in_array(
(string) $existingRequest->state,
['preparing', 'failed'],
true
)) {
throw new UserCopyAdminException(
'原发布请求尚未成功完成,请核对后再操作。',
409
);
}
if ((string) $existingRequest->state === 'failed') {
$this->database->table('ui_copy_publications')
->where('id', (int) $existingRequest->id)
->where('state', 'failed')
->update([
'state' => 'preparing',
'error_code' => '',
'updated_at' => time(),
]);
}
return [
'existing' => false,
'publication_id' => (int) $existingRequest->id,
'compiled' => $compiled,
'locale_metadata' => $localeMetadata,
];
}
$sameGeneration = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('catalog_generation', $compiled->generation)
->where('state', 'ready')
->lockForUpdate()
->first();
if ($sameGeneration !== null) {
return [
'existing' => true,
'publication' => $sameGeneration,
'compiled' => $compiled,
'locale_metadata' => $localeMetadata,
];
}
$preparing = $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('state', 'preparing')
->lockForUpdate()
->first();
if ($preparing !== null) {
throw new UserCopyAdminException(
'该语言已有发布正在准备,请稍后核对。',
409
);
}
$current = $this->store->current();
$currentGeneration = $current['locales'][$locale]['generation']
?? null;
$previous = is_string($currentGeneration)
? $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->where('catalog_generation', $currentGeneration)
->where('state', 'ready')
->first()
: null;
$revision = (int) $this->database->table('ui_copy_publications')
->where('locale_id', (int) $localeRow->id)
->lockForUpdate()
->max('revision') + 1;
$now = time();
$publicationKey = bin2hex(random_bytes(16));
$publicationId = (int) $this->database
->table('ui_copy_publications')->insertGetId([
'publication_key' => $publicationKey,
'locale_id' => (int) $localeRow->id,
'revision' => $revision,
'catalog_generation' => $compiled->generation,
'previous_publication_id' => $previous === null
? null : (int) $previous->id,
'manifest_revision' => (int) $this->manifest['version'],
'manifest_hash' => $this->source->sourceHash(),
'catalog_hash' => '',
'artifact_path' => '',
'entry_count' => count($entries),
'state' => 'preparing',
'request_idempotency_key' => $requestIdempotencyKey,
'request_fingerprint' => $fingerprint,
'requested_by' => $actorId,
'published_by' => null,
'prepared_at' => $now,
'published_at' => 0,
'error_code' => '',
'created_at' => $now,
'updated_at' => $now,
]);
foreach ($entries as $copyKey => $entry) {
$scope = (string) $entry->scope;
$payload = $compiled->scopes[$scope] ?? null;
if (!is_array($payload)
|| !array_key_exists($copyKey, $payload['messages'] ?? [])) {
throw new UserCopyAdminException(
'编译结果缺少词条:' . $copyKey,
500
);
}
$publishedText = (string) $payload['messages'][$copyKey];
$hidden = (bool) ($payload['metadata'][$copyKey]['hidden'] ?? false);
$this->database->table('ui_copy_revision_items')->insert([
'publication_id' => $publicationId,
'entry_id' => (int) $entry->id,
'copy_key' => $copyKey,
'source_text_zh' => (string) $entry->source_text_zh,
'published_text' => $publishedText,
'visibility' => $hidden ? 'hidden' : 'visible',
'source_hash_zh' => (string) $entry->source_hash_zh,
'placeholder_contract_json' =>
(string) $entry->placeholder_contract_json,
'placeholder_hash' => (string) $entry->placeholder_hash,
'published_hash' => hash('sha256', $publishedText),
'manifest_revision' => (int) $entry->manifest_revision,
'draft_version' => $draftVersions[$copyKey] ?? null,
'created_at' => $now,
]);
}
return [
'existing' => false,
'publication_id' => $publicationId,
'compiled' => $compiled,
'locale_metadata' => $localeMetadata,
];
});
/** @var UserCopyCompiledCatalog $compiled */
$compiled = $prepared['compiled'];
if (($prepared['existing'] ?? false) === true) {
try {
$metadata = $prepared['locale_metadata'];
$this->store->configureLocale(
$locale,
(string) $metadata['display_name'],
(bool) $metadata['enabled']
);
} catch (UserCopyCatalogException $exception) {
throw new UserCopyAdminException(
'发布版本存在,但语言运行目录同步失败;请保留原请求重试。',
503,
$exception
);
}
$current = $this->store->current();
$pointer = $current['locales'][$locale] ?? [];
return $this->publicationDto(
$prepared['publication'],
is_array($pointer) ? $pointer : []
);
}
$publicationId = (int) $prepared['publication_id'];
try {
$pointer = $this->store->publish(
$compiled,
$prepared['locale_metadata']
);
} catch (\Throwable $exception) {
try {
$current = $this->store->current();
$active = $current['locales'][$locale] ?? null;
if (!is_array($active)
|| ($active['generation'] ?? null) !== $compiled->generation) {
$this->database->table('ui_copy_publications')
->where('id', $publicationId)
->where('state', 'preparing')
->update([
'state' => 'failed',
'error_code' => 'publication_store_failed',
'updated_at' => time(),
]);
throw new UserCopyAdminException(
'编译目录发布失败,原运行版本保持不变。',
503,
$exception
);
}
$this->store->validateGeneration($compiled->generation);
$pointer = $active;
} catch (UserCopyAdminException $known) {
throw $known;
} catch (\Throwable $reconciliationFailure) {
throw new UserCopyAdminException(
'发布结果无法确认,请保留原幂等标识核对,切勿创建新发布请求。',
503,
$reconciliationFailure
);
}
}
$publishedAt = time();
$updated = $this->database->table('ui_copy_publications')
->where('id', $publicationId)
->where('state', 'preparing')
->update([
'catalog_hash' => (string) $compiled->manifest['catalog_sha256'],
'artifact_path' => 'generations/' . $compiled->generation,
'state' => 'ready',
'published_by' => $actorId,
'published_at' => $publishedAt,
'updated_at' => $publishedAt,
]);
if ($updated !== 1) {
throw new UserCopyAdminException(
'运行版本已切换,但发布账本最终化失败,请人工核对。',
503
);
}
$publication = $this->database->table('ui_copy_publications')
->where('id', $publicationId)
->first();
return $this->publicationDto($publication, $pointer);
}
/** @return array<string,mixed> */
public function rollback(
array $actor,
string $locale,
string $publicationKey
): array {
$this->authorize($actor);
$locale = $this->normalizeLocale($locale);
$this->assertTargetLocale($locale);
if (preg_match('/\A[a-f0-9]{32}\z/D', $publicationKey) !== 1) {
throw new UserCopyAdminException('回滚版本标识无效。', 400);
}
$publication = $this->database->transaction(function () use (
$locale,
$publicationKey
) {
$localeRow = $this->targetLocale($locale, true);
$row = $this->database->table('ui_copy_publications')
->where('publication_key', $publicationKey)
->where('locale_id', (int) $localeRow->id)
->where('state', 'ready')
->lockForUpdate()
->first();
if ($row === null) {
throw new UserCopyAdminException('可回滚版本不存在。', 404);
}
if (!hash_equals(
(string) $row->manifest_hash,
$this->source->sourceHash()
)) {
throw new UserCopyAdminException(
'该版本属于旧 Manifest,不能恢复为当前运行版本。',
409
);
}
return $row;
});
$pointer = $this->store->rollback(
$locale,
(string) $publication->catalog_generation
);
return $this->publicationDto($publication, $pointer);
}
/**
* @return array{0:array<string,object>,1:array<string,string|array<string,mixed>>,2:array<string,int>}
*/
private function publicationInputs(int $localeId): array
{
$databaseEntries = $this->database->table('ui_copy_entries')
->where('state', 'active')
->orderBy('copy_key')
->lockForUpdate()
->get()
->all();
$entries = [];
foreach ($databaseEntries as $entry) {
$entries[(string) $entry->copy_key] = $entry;
}
$this->projectionGuard->assertReady($entries);
$drafts = $this->database->table('ui_copy_drafts')
->where('locale_id', $localeId)
->whereIn('entry_id', array_map(
static fn ($entry): int => (int) $entry->id,
$databaseEntries
))
->lockForUpdate()
->get()
->all();
$draftsByEntry = [];
foreach ($drafts as $draft) {
$draftsByEntry[(int) $draft->entry_id] = $draft;
}
$translations = [];
$draftVersions = [];
foreach ($entries as $copyKey => $entry) {
$draft = $draftsByEntry[(int) $entry->id] ?? null;
if ($draft === null) {
continue;
}
$currentContract = hash_equals(
(string) $draft->translated_source_hash_zh,
(string) $entry->source_hash_zh
) && hash_equals(
(string) $draft->translated_placeholder_hash,
(string) $entry->placeholder_hash
);
if (!$currentContract || (string) $draft->validation_state !== 'valid') {
if (!$currentContract) {
$this->database->table('ui_copy_drafts')
->where('id', (int) $draft->id)
->update([
'validation_state' => 'stale',
'validation_errors_json' =>
UserCopySourceCatalog::canonicalJson([
'source_contract_changed',
]),
'updated_at' => time(),
]);
}
throw new UserCopyAdminException(
'存在无效或过期草稿,不能发布:' . $copyKey,
422
);
}
$translations[$copyKey] = (string) $draft->visibility === 'hidden'
? ['hidden' => true]
: (string) $draft->draft_text;
$draftVersions[$copyKey] = (int) $draft->draft_version;
}
return [$entries, $translations, $draftVersions];
}
/** @return list<string> */
private function validateDraft(
string $copyKey,
string $locale,
string $text,
string $visibility
): array {
try {
$this->compiler->compile($locale, [
$copyKey => $visibility === 'hidden'
? ['hidden' => true]
: $text,
]);
return [];
} catch (UserCopyCatalogException $exception) {
return [$exception->getMessage()];
}
}
private function targetLocale(string $locale, bool $lock): object
{
$query = $this->database->table('ui_copy_locales')
->where('locale', $locale);
if ($lock) {
$query->lockForUpdate();
}
$row = $query->first();
if ($row === null || (int) $row->enabled !== 1) {
throw new UserCopyAdminException('目标语言未启用。', 409);
}
if ($row->source_claim !== null) {
throw new UserCopyAdminException('源语言不能保存翻译草稿。', 409);
}
return $row;
}
private function assertTargetLocale(string $locale): void
{
if ($locale === 'zh-CN') {
throw new UserCopyAdminException('中文基线不能作为翻译草稿。', 409);
}
}
private function authorize(array $actor): int
{
$actorId = (int) ($actor['user_id'] ?? 0);
if ($actorId < 1) {
throw new UserCopyAdminException('请先登录。', 401);
}
if (!($actor['is_admin'] ?? false)) {
throw new UserCopyAdminException('只有管理员可以管理界面文案。', 403);
}
if (!($actor['is_super_admin'] ?? false)
|| !($actor['can_manage'] ?? false)) {
throw new UserCopyAdminException(
'只有超级管理员可以修改或发布界面文案。',
403
);
}
return $actorId;
}
private function normalizeLocale(string $locale): string
{
$normalized = LocaleCode::canonicalize($locale);
if ($normalized === null) {
throw new UserCopyAdminException('语言代码无效。', 400);
}
return $normalized;
}
private function displayName(string $displayName): string
{
$displayName = trim($displayName);
if ($displayName === ''
|| !mb_check_encoding($displayName, 'UTF-8')
|| mb_strlen($displayName, 'UTF-8') > 128
|| preg_match('/[\x00-\x1F\x7F]/u', $displayName) === 1) {
throw new UserCopyAdminException('语言显示名称无效。', 422);
}
return $displayName;
}
/** @return array<string,mixed> */
private function localeDto(?object $row): array
{
if ($row === null) {
throw new UserCopyAdminException('语言保存结果不存在。', 500);
}
return [
'id' => (int) $row->id,
'locale' => (string) $row->locale,
'display_name' => (string) $row->display_name,
'enabled' => (bool) $row->enabled,
'source' => $row->source_claim !== null,
];
}
/** @return array<string,mixed> */
private function draftDto(?object $row): array
{
if ($row === null) {
throw new UserCopyAdminException('草稿保存结果不存在。', 500);
}
try {
$errors = json_decode(
(string) $row->validation_errors_json,
true,
32,
JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
$errors = ['validation_result_corrupt'];
}
return [
'id' => (int) $row->id,
'entry_id' => (int) $row->entry_id,
'locale_id' => (int) $row->locale_id,
'text' => (string) $row->draft_text,
'visibility' => (string) $row->visibility,
'version' => (int) $row->draft_version,
'validation_state' => (string) $row->validation_state,
'validation_errors' => is_array($errors) ? $errors : [],
];
}
/** @return array<string,mixed> */
private function publicationDto(?object $row, array $pointer): array
{
if ($row === null) {
throw new UserCopyAdminException('发布结果不存在。', 500);
}
return [
'id' => (int) $row->id,
'publication_key' => (string) $row->publication_key,
'revision' => (int) $row->revision,
'generation' => (string) $row->catalog_generation,
'state' => (string) $row->state,
'entry_count' => (int) $row->entry_count,
'current' => $pointer,
];
}
}