Skip to content

Commit 432c0a2

Browse files
authored
fix(translate): enforce 1500-char text limit + add request timeout (#220)
* fix(translate): enforce 1500-char limit upfront and add request timeout Two related stability issues hit during real-world use: 1. **Hung requests** — without an explicit timeout the upstream HTTP call could dangle indefinitely on a stuck connection. Browser extensions calling /translate would sit on a spinner forever with no error to surface to the user (reported in the field). 2. **No-feedback on oversized input** — the oneshot endpoint caps the total text length at 1500 characters (matches the extension's own \`G.notLoggedIn = 1500\` constant). We were forwarding the request anyway and letting DeepL 400 it, which a) wasted an upstream round trip and b) the caller had no way to distinguish from other 400s. Changes: - Pre-validate \`text\` length in characters (utf8.RuneCountInString, not byte length — verified the cap is rune-based: 1500 Chinese characters / 4500 bytes is accepted, 1501 is rejected). Return HTTP 413 Payload Too Large with a clear message naming both the observed length and the limit. - Set a 20s timeout on the oneshot HTTP client (req.SetTimeout). On timeout return HTTP 504 Gateway Timeout — distinguishes a slow DeepL from other 503 failure modes (DNS, TLS, etc.). The check catches both context.DeadlineExceeded and url.Error{Timeout()=true}. - Set a separate 5s timeout on the cookie-jar warmup GET to www.deepl.com. Warmup is best-effort; we'd rather a slow warmup (cookies still seed eventually next time) than block the very first translation behind a hung GET. Behaviour verified against the live oneshot endpoint: - 1500 ASCII chars → 200 - 1501 ASCII chars → 413 (upstream not contacted) - 1500 Chinese chars (4500 bytes) → 200 - 1501 Chinese chars → 413 - Pathological "your"*1500 → 504 at 20s (was hanging without timeout) - Realistic 245-char Chinese → 200 in ~13s * perf(translate): share oneshot req.Client across requests + eager warmup Each TranslateByDeepLX call was building a brand-new req.Client via newOneshotClient(), which meant a fresh TLS handshake + HTTP/2 SETTINGS negotiation per request — ~200-400ms of pure overhead on top of DeepL's own ~1.5s processing latency. Share one client per proxy URL (sync.Map) so subsequent requests reuse the kept-alive HTTP/2 connection in the underlying http.Transport's pool. Also flip the cookie-jar warmup from synchronous-on-first-call to fire-and-forget at first client creation. Same sync.Once semantics (runs exactly once per process), but in a background goroutine so the first translate request runs in parallel with the TLS handshake to www.deepl.com rather than serially behind it. Measured against the live oneshot endpoint (Tokyo → Frankfurt): before, 5 sequential requests: 3.19s, 2.05s, 2.07s, 2.89s, 2.22s after, 5 sequential requests: 2.20s, 1.27s, 1.26s, 1.42s, 1.34s └─ first └────────── warm path ─────┘ The warm-path 1.3s is also faster than a bare \`curl\` to oneshot (~1.9s, every call doing its own TLS handshake) — proof the connection-pool reuse is now actually paying off.
1 parent 1a06bae commit 432c0a2

1 file changed

Lines changed: 82 additions & 5 deletions

File tree

translate/translate.go

Lines changed: 82 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ package translate
1515
import (
1616
"compress/flate"
1717
"compress/gzip"
18+
"context"
1819
"crypto/rand"
1920
"encoding/hex"
2021
"encoding/json"
22+
"errors"
2123
"fmt"
2224
"io"
2325
"net/http"
@@ -27,6 +29,7 @@ import (
2729
"strings"
2830
"sync"
2931
"time"
32+
"unicode/utf8"
3033

3134
"github.com/andybalholm/brotli"
3235
"github.com/imroc/req/v3"
@@ -57,6 +60,26 @@ const (
5760
impersonatedChromeMajor = "120"
5861
chromeExtensionVersion = "1.86.0"
5962
chromeExtensionID = "cofdbpoegempjloogbagkncekinflcnj"
63+
64+
// oneshot enforces a 1500-character hard cap on the total length of
65+
// the `text` array (sum across all items). Source: the extension's
66+
// own `G.notLoggedIn = 1500` constant in background.js. The server
67+
// returns 400 `{"errors":{"text":["text exceeds maximum length"]}}`
68+
// past this; bail early to spare the upstream and give the caller a
69+
// faster, less ambiguous error.
70+
maxFreeTextLength = 1500
71+
72+
// oneshotTimeout caps how long we wait on a single translate request.
73+
// Without an explicit timeout, a hung upstream connection would
74+
// dangle indefinitely and the caller (e.g. browser extension) would
75+
// sit on a spinner forever — observed in the field.
76+
oneshotTimeout = 20 * time.Second
77+
78+
// warmupTimeout caps the initial GET to www.deepl.com that seeds the
79+
// cookie jar. Shorter than oneshotTimeout because warmup typically
80+
// completes in well under a second; we'd rather skip a slow warmup
81+
// (cookies are best-effort anyway) than block the first translation.
82+
warmupTimeout = 5 * time.Second
6083
)
6184

6285
// instanceID mirrors the UUID the extension persists in chrome.storage on
@@ -76,6 +99,14 @@ var (
7699
cookieWarmer sync.Once
77100
)
78101

102+
// oneshotClients caches one req.Client per proxy URL so all translate
103+
// calls share the underlying TCP / TLS / HTTP/2 connection pool.
104+
// Creating a fresh req.Client per request meant a brand-new TLS
105+
// handshake every time (~200-400ms of overhead on top of DeepL's own
106+
// ~1.5s processing latency). Reusing the client lets keep-alive +
107+
// session tickets cut that to near zero on the warm path.
108+
var oneshotClients sync.Map // map[string]*req.Client
109+
79110
func sharedCookieJar() http.CookieJar {
80111
cookieJarOnce.Do(func() {
81112
j, _ := cookiejar.New(nil)
@@ -87,10 +118,15 @@ func sharedCookieJar() http.CookieJar {
87118
// warmCookies primes the shared jar by GETting www.deepl.com once.
88119
// The Set-Cookie response (userCountry / verifiedBot) lands on .deepl.com,
89120
// which is the eTLD+1 of oneshot-free.www.deepl.com, so subsequent POSTs
90-
// to the oneshot endpoint will carry those cookies automatically.
121+
// to the oneshot endpoint will carry those cookies automatically. The
122+
// same request doubles as a TLS-handshake warmup: it leaves a live
123+
// HTTP/2 connection to www.deepl.com in the client pool, which the
124+
// first oneshot POST then resumes via TLS session tickets.
91125
func warmCookies(client *req.Client) {
92126
cookieWarmer.Do(func() {
93-
_, _ = client.R().Get("https://www.deepl.com/translator")
127+
ctx, cancel := context.WithTimeout(context.Background(), warmupTimeout)
128+
defer cancel()
129+
_, _ = client.R().SetContext(ctx).Get("https://www.deepl.com/translator")
94130
})
95131
}
96132

@@ -239,8 +275,33 @@ type oneshotRequest struct {
239275
// headers (pragma, cache-control, upgrade-insecure-requests, sec-fetch-user)
240276
// that a fetch() never emits — wipe those so the WAF cannot tell us apart
241277
// on that axis.
278+
// getOneshotClient returns a process-wide cached client for the given
279+
// proxy URL, creating it on first use. Sharing the client across
280+
// requests is the single biggest latency win we have on the warm path:
281+
// it keeps the TLS / HTTP/2 connection in the pool so subsequent
282+
// requests skip the handshake entirely. Kicks off cookie-jar warmup
283+
// in the background on first creation so that the first real translate
284+
// call lands on an already-established connection.
285+
func getOneshotClient(proxyURL string) (*req.Client, error) {
286+
if c, ok := oneshotClients.Load(proxyURL); ok {
287+
return c.(*req.Client), nil
288+
}
289+
c, err := newOneshotClient(proxyURL)
290+
if err != nil {
291+
return nil, err
292+
}
293+
if actual, loaded := oneshotClients.LoadOrStore(proxyURL, c); loaded {
294+
return actual.(*req.Client), nil
295+
}
296+
// First time we've seen this proxy. Kick warmup off in the
297+
// background so the very first translate call can run in parallel
298+
// with the TLS handshake to www.deepl.com.
299+
go warmCookies(c)
300+
return c, nil
301+
}
302+
242303
func newOneshotClient(proxyURL string) (*req.Client, error) {
243-
client := req.C().ImpersonateChrome().SetCookieJar(sharedCookieJar())
304+
client := req.C().ImpersonateChrome().SetCookieJar(sharedCookieJar()).SetTimeout(oneshotTimeout)
244305
for _, h := range []string{
245306
"Pragma",
246307
"Cache-Control",
@@ -270,11 +331,10 @@ func newOneshotClient(proxyURL string) (*req.Client, error) {
270331
// exactly. Omitting that header instead would put the request on a
271332
// different server-side auth branch.
272333
func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gjson.Result, int, error) {
273-
client, err := newOneshotClient(proxyURL)
334+
client, err := getOneshotClient(proxyURL)
274335
if err != nil {
275336
return gjson.Result{}, 0, err
276337
}
277-
warmCookies(client) // no-op after the first translation in the process
278338

279339
authValue := "None"
280340
if bearerToken != "" {
@@ -349,6 +409,13 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
349409
}, nil
350410
}
351411

412+
if n := utf8.RuneCountInString(text); n > maxFreeTextLength {
413+
return DeepLXTranslationResult{
414+
Code: http.StatusRequestEntityTooLarge,
415+
Message: fmt.Sprintf("text exceeds maximum length: %d characters (anonymous oneshot limit is %d)", n, maxFreeTextLength),
416+
}, nil
417+
}
418+
352419
reqStruct := oneshotRequest{
353420
Text: []string{text},
354421
TargetLang: resolvedTarget,
@@ -372,6 +439,16 @@ func TranslateByDeepLX(sourceLang, targetLang, text string, tagHandling string,
372439
id := time.Now().UnixMilli()
373440
result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL)
374441
if err != nil {
442+
// Map upstream timeouts to 504 so callers can distinguish "DeepL
443+
// took too long" from other 503 failure modes (DNS, TLS, etc.).
444+
var ue *url.Error
445+
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &ue) && ue.Timeout()) {
446+
return DeepLXTranslationResult{
447+
ID: id,
448+
Code: http.StatusGatewayTimeout,
449+
Message: fmt.Sprintf("upstream DeepL request timed out after %s", oneshotTimeout),
450+
}, nil
451+
}
375452
return DeepLXTranslationResult{
376453
ID: id,
377454
Code: http.StatusServiceUnavailable,

0 commit comments

Comments
 (0)