santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-socket

View on LuaRocks

HTTP(S) client: blocking fetch and millisecond sleep over LuaSocket and LuaSec

santoku-socket is the native HTTP(S) client, an HTTP/1.1 client over LuaSocket, with TLS from santoku.socket.stream over LuaSec. Its sockets wait through santoku.system.async, so a fetch in a task lets other tasks run. From the main thread, fetch and sleep read as blocking calls.

Details
  • The request and response format is small and uniform.
  • sleep is santoku.system.async's sleep.
  • Since santoku-socket 6.0.0, every socket this rock opens sets a 0 timeout and waits on its fd through the loop: fetch, tcp, stream, websocket and the server's accept and reads. DNS lookups still block.
  • santoku-http expects these same names of a backend. Plugging this module into that front end adds retry, hooks and query building with no glue.
  • Identical client code runs over this module's browser and OpenResty siblings.
  • santoku-socket needs native TLS sockets, so it runs in servers, CLIs and scripts, outside this page.
  • The examples are shown for reading, except the response model, which is plain Lua and runs live.
  • The examples run in order. fetch comes first, then sleep, then composition with santoku-http.
  • Last come the raw TLS stream driver and the WebSocket client built on it. Then come the TCP transport santoku-mysql runs over and a loopback HTTP listener for browser callbacks.

fetch

A simple GET

fetch(url) runs a GET and returns ok (true for 2xx) and a response table. resp.body is a function that returns the full text.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://example.com/")
print(ok, resp.status)
print(resp.headers["content-type"])
return #resp.body()
Illustrative: runs outside the browser.
Details
  • A connect, send or read failure returns false and status 0 with resp.error, so fetch itself never raises on network trouble.
  • fetch reads content-length, chunked and read-to-close bodies, and follows up to 5 redirects for GET and HEAD. opts.redirect = false stops that.
  • opts.timeout_ms (60000) bounds each read and write, and opts.connect_timeout_ms (30000) the connect and TLS handshake.

Compressed responses

fetch sends Accept-Encoding: gzip, deflate unless opts.headers already sets Accept-Encoding in any case. resp.body() is always the decoded body.

