From 7269cf615a360582ba411f06ef442a416e0728b0 Mon Sep 17 00:00:00 2001 From: JounQin Date: Sat, 10 Oct 2026 23:17:47 +0800 Subject: [PATCH 1/4] fix(translate): answer blank texts with themselves instead of failing the request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request fails as a whole when any one of its texts is empty, so a document split into lines cannot be translated at all if it has a blank line in it: ["", "Hello"] answers 404 "No text to translate" and nothing is translated. A blank text — empty, or nothing but whitespace — carries nothing to translate, so it is no longer sent, and its own text is the answer. That keeps the response position-aligned, and it is the only thing that can work: oneshot echoes an empty input, and the positional check would read that echo as a failed translation and answer 503 instead. A whitespace-only text survives today only because oneshot happens to echo it as well. The 404 is now only for a request with no text at all — no texts, or every text empty. A request that has text but nothing to translate, like [" "], is answered with its own texts, so no blank input errors any more and no input that used to succeed fails now. This matches the JavaScript client (@deeplx/core batchPayload and restoreBlankSegments), which already drops text.trim() === '' segments and puts them back, so the two sides agree on what a blank segment means. Refs #240, #241, #244. --- README.md | 2 +- translate/textlength_test.go | 6 +-- translate/translate.go | 78 ++++++++++++++++++++++------- translate/translate_test.go | 95 ++++++++++++++++++++++++++++-------- 4 files changed, 139 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 5b5712a..e31b47b 100644 --- a/README.md +++ b/README.md @@ -90,8 +90,8 @@ curl -X POST http://localhost:1188/translate \ Batch limits and failure modes: - The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts. +- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. A request with no text at all — no texts, or every text empty — is still rejected with `404 {"code":404,"message":"No text to translate"}`. - A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array. -- `"text": []`, and any array containing an empty string, are rejected with the same `404 {"code":404,"message":"No text to translate"}` as `"text": ""`. ## Discussion Group [Telegram Group](https://t.me/+8KDGHKJCxEVkNzll) diff --git a/translate/textlength_test.go b/translate/textlength_test.go index 0ee65e4..e35e9ea 100644 --- a/translate/textlength_test.go +++ b/translate/textlength_test.go @@ -104,12 +104,12 @@ func TestTranslateByDLXRejectsOversizedTextsBeforeUpstream(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - length, ok := totalTextLength(tt.texts) + _, length, ok := textsToTranslate(tt.texts) if !ok { - t.Fatalf("totalTextLength(%q) reported no text", tt.texts) + t.Fatalf("textsToTranslate(%q) reported no text", tt.texts) } if length <= maxFreeTextLength { - t.Fatalf("totalTextLength(%q) = %d, which is not over the limit", tt.texts, length) + t.Fatalf("textsToTranslate(%q) = %d, which is not over the limit", tt.texts, length) } result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "") if err != nil { diff --git a/translate/translate.go b/translate/translate.go index c3b9304..e991da7 100644 --- a/translate/translate.go +++ b/translate/translate.go @@ -439,21 +439,39 @@ func textLength(text string) int { return n } -// totalTextLength returns the total length of texts in UTF-16 code units. ok is -// false when no text was requested or any of them is empty, which callers -// report as "No text to translate" — an empty element fails the batch as a -// whole rather than being skipped or translated as an empty segment. -func totalTextLength(texts []string) (total int, ok bool) { - if len(texts) == 0 { - return 0, false - } - for _, text := range texts { - if text == "" { - return 0, false +// textsToTranslate returns the positions of the texts that carry something to +// translate and their total length in UTF-16 code units, and whether the request +// holds any text at all. +// +// A blank text — empty, or nothing but whitespace — carries nothing to +// translate, so it is not sent: its own text is the answer, which keeps a +// segmented document position-aligned instead of failing the whole request. +// Whitespace is still text, so only a request whose texts are all empty is a +// request with nothing to translate. +func textsToTranslate(texts []string) (positions []int, total int, hasText bool) { + for i, text := range texts { + if text != "" { + hasText = true } + if strings.TrimSpace(text) == "" { + continue + } + positions = append(positions, i) total += textLength(text) } - return total, true + return positions, total, hasText +} + +// mergeTranslations puts the translations back at the positions they were asked +// for, leaving every text that was not sent — a blank one — exactly as it +// arrived. +func mergeTranslations(texts []string, positions []int, translations []string) []string { + merged := make([]string, len(texts)) + copy(merged, texts) + for i, position := range positions { + merged[position] = translations[i] + } + return merged } // translationsFromResult extracts exactly count non-empty translations from @@ -486,9 +504,9 @@ func translationsFromResult(result gjson.Result, count int) ([]string, error) { func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) { // oneshot charges its anonymous cap against the total length of the // `text` array, and a batch is one upstream request, so the cap applies - // to the sum of the requested texts rather than to each text. - totalLength, ok := totalTextLength(texts) - if !ok { + // to the sum of the texts that are actually sent. + positions, totalLength, hasText := textsToTranslate(texts) + if !hasText { return DLXTranslationResult{ Code: http.StatusNotFound, Message: "No text to translate", @@ -517,6 +535,22 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s }, nil } + // Nothing to translate, but text was requested: every text is blank, so + // none of them travels and the request is answered with its own texts, + // exactly as a blank element is inside a request that does have something + // to translate. + if len(positions) == 0 { + return DLXTranslationResult{ + Code: http.StatusOK, + ID: time.Now().UnixMilli(), + Data: append([]string(nil), texts...), + Alternatives: nil, // oneshot does not return alternatives + SourceLang: sourceLang, + TargetLang: targetLang, + Method: map[bool]string{true: "Pro", false: "Free"}[dlSession != ""], + }, nil + } + // tagHandling is accepted by the public DLX API for compatibility // but oneshot does not expose html/xml tag handling the way the // official v2 API does — ignored upstream. @@ -526,8 +560,16 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s // app_information always agree; the lookup itself is cached (appversion.go). appVersion := currentIOSAppVersion() + // Blank texts stay here: oneshot echoes an empty input, and the positional + // check on the answer would read that echo as a failed translation and fail + // the batch, so there is nothing to gain by sending them. + requested := make([]string, 0, len(positions)) + for _, position := range positions { + requested = append(requested, texts[position]) + } + reqStruct := oneshotRequest{ - Text: texts, + Text: requested, TargetLang: resolvedTarget, SourceLang: resolvedSource, // empty = autodetect; omitempty drops the field // ItaClient.OneShotUsageType.translate (also: ocr, voiceforconversations) @@ -599,7 +641,7 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s }, nil } - data, err := translationsFromResult(result, len(texts)) + translations, err := translationsFromResult(result, len(requested)) if err != nil { return DLXTranslationResult{ ID: id, @@ -615,7 +657,7 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s return DLXTranslationResult{ Code: http.StatusOK, ID: id, - Data: data, + Data: mergeTranslations(texts, positions, translations), Alternatives: nil, // oneshot does not return alternatives SourceLang: sourceLang, TargetLang: targetLang, diff --git a/translate/translate_test.go b/translate/translate_test.go index 88b1c2e..b2a7497 100644 --- a/translate/translate_test.go +++ b/translate/translate_test.go @@ -9,33 +9,62 @@ import ( "github.com/tidwall/gjson" ) -func TestTotalTextLength(t *testing.T) { +func TestTextsToTranslate(t *testing.T) { tests := []struct { name string texts []string + wantAt []int wantTotal int - wantOK bool + wantText bool }{ - {"no texts", nil, 0, false}, - {"empty array", []string{}, 0, false}, - {"empty string", []string{""}, 0, false}, - {"empty element in batch", []string{"Hello", ""}, 0, false}, - {"single text", []string{"Hello"}, 5, true}, - {"batch total", []string{"Hello", "Good morning"}, 17, true}, - {"counts UTF-16 units, not bytes", []string{"你好"}, 2, true}, - {"astral character costs two units", []string{"😀"}, 2, true}, - {"combining mark is two units, not one grapheme", []string{"e\u0301"}, 2, true}, - {"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, 3, true}, - {"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, maxFreeTextLength, true}, - {"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, maxFreeTextLength, true}, - {"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, maxFreeTextLength + 2, true}, - {"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, 1600, true}, + {"no texts", nil, nil, 0, false}, + {"empty array", []string{}, nil, 0, false}, + {"empty string", []string{""}, nil, 0, false}, + {"every text empty", []string{"", ""}, nil, 0, false}, + {"whitespace only", []string{" \t "}, nil, 0, true}, + {"empty and blank", []string{"", " "}, nil, 0, true}, + {"single text", []string{"Hello"}, []int{0}, 5, true}, + {"empty element in batch", []string{"Hello", ""}, []int{0}, 5, true}, + {"leading empty element in batch", []string{"", "Hello"}, []int{1}, 5, true}, + {"blank elements around a batch", []string{"", "Hello", " ", "Good morning", "\n"}, []int{1, 3}, 17, true}, + {"batch total", []string{"Hello", "Good morning"}, []int{0, 1}, 17, true}, + {"counts UTF-16 units, not bytes", []string{"你好"}, []int{0}, 2, true}, + {"astral character costs two units", []string{"😀"}, []int{0}, 2, true}, + {"combining mark is two units, not one grapheme", []string{"e\u0301"}, []int{0}, 2, true}, + {"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, []int{0}, 3, true}, + {"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, []int{0}, maxFreeTextLength, true}, + {"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, []int{0}, maxFreeTextLength, true}, + {"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, []int{0, 1}, maxFreeTextLength + 2, true}, + {"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, []int{0, 1}, 1600, true}, + {"blank texts are not charged", []string{" ", "Hello"}, []int{1}, 5, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - total, ok := totalTextLength(tt.texts) - if ok != tt.wantOK || total != tt.wantTotal { - t.Fatalf("totalTextLength(%q) = (%d, %v), want (%d, %v)", tt.texts, total, ok, tt.wantTotal, tt.wantOK) + at, total, hasText := textsToTranslate(tt.texts) + if hasText != tt.wantText || total != tt.wantTotal || !reflect.DeepEqual(at, tt.wantAt) { + t.Fatalf("textsToTranslate(%q) = (%v, %d, %v), want (%v, %d, %v)", tt.texts, at, total, hasText, tt.wantAt, tt.wantTotal, tt.wantText) + } + }) + } +} + +func TestMergeTranslations(t *testing.T) { + tests := []struct { + name string + texts []string + positions []int + translations []string + want []string + }{ + {"no blanks", []string{"Hello"}, []int{0}, []string{"你好"}, []string{"你好"}}, + {"leading blank", []string{"", "Hello"}, []int{1}, []string{"你好"}, []string{"", "你好"}}, + {"blank keeps its exact text", []string{"", "Hello", " "}, []int{1}, []string{"你好"}, []string{"", "你好", " "}}, + {"batch keeps order", []string{"Hello", " ", "Good morning"}, []int{0, 2}, []string{"你好", "早上好"}, []string{"你好", " ", "早上好"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := mergeTranslations(tt.texts, tt.positions, tt.translations); !reflect.DeepEqual(got, tt.want) { + t.Fatalf("mergeTranslations(%q, %v, %q) = %q, want %q", tt.texts, tt.positions, tt.translations, got, tt.want) } }) } @@ -92,7 +121,8 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { }{ {"no texts", nil, http.StatusNotFound}, {"empty array", []string{}, http.StatusNotFound}, - {"empty element in batch", []string{"Hello", ""}, http.StatusNotFound}, + {"empty string", []string{""}, http.StatusNotFound}, + {"every text empty", []string{"", ""}, http.StatusNotFound}, {"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge}, {"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, http.StatusRequestEntityTooLarge}, // 751 runes in the batch, but 1502 UTF-16 units: the case a rune count @@ -112,3 +142,28 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { }) } } + +// A request that has text but nothing to translate is answered with its own +// texts rather than rejected, and — like the validation cases above — it never +// reaches DeepL. +func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) { + tests := [][]string{ + {" \t "}, + {"", " "}, + {"\n", "\t\n", " "}, + } + for _, texts := range tests { + t.Run(strings.Join(texts, "|"), func(t *testing.T) { + result, err := TranslateByDLX("", "ZH", texts, "", "", "") + if err != nil { + t.Fatalf("TranslateByDLX() error = %v", err) + } + if result.Code != http.StatusOK { + t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK) + } + if !reflect.DeepEqual(result.Data, texts) { + t.Fatalf("TranslateByDLX() data = %q, want %q", result.Data, texts) + } + }) + } +} From 4fb2759d48ac205dd67a1470aabb712971cc00ad Mon Sep 17 00:00:00 2001 From: JounQin Date: Sat, 10 Oct 2026 23:39:45 +0800 Subject: [PATCH 2/4] fix(translate): answer a request whose texts are all empty with 200 as well Every text is answered now, blank or not, so the all-empty case needs no rule of its own: "" and [""] are texts with nothing to translate in them, and they are answered with themselves like any other blank text. A missing or null `text` decodes to the one empty string and is answered the same way. The 404 is left for a request that names no text at all: `"text": []`, the one shape there is nothing to answer with. Nothing else errors on emptiness. Refs #244. --- README.md | 2 +- translate/textlength_test.go | 5 +-- translate/translate.go | 40 +++++++++--------- translate/translate_test.go | 78 ++++++++++++++++++------------------ 4 files changed, 60 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index e31b47b..ccebd1b 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ curl -X POST http://localhost:1188/translate \ Batch limits and failure modes: - The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts. -- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. A request with no text at all — no texts, or every text empty — is still rejected with `404 {"code":404,"message":"No text to translate"}`. +- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. Only a request that names no text at all, `"text": []`, is rejected with `404 {"code":404,"message":"No text to translate"}`. - A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array. ## Discussion Group diff --git a/translate/textlength_test.go b/translate/textlength_test.go index e35e9ea..f22b7ba 100644 --- a/translate/textlength_test.go +++ b/translate/textlength_test.go @@ -104,10 +104,7 @@ func TestTranslateByDLXRejectsOversizedTextsBeforeUpstream(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, length, ok := textsToTranslate(tt.texts) - if !ok { - t.Fatalf("textsToTranslate(%q) reported no text", tt.texts) - } + _, length := textsToTranslate(tt.texts) if length <= maxFreeTextLength { t.Fatalf("textsToTranslate(%q) = %d, which is not over the limit", tt.texts, length) } diff --git a/translate/translate.go b/translate/translate.go index e991da7..6fb12bf 100644 --- a/translate/translate.go +++ b/translate/translate.go @@ -440,26 +440,19 @@ func textLength(text string) int { } // textsToTranslate returns the positions of the texts that carry something to -// translate and their total length in UTF-16 code units, and whether the request -// holds any text at all. -// -// A blank text — empty, or nothing but whitespace — carries nothing to -// translate, so it is not sent: its own text is the answer, which keeps a -// segmented document position-aligned instead of failing the whole request. -// Whitespace is still text, so only a request whose texts are all empty is a -// request with nothing to translate. -func textsToTranslate(texts []string) (positions []int, total int, hasText bool) { +// translate and their total length in UTF-16 code units. A blank text — empty, +// or nothing but whitespace — carries nothing to translate, so it is not sent: +// its own text is the answer, which keeps a segmented document position-aligned +// and lets an empty line pass through instead of failing the request. +func textsToTranslate(texts []string) (positions []int, total int) { for i, text := range texts { - if text != "" { - hasText = true - } if strings.TrimSpace(text) == "" { continue } positions = append(positions, i) total += textLength(text) } - return positions, total, hasText + return positions, total } // mergeTranslations puts the translations back at the positions they were asked @@ -502,17 +495,21 @@ func translationsFromResult(result gjson.Result, count int) ([]string, error) { // to the Pro endpoint; the value is sent verbatim as the Bearer token (i.e. // it must be an OAuth access token, not the legacy dl_session cookie). func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) { - // oneshot charges its anonymous cap against the total length of the - // `text` array, and a batch is one upstream request, so the cap applies - // to the sum of the texts that are actually sent. - positions, totalLength, hasText := textsToTranslate(texts) - if !hasText { + // A request that names no text at all is not a translation request; any + // text, blank or not, is answered. A missing or null `text` decodes to the + // one empty string, so this is the empty array. + if len(texts) == 0 { return DLXTranslationResult{ Code: http.StatusNotFound, Message: "No text to translate", }, nil } + // oneshot charges its anonymous cap against the total length of the + // `text` array, and a batch is one upstream request, so the cap applies + // to the sum of the texts that are actually sent. + positions, totalLength := textsToTranslate(texts) + resolvedTarget, err := resolveTargetLang(targetLang) if err != nil { return DLXTranslationResult{ @@ -535,10 +532,9 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s }, nil } - // Nothing to translate, but text was requested: every text is blank, so - // none of them travels and the request is answered with its own texts, - // exactly as a blank element is inside a request that does have something - // to translate. + // Nothing to translate: every text is blank, so none of them travels and + // the request is answered with its own texts, exactly as a blank element + // is inside a request that does have something to translate. if len(positions) == 0 { return DLXTranslationResult{ Code: http.StatusOK, diff --git a/translate/translate_test.go b/translate/translate_test.go index b2a7497..ba347be 100644 --- a/translate/translate_test.go +++ b/translate/translate_test.go @@ -15,34 +15,33 @@ func TestTextsToTranslate(t *testing.T) { texts []string wantAt []int wantTotal int - wantText bool }{ - {"no texts", nil, nil, 0, false}, - {"empty array", []string{}, nil, 0, false}, - {"empty string", []string{""}, nil, 0, false}, - {"every text empty", []string{"", ""}, nil, 0, false}, - {"whitespace only", []string{" \t "}, nil, 0, true}, - {"empty and blank", []string{"", " "}, nil, 0, true}, - {"single text", []string{"Hello"}, []int{0}, 5, true}, - {"empty element in batch", []string{"Hello", ""}, []int{0}, 5, true}, - {"leading empty element in batch", []string{"", "Hello"}, []int{1}, 5, true}, - {"blank elements around a batch", []string{"", "Hello", " ", "Good morning", "\n"}, []int{1, 3}, 17, true}, - {"batch total", []string{"Hello", "Good morning"}, []int{0, 1}, 17, true}, - {"counts UTF-16 units, not bytes", []string{"你好"}, []int{0}, 2, true}, - {"astral character costs two units", []string{"😀"}, []int{0}, 2, true}, - {"combining mark is two units, not one grapheme", []string{"e\u0301"}, []int{0}, 2, true}, - {"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, []int{0}, 3, true}, - {"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, []int{0}, maxFreeTextLength, true}, - {"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, []int{0}, maxFreeTextLength, true}, - {"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, []int{0, 1}, maxFreeTextLength + 2, true}, - {"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, []int{0, 1}, 1600, true}, - {"blank texts are not charged", []string{" ", "Hello"}, []int{1}, 5, true}, + {"no texts", nil, nil, 0}, + {"empty array", []string{}, nil, 0}, + {"empty string", []string{""}, nil, 0}, + {"every text empty", []string{"", ""}, nil, 0}, + {"whitespace only", []string{" \t "}, nil, 0}, + {"empty and blank", []string{"", " "}, nil, 0}, + {"single text", []string{"Hello"}, []int{0}, 5}, + {"empty element in batch", []string{"Hello", ""}, []int{0}, 5}, + {"leading empty element in batch", []string{"", "Hello"}, []int{1}, 5}, + {"blank elements around a batch", []string{"", "Hello", " ", "Good morning", "\n"}, []int{1, 3}, 17}, + {"batch total", []string{"Hello", "Good morning"}, []int{0, 1}, 17}, + {"counts UTF-16 units, not bytes", []string{"你好"}, []int{0}, 2}, + {"astral character costs two units", []string{"😀"}, []int{0}, 2}, + {"combining mark is two units, not one grapheme", []string{"e\u0301"}, []int{0}, 2}, + {"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, []int{0}, 3}, + {"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, []int{0}, maxFreeTextLength}, + {"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, []int{0}, maxFreeTextLength}, + {"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, []int{0, 1}, maxFreeTextLength + 2}, + {"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, []int{0, 1}, 1600}, + {"blank texts are not charged", []string{" ", "Hello"}, []int{1}, 5}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - at, total, hasText := textsToTranslate(tt.texts) - if hasText != tt.wantText || total != tt.wantTotal || !reflect.DeepEqual(at, tt.wantAt) { - t.Fatalf("textsToTranslate(%q) = (%v, %d, %v), want (%v, %d, %v)", tt.texts, at, total, hasText, tt.wantAt, tt.wantTotal, tt.wantText) + at, total := textsToTranslate(tt.texts) + if total != tt.wantTotal || !reflect.DeepEqual(at, tt.wantAt) { + t.Fatalf("textsToTranslate(%q) = (%v, %d), want (%v, %d)", tt.texts, at, total, tt.wantAt, tt.wantTotal) } }) } @@ -121,8 +120,6 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { }{ {"no texts", nil, http.StatusNotFound}, {"empty array", []string{}, http.StatusNotFound}, - {"empty string", []string{""}, http.StatusNotFound}, - {"every text empty", []string{"", ""}, http.StatusNotFound}, {"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge}, {"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, http.StatusRequestEntityTooLarge}, // 751 runes in the batch, but 1502 UTF-16 units: the case a rune count @@ -143,26 +140,31 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { } } -// A request that has text but nothing to translate is answered with its own -// texts rather than rejected, and — like the validation cases above — it never -// reaches DeepL. +// Every text is answered — translated when it carries something, returned as it +// is when it is blank — so only a request that names no text at all is an +// error, and none of the cases below reaches DeepL. func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) { - tests := [][]string{ - {" \t "}, - {"", " "}, - {"\n", "\t\n", " "}, + tests := []struct { + name string + texts []string + }{ + {"single empty", []string{""}}, + {"two empty", []string{"", ""}}, + {"whitespace only", []string{" \t "}}, + {"empty and whitespace", []string{"", " "}}, + {"newlines and spaces", []string{"\n", "\t\n", " "}}, } - for _, texts := range tests { - t.Run(strings.Join(texts, "|"), func(t *testing.T) { - result, err := TranslateByDLX("", "ZH", texts, "", "", "") + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "") if err != nil { t.Fatalf("TranslateByDLX() error = %v", err) } if result.Code != http.StatusOK { t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK) } - if !reflect.DeepEqual(result.Data, texts) { - t.Fatalf("TranslateByDLX() data = %q, want %q", result.Data, texts) + if !reflect.DeepEqual(result.Data, tt.texts) { + t.Fatalf("TranslateByDLX() data = %q, want %q", result.Data, tt.texts) } }) } From b28dcd4958a4aa850421c2b34ef5dc5a5e920f6c Mon Sep 17 00:00:00 2001 From: JounQin Date: Sat, 10 Oct 2026 23:44:37 +0800 Subject: [PATCH 3/4] fix(translate): answer an empty text list with an empty list, not 404 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `"text": []` names a list that happens to be empty, and the response can render that perfectly well, so rejecting it bought nothing: it was the original "No text to translate" condition surviving for the one shape the code had no answer to. It is answered with `{"data": []}` now — the same rule as every other text, applied to none of them. A body that never named `text` is a different thing, a payload without its parameter: it answers 400 Invalid request payload instead of the 404 that stood in for it, which is also what the endpoint answers for a body it cannot bind. That is the only refusal left. Refs #244. --- README.md | 2 +- service/service.go | 11 ++++++++++ service/service_test.go | 42 +++++++++++++++++++++++++++++++++++++ translate/translate.go | 17 ++++----------- translate/translate_test.go | 21 +++++++++++++------ 5 files changed, 73 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index ccebd1b..f6b362f 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ curl -X POST http://localhost:1188/translate \ Batch limits and failure modes: - The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts. -- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. Only a request that names no text at all, `"text": []`, is rejected with `404 {"code":404,"message":"No text to translate"}`. +- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. `"text": []` is answered with `{"data": []}`; a body with no `text` field at all is rejected with `400 {"code":400,"message":"Invalid request payload"}`. - A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array. ## Discussion Group diff --git a/service/service.go b/service/service.go index de0773a..842309c 100644 --- a/service/service.go +++ b/service/service.go @@ -159,6 +159,17 @@ func Router(cfg *Config) *gin.Engine { return } + // A body without `text` never named a text to translate, which is a + // payload error. `"text": []` names a list that happens to be empty, + // and is answered with an empty list, so it is not caught here. + if !req.Text.Batch && len(req.Text.Texts) == 0 { + c.JSON(http.StatusBadRequest, gin.H{ + "code": http.StatusBadRequest, + "message": "Invalid request payload", + }) + return + } + sourceLang := req.SourceLang targetLang := req.TargetLang texts := req.Text.Texts diff --git a/service/service_test.go b/service/service_test.go index ae108eb..c3f0b38 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -2,9 +2,13 @@ package service import ( "encoding/json" + "net/http" + "net/http/httptest" "reflect" "strings" "testing" + + "github.com/gin-gonic/gin" ) // The `text` field of POST /translate accepts either shape; decoding uses the @@ -23,6 +27,7 @@ func TestPayloadTextUnmarshalJSON(t *testing.T) { {name: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true}, {name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true}, {name: "null", payload: `{"text":null}`, wantTexts: []string{""}}, + {name: "no text field", payload: `{}`, wantTexts: nil}, {name: "number", payload: `{"text":1}`, wantErr: true}, {name: "object", payload: `{"text":{}}`, wantErr: true}, {name: "mixed array", payload: `{"text":["Hello",1]}`, wantErr: true}, @@ -46,3 +51,40 @@ func TestPayloadTextUnmarshalJSON(t *testing.T) { }) } } + +// POST /translate mirrors the shape it was given, and no shape that carries +// text is an error any more — an empty text is answered with itself and an +// empty array with an empty array. Every case here is answered (or refused) +// before a translation is attempted, so the test never reaches DeepL. +func TestTranslateHandlerAnswersEmptyText(t *testing.T) { + gin.SetMode(gin.TestMode) + router := Router(&Config{}) + + tests := []struct { + name string + payload string + wantCode int + wantInBody string + }{ + {"empty array", `{"text":[],"target_lang":"EN"}`, http.StatusOK, `"data":[]`}, + {"empty string", `{"text":"","target_lang":"EN"}`, http.StatusOK, `"data":""`}, + {"null", `{"text":null,"target_lang":"EN"}`, http.StatusOK, `"data":""`}, + {"array of empty", `{"text":[""],"target_lang":"EN"}`, http.StatusOK, `"data":[""]`}, + {"no text field", `{"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/translate", strings.NewReader(tt.payload)) + request.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, request) + + if recorder.Code != tt.wantCode { + t.Fatalf("POST /translate %s = %d %s, want %d", tt.payload, recorder.Code, recorder.Body.String(), tt.wantCode) + } + if !strings.Contains(recorder.Body.String(), tt.wantInBody) { + t.Fatalf("POST /translate %s body = %s, want it to contain %s", tt.payload, recorder.Body.String(), tt.wantInBody) + } + }) + } +} diff --git a/translate/translate.go b/translate/translate.go index 6fb12bf..421cae0 100644 --- a/translate/translate.go +++ b/translate/translate.go @@ -495,16 +495,6 @@ func translationsFromResult(result gjson.Result, count int) ([]string, error) { // to the Pro endpoint; the value is sent verbatim as the Bearer token (i.e. // it must be an OAuth access token, not the legacy dl_session cookie). func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) { - // A request that names no text at all is not a translation request; any - // text, blank or not, is answered. A missing or null `text` decodes to the - // one empty string, so this is the empty array. - if len(texts) == 0 { - return DLXTranslationResult{ - Code: http.StatusNotFound, - Message: "No text to translate", - }, nil - } - // oneshot charges its anonymous cap against the total length of the // `text` array, and a batch is one upstream request, so the cap applies // to the sum of the texts that are actually sent. @@ -533,13 +523,14 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s } // Nothing to translate: every text is blank, so none of them travels and - // the request is answered with its own texts, exactly as a blank element - // is inside a request that does have something to translate. + // the request is answered with its own texts — an empty list in, an empty + // list out — exactly as a blank element is inside a request that does have + // something to translate. if len(positions) == 0 { return DLXTranslationResult{ Code: http.StatusOK, ID: time.Now().UnixMilli(), - Data: append([]string(nil), texts...), + Data: mergeTranslations(texts, positions, nil), Alternatives: nil, // oneshot does not return alternatives SourceLang: sourceLang, TargetLang: targetLang, diff --git a/translate/translate_test.go b/translate/translate_test.go index ba347be..1af79cf 100644 --- a/translate/translate_test.go +++ b/translate/translate_test.go @@ -118,8 +118,6 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { texts []string code int }{ - {"no texts", nil, http.StatusNotFound}, - {"empty array", []string{}, http.StatusNotFound}, {"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge}, {"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, http.StatusRequestEntityTooLarge}, // 751 runes in the batch, but 1502 UTF-16 units: the case a rune count @@ -141,13 +139,16 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) { } // Every text is answered — translated when it carries something, returned as it -// is when it is blank — so only a request that names no text at all is an -// error, and none of the cases below reaches DeepL. +// is when it is blank — so nothing about emptiness is an error, and none of the +// cases below reaches DeepL. Data is always allocated, so an empty request +// marshals as `[]` rather than `null`. func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) { tests := []struct { name string texts []string }{ + {"no texts", nil}, + {"empty array", []string{}}, {"single empty", []string{""}}, {"two empty", []string{"", ""}}, {"whitespace only", []string{" \t "}}, @@ -163,8 +164,16 @@ func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) { if result.Code != http.StatusOK { t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK) } - if !reflect.DeepEqual(result.Data, tt.texts) { - t.Fatalf("TranslateByDLX() data = %q, want %q", result.Data, tt.texts) + if result.Data == nil { + t.Fatal("TranslateByDLX() data = nil, want an allocated slice so it marshals as []") + } + if len(result.Data) != len(tt.texts) { + t.Fatalf("TranslateByDLX() data = %q, want %d element(s)", result.Data, len(tt.texts)) + } + for i, text := range tt.texts { + if result.Data[i] != text { + t.Fatalf("TranslateByDLX() data[%d] = %q, want %q", i, result.Data[i], text) + } } }) } From ee1114252e82702358f096c4f8303bf76c646dcd Mon Sep 17 00:00:00 2001 From: JounQin Date: Sun, 11 Oct 2026 00:40:57 +0800 Subject: [PATCH 4/4] fix(service): treat a null text as no text, and read that from the field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UnmarshalJSON sent `null` down the string branch, where json.Unmarshal into a string is a documented no-op, so `{"text":null}` decoded to `[""]` and was indistinguishable from `{"text":""}` for the rest of the request. On main both were an error, but this branch answers an empty text with itself, so null quietly became a 200 instead. A JSON null is a present key with no value, so it leaves the zero value now — the same Texts == nil a body with no `text` key has — and the handler refuses both with 400 Invalid request payload, testing the field directly instead of re-deriving the decoder with `!Batch && len(Texts) == 0`. Every shape that names text, including `"text": []`, still decodes to a non-nil Texts and is answered rather than refused. Refs #244. --- README.md | 2 +- service/service.go | 13 +++++++++---- service/service_test.go | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f6b362f..335ec2d 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ curl -X POST http://localhost:1188/translate \ Batch limits and failure modes: - The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts. -- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. `"text": []` is answered with `{"data": []}`; a body with no `text` field at all is rejected with `400 {"code":400,"message":"Invalid request payload"}`. +- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. `"text": []` is answered with `{"data": []}`; a body with no `text` field at all, or `"text": null`, is rejected with `400 {"code":400,"message":"Invalid request payload"}`. - A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array. ## Discussion Group diff --git a/service/service.go b/service/service.go index 842309c..c7eb78a 100644 --- a/service/service.go +++ b/service/service.go @@ -91,8 +91,7 @@ type PayloadTranslate struct { // Texts, and Batch records which shape the caller used so the response can // mirror it. Any other shape (a number, an object, an array holding // non-strings) fails the payload decode, which the handler reports as -// 400 Invalid request payload; null decodes to the empty string exactly as it -// did when text was a plain string. +// 400 Invalid request payload; null names no text, like a body without the key. type PayloadText struct { Texts []string Batch bool @@ -100,7 +99,8 @@ type PayloadText struct { // UnmarshalJSON implements json.Unmarshaler. func (p *PayloadText) UnmarshalJSON(data []byte) error { - if trimmed := bytes.TrimSpace(data); len(trimmed) > 0 && trimmed[0] == '[' { + trimmed := bytes.TrimSpace(data) + if len(trimmed) > 0 && trimmed[0] == '[' { var texts []string if err := json.Unmarshal(trimmed, &texts); err != nil { return err @@ -109,6 +109,11 @@ func (p *PayloadText) UnmarshalJSON(data []byte) error { return nil } + // A JSON null names no text: leave the zero value, so Texts stays nil. + if string(trimmed) == "null" { + return nil + } + var text string if err := json.Unmarshal(data, &text); err != nil { return err @@ -162,7 +167,7 @@ func Router(cfg *Config) *gin.Engine { // A body without `text` never named a text to translate, which is a // payload error. `"text": []` names a list that happens to be empty, // and is answered with an empty list, so it is not caught here. - if !req.Text.Batch && len(req.Text.Texts) == 0 { + if req.Text.Texts == nil { c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, "message": "Invalid request payload", diff --git a/service/service_test.go b/service/service_test.go index c3f0b38..a8aa210 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -26,7 +26,7 @@ func TestPayloadTextUnmarshalJSON(t *testing.T) { {name: "array", payload: `{"text":["Hello","Good morning"]}`, wantTexts: []string{"Hello", "Good morning"}, wantBatch: true}, {name: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true}, {name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true}, - {name: "null", payload: `{"text":null}`, wantTexts: []string{""}}, + {name: "null", payload: `{"text":null}`, wantTexts: nil}, {name: "no text field", payload: `{}`, wantTexts: nil}, {name: "number", payload: `{"text":1}`, wantErr: true}, {name: "object", payload: `{"text":{}}`, wantErr: true}, @@ -68,7 +68,7 @@ func TestTranslateHandlerAnswersEmptyText(t *testing.T) { }{ {"empty array", `{"text":[],"target_lang":"EN"}`, http.StatusOK, `"data":[]`}, {"empty string", `{"text":"","target_lang":"EN"}`, http.StatusOK, `"data":""`}, - {"null", `{"text":null,"target_lang":"EN"}`, http.StatusOK, `"data":""`}, + {"null", `{"text":null,"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`}, {"array of empty", `{"text":[""],"target_lang":"EN"}`, http.StatusOK, `"data":[""]`}, {"no text field", `{"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`}, }