Fix extension translations staying cached after an extension update

Fixes #7245
This commit is contained in:
Anthony
2026-10-06 00:18:41 -05:00
parent 0a688b2eac
commit e52fdfd416
9 changed files with 160 additions and 9 deletions
+16 -6
View File
@@ -35,13 +35,23 @@ class LocaleController extends Controller
JsonValueGuard::assertValue($translations);
$response[$locale][$namespace] = $this->i18n($translations);
return new JsonResponse($response, 200, [
// Cache this in the browser for an hour, and allow the browser to use a stale
// cache for up to a day after it was created while it fetches an updated set
// of translation keys.
'Cache-Control' => 'public, max-age=3600, stale-while-revalidate=86400',
'ETag' => hash('sha256', json_encode($response, JSON_THROW_ON_ERROR)),
$json = new JsonResponse($response, 200, [
// Core translations only change with a panel build, and the frontend puts the
// build hash in the URL: cache them in the browser for an hour, and allow a stale
// copy for up to a day while it fetches an updated set of translation keys.
//
// An extension's translations change whenever it is installed or upgraded, so
// the frontend adds their revision to the URL and they are cached the same way.
// Without it the URL would stay the same, and the browser has to revalidate.
'Cache-Control' => count($segments) === 2 && ! $request->has('revision')
? 'no-cache'
: 'public, max-age=3600, stale-while-revalidate=86400',
]);
$json->setEtag(hash('sha256', json_encode($response, JSON_THROW_ON_ERROR)));
// Answers a matching If-None-Match with an empty 304, which keeps revalidation cheap.
$json->isNotModified($request);
return $json;
}
/**
+2
View File
@@ -16,6 +16,8 @@ class LocaleRequest extends FormRequest
return [
'locale' => ['required', 'string', 'regex:/^[a-z][a-z]$/'],
'namespace' => ['required', 'string', 'regex:/^(?:[a-z]{1,191}|ext-[a-z][a-z0-9-]{0,47}::[a-z][a-z0-9_-]{0,63})$/'],
// The revision of an extension's translations, which only makes the URL unique.
'revision' => ['sometimes', 'string', 'regex:/^[a-f0-9]{32}$/'],
];
}
}
@@ -6,12 +6,14 @@ namespace Pterodactyl\Services\Extensions;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Pterodactyl\Events\Extensions\ExtensionLoadFailed;
use Pterodactyl\Exceptions\Extensions\InvalidExtensionException;
use Pterodactyl\Models\Extension;
use Pterodactyl\Support\JsonValueGuard;
use Symfony\Component\Finder\SplFileInfo;
use Throwable;
class ExtensionRepository
@@ -152,7 +154,7 @@ class ExtensionRepository
* The enabled frontend extensions for the SPA to load. Signed-in users receive
* each extension's frontend settings; everyone else only those marked ->public().
*
* @return array<int, array{id: string, version: string, entry: string, prefix: string|null, config: object, screens: list<ExtensionScreenDefinition>, components: list<string>, development: array{url: string, version: string}|null}>
* @return array<int, array{id: string, version: string, entry: string, prefix: string|null, translations: string|null, config: object, screens: list<ExtensionScreenDefinition>, components: list<string>, development: array{url: string, version: string}|null}>
*/
public function frontendPayload(bool $authenticated): array
{
@@ -167,6 +169,7 @@ class ExtensionRepository
'version' => $manifest->version,
'entry' => $this->assets->entryUrl($manifest),
'prefix' => $manifest->uiPrefix,
'translations' => $this->translationsRevision($manifest),
'config' => (object) $this->frontendConfig($manifest->id, ! $authenticated),
'screens' => $manifest->screens,
'components' => $manifest->components,
@@ -224,6 +227,27 @@ class ExtensionRepository
return $this->settings[$identifier] ??= new ExtensionSettings($identifier);
}
/**
* Changes whenever the extension's translation files do. The frontend puts it in the
* URL it loads those translations from, which lets the browser cache them for as long
* as core translations and still pick up an installed or upgraded extension at once.
*/
private function translationsRevision(ExtensionManifest $manifest): ?string
{
$directory = $manifest->path('resources', 'lang');
if (! is_dir($directory)) {
return null;
}
$files = array_map(
fn (SplFileInfo $file): string => implode("\0", [$file->getRelativePathname(), $file->getSize(), $file->getMTime()]),
File::allFiles($directory),
);
sort($files);
return hash('xxh128', $manifest->version."\0".implode("\0", $files));
}
/**
* @param array<string, Extension> $records
* @return Collection<string, Extension>
+2
View File
@@ -168,6 +168,8 @@ export interface SiteExtensionEntry {
entry: string;
/** The Tailwind prefix declared as `ui.prefix`: the extension writes `<prefix>:flex`. */
prefix?: string | null;
/** Changes with the extension's translation files, and is sent when loading them. */
translations?: string | null;
config?: ExtensionConfig;
screens?: ExtensionScreenDefinition[];
components?: ComponentName[];
+2
View File
@@ -371,6 +371,8 @@ export interface SiteExtensionEntry {
entry: string;
/** The Tailwind prefix declared as `ui.prefix`: the extension writes `<prefix>:flex`. */
prefix?: string | null;
/** Changes with the extension's translation files, and is sent when loading them. */
translations?: string | null;
config?: ExtensionConfig;
screens?: ExtensionScreenDefinition[];
components?: ComponentName[];
+18
View File
@@ -65,3 +65,21 @@ it('follows language changes of the cached current user', async () => {
expect(instance.language).toBe('nl');
client.clear();
});
it('adds the revision of an extension to the URL of its translations only', async () => {
(window as BootstrapWindow).SiteConfiguration = {
extensions: [
{ id: 'notes', entry: '/notes.js', translations: 'a1b2' },
{ id: 'plain', entry: '/plain.js', translations: null },
],
};
const { localeLoadPath } = await import('@/i18n');
const core = '/locales/locale.json?locale={{lng}}&namespace={{ns}}';
expect(localeLoadPath(['ext-notes::messages'])).toBe(`${core}&revision=a1b2`);
expect(localeLoadPath(['strings'])).toBe(core);
expect(localeLoadPath(['ext-plain::messages'])).toBe(core);
expect(localeLoadPath(['ext-missing::messages'])).toBe(core);
// One request for several namespaces has no single revision to carry.
expect(localeLoadPath(['ext-notes::messages', 'strings'])).toBe(core);
});
+17 -2
View File
@@ -6,7 +6,7 @@ import I18NextHttpBackend from 'i18next-http-backend';
import I18NextMultiloadBackendAdapter from 'i18next-multiload-backend-adapter';
import { currentUserQueryKey } from '@/api/account/queries';
import type { UserData } from '@/api/account/types';
import { getBootstrapSiteSettings, getBootstrapUser } from '@/bootstrap';
import { getBootstrapExtensions, getBootstrapSiteSettings, getBootstrapUser } from '@/bootstrap';
interface MultiloadHttpBackendOptions extends HttpBackendOptions {
allowMultiLoading: boolean;
@@ -15,6 +15,21 @@ interface MultiloadHttpBackendOptions extends HttpBackendOptions {
// Busts the locale cache on every reload under HMR, otherwise once per build.
const hash = import.meta.hot ? Date.now().toString(16) : import.meta.env.WEBPACK_BUILD_HASH;
const localePath = '/locales/locale.json?locale={{lng}}&namespace={{ns}}';
/**
* Extension translations change when the extension is upgraded, not with the panel build,
* so their URL also carries the revision the panel reported for that extension.
*/
export function localeLoadPath(namespaces: string[]): string {
const extensionId = namespaces.length === 1 ? /^ext-(.+)::/.exec(namespaces[0]!)?.[1] : undefined;
const revision = extensionId
? getBootstrapExtensions().find((extension) => extension.id === extensionId)?.translations
: undefined;
return revision ? `${localePath}&revision=${revision}` : localePath;
}
export const initialLanguage = (): string => getBootstrapUser()?.language || getBootstrapSiteSettings()?.locale || 'en';
export function followCurrentUserLanguage(queryClient: QueryClient, instance: I18n = i18n): () => void {
@@ -41,7 +56,7 @@ i18n.use(I18NextMultiloadBackendAdapter)
backend: {
backend: I18NextHttpBackend,
backendOption: {
loadPath: '/locales/locale.json?locale={{lng}}&namespace={{ns}}',
loadPath: (_languages, namespaces) => localeLoadPath(namespaces),
queryStringParams: { hash },
allowMultiLoading: true,
} satisfies MultiloadHttpBackendOptions,
@@ -24,3 +24,57 @@ test('serves namespaced extension translations and rejects path traversal', func
\Illuminate\Support\Facades\File::deleteDirectory($directory);
}
});
test('caches translations whose URL changes with them and makes the browser revalidate the rest', function (): void {
$directory = sys_get_temp_dir().'/ptero-locale-'.uniqid();
\Illuminate\Support\Facades\File::ensureDirectoryExists($directory.'/en');
\Illuminate\Support\Facades\File::put($directory.'/en/messages.php', '<?php return ["welcome" => "Welcome"];');
$this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory);
try {
$core = $this->getJson('/locales/locale.json?locale=en&namespace=auth')->assertOk();
expect($core->headers->get('Cache-Control'))->toContain('max-age=3600')->toContain('public');
// The frontend sends the revision of the extension's translations, so upgrading
// the extension changes the URL.
$revision = str_repeat('a1', 16);
$extension = $this->getJson("/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages&revision={$revision}")->assertOk();
expect($extension->headers->get('Cache-Control'))->toContain('max-age=3600')->toContain('public');
// Without it an upgrade leaves the URL as it was, so a cached copy must never be
// used without asking the server first.
$bare = $this->getJson('/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages')->assertOk();
expect($bare->headers->get('Cache-Control'))->toContain('no-cache')->not->toContain('max-age');
$this->getJson('/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages&revision=..%2F')->assertUnprocessable();
} finally {
\Illuminate\Support\Facades\File::deleteDirectory($directory);
}
});
test('answers an unchanged translation set with 304 and a changed one with the new strings', function (): void {
$directory = sys_get_temp_dir().'/ptero-locale-'.uniqid();
$url = '/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages';
\Illuminate\Support\Facades\File::ensureDirectoryExists($directory.'/en');
\Illuminate\Support\Facades\File::put($directory.'/en/messages.php', '<?php return ["welcome" => "Welcome"];');
$this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory);
try {
$etag = $this->getJson($url)->assertOk()->headers->get('ETag');
expect($etag)->toBeString()->toStartWith('"');
$this->getJson($url, ['If-None-Match' => $etag])->assertStatus(304);
// What an extension upgrade does: the same URL now holds different strings.
\Illuminate\Support\Facades\File::put($directory.'/en/messages.php', '<?php return ["welcome" => "Welcome", "summary" => "Summary"];');
if (function_exists('opcache_invalidate')) {
opcache_invalidate($directory.'/en/messages.php', true);
}
$this->refreshApplication();
$this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory);
$this->getJson($url, ['If-None-Match' => $etag])
->assertOk()
->assertJsonPath('en.ext-probe::messages.summary', 'Summary');
} finally {
\Illuminate\Support\Facades\File::deleteDirectory($directory);
}
});
@@ -185,8 +185,32 @@ test('leaves settings out of the bootstrap payload when config is not included',
$payload = $repository->frontendPayload(authenticated: false);
expect($payload[0]['id'])->toBe('example');
expect($payload[0]['prefix'])->toBeNull();
expect($payload[0]['translations'])->toBeNull();
expect((array) $payload[0]['config'])->toBe([]);
});
test('reports a translations revision that changes with the translation files', function (): void {
writeManifest(['id' => 'example', 'name' => 'Example', 'version' => '1.0.0', 'ui' => ['entry' => 'dist/client.js']]);
$manifest = (new ExtensionManifestValidator)->fromDirectory($this->directory);
$repository = Mockery::mock(ExtensionRepository::class, [
new ExtensionManifestValidator,
resolve(ExtensionAssetPublisher::class),
resolve(Dispatcher::class),
resolve(ExtensionSettingsRegistry::class),
resolve(\Pterodactyl\Services\Extensions\ExtensionCompatibility::class),
])->makePartial();
$repository->shouldReceive('enabled')->andReturn(collect(['example' => $manifest]));
$revision = fn (): ?string => $repository->frontendPayload(authenticated: false)[0]['translations'];
File::ensureDirectoryExists($this->directory.'/resources/lang/en');
File::put($this->directory.'/resources/lang/en/messages.php', '<?php return ["welcome" => "Welcome"];');
$installed = $revision();
expect($installed)->toMatch('/^[a-f0-9]{32}$/')->toBe($revision());
// What an upgrade does: the same file, with different contents.
File::put($this->directory.'/resources/lang/en/messages.php', '<?php return ["welcome" => "Welcome", "summary" => "Summary"];');
clearstatcache();
expect($revision())->toMatch('/^[a-f0-9]{32}$/')->not->toBe($installed);
});
test('preserves resource tab parents in validated screen metadata', function (): void {
$screens = [