Skip to content

Commit b474e87

Browse files
phasenullclaude
andauthored
Analytics: honour Retry-After on 429/503, optional backend.ingest URL (plans/35, 0.7.2) (#23)
- queue.ts: retryAfterSeconds (429/503, whole seconds 1-300, else ignored) and retryWaitSeconds (at least Retry-After, jittered up to half again; without it exactly the old backoff). flushOnce uses it; a busy 503 logs 'the server is busy'. - settings.ts sinkSettings: backend.ingest (same URL check) takes the events at <ingest>/v1/ingest with the same key; a bad value falls back to <url>/v1/ingest with an error the server warns about once. A Basin analytics sink still wins. - kernel.ts backend.ingest type, version 0.7.2, README, Lune tests. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ba18a9f commit b474e87

9 files changed

Lines changed: 159 additions & 21 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -653,7 +653,9 @@ const variant = analytics.experiment("onboarding", ["short", "long"]); // same a
653653
- **When uploads fail** (a stale quick-tunnel URL, the dev PC's server or tunnel down, a wrong token, HttpService off;
654654
Roblox reports most network problems as `HttpError: NetFail`, `DnsResolve` or `ConnectFail`): the server backs off
655655
with jitter (5, 10, 20 ... 300 s, spread +-25% so a fleet of servers doesn't retry in step; a wrong token or URL waits
656-
about 5 minutes, and a settings change retries at once), keeps the rows, and logs at most ONE line a minute: the
656+
about 5 minutes, and a settings change retries at once). A `429` or `503` with a `Retry-After` of 1-300 seconds (the
657+
backend's "busy" answer) waits at least that long, plus up to half again of jitter (framework 0.7.2; without the
658+
header, or with a date or an out-of-range value, the plain backoff). It keeps the rows, and logs at most ONE line a minute: the
657659
reason and the fix (`analytics upload failed 5 times in a row: NetFail: the connection broke mid-request. ... Retrying
658660
in 80 s.`, with "(+N more in the last minute)" for the lines it held back) and one line when uploads work again.
659661
`stats()` also has `failures` (in a row), `failed` (since the server started), `lastError`, `lastStatus`
@@ -672,9 +674,12 @@ const variant = analytics.experiment("onboarding", ["short", "long"]); // same a
672674
- **Friends in the server** (the join's `friends`): one `Players:GetFriendsAsync` per join (at most 10 pages, none
673675
when the player is alone) intersected with the players there, not a web call per player.
674676