local socket = require("santoku.socket")
local err = require("santoku.error")
local ok, resp = socket.fetch("https://example.com/feed.xml")
print(ok, resp.headers["content-encoding"], resp.headers["content-length"])
print(#resp.body())
local _, gz = socket.fetch("https://example.com/archive.tar.gz")
print(gz.headers["content-type"], #gz.body())
local _, plain = socket.fetch("https://example.com/feed.xml", {
  headers = { ["Accept-Encoding"] = "identity" },
})
print(#plain.body())
print(err.pcall(socket.fetch, "https://brotli-only.example.com/"))
return ok
Illustrative: runs outside the browser.
Details
  • fetch never changes the headers table you pass.
  • gzip and x-gzip decode through santoku-zlib, every member included.
  • deflate decodes as zlib-wrapped or raw deflate, whichever the first two bytes say.
  • Stacked codings such as "deflate, gzip" decode in reverse order, and identity is ignored.
  • A body with no coding that starts with the gzip magic bytes 1f 8b decodes as gzip.
  • A Content-Type of application/gzip or application/x-gzip turns that detection off, so a .gz download stays compressed.
  • After a decode, content-encoding and content-length are gone from resp.headers, since both described the encoded bytes.
  • An untouched body keeps its content-length.
  • Non-2xx bodies decode too.
  • A coding fetch can't decode, br and zstd included, raises "unsupported content-encoding" and its name.
  • A corrupt body raises santoku-zlib's error, such as "gunzip", "truncated input".
  • These errors raise from fetch itself, so wrap the call in err.pcall when the server is untrusted.

The max_body cap

opts.max_body caps the output that fetch decodes, in bytes, at 67108864 (64 MiB) by default. A small gzip body can decode to gigabytes.

local socket = require("santoku.socket")
local err = require("santoku.error")
local ok, resp = socket.fetch("https://example.com/big.json", { max_body = 1048576 })
print(ok, #resp.body())
print(err.pcall(socket.fetch, "https://example.com/bomb", { max_body = 1048576 }))
return ok
Illustrative: runs outside the browser.
Details
  • A body that decodes past the cap raises "gunzip" or "inflate_raw" with "output exceeds max_out".
  • A body of exactly max_body bytes passes.
  • The cap applies only when fetch decodes. An uncompressed body comes back as received at any size.

The response fields

Every completed response carries status, ok, headers and body. Header keys are lowercased on the way in, and resp.ok always equals the first return.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://example.com/")
print(resp.status)
print(resp.ok == ok)
for k, v in pairs(resp.headers) do
  print(k, v)
end
return resp.body()
Illustrative: runs outside the browser.

The response model

This model takes the same steps as the module after the response arrives. The construction is plain Lua, so this example runs here.

local arr = require("santoku.array")
local str = require("santoku.string")
local chunks = { "{\"pong\"", ":true}" }
local raw_headers = {
  ["Content-Type"] = "application/json",
  ["X-Request-Id"] = "abc123",
}
local body = arr.concat(chunks)
local headers = {}
for k, v in pairs(raw_headers) do
  headers[str.lower(k)] = v
end
local status = 200
local is2xx = status >= 200 and status < 300
local resp = {
  status = status,
  ok = is2xx,
  headers = headers,
  body = function () return body end,
}
print(resp.status, resp.ok)
print(resp.headers["content-type"], resp.headers["x-request-id"])
print(resp.body())
print(resp.body() == resp.body())
return resp.body()
Details
  • It concatenates the sink chunks into one body.
  • It lowercases every header key.
  • It computes ok from the 2xx range.
  • It captures the body in a closure, so body() reads repeatedly.

POST with a body

Pass method, headers and body in opts. When a body is present and no content-length header is given, fetch derives one from the body's byte length.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://api.example.com/echo", {
  method = "POST",
  headers = { ["content-type"] = "application/json" },
  body = "{\"hello\":\"world\"}",
})
print(ok, resp.status)
return resp.body()
Illustrative: runs outside the browser.

Methods and headers

Any method string passes straight through to the transport. fetch keeps an explicit content-length as given and doesn't overwrite it. Auth is another header.

local socket = require("santoku.socket")
local token = "..."
local ok, resp = socket.fetch("https://api.example.com/items/42", {
  method = "PUT",
  headers = {
    ["authorization"] = "Bearer " .. token,
    ["content-type"] = "text/plain",
    ["content-length"] = "5",
  },
  body = "hello",
})
print(ok, resp.status)
return resp.status
Illustrative: runs outside the browser.

Non-2xx responses

A request that completes with a non-2xx status returns false. The response still carries the real status, headers and body, so error pages stay readable.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://example.com/missing")
print(ok, resp.ok, resp.status)
return resp.body()
Illustrative: runs outside the browser.

TLS verification

An https fetch connects through santoku.socket.stream's TLS layer. It verifies the server certificate and checks the hostname the same way raw TLS connections do.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://self-signed.badssl.com/")
print(ok, resp.status, resp.error)
local ok2 = socket.fetch("https://self-signed.badssl.com/", { verify = false })
print(ok2)
local ok3 = socket.fetch("https://10.0.0.5/", {
  cafile = "/etc/myca/root.pem",
  sslname = "api.internal",
})
return ok3
Illustrative: runs outside the browser.
Details
  • The CA source is opts.cafile or opts.capath when given.
  • Otherwise the CA source is SSL_CERT_FILE, then SSL_CERT_DIR, then the first santoku.socket.stream.ca_paths entry that exists. The last fallback is the bundle or directory OpenSSL was built with.
  • A failure in either check lands in resp.error with status 0 and no body.
  • opts.verify = false skips both checks.
  • opts.sslname names a host to verify and send as SNI when it differs from the URL's host.

Transport failures

A failure before any status arrives yields status 0, empty headers, and a body() that returns nil and doesn't raise.

local socket = require("santoku.socket")
local ok, resp = socket.fetch("https://localhost:1/down")
print(ok, resp.status)
print(resp.error)
return resp.body() == nil
Illustrative: runs outside the browser.
Details
  • The socket's error message, such as "connection refused" or "timeout", lands in resp.error.

Save a response to disk

body() hands back the whole text, so a download takes one santoku.fs call to save.

local socket = require("santoku.socket")
local fs = require("santoku.fs")
local ok, resp = socket.fetch("https://example.com/data.json")
if ok then
  fs.writefile("data.json", resp.body())
end
print(ok, resp.status)
return resp.headers["content-length"]
Illustrative: runs outside the browser.

sleep

Millisecond sleep

sleep takes milliseconds and is santoku.system.async's timer sleep. Inside a task it yields. From the main thread it runs the loop until the deadline.

local socket = require("santoku.socket")
socket.sleep(250)
socket.sleep(1500)
return true
Illustrative: runs outside the browser.

Composition

A REST wrapper

One function turns method, path and params into a bearer-authenticated, form-encoded request. It returns a decoded JSON table or an error string.

local socket = require("santoku.socket")
local str = require("santoku.string")
local cjson = require("cjson")
local key = "..."
local function stripe (method, path, params)
  local opts = {
    method = method,
    headers = {
      ["authorization"] = "Bearer " .. key,
      ["content-type"] = "application/x-www-form-urlencoded",
    },
  }
  if params then
    opts.body = str.to_formdata(params)
  end
  local ok, resp = socket.fetch("https://api.stripe.com" .. path, opts)
  local body = resp.body()
  if not ok then
    return nil, "request failed: " .. (resp.error or body or "unknown")
  end
  return cjson.decode(body)
end
local session, err = stripe("POST", "/v1/checkout/sessions", {
  mode = "subscription",
})
return session or err
Illustrative: runs outside the browser.
Details
  • body() returns nil on transport failure and doesn't raise. The error path can thus use resp.error or the body without extra guards.

A santoku-http backend

santoku-http expects a backend with fetch and sleep, the two functions this module exports.

local http = require("santoku.http")(require("santoku.socket"))
local ok, resp = http.get("https://api.example.com/search", {
  params = { q = "lua" },
})
print(ok, resp.status)
local pok, presp = http.post("https://api.example.com/jobs", { body = "{}", retry = true })
print(pok, presp.status)
return presp.status
Illustrative: runs outside the browser.
Details
  • One line adds query params through to_query, request and response hooks, and retry with jittered backoff.
  • By default santoku-http retries GET, HEAD, OPTIONS, PUT and DELETE 3 times, starting at 1000ms with a 3x multiplier, on status 0, 429, 502, 503 and 504. A POST or PATCH retries only when the call passes retry.
  • Retry and backoff belong in santoku-http, so don't hand-roll them over fetch.
  • santoku-http runs retry through santoku.async's retry over this module's sleep, which is the native loop's.
  • A retry backoff in a task lets other tasks run.

One contract, three transports

The response fields are shared, so the same application code runs over three interchangeable backends. They are this module in native scripts, santoku.web.socket in the browser, and santoku.resty.socket under OpenResty.

local native = require("santoku.http")(require("santoku.socket"))
local browser = require("santoku.web.http")
local server = require("santoku.http")(require("santoku.resty.socket"))
local function ping (http)
  local ok, resp = http.get("https://example.com/ping")
  return ok and resp.body()
end
return ping
Illustrative: runs outside the browser.

Lower-level modules

The raw TLS stream driver

santoku.socket.stream's connect(opts, done) dials host and port and wraps the socket in TLS unless tls = false. It hands done(ok, conn) a connection with write, close and step.

local stream = require("santoku.socket.stream")
stream.connect({
  host = "imap.example.com",
  port = 993,
  data = function (chunk) print("read", #chunk, "bytes") end,
  closed = function (e) print("closed:", e) end,
}, function (ok, conn)
  if not ok then
    return print("connect failed:", conn)
  end
  print("verified:", conn.tls.verified)
  conn.write("A1 CAPABILITY\r\n")
  for _ = 1, 10 do
    conn.step(200)
  end
  conn.close()
end)
return true
Illustrative: runs outside the browser.
Details
  • Protocols outside request and response need bytes instead of messages, and santoku.socket.stream is that layer.
  • Inbound data is pushed. Every chunk the socket produces goes to the data callback in whatever fragmentation the network gave it.
  • Reassembly is the protocol's job.
  • The driver exposes step(ms). step does one bounded read, waiting through the native loop, and delivers it through the same data callback.
  • step returns true, "timeout" when the window passed with nothing to read. It returns false plus a reason once the connection is gone.
  • connect_timeout_ms defaults to 30000.
  • sslname overrides the SNI name when it differs from host.

The WebSocket client

santoku.socket.websocket's connect(url, opts, done) opens a ws:// or wss:// connection over the stream driver. It runs the RFC 6455 handshake and hands done(ok, conn) the connection or a reason.

local ws = require("santoku.socket.websocket")
local reply
ws.connect("wss://echo.example.com/socket", {
  message = function (data, kind) reply = data end,
  closed = function (code, reason) print("closed:", code, reason) end,
}, function (ok, conn)
  if not ok then
    return print("connect failed:", conn)
  end
  conn.send("hello")
  print(conn.wait(function () return reply ~= nil end, 5000), reply)
  conn.close()
end)
return true
Illustrative: runs outside the browser.
Details
  • Messages are pushed. opts.message(data, kind) receives each reassembled message with kind "text" or "binary".
  • opts.ping, opts.pong and opts.closed(code, reason) report control frames.
  • conn.send(data[, binary]) sends text unless binary is true. It refuses text that isn't valid UTF-8.
  • conn.ping(data) sends a ping.
  • conn.close([code, reason, ms]) uses 1000 and a one-second wait by default.
  • conn.step(ms) does one bounded read.
  • conn.wait(fn, ms) steps until fn() is true or the time runs out, and then returns false, "timeout".
  • Nothing reads a conn's socket except its own step and wait. With two clients in one process, a message for the second waits until you call wait or step on that conn.
  • connect_timeout_ms defaults to 30000.
  • max_message defaults to 64 MiB.
  • frame_max fragments large sends.
  • The other options are protocols, headers, and verify, cafile, capath and sslname as for the stream driver.
  • accept_key(key) returns the Sec-WebSocket-Accept value that RFC 6455 derives from a key.
  • This backend has no accept, so santoku-websocket's accept raises on it.
  • The client has driven Chrome's DevTools protocol end to end, a 299 KB screenshot message included.

The TCP byte transport

santoku.socket.tcp's connect(opts) opens a TCP connection to opts.host and opts.port, or a unix socket at opts.path. It returns a transport, or nil and the error. santoku-mysql takes this module as its native transport.

local tcp = require("santoku.socket.tcp")
local err = require("santoku.error")
local t = err.assert(tcp.connect({ host = "127.0.0.1", port = 6379, timeout_ms = 2000 }))
err.assert(t.send("PING\r\n"))
print(t.receive(7) == "+PONG\r\n", t.idle())
t.close()
print(tcp.connect({ host = "127.0.0.1", port = 1, timeout_ms = 500 }))
Illustrative: runs outside the browser.
Details
  • opts.timeout_ms (30000) bounds every connect, send and receive.
  • send(data) writes all of data and returns true, or nil and the error.
  • receive(n) blocks until it has n bytes.
  • starttls(opts) upgrades the connection in place with santoku.socket.stream's verification (verify, cafile, capath, sslname) and sets t.tls.
  • idle() returns true when no unread bytes wait on the socket.
  • close() closes the socket.
  • santoku-resty's santoku.resty.tcp has connect, send, receive, starttls and close over cosockets, with keepalive(idle_ms) and no idle().

The loopback HTTP listener

santoku.socket.server's listen(opts) binds opts.host (127.0.0.1) on opts.port and returns a server with host, port, url, serve and close. It suits a CLI that needs a browser to call it back.

local server = require("santoku.socket.server")
local srv = server.listen()
print("open", srv.url)
local ok, token = srv.serve(function (req)
  if req.method == "GET" and req.path == "/" then
    return { status = 200, headers = { ["Content-Type"] = "text/html" },
      body = "<form method=post action=/done><input name=t><button>Send</button></form>" }
  elseif req.method == "POST" and req.path == "/done" then
    return { status = 200, body = "You can close this tab." }, req.body
  end
  return { status = 404 }
end, { timeout = 600000 })
srv.close()
print(ok, token)
Illustrative: runs outside the browser.
Details
  • opts.port is 0 by default, for an ephemeral port.
  • An OAuth redirect and a page that posts a token are such callbacks.
  • serve(handler, { timeout = ms }) accepts one connection at a time and calls handler(req).
  • req has method, path, target, query (decoded), headers (lowercased) and body.
  • serve reads the body to Content-Length, at most opts.max_body bytes, 1 MiB by default.
  • The handler returns a response table { status, headers, body } and, to stop, a second value. serve then returns true and that value.
  • A handler that returns nil answers 204.
  • At the timeout serve returns false and "timeout".
  • Every response closes its connection.
  • A malformed request gets 400, and an oversized body gets 413.
  • A request line and headers over 64 KiB get 431.
  • A client that sends nothing for opts.read_timeout_ms (10000) gets 408.
  • Those four answers never reach the handler.
  • A handler error answers 500 and raises.
  • The listener has no TLS, no keepalive and no chunked bodies.

Stream certificate verification

santoku.socket.stream verifies by default. luasec verifies the certificate chain and nothing else, so the driver also matches the host name against the certificate.

local stream = require("santoku.socket.stream")
stream.connect({
  host = "imap.example.com",
  port = 993,
  cafile = "/etc/ssl/certs/ca-certificates.crt",
  data = function (chunk) print(#chunk) end,
}, function (ok, conn)
  print(ok, ok and conn.tls.verified, ok and conn.tls.names[1])
end)
stream.connect({
  host = "192.0.2.10",
  port = 993,
  verify = false,
  data = function () end,
}, function (ok, conn)
  print("unverified:", ok, conn.tls.verified)
end)
return true
Illustrative: runs outside the browser.
Details
  • opts.cafile or opts.capath wins when given.
  • Otherwise the driver takes the CA bundle from SSL_CERT_FILE, or the directory from SSL_CERT_DIR. It then probes the common Linux and macOS paths.
  • The last fallback is the bundle or directory OpenSSL was built to look in.
  • The driver verifies the chain against that CA source.
  • A host name matches the certificate's subjectAltName dNSName entries, and a single leading wildcard label is honored.
  • An IPv4 or IPv6 address target matches the iPAddress entries instead, and it gets no SNI.
  • A certificate with no subjectAltName fails, since RFC 6125 retires commonName matching.
  • A mismatch closes the connection and reports which names the certificate actually carries.
  • No bundle found is a hard error, with no silent downgrade. Set SSL_CERT_FILE, pass cafile or capath, or pass verify = false to opt out deliberately.
  • conn.tls reports the outcome. It carries verified, the bundle used, and the names matched against.
  • stream.ca_paths is the probe list, and you can extend it before you connect.

One driver contract

The driver is injected, so a protocol written against this contract runs unchanged in every runtime where a driver exists.

local imap = require("santoku.imap")(require("santoku.socket.stream"))
imap.connect({ host = "imap.example.com", port = 993 }, function (ok, client)
  if not ok then
    return print("connect failed:", client)
  end
  client.login("me@example.com", "app-password", function (okl)
    print("login:", okl)
    client.logout(function () end)
  end)
end)
return true
Illustrative: runs outside the browser.
Details
  • santoku.socket.stream runs over LuaSocket and LuaSec.
  • santoku.web.stream runs over node tls under wasm.
  • santoku.resty.stream runs over ngx cosockets.
  • santoku-imap is the consumer to read. It takes a driver and detects whether step is present.
  • On a pull driver santoku-imap pumps internally, so completion is synchronous there.
  • On a push driver santoku-imap is event-driven, with the same callback API either way.

Examples

Projects that toku init creates with this rock. The examples page shows their files.

  • A WebSocket echo server: An OpenResty server that echoes WebSocket messages, with a spec that talks to it from a native client. toku init --example websocket my-websocket