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 library

scaffold, build, test and publish a Lua rock with toku, from toku init to the luarocks upload

This tab is the shortest path from nothing to a published Lua rock. Work through it in order: toolchain, scaffold, the development loop, then publishing. The example project is my-lib, and toku init puts your own name everywhere, file contents and directory names included.

Details
  • Everything here assumes toku is installed and its one-time toku setup has run. setup-toku.sh on https://santoku.dev/install does both, and toku doctor confirms it.
  • Get the rest of the toolchain one of two ways. Install it on your machine, or run toku from the container image that santoku-make ships, with your code mounted in.
  • The first cards cover both ways, and everything after them is the same either way.

Install the toolchain

A library project needs far less than a web one: no wasm toolchain, no OpenResty and no node. Put the tools below on PATH.

toku setup        mandatory, once; done by setup-toku.sh (the Install tab)
luarocks          invoked by toku; the managed toolchain ships its own
cc and make       compile the C sources in the rock and in its dependencies
git               toku init runs git init; toku release tags and pushes
gh                when env.release hosts on GitHub (release.gh_release, the scaffold's default):
                  authenticate it first with gh auth login. release.s3_upload
                  needs curl and AWS_* variables instead
luacheck          toku test's check stage stops without it unless --skip-check;
                  setup-toku.sh installs it into the managed tree
Illustrative: runs outside the browser.
Details
  • The first line is the mandatory one-time step, and setup-toku.sh from https://santoku.dev/install already ran it.
  • The build fails at the first tool it can't find, and the error comes from that tool instead of from toku.

Run toku in a container

setup-toku.sh --container builds the toku-lib and toku-web images that santoku-make ships, and installs the toku-lib and toku-web commands. toku-lib runs toku in its image with the current directory mounted at the same path.

Shell
$ curl -fsSL https://santoku.dev/setup-toku.sh | sh -s -- --container
$ export PATH="$HOME/.local/share/toku/rocks/bin:$PATH"
$ toku-lib test
$ toku-lib test --iterate
$ toku-lib -- install --bundled --prefix "$PWD/out"
$ curl -fsSL https://santoku.dev/setup-toku.sh | sh -s -- --check --container
Shell, by hand
$ for f in toku-lib.dockerfile toku-container.sh toku-lib.sh; do
>   curl -fsSLO https://releases.santoku.dev/santoku-make/13.1.0-1/$f
> done
$ chmod +x toku-container.sh toku-lib.sh
$ docker build -t toku-lib -f toku-lib.dockerfile .

$ ./toku-lib.sh -- test
$ ./toku-lib.sh -- test --iterate
$ ./toku-lib.sh -- install --bundled --prefix "$PWD/out"
$ ./toku-lib.sh -- pack
toku-lib.sh flags
-c podman | -c docker   force a runtime, otherwise podman then docker
-g <flag>               global runtime flag ahead of run (or set TOKU_CONTAINER_GLOBAL)
-n                      print the command it would run, and exit
-u "$(id -u):$(id -g)"  passed through; docker only, keeps output yours
-i <image>              override the image name (or set TOKU_IMAGE)
Illustrative: runs outside the browser.
Details
  • --container needs only podman or docker: no compiler, BLAS or other host tools. It picks podman when podman is on PATH, else docker.
  • It fetches toku-container.sh, toku-lib.sh, toku-web.sh, toku-lib.dockerfile and toku-web.dockerfile for santoku-make 13.1.0-1 from https://releases.santoku.dev/santoku-make/13.1.0-1/ into $XDG_DATA_HOME/toku/container/13.1.0-1.
  • It builds both images, links toku-lib and toku-web into $XDG_DATA_HOME/toku/rocks/bin, the native install's bin directory, and prints the PATH line.
  • A rerun skips an image whose dev.santoku.make label names that santoku-make, and rebuilds one whose label doesn't. So a newer setup-toku.sh rebuilds the images. --rebuild rebuilds them anyway.
  • --check --container checks that both images carry that santoku-make and both commands link to its wrappers. It changes nothing.
  • The wrapper keeps toku's download and built-rock caches in a named volume per image and santoku-make version, such as toku-web-cache-<version>, mounted at /opt/toku/cache. A second run reuses the rocks the first built.
  • Your code stays on your machine. Only the tooling lives in the container, so the build tree lands in your working directory as it would locally.
  • To set up by hand, download the dockerfile and wrappers for your santoku-make version from https://releases.santoku.dev/santoku-make/<version>/. Build the image once, then use the wrapper anywhere you would type toku.
  • toku-lib.sh and toku-web.sh are one-line shims over a shared toku-container.sh that sits beside them. Download all three and mark the scripts executable.
  • Everything after the double dash goes to toku, and anything before it goes to the container runtime.
  • The wrapper's own flags go before the double dash and ahead of any runtime flags.
  • Podman keeps file ownership yours automatically. Docker doesn't, so pass -u if root-owned build output would bother you.
  • toku-lib is the image for library projects. A project with a client directory wants toku-web, the same wrapper over a much larger image: https://santoku.dev/start-web#start-web--run-toku-in-a-container
  • toku-lib has no wasm toolchain, so run toku test --wasm and other wasm builds in toku-web. Since santoku-make 7.11.1, toku-lib stops a wasm build with an error that names toku-web, in place of Permission denied: /opt/toku/wasm.
  • Plain toku install has nothing to install into. The container is --rm, and under podman you run as your own uid against a root-owned rocks tree, so the install fails on permissions. Bundle to the mounted directory instead.
  • The image provisions toku with the same setup-toku.sh as a native install, and the wrapper runs the container with --init.
  • toku test --iterate runs in the container as it does natively.

The toku-lib-deployment image

toku-lib-deployment is a runtime base image for the executable that toku install --bundled builds. It's debian:bookworm-slim plus liblua5.1-0 and ca-certificates, with a non-root system user worker and WORKDIR /app.

Shell
$ docker build -t toku-lib-deployment -f toku-lib-deployment.dockerfile .
Dockerfile
FROM toku-lib AS builder
WORKDIR /app
COPY . .
RUN toku install --bundled --prefix /usr/local

FROM toku-lib-deployment
COPY --from=builder /usr/local/bin/mytool /usr/local/bin/mytool
USER worker
ENTRYPOINT ["mytool"]
Illustrative: runs outside the browser.
Details
  • toku-lib is a build image and carries a toolchain that no library needs at runtime.
  • A library project has no long-running process. The deployable artifact is the bundled executable.
  • Lua links statically, so the executable's dynamic dependencies reduce to libc, libm and the system libraries your dependencies link.
  • Download toku-lib-deployment.dockerfile from the same releases.santoku.dev directory and build it there.
  • apt works, but the package lists are stripped. A downstream layer that adds native libraries must run apt-get update first and remove the lists again afterwards.

Scaffold a library project

toku init creates a complete, already-working rock: a Lua module, a C extension, an executable, a spec and SQL migrations. The directory layout carries the build conventions.

$ toku init my-lib
Initialized empty Git repository in /home/you/my-lib/.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-lib from the lib example: A library with a command

Next steps:
  cd my-lib
  toku test     # Run tests
  toku install  # Install locally

$ find my-lib -type f -not -path "*/.git/*" | sort
my-lib/.gitignore
my-lib/bin/my-lib.lua
my-lib/lib/my_lib.lua
my-lib/lib/my_lib/capi.c
my-lib/lib/my_lib/migrations.tk.lua
my-lib/lib/my_lib/store.lua
my-lib/make.lua
my-lib/res/lib/migrations/0.0.1.sql
my-lib/test/spec/my_lib.lua
Illustrative: runs outside the browser.
Details
  • C files under lib compile as Lua modules with no configuration.
  • bin files become executables, and toku install --bundled compiles them to single native binaries.
  • res files install with the rock and are readable at runtime.
  • 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. The rock and the executable keep the hyphen. The Lua module and the C entry point use underscores, because luaopen_my-lib_capi isn't a valid C identifier. So my-lib publishes as the rock my-lib and is required as my_lib.
  • --here scaffolds into the current directory and takes its name. The directory must be empty, so fetch notes or docs somewhere else first. toku init rejects --here beside a project name.
  • The C extension includes santoku/lua/utils.h, which rock.include("santoku") in the cflags of make.lua puts on the include path. lua.h and lauxlib.h need no flag.
  • The executable parses its arguments with argparse, an upstream rock documented at https://argparse.readthedocs.io.
  • lib/my_lib/store.lua is a store builder. It returns a read table (list, get) and a write table (add, delete, update).
  • lib/my_lib.lua opens the database and applies the migrations with require("santoku.migrate"). It returns db.store(store), which runs each write in a transaction, and the connection.
  • lib/my_lib/migrations.tk.lua is the template that the web and api scaffolds use. It reads res/<component>/migrations at build time, and component is "lib" in a lib project.
  • make.lua pins santoku-sqlite >= 9.0.0, < 10.0.0 and santoku-migrate >= 0.1.3, < 0.2.0.
  • A rock without a database deletes res/lib, lib/my_lib/migrations.tk.lua and lib/my_lib/store.lua. It rewrites lib/my_lib.lua and drops santoku-sqlite and santoku-migrate from the dependencies in make.lua.
  • bin/my-lib.lua and test/spec/my_lib.lua both require my_lib, so rewrite both. lib/my_lib/capi.c has no caller once store.lua is gone.
  • santoku-fs sits in the test dependencies only, so move it up if the rock itself reads files.

The dev loop

toku test --iterate builds the rock, runs the specs and luacheck, then reruns them when a file the rock ships changes. Leave it running in one pane and edit in another.

$ toku test --iterate

$ toku test
$ toku test test/spec/my_lib.lua
$ toku test test/spec -s
$ toku test --resty
$ toku install
$ toku run lua -e 'print(require("my_lib"))'
$ toku run my-lib --help
$ eval "$(toku env)"
Illustrative: runs outside the browser.
Details
  • It's the expected day-to-day loop for a library, and santoku's own repos use it. Run it against the fresh scaffold before you change anything.
  • --show-logs is the web-project addition and doesn't apply to libraries. Passing it here is an error instead of a silent no-op.
  • Every file under lib, bin and res ships in the rock, so an edit there reruns the specs.
  • An edit to a root file that the rock doesn't ship, such as NOTES.md, prints iterate nothing reads NOTES.md, so nothing reruns. No spec runs.
  • A change to make.lua, or a file created or deleted under lib, bin, test or res, reloads the project before the next run. A new module or spec joins without a restart.
  • Since santoku-make 10.2.0, the loop also watches each local_deps entry's lib, bin, deps and res directories and its make.lua and make.common.lua, and reloads the project when the descriptor's values change.
  • Since santoku-make 10.2.0, toku test --iterate records its pid in build/<env>/toku.pid. A toku build, test or second loop in that build tree stops at once with "<command> (pid N) already loops in <dir>". Stop the loop, or run the command in another checkout.
  • Underneath, toku test renders sources into build/default/test and luarocks-makes them into a private lua_modules there. Then it runs the specs, then luacheck.
  • Without luacheck on PATH, the check stage stops with exit 1 and names the fix, unless you pass --skip-check.
  • toku test discovers spec files recursively under test/spec and runs each in its own interpreter process.
  • toku test PATH runs the specs at or under a project path, ^PATH leaves them out, -s stops at the first failure, and --resty runs the specs under OpenResty's resty CLI.
  • The test tree is a real installed rock, so specs run against the installed layout instead of your source tree.
  • Specs run with build/default/test as the working directory, and test/res is copied there. Keep fixtures in test/res and open them as test/res/<file>.
  • The rock's bin scripts install to build/default/test/lua_modules/bin, which a spec reaches as lua_modules/bin/<name>.
  • toku install builds the shippable tree and installs it into your active rocks tree.
  • toku lua runs toku's own Lua 5.1 with toku's rocks tree ahead of any LUA_PATH and LUA_CPATH you set. That tree is $XDG_DATA_HOME/toku/rocks (~/.local/share/toku/rocks by default), where toku install puts things. So toku lua sees installed rocks but never the project you're in.
  • toku run runs a command against the project's test tree instead: lua as the tree's interpreter, or a bin script by name. toku env prints the PATH, LUA_PATH and LUA_CPATH exports for that tree.

User-facing errors from C

tk_lua_verror, tk_lua_error and tk_error from santoku/lua/utils.h raise through santoku.error with no source position. Use them when a CLI prints the error, since luaL_error prefixes a build path.

#include <santoku/lua/utils.h>

static int lines (lua_State *L)
{
  const char *path = luaL_checkstring(L, 1);
  FILE *fh = fopen(path, "r");
  if (!fh)
    return tk_lua_verror(L, 2, path, strerror(errno));
  lua_Integer n = 0;
  int c;
  while ((c = fgetc(fh)) != EOF)
    if (c == '\n')
      n ++;
  fclose(fh);
  lua_pushinteger(L, n);
  return 1;
}

static luaL_Reg fns[] = {
  { "lines", lines },
  { NULL, NULL }
};

int luaopen_my_lib_count (lua_State *L)
{
  lua_newtable(L);
  luaL_register(L, NULL, fns);
  return 1;
}
Illustrative: runs outside the browser.
Details
  • luaL_error prefixes the message with the Lua line that called the C function. A CLI that prints the error then shows a build path such as .../lua_modules/share/lua/5.1/my_lib.lua:8:.
  • tk_lua_verror(L, n, ...) takes n strings, tk_lua_error(L, msg) takes one, and tk_error(L, label, err) adds strerror(err).
  • err.pcall returns each string as its own value. Uncaught, or under plain pcall, the strings join with ": ".
  • The header needs rock.include("santoku") in cflags, as the scaffold's make.lua has.
  • The file below is lib/my_lib/count.c.
  • In Lua, err.pcall(count.lines, "missing.txt") returns false, missing.txt and No such file or directory. An uncaught call raises "missing.txt: No such file or directory".
  • With luaL_error(L, "%s: %s", ...), the same call raises ".../my_lib.lua:8: missing.txt: ...".

Publish with toku release

The scaffolded env.release makes toku release tag the commit, push it to git, create a GitHub release with the tarball and upload the rockspec to luarocks. Set homepage first, the one edit the scaffold needs.

make.lua (env.release, as toku init scaffolds it)
local release = require("santoku.make.release")
env.homepage = "https://YOUR-HOMEPAGE.example/" .. env.name
env.release = {
  push = release.git_push(),
  host = release.gh_release(),
  registry = release.luarocks_upload(),
}
make.lua (env.release, hosted on S3)
env.homepage = "https://example.com/#" .. env.name
env.release = {
  push = release.git_push(),
  host = release.s3_upload({ bucket = "my-releases", base_url = "https://releases.example.com" }),
  registry = release.luarocks_upload(),
}
Shell
$ toku pack
$ toku release
What toku release runs
git status --porcelain
luarocks search --porcelain --only-server=https://luarocks.org --all
git tag 0.0.1-1
git push origin HEAD
git push origin refs/tags/0.0.1-1
gh release create --generate-notes 0.0.1-1 my-lib-0.0.1-1.tar.gz my-lib-0.0.1-1.rockspec
luarocks upload --skip-pack --api-key "$LUAROCKS_API_KEY" my-lib-0.0.1-1.rockspec
curl https://luarocks.org/my-lib-0.0.1-1.rockspec
Illustrative: runs outside the browser.
Details
  • luarocks installs fetch the tarball from the source url in the rockspec. gh_release points that url at the GitHub release, and takes the repo from the origin remote or opts.repo.
  • The env.release table registers the release target. Without it, toku release errors out.
  • Set homepage to your project's page. release refuses to run while homepage still holds the YOUR-HOMEPAGE placeholder.
  • To host the tarball elsewhere, swap the host hook for release.s3_upload. The source url then derives from its base_url, name and version, so the source url in the rockspec points at the bucket.
  • release runs test and check for every test profile the rock declares, then pack. It refuses to continue on a tree with uncommitted or untracked files.
  • release checks that every rockspec dependency has a version on luarocks.org that meets its constraint. When one doesn't, it stops with the list, so release dependencies first.
  • It then tags and runs the hooks in order: artifacts (when declared), push, host, registry.
  • After the upload, luarocks_upload polls the rockspec url and luarocks search until the version is public, and fails when it never appears.
  • Credentials come from environment variables, and no flag takes them. LUAROCKS_API_KEY must be set, and a host needs its own: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for s3_upload.
  • A failure names the phases that already ran. toku release removes the local tag only when none did, so you can fix the cause and rerun.
  • toku pack builds the tarball only and publishes nothing.
  • toku release runs the commands below in order. First come the clean-tree check, the dependency preflight, and the tag, reused if it already points at HEAD. Then come the push, host and registry phases. Last, it polls the rockspec url until it answers 200, then luarocks search.

Environment variables the harness reads

santoku-make, santoku-cli and santoku-bundle read the environment variables below, apart from PATH, LUA_PATH and LUA_CPATH. They supply release credentials and override tool locations and defaults.

LUAROCKS_API_KEY        release.luarocks_upload; no CLI flag exists for it
AWS_ACCESS_KEY_ID       release.s3_upload
AWS_SECRET_ACCESS_KEY   release.s3_upload
AWS_SESSION_TOKEN       release.s3_upload
AWS_REGION              release.s3_upload, default us-east-1
OPENRESTY_DIR           web projects: OpenResty override; default the managed one, if installed
CC                      C compiler for native builds and bundling (default: cc)
PREFIX                  install prefix for toku install --bundled, unless --prefix
HOME                    fallback prefix root ($HOME/.local) when PREFIX is unset
XDG_DATA_HOME           managed tree at $XDG_DATA_HOME/toku (default ~/.local/share/toku)
TOKU_WASM_DIR           wasm toolchain directory (default $XDG_DATA_HOME/toku/wasm)
TOKU_CACHE              local rock server ahead of luarocks.org (default the managed cache)
TOKU_FG                 toku start in the foreground, unless empty or 0
TOKU_TRACE              print the full Lua traceback when a command fails
Illustrative: runs outside the browser.
Details
  • release.luarocks_upload needs LUAROCKS_API_KEY, which has no command line equivalent.
  • release.s3_upload reads the AWS credential variables and AWS_REGION.
  • OPENRESTY_DIR overrides which OpenResty web projects build against and run their server specs under. Unset, santoku-make uses the managed one that toku setup --resty installs under $XDG_DATA_HOME/toku/openresty (default ~/.local/share/toku/openresty).
  • CC overrides the C compiler for native builds and bundling.
  • PREFIX and HOME supply the default install prefix for toku install --bundled. --prefix wins if given, then $PREFIX, then $HOME/.local.
  • XDG_DATA_HOME moves the managed tree, and TOKU_WASM_DIR moves the wasm toolchain out of it.
  • TOKU_CACHE names a local rock server that builds consult before luarocks.org. toku sets it to the cache directory of the managed tree when it's unset.
  • TOKU_FG runs toku start in the foreground, and TOKU_TRACE prints the full Lua traceback on a failure.