santoku-http
View on LuaRockstransport-agnostic HTTP client front end: retry with jittered backoff, cancellation, query params, and request/response hooks over a pluggable socket backend
santoku-http is a transport-agnostic HTTP client front end. Calling the module with a backend table yields a client with fetch, get, post and on. The client adds query strings, retry with jittered backoff and hooks, and the backend does all the network I/O.
Details
- A backend supplies fetch(url, opts), which returns ok, resp, and sleep(ms).
- Since santoku-http 3.0.0, retry runs through santoku.async's retry over the backend's sleep: https://santoku.dev/santoku#santoku--santoku-async
- The same client code runs over santoku.socket in native scripts, santoku.web.socket in the browser, and santoku.resty.socket under OpenResty.
- The examples cover the request verbs and the shared response fields, the arithmetic of the retry loop, which methods retry by default, and where cancellation lives.
- They also cover hooks and fuller worked examples.
- The examples use tiny in-memory backends, the same technique the test suite uses, so every printed count is exact.
- Apart from one query-string interlude that runs live, the examples are shown for reading.
Requests and responses
A client over a backend
The module is a factory. Pass a backend with fetch(url, opts) and sleep(ms), and get back { fetch, get, post, on }.
local http = require("santoku.http")
local client = http({
fetch = function (url, opts)
return true, { status = 200, body = "hello from " .. url }
end,
sleep = function (ms) end,
})
local ok, resp = client.get("http://example/api")
print(ok, resp.status)
return resp.body
GET with query params
get sets opts.method and appends str.to_query(opts.params) to the url before it hands the url to the backend. Values are percent-encoded.
local http = require("santoku.http")
local seen
local client = http({
fetch = function (url, opts)
seen = url
return true, { status = 200 }
end,
sleep = function (ms) end,
})
client.get("http://example/search", { params = { q = "hello world" } })
print("get:", seen)
client.post("http://example/search", { params = { q = "hello world" } })
print("post:", seen)
return seen
Details
- Only string, number and boolean params are kept. get drops anything else silently.
- params is a get feature. post and fetch forward params untouched, and no transport reads it.
- For other verbs, encode the query into the url yourself, as in a post to "/sync?since=" .. cursor.
- The built string always starts with "?", so hand get a url without one.
Query strings by hand
The encoding under get lives in santoku.string, so this example runs here. to_query builds the "?k=v" string that the client appends.
local str = require("santoku.string")
print(str.to_query({ q = "hello world" }))
print(str.to_formdata({ mode = "subscription" }))
local parsed = str.from_query("?page=2&debug=true&q=hello%20world")
print(tonumber(parsed.page) + 1, parsed.debug == "true", parsed.q)
return str.to_query({ n = 42 })
Details
- to_formdata gives the same pairs minus the leading "?", as the Stripe bodies below use.
- from_query reverses both. It decodes percent escapes and returns every value as a string.
- In santoku 3.4.4 and later, from_query also decodes "+" as a space.
- In santoku 3.4.4 and later, from_query splits each pair on its first "=".
- In santoku 3.4.4 and later, from_query splits pairs on "&" only. A value may thus hold "=" or ";".
POST with headers and body
post writes method = "POST" into the opts table you pass and forwards everything else untouched. Headers and body reach the backend exactly as given.
local http = require("santoku.http")
local seen
local client = http({
fetch = function (url, opts)
seen = opts
return true, { status = 201 }
end,
sleep = function (ms) end,
})
local ok, resp = client.post("http://example/items", {
headers = { ["Content-Type"] = "application/json" },
body = "{\"name\":\"widget\"}",
})
print(seen.method, seen.headers["Content-Type"])
print(ok, resp.status)
return seen.body
Details
- Encoding is the caller's job, in practice str.to_formdata and cjson.encode.
Any method through fetch
fetch is the primitive under get and post. Set opts.method yourself for DELETE, PUT or PATCH, as in method = "DELETE" with the rest unchanged.
local http = require("santoku.http")
local seen
local client = http({
fetch = function (url, opts)
seen = opts.method
return true, { status = 204 }
end,
sleep = function (ms) end,
})
local ok, resp = client.fetch("http://example/items/42", { method = "DELETE" })
print("method:", seen)
print(ok, resp.status)
return resp.status
The response convention
The client passes responses through untouched. Their fields are a convention that all three shipped transports keep.
local http = require("santoku.http")
local client = http({
fetch = function (url, opts)
local body = "{\"n\":1}"
return true, {
status = 200,
ok = true,
headers = { ["content-type"] = "application/json" },
body = function () return body end,
}
end,
sleep = function (ms) end,
})
local ok, resp = client.get("http://example/api")
print(ok, resp.ok, resp.status)
print(resp.headers["content-type"])
return resp.body()
Details
- ok is true for 2xx.
- status is a number.
- headers are lowercased.
- resp.ok mirrors the first return.
- body is a function, so streaming transports can defer the read.
The transport failure sentinel
When the network fails before any status arrives, all three transports return the same sentinel. ok is false, status is 0, headers are empty, and body() returns nil.
local http = require("santoku.http")
local client = http({
fetch = function (url, opts)
return false, {
status = 0,
ok = false,
headers = {},
error = "connection refused",
body = function () return nil end,
}
end,
sleep = function (ms) end,
})
local ok, resp = client.get("http://example/api", { retry = false })
print(ok, resp.status, resp.error)
print(resp.body())
return resp.status
Details
- error carries the transport's reason: the LuaSec message natively, err from lua-resty-http, and the thrown value in the browser.
- Status 0 counts as transient for the default retry filter. Probes that must answer fast thus pair it with retry = false.
- A status of 0 is the natural place to map "offline".
Retry
Retry with jittered backoff
Retry is on by default for GET, HEAD, OPTIONS, PUT and DELETE. Transient failures are re-fetched with a growing jittered delay between attempts. Here the third attempt succeeds, so the backend saw 3 calls and slept twice.
local http = require("santoku.http")
local calls, backoffs = 0, 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
if calls < 3 then
return false, { status = 503 }
end
return true, { status = 200, body = "recovered" }
end,
sleep = function (ms)
backoffs = backoffs + 1
end,
})
local ok, resp = client.get("http://example/flaky")
print("attempts:", calls, "backoffs:", backoffs)
print(ok, resp.status)
return resp.body
Retry by method since santoku-http 3.0.0
A method outside GET, HEAD, OPTIONS, PUT and DELETE makes one attempt unless the call passes retry. retry = true opts in with the default policy, and a retry table opts in with its own fields.
local http = require("santoku.http")
local calls = 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
return false, { status = 503 }
end,
sleep = function (ms) end,
})
client.post("http://example/items", { body = "x" })
print("default post:", calls)
calls = 0
client.post("http://example/items", { body = "x", retry = true })
print("retry = true:", calls)
calls = 0
client.post("http://example/items", { body = "x", retry = { times = 1 } })
print("times = 1:", calls)
return calls
Details
- A retried POST can run its write twice when only the response was lost, so a POST opts in only when the server side is safe to repeat.
- The method compares case-insensitively, and a fetch with no method counts as GET.
What retries by default
The default filter retries only when status is missing or 0 (transport failure), or one of 429, 502, 503 and 504. Everything else, 500 and 404 included, returns at once.
local http = require("santoku.http")
local calls = 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
return false, { status = 500 }
end,
sleep = function (ms) end,
})
local ok, resp = client.get("http://example/bug")
print("attempts:", calls)
print(ok, resp.status)
return resp.status
Details
- This example makes exactly one backend call.
Retry exhaustion since santoku-http 3.0.0
The default policy, also used by retry = true, is times = 3. A failing request makes times + 1 attempts with a backoff sleep between each pair, and the last attempt's result returns as-is.
local http = require("santoku.http")
local calls, sleeps = 0, 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
return false, { status = 503 }
end,
sleep = function (ms)
sleeps = sleeps + 1
end,
})
local ok, resp = client.get("http://example/down")
print("calls:", calls, "sleeps:", sleeps)
print(ok, resp.status)
return calls
Details
- A permanently failing endpoint sees 4 backend calls and 3 sleeps. Before santoku-http 3.0.0 it saw 5 calls.
Custom retry policies
opts.retry takes times, backoff, multiplier and filter(ok, resp), which decides what counts as transient. An unset field keeps its default.
local http = require("santoku.http")
local calls, sleeps = 0, 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
return false, { status = 500 }
end,
sleep = function (ms)
sleeps = sleeps + 1
end,
})
local ok, resp = client.get("http://example/fivehundred", {
retry = {
times = 1,
backoff = 50,
multiplier = 2,
filter = function (ok, resp)
return resp and resp.status == 500
end,
},
})
print("calls:", calls, "sleeps:", sleeps)
print(ok, resp.status)
return calls
Details
- times defaults to 3.
- backoff is the initial delay in ms, 1000 by default.
- multiplier defaults to 3.
- With times = 1 the first attempt fails, the loop sleeps once, and the second attempt returns unfiltered: 2 calls and 1 sleep.
retry = false
opts.retry = false makes exactly one attempt and returns whatever comes back. A connectivity probe works this way: a nonce fetch with retry = false answers "am I online" fast and doesn't back off for seconds.
local http = require("santoku.http")
local calls = 0
local client = http({
fetch = function (url, opts)
calls = calls + 1
return false, { status = 503 }
end,
sleep = function (ms) end,
})
local ok, resp = client.get("http://example/nonce", { retry = false })
print("attempts:", calls)
print(ok, resp.status)
return resp.status
The backoff schedule
Each delay is backoff + backoff * rand.num(), so it falls between 1x and 2x the current backoff. The multiplier then grows the backoff for the next attempt.
local http = require("santoku.http")
local delays = {}
local client = http({
fetch = function (url, opts)
return false, { status = 503 }
end,
sleep = function (ms)
delays[#delays + 1] = ms
end,
})
client.get("http://example/down", {
retry = { times = 2, backoff = 100, multiplier = 2 },
})
print("sleeps:", #delays)
print(delays[1] >= 100 and delays[1] < 200)
print(delays[2] >= 200 and delays[2] < 400)
return #delays
Details
- With backoff = 100 and multiplier = 2, the recorded delays land in [100, 200) and [200, 400).
Cancellation
Cancellation by scope since santoku-http 3.0.0
santoku-http holds no cancellation code. fetch, get and post always return ok, resp. In the browser the runtime owns cancellation: a component's disconnect or a newer call of a latest kills the scope the request runs in.
local http = require("santoku.web.http")
local async = require("my_app.async")
local search = async.latest(function (q)
return http.get("/api/search", { params = { q = q } })
end)
local function find (q)
local ok, resp = search(q)
return ok and resp.body()
end
return find
Details
- The kill aborts the fetch in flight through its AbortController and clears a backoff sleep, since that sleep is the browser runtime's sleep. No further attempt starts. The caller never resumes, so it needs no sentinel check.
- A response hook doesn't run for an attempt the kill aborted.
- In native scripts nothing cancels a request, and the retry loop runs to its end.
- latest comes from the app's santoku.async module: https://santoku.dev/santoku#santoku--santoku-async
Hooks
Hooks mutate in place since santoku-http 4.0.0
on("request", fn) calls fn(url, opts) before each attempt, and fn changes opts in place. on("response", fn) calls fn(ok, resp) after each attempt, and fn changes resp in place. A hook that returns a value raises.
local http = require("santoku.http")
local arr = require("santoku.array")
local log = {}
local client = http({
fetch = function (url, opts)
log[#log + 1] = url .. " traced=" .. opts.headers["x-trace"]
return true, { status = 200, body = "raw" }
end,
sleep = function (ms) end,
})
client.on("request", function (url, opts)
opts.headers = opts.headers or {}
opts.headers["x-trace"] = "1"
end)
client.on("response", function (ok, resp)
resp.body = resp.body .. " (rewritten)"
end)
local ok, resp = client.get("http://example/a")
log[#log + 1] = resp.body
print(arr.concat(log, "\n"))
return resp.body
Details
- Hooks fire per backend attempt, so a retried request logs once per try.
- Hooks run in the order added, and each one sees the changes of the hooks before it.
- A hook can't replace the url or ok. Response hooks run before the retry filter reads resp.
- A hook may block, such as on a token refresh, inside the request's task.
- A hook stays registered for the client's lifetime. santoku-http 4.0.0 removed off.
In practice
One client, three transports
Everything above is transport-independent. In the browser, santoku.web.http is the app's one client over santoku.web.socket, so a hook installed on it reaches every request in the app.
local http = require("santoku.http")
local in_browser = require("santoku.web.http")
local in_scripts = http(require("santoku.socket"))
local under_nginx = http(require("santoku.resty.socket"))
return in_browser, in_scripts, under_nginx
Details
- santoku.web.socket wraps browser fetch, and the scope that awaits it can abort it. Its sleep is santoku.web.async's sleep.
- santoku.socket wraps LuaSec's ssl.https with ltn12 for scripts and CLIs. Its sleep blocks, so retry works natively.
- santoku.resty.socket wraps lua-resty-http cosockets. Its sleep is santoku.resty.async's sleep, which calls ngx.sleep.
Version pinning through hooks
santoku.web.version.install_hooks is a real hook consumer. A request hook stamps x-client-version on same-origin requests, and a response hook compares the server's x-app-version header.
local http = require("santoku.web.http")
local version = require("santoku.web.version")
version.install_hooks(http, "42", function ()
print("server is ahead, reload for the new bundle")
end)
local ok, resp = http.get("/api/items")
print(ok, resp.status)
return resp.body()
Details
- The response hook fires on_mismatch once when the deploy has moved ahead.
- On the server, santoku.resty.version.check(expected) answers a stale client with 409.
Stripe from OpenResty
This billing integration sends form-encoded bodies through str.to_formdata and bearer auth in headers. It reads body() once up front, so both the error path and the success path can use it.
local json = require("cjson")
local str = require("santoku.string")
local http = require("santoku.http")(require("santoku.resty.socket"))
local secret_key = "sk_test_..."
local ok, resp = http.fetch("https://api.stripe.com/v1/checkout/sessions", {
method = "POST",
headers = {
["Authorization"] = "Bearer " .. secret_key,
["Content-Type"] = "application/x-www-form-urlencoded",
},
body = str.to_formdata({
mode = "subscription",
success_url = "https://example.com/ok",
["line_items[0][quantity]"] = "1",
}),
})
local body = resp.body()
if not ok then
return nil, "request failed: " .. (resp.error or body or "unknown")
end
if resp.status < 200 or resp.status >= 300 then
return nil, "stripe error " .. resp.status .. ": " .. (body or "")
end
return json.decode(body).url
AWS SigV4 and credentials since santoku-http 4.0.0
santoku.http.aws signs requests with AWS Signature Version 4 and needs no SDK. instance_credentials reads an EC2 instance role's credentials through IMDSv2.
local json = require("cjson")
local utc = require("santoku.utc")
local http = require("santoku.http")(require("santoku.resty.socket"))
local aws = require("santoku.http.aws")
local creds = aws.instance_credentials(http)
local host = "cognito-idp.us-east-1.amazonaws.com"
local body = json.encode({ UserPoolId = "us-east-1_EXAMPLE", Username = "a@example.com" })
local headers = {
["Content-Type"] = "application/x-amz-json-1.1",
["X-Amz-Target"] = "AWSCognitoIdentityProviderService.AdminGetUser",
}
aws.sign({
method = "POST", host = host, path = "/", headers = headers, body = body,
region = "us-east-1", service = "cognito-idp", time = utc.time(), credentials = creds(),
})
local ok, resp = http.post("https://" .. host .. "/", { headers = headers, body = body })
return ok and json.decode(resp.body())
Details
- sign(r) takes method, host, path, query (the raw query string), headers, body, region, service, time (epoch seconds) and credentials.
- credentials holds access_key_id, secret_access_key and session_token.
- sign writes the headers it adds into r.headers, creating the table when r has none, and returns them: Authorization, X-Amz-Date, and X-Amz-Security-Token when there is a token.
- sign_body = true also signs and adds X-Amz-Content-Sha256.
- omit_session_token = true leaves the token out of the signed headers and still returns it.
- normalize = false keeps . and .. path segments as written, as S3 expects.
- A second return value carries canonical_request, string_to_sign and signature, for debugging a mismatch.
- The module is pure Lua over santoku.string, so it runs natively, in the browser and under OpenResty.
- Its spec passes AWS's published SigV4 test suite.
- instance_credentials(client[, opts]) returns a function that reads the credentials with the client you pass.
- That function caches the credentials until opts.margin seconds (300 by default) before they expire.
- opts.base_url (http://169.254.169.254), opts.token_ttl (21600 seconds) and opts.now (utc.time) override the endpoint, the IMDSv2 token lifetime and the clock.
- The example calls Cognito's JSON 1.1 API.
A stoppable sync loop
This sync orchestrator runs each post through a latest from the app's async module, so lock or teardown aborts the post in flight with syncing.cancel().
local http = require("santoku.web.http")
local async = require("my_app.async")
local syncing = async.latest(function (cursor, body, headers)
return http.post("/sync?since=" .. cursor, { headers = headers, body = body })
end)
local function sync (cursor, body, headers)
local _, response = syncing(cursor, body, headers)
local status = tonumber(response.status) or 0
if status == 0 then return "offline" end
if status == 401 then return "auth-required" end
if status == 409 then return "resync" end
if not response.ok then return false end
return response.body()
end
return sync, syncing.cancel
Details
- A cancelled sync never returns to its caller, so state the caller sets before the post, such as a sync-in-progress flag, gets its reset next to the cancel.
- Offline (status 0) and protocol statuses each route differently.
- The post makes one attempt, since a POST doesn't retry by default.
Examples
Projects that toku init creates with this rock. The examples page shows their files.
- A JSON API: An OpenResty server with no frontend, over a server-side sqlite database.
toku init --example api my-api - A command that runs under OpenResty: A Lua rock whose command and specs run under OpenResty's resty CLI and fetch URLs at once.
toku init --example resty my-tool