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) + } } }) }