fix(translate): answer an empty text list with an empty list, not 404

`"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.
This commit is contained in:
JounQin
2026-10-10 23:44:37 +08:00
parent 4fb2759d48
commit b28dcd4958
5 changed files with 73 additions and 20 deletions
+1 -1
View File
@@ -90,7 +90,7 @@ curl -X POST http://localhost:1188/translate \
Batch limits and failure modes: 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. - 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. - 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 ## Discussion Group
+11
View File
@@ -159,6 +159,17 @@ func Router(cfg *Config) *gin.Engine {
return 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 sourceLang := req.SourceLang
targetLang := req.TargetLang targetLang := req.TargetLang
texts := req.Text.Texts texts := req.Text.Texts
+42
View File
@@ -2,9 +2,13 @@ package service
import ( import (
"encoding/json" "encoding/json"
"net/http"
"net/http/httptest"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"github.com/gin-gonic/gin"
) )
// The `text` field of POST /translate accepts either shape; decoding uses the // 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: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true},
{name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true}, {name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true},
{name: "null", payload: `{"text":null}`, wantTexts: []string{""}}, {name: "null", payload: `{"text":null}`, wantTexts: []string{""}},
{name: "no text field", payload: `{}`, wantTexts: nil},
{name: "number", payload: `{"text":1}`, wantErr: true}, {name: "number", payload: `{"text":1}`, wantErr: true},
{name: "object", payload: `{"text":{}}`, wantErr: true}, {name: "object", payload: `{"text":{}}`, wantErr: true},
{name: "mixed array", payload: `{"text":["Hello",1]}`, 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)
}
})
}
}
+4 -13
View File
@@ -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. // 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). // 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) { 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 // oneshot charges its anonymous cap against the total length of the
// `text` array, and a batch is one upstream request, so the cap applies // `text` array, and a batch is one upstream request, so the cap applies
// to the sum of the texts that are actually sent. // 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 // 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 // the request is answered with its own texts — an empty list in, an empty
// is inside a request that does have something to translate. // list out — exactly as a blank element is inside a request that does have
// something to translate.
if len(positions) == 0 { if len(positions) == 0 {
return DLXTranslationResult{ return DLXTranslationResult{
Code: http.StatusOK, Code: http.StatusOK,
ID: time.Now().UnixMilli(), ID: time.Now().UnixMilli(),
Data: append([]string(nil), texts...), Data: mergeTranslations(texts, positions, nil),
Alternatives: nil, // oneshot does not return alternatives Alternatives: nil, // oneshot does not return alternatives
SourceLang: sourceLang, SourceLang: sourceLang,
TargetLang: targetLang, TargetLang: targetLang,
+15 -6
View File
@@ -118,8 +118,6 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) {
texts []string texts []string
code int code int
}{ }{
{"no texts", nil, http.StatusNotFound},
{"empty array", []string{}, http.StatusNotFound},
{"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge}, {"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge},
{"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, 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 // 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 // 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 // is when it is blank — so nothing about emptiness is an error, and none of the
// error, and none of the cases below reaches DeepL. // cases below reaches DeepL. Data is always allocated, so an empty request
// marshals as `[]` rather than `null`.
func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) { func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
texts []string texts []string
}{ }{
{"no texts", nil},
{"empty array", []string{}},
{"single empty", []string{""}}, {"single empty", []string{""}},
{"two empty", []string{"", ""}}, {"two empty", []string{"", ""}},
{"whitespace only", []string{" \t "}}, {"whitespace only", []string{" \t "}},
@@ -163,8 +164,16 @@ func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) {
if result.Code != http.StatusOK { if result.Code != http.StatusOK {
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK) t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK)
} }
if !reflect.DeepEqual(result.Data, tt.texts) { if result.Data == nil {
t.Fatalf("TranslateByDLX() data = %q, want %q", result.Data, tt.texts) 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)
}
} }
}) })
} }