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.
538 lines
19 KiB
PHP
538 lines
19 KiB
PHP
<?php
|
|
|
|
namespace App\Services\UserCopy;
|
|
|
|
use App\Services\LocaleCode;
|
|
|
|
/**
|
|
* Filesystem Adapter for immutable locale generations.
|
|
*
|
|
* A generation is fully fsynced and atomically renamed before current.json is
|
|
* switched. Publication failures can therefore leave only an unreachable
|
|
* immutable generation; the previously active pointer remains authoritative.
|
|
*/
|
|
final class UserCopyPublicationStore
|
|
{
|
|
private readonly string $root;
|
|
|
|
public function __construct(string $rootDirectory)
|
|
{
|
|
$rootDirectory = rtrim($rootDirectory, DIRECTORY_SEPARATOR);
|
|
if ($rootDirectory === '') {
|
|
throw new UserCopyCatalogException(
|
|
'User copy publication directory cannot be empty.'
|
|
);
|
|
}
|
|
$this->ensureDirectory($rootDirectory);
|
|
$resolved = realpath($rootDirectory);
|
|
if (!is_string($resolved) || $resolved === '') {
|
|
throw new UserCopyCatalogException(
|
|
'User copy publication directory cannot be resolved.'
|
|
);
|
|
}
|
|
$this->root = $resolved;
|
|
$this->ensureDirectory($this->root . '/generations');
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function publish(
|
|
UserCopyCompiledCatalog $catalog,
|
|
?array $localeMetadata = null
|
|
): array
|
|
{
|
|
return $this->withPublicationLock(function () use (
|
|
$catalog,
|
|
$localeMetadata
|
|
): array {
|
|
$this->assertGeneration($catalog->generation);
|
|
$target = $this->generationDirectory($catalog->generation);
|
|
if (is_dir($target)) {
|
|
$manifest = $this->validateGeneration($catalog->generation);
|
|
if (($manifest['locale'] ?? null) !== $catalog->locale
|
|
|| !hash_equals(
|
|
(string) ($manifest['catalog_sha256'] ?? ''),
|
|
(string) ($catalog->manifest['catalog_sha256'] ?? '')
|
|
)) {
|
|
throw new UserCopyCatalogException(
|
|
'An incompatible immutable user copy generation exists.'
|
|
);
|
|
}
|
|
} else {
|
|
$this->materializeGeneration($catalog);
|
|
$this->validateGeneration($catalog->generation);
|
|
}
|
|
|
|
$current = $this->readCurrentPointer();
|
|
$manifestHash = hash(
|
|
'sha256',
|
|
$this->readRequiredFile($target . '/manifest.json')
|
|
);
|
|
$current['locales'][$catalog->locale] = [
|
|
'generation' => $catalog->generation,
|
|
'manifest_sha256' => $manifestHash,
|
|
'catalog_sha256' => $catalog->manifest['catalog_sha256'],
|
|
];
|
|
if ($localeMetadata !== null) {
|
|
$current['locale_directory'][$catalog->locale] =
|
|
$this->localeMetadata($localeMetadata);
|
|
ksort($current['locale_directory'], SORT_STRING);
|
|
}
|
|
ksort($current['locales'], SORT_STRING);
|
|
$current['updated_at'] = gmdate('c');
|
|
$this->writeCurrentPointer($current);
|
|
return $current['locales'][$catalog->locale];
|
|
});
|
|
}
|
|
|
|
/** @return array{display_name:string,enabled:bool} */
|
|
public function configureLocale(
|
|
string $locale,
|
|
string $displayName,
|
|
bool $enabled
|
|
): array {
|
|
return $this->withPublicationLock(function () use (
|
|
$locale,
|
|
$displayName,
|
|
$enabled
|
|
): array {
|
|
$locale = $this->normalizeLocale($locale);
|
|
$metadata = $this->localeMetadata([
|
|
'display_name' => $displayName,
|
|
'enabled' => $enabled,
|
|
]);
|
|
$current = $this->readCurrentPointer();
|
|
$current['locale_directory'][$locale] = $metadata;
|
|
ksort($current['locale_directory'], SORT_STRING);
|
|
$current['updated_at'] = gmdate('c');
|
|
$this->writeCurrentPointer($current);
|
|
return $metadata;
|
|
});
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function rollback(string $locale, string $generation): array
|
|
{
|
|
return $this->withPublicationLock(function () use (
|
|
$locale,
|
|
$generation
|
|
): array {
|
|
$locale = $this->normalizeLocale($locale);
|
|
$manifest = $this->validateGeneration($generation);
|
|
if (($manifest['locale'] ?? null) !== $locale) {
|
|
throw new UserCopyCatalogException(
|
|
'User copy generation belongs to another locale.'
|
|
);
|
|
}
|
|
|
|
$manifestPath = $this->generationDirectory($generation)
|
|
. '/manifest.json';
|
|
$current = $this->readCurrentPointer();
|
|
$current['locales'][$locale] = [
|
|
'generation' => $generation,
|
|
'manifest_sha256' => hash(
|
|
'sha256',
|
|
$this->readRequiredFile($manifestPath)
|
|
),
|
|
'catalog_sha256' => $manifest['catalog_sha256'],
|
|
];
|
|
ksort($current['locales'], SORT_STRING);
|
|
$current['updated_at'] = gmdate('c');
|
|
$this->writeCurrentPointer($current);
|
|
return $current['locales'][$locale];
|
|
});
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function current(): array
|
|
{
|
|
return $this->readCurrentPointer();
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function validateGeneration(string $generation): array
|
|
{
|
|
$this->assertGeneration($generation);
|
|
$directory = $this->generationDirectory($generation);
|
|
$raw = $this->readRequiredFile($directory . '/manifest.json');
|
|
try {
|
|
$manifest = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
|
} catch (\JsonException $exception) {
|
|
throw new UserCopyCatalogException(
|
|
'User copy generation manifest is invalid.',
|
|
0,
|
|
$exception
|
|
);
|
|
}
|
|
if (!is_array($manifest)
|
|
|| ($manifest['schema'] ?? null) !== 1
|
|
|| ($manifest['generation'] ?? null) !== $generation
|
|
|| !is_string($manifest['locale'] ?? null)
|
|
|| !is_string($manifest['catalog_sha256'] ?? null)
|
|
|| !is_array($manifest['scopes'] ?? null)) {
|
|
throw new UserCopyCatalogException(
|
|
'User copy generation manifest has an invalid shape.'
|
|
);
|
|
}
|
|
|
|
$locale = $this->normalizeLocale($manifest['locale']);
|
|
$scopeHashes = [];
|
|
foreach ($manifest['scopes'] as $scope => $descriptor) {
|
|
$this->assertScope($scope);
|
|
if (!is_array($descriptor)
|
|
|| ($descriptor['php'] ?? null) !== $locale . '/' . $scope . '.php'
|
|
|| ($descriptor['json'] ?? null) !== $locale . '/' . $scope . '.json'
|
|
|| preg_match(
|
|
'/\A[a-f0-9]{64}\z/D',
|
|
(string) ($descriptor['payload_sha256'] ?? '')
|
|
) !== 1) {
|
|
throw new UserCopyCatalogException(
|
|
'User copy scope descriptor is invalid: ' . $scope
|
|
);
|
|
}
|
|
$jsonRaw = $this->readRequiredFile(
|
|
$directory . '/' . $descriptor['json']
|
|
);
|
|
try {
|
|
$jsonPayload = json_decode(
|
|
$jsonRaw,
|
|
true,
|
|
512,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
} catch (\JsonException $exception) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy JSON is invalid: ' . $scope,
|
|
0,
|
|
$exception
|
|
);
|
|
}
|
|
$phpPath = $directory . '/' . $descriptor['php'];
|
|
if (!is_file($phpPath)) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy PHP is missing: ' . $scope
|
|
);
|
|
}
|
|
try {
|
|
$phpPayload = require $phpPath;
|
|
} catch (\Throwable $exception) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy PHP is invalid: ' . $scope,
|
|
0,
|
|
$exception
|
|
);
|
|
}
|
|
if (!is_array($jsonPayload) || !is_array($phpPayload)
|
|
|| UserCopySourceCatalog::canonicalJson($jsonPayload)
|
|
!== UserCopySourceCatalog::canonicalJson($phpPayload)) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy scope formats disagree: ' . $scope
|
|
);
|
|
}
|
|
$payloadHash = hash(
|
|
'sha256',
|
|
UserCopySourceCatalog::canonicalJson($phpPayload)
|
|
);
|
|
if (!hash_equals($descriptor['payload_sha256'], $payloadHash)) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy scope identity is invalid: ' . $scope
|
|
);
|
|
}
|
|
$scopeHashes[$scope] = $payloadHash;
|
|
}
|
|
ksort($scopeHashes, SORT_STRING);
|
|
$catalogHash = hash(
|
|
'sha256',
|
|
UserCopySourceCatalog::canonicalJson($scopeHashes)
|
|
);
|
|
if (!hash_equals($manifest['catalog_sha256'], $catalogHash)) {
|
|
throw new UserCopyCatalogException(
|
|
'Compiled user copy catalog identity is invalid.'
|
|
);
|
|
}
|
|
return $manifest;
|
|
}
|
|
|
|
private function materializeGeneration(UserCopyCompiledCatalog $catalog): void
|
|
{
|
|
$temporary = $this->root . '/generations/.tmp-'
|
|
. bin2hex(random_bytes(12));
|
|
$target = $this->generationDirectory($catalog->generation);
|
|
$this->ensureDirectory($temporary);
|
|
try {
|
|
$localeDirectory = $temporary . '/' . $catalog->locale;
|
|
$this->ensureDirectory($localeDirectory);
|
|
foreach ($catalog->scopes as $scope => $payload) {
|
|
$this->assertScope($scope);
|
|
$this->writeSyncedFile(
|
|
$localeDirectory . '/' . $scope . '.json',
|
|
UserCopySourceCatalog::canonicalJson($payload)
|
|
);
|
|
$this->writeSyncedFile(
|
|
$localeDirectory . '/' . $scope . '.php',
|
|
"<?php\n\nreturn " . var_export($payload, true) . ";\n"
|
|
);
|
|
}
|
|
$this->syncDirectory($localeDirectory);
|
|
$this->writeSyncedFile(
|
|
$temporary . '/manifest.json',
|
|
UserCopySourceCatalog::canonicalJson($catalog->manifest)
|
|
);
|
|
$this->syncDirectory($temporary);
|
|
if (!rename($temporary, $target)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to publish immutable user copy generation.'
|
|
);
|
|
}
|
|
$this->syncDirectory($this->root . '/generations');
|
|
} finally {
|
|
if (is_dir($temporary)) {
|
|
$this->removeTemporaryDirectory($temporary);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function readCurrentPointer(): array
|
|
{
|
|
$path = $this->root . '/current.json';
|
|
if (!is_file($path)) {
|
|
return [
|
|
'schema' => 1,
|
|
'locales' => [],
|
|
'locale_directory' => [],
|
|
];
|
|
}
|
|
$raw = $this->readRequiredFile($path);
|
|
try {
|
|
$current = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
|
} catch (\JsonException $exception) {
|
|
throw new UserCopyCatalogException(
|
|
'Current user copy pointer is invalid.',
|
|
0,
|
|
$exception
|
|
);
|
|
}
|
|
if (!is_array($current)
|
|
|| ($current['schema'] ?? null) !== 1
|
|
|| !is_array($current['locales'] ?? null)) {
|
|
throw new UserCopyCatalogException(
|
|
'Current user copy pointer has an invalid shape.'
|
|
);
|
|
}
|
|
if (!array_key_exists('locale_directory', $current)) {
|
|
$current['locale_directory'] = [];
|
|
}
|
|
if (!is_array($current['locale_directory'])) {
|
|
throw new UserCopyCatalogException(
|
|
'Current user copy locale directory has an invalid shape.'
|
|
);
|
|
}
|
|
foreach ($current['locale_directory'] as $locale => $metadata) {
|
|
if (!is_string($locale)
|
|
|| $this->normalizeLocale($locale) !== $locale
|
|
|| !is_array($metadata)) {
|
|
throw new UserCopyCatalogException(
|
|
'Current user copy locale directory is invalid.'
|
|
);
|
|
}
|
|
$current['locale_directory'][$locale] =
|
|
$this->localeMetadata($metadata);
|
|
}
|
|
return $current;
|
|
}
|
|
|
|
/** @return array{display_name:string,enabled:bool} */
|
|
private function localeMetadata(array $metadata): array
|
|
{
|
|
$displayName = isset($metadata['display_name'])
|
|
&& is_string($metadata['display_name'])
|
|
? trim($metadata['display_name']) : '';
|
|
if ($displayName === '' || !mb_check_encoding($displayName, 'UTF-8')
|
|
|| mb_strlen($displayName, 'UTF-8') > 128
|
|
|| preg_match('/[\x00-\x1F\x7F]/u', $displayName) === 1
|
|
|| !array_key_exists('enabled', $metadata)
|
|
|| !is_bool($metadata['enabled'])) {
|
|
throw new UserCopyCatalogException(
|
|
'User copy locale metadata is invalid.'
|
|
);
|
|
}
|
|
return [
|
|
'display_name' => $displayName,
|
|
'enabled' => $metadata['enabled'],
|
|
];
|
|
}
|
|
|
|
/** @param array<string,mixed> $current */
|
|
private function writeCurrentPointer(array $current): void
|
|
{
|
|
$temporary = $this->root . '/.current-'
|
|
. bin2hex(random_bytes(12)) . '.tmp';
|
|
try {
|
|
$this->writeSyncedFile(
|
|
$temporary,
|
|
UserCopySourceCatalog::canonicalJson($current)
|
|
);
|
|
if (!rename($temporary, $this->root . '/current.json')) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to switch the current user copy generation.'
|
|
);
|
|
}
|
|
$this->syncDirectory($this->root);
|
|
} finally {
|
|
if (is_file($temporary)) {
|
|
@unlink($temporary);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @template T @param callable():T $callback @return T */
|
|
private function withPublicationLock(callable $callback)
|
|
{
|
|
$handle = fopen($this->root . '/publish.lock', 'c+b');
|
|
if (!is_resource($handle)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to open the user copy publication lock.'
|
|
);
|
|
}
|
|
try {
|
|
if (!flock($handle, LOCK_EX)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to acquire the user copy publication lock.'
|
|
);
|
|
}
|
|
return $callback();
|
|
} finally {
|
|
flock($handle, LOCK_UN);
|
|
fclose($handle);
|
|
}
|
|
}
|
|
|
|
private function writeSyncedFile(string $path, string $contents): void
|
|
{
|
|
$handle = fopen($path, 'x+b');
|
|
if (!is_resource($handle)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to create compiled user copy file.'
|
|
);
|
|
}
|
|
try {
|
|
$length = strlen($contents);
|
|
$written = 0;
|
|
while ($written < $length) {
|
|
$count = fwrite($handle, substr($contents, $written));
|
|
if (!is_int($count) || $count < 1) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to write compiled user copy file.'
|
|
);
|
|
}
|
|
$written += $count;
|
|
}
|
|
if (!fflush($handle) || !fsync($handle)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to sync compiled user copy file.'
|
|
);
|
|
}
|
|
} finally {
|
|
fclose($handle);
|
|
}
|
|
@chmod($path, 0640);
|
|
}
|
|
|
|
private function syncDirectory(string $path): void
|
|
{
|
|
$handle = fopen($path, 'r');
|
|
if (!is_resource($handle)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to open user copy directory for syncing.'
|
|
);
|
|
}
|
|
try {
|
|
if (!fsync($handle)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to sync user copy directory.'
|
|
);
|
|
}
|
|
} finally {
|
|
fclose($handle);
|
|
}
|
|
}
|
|
|
|
private function ensureDirectory(string $path): void
|
|
{
|
|
if (is_dir($path)) {
|
|
return;
|
|
}
|
|
if (!mkdir($path, 0750, true) && !is_dir($path)) {
|
|
throw new UserCopyCatalogException(
|
|
'Unable to create user copy publication directory.'
|
|
);
|
|
}
|
|
}
|
|
|
|
private function readRequiredFile(string $path): string
|
|
{
|
|
$contents = is_file($path) ? file_get_contents($path) : false;
|
|
if (!is_string($contents)) {
|
|
throw new UserCopyCatalogException(
|
|
'Required user copy publication file is unavailable.'
|
|
);
|
|
}
|
|
return $contents;
|
|
}
|
|
|
|
private function generationDirectory(string $generation): string
|
|
{
|
|
return $this->root . '/generations/' . $generation;
|
|
}
|
|
|
|
private function assertGeneration(string $generation): void
|
|
{
|
|
if (preg_match('/\Ag-[a-f0-9]{64}\z/D', $generation) !== 1) {
|
|
throw new UserCopyCatalogException(
|
|
'Invalid user copy generation identifier.'
|
|
);
|
|
}
|
|
}
|
|
|
|
private function assertScope(string $scope): void
|
|
{
|
|
if (preg_match('/\A[a-z0-9][a-z0-9._-]{0,63}\z/D', $scope) !== 1) {
|
|
throw new UserCopyCatalogException('Invalid user copy scope.');
|
|
}
|
|
}
|
|
|
|
private function normalizeLocale(string $locale): string
|
|
{
|
|
$normalized = LocaleCode::canonicalize($locale);
|
|
if ($normalized === null) {
|
|
throw new UserCopyCatalogException('Invalid user copy locale.');
|
|
}
|
|
return $normalized;
|
|
}
|
|
|
|
private function removeTemporaryDirectory(string $directory): void
|
|
{
|
|
$prefix = $this->root . '/generations/.tmp-';
|
|
if (!str_starts_with($directory, $prefix)) {
|
|
throw new UserCopyCatalogException(
|
|
'Refusing to remove a non-temporary user copy directory.'
|
|
);
|
|
}
|
|
$iterator = new \RecursiveIteratorIterator(
|
|
new \RecursiveDirectoryIterator(
|
|
$directory,
|
|
\FilesystemIterator::SKIP_DOTS
|
|
),
|
|
\RecursiveIteratorIterator::CHILD_FIRST
|
|
);
|
|
foreach ($iterator as $item) {
|
|
if ($item->isDir()) {
|
|
@rmdir($item->getPathname());
|
|
} else {
|
|
@unlink($item->getPathname());
|
|
}
|
|
}
|
|
@rmdir($directory);
|
|
}
|
|
}
|