santoku-resty
View on LuaRockswrap lua-resty HTTP, JWT and WebSocket clients for OpenResty, and share calls and a SQLite store across nginx workers
santoku-resty is the OpenResty glue layer. It supplies the cosocket and OpenSSL backends that run santoku-http, santoku-jwt, santoku-websocket and santoku-mysql inside nginx. santoku-resty also carries calls between nginx workers through shared memory and runs one SQLite store across the workers. Every module runs only inside an nginx worker, so every example here is display-only.
Details
- Every module calls the ngx API and the cosocket-based upstream rocks, which exist only inside an nginx worker.
- santoku.resty.jwt.openssl is the OpenSSL backend for RS256 and ES256. require("santoku.jwt")(require("santoku.resty.jwt.openssl")) builds the JWT module.
- The santoku-jwt tab covers that module: https://santoku.dev/santoku-jwt
- santoku.resty.websocket is the backend for santoku-websocket: https://santoku.dev/santoku-websocket
- santoku.resty.ring passes calls from every worker to one owner worker through shared memory.
- santoku.resty.sqlite runs one SQLite store across the workers. Each worker writes, or one writer serves the others through a ring.
- nginx confs templated by santoku-template route requests into Lua handlers. The handlers use these modules for outbound HTTP and token checks.
- santoku.resty.request reads a handler's query arguments and request body.
- santoku.resty.pipe runs child processes without blocking the worker.
- santoku.resty.async is the OpenResty runtime for santoku.async, and santoku.resty.version checks a client's version header.
santoku.resty.async
The OpenResty runtime since santoku-resty 3.0.0
santoku.resty.async is the OpenResty runtime for santoku.async. The app's one async module is require("santoku.async")(require("santoku.resty.async")), and every handler requires that module.
local async = require("santoku.async")(require("santoku.resty.async"))
local http = require("santoku.http")(require("santoku.resty.socket"))
local quote = async.retry(function (sym)
local ok, res = http.get("https://quotes.example.com/" .. sym, { retry = false })
return ok and res.body()
end, { times = 2, backoff = 200 })
local t0 = async.now()
local body = async.atleast(quote, 100)("LUA")
ngx.say(body or "no quote", " after ", async.now() - t0, " ms")
Details
| Function | Behavior |
|---|---|
| now() | resty.core.time's monotonic_msec |
| sleep(ms) | ngx.sleep(ms / 1000) |
| spawn(fn, ...) | ngx.thread.spawn, recorded in the caller's scope |
| scope() | a new scope under the caller's scope |
| run(s, fn, ...) | calls fn in the caller's light thread inside s |
| kill(s) | ngx.thread.kill on each light thread that s and its children spawned |
- OpenResty stops only light threads the caller spawned. kill raises when the scope holds a light thread the caller didn't spawn, such as a latest shared between sibling light threads.
- santoku.resty.socket's sleep is this runtime's sleep, and santoku.resty.sqlite hands this runtime to santoku-sqlite.
- santoku.async: https://santoku.dev/santoku#santoku--santoku-async
santoku.resty.socket
Fetch without raising
santoku.resty.socket is a second HTTP client, and its fetch(url, opts) never raises. fetch returns ok and a response, where ok is true for a 2xx status.
local socket = require("santoku.resty.socket")
local ok, res = socket.fetch("https://api.example.com/items", {
method = "GET",
headers = { ["Accept"] = "application/json" },
})
print(ok, res.status)
print(res.headers["content-type"])
if ok then
print(res.body())
else
print("failed:", res.error or res.status)
end
Details
- The response has lowercase header keys.
- res.body is a function that returns the body.
- res.ok repeats ok.
- A transport error returns { status = 0, ok = false, error = e }, with a body function that returns nil.
sleep since santoku-resty 3.0.0
sleep(ms) is santoku.resty.async's sleep. It calls ngx.sleep and yields the current light thread instead of blocking the worker.
local socket = require("santoku.resty.socket")
socket.sleep(500)
local ok, res = socket.fetch("https://api.example.com/big-report")
print(ok, res.status)
Details
- sleep takes milliseconds.
- fetch and sleep are the whole backend santoku-http needs, so a retry backoff yields too.
- nginx ends the request's light threads when the request ends.
A payments client
santoku.http(backend) takes a backend with socket's fetch and sleep functions. Pass it santoku.resty.socket to get a server-side client with retries and jittered backoff.
local json = require("cjson")
local str = require("santoku.string")
local http = require("santoku.http")(require("santoku.resty.socket"))
local function stripe_request (method, path, params, key)
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, res = http.fetch("https://api.stripe.com" .. path, opts)
local body = res.body()
if not ok then
return nil, "stripe error " .. res.status .. ": " .. (body or "")
end
return json.decode(body)
end
local session = stripe_request("POST", "/v1/checkout/sessions", {
mode = "subscription",
["line_items[0][quantity]"] = "1",
}, secret_key)
print(session and session.url)
Details
- The checkout POST makes one attempt, since a POST doesn't retry by default. A retry would create a second session.
santoku.resty.stream
TLS stream on a cosocket
connect(opts, done) gives santoku.socket.stream's contract inside an nginx worker, so a protocol client such as santoku-imap runs on either. It opens the connection, then calls done(true, conn) or done(false, reason).
local stream = require("santoku.resty.stream")
stream.connect({
host = "imap.example.com",
port = 993,
data = function (chunk) ngx.log(ngx.INFO, "read ", #chunk, " bytes") end,
closed = function (e) ngx.log(ngx.INFO, "closed: ", tostring(e)) end,
}, function (ok, conn)
if not ok then
return ngx.log(ngx.ERR, "connect failed: ", conn)
end
conn.write("A1 CAPABILITY\r\n")
ngx.sleep(1)
conn.close()
end)
Details
- connect opens an ngx.socket.tcp to opts.host and opts.port.
- The TLS handshake sends opts.sslname, or the host, as SNI, and verifies the certificate.
- opts.verify = false skips the verification.
- opts.tls = false skips TLS.
- A light thread reads in 8 KiB chunks and hands each chunk to opts.data(chunk).
- opts.closed(reason) fires once, when the peer closes or a read or write fails.
- conn.write(data) returns true, or false and the reason.
- conn.close() shuts the socket.
- conn.thread is the reader thread.
- opts.connect_timeout_ms, opts.send_timeout_ms and opts.read_timeout_ms default to 30000 ms.
- Verification needs lua_ssl_trusted_certificate in the nginx conf, and a hostname needs a resolver there.
santoku.resty.tcp
santoku-mysql's cosocket transport since santoku-resty 4.0.0
connect(opts) gives santoku.socket.tcp's contract over ngx.socket.tcp. It returns a transport with send, receive(n), starttls and close, or nil and the error.
local tcp = require("santoku.resty.tcp")
local t, e = tcp.connect({ host = "10.0.0.5", port = 6379, pool = "cache", pool_size = 8 })
if not t then
return ngx.log(ngx.ERR, "connect failed: ", e)
end
t.send("PING\r\n")
ngx.say(t.receive(7) == "+PONG\r\n", " reused ", t.reused)
t.keepalive(60000)
Details
- opts.host and opts.port name the peer, or opts.path names a unix socket.
- opts.timeout_ms (30000) applies to connect, send and read.
- opts.pool names a keepalive pool of opts.pool_size connections.
- t.reused counts how often nginx handed this connection out before.
- keepalive(idle_ms) returns the connection to the pool in place of close.
- The transport has no idle().
- starttls verifies against lua_ssl_trusted_certificate and checks an IP host against the certificate's IP entries.
- Given cafile or capath, starttls closes the connection and returns nil and "set lua_ssl_trusted_certificate in nginx.conf; cafile and capath don't apply under OpenResty".
- semaphore(n) wraps santoku.resty.async's semaphore with wait(ms) and post(). santoku-mysql pools connections over any transport that exports semaphore.
- Like every cosocket, a transport serves only the request that opened it.
santoku.resty.pipe
Child processes that yield since santoku-resty 4.0.0
sh(opts) and pread(opts) take santoku.system's options and return the same iterators. They run the child through ngx.pipe, so the worker serves other requests while the child runs.
local pipe = require("santoku.resty.pipe")
for line in pipe.sh({ "git", "-C", "/srv/site", "log", "-1", "--format=%h" }) do
ngx.say("deployed ", line)
end
for ev, pid, a, b in pipe.pread({ "sh", "-c", "echo out; exit 3", stderr = true }) do
ngx.say(ev, " ", a, " ", b or "")
end
Details
- santoku.system's sh and pread block the whole worker until the child exits.
- sh yields stdout lines and raises "child process exited with unexpected status" on a non-zero exit. pread yields ("stdout" or "stderr", pid, chunk) and ("exit", pid, reason, status).
- reason is exited or signaled, as in santoku.system.
- The options are the argument list, stdout, stderr, stdin, env, jobs, job_var, bufsize and skip_blank.
- env and job_var add variables through env(1). nginx passes a worker only the variables its env directives name, so add env PATH; to find programs on PATH.
- Without stdin the child reads end of file at once.
- An unwatched stdout goes to the worker's stdout, and an unwatched stderr to its stderr, which nginx points at the error log.
- fn and execute raise, because ngx.pipe can't fork the worker or hand it a terminal.
- Call sh and pread where the handler can yield: a request handler, a timer or the resty command.
santoku.resty.ring
Calls to one owner worker
santoku.resty.ring carries calls from the other nginx workers to one owner worker through shared memory. call(name, payload, timeout_ms) sends a string and returns the owner's result string to its caller.
worker_processes 4;
events { worker_connections 1024; }
http {
init_by_lua_block {
require("santoku.resty.ring").create("seq", { slots = 256, slot_size = 512 })
}
init_worker_by_lua_block {
local ring = require("santoku.resty.ring")
if ngx.worker.id() == 0 then
local lost = ring.serve("seq", require("myapp.seq").batch)
if lost > 0 then
ngx.log(ngx.WARN, lost, " seq calls were lost with the last owner")
end
else
ring.attach("seq")
end
}
server {
listen 8080;
location = /next {
content_by_lua_block {
local label = ngx.var.arg_label or "id"
if ngx.worker.id() == 0 then
return ngx.say(require("myapp.seq").next_id(label))
end
local res, e, code = require("santoku.resty.ring").call("seq", label, 1000)
if not res then
ngx.status = code == "full" and 503 or (code == "timeout" or code == "lost") and 504 or 500
return ngx.say(e)
end
ngx.say(res)
}
}
}
}
Details
- In init_by_lua, create(name, opts) maps the ring for ngx.worker.count() workers.
| create option | Default | Allowed |
|---|---|---|
| opts.slots, the slots per worker | 1024 | 1 to 65536 |
| opts.slot_size, the bytes per slot | 4096 | 16 to 16777216 |
| opts.max_bytes, the bytes per payload or result | 268435456 | slot_size to 2147483647 |
- create also raises on a name over 63 bytes or a ninth ring.
- Each slot takes slot_size plus 32 bytes, rounded up to a multiple of 64. A worker's part is about 4.3 MB at the defaults.
- In init_worker_by_lua, one worker calls serve(name, handler, opts), and every other worker calls attach(name).
- A payload over slot_size takes as many free slots of the caller's part as it needs.
- When the free slots can't hold the whole payload, it streams through them in turns. The owner joins the turns before the handler sees the payload.
- A result over the slots its call holds streams back the same way.
- A large call waits in line with the worker's other calls, so it keeps its place in the worker's order.
- The calls behind a large call wait until it has sent its last bytes.
- The request yields to nginx while it waits. Use call from a phase that can yield, such as content_by_lua.
- One worker's calls reach the owner in the order that worker made them. Calls that wait for a free slot keep that order.
- Up to 8 rings can exist, each with its own owner. One worker can own one ring and attach to another.
- A ring carries requests to its owner and results back. It has no push from the owner and no calls between two attached workers.
- The owner can't call its own ring. call raises "santoku.resty.ring: ring seq isn't attached in this worker".
- A request that the owner takes thus runs the service in place, as /next does for worker 0.
- The owner can still serve HTTP. A handler that blocks, such as a synchronous COMMIT, delays those requests.
- The privileged agent can't serve or attach.
- The code is nginx.conf, with myapp.seq from the next card.
Batch handler and errors
serve's handler(payloads, n) gets up to opts.batch payloads (1024) and returns a table of n result strings in the same order. call returns nil and an error string when it has no result.
local n = 0
local function next_id (label)
n = n + 1
return label .. " " .. n
end
return {
next_id = next_id,
batch = function (payloads, count)
local out = {}
for i = 1, count do
out[i] = next_id(payloads[i])
end
return out
end,
}
Details
- The payloads arrive in payloads[1] to payloads[n].
- serve reuses the payloads table from batch to batch, so read only its first n entries.
- serve runs the handler from an ngx.timer thread, one batch at a time, so the handler may yield.
- serve returns how many calls the owner's previous process had taken when it died. Those calls return lost.
- Each error is a status word, a colon and a detail.
- Since santoku-resty 4.1.0, call returns the status word alone as a third value: local res, e, status = ring.call(name, payload, timeout_ms).
- "full: every slot stayed busy until the timeout": the owner never saw the payload.
- "timeout: no result came before the timeout": the payload was queued, so the owner may still apply it.
- "lost: the owner died with the payload in its batch": the owner may have applied it.
- "lost: the owner died before the whole payload arrived": the handler never saw it.
- "lost: the owner died before the whole result came back": the handler ran.
- "failed: " plus the message: the handler raised. Every call in that batch gets the message, cut to slot_size.
- "failed: payload of N bytes exceeds max_bytes M": nothing left the worker.
- "failed: result of N bytes exceeds max_bytes M": the handler ran, but its result stayed with the owner.
- "failed: handler returned no string for this item": the handler's result for that call isn't a string.
- call raises only on a missing ring or a payload that isn't a string.
- The code is myapp/seq.lua. The counter lives only in the owner, so every worker gets numbers from one sequence.
Respawns, reloads and state
nginx respawns a dead worker on the same ring, and a reload (HUP) makes a new ring for the new workers. state(name) returns this worker's view of the ring.
local cjson = require("cjson")
local ring = require("santoku.resty.ring")
local s = ring.state("seq")
ngx.say(s.role, ": ", s.free, " of ", s.slots, " slots free, ", s.inflight, " in flight")
for w = 1, s.workers do
ngx.say(w - 1, " ", cjson.encode(s.parts[w]))
end
Details
- A respawned owner marks each payload its old process had taken as lost and wakes those callers. Then it serves the queued payloads as usual.
- A respawned attached worker frees the slots its old process left in flight once their results arrive.
- The owner drops the parts of payloads and results it held for the old process.
- A call that times out partway through a large payload or result tells the owner to drop what it holds, then frees its slots.
- A reload runs init_by_lua again, so create makes the new ring.
- The old owner serves the old workers until they've exited and their queues are empty, for at most 30 seconds.
- Calls in flight during a reload thus still get their results.
- state returns workers, slots, slot_size, max_bytes, role, writer_pid, pending, free, inflight and parts.
- role is writer, client or none.
- pending is the payloads and results that the owner holds partway.
- free and inflight are this worker's slot counts.
- parts holds one entry per worker, with head, tail, pid, gen (how many processes have attached), and the count of slots in each state.
- The slot states are free, filling, queued, taken, done and linked. A linked slot is the second or a later slot of a large call.
Pack and unpack
pack(...) turns a list of Lua values into one string, and unpack(s) returns the same list. A ring's payloads and results are strings, so use them to send Lua values.
local str = require("santoku.string")
local ring = require("santoku.resty.ring")
local function batch (payloads, n)
local out = {}
for i = 1, n do
local op, key, t = ring.unpack(payloads[i])
out[i] = ring.pack(op, key, #t.ids, t.ids[3])
end
return out
end
local payload = ring.pack("count", nil, { ids = { 1, 2, 123456789012345 }, [true] = 0.5 })
local op, key, n, last = ring.unpack(batch({ payload }, 1)[1])
ngx.say(op, " ", tostring(key), " ", n, " ", str.format("%.0f", last))
Details
- Numbers travel as doubles, so 123456789012345, -0.0 and NaN arrive as they left.
- Since santoku-resty 4.0.0, ring.pack and ring.unpack are santoku.pack's pack and unpack from core santoku 5.1.0. The bytes are the same as before.
- Strings keep embedded zero bytes.
- Tables keep number and boolean keys as well as string keys.
- nils keep their place in the list.
- A userdata crosses when its metatable sets __pack to the name of the module that rebuilds it.
- pack stores that name and the string v:raw() returns. unpack returns require(name).from_raw(s).
- santoku-matrix sets __pack on its vectors (ivec, fvec, dvec, svec, cvec, pvec, rvec) and on mtx, csr and spans. They arrive as copies with the same type.
- An error from raw() raises from pack.
- pack raises on a function, cdata, a userdata with no __pack, a table with a metatable, or a table or userdata used as a key.
- pack also raises on tables nested deeper than 64, which catches a cycle.
- unpack raises on truncated input, an unknown tag and trailing bytes.
- santoku.resty.sqlite packs its write arguments and results this way in single mode.
- The code is a batch handler that unpacks each payload and packs its result, called here on one payload. It prints count, nil, 3 and 123456789012345.
Matching nginx headers
santoku.resty.ring is C that calls nginx's own functions. santoku-resty compiles it only against nginx headers that match the OpenResty it installs into.
local ring = require("santoku.resty.ring")
if not ring then
ngx.log(ngx.ERR, "santoku.resty.ring wasn't built: this OpenResty has no matching nginx headers")
return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end
ngx.say(ring.state("seq").writer_pid)
Details
- The build looks in nginx/include under that OpenResty's prefix, three directories above LUA_INCDIR.
- The build compares nginx_version and the configure arguments with nginx/sbin/nginx -V.
- When the headers are missing or differ, the build prints "santoku-resty: santoku.resty.accept and santoku.resty.ring not built: " and the reason.
- require("santoku.resty.ring") then returns false.
- setup-toku.sh --resty installs matching headers into the managed OpenResty: https://santoku.dev/install
- santoku.resty.sqlite needs the ring in single mode only.
santoku.resty.sqlite
One store across workers
santoku.resty.sqlite runs a SQLite database under every nginx worker through stores. A store is the builder santoku-sqlite's db.store takes: a function (db) that prepares statements and returns { read = {...}, write = {...} }.
return function (db)
local add = db.inserter("insert into notes (body) values (?)")
return {
read = {
body = db.getter("select body from notes where id = ?"),
count = db.getter("select count(*) from notes"),
},
write = {
add = function (body)
return add(body)
end,
},
}
end
Details
- santoku-sqlite's store card has that contract, so one builder module serves plain Lua and nginx unchanged: https://santoku.dev/santoku-sqlite
- In init_by_lua, call init(opts), then store(builder) once per builder. Every forked worker then inherits the stores.
- store returns the store's module table at once.
- init_worker() in init_worker_by_lua opens this process's connection and fills that table.
- store with the same builder returns the same table, which is how a handler gets it.
- store with a new builder after the workers start raises "register each builder in init_by_lua, before the workers start".
- In single mode two stores can't share a write method name, since the writer finds each write by name.
- The code is myapp/notes.lua, a builder module, and the next card wires it into nginx.conf.
init, init_worker and a handler
init(opts) in init_by_lua takes the store settings and doesn't open the database. init_worker(fn) in init_worker_by_lua migrates, opens this process's connection, fills the stores and returns the process's role.
worker_processes 4;
events { worker_connections 1024; }
http {
init_by_lua_block {
local resty_sqlite = require("santoku.resty.sqlite")
resty_sqlite.init({
file = "/var/lib/myapp/notes.db",
writer = "single",
migrate = function (db)
db.exec("create table if not exists notes (id integer primary key, body text not null)")
end,
})
resty_sqlite.store(require("myapp.notes"))
}
init_worker_by_lua_block {
require("santoku.resty.sqlite").init_worker()
}
server {
listen 8080;
location = /notes {
content_by_lua_block {
local notes = require("santoku.resty.sqlite").store(require("myapp.notes"))
local ok, id = notes.add(ngx.var.arg_body)
if not ok then
return ngx.say(id)
end
ngx.say(notes.body(id), " is note ", id, " of ", notes.count())
}
}
}
}
Details
- init needs opts.file and opts.writer, which is "local" or "single".
- Every worker runs opts.migrate(db) in init_worker, on its own setup connection, inside one db.transaction. The privileged agent doesn't run it.
- migrate must thus be idempotent, as with CREATE TABLE IF NOT EXISTS.
- migrate can't change journal_mode or run VACUUM, since neither works inside a transaction.
- init_worker runs fn(role) after it fills the stores, so app setup that needs the stores goes in fn.
- init_worker returns local, writer, reader, or agent for the privileged agent.
- init_worker raises "init wasn't called" when init didn't run in init_by_lua.
- init_worker raises "fn must be a function" when fn is set to anything else.
- A process's setup covers migrate, opening a connection, a builder, fn, and attaching to the ring.
- When a setup step raises, init_worker logs the error and the role at crit, waits 1 second and exits the process. nginx then starts a new one.
- Before the wait, a worker closes its listeners through santoku.resty.accept when that module is built.
- Under reuseport, that close takes the worker's socket out of the group, so new connections go to the other workers.
- Connections already queued on that socket at that moment are reset.
- The OpenResty that setup-toku.sh installs listens on the socket again in the next process whose setup succeeds.
- The failed process takes no requests. A transient cause, such as a locked file, heals on the next try.
- A lasting cause shows as at most one crit line a second.
- A writer that fails leaves the readers' writes queued until it comes back, up to opts.timeout_ms.
- init turns on nginx's privileged agent. init_worker runs santoku-sqlite's db.checkpointer there, one step every opts.checkpointer.every_ms (100).
- With opts.checkpointer = false, init leaves the agent off and nothing checkpoints. An outside tool such as litestream then owns the WAL.
- Since santoku-resty 4.0.0, init raises when it gets the removed top-level opts.checkpoint_ms.
- opts.retry goes to db.retry_busy, and opts.checkpointer goes to db.checkpointer.
- Since santoku-resty 3.0.0, santoku.resty.sqlite passes santoku.resty.async to both as opts.runtime, and init raises when either table sets runtime.
- Every connection opens through santoku-sqlite's shared.open. It runs in WAL mode with synchronous NORMAL and wal_autocheckpoint = 0.
- An app that turns its store off skips both calls.
- A handler calls store with the same builder to get the filled table.
- The code is nginx.conf.
Local and single modes
opts.writer picks how writes reach the file. In local mode each worker writes on its own connection, and in single mode worker 0 is the one writer. A store's methods stay the same in both modes.
require("santoku.resty.sqlite").init({
file = "/var/lib/myapp/notes.db",
writer = "local",
retry_dict = "sqlite_retry",
retry = { first_ms = 0.1, max_ms = 250, budget_ms = 30000, fair_ms = 2 },
checkpointer = { every_ms = 100, mode = "restart", restart_every = 10, restart_frames = 0, idle_steps = 10 },
})
require("santoku.resty.sqlite").store(require("myapp.notes"))
Details
- In local mode every method runs through santoku-sqlite's db.store, and each write runs inside db.transaction.
- Local-mode workers take the write lock in turn through db.retry_busy with opts.retry.
- opts.retry_dict names a lua_shared_dict for retry_busy's count, so the write that has waited longest gets the lock next.
- santoku-sqlite's retry_busy card has the measurements for that queue: https://santoku.dev/santoku-sqlite
- opts.retry_dict is the only source of that count. Since santoku-resty 4.0.0, init raises when opts.retry sets count.
- In single mode worker 0 closes its listeners through santoku.resty.accept, so it takes no connections.
- Then worker 0 opens the write connection and serves a santoku.resty.ring.
- Every other worker runs read methods on its own connection with query_only = 1. It sends each write's method name and arguments to worker 0.
- Single mode thus needs worker_processes 2 or more.
- In single mode init raises "needs at least 2 worker_processes" when ngx.worker.count() is below 2, so nginx fails to start.
- Without santoku.resty.ring, init raises an error that ends "needs santoku.resty.ring, which this openresty build lacks".
- opts.slots (1024) and opts.slot_size (4096) size the ring.
- opts.max_bytes (268435456) caps a write's packed arguments and its packed result.
- opts.batch (1024) caps the writes in one writer transaction.
- Arguments and results of any size up to max_bytes cross the ring with no app code.
- The table measures a pre-release build of single mode with 4 workers and 64 clients, 3 runs each. Request rates are medians.
- In the baseline, each worker wrote on its own connection with retry_busy and the checkpointer.
| Workload | Baseline | Single mode |
|---|---|---|
| writes, requests per second | 175.5k | 320.3k |
| write p99 | 1.36 ms | 0.38 ms |
| slowest write | 2655 ms | 138 ms |
| mixed load, requests per second | 270.7k | 397.0k |
| reads, requests per second | 629.9k | 475.4k |
| WAL peak under writes | 0.67 GB | 1.8 GB |
- Reads fall in single mode because worker 0 takes no requests.
- The code is local mode's init with every retry and checkpointer option at its default.
- nginx.conf needs "lua_shared_dict sqlite_retry 1m;" in its http block.
What a write returns
A write method returns true and its own values, or nil and an error string, in both modes. A read method returns its values and raises on error. A write waits up to opts.timeout_ms (10000) for its result.
local str = require("santoku.string")
local notes = require("santoku.resty.sqlite").store(require("myapp.notes"))
local http = { full = 503, timeout = 504, lost = 504, committed = 200, failed = 500 }
local ok, id = notes.add(ngx.var.arg_body)
if ok then
return ngx.say(id)
end
ngx.status = http[str.match(id, "^(%l+): ")]
ngx.say(id)
Details
- Each error is a status word, a colon and a detail.
- err.checkok(notes.add(x)) returns the write's values or raises the error. local ok, r = notes.add(x) branches on ok, and str.match(r, "^(%l+): ") gives the status word, such as "full" or "committed", for a table lookup of an HTTP status.
- "failed: " plus the message: the write raised, and nothing it did was kept.
- Single mode adds the errors that follow.
- "failed: payload of N bytes exceeds max_bytes M": the packed arguments are over opts.max_bytes, so the write never left the worker.
- "full: every slot stayed busy until the timeout": the write never left the worker.
- "timeout: no result came before the timeout" and "lost: the owner died with the payload in its batch": the outcome is unknown, so the write may have committed.
- "lost: the owner died before the whole payload arrived": the write never ran.
- "lost: the owner died before the whole result came back": the write committed.
- "committed: result of N bytes exceeds max_bytes M": the write committed, but its packed result is over opts.max_bytes.
- When a write must apply once, store an idempotency key in the same transaction.
- The writer runs up to opts.batch writes from the ring in one transaction.
- When one write raises, the writer rolls the batch back. It runs the batch again with a savepoint around each write, so only that write fails.
- The other writes in that batch run twice, so keep a write method's effects inside the database.
- A light thread's writes land in the order it makes them, since each call returns only after its write is done or has failed.
- Writes from other light threads and other workers may land between them.
- In single mode a read method that writes raises SQLite's readonly error.
- In single mode, arguments and results cross to the writer through santoku.pack, and a reader's write methods come from santoku.async.proxy.
- Numbers, the places of nils and santoku-matrix values thus arrive unchanged.
- A write raises in the caller when an argument can't be packed.
- A result that can't be packed fails its write, which rolls back.
- The message in a "failed: " error is cut to opts.max_bytes minus 16 bytes.
- Local mode passes arguments and results through unchanged.
- The code maps each error to a status.
Handlers
Templated nginx confs
The nginx conf is typically a santoku-template file rendered at build time. Each API location's content_by_lua_block requires a web module and calls the function it returns.
local auth = require("tasks.web.auth")
local stripe = require("tasks.stripe")
return function ()
local psub, user = auth.signed_header("portal")
auth.require_token(psub)
if not user.stripe_customer_id or user.stripe_customer_id == "none" then
return auth.fail(400, "no_subscription")
end
local portal_url, e = stripe.create_portal_session(
user.stripe_customer_id, return_url)
if not portal_url then
return auth.fail(500, "portal_failed", { detail = e })
end
ngx.header.content_type = "text/plain"
ngx.say(portal_url)
end
Details
- Those handlers take the inbound side with the raw ngx API. They use santoku-resty for the outbound side, as the Stripe portal handler in the code does.
Query arguments and bodies since santoku-resty 4.0.0
santoku.resty.request reads query arguments and request bodies in a handler. A check that fails returns nil, an HTTP status and a message, and the handler sends its own error response.
local request = require("santoku.resty.request")
local response = require("santoku.resty.response")
local function fail (code, msg)
return response.json({ ok = false, error = msg }, code)
end
local page = request.int("page", 1, 1, 1000)
local q = request.arg("q")
local body, code, msg = request.json(1024 * 1024)
if not body then
return fail(code, msg)
end
local title, tcode, tmsg = request.field(body, "title")
if not title then
return fail(tcode, tmsg)
end
return response.json({ page = page, q = q, title = title })
Details
- arg(name) returns the named query argument when it's set and not empty, decoded by ngx.unescape_uri, so + reads as a space. It returns nil otherwise.
- Since santoku-resty 4.0.0, arg raises when it gets a second name.
- int(name, default, min, max) floors the argument to an integer. It returns default when the argument is absent, not a number, infinite, or outside min and max.
- min and max are optional.
- Since santoku-resty 4.1.0, require("santoku.resty.response").json(value, status) sets the status (200 by default) and the content type application/json; charset=utf-8, sends cjson.encode(value) and ends the request with ngx.exit(status).
- required(name) returns the argument, or nil, 400 and "missing required parameter: name".
- body() returns the request body, including a body nginx buffered to a temp file. It returns nil for an empty body.
- json(max) decodes the body with cjson and returns the table. max is optional, and a JSON array passes as a table.
| Status | Message | When |
|---|---|---|
| 400 | missing request body | the body is empty |
| 413 | request body too large | the body is longer than max bytes |
| 400 | invalid JSON body | cjson can't decode the body |
| 400 | JSON body must be an object | the body decodes to a string, number or boolean |
- field(t, name) returns t[name], or nil, 400 and "missing required field: name" when the value is nil or cjson.null.
Query and form tables since santoku-resty 2.12.0
query, form and params read every argument of a request into one table that maps each name to a string.
local cjson = require("cjson")
local request = require("santoku.resty.request")
local p = request.params(32)
if not p.email or p.email == "" then
ngx.status = 400
return ngx.say(cjson.encode({ ok = false, error = "missing email" }))
end
ngx.say(cjson.encode({ email = p.email, remember = p.remember ~= nil }))
Details
- query(max) reads the query string with ngx.req.get_uri_args.
- form(max) reads a form-encoded body with ngx.decode_args, including a body nginx buffered to a temp file. It returns {} for an empty or absent body.
- params(max) reads the form on a POST and the query on any other method.
- Each value is decoded, so + reads as a space. A repeated name keeps its first value, and a name with no = reads as "".
- max caps how many arguments a call reads. Arguments past max are dropped without an error.
- The three return only the table, never a status. A temp file that can't be opened raises.
Client version checks since santoku-resty 3.0.0
santoku.resty.version.check(expected) compares the request's x-client-version header with expected. A stale client gets 409 and "Version mismatch", and every response carries x-app-version.
local version = require("santoku.resty.version")
version.check("42")
ngx.say("current client")
Details
- A request with no x-client-version passes.
- check moved here from santoku.web.version in santoku-web 10.0.0.
- santoku.web.version.install_hooks stamps the header in the browser: https://santoku.dev/santoku-http#santoku-http--version-pinning-through-hooks
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 - An offline web app: The web app with its data in sqlite in the browser, synced to the server, and a service worker so it boots offline.
toku init --example pwa my-app - 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 - A web app: A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server.
toku init --example web my-app - 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