santoku-make
View on LuaRocksthe build harness behind toku: a dependency-graph engine, the make.lua project layer, wasm gating, and license notices
santoku-make is the build system behind the toku CLI. santoku.make is a small dependency-graph engine that resolves file targets by modification time. santoku.make.project turns a make.lua descriptor into a built, tested and installable luarocks package: a library, an executable, or a web app with a WASM client served by OpenResty.
Details
- The cards run as a guided tour. The engine comes first, then a library project end to end (init, descriptor, test, install, release).
- The web project pipeline comes last: client pages, asset hashing, nginx and the dev server.
- Builds touch the real filesystem and toolchain, so most examples are for reading. The descriptor, env-merge and template examples are plain Lua and run in the page.
- Real descriptors teach the layer best. The minimal make.lua of the base library ships in its source tarball and is the canonical lib project.
The engine
A target graph
make() returns a submake. target(targets, deps, fn) registers nodes, and build(targets, verbosity) resolves the DAG.
local make = require("santoku.make")
local fs = require("santoku.fs")
local arr = require("santoku.array")
local m = make()
m.target({ "out/header.txt" }, {}, function (ts)
fs.mkdirp(fs.dirname(ts[1]))
fs.writefile(ts[1], "Header\n")
end)
m.target({ "out/body.txt" }, {}, function (ts)
fs.writefile(ts[1], "Body\n")
end)
m.target(
{ "out/main.txt" },
{ "out/header.txt", "out/body.txt" },
function (ts, ds)
local parts = {}
for i = 1, #ds do
parts[i] = fs.readfile(ds[i])
end
fs.writefile(ts[1], arr.concat(parts))
end)
m.target({ "all" }, { "out/main.txt" }, true)
m.build({ "all" }, 3)
print("[make] header, body, main were logged, then [phony] all")
return fs.readfile("out/main.txt")
Details
- fn = true marks a phony aggregate, which is always stale.
- A registered file with no fn is a source leaf.
- At verbosity 2 and up, build traces every node as [make], [ok], [src] or [phony].
Staleness by modification time
A target with a build fn reruns when a dependency is newer than the target. A second build does nothing, and a rewritten dependency restales only its consumers.
local make = require("santoku.make")
local fs = require("santoku.fs")
local str = require("santoku.string")
local m = make()
m.target({ "out/upper.txt" }, { "out/lower.txt" }, function (ts, ds)
fs.writefile(ts[1], str.upper(fs.readfile(ds[1])))
end)
fs.mkdirp("out")
fs.writefile("out/lower.txt", "hello\n")
m.build({ "out/upper.txt" }, 2)
print("first run: [src] out/lower.txt, [make] out/upper.txt")
m.build({ "out/upper.txt" }, 2)
print("second run: [ok] out/upper.txt, nothing rebuilt")
fs.writefile("out/lower.txt", "changed\n")
m.build({ "out/upper.txt" }, 2)
print("third run: [make] out/upper.txt again")
return fs.readfile("out/upper.txt")
Details
- A missing target with no registered fn is an error.
- A filesystem with coarse timestamps gives a dependency rewritten in the target's tick the same mtime as the target.
- Since santoku-make 7.7.0, make breaks such ties. After each fn runs, it records the fs.stamp of every dependency, plus a hash of each dependency that shares the target's mtime.
- A tie rebuilds unless both records still match.
- make(opts) takes opts.stamps, a file path that keeps those records across runs. The project layer keeps them in build/<env>/make-stamps.txt.
- A tie with no record rebuilds once. So the first build after the records are lost redoes the tied targets and what depends on them.
- A copy made with rsync -a or cp -p keeps the old mtimes. Its build can then skip sources that changed and test stale code. Copy without preserving times, or start from a clean build directory.
Sidecar .d files
For any target t, the engine also reads t .. ".d", a make-style dependency file. It folds the newest file listed there into the staleness of t.
local make = require("santoku.make")
local fs = require("santoku.fs")
local tmpl = require("santoku.template")
local m = make()
m.target({ "out/page.html" }, { "res/page.tk.html" }, function (ts, ds)
local deps = {}
local env = {
title = "Docs",
readfile = function (fp)
deps[fp] = true
return fs.readfile(fp)
end,
depend = function (fp)
deps[fp] = true
return fp
end,
}
fs.mkdirp(fs.dirname(ts[1]))
fs.writefile(ts[1], tmpl.compile(fs.readfile(ds[1]), ds[1])(env))
fs.writefile(ts[1] .. ".d", tmpl.serialize_deps(ds[1], ts[1], deps))
end)
m.build({ "out/page.html" }, 2)
print("if the template read res/header.html, touching it restales out/page.html")
return true
Details
- The project layer writes a .d file next to every rendered template.
- The render env's readfile records each file the template reads, and that file's directory. A template that lists a directory and reads each entry then restales when a file is added or removed.
- depend records a file or directory tree without reading it.
- serialize_deps saves the set as one line.
- An edit to a recorded file restales the output, though the file isn't a direct dependency.
- At the next init, a copy under res, lib, bin or test in a build tree is removed when its source is gone.
Track unread files with depend
Every project template render gets depend(path, prune) beside readfile. depend records a file in the .d sidecar without reading it, and returns path.
<%
local fs = require("santoku.fs")
local helper = fs.runfile(depend("res/app_html.lua"))
depend("res/icons", function (fp)
return fs.basename(fp) == "drafts"
end)
return helper.render()
%>
Details
- So depend wraps anything a block reaches through fs.runfile, require or a directory walk.
- On a directory, depend also records every entry under it. Adding or removing a file then restales the output.
- prune(path, mode) returns true for an entry or subtree to leave out.
Library projects
Scaffold a library project
toku init extracts the boilerplate that the project layer ships, renames every tokuboilerplate occurrence to your project name, and runs git init.
$ toku init my-lib
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/*"
my-lib/.gitignore
my-lib/make.lua
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/res/lib/migrations/0.0.1.sql
my-lib/test/spec/my_lib.lua
Details
- The result is a complete lib project: a descriptor, a Lua module over a store builder, a migrations template, a C extension stub, a bin entry point and a spec.
What make.lua contains
A project is a make.lua that returns a table with an env field. The table is plain data, with no framework calls.
local descriptor = {
type = "lib",
env = {
name = "my-lib",
version = "0.0.1-1",
license = "MIT",
copyright = "Your Name",
dependencies = {
"lua == 5.1",
"santoku >= 2.0.0, < 3.0.0",
},
test = {
dependencies = { "santoku-system >= 2.2.0, < 3.0.0" },
},
},
}
local env = descriptor.env
print("rockspec:", env.name .. "-" .. env.version .. ".rockspec")
print("runtime deps:", #env.dependencies)
print("test-only deps:", #env.test.dependencies)
return env.name
Details
- name and version are required.
- dependencies are luarocks constraints.
- test.dependencies stay out of the runtime rockspec.
- An env.release table of hooks from santoku.make.release turns on toku release.
- A top-level public key is an error.
- The rockspec filename comes from name and version, exactly as the code prints it.
License and header keys
toku license reads copyright, license_exclude and vendored. copyright names the holder in LICENSE and in every SPDX header, and license_exclude lists path globs for generated files that get no header.
local env = {
name = "my-lib",
version = "0.0.1-1",
license = "MIT",
copyright = "Your Name",
license_exclude = { "src/parser.c" },
vendored = {
{
name = "LPeg", version = "1.1.0",
path = { "lib/my_lib/lp*", "lib/my_lib/grammar.lua" },
copyright = "(C) 2007-2023 Lua.org, PUC-Rio.",
license = "MIT",
note = "Renamed for coexistence with an external lpeg.",
},
{
name = "SQLite", version = "3.49.2",
source = "https://www.sqlite.org/2025/sqlite-amalgamation-3490200.zip",
license = "blessing",
},
},
}
for _, c in ipairs(env.vendored) do
print(c.name, c.path and "vendors" or "links", c.license)
end
return #env.vendored
Details
- vendored has one entry per piece of third-party code.
| vendored field | Meaning |
|---|---|
| name | required |
| license | required |
| version | optional |
| path | a glob or list of globs for code in the repo |
| source | the URL of code fetched at build time, required when there's no path |
| copyright | a string or a list |
| text | replaces the fetched SPDX text, for code with no SPDX id |
| note | a paragraph after the license text |
- Globs follow REUSE: * stays inside one directory, and ** crosses directories.
- Vendored paths get no header, and each vendored entry gets its own LICENSE section.
- check and apply fail when a tracked file under a vendor, vendored, third_party or third-party directory matches no vendored path or exclude.
- check and apply also fail when a path glob matches no tracked file.
- check and apply also fail when an entry's LICENSE label would match a different entry.
- check also fails on a license_exclude entry that matches no tracked file.
- check also fails on a license_exclude entry that starts with ^ or contains %. Those are Lua pattern syntax, and they never match as globs.
Third-party notices since santoku-make 7.8.0
A components key, even components = {}, turns on THIRD-PARTY-NOTICES.txt. toku license writes it beside LICENSE, and toku license --check fails when it's stale.
local env = {
name = "my-api",
version = "0.0.1-1",
copyright = "Example Corp",
license_ids = { ["2-clause BSD"] = "BSD-2-Clause" },
toolchain = { resty = false, node = false },
components = {
{ name = "lua-cjson", copyright = "2010-2012 Mark Pulford" },
{
name = "debian", version = "bookworm-slim", scope = "image",
license = "LicenseRef-Debian", source = "docker.io/library/debian",
text = "Each Debian package carries its own license.",
},
{
name = "esbuild", version = "0.28.2", scope = "tool", license = "MIT",
copyright = "(c) 2020 Evan Wallace", source = "https://registry.npmjs.org/esbuild",
},
},
}
for _, c in ipairs(env.components) do
print(c.name, c.scope or "adds to the rock's row")
end
return #env.components
Details
- The file opens with a table of every component (name, version, SPDX id, scope, source), then one notice section per component.
| Rows from | Scope | Where toku reads them |
|---|---|---|
| Shipped rocks | shipped | The luarocks manifest in build/<env>/build/lua_modules for a lib, or build/<env>/dist/lua_modules for a web project, plus the client tree when client.dependencies is set |
| Build rocks | build | build/<env>/build-deps/lua_modules, when build.dependencies is set |
| Toolchain | toolchain | The components list setup-toku.sh writes to manifest.lua, with each license file under licenses/ |
| Vendored code | vendored | make.lua's vendored |
| Hand entries | the entry's scope | make.lua's components: base images, apt packages, tools, CDN scripts, fonts |
- The project's own rocks and its local_deps rocks get no row.
- A components entry takes name, version, license, copyright, source, text, note, notice and scope. scope is required, and shipped and build are kept for rocks.
- An entry with no scope that names a rock adds its fields to that rock's row, so a rock with no license file gets its copyright line from make.lua.
- license_ids maps a rockspec license string that isn't an SPDX id to one, like ["2-clause BSD"] = "BSD-2-Clause".
- Notice text comes from the rock's doc/LICENSE, then the entry's text, then the SPDX license text with the copyright lines filled in. A santoku rock's vendored LICENSE sections become rows nested under the rock.
- notice holds the text of an Apache-2.0 NOTICE file. notice = false records that upstream ships none.
- A component with no text and no SPDX id gets a row and no section, and --check reports it.
- A bundled toolchain component with no license file of its own gets a row under its parent, and the parent's section covers it. OpenResty's COPYRIGHT covers its bundled modules this way.
- Since santoku-make 7.11.0, toolchain names the setup-toku.sh options the shipped image ran with, like toolchain = { resty = false, node = false }.
- toku license then drops each toolchain row tagged with an option set to false. setup-toku 0.0.64-1 tags the rows that --resty and --node install.
- With no toolchain key, every toolchain row stays.
- A manifest from setup-toku before 0.0.64-1 has no tags. With a toolchain key set, toku license fails and says to download and run the current setup-toku.sh.
- resty = true fails when the toolchain tree was built without --resty. node = true works the same way.
- A toolchain key other than resty or node, or a value other than true or false, fails.
One env, two build environments
The project layer builds a test env and a main env from your descriptor with santoku.table merge. Phase-specific fields win, and everything else inherits.
local tbl = require("santoku.table")
local str = require("santoku.string")
local config_env = {
name = "my-lib",
version = "0.0.1-1",
cflags = { "-O2" },
}
local base_env = { root_dir = "/src/my-lib", is_wasm = false }
local test_env = tbl.merge(
{ environment = "test", build_dir = "build/default/test" },
config_env, base_env)
local build_env = tbl.merge(
{ environment = "main", build_dir = "build/default/build" },
config_env, base_env)
print(test_env.environment, test_env.name, test_env.cflags[1])
print(build_env.environment, build_env.build_dir)
local prefix = config_env.variable_prefix
or str.upper(str.gsub(config_env.name, "%W+", "_"))
print("variable_prefix:", prefix)
return test_env.root_dir
Details
- merge fills only missing keys and merges tables deeply.
- The code mirrors the real merge chain, including the variable_prefix default that comes from the project name.
- Templates read the env's name as environment.
- Since santoku-make 7.7.0, the shipped env is named main, and a lib's test env is named test.
- A web project's server template gets no environment value, and a page's lib rock renders as main.
- The tree directory keeps the name build.
Environment variables and staleness
santoku-make writes the resolved descriptor to build/<env>/config.stamp and tracks the stamp beside the descriptor. A descriptor that reads env.var then rebuilds when a variable it reads changes.
local env = require("santoku.env")
return { env = { nginx = { workers = env.var("WORKERS", "auto") } } }
$ toku build
$ WORKERS=4 toku build
$ WORKERS=4 toku build
$ cat build/default/config.stamp
Details
- Such a descriptor parameterises the build by the environment. mtimes alone would miss that, because make.lua is the tracked file and the variables it read aren't.
- A wasm build writes build/<env>-wasm/config.stamp.
- config.stamp holds the whole resolved descriptor and the configured rock servers.
- WORKERS=4 toku build re-renders everything the value feeds, with no change to make.lua. A second run with the environment unchanged does nothing.
- A C object or module rebuilds when its compile or link command changes. The lib Makefile writes each command to X.o.cmd and X.so.cmd beside the output and rewrites the file only when the command differs.
- env.var inside the configure hook isn't captured. The hook runs after the stamp is written, and those values never land in the config table.
- To track such a value, read it in the descriptor and pass it through env.
Dependency trees and TOKU_CACHE
Each project installs its dependencies into its own trees under build/. When a newer release of a rock is in range for a tree with an older copy, the next build clears that tree.
$ toku test
warning clearing build/default/test/lua_modules: it holds santoku 2.8.0-1, and 2.8.1-1 is available and in range
warning clearing build/default/test/lua_modules: it holds santoku-web 8.0.0-1, outside the declared santoku-web >= 9.0.0, < 10.0.0
$ cat build/default/test/luarocks.lua | grep rocks_servers
rocks_servers = { "/home/you/.local/share/toku/cache", { "https://luarocks.org", "https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master", "https://loadk.com/luarocks" } }
$ ls ~/.local/share/toku/cache
manifest santoku-2.8.1-1.rockspec santoku-2.8.1-1.src.rock upstream ...
Details
- Since santoku-make 8.0.0, the next build also clears a tree that holds a rock outside its declared range. A pin that moves back to an earlier range does the same.
- Since santoku-make 7.7.0, the check covers every tree a project builds.
- The trees are a lib's test and build trees, the build-deps tree, and a web project's dist/lua_modules, client/pages/lua_modules and spec trees under test.
- toku checks every tree against its own pins and its local deps' pins.
- A newer release counts once it's in the toku tree, in TOKU_CACHE, or in a luarocks.org listing at $TOKU_CACHE/upstream/luarocks.org.txt.
- toku refetches the listing when it's older than 600 s. When the refetch fails, the build stops with the listing's path and "reconnect and rerun the build".
- scm, dev and cvs versions never count.
- Before it clears a tree, toku downloads the rockspec and source rock of everything the tree needs into TOKU_CACHE.
- Local deps rebuild from source, so the download skips them. Since santoku-make 7.11.4, that covers a web project's build-deps tree too, so a local dep that no server publishes no longer keeps that tree stale.
- toku sets TOKU_CACHE itself, to ~/.local/share/toku/cache.
- Every generated luarocks config lists that cache first.
- Since santoku-make 7.10.0, the rock servers that the luarocks config names follow the cache, in their own order. So a private server that a Dockerfile writes into the system config stays in the list.
- Since santoku-make 7.11.6, toku strips trailing slashes from the cache path and every server it writes, because LuaRocks under Lua 5.1 doubles a trailing slash and then skips that server's mirrors.
- A luarocks config that names no servers gives luarocks' default list, luarocks.org and its mirrors, as the code shows.
- Since santoku-make 7.8.0, toku writes an empty manifest into a cache directory that has none. luarocks then reads the directory without a Failed loading manifest warning.
- Since santoku-make 7.8.0, the listing fetch prints luarocks' stderr only when the fetch fails. That hides the warning luarocks prints for each luarocks.org version it can't parse, such as '@version@'.
- The rebuild itself needs no network. If the download fails, toku keeps the old tree and says why.
- Compiled rocks live in $TOKU_CACHE/built, the built-rock cache below.
- Downloads go through $TOKU_CACHE/downloads/url. A versioned file is fetched once and checked by sha256 on each use. toku clean --deps keeps this cache.
Built-rock cache
Since santoku-make 10.0.0, toku keeps each dependency it compiles as a binary rock in $TOKU_CACHE/built, and a later tree with the same build context installs it in place of a source build.
$ toku test
deps 38 rocks (2 built, 36 reused) 10.7s
$ grep reused build/default/toku.log | head -1
[built] reused /home/you/.local/share/toku/cache/built/3f1c0a9e5b2d7c41/santoku-4.0.0-1.linux-x86_64.rock
Details
- $TOKU_CACHE/built is $XDG_DATA_HOME/toku/cache/built by default.
- built/<context>/ holds the entries of one build context. <context> is the first 16 hex digits of the sha256 of context.txt in that directory.
- The context covers the tree's luarocks config and variables, the luarocks.env_vars arguments, dependency_env, MAKEFLAGS, the cmake toolchain file, the compilers and their --version output, make and ld, the Lua headers and library, the luarocks version and patches, the CPU flags and the .pc files on pkg-config's path. It holds no project path.
- An entry is <name>-<version>.<arch>.rock with a <name>-<version>.record beside it. The record holds the rock's sha256, its source and the name, version and source of every rock it depends on.
- toku installs an entry only when the context, the version luarocks resolves, the source and every dependency's version and source match. Otherwise the rock builds from source and its entry is replaced.
- The source of a released rock is release. A rock packed into TOKU_CACHE with toku pack --cache is keyed by the sha256 of its files, so a repack of one version builds once.
- toku never stores the project's own rock, a local_deps rock, an scm, dev or cvs version, a rock with external_dependencies, or a rock that depends on one of these.
- A rock whose sha256 doesn't match its record is never installed.
- Dependency builds see only PATH, HOME, TMPDIR, the locale variables, LUAROCKS_CONFIG, MAKEFLAGS, CMAKE_TOOLCHAIN_FILE and the dependency_env variables. An exported TK_SQLITE_CFLAGS no longer reaches santoku-sqlite; set it in dependency_env.
- Each tree has a <tree>.context stamp beside it. When a recorded compiler, header, library or .pc file changes, the next build clears the tree.
- The deps line counts reused rocks apart from built ones, and toku.log names each entry a tree reused or stored.
- toku clean --deps removes the project's trees and the entries they reused or stored, so the next build compiles them. toku clean and toku clean --all leave built/ alone.
- toku doctor prints the path, entry count and size of built/, and names the directory to delete for a broken entry.
- setup-toku.sh deletes built/ when it rebuilds the toolchain.
Templates in .tk files
Any file named *.tk or *.tk.* renders through santoku.template against the project env, and the output name drops .tk. Every other file is copied verbatim.
local template = require("santoku.template")
local env = { name = "my-lib", version = "0.0.2-1" }
local src = "return { name = \"<% return name %>\", " ..
"version = \"<% return version %>\" }"
local out = template.render(src, env)
print(out)
return out
Details
- In a lib project, that env is the descriptor's env table. component is "lib" unless the descriptor sets it.
- In a web or api project, server and client templates see the build's own fields. From the descriptor, they see only client, server, nginx, name and version.
- So app settings belong under env.server or env.client.
- A block returns a string or nothing. Any other value fails the render, which names the file and line.
- The framework's own Makefiles and rockspec are the same kind of template.
- So lib/version.tk.lua becomes lib/version.lua with the blocks already evaluated.
Conditionals with push and pop
Each <% %> block compiles as its own chunk, so a Lua if can't span two blocks. Emit text conditionally with push(cond) and pop() instead.
<% if access_log_on then %>
access_log <% return n.access_log %>;
<% else %>
access_log off;
<% end %>
toku: Invalid Lua code in template: server/nginx.tk.conf:1: server/nginx.tk.conf:1:1: 'end' expected near '<eof>'
<% push(access_log_on) %>
access_log <% return n.access_log %>;
<% pop() %>
<% push(not access_log_on) %>
access_log off;
<% pop() %>
Details
- A Lua if across two blocks is the common first mistake in a .tk file.
- The error names the file and the line of the block that failed to compile. Then comes Lua's own message, 'end' expected near '<eof>'.
- The template engine injects push and pop for this case. Text between them is emitted only when the condition held, and pairs nest.
- The santoku-template tab covers them in full, showing() included: https://santoku.dev/santoku-template
toku test
toku test renders everything into build/<env>/test and runs luarocks make there, so the rock and its test deps land in a local lua_modules. Then it runs the spec suite with the santoku test runner, then luacheck.
$ toku test
$ toku test --iterate
$ toku test test/spec/my_lib.lua
$ toku test ^test/spec/slow
$ toku test --skip-check
$ toku test --wasm
$ toku test --env prod
Details
- --iterate watches the files at the project root and lib, bin, test and res. It reruns when a file the build reads changes.
- Since santoku-make 10.2.1, --iterate polls the watched files every 0.5 s.
- --iterate reloads the project when make.lua changes or a watched file is created or deleted.
- --wasm compiles each spec with clang for wasm32-wasip1 into a .js file that runs the spec under node's WASI.
- --wasm runs that file with --expose-gc on the node that toku setup --node recorded.
- With no such node, --wasm stops with "wasm tests need the managed node; run: toku setup --node".
- test.wasm.bundle_ignores in the descriptor names modules that the spec bundler skips. debug is always ignored.
- Since santoku-make 7.9.0, toku test prints one line per phase and writes the full output to build/<env>/toku.log. https://santoku.dev/santoku-cli covers the lines.
- Since santoku-make 8.0.0, toku.log lists each resolved rock, version and tree on a [rock] line.
- Since santoku-make 9.0.0, toku test PATH... and env.test.select pick the specs: https://santoku.dev/santoku-cli#santoku-cli--selecting-and-instrumenting-tests
- A spec runs as the file the build wrote: .lua natively, .js under --wasm.
toku build, install, pack, release
For a lib, toku build renders the rock and installs it with its dependencies into build/<env>/build/lua_modules. install, pack and release then install the built rock, package it, or publish it.
$ toku build
$ toku install
$ toku install --bundled --prefix "$HOME/.local"
$ toku pack
$ LUAROCKS_API_KEY=... toku release
local release = require("santoku.make.release")
env.release = {
push = release.git_push(),
host = release.s3_upload({ bucket = "my-releases", base_url = "https://releases.example.com" }),
registry = release.luarocks_upload(),
}
Details
- Since santoku-make 7.7.0, toku build works on a lib project. It renders under build/<env>/build and runs no specs.
- install runs luarocks make on the built rock into the active tree.
- install --bundled compiles every bin/*.lua to a standalone executable through santoku-bundle and copies it into <prefix>/bin.
- prefix defaults to $PREFIX, then ~/.local.
- pack tars lib, bin, deps, LICENSE and the Makefiles into name-version.tar.gz.
- release needs an env.release table and a clean git tree. It tags the version and runs the declared hooks in this order:
| Hook | Function |
|---|---|
| push | release.git_push |
| host | release.s3_upload or release.gh_release |
| registry | release.luarocks_upload, with the key from LUAROCKS_API_KEY |
- luarocks_upload uploads the rockspec alone, and luarocks installs fetch the tarball from the rockspec's source url. So a published rock needs a host.
- The source url comes from the host hook. Without a host hook, the url is the bare tarball name, and luarocks_upload refuses it.
Release preflight and reruns
Before it tags, toku release resolves every rockspec dependency against luarocks.org with luarocks search. After s3_upload and luarocks_upload, it polls each public URL until the URL answers 200.
$ toku release
build 4 targets 0.2s
test native: 3 specs ok 0.4s
preflight 3 dependencies resolve 0.9s
tag 1.2.0-1 created 0.0s
push origin main and 1.2.0-1 1.8s
host 2 uploaded 4.2s
registry 1 uploaded 38.0s
log build/default/toku.log
Details
- A "release preflight" error names each dependency that no published version meets, with the newest version luarocks.org has. Nothing is tagged or pushed.
- After s3_upload and luarocks_upload, the release polls the tarball, the rockspec and luarocks.org's copy of the rockspec.
- The backoff is 1, 2, 4, 8, 16 and then 32 s, about 159 s in all. The release fails and names a URL that never answers 200.
- luarocks_upload also waits until luarocks search lists the new version. So the next rock in a batch released in dependency order passes its preflight.
- A rerun skips an upload whose published bytes match.
- A rerun fails when the published bytes differ, because a release never replaces a published file. Bump the version instead.
The release push since santoku-make 7.10.0
release.git_push pushes the release commit to origin's default branch, then pushes the tag. A release made on another branch or in a worktree still lands on the default branch.
$ git worktree add ../rel-1.2.0 -b rel-1.2.0
$ cd ../rel-1.2.0
$ toku release
...
tag 1.2.0-1 created 0.0s
push origin main and 1.2.0-1 1.8s
...
$ git ls-remote --symref origin HEAD
ref: refs/heads/main HEAD
Details
- git ls-remote --symref origin HEAD names the default branch. An origin that names none stops the push with "origin names no default branch".
- git_push fetches that branch first and checks that the release commit descends from it.
- A commit that isn't a fast-forward stops the push with "the release commit isn't a fast-forward of origin's <branch>", and nothing reaches origin.
- From santoku-make 9.1.0, a diverged commit whose version is below the version in the branch's make.common.lua or make.lua is a maintenance release: git_push pushes only the tag.
- Merge origin's branch into the release commit, or rebase onto it. The merge or rebase moves HEAD, so delete the old tag with git tag -d <version> before you release again.
- The push line names the branch, as in the code.
Driving the lifecycle from Lua
toku is a thin front end. project.init reads the descriptor and returns the lifecycle table, which a Lua script can call directly.
local project = require("santoku.make.project")
local sys = require("santoku.system")
local m = project.init({ env = "default" })
m.test({ skip_check = true })
m.install()
local t = m.lua_env("test")
sys.execute({ t.lua, "-e", "print('runs against the test tree')",
env = { LUA_PATH = t.lua_path, LUA_CPATH = t.lua_cpath } })
local removed = m.clean({ deps = true, dry_run = true })
print("clean --deps would remove", #removed, "paths")
return m.config.env.name
Details
- test builds and runs the suite.
- install runs luarocks make.
- lua_env() builds the test tree and returns its interpreter, with absolute lua_path, lua_cpath and bin_path. bin_path is the tree's lua_modules/bin, as a PATH prefix. toku run and toku env use it.
- clean returns the list of paths it removed, or would remove with dry_run.
Phase lines from Lua since santoku-make 7.9.0
santoku.make.output carries toku's terminal output. supervise runs a command as a child, writes everything it prints to a log, and prints a line per phase that the child reports.
local output = require("santoku.make.output")
local env = require("santoku.env")
local sys = require("santoku.system")
if output.adopt() then
output.phase("build", function ()
output.count("targets", 2)
output.phase("test", output.note, "smoke only")
end)
else
sys.exit(output.supervise({
argv = env.interpreter(true),
log = "build/default/toku.log",
header = "smoke",
}))
end
Details
- output.phase(name, fn, ...) runs fn as a phase and returns its results. Outside a supervised child it only calls fn.
- output.count(key, n) and output.note(text) add to the summary of the running phase.
- output.warn(text) and output.notice(label, text) print at once. Outside a supervised child they print warning: <text> on stderr and a label line on stdout.
- output.supervise({ argv, log, shown, verbose, header }) returns the child's exit code. shown is the log path that the last line names.
- The child calls output.adopt() first. supervise sets TOKU_OUTPUT_CHILD for it, and adopt clears the variable, so a nested toku supervises its own run.
- The child's stderr joins its stdout, so the log keeps the order of the lines.
- A phase name outside toku's own prints after them, in name order. A target function in make.lua can report its work that way.
Dependencies and C extensions
C extensions and deps Makefiles
A lib project compiles every lib/**/*.c to a shared object. To link an upstream C library, add a deps/<name>/Makefile that builds the library and writes results.mk.
cflags = {
"-I$(PWD)/deps/sqlite3/",
},
ldflags = {
"$(PWD)/deps/sqlite3/sqlite-amalgamation-3490200/libsqlite3.a",
"-lm",
},
results.mk: Makefile
[ -f sqlite-amalgamation-$(V).zip ] || exit 1
unzip sqlite-amalgamation-$(V).zip
cd $(DIR) && $(CC) -c $(SQLITE_CFLAGS) $(CFLAGS) -o sqlite3.o sqlite3.c
cd $(DIR) && $(AR) rcs libsqlite3.a sqlite3.o
touch results.mk
Details
- The generated build finds each deps directory, runs its Makefile and includes the result.
- Compile upstream sources directly with $(CC) $(CFLAGS) and archive them, as santoku-sqlite does. Never run the upstream's own configure.
- The results.mk rule must list Makefile as a prerequisite, or an edit to the Makefile would rebuild nothing. The build stops with an error when the rule doesn't.
- Objects compile with -MMD -MP, so an edit to a header recompiles every object that includes it.
- Each C module also gets a .requires file. It lists the other C modules whose headers the module includes and whose names appear in its object.
- The .requires file installs next to the module, and santoku-bundle reads it.
Lua build helpers since santoku-make 7.7.0
A deps/<name>/Makefile can run a santoku Lua script when luarocks builds the rock. That works from the packed tarball as well as from toku test.
return {
env = {
name = "my-rock",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
build_dependencies = { "santoku-fs >= 2.3.1, < 3.0.0" },
},
}
results.mk: Makefile gen.lua
LUA_PATH='$(TK_LUA_PATH)' LUA_CPATH='$(TK_LUA_CPATH)' $(LUA) gen.lua out.h
touch results.mk
Details
- env.build_dependencies lists rocks for the rockspec's build_dependencies. luarocks installs them into the target tree before the build.
- The make build sees $(LUA), the interpreter of luarocks.
- The top Makefile exports TK_LUA_PATH and TK_LUA_CPATH, the share/lua/5.1 and lib/lua/5.1 paths of that tree. Both come from TK_ROCKS_DIR.
- The release preflight checks build_dependencies on luarocks.org the same way as dependencies.
- env.build_dependencies are rocks for luarocks install time.
- build.dependencies are toku's own tree for template time: https://santoku.dev/santoku-make#santoku-make--rocks-for-template-time
- A wasm build compiles the build dependencies for wasm too, and $(LUA) can't load them. So keep a helper like this to native rocks.
Headers from another rock
A C extension that includes another rock's headers lists that rock in dependencies and adds rock.include(name) to cflags. rock is santoku.make.rock.
local rock = require("santoku.make.rock")
return {
type = "lib",
env = {
name = "my-lib",
version = "0.0.1-1",
cflags = { rock.include("santoku-monocypher") },
dependencies = {
"lua == 5.1",
"santoku-monocypher >= 2.0.1, < 3.0.0",
},
},
}
Details
- include returns -I plus incdir(name). incdir(name) is a Makefile expression for the include directory of the rock installed in the tree being built.
- The build stops with an error that names the rock when the rock isn't installed there.
Link a system library
A C extension can link a library installed on the host, such as OpenSSL. It declares the library under dependencies.external, a list of luarocks external dependency entries.
return {
env = {
name = "my-tls-lib",
version = "0.0.1-1",
cflags = { "-I$(OPENSSL_INCDIR)" },
ldflags = { "-L$(OPENSSL_LIBDIR)", "-lcrypto" },
dependencies = {
external = { { OPENSSL = { header = "openssl/x509.h", library = "crypto" } } },
"lua == 5.1",
},
},
}
Details
- luarocks finds the header and library at install time. make gets the result as <NAME>_INCDIR and <NAME>_LIBDIR.
- So cflags and ldflags name those variables, never a path.
- On a host without the library, the install fails and names what it looked for.
- santoku-socket links libcrypto this way.
Vendoring with sha256 pins
A deps Makefile never downloads. The archive path is declared data in rules.include, and a configure hook registers the target that fetches the archive with vendor.fetch.
local fs = require("santoku.fs")
local vendor = require("santoku.make.vendor")
local spec = {
file = "deps/sqlite3/sqlite-amalgamation-3490200.zip",
url = "https://www.sqlite.org/2025/sqlite-amalgamation-3490200.zip",
sha256 = "921fc725517a694df7df38a2a3dfede6684024b5788d9de464187c612afb5918",
}
return {
env = {
name = "santoku-sqlite",
version = "2.2.0-1",
dependencies = { "lua == 5.1" },
rules = { include = { spec.file } },
configure = function (submake, envs)
local dest = fs.join(envs.root.build_dir, spec.file)
submake.target({ dest }, { "make.lua" }, function ()
vendor.fetch(spec, dest)
end)
end,
},
}
Details
- rules.include makes the archive flow through the build, test and release-tarball file lists like a tracked file.
- vendor.fetch downloads to a .part file next to dest, renames the file on success and checks the digest. It discards an existing file that fails the check.
- Since santoku-make 7.11.0, the download retries up to 5 times on any error, so one connection reset doesn't fail the build.
- Since santoku-make 7.11.2, each connect attempt gives up after 20 s. An unreachable host then fails the fetch in about 2.5 minutes. Before, a connect to lua.org that hung for about 130 s made the 6 attempts take about 13 minutes.
- Since santoku-make 7.11.6, the download retries up to 8 times, waiting 1 s and then twice as long each time. A source that answers HTTP 5xx for up to about 4 minutes then still downloads. An unreachable host fails the fetch in about 7 minutes.
- Since santoku-make 7.11.2, vendor.cached(spec) keeps one verified copy per sha256 in $TOKU_CACHE/downloads, or ~/.local/share/toku/cache/downloads when TOKU_CACHE is unset.
- A cache hit makes no network call. A cached file that fails the digest check is deleted and fetched again. cached raises when spec has no sha256.
- The wasm build's Lua 5.1.5 source comes through vendor.cached, so a machine fetches lua-5.1.5.tar.gz once rather than once per build directory.
- Omit sha256 on a new entry, and the fetch prints a warning with the computed digest to paste in, then exits non-zero.
- Consumers never fetch, because the archive ships inside the release tarball.
- The code distills the santoku-sqlite and santoku-mustache descriptors.
Sibling rocks with local_deps
local_deps lists paths to lib projects, usually git submodules. The build installs each one from source into every luarocks tree it manages, before the consuming rock.
return {
env = {
name = "my-app",
version = "0.0.1-1",
dependencies = {
"lua == 5.1",
"santoku >= 2.0.0, < 3.0.0",
},
local_deps = {
"submodules/my-shared-lib",
},
},
}
Details
- An mtime change under the dep's lib, bin, deps or res directories, or in its make files, triggers a reinstall.
- A local dep must be a lib project.
- Since santoku-make 10.1.0, a local dep can have local_deps. One copy per env.name installs, dependencies first, and the project's own entry wins a name clash.
- Don't also list a local dep in the project's own dependencies.
- A shared library is often a submodule of both an app repository and its CLI repository.
- In a web project, an entry written { path = ..., targets = { ... } } reaches only the trees it names. The names are "server", "client" and "build".
- Since santoku-make 7.6.0, a web project also installs its local deps into the build-deps tree. A build.dependencies entry can then come from a local dep that no rock server publishes.
- A dep whose targets leave out "build" stays out of that tree.
Rocks for template time
build.dependencies install once per env into a separate build-deps tree. Its paths join package.path around every template render, so a .tk file can require them at generation time.
return {
env = {
name = "my-app",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
build = {
dependencies = {
"santoku-web >= 13.0.0, < 14.0.0",
},
},
},
}
Details
- A .tk file can require them though they aren't runtime deps.
- Declare santoku-web here, so a template can compile mustache sources with santoku.web.mustache.compile or inline a santoku.web.pwa helper at render time.
- Since santoku-make 7.7.0, the page glue gets santoku.web.pwa.wrap_events without a pre_js: https://santoku.dev/santoku-make#santoku-make--client-pages
- Since santoku-make 7.3.3, a target action that a configure hook registers also runs with that tree on package.path and package.cpath.
- Such an action waits for the build dependencies to install first.
JavaScript bundles with bundle_js since santoku-make 7.4.0
local js, inputs = build.bundle_js(entry, opts) bundles an entry file with esbuild. js is the bundle as a string, and inputs lists the original files the bundle reached.
<%
local fs = require("santoku.fs")
local build = require("santoku.make.build")
local lp = require("santoku.lpeg")
local js, inputs = build.bundle_js(fs.join(root_dir, "res/web/app/index.js"), {
global = "App",
text = { [".css"] = build.minify_css, [".html"] = lp.minify_html },
})
for i = 1, #inputs do depend(inputs[i]) end
app_js = js
%>
<script><% return app_js %></script>
Details
- inputs is a sorted list of absolute paths.
- The esbuild flags are fixed: --bundle --minify --format=iife --legal-comments=none --charset=utf8, with no --mangle-props.
- opts.global adds --global-name, so the bundle assigns its exports to that global.
- opts.target adds --target.
- opts.text maps extensions to functions, such as { [".css"] = fn, [".html"] = fn }. Files with those extensions import as strings, each run through its function first.
- The longest matching extension in opts.text wins.
- A first esbuild pass writes a metafile that names the reached inputs.
- bundle_js copies the inputs under their common ancestor with opts.text applied, then builds the bundle from the copy. So imports from outside the entry's folder work.
- A bare import found in a node_modules folder above the importer is copied with the rest.
- An import that esbuild resolves any other way, such as through NODE_PATH, raises "bundle_js: an import resolved outside the copied tree".
- An esbuild error raises "esbuild failed" with esbuild's stderr.
- bundle_js removes its temporary directory on success and on failure.
- In a .tk template, pass each input to depend, which records it in the target's .d file. An edit to any reached file then rebuilds the page.
- depend is the template global from the engine cards: https://santoku.dev/santoku-make#santoku-make--track-unread-files-with-depend
Native, wasm and CUDA builds
Native and WASM variant flags
Top-level cflags and ldflags apply everywhere. native and wasm blocks scope flags by variant, build and test blocks by phase, and combined forms such as build.wasm.ldflags by both.
return {
env = {
name = "my-native-lib",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
cflags = { "-O2" },
native = {
cflags = { "-fopenmp" },
ldflags = { "-fopenmp" },
},
wasm = {
cflags = { "-DMY_LIB_NO_THREADS" },
},
},
}
Details
- One source tree builds with two toolchains.
- test.native.cflags is another combined form.
- --wasm selects a WASM build, which lands in build/<env>-wasm.
- The compiler is clang for wasm32-wasip1. C code tests __wasm__, and -DTK_WASM_WEB marks a browser build.
- The Makefile templates set _WASM when CC contains wasm32.
- Every wasm compile force-includes <tkwasm.h>, which carries the JS interop macros TK_JS, TK_JS_ASM and TK_EXPORT. So a page needs no export or runtime flags.
- santoku-learn's make.common.lua is a full real example, with OpenMP and BLAS confined to native.
- A rock that can't build for wasm at all sets wasm = false beside name and version.
- toku build --wasm and toku test --wasm then stop with <rock> is native-only. An install of the rock into a wasm tree fails with the same message.
C++ and wasi-libc in wasm
A wasm build compiles C++ against the sysroot's libc++. client.libc = "wasi" links wasi-libc into a web page, and wasm_exceptions = true turns on C++ exceptions.
return {
type = "lib",
env = {
name = "my-cxx-rock",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
wasm_exceptions = true,
},
}
return {
type = "web",
env = {
name = "my-app",
version = "0.0.1-1",
client = {
libc = "wasi",
wasm_exceptions = true,
dependencies = { "lua == 5.1", "my-cxx-rock >= 0.0.1, < 0.1.0" },
},
server = {},
},
}
Details
- Without exceptions, the build uses the noeh libc++ with -fno-exceptions.
- The node profile always links libc++ and libc++abi.
- A web page links them only with client.libc = "wasi". That links wasi-libc and the compiler builtins in place of the default "tlibc".
- wasm_exceptions = true is a client key on web and a top-level key in a lib.
- wasm_exceptions compiles with -fwasm-exceptions and links the eh libc++, libc++abi and libunwind. It also turns on wasm-opt's exception-handling features.
- On web, wasm_exceptions = true links wasi-libc on its own, and refuses libc = "tlibc".
- The eh libraries of wasi-sdk 34 use the exnref encoding. It runs from Chrome 137, Firefox 131, Safari 18.4 and Node 24.15.
- Those versions are santoku-learn's measurement against MDN's browser compatibility data.
- A wasm build runs luarocks with CMAKE_TOOLCHAIN_FILE set to a generated wasi.cmake. So a cmake deps/ Makefile builds for wasm.
- wasi.cmake sets system WASI, processor wasm32, static try-compiles and pthread present.
- When the page's wasm imports wasi_snapshot_preview1, the web glue adds a WASI shim. A wasm with no WASI imports gets no shim.
- The shim sends fd_write to console.log or console.error, a line at a time.
- In the shim, clocks read Date.now and performance.now, and random_get uses crypto.getRandomValues.
- The shim has no args, environment or preopened directories, and other calls return ENOSYS.
- With libc = "wasi", or when any linked object has a static constructor, the glue calls __wasm_call_ctors once before main.
- Since santoku-make 7.3.0, a C rock's __attribute__((constructor)) functions run on a web page.
- The page has no files. So under libc = "wasi", a rock reads bytes the page hands it as a Lua string, through fmemopen and wasi-libc stdio.
CUDA variants since santoku-make 7.5.0
In env.cuda, a rock declares its CUDA build. toku test, toku build and toku install with --cuda set _CUDA for every rock they build, dependencies included.
return {
env = {
name = "my-gpu-lib",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
cuda = {
nvcc = "nvcc",
nvccflags = { "-O2", "-gencode", "arch=compute_89,code=sm_89" },
cflags = { "-DMY_GPU_LIB_CUDA" },
ldflags = { "-lcublas", "-lcudart", "-lstdc++" },
},
},
}
$ toku test --cuda
$ toku build --cuda
$ toku install --cuda
Details
- env.cuda takes nvcc, nvccflags, cflags, cxxflags and ldflags, and nvcc is required.
- nvcc names the compiler command, and nvccflags go to every nvcc compile.
- cflags, cxxflags and ldflags join the rock's C compile and link lines.
- toku test --cuda and toku build --cuda work in build/<env>-cuda, so the CPU tree stays beside it.
- Since santoku-make 7.7.0, toku build --cuda installs the rock and its dependencies into build/<env>-cuda/build/lua_modules.
- Under _CUDA, nvcc compiles each lib/**/*.cu with -Xcompiler -fPIC -I. added.
- The objects go into <name>-cuda.a, and every C module of the rock links that archive.
- The rock's released Makefile carries this block. So a consumer with no env.cuda of its own still gets the dependency's cuda variant under --cuda.
- Without --cuda, nvcc never runs and the .cu files stay uncompiled. No cuda flag or library reaches a compile or link.
- A rock without env.cuda compiles and links the same either way.
- toku install --cuda installs into the active tree. A dependency already installed there from a CPU build stays as it is.
- When the declared nvcc isn't on PATH, --cuda stops at init with "<rock> builds its cuda variant with <nvcc>, and <nvcc> is not on PATH".
- A dependency's Makefile stops with the same message before it compiles anything.
- --cuda with --wasm stops with "--cuda and --wasm don't combine: a cuda build is native".
- A web project rejects --cuda.
- A .cu file in a rock without env.cuda fails init with "a .cu source needs env.cuda in make.lua".
- A GPU check at runtime is the rock's job.
Wasm gating
Choosing a wasm mechanism
Four mechanisms make code behave differently under wasm, or not exist. The one that applies follows from what is actually different about the build.
absent under wasm gate on presence if fs.hardlink then ... end
exists but always raises probe once local ok = pcall(io.popen, "true")
separate implementation filename variant lib/santoku/web/js.wasm.lua
must not be emitted template gate <% push(is_wasm) %> ... <% pop() %>
Details
- A capability compiled out of a C extension is absent, so a nil check settles it.
- A capability that exists and raises when called needs one invocation probe, because presence reads as available.
- A module with its own wasm implementation is a filename variant. The build selects it, and nothing branches on it at runtime.
- Text that must not appear in a generated file at all is a template gate.
- The santoku-template tab covers template gates under conditional sections with push and pop: https://santoku.dev/santoku-template
Compile a capability out
clang defines __wasm__ for every wasm build, so a C extension can drop a function the platform can't support. Guard the body and the luaL_Reg entry together.
#ifndef __wasm__
int tk_fs_posix_hardlink (lua_State *L)
{
lua_settop(L, 2);
const char *oldpath = luaL_checkstring(L, 1);
const char *newpath = luaL_checkstring(L, 2);
if (link(oldpath, newpath) == -1)
return tk_fs_posix_err(L, errno);
return 0;
}
#endif
luaL_Reg tk_fs_posix_fns[] =
{
{ "mode", tk_fs_posix_mode },
#ifndef __wasm__
{ "hardlink", tk_fs_posix_hardlink },
{ "symlink", tk_fs_posix_symlink },
#endif
{ "touch", tk_fs_posix_touch },
{ NULL, NULL }
};
Details
- An entry without a body fails to link, and a body without an entry is dead code.
- santoku-fs does this for hardlink and symlink in lib/santoku/fs/posix.c.
- So fs.hardlink is nil in a wasm spec, and the fs tab checks for it before the call: https://santoku.dev/santoku-fs
- When a module must keep the function and change what it does, guard inside the body. Then let Lua see which build it got.
- santoku.sqlite.db exposes a wasm field set from the same ifdef.
Gate specs on a capability
One spec file runs under both toolchains and registers only the tests its target supports. Gate on the capability rather than on the platform.
local test = require("santoku.test")
local fs = require("santoku.fs")
if fs.hardlink then
test("hardlink", function ()
fs.writefile("test/res/hl_src.txt", "hello")
fs.hardlink("test/res/hl_src.txt", "test/res/hl_dst.txt")
assert(fs.readfile("test/res/hl_dst.txt") == "hello")
fs.rm("test/res/hl_src.txt")
fs.rm("test/res/hl_dst.txt")
end)
end
Details
- With fs.hardlink nil, the suite is shorter under wasm, and the spec never names a platform.
- santoku-fs gates its hardlink and symlink tests this way. That keeps toku test and toku test --wasm both green on the same tree.
When presence checks lie
A presence check only answers for capabilities that are genuinely absent, and io.popen isn't one. In wasm specs, io.popen is a function that raises only when called, so probe it once.
local test = require("santoku.test")
local spawn_ok, spawn_probe = pcall(io.popen, "true")
local can_spawn = spawn_ok and spawn_probe ~= nil
if can_spawn then
spawn_probe:close()
end
if can_spawn then
test("generators are seeded per process", function ()
local f = io.popen("lua5.1 -e \"print(require('santoku.random').fast_random())\"")
local out = f:read("*a")
f:close()
assert(out ~= "" and out ~= nil)
end)
end
Details
- toku builds the node profile of Lua 5.1.5, the one wasm specs run on, with cflags that don't define LUA_USE_POSIX.
- So LUA_USE_POPEN is undefined, and luaconf.h expands lua_popen to a luaL_error that reads 'popen' not supported.
- liolib.c registers popen regardless.
- A nil check thus reports io.popen as available.
- Probe once at file scope and gate on the result. Don't probe inside each test.
- The same pattern covers anything whose failure waits for the call: os.execute, host paths, a spawned interpreter.
Filename variants
The build chooses a file named <name>.wasm.<ext>, and the running program doesn't. Native builds drop such files, and wasm builds keep them with the .wasm. infix stripped.
lib/santoku/web/js.wasm.lua installs as santoku/web/js.lua, wasm builds only
test/spec/santoku/web/val.wasm.lua runs under toku test --wasm and --browser
test/spec/santoku/web/dom.browser.wasm.lua runs under toku test --browser only
ifneq (,$(findstring wasm32,$(CC)))
_WASM = 1
endif
ifdef _WASM
LIB_LUA = $(shell find * -name '*.lua')
else
LIB_LUA = $(filter-out %.wasm.lua, $(shell find * -name '*.lua'))
endif
INST_LUA = $(patsubst %.wasm.lua,%.lua,$(addprefix $(INST_LUADIR)/, $(LIB_LUA)))
Details
- The generated lib Makefile sets _WASM when CC contains wasm32.
- Native builds filter %.wasm.lua, %.wasm.c and %.wasm.cpp out of the file list.
- Wasm builds strip the .wasm. infix when they name objects and install targets. So lib/santoku/web/js.wasm.lua installs as santoku/web/js.lua.
- That file is required as santoku.web.js.
- Specs follow the same rule in the project layer. A native run drops test/spec/**/*.wasm.lua, and --wasm bundles each one to the stripped .js name.
- A spec named *.browser.wasm.lua runs only under --browser, in headless Chromium. --wasm skips it by name.
- Since santoku-make 7.11.3, a native spec named *.browser.lua drives Chromium itself. toku test skips it with a warning when TOKU_CHROMIUM is unset, unless CI is set or a toku test PATH names the spec or its own directory: https://santoku.dev/start-web#start-web--the-web-scaffold-s-files
- This selects a variant and gates no capability. It says nothing about a file both targets share.
- A variant with no native counterpart is missing from a native build, with no stub.
- santoku-web ships this way. Its browser runtime modules exist only as .wasm. files.
- The build-time pwa helpers of santoku-web, which templates require natively, are plain sources beside those modules.
Rules and profiles
File rules
rules.exclude, rules.copy and rules.template are Lua patterns that drop files, force a copy or force templating. rules.include declares literal paths into the file set.
return {
env = {
name = "my-lib",
version = "0.0.1-1",
dependencies = { "lua == 5.1" },
rules = {
exclude = { "%.draft%.lua$" },
copy = { "^res/raw/" },
template = { "^res/index%.css$" },
include = { "deps/upstream/upstream-1.0.tar.gz" },
},
},
}
Details
- A rules.include path joins the file set even when the tree doesn't hold it. The path must gain a producer target, or the build fails.
- rules holds only these path lists. Any other key stops the build, and so do build.native.rules, build.wasm.rules, test.native.rules and test.wasm.rules.
Environment profiles
Real projects keep shared config in make.common.lua and override it per profile. make.prod.lua merges its overrides over the common table, and the profile's values win.
local tbl = require("santoku.table")
local common = {
env = {
name = "my-app",
version = "0.0.1-1",
client = { verbose = true, pre_js = { "res/pre.js" } },
nginx = { domain = "localhost", workers = "1" },
},
}
local prod = tbl.merge({
env = {
client = { verbose = false },
nginx = { workers = "auto" },
},
}, common)
print("client.verbose:", prod.env.client.verbose)
print("client.pre_js:", prod.env.client.pre_js[1])
print("nginx:", prod.env.nginx.domain, prod.env.nginx.workers)
return prod.env.name
Details
- The profile's values win because merge never overwrites existing keys.
- toku --env prod selects make.prod.lua and builds under build/prod.
- make.common.lua is tracked as a config dependency, so an edit to it restales every rendered target.
- Since santoku-make 8.0.0, toku test --iterate reloads the project when make.common.lua changes.
- In a profile file, the common table comes from fs.runfile("make.common.lua").
Web projects
The web scaffold
A web project pairs a client tree compiled to WebAssembly with a server tree of OpenResty Lua, plus a shared root lib and res. toku init --example web scaffolds one.
$ toku init --example web my-app
my-app/client/bin/bundle.lua
my-app/client/lib/my_app/core.lua
my-app/client/lib/my_app/main.lua
my-app/client/lib/my_app/templates.tk.lua
my-app/client/lib/my_app/todos.lua
my-app/client/static/index.html
my-app/make.common.lua
my-app/res/client/todo-app.html
my-app/res/server/migrations/0.0.1.sql
my-app/res/server/nginx.mustache
my-app/res/server/nginx/pages.mustache
my-app/server/lib/my_app/store.lua
my-app/server/lib/my_app/web/api.lua
my-app/server/lib/my_app/web/db.lua
my-app/server/lib/my_app/web/init.lua
my-app/server/nginx.tk.conf
my-app/server/test/spec/my_app.lua
$ toku init --example pwa my-app
my-app/client/lib/my_app/db.lua
my-app/client/lib/my_app/store.lua
my-app/client/lib/my_app/sync.lua
my-app/client/lib/my_app/sync_view.lua
my-app/client/static/serviceworker.tk.js
my-app/res/server/migrations/0.0.1.sql
my-app/res/server/nginx/pages.mustache
my-app/server/lib/my_app/store.lua
my-app/server/test/spec/offline.browser.lua
Details
- client/bin holds the page entry points, and client/static the templated HTML.
- server/nginx.tk.conf is the server config template, and it renders res/server/nginx.mustache.
- res/ holds the assets both sides render.
- The build copies root res/ into the client tree, the server tree and the server rock. So a helper there that only templates use still ships in the server rock.
- Since santoku-make 9.1.0, the scaffold's todo page runs on santoku-web 9.0.0, and its handlers take the handle c after s.
- Module paths use an underscore (my_app), and the rock keeps the hyphen.
- client/lib/my_app/templates.tk.lua reads res/client with santoku.web.mustache.loader and returns loader.templates over it at build time.
- The page markup is res/client/todo-app.html, the entry tpl.todo_app. It includes the partials by path key, such as {{> partials.toolbar.mustache}}.
- So build.dependencies lists santoku-web.
- main.lua passes the todo-app spec from todos.lua to santoku.web.app.define.
- index.html holds a todo-app element. The component renders into an open shadow root, which page code and a browser test reach as el.shadowRoot.
- Router scopes keep the page in the path (/, /tags and /settings) and the tag filter in ?tag=.
- toku init --example web keeps the store on the server, and the page calls it through POST /api/<name>.
- toku init --example pwa moves the store into a SQLite worker in the browser. It syncs the store with the server through POST /api/sync, with santoku.sqlite.sync on both sides since santoku-make 7.11.2.
- The pwa example also adds the Sync button, the /settings/todos and /settings/sync tabs, and a service worker, so the app boots offline.
- Both, and toku init --example api, lay down the same server files over santoku.resty.sqlite. Each supplies a store.lua builder.
- The web app tab lists every file of both scaffolds and says what each does: https://santoku.dev/start-web
The web descriptor
server and client carry separate dependency sets. The client compiles to WASM with clang for wasm32-wasip1, and the server runs native under OpenResty.
return {
env = {
name = "my-app",
version = "0.0.1-1",
server = {
dependencies = {
"lua == 5.1",
"santoku-resty >= 5.0.0, < 6.0.0",
"santoku-sqlite >= 9.0.0, < 10.0.0",
},
},
client = {
dependencies = {
"lua == 5.1",
"santoku-web >= 13.0.0, < 14.0.0",
},
},
nginx = {
domain = "localhost",
workers = "auto",
},
},
}
Details
- nginx is free-form context for your own server/nginx.tk.conf template.
- The whole project builds a lib project per component.
- Since santoku-make 7.7.0, dist/run.sh raises the soft open-file limit to the hard limit before it starts OpenResty.
- Linux caps a user's in-flight passed descriptors at the sender's soft limit.
- So at a limit of 1024, a reload with workers = "auto" on a 32-core host logged sendmsg() failed (109: Too many references).
- Since santoku-make 7.10.0, an unset nginx.workers lets run.sh count the server's CPUs when it starts: https://santoku.dev/santoku-make#santoku-make--worker-count-at-start
Client pages
Every client/bin/*.lua is one page. santoku-bundle merges it with every module it requires, and the build links it with clang for wasm32-wasip1 into page.js plus page.wasm in the public dist.
client = {
public = { "roboto.woff2", "index.49e48e032508.css", "favicon.f18d929ffecd.svg" },
bundle_mods = { "santoku.mtx" },
dependencies = {
"lua == 5.1",
"santoku >= 6.0.0, < 7.0.0",
"santoku-web >= 13.0.0, < 14.0.0",
},
pre_js = { "res/pre.js" },
},
Details
- minify.chunk sets whether the page loads that Lua as source or as bytecode: https://santoku.dev/santoku-make#santoku-make--the-shipped-chunk
- The same page.js runs in a window and in a worker.
- The glue exports what the page's JS references, so a page needs no export or runtime flags.
- Since santoku-make 7.6.0, the generated loader sets no global, so page.js doesn't assign globalThis.Module.
- The link keeps only the base, string, table and math functions whose names appear as strings in the chunk or the C objects.
- So a function reached only by a computed name, such as string["up" .. "per"], is nil in the page. This step has no switch.
- bundle_mods preloads modules the bundler can't see statically.
- client.pre_js lists JS files that run inside the page glue before the wasm module starts. toku reads them from the client build tree.
- client.rules holds the same path lists. A per-file flag pattern stops the build.
- client.ldflags reaches the link.
- Since santoku-make 7.7.0, a page whose client tree holds santoku-web gets santoku.web.pwa.wrap_events in its glue. It sits in its own block, ahead of the pre_js files.
- So a worker keeps the messages that arrive before Lua sets Module.on_message, and replays them at Module.start().
- A pre_js that already defines Module.start, such as one that inlines wrap_events, gets no second copy.
- A client with no client/bin is valid. It builds no wasm, toku test skips the client suite, and client/static alone makes a static site.
The shipped chunk
Inside bundle.wasm, minify.chunk picks the form of a page's merged Lua. The default, "smallest", builds the page as source and as re-encoded bytecode, and ships the smaller after compression.
return {
env = {
name = "my-app",
version = "0.0.1-1",
minify = { lua = true, chunk = "smallest", c = true },
client = {
dependency_env = {
["santoku-sqlite"] = {
TK_SQLITE_CFLAGS = "-DSQLITE_OMIT_FOREIGN_KEY -DSQLITE_OMIT_FLAG_PRAGMAS",
},
},
},
},
}
Details
- "smallest" compresses each form with santoku-brotli at quality 11 and logs both sizes.
- "bytecode" always ships re-encoded bytecode, and "source" always ships source.
- A page whose shipped chunk is source parses it once and caches the parsed chunk as bytecode in IndexedDB. A bytecode chunk has no cache.
- A web page links with a 512 KB stack.
- client.dependency_env sets environment variables for the client's dependency builds, grouped by the rock they're meant for.
- Every dependency build sees every variable, so each variable must carry a rock prefix.
- TK_SQLITE_CFLAGS is one such variable, and santoku-sqlite appends it to its wasm compile.
- -DSQLITE_OMIT_FOREIGN_KEY and -DSQLITE_OMIT_FLAG_PRAGMAS shrink the page. They suit only a consumer whose schema has no foreign keys.
client.public and the configure hook
File sets are declared data, and configure only registers their producers. client.public declares the public filenames your hook generates, such as fonts, compiled CSS and icons.
local fs = require("santoku.fs")
local sys = require("santoku.system")
return {
env = {
name = "my-app",
version = "0.0.1-1",
client = {
public = { "index.49e48e032508.css", "favicon.f18d929ffecd.svg" },
dependencies = { "lua == 5.1", "santoku-web >= 13.0.0, < 14.0.0" },
},
server = {
dependencies = { "lua == 5.1", "santoku-resty >= 5.0.0, < 6.0.0" },
},
configure = function (submake, envs)
local client = envs.client
if not client then
return
end
local css_out = fs.join(client.public_dir, "index.49e48e032508.css")
local css_in = fs.join(client.build_dir, "res/index.css")
submake.target({ client.target }, { css_out })
submake.target({ css_out }, { css_in }, function ()
sys.execute({ "tailwindcss", "-i", css_in, "-o", css_out, "--minify" })
end)
local icon_out = fs.join(client.public_dir, "favicon.f18d929ffecd.svg")
local icon_src = fs.join(client.root_dir, "res/favicon.svg")
submake.target({ client.target }, { icon_out })
submake.target({ icon_out }, { icon_src }, function (ts, ds)
fs.writefile(ts[1], fs.readfile(ds[1]))
end)
end,
},
}
Details
- client.public files join the hashed-asset manifest exactly like walked static files.
- A web project's hook runs once, with the merged envs: root, server and client.
- Attach each product to client.target, so the build waits for it.
- For Tailwind CSS, client.tailwind replaces the hook's css target and fetches the tailwindcss binary itself: https://santoku.dev/santoku-make#santoku-make--tailwind-css-with-client-tailwind
Tailwind CSS with client.tailwind since santoku-make 7.10.0
client.tailwind builds one stylesheet with the tailwindcss standalone binary, minified, and ships it as a hashed public file. List the input stylesheet and the sources that tailwind scans for class names.
client = {
tailwind = { input = "res/client/index.css", sources = { "res/client" } },
},
@import "tailwindcss";
<link rel="stylesheet" href="/index.49e48e032508.css">
Details
| Key | Meaning |
|---|---|
| input | the stylesheet, relative to the project root. Its file name is the public name, so res/client/index.css ships as /index.css |
| sources | files and directories, relative to the project root, that tailwind scans |
- The build writes the stylesheet to build/<env>/tailwind/<name>, then copies it into the public dir.
- The hashing pass gives it a hashed name and rewrites the /index.css link in index.html.
- The target depends on the input, every file under the sources and make.lua. So an edit to a template rebuilds the stylesheet.
- The build imports the input from an entry file with one @source line per source. So tailwind scans each source even where .gitignore hides it.
- An input that sets @import "tailwindcss" without source(none) also scans the project root.
- The first build fetches tailwindcss v4.3.3 into $XDG_DATA_HOME/toku/tailwind/v4.3.3 (~/.local/share/toku/tailwind/v4.3.3 by default) and checks its sha256. Later builds check the file again and reuse it.
- tailwindcss ships for x86_64 and arm64 Linux with glibc and for macOS. On any other platform, Android included, the build stops with "client.tailwind: tailwindcss v4.3.3 has no standalone build for this platform".
- A missing input or source stops the build with "client.tailwind.input does not exist" or "client.tailwind.sources names a path that does not exist".
- A component made by app.define renders in a shadow root. Put app.page first in its sheets, as the scaffolds' todo-app does, so the stylesheet that the document links reaches it.
Asset hashing and pwa data
The build stages static files and declared public files, and gives each a content-hashed name such as index.a1b2c3d4e5f6.html in the public dist. The copy rewrites every textual cross-reference.
server = {
preserve_public = { "%.well%-known" },
},
client = {
pwa = {
title = "My App",
name = "My App",
description = "...",
theme_color = "#262626",
background_color = "#262626",
transforms = {
js = build.minify_js,
css = build.minify_css,
html = lp.minify_html,
},
},
},
Details
- The manifest iterates until it converges.
- A quoted name of a client.stable file stays plain.
- Since santoku-make 7.6.0, a client.unhashed file ships under its own name only, and references to it stay plain.
- Since santoku-make 7.7.0, a file in a subdirectory that names a sibling by its bare name gets the sibling's hashed name.
- An example is the admin/tool.js loader that fetches "tool.wasm". So a page under client/bin/admin needs no client.unhashed entry.
- The mapping is saved as hash-manifest.lua and reaches templates as hashed().
- hashed() emits a placeholder resolved from the converged manifest. So every shipped file's name is the hash of the bytes it ships.
- A pwa block, if you add one, is free-form data that santoku-make doesn't interpret.
- Nothing in the engine reads a pwa block.
- A pwa block is one place to keep the values that your configure hook and templates pass to the santoku.web.pwa helpers. The minification transforms are among them.
- server.preserve_public protects paths like .well-known from the dist rebuild.
- Since santoku-make 9.0.0, the hash step renames new files into place and prunes old ones after the reload, so a rebuild causes no 404.
Shipped bytes
toku build writes name.br beside every hashed public file, every client.stable copy and the sitemap.xml file. Each .br is santoku-brotli at quality 11, in text mode for text files.
return {
env = {
name = "my-app",
version = "0.0.1-1",
minify = { lua = true, c = true, html = true },
},
}
http {
brotli on;
brotli_static on;
}
Details
- A .br ships only when it's smaller than the file.
- png, jpg, jpeg, gif, webp, avif, woff, woff2, br, gz, zst, zip, mp3, mp4, webm and ogg files get no .br.
- nginx serves the .br files only with brotli_static on. The web example's res/server/nginx.mustache sets it.
- Every .png in the hashed set goes through santoku.zlib.png's optimize before hashing. So the hashed name covers the optimized bytes.
- The build logs [png] rel: before -> after B with the encoding it chose.
- The env's compress-cache holds both results by sha256, and the build prunes entries no file used.
- minify.html = true minifies every static .html and .htm file with lp.minify_html.
- minify = true turns minify.html on. Since santoku-make 7.7.0, so does a web project with no minify key.
- Web-profile C compiles with -DNDEBUG: the Lua runtime, the kept stdlib, and each rock's wasm build in the build environment.
- Node-profile test builds keep their asserts.
More descriptor keys
The code lists the rest of the keys santoku-make reads, each with what it changes. This site's own make.common.lua sets minify.lua and client.lua_runtime.
minify.lua = true santoku-lpeg's minify_lua with fields and shake on
minify.lua = { ... } minify_lua options, such as { fields = false, shake = false }
minify.c = true drop C module registrations the chunk and pre_js never name
client.lua_runtime = true keep parser, hook and names in the page's Lua
client.lua_runtime = { parser = true, hook = false, names = true }
parser: keep the parser under minify.chunk = "bytecode",
so the page can load Lua source at runtime
hook: keep the debug library and its hooks
names: keep function and variable names in error messages
trace: append a stack traceback to every string error
lua_runtime the same table at the top level, for a lib's wasm specs
client.unhashed = { "sw.js" } public files that ship under their own names, keep plain
references and skip the PWA precache
client.generated = { "lib/x.lua" } client files the configure hook writes: templates
depend on them, and the stale-file prune keeps them
luarocks.env_vars = { K = "v" } passed to luarocks make for the build and test trees
test.luarocks.env_vars the test tree only; test.wasm. and test.native. narrow it
build.luarocks.env_vars the build tree only; build.wasm. and build.native. narrow it
test.env_vars = { K = "v" } exported by the generated run.sh before the specs run
test.env_scripts = { "env.sh" } sourced by run.sh, in order, before the specs run
server.run_env_vars, server.run_env_scripts
the same pair for the server's run.sh under toku start
Details
- Since santoku-make 7.7.0, a web project with no minify key gets { lua = true, chunk = "smallest", c = true, html = true }.
- minify = true means the same.
- minify = false is the debug build: https://santoku.dev/santoku-make#santoku-make--the-debug-build
- A minify table changes only the keys it names. So minify = { c = false } keeps Lua and HTML minified.
- While minify is unset, a library's wasm specs and a web project's client specs stay unminified.
- minify.c also drops the TK_JS_ASM snippets of the C functions it removes.
The debug build since santoku-make 7.7.0 with santoku-bundle 3.3.0
minify = false builds the page for debugging. The web scaffolds set it in make.lua and set minify = true in make.prod.lua. The code lists the parts of the build it changes.
Lua chunk source, one chunk per module named after its path, so an error
reads "my_app/boom.lua:4:" instead of "[string "bundle"]:51:"
Lua runtime lua_runtime names and trace on, unless client.lua_runtime is set:
"attempt to index field 'missing'" and a stack traceback in
every string error, including errors raised in timers and actions
wasm keeps the name section (5 KB brotli here), so the console shows
C function names such as luaD_call instead of wasm-function[77]
glue bundle.js ships unminified (2 KB brotli here), with its own
function names in JS frames
C assert "Assertion failed: expr (file: function: line)" in the console,
abort and "abort()" for abort, in every build: the message costs bytes
only in modules that call assert or abort
Details
| Workload | Default | minify = false |
|---|---|---|
| web example with a C module, brotli sizes of bundle.js plus bundle.wasm | 69.1 KB | 94.5 KB |
Stable names, link checks, sitemaps
client.stable lists public files that also ship under their own unhashed names, for URLs that other sites link to. client.check_links checks links, and client.sitemap writes sitemap.xml.
client = {
stable = { "feed.xml", "press-kit.zip" },
check_links = { allow = { "^/api/" } },
sitemap = "https://example.com",
},
client = {
sitemap = {
site = "https://example.com",
lastmod = function (url) return url == "/docs" and "2026-10-15" or nil end,
},
},
Details
- Each client.stable file must be in the hash manifest.
- client.check_links = true fails the build when a shipped page links to a page or asset that doesn't exist.
- check_links = { allow = { ... } } takes Lua patterns for links to let through.
- check_links also fails a link to #id when the target page has no element with that id.
- check_links also checks src= references, and skips anything inside <code>.
- client.sitemap = "https://example.com" writes sitemap.xml for that site and ships it under its own name.
- Write the site with no trailing slash, since each page URL starts with /.
- The table form { site = ..., lastmod = fn } adds a lastmod wherever fn(url) returns a YYYY-MM-DD date.
- A page's href="/feed.xml" to a stable file keeps the plain name, and hashed("feed.xml") gives the hashed copy.
santoku.make.site
llms.txt headers in nginx
headers(meta) returns the response headers that advertise the same files, as { name, value } pairs. Pass them to the nginx mustache template and write each one as an add_header line inside the page's location.
<%
local str = require("santoku.string")
local err = require("santoku.error")
local headers = {}
for _, h in ipairs(require("santoku.make.site").headers({ llms = "/llms.txt" })) do
err.assert(not str.find(h[2], "'", 1, true), "a header value can't hold a single quote", h[2])
headers[#headers + 1] = { name = h[1], value = h[2] }
end
return require("santoku.mustache")(readfile("res/server/nginx.mustache"), {
partials = { pages = readfile("res/server/nginx/pages.mustache") },
})({
nginx = nginx.nginx,
pages = { { url = "/", file = hashed("index.568b57e86a93.html"), headers = headers } },
})
%>
{{#pages}}
location = {{{url}}} {
limit_except GET { deny all; }
try_files /{{{file}}} =404;
add_header Cache-Control 'private, max-age=60';
{{#headers}}
add_header {{{name}}} '{{{value}}}' always;
{{/headers}}
}
{{/pages}}
Details
- Link carries markdown as alternate, llms as describedby and llms-txt, and llms_full as llms-full-txt.
- X-Llms-Txt carries llms.
- nginx drops every server-level add_header in a location that sets its own.
- The scaffold's page locations set Cache-Control, so emit the lines inside each page's location.
- The template quotes each value in single quotes, so the driver rejects a value that holds one.
- List llms.txt in client.stable, so it keeps its URL.
- The code shows server/nginx.tk.conf, then the pages loop in res/server/nginx/pages.mustache.
Pages, sitemap and check_links
client.sitemap and client.check_links call these functions after hashing, and a configure hook can call them too. pages(manifest) maps the hash manifest's HTML entries to URLs.
local site = require("santoku.make.site")
local manifest = {
["index.568b57e86a93.html"] = "index.0123456789ab.html",
["docs/index.html"] = "docs/index.0123456789ab.html",
["about.html"] = "about.0123456789ab.html",
["app.js"] = "app.0123456789ab.js",
}
local pages = site.pages(manifest)
print(pages["/"], pages["/docs"], pages["/about.html"], pages["/app.js"])
print(site.sitemap("https://example.com", manifest, function (url)
return url == "/docs" and "2026-10-15" or nil
end))
Details
- index.html maps to /, docs/index.html to /docs, and about.html stays /about.html.
- sitemap(site, manifest, lastmod) returns the sitemap XML with URLs sorted. It raises on a lastmod that isn't YYYY-MM-DD.
- check_links(opts) takes public_dir, manifest, stable and allow.
- check_links raises link check failed on the first dead reference, and returns the pages table.
- In the code, the first print shows index.0123456789ab.html, docs/index.0123456789ab.html, about.0123456789ab.html and nil. app.js isn't a page.
- The sitemap lists / and /about.html, then /docs with <lastmod>2026-10-15</lastmod>.
Serving
The server config
The engine renders your server/nginx.tk.conf into nginx.conf and a foreground variant. The render context holds your nginx block, the module and Lua paths, and the hashed() lookup.
<%
return require("santoku.mustache")(readfile("res/server/nginx.mustache"), {
partials = { pages = readfile("res/server/nginx/pages.mustache") },
})({
nginx = nginx.nginx,
openresty_dir = openresty_dir,
lua_package_path = lua_package_path,
lua_package_cpath = lua_package_cpath,
index = hashed("index.568b57e86a93.html"),
})
%>
Details
- The context merges your nginx block with daemon, pid and log settings.
- The context also holds the resolved module paths, and lua_package_path and cpath for the installed lua_modules.
- The scaffolds keep the nginx directives in res/server/nginx.mustache.
- Their server/nginx.tk.conf is one block. It builds a flat context with the hashed names, and renders the mustache file with santoku.mustache.
- From santoku-make 9.1.0, the build fails when a require("name") in a *_by_lua_block names no module under the server dist.
- The web example passes its page routes as the pages partial, res/server/nginx/pages.mustache.
- The pages partial is the one file that differs between the web and pwa examples.
- The block's readfile calls are recorded as dependencies. So an edit to either mustache file re-renders nginx.conf.
Worker count at start since santoku-make 7.10.0
With nginx.workers unset, run.sh counts the CPUs the server may use each time it starts, and passes worker_processes to openresty with -g. A built image then sizes itself to the host that runs it.
nginx = { domain = env.var("DOMAIN", "localhost"), workers = env.var("WORKERS", nil) },
{{#nginx.workers}}
worker_processes {{{nginx.workers}}};
{{/nginx.workers}}
$ toku build
$ taskset -c 0,1 build/default/dist/run.sh --fg
$ docker run --cpus 2 my-app
$ WORKERS=4 toku build
Details
- On Linux the count is the CPUs in the process's affinity mask, capped by the cgroup v2 quota in cpu.max, and at least 1.
- run.sh reads cpu.max in the process's own cgroup and every parent, and takes the smallest quota. A fractional quota rounds up, so a quota of 1.5 CPUs gives 2 workers.
- nginx's worker_processes auto counts every online CPU and ignores taskset and container limits. On a 32-core host, auto started 32 workers under taskset -c 8-15.
- On macOS, run.sh counts hw.activecpu. On any other system it stops with "run.sh can't count the CPUs on <system>; set nginx.workers in make.lua".
- run.sh --check passes the same -g, so the openresty -t check reads the config that the server runs.
- Set nginx.workers to pin a count. The template then renders worker_processes, and run.sh passes no -g.
- So a template renders worker_processes only while nginx.workers is set, as the scaffolds' nginx.mustache does. A config that sets it anyway while nginx.workers is unset fails openresty -t with "worker_processes" directive is duplicate.
- The scaffolds read nginx.workers from WORKERS at build time, so WORKERS=4 toku build pins 4 workers.
The web loop
toku build assembles the environment's one tree: server rock installed, pages bundled, assets hashed. toku start runs the server, toku test runs every suite, and toku stop signals the pid files.
$ toku build
$ toku start
serving http://127.0.0.1:8080/
build up to date 0.1s
start server 0.3s
log build/default/toku.log
$ toku test
$ toku test server --show-logs
$ toku stop
stop server stopped 0.3s
log build/default/toku.log
$ toku build --env prod
$ toku start --env prod --fg
$ toku clean --client --wasm
$ toku clean --all --dry-run
Details
- toku build and toku start without --iterate run no specs and no luacheck.
- build, start and stop take no --test flag. toku test builds the same dist.
- client.test dependencies and flags reach only the client spec tree.
- toku build reloads a running server when the build changes the dist.
- Since santoku-make 8.0.1, toku build with no server running runs no openresty, so it opens no certificate or other file that nginx.conf names.
- openresty -t checks the rendered config before toku start or toku test starts a server, and before a reload.
- A config that openresty rejects stops the command with "the server would not start: openresty -t rejects <path>" and openresty's text. Before a reload the message opens "the server was not reloaded", and the running workers keep the old config.
- Since santoku-make 8.0.1, a pid file names a running server only when ps -o args= for that pid holds "-p <dir> -c <conf>".
- <dir> is the dist or build/<env>/test/run. <conf> is nginx.conf for server.pid and nginx-fg.conf for temp/server.pid.
- toku signals nothing for any other pid file.
- When ps -o args= -p PID fails (Debian: procps), toku start and toku test stop.
- toku start runs the generated run.sh in the dist dir. It runs in the background with a server.pid, or in the foreground with --fg.
- toku start on a running server rebuilds and reloads it.
- toku start --iterate starts the server and the spec server, then on each change rebuilds, reloads and reruns the specs, or only the spec file you edited. Ctrl-C stops all three.
- Since santoku-make 7.9.0, toku start prints the URL on a serving line once the server is up.
- toku test runs the client specs under the managed node and the root specs as a lib project. Then it starts the test server from build/<env>/test/run and runs the server suite against it.
- A server that toku start runs stays up.
- toku test server runs the server suite alone.
- toku start's server listens on 8080 and the test server on 8081, so toku start and toku test can run at once. The templates read the port as nginx.port.
- The server specs get the test port as PORT. They also get DIST_DIR and RUN_DIR, the absolute paths of build/<env>/dist and build/<env>/test/run.
- When the port is taken, the start stops with "server failed to start" and nginx's emerg line, such as "bind() to 0.0.0.0:8080 failed (98: Address already in use)".
Examples
Projects that toku init creates with this rock. The examples page shows their files.
- A library with a command: A Lua rock with a C module, a sqlite store behind migrations, and an argparse command.
toku init --example lib my-lib