675-
**Settings, framework 0.4.0 / kernel 0.4.0 (plans/21):** the record's `backend` = `{ url, key, analytics?: { flushSeconds,
677+
**Settings, framework 0.4.0 / kernel 0.4.0 (plans/21):** the record's `backend` = `{ url, key, ingest?, analytics?: { flushSeconds,
676678
recordShare, recordSeconds, positions, techEvery, experiments, joinLaunchPrefix, joinData } }` is the whole sink: DuckDB
677-
at `<url>/v1/ingest` with the one key (Basin identities to `<url>/v1/identity`). `typetorch backend setup` writes it
679+
at `<url>/v1/ingest` with the one key (Basin identities to `<url>/v1/identity`). Framework 0.7.2 (plans/35): an
680+
optional `backend.ingest` URL (separate ingest servers, `typetorch backend setup --ingest <url>`, CLI 0.19.0) sends the
681+
events to `<ingest>/v1/ingest` with the same key; the kernel and everything else keep `url`. A bad `ingest` value
682+
falls back to `<url>/v1/ingest` and the server warns once. `typetorch backend setup` writes it
678683
(`--flush-seconds`, `--record-share`; `writeBackendSettings()` in `@typetorch/backend` runs it, and `bun run local`
679684
too), and `typetorch experiment` writes `experiments`. The other dials (`recordSeconds`, `positions`, `techEvery`,
680685
`joinLaunchPrefix`, `joinData`) have no CLI writer yet: `backend setup` keeps them when the record has them, and

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@typetorch/framework",
3-
"version": "0.7.1",
3+
"version": "0.7.2",
44
"description": "TypeTorch framework for roblox-ts: hot-swappable modules (dependency injection, lifecycle, troves), guarded networking, hot assets and the in-game dev menu. Ships inside every TypeTorch artifact.",
55
"license": "MIT",
66
"author": "TypeTorch",

‎scripts/test-analytics-server.luau‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,29 @@ local recovered = core1:stats()
890890
check("recovered: the streak is over, the history stays", recovered.failures == 0 and recovered.failed >= 2 and recovered.lastError ~= nil and recovered.lastOkAt >= recovered.lastErrorAt)
891891
check("recovered: nothing left to fix", recovered.retryIn == nil and recovered.reason == nil and recovered.fix == nil)
892892

893+
-- Framework 0.7.2 (plans/35 D): the backend's "busy" 503 with Retry-After: the rows stay, the wait is at least that long.
894+
core1:track(newbie, "custom", "busy_probe", nil)
895+
core1.lastWarnAt = -math.huge
896+
local requestsBeforeBusy = #requests
897+
respond = function()
898+
return { Success = false, StatusCode = 503, StatusMessage = "Service Unavailable", Headers = { ["retry-after"] = "20", ["content-type"] = "application/json" }, Body = '{"error":"busy: try later","busy":true}' }
899+
end
900+
core1:flushSoon()
901+
task.wait(1.5)
902+
local busy = core1:stats()
903+
check("busy 503: one request, rows kept", #requests == requestsBeforeBusy + 1 and #rowsNamed(store().events.rows, "custom", "busy_probe") == 1, #requests)
904+
check("busy 503: waits at least Retry-After (20-30 s)", busy.retryIn ~= nil and busy.retryIn >= 18 and busy.retryIn <= 31, busy.retryIn)
905+
check("busy 503: the log line says busy and the wait", said("the server is busy") and said("asked to wait 20 s"), warnings[#warnings])
906+
respond = function()
907+
return { Success = true, StatusCode = 200, StatusMessage = "OK", Body = "" }
908+
end
909+
task.wait(7.5)
910+
check("busy 503: no retry before Retry-After", #requests == requestsBeforeBusy + 1, #requests)
911+
core1.backoffUntil = 0 -- (skip the rest of the wait)
912+
core1:flushSoon()
913+
task.wait(1.5)
914+
check("busy 503: sent after the wait", #requests == requestsBeforeBusy + 2 and #rowsNamed(store().events.rows, "custom", "busy_probe") == 0 and store().failures == 0, #requests)
915+
893916
-- A refused batch is dropped.
894917
core1:track(newbie, "custom", "refused_one", nil)
895918
respond = function()

‎scripts/test-analytics.luau‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,26 @@ check("backoff 3", Q.backoffSeconds(3, 0.5) == 20)
260260
check("backoff capped", Q.backoffSeconds(20, 0.5) == 300)
261261
check("backoff jitter low", Q.backoffSeconds(2, 0) == 7.5)
262262
check("config wait: 300 s spread by jitter (0.75-1.25)", Q.configWaitSeconds(0.5) == 300 and Q.configWaitSeconds(0) == 225 and Q.configWaitSeconds(1) == 375 and Q.configWaitSeconds(7) == 375)
263+
-- Framework 0.7.2 (plans/35 D): Retry-After on 429 / 503 (the backend's "busy" answer) is a floor for the wait.
264+
check("Retry-After: 503 seconds", Q.retryAfterSeconds(503, { ["Retry-After"] = "20" }) == 20)
265+
check("Retry-After: 429, any header case, spaces", Q.retryAfterSeconds(429, { ["retry-after"] = " 45 " }) == 45 and Q.retryAfterSeconds(429, { ["RETRY-AFTER"] = "1" }) == 1)
266+
check("Retry-After: 300 is the top", Q.retryAfterSeconds(503, { ["Retry-After"] = "300" }) == 300)
267+
check("Retry-After: absent", Q.retryAfterSeconds(503, {}) == nil and Q.retryAfterSeconds(503, nil) == nil and Q.retryAfterSeconds(503, { ["Content-Type"] = "application/json" }) == nil)
268+
check("Retry-After: out of range", Q.retryAfterSeconds(503, { ["Retry-After"] = "0" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "301" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "99999999999999999999" }) == nil)
269+
check("Retry-After: not whole seconds", Q.retryAfterSeconds(503, { ["Retry-After"] = "Wed, 21 Oct 2015 07:28:00 GMT" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "abc" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "-5" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "2.5" }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = 20 }) == nil and Q.retryAfterSeconds(503, { ["Retry-After"] = "" }) == nil)
270+
check("Retry-After: only on 429 / 503", Q.retryAfterSeconds(500, { ["Retry-After"] = "20" }) == nil and Q.retryAfterSeconds(502, { ["Retry-After"] = "20" }) == nil and Q.retryAfterSeconds(200, { ["Retry-After"] = "20" }) == nil and Q.retryAfterSeconds(0, { ["Retry-After"] = "20" }) == nil)
271+
check("retry wait: without Retry-After exactly the backoff", Q.retryWaitSeconds(1, 0.5) == Q.backoffSeconds(1, 0.5) and Q.retryWaitSeconds(3, 0.2, nil) == Q.backoffSeconds(3, 0.2) and Q.retryWaitSeconds(20, 1) == Q.backoffSeconds(20, 1))
272+
check("retry wait: at least Retry-After (jitter 0)", Q.retryWaitSeconds(1, 0, 20) == 20, Q.retryWaitSeconds(1, 0, 20))
273+
check("retry wait: jitter on top (up to half again)", Q.retryWaitSeconds(1, 1, 20) == 30 and Q.retryWaitSeconds(1, 0.5, 20) == 25 and Q.retryWaitSeconds(1, 7, 20) == 30, Q.retryWaitSeconds(1, 0.5, 20))
274+
local spread, low, high = {}, math.huge, 0
275+
for index = 0, 10 do
276+
local wait = Q.retryWaitSeconds(1, index / 10, 10)
277+
spread[wait] = true
278+
low, high = math.min(low, wait), math.max(high, wait)
279+
end
280+
check("retry wait: a fleet told 10 s spreads over 10-15 s", low == 10 and high == 15 and spread[12.5] == true, `{low}-{high}`)
281+
check("retry wait: a longer backoff still wins", Q.retryWaitSeconds(6, 0.5, 10) == Q.backoffSeconds(6, 0.5) and Q.backoffSeconds(6, 0.5) == 160)
282+
check("retry wait: a 300 s Retry-After at most 450 s", Q.retryWaitSeconds(1, 1, 300) == 450)
263283
check("status 200", Q.classifyStatus(200) == "sent")
264284
check("status 204", Q.classifyStatus(204) == "sent")
265285
check("status 0", Q.classifyStatus(0) == "retry")
@@ -558,6 +578,26 @@ local both = S.sinkSettings({ url = "https://b.example.com", key = "k-0123456789
558578
check("backend wins over the old duckdb analytics value", both.events == "https://b.example.com/v1/ingest")
559579
local basin = S.sinkSettings({ url = "https://b.example.com", key = "k-0123456789" }, '{"backend":"basin","events":"https://s.ingest.cloudflare.com"}', decode)
560580
check("a Basin sink stays on analytics (backend can't describe streams)", basin == '{"backend":"basin","events":"https://s.ingest.cloudflare.com"}')
581+
-- Framework 0.7.2 (plans/35 C): an optional backend.ingest URL takes the events (same key); the kernel keeps url.
582+
local function sinkFor(record, analytics)
583+
return S.parseSettings(S.sinkSettings(record, analytics, decode), decode)
584+
end
585+
local noIngest = sinkFor({ url = "https://b.example.com", key = "k-0123456789" })
586+
check("ingest: unset, events at <url>/v1/ingest, no error", noIngest.settings.events == "https://b.example.com/v1/ingest" and #noIngest.errors == 0)
587+
local withIngest = sinkFor({ url = "https://b.example.com", key = "k-0123456789", ingest = "https://ingest.example.com//", analytics = { flushSeconds = 30 } })
588+
check("ingest: events at <ingest>/v1/ingest, same key, analytics dials kept", withIngest.settings.events == "https://ingest.example.com/v1/ingest" and withIngest.settings.token == "k-0123456789" and withIngest.settings.flushSeconds == 30 and #withIngest.errors == 0, withIngest.settings.events)
589+
check("ingest: still a duckdb sink (identities ride the batch)", withIngest.settings.backend == "duckdb" and S.identityTarget(withIngest.settings, { url = "https://b.example.com", key = "k" }, decode) == nil)
590+
for _, bad in { "ftp://ingest.example.com", "ingest.example.com", "https://in gest.example.com", "https://", "https:///", 42, true, { url = "https://x.example.com" }, "" } do
591+
local parsed = sinkFor({ url = "https://b.example.com", key = "k-0123456789", ingest = bad })
592+
check(`ingest: bad value {tostring(bad)} falls back to <url>/v1/ingest with one error`, parsed.settings ~= nil and parsed.settings.events == "https://b.example.com/v1/ingest" and #parsed.errors == 1 and string.find(parsed.errors[1], "backend.ingest", 1, true) ~= nil, parsed.errors[1])
593+
end
594+
local longIngest = sinkFor({ url = "https://b.example.com", key = "k-0123456789", ingest = "https://" .. string.rep("a", 2100) .. ".example.com" })
595+
check("ingest: over 2048 characters is bad too", longIngest.settings.events == "https://b.example.com/v1/ingest" and #longIngest.errors == 1)
596+
local badIngest = sinkFor({ url = "https://b.example.com", key = "k-0123456789", ingest = "not a url" })
597+
check("ingest: the error never echoes the value", not string.find(badIngest.errors[1], "not a url", 1, true))
598+
local basinIngest = S.sinkSettings({ url = "https://b.example.com", key = "k-0123456789", ingest = "https://ingest.example.com" }, { backend = "basin", events = "https://s.ingest.cloudflare.com" }, decode)
599+
check("ingest: a Basin analytics sink still wins", basinIngest.backend == "basin" and basinIngest.events == "https://s.ingest.cloudflare.com")
600+
check("ingest: sinkErrors only from strings, capped", #S.parseSettings({ backend = "duckdb", events = "https://a.example.com/ingest", sinkErrors = { "one", 2, "three" } }, decode).errors == 2)
561601
local target = S.identityTarget({ backend = "basin", events = "https://s.ingest.cloudflare.com" }, { url = "https://b.example.com/", key = "k-0123456789" }, decode)
562602
check("Basin identities go to the backend with its key", target ~= nil and target.url == "https://b.example.com/v1/identity" and target.token == "k-0123456789")
563603

‎src/analytics/queue.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,39 @@ export function backoffSeconds(failures: number, jitter: number): number {
113113
return base * (0.75 + 0.5 * math.clamp(jitter, 0, 1));
114114
}
115115

116+
/** The longest `Retry-After` honoured (seconds); a longer or shorter one is ignored (plain backoff instead). */
117+
export const RETRY_AFTER_MAX = 300;
118+
119+
/**
120+
* Framework 0.7.2 (plans/35 D): the `Retry-After` seconds of a 429 / 503 answer (the backend's "busy" 503 sends one),
121+
* from the response headers (any case). Undefined for other statuses, without the header, or when it isn't whole
122+
* seconds in 1-300 (an HTTP date, "abc", 0, 3600...): then the plain backoff applies, as before.
123+
*/
124+
export function retryAfterSeconds(status: number, headers: unknown): number | undefined {
125+
if (status !== 429 && status !== 503) return undefined;
126+
if (!typeIs(headers, "table")) return undefined;
127+
for (const [key, value] of pairs(headers as object)) {
128+
if (!typeIs(key, "string") || key.lower() !== "retry-after") continue;
129+
if (!typeIs(value, "string") || value.size() > 16) return undefined;
130+
const [digits] = value.match("^%s*(%d+)%s*$");
131+
if (!typeIs(digits, "string")) return undefined;
132+
const seconds = tonumber(digits);
133+
if (seconds === undefined || seconds < 1 || seconds > RETRY_AFTER_MAX) return undefined;
134+
return seconds;
135+
}
136+
return undefined;
137+
}
138+
139+
/**
140+
* Seconds to wait after a failed try: the backoff (`backoffSeconds`), and with a `retryAfter` (see retryAfterSeconds)
141+
* at least that, spread up to half again by `jitter` (0..1) so a fleet told the same number doesn't retry in step.
142+
*/
143+
export function retryWaitSeconds(failures: number, jitter: number, retryAfter?: number): number {
144+
const backoff = backoffSeconds(failures, jitter);
145+
if (retryAfter === undefined) return backoff;
146+
return math.max(backoff, retryAfter * (1 + 0.5 * math.clamp(jitter, 0, 1)));
147+
}
148+
116149
/**
117150
* Seconds to wait after a settings problem (401/403/404: wrong token or URL): long, because retrying doesn't help until
118151
* the settings change (that retries at once), spread by `jitter` (0..1) so a whole fleet of servers doesn't retry in step.
@@ -126,7 +159,8 @@ export type Outcome = "sent" | "retry" | "split" | "drop" | "config";
126159

127160
/**
128161
* 2xx sent; 413 split the batch; 401/403/404 a settings problem (wrong token or URL: keep the rows, wait long, a
129-
* settings change retries at once); 408/429/5xx/no response retry with backoff; other 4xx drop the batch.
162+
* settings change retries at once); 408/429/5xx/no response retry with backoff (429/503: at least the answer's
163+
* Retry-After, see retryWaitSeconds); other 4xx drop the batch.
130164
*/
131165
export function classifyStatus(status: number): Outcome {
132166
if (status >= 200 && status < 300) return "sent";

‎src/analytics/server.ts‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { describeFailure } from "./hints";
4646
import { encodeJoinData, joinDataJson, joinProps, wantedUserIds, type JoinDataLike, type JoinDataMode, type JoinFacts, type LaunchVerdict } from "./join";
4747
import { registerBuiltinRows, registerBuiltinSessions } from "./rows";
4848
import { readKeys, verifyToken } from "../notifications/token";
49-
import { backoffSeconds, classifyStatus, configWaitSeconds, newQueueState, RowQueue, takeToken, type BucketState, type QueueState } from "./queue";
49+
import { classifyStatus, configWaitSeconds, retryAfterSeconds, retryWaitSeconds, newQueueState, RowQueue, takeToken, type BucketState, type QueueState } from "./queue";
5050
import {
5151
PROPS_MAX_BYTES,
5252
RECORDING_CODEC,
@@ -1615,8 +1615,11 @@ export class ServerAnalytics {
16151615
}
16161616
}
16171617

1618-
/** POST one request. Returns the HTTP status (0: no response). Never logs the token or the body. */
1619-
private post(request: SinkRequest): number {
1618+
/**
1619+
* POST one request. Returns the HTTP status (0: no response) and, on a 429 / 503, the answer's Retry-After seconds
1620+
* (1-300, else undefined). Never logs the token or the body.
1621+
*/
1622+
private post(request: SinkRequest): LuaTuple<[number, number | undefined]> {
16201623
this.countBudget("http", request.table === "identities" ? "identity" : "ingest");
16211624
const [ok, response] = pcall(() =>
16221625
HttpService.RequestAsync({
@@ -1629,10 +1632,10 @@ export class ServerAnalytics {
16291632
);
16301633
if (!ok) {
16311634
this.store.lastError = `${request.table}: ${tostring(response).sub(1, 120)}`;
1632-
return 0;
1635+
return $tuple(0, undefined);
16331636
}
16341637
if (!response.Success) this.store.lastError = `${request.table}: HTTP ${response.StatusCode} ${response.StatusMessage.sub(1, 60)}`;
1635-
return response.StatusCode;
1638+
return $tuple(response.StatusCode, retryAfterSeconds(response.StatusCode, response.Headers));
16361639
}
16371640

16381641
/** Sends one batch per table. `final`: shutdown, ignore the budget. */
@@ -1691,7 +1694,7 @@ export class ServerAnalytics {
16911694
settle(request, true);
16921695
continue;
16931696
}
1694-
const status = this.post(request);
1697+
const [status, retryAfter] = this.post(request);
16951698
const outcome = classifyStatus(status);
16961699
const rows = request.events + request.recordings + request.identities;
16971700
if (outcome === "sent") {
@@ -1715,12 +1718,17 @@ export class ServerAnalytics {
17151718
this.store.lastStatus = status;
17161719
this.store.lastErrorAt = os.time();
17171720
// Backs off with jitter (so a fleet of servers doesn't retry in step): 5, 10, 20 ... 300 s for a network or
1718-
// server problem, about 5 minutes for a settings problem (a settings change retries at once).
1719-
const wait = outcome === "config" ? configWaitSeconds(math.random()) : backoffSeconds(this.store.failures, math.random());
1721+
// server problem, about 5 minutes for a settings problem (a settings change retries at once). A 429 / 503 with
1722+
// Retry-After (the backend's "busy" answer) waits at least that long (framework 0.7.2, plans/35 D).
1723+
const wait = outcome === "config" ? configWaitSeconds(math.random()) : retryWaitSeconds(this.store.failures, math.random(), retryAfter);
17201724
this.backoffUntil = os.clock() + wait;
17211725
// "both" = one batch with events and recordings (the DuckDB sink); say "analytics upload" instead.
17221726
const what = request.table === "both" ? "analytics upload" : `analytics upload (${request.table})`;
1723-
const help = describeFailure(status, this.store.lastError);
1727+
// The backend's "busy" 503 isn't a failing server: say so instead of "check the log".
1728+
const help =
1729+
status === 503 && retryAfter !== undefined
1730+
? { reason: "HTTP 503: the server is busy", fix: `it asked to wait ${retryAfter} s; the rows are kept.` }
1731+
: describeFailure(status, this.store.lastError);
17241732
const streak = this.store.failures > 1 ? ` ${this.store.failures} times in a row` : "";
17251733
if (this.warn(`${what} failed${streak}: ${help.reason}. ${help.fix} Retrying in ${math.floor(wait)} s.`)) this.outageLogged = true;
17261734
}

0 commit comments

Comments
 (0)