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.

Getting started: a server API

build a JSON API with no frontend: OpenResty over a server-side SQLite database, scaffolded by toku init --example api

This tab builds a JSON API with no frontend. An OpenResty server sits over a SQLite database in WAL mode, with one connection and one set of prepared statements per nginx worker. toku init --example api scaffolds it, here as my-api.

Details
  • It's the server half of https://santoku.dev/start-web, isolated.
  • Everything here assumes toku is installed per https://santoku.dev/install, plus the managed OpenResty from toku setup --resty and git, which toku init runs.
  • Set OPENRESTY_DIR only to use your own OpenResty install instead.
  • A server-only project needs none of the client toolchain. toku doctor reports the project as server only and checks exactly that.
  • This tab follows the santoku-make 13.1.0-1 scaffold, under santoku-cli 5.0.0 or newer. https://santoku.dev/install has the upgrade commands for both.

Scaffold an API project

toku init --example api creates a complete, already-working JSON API, with specs that run with and without the server. The listing shows every file it writes.

$ toku init --example api my-api
Initialized empty Git repository in /home/you/my-api/.git/
warning: copyright is not set, so this project is all rights reserved with no notice; set it in make.lua
warning: license is not set, so this project is all rights reserved; set it in make.lua
Created my-api from the api example: A JSON API

Next steps:
  cd my-api
  toku start            # Build and start the server
  toku start --iterate  # The same, then rebuild and reload it on each edit
  toku test             # Run the specs beside it

$ find my-api -type f -not -path "*/.git/*" | sort
my-api/.gitignore
my-api/make.lua
my-api/res/server/migrations/0.0.1.sql
my-api/res/server/nginx.mustache
my-api/server/lib/my_api/migrations.tk.lua
my-api/server/lib/my_api/store.lua
my-api/server/lib/my_api/web/db.lua
my-api/server/lib/my_api/web/init.lua
my-api/server/lib/my_api/web/init_worker.lua
my-api/server/lib/my_api/web/items.lua
my-api/server/lib/my_api/web/status.lua
my-api/server/nginx.tk.conf
my-api/server/test/spec/db_file.lua
my-api/server/test/spec/my_api.lua
my-api/server/test/spec/status.lua
Illustrative: runs outside the browser.
Details
  • It writes the descriptor, the nginx config, the store, the migrations template, the init and init_worker pair, one handler, one migration and the specs.
  • migrations.tk.lua, web/init.lua, web/init_worker.lua, web/db.lua and web/status.lua are the same files that toku init --example web lays down. The server's database card covers them: https://santoku.dev/start-web#start-web--the-server-s-database
  • toku init runs git init unless you pass git = false through the API.
  • The name must be lowercase letters, digits and hyphens, and start with a letter.
  • A hyphenated name splits in two, as it does for libraries. The rock keeps the hyphen, and module directories and requires use underscores. So my-api publishes as the rock my-api, and its modules load as my_api.store and my_api.web.init.
  • --here scaffolds into the current directory and takes its name. The directory must be empty, and toku init rejects --here beside a project name.

A server without a database

The api example always scaffolds the SQLite layer and has no flag to leave it out. For a server with no database, such as a WebSocket relay or a proxy, delete the files below.

Shell
$ rm -r res/server/migrations
$ rm server/lib/my_api/migrations.tk.lua server/lib/my_api/store.lua server/lib/my_api/web/db.lua
$ rm server/lib/my_api/web/init.lua server/lib/my_api/web/init_worker.lua
$ rm server/lib/my_api/web/items.lua server/lib/my_api/web/status.lua server/test/spec/status.lua
res/server/nginx.mustache (lines to delete)
lua_shared_dict sqlite_retry 1m;
init_by_lua_block { require("my_api.web.init") }
init_worker_by_lua_block { require("my_api.web.init_worker") }
res/server/nginx.mustache (a location for your handler)
location = /health {
  content_by_lua_block { require("my_api.web.health")() }
}
Illustrative: runs outside the browser.
Details
  • In res/server/nginx.mustache, delete the sqlite_retry dict line and the two init blocks. A block that requires a deleted module fails the build with that module's name.
  • Drop santoku-sqlite, santoku-migrate and santoku-resty from server.dependencies.
  • Delete the store half of the spec, since it requires my_api.store.
  • Instead of deleting items.lua, you can rewrite it without my_api.web.db.
  • A location for your own handler replaces the /items location.
  • The env DB_FILE and env DB_WRITER lines at the top of nginx.mustache can go too.

