fix(i18n): give render_exists a message and check every server error code

The render upload refusal render_exists had no Server.Error.RenderExists
resource, so clients showed the raw code. ApiErrors builds that key at run
time, which the scan of used keys cannot see: i18n check now maps every
snake_case code literal the server passes to ApiErrors, Outcome.Fail and its
Fail and TooMany helpers to its Server.Error.* key and fails when one is
missing (SRV-6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 09:39:44 +00:00
1 parent c11c996bc6
commit eeee99694b
4 files changed
+95 -4

No files matched your search

+1
View File
@@ -69,6 +69,7 @@
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>This upload would exceed your quota.</value><comment>long</comment></data>
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Too many attempts; wait a minute and try again.</value><comment>long</comment></data>
<data name="Server.Error.RenderExists" xml:space="preserve"><value>This render is already filed under another sequence.</value><comment>long</comment></data>
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Choose a password different from the current one.</value><comment>long</comment></data>
<data name="Server.Error.Self" xml:space="preserve"><value>You cannot do this to your own account.</value><comment>long</comment></data>
<data name="Server.Error.SequenceBusy" xml:space="preserve"><value>A job is working on this sequence or its archive; try again when it is free.</value><comment>long</comment></data>
+1
View File
@@ -67,6 +67,7 @@
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>Questo caricamento supererebbe la tua quota.</value></data>
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Troppi tentativi; attendi un minuto e riprova.</value></data>
<data name="Server.Error.RenderExists" xml:space="preserve"><value>Questo render è già archiviato in un'altra sequenza.</value></data>
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Scegli una password diversa da quella attuale.</value></data>
<data name="Server.Error.Self" xml:space="preserve"><value>Non puoi farlo sul tuo account.</value></data>
<data name="Server.Error.SequenceBusy" xml:space="preserve"><value>Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera.</value></data>
+40 -4
View File
@@ -7,8 +7,8 @@ using Titano.Core.Localization;
namespace Titano.Tools.Commands;
/// <summary>
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets and that
/// every key used in code/XAML/admin JS exists (BRIEF §16).
/// <c>i18n check</c>: completeness of <c>en</c> and <c>it</c>, placeholder parity, length budgets, that every key
/// used in code/XAML/admin JS exists and that every error code the server answers with has its message (BRIEF §16).
/// <c>i18n export --out dir</c>: one JSON per culture for the web admin.
/// <c>i18n missing --culture xx [--all]</c>: untranslated (or all) keys as TSV for a translator or reviewer.
/// <c>i18n import --culture xx file.tsv</c>: merges translated <c>key&lt;TAB&gt;text</c> rows into the culture's resx files.
@@ -91,6 +91,8 @@ internal sealed partial class I18nCommand : ICommand
if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue;
errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}");
}
foreach (var (file, code, key) in MissingErrorMessages(root, en.Keys.ToHashSet(StringComparer.Ordinal)))
errors.Add($"{Path.GetRelativePath(root, file)}: error code {code} has no message {key}");
foreach (var w in warnings.Take(50)) Console.WriteLine("warning: " + w);
if (warnings.Count > 50) Console.WriteLine($"warning: … {warnings.Count - 50} more");
@@ -253,8 +255,7 @@ internal sealed partial class I18nCommand : ICommand
var src = Path.Combine(root, "src");
foreach (var file in Directory.EnumerateFiles(src, "*.*", SearchOption.AllDirectories))
{
if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
|| file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue;
if (IsBuildOutput(file)) continue;
var ext = Path.GetExtension(file);
Regex? regex = ext switch
{
@@ -274,9 +275,44 @@ internal sealed partial class I18nCommand : ICommand
}
}
/// <summary>
/// Error codes of the server (literals passed to <c>ApiErrors</c>, <c>Outcome.Fail</c> and the local <c>Fail</c> and
/// <c>TooMany</c> helpers) whose message <c>Server.Error.&lt;Code&gt;</c> is not in <paramref name="keys"/>, each once.
/// <c>ApiErrors.Message</c> builds that key at run time, so the scan of used keys cannot see it.
/// </summary>
internal static IEnumerable<(string File, string Code, string Key)> MissingErrorMessages(string root, IReadOnlySet<string> keys)
{
var reported = new HashSet<string>(StringComparer.Ordinal);
var server = Path.Combine(root, "src", "Titano.Server");
foreach (var file in Directory.EnumerateFiles(server, "*.cs", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
{
if (IsBuildOutput(file)) continue;
foreach (var code in ErrorCodes(File.ReadAllText(file)))
{
var key = ErrorKey(code);
if (!keys.Contains(key) && reported.Add(code)) yield return (file, code, key);
}
}
}
/// <summary>The literal error codes (snake_case) a C# source passes to the server's error helpers.</summary>
internal static IEnumerable<string> ErrorCodes(string source) => ErrorCodeRegex().Matches(source).Select(m => m.Groups[1].Value);
/// <summary>The message key of an error code, built like <c>ApiErrors.Message</c>: <c>render_exists</c> → <c>Server.Error.RenderExists</c>.</summary>
internal static string ErrorKey(string code) =>
"Server.Error." + string.Concat(code.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(part => char.ToUpperInvariant(part[0]) + part[1..]));
private static bool IsBuildOutput(string file) =>
file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
|| file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal);
[GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")]
private static partial Regex PlaceholderRegex();
/// <summary>A call of an error helper up to its first string argument (no statement end in between) when that is a snake_case code.</summary>
[GeneratedRegex(@"(?:\bApiErrors\.(?:Result|WriteAsync|BadRequest|Conflict|Message)|\bFail(?:<[^;()]*?>)?|\bTooMany)\([^;""]*?""([a-z][a-z0-9_]*)""")]
private static partial Regex ErrorCodeRegex();
[GeneratedRegex(@"\b(?:L|Plural|Loc\.Get|LocKey)\(\s*""([A-Z][A-Za-z0-9]*\.[A-Za-z0-9_.]+)""")]
private static partial Regex CsKeyRegex();
@@ -0,0 +1,53 @@
using System.Xml.Linq;
using Titano.Testing;
using Titano.Tools.Commands;
namespace Titano.Tools.Tests;
/// <summary><c>i18n check</c> also covers the messages of the server's error codes, whose keys are built at run time.</summary>
public sealed class I18nCommandTests
{
[Test]
public void ErrorCodesAreTheLiteralsPassedToTheServerErrorHelpers()
{
const string source = """
if (bad) return ApiErrors.BadRequest(context, "invalid_filter", "status");
return known.SequenceId == sequenceId
? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null)
: Outcome<StartUploadResponse>.Fail(409, "render_exists");
return Fail<ChunkReceived>(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable,
"archive_offline"),
return TooMany(context, "rate_limited", wait);
return ApiErrors.NotFound(context, "sequence");
return ApiErrors.BadRequest(context, code, setting, setting);
await FailAsync(upload, "not_a_code");
""";
Assert.SequenceEqual(["invalid_filter", "render_exists", "chunk_size", "archive_offline", "rate_limited"], I18nCommand.ErrorCodes(source).ToList());
}
[Test]
public void AnErrorCodeNamesItsMessageKeyLikeTheServer()
{
Assert.Equal("Server.Error.RenderExists", I18nCommand.ErrorKey("render_exists"));
Assert.Equal("Server.Error.Forbidden", I18nCommand.ErrorKey("forbidden"));
Assert.Equal("Server.Error.Http413", I18nCommand.ErrorKey("http_413"));
}
[Test]
public void EveryErrorCodeOfTheServerHasAnEnglishMessage()
{
var root = Args.RepoRoot();
var keys = XDocument.Load(Path.Combine(root, "i18n", "en", "Server.resx")).Root!.Elements("data")
.Select(d => (string)d.Attribute("name")!).ToHashSet(StringComparer.Ordinal);
var missing = I18nCommand.MissingErrorMessages(root, keys).ToList();
Assert.Empty(missing.Select(m => $"{m.Code} ({Path.GetFileName(m.File)})"));
var withoutOne = keys.Where(k => k != "Server.Error.RenderExists").ToHashSet(StringComparer.Ordinal);
var reported = I18nCommand.MissingErrorMessages(root, withoutOne).ToList();
Assert.Count(1, reported);
Assert.Equal(("render_exists", "Server.Error.RenderExists", "RenderUploads.cs"), (reported[0].Code, reported[0].Key, Path.GetFileName(reported[0].File)));
}
}