The init and init_worker split

init_by_lua runs once in the master process before nginx forks its workers, and init_worker_by_lua runs once inside each worker afterwards. Anything that prepares statements belongs in the worker, never in the master.

server/lib/my_api/web/init.lua
local env = require("santoku.env")
local migrate = require("santoku.migrate")
local sqlite = require("santoku.resty.sqlite")
local migrations = require("my_api.migrations")

sqlite.init({
  file = env.var("DB_FILE", "data/my_api.db"),
  writer = env.var("DB_WRITER", "local"),
  migrate = function (db)
    migrate(db, migrations)
  end,
  retry_dict = "sqlite_retry",
})

require("my_api.web.db")
server/lib/my_api/web/init_worker.lua
require("santoku.resty.sqlite").init_worker()
server/lib/my_api/web/db.lua
return require("santoku.resty.sqlite").store(require("my_api.store"))
server/lib/my_api/web/items.lua (excerpt)
local db = require("my_api.web.db")

return function ()
  local created, id = db.create_item(req.name)
  ngx.status = status(created, id)
  ngx.say(json.encode(created and { id = id } or { status = id }))
end
Illustrative: runs outside the browser.
Details
  • The master opens no database, because a SQLite connection must not cross a fork.
  • So init.lua only configures santoku.resty.sqlite and registers the store. It requires my_api.web.db, which hands santoku.resty.sqlite.store the my_api.store builder.
  • store must run before the workers start, and it raises later.
  • The init_worker_by_lua of each worker calls santoku.resty.sqlite.init_worker. That call migrates on a setup connection, opens the worker's own connection and runs the builder on it.
  • So the statements are prepared in the worker that uses them. The privileged agent runs the checkpointer instead.
  • Handlers require my_api.web.db too, and require returns the module that init.lua already loaded. Every handler in a worker shares the one connection.
  • A handler that opens a connection itself opens a new one on every request, since content_by_lua_block calls the handler's function once per request. Nothing reports it.
  • The workers read DB_FILE and DB_WRITER, so nginx.mustache names them with env in its main context. Without those lines, the workers can't see the variables and open data/my_api.db in local mode.
  • The rule holds generally: anything that prepares statements belongs in a store builder or in init_worker_by_lua beside the connection.
  • Statements are prepared when the closure is constructed and finalized when their connection closes. A statement prepared in the master is dead by the time the workers exist. The first request then fails with nothing in the log to explain it.
  • That covers the create of santoku.sqlite.sync and of santoku.sqlite.fts as much as the scaffold's own getters.
  • The items.lua excerpt omits the requires of cjson as json and my_api.web.status as status, and the decode of the request body into req.

Secrets in init_by_lua

Read each secret once in init_by_lua with env.var and publish it through package.loaded. The master's init_by_lua sees every variable, and the workers inherit package.loaded from it.

server/lib/my_api/config.lua
local env = require("santoku.env")
return function ()
  return {
    host = env.var("MYSQL_HOST", "127.0.0.1"),
    user = env.var("MYSQL_USER"),
    password = env.var("MYSQL_PASSWORD"),
    database = env.var("MYSQL_DATABASE"),
  }
end
server/lib/my_api/web/init.lua
package.loaded["my_api.config.loaded"] = require("my_api.config")()
server/lib/my_api/web/items.lua
local config = require("my_api.config.loaded")
res/server/nginx.mustache (main context)
env STRIPE_KEY;
Illustrative: runs outside the browser.
Details
  • A database password or an API key reaches the server as an environment variable.
  • The scaffold's DB_FILE isn't a secret and takes the other route. Every process reads it with env.var, and the env DB_FILE line in nginx.mustache passes it to the workers.
  • With no default, env.var raises Missing environment variable: NAME, so a missing secret stops the server at startup.
  • nginx clears the environment of its workers. In init_worker or a handler, env.var sees only the variables that nginx.conf names with env NAME; in its main context.
  • Never read a secret in make.lua or a .tk.lua. Both run at build time, the rendered file lands in the build tree, and santoku-make writes the resolved descriptor to build/<env>/config.stamp.
  • For toku test, export the variables in the shell that runs it, and the test server inherits them.
  • init.lua runs in the master and items.lua in a worker.
  • The env line in nginx.mustache is needed only for a variable that a worker reads itself.

Secrets in production

Keep each secret in the platform's store, SSM Parameter Store as a SecureString or Secrets Manager. At service start, a step under the instance's role fetches them into a 0600 env file for podman run --env-file.

/usr/local/bin/my-api-env
#!/bin/sh
set -eu
umask 077
aws ssm get-parameters-by-path --path /my-api/prod/ --with-decryption \
  --query 'Parameters[].[Name,Value]' --output text |
  while IFS="$(printf '\t')" read -r name value; do
    printf '%s=%s\n' "${name##*/}" "$value"
  done > /run/my-api/env.tmp
mv /run/my-api/env.tmp /run/my-api/env
/etc/systemd/system/my-api.service
[Service]
RuntimeDirectory=my-api
RuntimeDirectoryMode=0700
ExecStartPre=/usr/local/bin/my-api-env
ExecStart=/usr/bin/podman run --rm --name my-api --env-file /run/my-api/env -p 8080:8080 my-api
Illustrative: runs outside the browser.
Details
  • podman run --env-file hands the variables in that file to the container.
  • Scope the role to the service's own parameter path.
  • A host with no cloud role keeps a root-owned 0600 env file instead.
  • Don't encrypt the env file, since its key would sit on the same host.
  • The env file format has no quoting, so a value can't hold a newline.

Add an endpoint

A handler is a module under server/lib that returns a function. To add an endpoint, write the module and add a location whose content_by_lua_block requires it and calls the function.

make.lua (nginx block)
nginx = {
  domain = env.var("DOMAIN", "localhost"),
  workers = env.var("WORKERS", "auto"),
},
server/nginx.tk.conf
<%
  return require("santoku.mustache")(readfile("res/server/nginx.mustache"))({
    nginx = nginx.nginx,
    openresty_dir = openresty_dir,
    lua_package_path = lua_package_path,
    lua_package_cpath = lua_package_cpath,
  })
%>
res/server/nginx.mustache (the init blocks and the /items location)
init_by_lua_block { require("my_api.web.init") }
init_worker_by_lua_block { require("my_api.web.init_worker") }

server {

  listen {{{nginx.port}}};
  server_name {{{nginx.domain}}};

  location = /items {
    limit_except GET POST { deny all; }
    content_by_lua_block { require("my_api.web.items")() }
  }

}
Illustrative: runs outside the browser.
Details
  • require loads the module once per worker, and the block calls the returned function on each request. Code at the module's top level runs once.
  • init and init_worker are plain modules. Their blocks require them once, and nothing calls a returned value.
  • The descriptor and server/nginx.tk.conf declare nothing for a handler.
  • Since santoku-make 9.1.0, the build reads every require("name") in each *_by_lua_block of the rendered conf. A name that resolves to no module on the conf's lua_package_path fails the build and names the module and the conf.
  • A typo then surfaces at build time instead of as a 500.
  • The engine also checks every by_lua_file directive in the rendered conf against the server dist. An empty or wrong path fails the build and names the directive.
  • The template uses triple braces, since double braces escape &, <, > and " for HTML.
  • A tag whose key the context lacks renders empty.
  • In nginx.tk.conf, nginx is the render context, with lua_package_path and the like. nginx.nginx is your descriptor's nginx block merged with the daemon, pid and log settings, and the scaffold hands it to the template as nginx.
  • Templates under server/lib see only client, server, nginx, name and version from the descriptor, and there nginx is the plain descriptor block.
  • So keep app settings under env.server (server.rate.limit), and read them from a .tk.lua module that both handlers and specs require.
  • A block returns a string or nothing, so write ports and limits as strings or wrap them in tostring.

Path parameters and 404

nginx does the routing: a regex location captures the id, and the handler reads it as ngx.var[1]. A nil from a getter becomes a 404.

res/server/nginx.mustache (server block)
location ~ ^/items/(\d+)$ {
  limit_except GET DELETE { deny all; }
  content_by_lua_block { require("my_api.web.item")() }
}
server/lib/my_api/store.lua (read and write entries of the builder)
read = {
  get_item = db.getter("select json_object('id', id, 'name', name) from items where id = ?1"),
},
write = {
  delete_item = db.getter("delete from items where id = ?1 returning id"),
},
server/lib/my_api/web/item.lua
local db = require("my_api.web.db")
local status = require("my_api.web.status")
local json = require("cjson")
return function ()
  local id = tonumber(ngx.var[1])
  ngx.header.content_type = "application/json"
  if ngx.req.get_method() == "DELETE" then
    local gone, e = db.delete_item(id)
    if e then
      ngx.status = status(gone, e)
      ngx.say(json.encode({ status = e }))
      return ngx.exit(ngx.status)
    elseif not gone then
      ngx.status = 404
      ngx.say(json.encode({ error = "not_found" }))
      return ngx.exit(404)
    end
    return ngx.exit(204)
  end
  local item = db.get_item(id)
  if not item then
    ngx.status = 404
    ngx.say(json.encode({ error = "not_found" }))
    return ngx.exit(404)
  end
  ngx.say(item)
end
Illustrative: runs outside the browser.
Details
  • A path the regex rejects, such as /items/abc, never reaches Lua and gets nginx's own 404.
  • For a row that doesn't exist, a getter returns nil. A getter over delete ... returning id does the same when nothing was deleted, so each nil becomes a 404.
  • A write that fails returns nil and a status as well, so the handler checks the status first and hands it to status.lua.
  • Set ngx.status before the body and end with ngx.exit.

Shared state across workers

A lua_shared_dict declared in the http block reaches every worker as ngx.shared.<name>. Use it for counters, rate limits and small caches, since each worker has its own Lua state and a module-level table is per worker.

res/server/nginx.mustache (http block)
lua_shared_dict hits 1m;
server/lib/my_api/web/hits.lua
local json = require("cjson")
return function ()
  local n = ngx.shared.hits:incr(ngx.var.remote_addr, 1, 0, 60)
  ngx.header.content_type = "application/json"
  if n > 3 then
    ngx.status = 429
    ngx.say(json.encode({ error = "rate_limited" }))
    return ngx.exit(429)
  end
  ngx.say(json.encode({ count = n }))
end
Illustrative: runs outside the browser.
Details
  • incr(key, by, init, ttl) is atomic across workers. When the key is missing, incr creates it with init and an expiry in seconds, so a fixed-window rate limit is one line.
  • The size caps the dict's memory. When it fills, set and incr evict the least recently used keys.
  • hits.lua allows at most 3 requests per address per minute.

Brotli and gzip

The api and web scaffolds turn on brotli and gzip in the http block of res/server/nginx.mustache. A browser that sends Accept-Encoding: br gets brotli, and any other client gets gzip.

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml text/javascript application/json
  application/javascript application/xml application/wasm image/svg+xml;

brotli on;
brotli_comp_level 6;
brotli_min_length 1000;
brotli_types text/plain text/css text/xml text/javascript application/json
  application/javascript application/xml application/wasm image/svg+xml;
Illustrative: runs outside the browser.
Details
  • The managed OpenResty has ngx_brotli compiled in, so the brotli directives need no load_module line.
  • application/wasm is in both type lists, since a wasm bundle is usually the largest file a page loads.
  • Both compress each response on the fly at level 6.
  • If nginx stops with unknown directive "brotli", the managed OpenResty predates ngx_brotli. Rerun setup-toku.sh from https://santoku.dev/install, and it rebuilds OpenResty.

Headers and rate limits

A handler reads a request header as ngx.var.http_<name>, so X-Api-Key is ngx.var.http_x_api_key. resty.limit.count, from the lua-resty-limit-traffic that the managed OpenResty ships, rate-limits by key.

res/server/nginx.mustache (http block)
lua_shared_dict per_key 1m;
server/lib/my_api/web/limited.lua
local json = require("cjson")
local limit_count = require("resty.limit.count")
return function ()
  ngx.header.content_type = "application/json"
  local key = ngx.var.http_x_api_key
  if not key then
    ngx.status = 401
    ngx.say(json.encode({ error = "missing_key" }))
    return ngx.exit(401)
  end
  local lim = limit_count.new("per_key", 3, 10)
  local delay, left = lim:incoming(key, true)
  if not delay then
    ngx.status = left == "rejected" and 429 or 500
    ngx.say(json.encode({ error = left }))
    return ngx.exit(ngx.status)
  end
  ngx.say(json.encode({ left = left }))
end
Illustrative: runs outside the browser.
Details
  • The name is lowercase, with dashes turned to underscores.
  • A missing header reads as nil.
  • ngx.req.get_headers() returns all headers, keyed by lowercase name.
  • resty.limit.count is a fixed window over a lua_shared_dict. Call new(dict, limit, window_seconds), then incoming(key, true).
  • incoming returns 0 and the requests left, or nil and "rejected" once the key passes the limit.
  • resty.limit.req is a leaky bucket for a rate per second plus a burst.
  • resty.limit.conn caps concurrent requests.
  • limited.lua allows at most 3 requests per key per 10 seconds.

Multipart file uploads

resty.upload, which OpenResty ships, streams a multipart/form-data body in chunks. A large file never sits whole in memory unless you collect it.

local upload = require("resty.upload")
local json = require("cjson")
local str = require("santoku.string")
local arr = require("santoku.array")
return function ()
  local form, e = upload:new(8192)
  ngx.header.content_type = "application/json"
  if not form then
    ngx.status = 400
    ngx.say(json.encode({ error = e }))
    return ngx.exit(400)
  end
  form:set_timeout(5000)
  local files, name, chunks = {}, nil, nil
  while true do
    local typ, res, re = form:read()
    if not typ then
      ngx.status = 400
      ngx.say(json.encode({ error = re }))
      return ngx.exit(400)
    end
    if typ == "header" and str.lower(res[1]) == "content-disposition" then
      name = str.match(res[2], 'filename="([^"]*)"')
      chunks = {}
    elseif typ == "body" and chunks then
      arr.push(chunks, res)
    elseif typ == "part_end" and chunks then
      if name then
        arr.push(files, { name = name, size = #arr.concat(chunks) })
      end
      name, chunks = nil, nil
    elseif typ == "eof" then
      break
    end
  end
  ngx.say(json.encode({ files = files }))
end
Illustrative: runs outside the browser.
Details
  • read() returns a type and a value: "header" with a { name, value } pair, "body" with a chunk, "part_end" after each part, and "eof" at the end.
  • The filename comes from the Content-Disposition header.
  • To accept bigger files, raise client_max_body_size in the http block above the scaffold's 1m.
  • The code is server/lib/my_api/web/upload.lua, behind location = /upload.

The per-worker pragmas

santoku.resty.sqlite sets the pragmas on each connection before anything else touches it. Apart from WAL, none persist in the file, so they apply per connection, which here means per worker.

santoku.resty.sqlite, on a request connection
db.exec("pragma busy_timeout = 5000")
db.exec("pragma journal_mode = WAL")
db.exec("pragma synchronous = NORMAL")
db.exec("pragma wal_autocheckpoint = 0")
server/lib/my_api/store.lua (top of the builder, for foreign keys)
db.exec("pragma foreign_keys = ON")
Illustrative: runs outside the browser.
Details
  • WAL lets readers run while a writer holds the database, and WAL persists in the file.
  • SQLite answers the switch to WAL with SQLITE_BUSY, without a call to the busy handler, when another worker holds the write lock. So every open retries it every 5 ms until busy_timeout runs out.
  • synchronous NORMAL is the setting WAL is designed around.
  • busy_timeout covers the boot window where every worker opens a write transaction at once. It's 30000 ms on the setup connection that migrates, and 5000 ms on the rest.
  • The automatic checkpoint is off on every connection, since the privileged agent checkpoints.
  • In single mode the readers add query_only.
  • cache_size stays at SQLite's default of 2 MB.
  • foreign_keys is off by default in SQLite. A schema with foreign keys turns it on at the top of its store builder, since the builder runs once per connection.
  • Pragmas you add also apply per connection, which here means per worker.
  • Anything sized in bytes is paid once per worker, so the real cost is the value multiplied by worker_processes.
  • worker_processes defaults to auto, which resolves to the core count of whatever machine you deploy on.
  • A cache_size you set costs memory that way, so multiply before you decide the number is affordable. A 64 MiB cache_size across 16 workers reserves 1 GiB of page cache before nginx, LuaJIT or SQLite's own structures are counted.
  • On a memory-limited deploy, pin worker_processes to a number you chose instead of auto.

Separate files for request logs

Write a query log, telemetry or audit rows into their own database file, on their own connection. In a file that a batch job also writes, they wait behind its transaction, and so does every request on that worker.

local err = require("santoku.error")
local db_mod = require("santoku.sqlite.db")
local sqlite = require("santoku.sqlite")
local insert

local function open (file)
  if not insert then
    local db = sqlite(err.assert(db_mod.open(file)))
    db.exec("pragma busy_timeout = 30000")
    db.exec("pragma journal_mode = WAL")
    db.exec("pragma synchronous = NORMAL")
    db.exec([=[
      create table if not exists query_log (
        id integer primary key,
        stamp text not null,
        type text not null,
        data text)
    ]=])
    insert = db.inserter("insert into query_log (stamp, type, data) values (?1, ?2, ?3)")
  end
  return insert
end

return function (file)
  return {
    write = function (type, data)
      open(file)(ngx.utctime(), type, data)
    end,
  }
end
Illustrative: runs outside the browser.
Details
  • SQLite has one writer per file. An insert on the main connection waits behind whatever transaction a rebuild or import holds.
  • An nginx worker is single-threaded, so every request on that worker waits with the insert.
  • Measured on one box: a 16-core desktop and toku's PUC Lua 5.1. One process ran 3,000 serial searches against a 100k-row FTS corpus, and a second process looped 5,000-row rebuild transactions.
Where the log insert goesResult
the main databasep99 went from 100 ms to 3.2 s, and one write waited 25.4 s
a separate file on its own connection, WAL and synchronous NORMALp99 within 2% of no logging
  • ATTACH is no escape. The attached file shares the main connection's lock, and it was slower even with no other writer.
  • Not measured: LuaJIT inside nginx, several workers that write the log at once, and slower disks. Treat the numbers as the direction and measure your own.
  • Open the log connection lazily inside the worker, on first use, so no SQLite handle crosses the master's fork.
  • The code is server/lib/my_api/log.lua.
  • Never put the same insert on the main db's connection, or behind db.exec("attach 'log.db' as log"). Both put the request behind the batch writer's lock.

The scaffold's specs

server/test/spec/my_api.lua tests the store over an in-memory database with no server, then the API over HTTP against the test server. server/test/spec/status.lua checks the HTTP status of each write status.

local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local str = require("santoku.string")
local sqlite_db = require("santoku.sqlite.db")
local sqlite = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local http = require("santoku.http")(require("santoku.socket"))

test("the store, no server", function ()
  local db = sqlite(err.assert(sqlite_db.open_memory()))
  migrate(db, require("my_api.migrations"))
  local items = db.store(require("my_api.store"))
  err.assert(err.checkok(items.create_item("first")) == 1, "first rowid is 1")
  err.assert(str.find(items.list_items(10), "\"first\"", 1, true), "created row listed")
  db.close()
end)

test("items endpoint", function ()
  local url = "http://127.0.0.1:" .. env.var("PORT") .. "/items"
  local ok, resp = http.post(url, {
    headers = { ["content-type"] = "application/json" },
    body = "{\"name\":\"from the spec\"}",
  })
  err.assert(ok and str.find(resp.body(), "\"id\""), "create failed", resp.status)
  ok, resp = http.get(url)
  err.assert(ok and str.find(resp.body(), "from the spec", 1, true), "posted row listed", resp.status)
  ok, resp = http.post(url, { body = "{}" })
  err.assert(not ok and resp.status == 400, "a body without a name is rejected", resp.status)
end)
Illustrative: runs outside the browser.
Details
  • The store test opens an in-memory database, migrates it with my_api.migrations and flattens the my_api.store builder over it with db.store.
  • That's the same wrapping santoku.resty.sqlite gives the builder in local mode, so the test checks the SQL with no server at all.
  • server/test/spec/status.lua checks the mapping in status.lua, also with no server.
  • The HTTP test talks to the test server through santoku.http over santoku.socket, and the port arrives in the PORT environment variable.
  • make.lua lists santoku-http and santoku-socket under server.test.dependencies.
  • The HTTP test creates a row, lists it back, and checks that a body with no name gets 400.
  • A spec can require cjson to decode a response, with no entry in that list. Server specs run under OpenResty's LuaJIT with OpenResty's lualib on the path.
  • Specs run with build/default/test/server as the working directory. nginx runs with build/default/test/run as its prefix (ngx.config.prefix()), so relative paths in a spec and in a handler point at different trees.
  • Besides PATH, LUA_PATH and LUA_CPATH, a spec gets the test server's port, 8081, as PORT.
  • A spec also gets DIST_DIR, the absolute path of build/default/dist. RUN_DIR is the absolute path of build/default/test/run, the directory the test server runs in. A spec can then read the dist and the running server's files without a relative path.
  • RUN_DIR holds links to the dist's lua_modules and public. It also holds the test server's own nginx.conf, data, logs and pid file.
  • Nothing else from the descriptor arrives. Keep a value both sides need in a .tk.lua module under server/lib, and require it from the spec.
  • The template runs at build time, so a rock it requires goes in build.dependencies. santoku-jwt, to make a signing key both sides share, is one such rock.
  • Every build tree then renders the same value. The build.dependencies card on https://santoku.dev/santoku-make covers that list.

Verify the project

Run the commands below against the finished project and compare the output. toku test then runs the specs against a fresh test server that it starts and stops itself.

$ toku build
$ toku start

$ curl -s -X POST http://127.0.0.1:8080/items \
    -H 'content-type: application/json' -d '{"name":"first"}'
{"id":1}

$ curl -s http://127.0.0.1:8080/items
{"items":[{"id":1,"name":"first","created_at":1756772183.412}]}

$ curl -si -X POST http://127.0.0.1:8080/items -d 'not json' | head -1
HTTP/1.1 400 Bad Request

$ toku stop

$ toku test
Illustrative: runs outside the browser.
Details
  • The build renders the templates and installs the server tree, and start runs OpenResty against it.
  • The first curl creates a row and returns its id. The second lists it back, with created_at set to whatever timestamp SQLite assigned. The third shows that validation rejects a bad body with a 400.
  • Plain toku test builds, starts the test server, runs both tests above and status.lua, and stops the server, on success or failure.
  • toku test server selects only the server specs. This project has no client or root specs, so it runs the same specs.
  • A server that exits during startup fails the run at once with its error log lines.
  • If any step differs, the nginx error log under the build tree holds the failure.
  • error.log, access.log and run.log in build/default/test/run/logs append across runs. A trace from an earlier run can sit at the tail of a passing run's log. Count the lines before a run and read only the new ones, or delete the three files first.
  • A pass prints a luacheck summary with 0 errors after both spec halves print nothing, and exits 0.
  • The access log under build/default/test/run/logs shows the spec's POST and GET, which proves that the HTTP half ran.
  • toku start serves on 8080, which the curl lines use, and the test server on 8081.
  • The spec receives the test port through PORT. PORT, DIST_DIR and RUN_DIR are the only variables the test runner sets.
  • Each server keeps its database in its own data directory, which run.sh creates. The test server writes build/default/test/run/data/my_api.db, and toku start's server writes build/default/dist/data/my_api.db. Spec rows never show up in the server you try by hand.
  • Both databases persist across runs, and migrations already applied there are skipped. Add a new migration file, or delete build/default/test/run/data/my_api.db* to start the specs from an empty database.