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.

Examples

small toku projects that toku init --example creates, each demonstrating one capability with its files shown in full

Each example is a small toku project that santoku-make ships and toku init --example creates. Each one demonstrates one capability and names the rocks it exercises.

Details
  • toku init --example NAME my-project creates the project from the example NAME, and toku init with no --example creates the lib example.
  • --example needs santoku-cli 8.0.0 and santoku-make 13.0.0.
  • An unknown name lists every example with its summary and fails before init writes anything.
  • The site build runs the real toku init for every example, and this page shows the files it writes. Each rock's tab links the examples that use it.
  • santoku-make's suite runs every example's toku test before a release.
  • The project initializer adds --license, --copyright and --comments to each example: https://santoku.dev/santoku-cli/init

A JSON API

An OpenResty server with no frontend, over a server-side sqlite database.

apiserversqlite

Rocks: santoku-restysantoku-sqlitesantoku-migratesantoku-http

toku init --example api my-api
.gitignore
build/
lua_modules/
*.swp
*.swo
.tmp*
make.lua
local env = require("santoku.env")

return {
  env = {

    name = "my-api",
    version = "0.0.1-1",

    dependencies = { "lua == 5.1" },

    server = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-sqlite >= 9.0.0, < 10.0.0",
        "santoku-migrate >= 0.1.3, < 0.2.0",
        "santoku-resty >= 5.0.0, < 6.0.0",
      },
      test = { dependencies = { "santoku-http >= 4.0.1, < 5.0.0", "santoku-socket >= 6.0.1, < 7.0.0" } },
    },

    nginx = { domain = env.var("DOMAIN", "localhost"), workers = env.var("WORKERS", nil) },

  },
}
res/server/migrations/0.0.1.sql
create table items (
  id integer primary key,
  name text not null,
  created_at real not null default (unixepoch('now', 'subsec'))
);
res/server/nginx.mustache
daemon {{{nginx.daemon}}};
pid {{{nginx.pid}}};
{{#nginx.workers}}
worker_processes {{{nginx.workers}}};
{{/nginx.workers}}
error_log {{{nginx.error_log}}} info;
env DB_FILE;
env DB_WRITER;

events {}

http {

  include {{{openresty_dir}}}/nginx/conf/mime.types;

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

  brotli on;
  brotli_comp_level 6;
  brotli_min_length 1000;
  brotli_types text/plain text/css text/xml text/javascript application/json
    application/javascript application/xml application/wasm image/svg+xml;

  access_log {{{nginx.access_log}}};

  client_max_body_size 1m;
  client_body_buffer_size 1m;
  client_body_temp_path temp/client_body;
  proxy_temp_path temp/proxy;
  fastcgi_temp_path temp/fastcgi;
  uwsgi_temp_path temp/uwsgi;
  scgi_temp_path temp/scgi;

  lua_package_path "{{{lua_package_path}}}";
  lua_package_cpath "{{{lua_package_cpath}}}";

  lua_shared_dict sqlite_retry 1m;

  init_by_lua_block { require("my_api.web.init") }
  init_worker_by_lua_block { require("my_api.web.init_worker") }

  server {

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

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

  }
}
server/lib/my_api/migrations.tk.lua
<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
server/lib/my_api/store.lua
return function (db)

  local list = db.getter([[
    select json_object('items', coalesce((
      select json_group_array(json_object('id', id, 'name', name, 'created_at', created_at))
      from (select id, name, created_at from items order by id desc limit ?1)
    ), json_array()))
  ]])

  return {

    read = {
      list_items = function (limit)
        return list(limit or 50)
      end,
    },

    write = { create_item = db.inserter("insert into items (name) values (?1)") },

  }

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

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

require("my_api.web.db")
server/lib/my_api/web/init_worker.lua
require("santoku.resty.sqlite").init_worker()
server/lib/my_api/web/items.lua
local err = require("santoku.error")
local json = require("cjson")
local status = require("my_api.web.status")
local db = require("my_api.web.db")

return function ()
  ngx.header.content_type = "application/json"

  if ngx.req.get_method() ~= "POST" then
    return ngx.say(db.list_items(tonumber(ngx.req.get_uri_args().limit)))
  end

  ngx.req.read_body()
  local ok, req = err.pcall(json.decode, ngx.req.get_body_data() or "")
  if not ok or type(req) ~= "table" or type(req.name) ~= "string" or #req.name == 0 or #req.name > 200 then
    ngx.status = 400
    ngx.say(json.encode({ error = "bad_body" }))
    return ngx.exit(400)
  end

  local created, id = db.create_item(req.name)
  ngx.status = status(created, id)
  ngx.say(json.encode(created and { id = id } or { status = id }))
end
server/lib/my_api/web/status.lua
local err = require("santoku.error")
local str = require("santoku.string")

local codes = { full = 503, timeout = 504, lost = 504, failed = 500, committed = 200 }

return function (value, e)
  if value ~= nil then
    return 200
  end
  if type(e) ~= "string" then
    return 404
  end
  return err.assert(codes[str.match(e, "^%a+")], "a write returned an unknown status", e), e
end
server/nginx.tk.conf
<%
  return require("santoku.mustache")(readfile("res/server/nginx.mustache"))({
    nginx = nginx.nginx,
    openresty_dir = openresty_dir,
    lua_package_path = lua_package_path,
    lua_package_cpath = lua_package_cpath,
  })
%>
server/test/spec/db_file.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local str = require("santoku.string")

test("toku test's server keeps its database in its own run directory, so toku start's holds no spec rows", function ()
  local run = env.var("RUN_DIR")
  err.assert(str.endswith(run, "/test/run"), "the specs' server runs outside build/<env>/test/run", run)
  err.assert(
    fs.exists(fs.join(run, "data", "my_api.db")),
    "the specs' server opened no database of its own",
    run
  )
end)
server/test/spec/my_api.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local str = require("santoku.string")
local sqlite_db = require("santoku.sqlite.db")
local sqlite = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local http = require("santoku.http")(require("santoku.socket"))

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

test("items endpoint", function ()
  local url = "http://127.0.0.1:" .. env.var("PORT") .. "/items"
  local ok, resp = http.post(url, {
    headers = { ["content-type"] = "application/json" },
    body = "{\"name\":\"from the spec\"}",
  })
  err.assert(ok and str.find(resp.body(), "\"id\""), "create failed", resp.status)
  ok, resp = http.get(url)
  err.assert(ok and str.find(resp.body(), "from the spec", 1, true), "posted row listed", resp.status)
  ok, resp = http.post(url, { body = "{}" })
  err.assert(not ok and resp.status == 400, "a body without a name is rejected", resp.status)
end)
server/test/spec/status.lua
local test = require("santoku.test")
local err = require("santoku.error")
local status = require("my_api.web.status")

test("a result picks the HTTP status, and nil with no write status is 404", function ()
  for _, c in ipairs({
    { 200, 7 },
    { 404, nil },
    { 200, false },
    { 503, nil, "full" },
    { 504, nil, "timeout" },
    { 504, nil, "lost" },
    { 500, nil, "failed: UNIQUE constraint failed: items.id" },
    { 200, nil, "committed: result exceeds slot_size" },
  }) do
    local code, e = status(c[2], c[3])
    err.assert(code == c[1], "wrong status", c[3], code)
    err.assert(e == c[3], "the status message is lost", c[3], e)
  end
  err.assert(not err.pcall(status, nil, "odd"), "an unknown status passes")
end)

A browser script

A command that loads a page in headless Chromium, reads its title and links, and saves a screenshot.

libclibrowser

Rocks: santoku-cdp

toku init --example browser my-browser
.gitignore
build/
lua_modules/
*.swp
*.swo
bin/my-browser.lua
#!/usr/bin/env lua

local argparse = require("argparse")
local fs = require("santoku.fs")
local visit = require("my_browser")

local parser = argparse():name(
  "my_browser"
):description("Load a page in headless Chromium and print its title and links")

parser:argument("url", "Page to load")
parser:option("--screenshot", "Write a PNG of the whole page to this file"):args("1"):count("0-1")

local args = parser:parse()
local found = visit(args.url)

print(found.title)
for i = 1, #found.links do
  print("  " .. found.links[i])
end

if args.screenshot then
  fs.writefile(args.screenshot, found.png)
end
lib/my_browser.lua
local err = require("santoku.error")
local run = require("santoku.cdp.run")
local page = require("santoku.cdp.page")

return function (url)
  local browser = run.launch()
  local ok, out = err.pcall(function ()
    local s = page.open({ port = browser.port })
    page.navigate(s, url)
    local found = {
      title = page.eval(s, "document.title"),
      links = page.eval(s, "Array.from(document.querySelectorAll('a[href]'), function (a) { return a.href })"),
      png = page.screenshot(s, { full = true }),
    }
    s.close()
    return found
  end)
  run.stop(browser)
  if not ok then
    err.error(out)
  end
  return out
end
make.lua
local release = require("santoku.make.release")

local env = {
  name = "my-browser",
  version = "0.0.1-1",
  wasm = false,
  dependencies = { "lua == 5.1", "santoku >= 6.0.0, < 7.0.0", "santoku-cdp >= 0.5.1, < 0.6.0", "argparse >= 0.7.1-1" },
  test = { dependencies = { "santoku-fs >= 2.6.1, < 3.0.0" } },
}

env.homepage = "https://YOUR-HOMEPAGE.example/" .. env.name
env.release = { push = release.git_push(), host = release.gh_release(), registry = release.luarocks_upload() }

return { type = "lib", env = env }
test/spec/my_browser.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local fs = require("santoku.fs")
local str = require("santoku.string")
local visit = require("my_browser")

test("my_browser", function ()

  local html = fs.tmpname() .. ".html"
  fs.writefile(
    html,
    "<!doctype html><title>Two links</title>"
      .. "<a href=\"https://santoku.dev/\">santoku</a> <a href=\"https://luarocks.org/\">luarocks</a>"
  )

  test("visit reads the title and links and takes a screenshot", function ()
    local found = visit("file://" .. html)
    err.assert(found.title == "Two links", "the title", found.title)
    err.assert(#found.links == 2 and found.links[1] == "https://santoku.dev/", "the links", #found.links)
    err.assert(str.sub(found.png, 1, 8) == "\137PNG\r\n\26\n", "the screenshot is a PNG")
  end)

  test("visit raises when the page doesn't load", function ()
    local ok, e = err.pcall(visit, "http://127.0.0.1:9/")
    err.assert(not ok and str.find(tostring(e), "cdp: navigate failed", 1, true), "a failed load passed", e)
  end)

  fs.rm(html)

end)

A text classifier

A command that trains a kernel ridge text classifier on a small built-in dataset and labels new text.

libclilearnclassify

Rocks: santoku-learnsantoku-matrix

toku init --example classify my-classify
.gitignore
build/
lua_modules/
*.swp
*.swo
bin/my-classify.lua
#!/usr/bin/env lua

local argparse = require("argparse")
local str = require("santoku.string")
local classifier = require("my_classify")
local data = require("my_classify.data")

local parser = argparse():name(
  "my_classify"
):description("Label each text as weather or sports, with a classifier trained on the built-in dataset")

parser:argument("texts", "Texts to label"):args("+")

local args = parser:parse()
local model = classifier.train(data)
local labels = model.classify(args.texts)

for i = 1, #args.texts do
  print(str.format("%s: %s", labels[i], args.texts[i]))
end

model.destroy()
lib/my_classify.lua
local err = require("santoku.error")
local arr = require("santoku.array")
local krr = require("santoku.learn.krr")
local csr = require("santoku.csr")
local ivec = require("santoku.ivec")

local function classifier (model, labels)
  return {
    classify = function (texts)
      local ks = model:predict({ text = { texts = texts } })
      local out = {}
      for i = 1, #texts do
        out[i] = labels[ks:get(i - 1) + 1]
      end
      return out
    end,
    persist = function (dir)
      model:persist(dir)
    end,
    destroy = function ()
      model:destroy()
    end,
  }
end

local function train (data)
  local index = {}
  for i = 1, #data.labels do
    index[data.labels[i]] = i - 1
  end
  local texts, offsets, neighbors = {}, ivec.create({ 0 }), ivec.create()
  for i = 1, #data.rows do
    local text, label = data.rows[i][1], data.rows[i][2]
    texts[i] = text
    neighbors:push(err.assert(index[label], "a row has a label outside data.labels", label))
    offsets:push(i)
  end
  local model = krr.fit({
    inputs = { text = { texts = texts } },
    targets = csr.create({ offsets = offsets, neighbors = neighbors, n_cols = #data.labels }),
    n_labels = #data.labels,
    blocks = { { input = "text", view = { "words" }, ngram = { words = { 1, 1 } } } },
    knobs = {
      inv_nu = { def = 1.3 },
      cosine_w = { def = 0.25 },
      gamma = { def = 0.5 },
      constant = { def = 0.1 },
      lambda = { def = 1e-2 },
      scales = { def = { 1 } },
    },
    n_landmarks = 16,
    search_landmarks = 8,
    search_trials = 0,
  })
  return classifier(model, arr.copy({}, data.labels))
end

local function load (dir, labels)
  return classifier(krr.load(dir), labels)
end

return { train = train, load = load }
lib/my_classify/data.lua
return {
  labels = { "weather", "sports" },
  rows = {
    { "rain is coming this afternoon", "weather" },
    { "a cold front brings snow tonight", "weather" },
    { "sunny skies and a light breeze", "weather" },
    { "heavy rain and thunder by evening", "weather" },
    { "the forecast calls for fog at dawn", "weather" },
    { "a warm and humid day with showers", "weather" },
    { "strong winds and hail expected", "weather" },
    { "clear skies tonight, frost by morning", "weather" },
    { "the striker scored twice in the final", "sports" },
    { "the home team won the match", "sports" },
    { "a late goal sealed the cup", "sports" },
    { "the coach praised the defense after the game", "sports" },
    { "the pitcher threw a perfect inning", "sports" },
    { "fans cheered as the team took the title", "sports" },
    { "the referee awarded a penalty kick", "sports" },
    { "she won the race by two seconds", "sports" },
  },
}
make.lua
local release = require("santoku.make.release")

local env = {
  name = "my-classify",
  version = "0.0.1-1",
  dependencies = {
    "lua == 5.1",
    "santoku >= 6.0.0, < 7.0.0",
    "santoku-learn >= 20.0.1, < 21.0.0",
    "santoku-matrix >= 6.5.3, < 7.0.0",
    "argparse >= 0.7.1-1",
  },
  test = { dependencies = { "santoku-fs >= 2.6.1, < 3.0.0" } },
}

env.homepage = "https://YOUR-HOMEPAGE.example/" .. env.name
env.release = { push = release.git_push(), host = release.gh_release(), registry = release.luarocks_upload() }

return { type = "lib", env = env }
test/spec/my_classify.lua
local test = require("santoku.test")
local err = require("santoku.error")
local arr = require("santoku.array")
local fs = require("santoku.fs")
local classifier = require("my_classify")
local data = require("my_classify.data")

test("my_classify", function ()

  local model = classifier.train(data)
  local held_out = {
    { "thunder showers this evening", "weather" },
    { "snow and wind tonight", "weather" },
    { "the team scored a goal", "sports" },
    { "the final match", "sports" },
  }
  local texts = arr.mapped(held_out, function (r)
    return r[1]
  end)

  test("the model labels every training row it saw", function ()
    local rows = arr.mapped(data.rows, function (r)
      return r[1]
    end)
    local got = model.classify(rows)
    for i = 1, #data.rows do
      err.assert(got[i] == data.rows[i][2], "a training row got the wrong label", data.rows[i][1], got[i])
    end
  end)

  test("the model labels text it never saw", function ()
    local got = model.classify(texts)
    for i = 1, #held_out do
      err.assert(got[i] == held_out[i][2], "a held-out text got the wrong label", held_out[i][1], got[i])
    end
  end)

  test("a persisted model loads and labels the same", function ()
    local dir = fs.tmpname() .. ".krr"
    model.persist(dir)
    local loaded = classifier.load(dir, data.labels)
    err.assert(
      arr.concat(loaded.classify(texts), " ") == arr.concat(model.classify(texts), " "),
      "the loaded model labels differently"
    )
    loaded.destroy()
    require("santoku.learn.krr").rm(dir)
  end)

  model.destroy()

end)

A library with a command

A Lua rock with a C module, a sqlite store behind migrations, and an argparse command.

libclisqlitec

Rocks: santokusantoku-sqlitesantoku-migratesantoku-make

toku init --example lib my-lib
.gitignore
build/
lua_modules/
*.swp
*.swo
bin/my-lib.lua
#!/usr/bin/env lua

local argparse = require("argparse")
local err = require("santoku.error")
local str = require("santoku.string")
local db_mod = require("my_lib")

local parser = argparse():name("my-lib"):description("CLI for managing random numbers in a SQLite database")

parser:option("--sqlite", "SQLite database file"):args("1"):count("1")

parser:command("add", "Add a new random number")

local delete_cmd = parser:command("delete", "Delete a number by ID")
delete_cmd:argument("id", "ID of the number to delete"):convert(tonumber)

local update_cmd = parser:command("update", "Regenerate a random number by ID")
update_cmd:argument("id", "ID of the number to update"):convert(tonumber)

parser:command("list", "List all numbers (id, value)")

local args = parser:parse()
local db = db_mod(args.sqlite)

if args["add"] then
  local id = err.checkok(db.add())
  local row = db.get(id)
  print(str.format("Added: id=%d value=%d", row.id, row.value))

elseif args["delete"] then
  if err.checkok(db.delete(args.id)) then
    print(str.format("Deleted: id=%d", args.id))
  else
    print(str.format("Not found: id=%d", args.id))
  end

elseif args["update"] then
  local found, value = err.checkok(db.update(args.id))
  if found then
    print(str.format("Updated: id=%d value=%d", args.id, value))
  else
    print(str.format("Not found: id=%d", args.id))
  end

elseif args["list"] then
  local numbers = db.list()
  if #numbers == 0 then
    print("No numbers in database")
  else
    for _, row in ipairs(numbers) do
      print(str.format("id=%d value=%d", row.id, row.value))
    end
  end
end
lib/my_lib.lua
local err = require("santoku.error")
local sqlite_db = require("santoku.sqlite.db")
local sqlite = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local migrations = require("my_lib.migrations")
local store = require("my_lib.store")

return function (db_file)
  local db = sqlite(err.assert(sqlite_db.open(db_file)))
  db.exec("pragma journal_mode = WAL")
  db.exec("pragma synchronous = NORMAL")
  db.exec("pragma busy_timeout = 5000")
  migrate(db, migrations)
  return db.store(store), db
end
lib/my_lib/capi.c
#include <santoku/lua/utils.h>

static inline int get_random (lua_State *L)
{
  tk_fast_bind(L);
  lua_pushinteger(L, (lua_Integer)tk_fast_random());
  return 1;
}

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

int luaopen_my_lib_capi (lua_State *L)
{
  lua_newtable(L);
  luaL_register(L, NULL, fns);
  return 1;
}
lib/my_lib/migrations.tk.lua
<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
lib/my_lib/store.lua
local capi = require("my_lib.capi")

return function (db)

  local insert = db.inserter("insert into numbers (value) values (?1)")
  local delete = db.runner("delete from numbers where id = ?1")
  local update = db.runner("update numbers set value = ?1 where id = ?2")
  local list = db.all("select id, value from numbers order by id", true)
  local get = db.getter("select id, value from numbers where id = ?1", true)

  return {

    read = { list = list, get = get },

    write = {

      add = function ()
        return insert(capi.random())
      end,

      delete = function (id)
        if not get(id) then
          return false
        end
        delete(id)
        return true
      end,

      update = function (id)
        if not get(id) then
          return false
        end
        local value = capi.random()
        update(value, id)
        return true, value
      end,

    },

  }

end
make.lua
local rock = require("santoku.make.rock")
local release = require("santoku.make.release")

local env = {
  name = "my-lib",
  version = "0.0.1-1",
  cflags = { "-Wall", "-Wextra", rock.include("santoku") },
  dependencies = {
    "lua == 5.1",
    "santoku >= 6.0.0, < 7.0.0",
    "santoku-sqlite >= 9.0.0, < 10.0.0",
    "santoku-migrate >= 0.1.3, < 0.2.0",
    "argparse >= 0.7.1-1",
  },
  test = { dependencies = { "santoku-fs >= 2.6.1, < 3.0.0" } },
}

env.homepage = "https://YOUR-HOMEPAGE.example/" .. env.name
env.release = { push = release.git_push(), host = release.gh_release(), registry = release.luarocks_upload() }

return { type = "lib", env = env }
res/lib/migrations/0.0.1.sql
create table numbers (
  id integer primary key autoincrement,
  value integer not null
);
test/spec/my_lib.lua
local test = require("santoku.test")
local err = require("santoku.error")
local fs = require("santoku.fs")
local str = require("santoku.string")

test("my_lib", function ()

  local db_file = fs.tmpname()
  local s, db = require("my_lib")(db_file)

  test("add", function ()
    local id = err.checkok(s.add())
    local row = s.get(id)
    err.assert(id == 1 and row.id == 1, "first id is 1", id)
    err.assert(type(row.value) == "number", "value is a number", row.value)
  end)

  test("list", function ()
    err.assert(#s.list() == 1, "one row")
  end)

  test("update", function ()
    local found, value = err.checkok(s.update(1))
    err.assert(found and s.get(1).value == value, "update stores the new value")
    err.assert(not err.checkok(s.update(999)), "update misses an unknown id")
  end)

  test("delete", function ()
    err.assert(err.checkok(s.delete(1)), "delete finds the row")
    err.assert(not err.checkok(s.delete(1)), "delete misses a removed row")
    err.assert(#s.list() == 0, "list is empty")
  end)

  test("a write that fails rolls back and says so", function ()
    db.exec("create trigger no_insert before insert on numbers begin select raise(abort, 'no insert'); end")
    local ok, e = s.add()
    err.assert(ok == nil and str.find(e, "failed: ", 1, true) == 1, "a failed add reports failed", ok, e)
    err.assert(#s.list() == 0, "the failed add left a row")
    db.exec("drop trigger no_insert")
  end)

  db.close()
  fs.rm(db_file)

end)

An offline web app

The web app with its data in sqlite in the browser, synced to the server, and a service worker so it boots offline.

webwasmpwaofflinesqlitesync

Rocks: santoku-websantoku-sqlitesantoku-migratesantoku-restysantoku-cdp

toku init --example pwa my-app
.gitignore
build/
lua_modules/
*.swp
*.swo
.tmp*
client/bin/bundle.lua
local js = require("santoku.web.js")

if not js.self.document then
  return require("my_app.db")
end

require("my_app.main")
client/lib/my_app/async.lua
return require("santoku.async")(require("santoku.web.async"))
client/lib/my_app/core.lua
local err = require("santoku.error")
local js = require("santoku.web.js")
local val = require("santoku.web.val")
local async = require("my_app.async")
local http = require("santoku.web.http")
local proxy = require("santoku.web.sqlite.proxy")

local restart = {}
local db, ready = proxy(js.document:querySelector("script[src]").src, restart)

local sw = js.navigator.serviceWorker
local updating = sw.controller ~= nil

local function activate (w)
  if w and updating then
    w:postMessage(val.pack({ type = "skip_waiting" }))
  end
end

sw:addEventListener("controllerchange", function ()
  if updating then
    js.location:reload()
  end
end)

async.spawn(function ()
  local ok, reg = sw:register("/serviceworker.js"):await()
  err.assert(ok, "service worker registration failed", reg)
  activate(reg.waiting)
  reg:addEventListener("updatefound", function ()
    local w = reg.installing
    w:addEventListener("statechange", function ()
      if w.state == "installed" then
        activate(w)
      end
    end)
  end)
end)

local core = setmetatable({}, {
  __index = function (_, name)
    return function (...)
      return err.checkok(db[name](...))
    end
  end,
})

core.ready = ready

core.on_restart = function (fn)
  restart.on_restart = fn
  return function ()
    if restart.on_restart == fn then
      restart.on_restart = nil
    end
  end
end

core.sync = function ()
  repeat
    local body, seq = core.outbox()
    local ok, resp = http.post("/api/sync", { headers = { ["content-type"] = "application/json" }, body = body })
    if not ok then
      core.set("last_result", "failed (" .. resp.status .. ")")
      return false
    end
  until not core.inbox(resp.body(), seq)
  return true
end

return core
client/lib/my_app/db.lua
local worker = require("santoku.web.sqlite.worker")
local migrate = require("santoku.migrate")
local migrations = require("my_app.migrations")
local store = require("my_app.store")
local sync = require("my_app.sync")

return worker("/my_app.db", function (db)
  db.exec("pragma journal_mode = TRUNCATE")
  db.exec("pragma synchronous = NORMAL")
  migrate(db, migrations)
  return db.store(function (d)
    return sync(d, store(d))
  end, {
    raise = true,
  })
end)
client/lib/my_app/main.lua
require("santoku.web.app").define(require("my_app.todos")(require("my_app.sync_view")))
client/lib/my_app/migrations.tk.lua
<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
client/lib/my_app/store.lua
local arr = require("santoku.array")
local str = require("santoku.string")

local function parse (body)
  local tags, seen = {}, {}
  for tag in str.gmatch(body, "#([%w-]+)") do
    tag = str.lower(tag)
    if not seen[tag] then
      seen[tag] = true
      arr.push(tags, tag)
    end
  end
  return str.trim((str.gsub(body, "%s*#[%w-]+", ""))), tags
end

local defaults = { show_done = "1", sort = "oldest" }

local function todo (r)
  local text, tags = parse(r.body)
  return { id = r.id, text = text, tags = tags, done = r.done == 1 }
end

return function (db)

  local rows = db.all([[
    select id, body, done from todos t
    where (?1 is null or id = ?1)
      and (?2 is null or exists (select 1 from todos_tags g where g.todo_id = t.id and g.tag = ?2))
      and (?3 = 1 or done = 0)
    order by case when ?4 = 1 then -rowid else rowid end
  ]], true)

  local get_setting = db.getter("select value from settings where key = ?1")
  local set_setting = db.runner("insert or replace into settings (key, value) values (?1, ?2)")

  local function setting (key)
    return get_setting(key) or defaults[key]
  end

  local tag_counts = db.all([[
    select tag, count(*) as n from todos_tags group by tag order by n desc, tag limit ?1
  ]], true)

  local drop_done = db.runner("delete from todos where done = 1")

  local drop_orphan_tags = db.runner([[
    delete from todos_tags where todo_id not in (select id from todos)
  ]])

  local insert = db.getter([[
    insert into todos (id, body, done) values (lower(hex(randomblob(8))), ?1, 0)
    returning id
  ]])

  local flip = db.runner("update todos set done = 1 - done where id = ?1")
  local drop = db.runner("delete from todos where id = ?1")
  local live_body = db.getter("select body from todos where id = ?1")
  local drop_tags = db.runner("delete from todos_tags where todo_id = ?1")
  local add_tag = db.runner("insert or ignore into todos_tags (todo_id, tag) values (?1, ?2)")

  local function retag (id)
    drop_tags(id)
    local body = live_body(id)
    if body then
      local _, tags = parse(body)
      for i = 1, #tags do
        add_tag(id, tags[i])
      end
    end
  end

  local function get (id)
    return todo(rows(id, nil, 1, 0)[1])
  end

  local export = db.getter([[
    select coalesce(json_group_array(json_object(
      'id', t.id, 'body', t.body, 'done', t.done,
      'tags', (select json_group_array(tag) from todos_tags g where g.todo_id = t.id)
    )), '[]') from todos t
  ]])

  local function list (tag)
    local show_done = setting("show_done") == "1" and 1 or 0
    local newest = setting("sort") == "newest" and 1 or 0
    return arr.map(rows(nil, tag, show_done, newest), todo)
  end

  local function settings ()
    return { show_done = setting("show_done") == "1", sort = setting("sort") }
  end

  local function view (tag, all)
    return { settings = settings(), todos = list(tag), top = tag_counts(10), all = all and tag_counts(-1) or nil }
  end

  return {

    read = {

      list = list,

      settings = settings,

      view = view,

      tags = function (limit)
        return tag_counts(limit)
      end,

      export = function ()
        return export()
      end,

    },

    write = {

      add = function (body)
        local id = insert(body)
        retag(id)
        return get(id), tag_counts(10)
      end,

      toggle = function (id)
        flip(id)
        return get(id)
      end,

      remove = function (id)
        drop(id)
        drop_tags(id)
        return tag_counts(10)
      end,

      set = function (key, value, tag)
        set_setting(key, value)
        return list(tag)
      end,

      clear_done = function (tag, all)
        drop_done()
        drop_orphan_tags()
        return view(tag, all)
      end,

      retag = retag,

    },

  }

end
client/lib/my_app/sync.lua
local cjson = require("cjson")
local sync = require("santoku.sqlite.sync")
local utc = require("santoku.utc")

local defaults = { auto_sync = "0", interval = "30", last_result = "" }

return function (db, s)

  local engine = sync.create(db, {
    space = "my_app",
    tables = {
      todos = {
        pk = { "id" },
        columns = { "body", "done" },
        after_apply = function (_, rid)
          s.write.retag(cjson.decode(rid)[1])
        end,
      },
    },
  })

  local get_setting = db.getter("select value from settings where key = ?1")

  local function setting (key)
    return get_setting(key) or defaults[key]
  end

  local synced_at = db.getter("select cast(value as real) from settings where key = 'last_sync'")

  local function last_sync ()
    local t = synced_at()
    return t and utc.format(t, "%Y-%m-%d %H:%M:%S", true) or ""
  end

  local set_last_sync = db.runner([[
    insert or replace into settings (key, value) values ('last_sync', unixepoch('now', 'subsec'))
  ]])

  local stale = db.getter([[
    select coalesce(unixepoch('now', 'subsec') - (select cast(value as real) from settings where key = 'last_sync'), ?1) >= ?1
  ]])

  local function server ()
    return engine.peers()[1]
  end

  local function unsent (peer)
    return engine.seq() > (peer and peer.served or 0)
  end

  s.read.outbox = function ()
    local peer = server()
    local push = peer and unsent(peer) and engine.push(peer.peer) or nil
    return cjson.encode({ request = engine.request(peer and peer.peer), push = push }), push and push.seq or 0
  end

  s.read.sync_due = function ()
    return unsent(server()) or stale(tonumber(setting("interval"))) == 1
  end

  s.read.sync_settings = function ()
    return {
      auto_sync = setting("auto_sync") == "1",
      interval = setting("interval"),
      last_sync = last_sync(),
      last_result = setting("last_result"),
    }
  end

  s.write.inbox = function (body, seq)
    local res = cjson.decode(body)
    engine.ack(res.replica, seq)
    engine.apply(res)
    set_last_sync()
    s.write.set("last_result", "ok")
    return res.more or unsent(server())
  end

  return s

end
client/lib/my_app/sync_view.lua
local js = require("santoku.web.js")
local dom = require("santoku.web.dom")
local async = require("my_app.async")
local core = require("my_app.core")

local function load (s)
  for k, v in pairs(core.sync_settings()) do
    s[k] = v
  end
end

local function sync (s, c)
  s.sync_status = "syncing..."
  c.commit()
  local ok = core.sync()
  if ok then
    local v = core.view(s.tag, s.view == "tags")
    s.todos, s.top, s.all = v.todos, v.top, v.all
  end
  local st = core.sync_settings()
  s.last_sync, s.last_result = st.last_sync, st.last_result
  s.sync_status = ok and "synced" or s.last_result
end

local pending = async.latest(function (s, c, ms)
  while s.auto_sync do
    async.sleep(ms)
    sync(s, c)
    c.commit()
    ms = tonumber(s.interval) * 1000
  end
end)

local function schedule (s, c, ms)
  if not s.auto_sync then
    return pending.cancel()
  end
  async.spawn(function ()
    pending(s, c, ms or tonumber(s.interval) * 1000)
  end)
end

local function wake (s, c)
  if s.auto_sync and js.document.visibilityState == "visible" and core.sync_due() then
    schedule(s, c, 0)
  end
end

local function route (s, sub)
  s.tab = sub == "" and "todos" or sub
end

local function changed (s, c)
  schedule(s, c)
end

local function wrote (s, c)
  schedule(s, c, 1500)
end

local function started (s, c)
  c.on_stop(function ()
    pending.cancel()
  end)
  schedule(s, c, core.sync_due() and 0 or nil)
  c.on_stop(dom.listen("window", "online", function ()
    wake(s, c)
  end))
  c.on_stop(dom.listen("document", "visibilitychange", function ()
    wake(s, c)
  end))
end

return {
  state = { sync_status = "" },
  route = route,
  load = load,
  changed = changed,
  wrote = wrote,
  started = started,
  actions = {
    sync = function (s, c)
      sync(s, c)
      schedule(s, c)
    end,
  },
}
client/lib/my_app/templates.tk.lua
<%
  local loader = require("santoku.web.mustache.loader")
  return loader.templates("res/client", { readfile = readfile })
%>
client/lib/my_app/todos.lua
local arr = require("santoku.array")
local str = require("santoku.string")
local tbl = require("santoku.table")
local js = require("santoku.web.js")
local val = require("santoku.web.val")
local dom = require("santoku.web.dom")
local rt = require("santoku.web.async")
local async = require("my_app.async")
local history = require("santoku.web.history")
local router = require("santoku.web.router")
local app = require("santoku.web.app")
local core = require("my_app.core")
local tpl = require("my_app.templates")

return function (extra)

  local routes = router({ history = history({ mode = "query", batch = true }), scroll = true })
  local page = routes.scope("page", { primary = true })
  local filter = routes.scope("todos", { keys = { "tag" } })

  local function route (s)
    local top, sub = str.match(page.path(), "^/([^/]*)/?([^/]*)")
    s.view = top == "" and "list" or top
    s.tag = filter.path().tag
    if extra.route then
      extra.route(s, sub)
    end
  end

  local function apply (s, v)
    for k, x in pairs(v.settings) do
      s[k] = x
    end
    s.todos = v.todos
    s.top = v.top
    s.all = v.all
  end

  local function fetch (s)
    apply(s, core.view(s.tag, s.view == "tags"))
  end

  local function refresh (s)
    fetch(s)
    if extra.load then
      extra.load(s)
    end
  end

  local function reload (s)
    if s.view ~= "settings" then
      fetch(s)
    end
  end

  local function first_key (list)
    return (list.each()())
  end

  local function wrote (s, c)
    if extra.wrote then
      extra.wrote(s, c)
    end
  end

  return {

    tag = "todo-app",

    template = tpl.todo_app,

    sheets = { app.page },

    events = { "change" },

    state = function ()
      local s = tbl.assign({ status = "Loading..." }, extra.state or {})
      route(s)
      return s
    end,

    start = function (s, c)
      local function failed (_, ev)
        s.error = str.match(tostring(ev.reason or ev.message), "[^\n]*")
        c.commit()
      end
      c.on_stop(dom.listen("window", "unhandledrejection", failed))
      c.on_stop(dom.listen("window", "error", failed))
      local ok, e = core.ready:await()
      if not ok then
        s.status = "Couldn't start: " .. tostring(e)
        return
      end
      refresh(s)
      s.status = nil
      if extra.started then
        extra.started(s, c)
      end
      page.links(c.root)
      local function changed ()
        return rt.task(function ()
          route(s)
          reload(s)
          c.commit()
        end)
      end
      c.on_stop(page.on_change(changed))
      c.on_stop(filter.on_change(changed))
      c.on_stop(core.on_restart(function ()
        async.spawn(function ()
          refresh(s)
          c.commit()
        end)
      end))
      routes.wait()()
    end,

    actions = tbl.assign({

      add = function (s, c, ev)
        local body = ev.form.body
        if body ~= "" then
          dom.reset(ev.el)
          c.commit()
          local todo, top = core.add(body)
          if not s.tag or arr.includes(todo.tags, s.tag) then
            s.todos.insert(todo, s.sort == "newest" and first_key(s.todos) or nil)
          end
          s.top = top
          wrote(s, c)
        end
      end,

      toggle = function (s, c, ev)
        local todo = core.toggle(ev.key)
        if todo.done and not s.show_done then
          s.todos.remove(ev.key)
        else
          s.todos.update(ev.key, todo)
        end
        wrote(s, c)
      end,

      remove = function (s, c, ev)
        s.top = core.remove(ev.key)
        s.todos.remove(ev.key)
        wrote(s, c)
      end,

      set = function (s, c, ev)
        local name = ev.data.name
        local checkbox = ev.checked ~= nil
        if checkbox then
          s[name] = ev.checked
        else
          s[name] = ev.value
        end
        local todos = core.set(name, checkbox and (ev.checked and "1" or "0") or ev.value, s.tag)
        if name == "show_done" or name == "sort" then
          s.todos = todos
        elseif extra.changed then
          extra.changed(s, c, name)
        end
      end,

      ask_clear = function (s)
        s.confirm = true
      end,

      cancel_clear = function (s)
        s.confirm = false
      end,

      clear_done = function (s, c)
        s.confirm = false
        apply(s, core.clear_done(s.tag, s.view == "tags"))
        wrote(s, c)
      end,

      export = function ()
        local blob = js.Blob:new(val.pack({ core.export() }), val.pack({ type = "application/json" }))
        local url = js.URL:createObjectURL(blob)
        local a = js.document:createElement("a")
        a.href = url
        a.download = "my_app-export.json"
        a:click()
        js.URL:revokeObjectURL(url)
      end,

    }, extra.actions or {}),

  }

end
client/static/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="data:,">
    <title>my_app</title>
    <style>
      body { font-family: sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
      todo-app { display: block; }
      #error { color: #b00; }
      #composer { display: flex; gap: 0.5rem; }
      #new-todo { flex: 1; padding: 0.4rem; }
      #todo-list { list-style: none; padding: 0; }
      #todo-list li { display: flex; gap: 0.5rem; align-items: center; padding: 0.3rem 0; }
      #todo-list li span { flex: 1; }
      #todo-list li.done span { text-decoration: line-through; color: #888; }
      .tag { color: #06c; font-style: normal; }
      #toolbar { display: flex; gap: 0.5rem; align-items: center; margin-top: 1rem; }
      header { display: flex; justify-content: space-between; align-items: baseline; }
      h1 a { color: inherit; text-decoration: none; }
      #top-tags, #settings label { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
      #views > section { display: none; }
      #views[data-view=list] #list, #views[data-view=tags] #tags, #views[data-view=settings] #settings { display: block; }
    </style>
  </head>
  <body>
    <todo-app></todo-app>
    <script src="/bundle.606e713e9c93.js"></script>
  </body>
</html>
client/static/serviceworker.tk.js
<%
  local sw = require("santoku.web.pwa.sw")
  return sw({
    nonce = hashed("index.568b57e86a93.html") .. "-" .. hashed("bundle.606e713e9c93.js") .. "-" .. hashed("bundle.f4c2e4986607.wasm"),
    precache = {
      "/", "/tags", "/settings", "/settings/todos", "/settings/sync",
      hashed("bundle.606e713e9c93.js"), hashed("bundle.f4c2e4986607.wasm"),
    },
    no_cache = { "^/api/" },
  })
%>
client/test/spec/my_app.lua
local test = require("santoku.test")
local err = require("santoku.error")
local str = require("santoku.string")
local cjson = require("cjson")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local engine = require("santoku.sqlite.sync")
local migrate = require("santoku.migrate")
local migrations = require("my_app.migrations")
local store = require("my_app.store")
local sync = require("my_app.sync")

local function server ()
  local db = sql(err.assert(sqlite.open_memory()))
  db.exec("create table todos (id text primary key, body text not null, done integer not null default 0)")
  local e = engine.create(db, {
    space = "my_app",
    tables = { todos = { pk = { "id" }, columns = { "body", "done" } } },
  })
  return {
    serve = function (body)
      local msg = cjson.decode(body)
      if msg.push then
        e.apply(msg.push)
      end
      return cjson.encode(e.respond(msg.request, msg.push))
    end,
    body = db.getter("select body from todos where id = ?1"),
    done = db.getter("select done from todos where id = ?1"),
    count = db.getter("select count(*) from todos"),
    add = db.runner("insert into todos (id, body) values (?1, ?2)"),
    drop = db.runner("delete from todos where id = ?1"),
  }
end

local function round (s, srv)
  local steps = 0
  local more
  repeat
    steps = steps + 1
    local body, seq = s.outbox()
    more = s.inbox(srv.serve(body), seq)
  until not more or steps > 10
  err.assert(steps <= 10, "the sync never settled")
  return steps
end

test("the store the worker serves syncs", function ()

  local db = sql(err.assert(sqlite.open_memory()))
  migrate(db, migrations)
  local s = db.store(function (d)
    return sync(d, store(d))
  end, {
    raise = true,
  })
  local srv = server()

  local a = s.add("one #home")
  s.add("two")
  s.toggle(a.id)
  local b = s.add("three")
  s.remove(b.id)

  test("local writes make a sync due", function ()
    err.assert(s.sync_due(), "three writes and no sync, yet nothing is due")
  end)

  test("a sync pushes local rows and pulls the server's, tagged", function ()
    srv.add("aaaaaaaaaaaaaaaa", "from #server")
    round(s, srv)
    err.assert(srv.count() == 3 and srv.body(a.id) == "one #home", "the server misses local rows", srv.count())
    err.assert(#s.list("server") == 1, "incoming rows are tagged")
    err.assert(not s.sync_due(), "a sync is due right after one")
    local st = s.sync_settings()
    err.assert(
      str.match(st.last_sync, "^%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d$") and st.last_result == "ok",
      "last sync",
      st.last_sync
    )
  end)

  test("an incoming delete drops the row and its tags", function ()
    srv.drop("aaaaaaaaaaaaaaaa")
    round(s, srv)
    err.assert(#s.list("server") == 0 and #s.tags(-1) == 1, "the deleted row kept its tags")
  end)

  test("an edit made while a sync is in flight goes out on the next step", function ()
    local c = s.add("sent #flight")
    local body, seq = s.outbox()
    s.toggle(c.id)
    err.assert(s.inbox(srv.serve(body), seq) == true, "the in-flight edit didn't ask for another step")
    round(s, srv)
    err.assert(srv.done(c.id) == 1 and not s.sync_due(), "the in-flight edit never reached the server")
  end)

  test("an inbox that fails leaves the sync state alone", function ()
    s.add("kept #pending")
    local before, seq = s.outbox()
    local last_sync = s.sync_settings().last_sync
    local ok, e = err.pcall(s.inbox, "not json", seq)
    err.assert(ok == false and e ~= nil, "a broken response raises", ok, e)
    local x, y = cjson.decode(before), cjson.decode((s.outbox()))
    err.assert(
      x.push.seq == y.push.seq and #x.push.changes == #y.push.changes and x.request.cursor == y.request.cursor
        and s.sync_due() and s.sync_settings().last_sync == last_sync,
      "the failed inbox wrote"
    )
  end)

  db.close()

end)
client/test/spec/store.lua
local test = require("santoku.test")
local err = require("santoku.error")
local str = require("santoku.string")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local migrations = require("my_app.migrations")
local store = require("my_app.store")

test("the store", function ()

  local db = sql(err.assert(sqlite.open_memory()))
  migrate(db, migrations)
  local s = db.store(store)

  test("add returns the row the page renders", function ()
    local t = err.checkok(s.add("write docs #Docs #docs"))
    err.assert(#t.id == 16, "16-char hex id", t.id)
    err.assert(t.text == "write docs", "tags leave the text", t.text)
    err.assert(#t.tags == 1 and t.tags[1] == "docs", "tags are lowercased and unique")
    err.assert(t.done == false, "a new row is open")
  end)

  test("list, filter, toggle, remove", function ()
    local id = s.list()[1].id
    s.add("buy milk")
    local rows = s.list()
    err.assert(#rows == 2 and rows[2].text == "buy milk", "oldest first")
    err.assert(#s.list("docs") == 1 and s.list("docs")[1].id == id, "tag filter")
    err.assert(err.checkok(s.toggle(id)).done == true, "toggle returns the updated row")
    s.remove(id)
    err.assert(#s.list() == 1 and #s.list("docs") == 0, "remove drops the row and its tags")
  end)

  test("settings order the list, and tags count live todos", function ()
    local a = err.checkok(s.add("one #home"))
    s.add("two #home #work")
    s.toggle(a.id)
    local top = s.tags(10)
    err.assert(top[1].tag == "home" and top[1].n == 2 and top[2].tag == "work", "most used first")
    s.set("show_done", "0")
    err.assert(#s.list("home") == 1, "hide done")
    s.set("show_done", "1")
    s.set("sort", "newest")
    err.assert(s.list()[1].text == "two", "newest first")
    err.assert(s.settings().sort == "newest" and s.settings().show_done == true, "settings read back")
    s.clear_done()
    err.assert(#s.list("home") == 1 and s.tags(10)[1].n == 1, "clear done drops done rows and their tags")
  end)

  test("view and the writes return what the page renders next", function ()
    local t, top = err.checkok(s.add("five #view"))
    err.assert(t.text == "five" and #top >= 1, "add returns the row and the top tags")
    local v = s.view("view", true)
    err.assert(#v.todos == 1 and v.todos[1].id == t.id, "view filters by tag")
    err.assert(v.settings.sort and #v.top >= 1 and #v.all >= #v.top, "view carries settings and tags")
    err.assert(s.view().all == nil, "all tags only when asked")
    err.assert(#err.checkok(s.set("show_done", "1", "view")) == 1, "set returns the list it reorders")
    err.assert(
      #err.checkok(s.set("other", "x", "view")) == 1,
      "every setting returns the list, so the api never answers a write with nil"
    )
    local left = err.checkok(s.remove(t.id))
    for i = 1, #left do
      err.assert(left[i].tag ~= "view", "remove returns the tags without the row")
    end
    err.assert(err.checkok(s.clear_done()).todos, "clear done returns a fresh view")
  end)

  test("retag rebuilds a row's tags from its body", function ()
    local t = err.checkok(s.add("three #a"))
    db.exec(str.format("update todos set body = 'three #b' where id = '%s'", t.id))
    s.retag(t.id)
    err.assert(#s.list("a") == 0 and #s.list("b") == 1, "retag reads the stored body")
  end)

  test("a write that fails rolls back and says so", function ()
    local before = #s.list()
    local ok, e = s.add(nil)
    err.assert(ok == nil and str.find(e, "failed: ", 1, true) == 1, "a failed add reports failed", ok, e)
    err.assert(#s.list() == before, "the failed add left a row", #s.list(), before)
  end)

  db.close()

end)
make.common.lua
local env = require("santoku.env")

return {
  env = {

    name = "my-app",
    version = "0.0.1-1",

    dependencies = { "lua == 5.1" },

    build = { dependencies = { "santoku-web >= 13.0.0, < 14.0.0" } },

    server = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-sqlite >= 9.0.0, < 10.0.0",
        "santoku-migrate >= 0.1.3, < 0.2.0",
        "santoku-resty >= 5.0.0, < 6.0.0",
      },
      test = {
        dependencies = {
          "santoku-http >= 4.0.1, < 5.0.0",
          "santoku-socket >= 6.0.1, < 7.0.0",
          "santoku-cdp >= 0.5.1, < 0.6.0",
        },
      },
    },

    client = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-web >= 13.0.0, < 14.0.0",
        "santoku-sqlite >= 9.0.0, < 10.0.0",
        "santoku-migrate >= 0.1.3, < 0.2.0",
        "lua-cjson == 2.1.0.10-1",
      },
      stable = { "serviceworker.js" },
      check_links = true,
    },

    nginx = { domain = env.var("DOMAIN", "localhost"), workers = env.var("WORKERS", nil) },

  },
}
make.lua
local fs = require("santoku.fs")
local tbl = require("santoku.table")

return tbl.merge({ env = { minify = false } }, fs.runfile("make.common.lua"))
make.prod.lua
local fs = require("santoku.fs")
local tbl = require("santoku.table")

return tbl.merge({ env = { minify = true } }, fs.runfile("make.common.lua"))
res/client/migrations/0.0.1.sql
create table todos (
  id text primary key,
  body text not null,
  done integer not null default 0
);

create table settings (
  key text primary key,
  value text
);

create table todos_tags (
  todo_id text not null,
  tag text not null,
  primary key (todo_id, tag)
);

create index todos_tags_tag on todos_tags (tag);
res/client/partials/settings.mustache
<style>
  #settings-tabs nav { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
  #settings-tabs[data-tab=todos] #settings-sync, #settings-tabs[data-tab=sync] #settings-todos { display: none; }
  #settings-tabs[data-tab=todos] #tab-todos, #settings-tabs[data-tab=sync] #tab-sync { font-weight: bold; }
  #sync-status, #last-sync { color: #888; }
</style>
<div id="settings-tabs" data-tab="{{tab}}">
  <nav>
    <a id="tab-todos" href="/settings/todos">Todos</a>
    <a id="tab-sync" href="/settings/sync">Sync</a>
  </nav>
  <div id="settings-todos">
    {{> partials.todo_settings.mustache}}
  </div>
  <div id="settings-sync">
    <label><input id="auto-sync" type="checkbox" {{#auto_sync}}checked{{/auto_sync}} data-name="auto_sync" data-action="change:set"> Sync automatically</label>
    <label>Every
      <select id="interval" value="{{interval}}" data-name="interval" data-action="change:set">
        <option value="5">5 seconds</option>
        <option value="30">30 seconds</option>
        <option value="300">5 minutes</option>
      </select>
    </label>
    <button data-action="sync">Sync now</button>
    <p id="last-sync">Last sync: {{last_sync}}{{^last_sync}}never{{/last_sync}} {{last_result}}</p>
  </div>
</div>
res/client/partials/todo_settings.mustache
<label><input id="show-done" type="checkbox" {{#show_done}}checked{{/show_done}} data-name="show_done" data-action="change:set"> Show done</label>
<label>Order
  <select id="sort" value="{{sort}}" data-name="sort" data-action="change:set">
    <option value="oldest">Oldest first</option>
    <option value="newest">Newest first</option>
  </select>
</label>
{{^confirm}}
<button id="clear-done" data-action="ask_clear">Clear done</button>
{{/confirm}}
{{#confirm}}
<span id="confirm">Delete every done todo? <button data-action="clear_done">Yes</button> <button data-action="cancel_clear">No</button></span>
{{/confirm}}
res/client/partials/toolbar.mustache
<button data-action="sync">Sync</button>
<button data-action="export">Export</button>
<span id="sync-status">{{sync_status}}</span>
res/client/todo-app.html
<header>
  <h1><a href="/">my_app</a></h1>
  <a id="settings-link" href="/settings">Settings</a>
</header>
{{#error}}
  <p id="error">{{error}}</p>
{{/error}}
<p id="status">{{status}}</p>
{{^status}}
  <div id="views" data-view="{{view}}">
    <section id="list">
      <form id="composer" data-action="add">
        <input id="new-todo" name="body" autocomplete="off" placeholder="What needs doing? Use #tags">
        <button>Add</button>
      </form>
      <p id="top-tags">
        {{#top}}
          <a data-key="{{tag}}" href="/?tag={{tag}}">#{{tag}}</a>
        {{/top}}
        <a id="all-tags" href="/tags">view all</a>
      </p>
      {{#tag}}
        <p id="filter">Showing #{{tag}} <a href="/">all</a></p>
      {{/tag}}
      <ul id="todo-list">
        {{#todos}}
          <li data-key="{{id}}" class="{{#done}}done{{/done}}">
            <button data-action="toggle">{{#done}}undo{{/done}}{{^done}}done{{/done}}</button>
            <span>{{text}}</span>
            {{#tags}}<a class="tag" href="/?tag={{.}}">#{{.}}</a>{{/tags}}
            <button data-action="remove">x</button>
          </li>
        {{/todos}}
      </ul>
      {{^todos}}<p id="empty">Nothing yet.</p>{{/todos}}
      <div id="toolbar">
        {{> partials.toolbar.mustache}}
      </div>
    </section>
    <section id="tags">
      <h2>Tags</h2>
      <ul id="tag-list">
        {{#all}}
          <li data-key="{{tag}}"><a href="/?tag={{tag}}">#{{tag}}</a> {{n}}</li>
        {{/all}}
      </ul>
    </section>
    <section id="settings">
      {{> partials.settings.mustache}}
    </section>
  </div>
{{/status}}
res/server/migrations/0.0.1.sql
create table todos (
  id text primary key,
  body text not null,
  done integer not null default 0
);
res/server/nginx.mustache
daemon {{{nginx.daemon}}};
pid {{{nginx.pid}}};
{{#nginx.workers}}
worker_processes {{{nginx.workers}}};
{{/nginx.workers}}
error_log {{{nginx.error_log}}} info;
env DB_FILE;
env DB_WRITER;

events {}

http {

  include {{{openresty_dir}}}/nginx/conf/mime.types;

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

  brotli on;
  brotli_static on;
  brotli_comp_level 6;
  brotli_min_length 1000;
  brotli_types text/plain text/css text/xml text/javascript application/json
    application/javascript application/xml application/wasm image/svg+xml;

  access_log {{{nginx.access_log}}};

  client_max_body_size 1m;
  client_body_buffer_size 1m;
  client_body_temp_path temp/client_body;
  proxy_temp_path temp/proxy;
  fastcgi_temp_path temp/fastcgi;
  uwsgi_temp_path temp/uwsgi;
  scgi_temp_path temp/scgi;

  lua_package_path "{{{lua_package_path}}}";
  lua_package_cpath "{{{lua_package_cpath}}}";

  lua_shared_dict sqlite_retry 1m;

  init_by_lua_block { require("my_app.web.init") }
  init_worker_by_lua_block { require("my_app.web.init_worker") }

  server {

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

{{> pages}}
    location = /favicon.ico {
      access_log off;
      log_not_found off;
      return 204;
    }

    location ~ "^/api/[a-z_]+$" {
      limit_except POST { deny all; }
      content_by_lua_block { require("my_app.web.api")() }
    }

    location ~* "\.[a-f0-9]{12}\." {
      limit_except GET { deny all; }
      root public;
      expires 1y;
      add_header Cache-Control "public, immutable";
    }

  }
}
res/server/nginx/pages.mustache
    location ~ "^/(tags|settings(/todos|/sync)?)?$" {
      limit_except GET { deny all; }
      root public;
      try_files /{{{index}}} =404;
      add_header Cache-Control "no-cache";
    }

    location = /serviceworker.js {
      limit_except GET { deny all; }
      root public;
      add_header Cache-Control "no-cache";
    }

server/lib/my_app/migrations.tk.lua
<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
server/lib/my_app/store.lua
local cjson = require("cjson")
local sync = require("santoku.sqlite.sync")

return function (db)

  local engine = sync.create(db, {
    space = "my_app",
    tables = { todos = { pk = { "id" }, columns = { "body", "done" } } },
  })

  return {

    write = {
      sync = function (body)
        local msg = cjson.decode(body)
        if msg.push then
          engine.apply(msg.push)
        end
        local res = engine.respond(msg.request, msg.push)
        for _, k in ipairs({ "changes", "fetched" }) do
          if res[k] then
            setmetatable(res[k], cjson.array_mt)
          end
        end
        return cjson.encode(res)
      end,
    },

  }

end
server/lib/my_app/web/api.lua
local cjson = require("cjson")
local status = require("my_app.web.status")
local db = require("my_app.web.db")

return function ()
  if ngx.var.uri ~= "/api/sync" then
    return ngx.exit(ngx.HTTP_NOT_FOUND)
  end

  ngx.req.read_body()
  local ok, body = db.sync(ngx.req.get_body_data())
  ngx.status = status(ok, body)
  ngx.header.content_type = "application/json"
  ngx.say(ok and body or cjson.encode({ status = body }))
end
server/lib/my_app/web/db.lua
return require("santoku.resty.sqlite").store(require("my_app.store"))
server/lib/my_app/web/init.lua
local env = require("santoku.env")
local migrate = require("santoku.migrate")
local sqlite = require("santoku.resty.sqlite")
local migrations = require("my_app.migrations")

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

require("my_app.web.db")
server/lib/my_app/web/init_worker.lua
require("santoku.resty.sqlite").init_worker()
server/lib/my_app/web/status.lua
local err = require("santoku.error")
local str = require("santoku.string")

local codes = { full = 503, timeout = 504, lost = 504, failed = 500, committed = 200 }

return function (value, e)
  if value ~= nil then
    return 200
  end
  if type(e) ~= "string" then
    return 404
  end
  return err.assert(codes[str.match(e, "^%a+")], "a write returned an unknown status", e), e
end
server/nginx.tk.conf
<%
  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"),
  })
%>
server/test/res/browser.lua
local str = require("santoku.string")
local run = require("santoku.cdp.run")
local page = require("santoku.cdp.page")
local log = require("santoku.cdp.log")

local kinds = { "error: ", "exception: ", "netfail: ", "http " }

local function reported (line)
  for i = 1, #kinds do
    if str.sub(line, 1, #kinds[i]) == kinds[i] then
      return true
    end
  end
  return false
end

return function (defer, fn)
  local browser = run.launch()
  local drain, passed
  defer(function ()
    if drain and not passed then
      local lines = drain()
      local head = false
      for i = 1, #lines do
        if reported(lines[i]) then
          if not head then
            print("the page reported:")
            head = true
          end
          print(lines[i])
        end
      end
    end
    run.stop(browser)
  end)
  local s = page.open({ port = browser.port })
  drain = log.watch(s)
  fn(s, browser)
  passed = true
  s.close()
end
server/test/res/shadow.lua
local err = require("santoku.error")
local cjson = require("cjson")
local page = require("santoku.cdp.page")

return function (tag)

  local root = "document.querySelector(" .. cjson.encode(tag) .. ")?.shadowRoot"

  local function q (selector)
    return root .. "?.querySelector(" .. cjson.encode(selector) .. ")"
  end

  local function all (selector)
    return "[...(" .. root .. "?.querySelectorAll(" .. cjson.encode(selector) .. ") ?? [])]"
  end

  local function center (s, selector)
    local c = page.eval(
      s,
      "(() => { const e = " .. q(selector) .. ";"
        .. " if (!e) return false; e.scrollIntoView({ block: 'center', inline: 'center' });"
        .. " const r = e.getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2]; })()"
    )
    if not c then
      err.error("no element in " .. tag .. " matches", selector)
    end
    return c[1], c[2]
  end

  local function type_into (s, selector, value)
    local found = page.eval(
      s,
      "(() => { const e = " .. q(selector) .. ";"
        .. " if (!e) return false; e.focus(); return e.getRootNode().activeElement === e; })()"
    )
    if not found then
      err.error("no focusable element in " .. tag .. " matches", selector)
    end
    s.call("Input.insertText", { text = value })
  end

  return { q = q, all = all, center = center, type = type_into }

end
server/test/spec/db_file.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local str = require("santoku.string")

test("toku test's server keeps its database in its own run directory, so toku start's holds no spec rows", function ()
  local run = env.var("RUN_DIR")
  err.assert(str.endswith(run, "/test/run"), "the specs' server runs outside build/<env>/test/run", run)
  err.assert(
    fs.exists(fs.join(run, "data", "my_app.db")),
    "the specs' server opened no database of its own",
    run
  )
end)
server/test/spec/my_app.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local str = require("santoku.string")
local utc = require("santoku.utc")
local cjson = require("cjson")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local sync = require("santoku.sqlite.sync")
local http = require("santoku.http")(require("santoku.socket"))

local url = "http://127.0.0.1:" .. env.var("PORT") .. "/api/sync"

local function device ()
  local db = sql(err.assert(sqlite.open_memory()))
  db.exec("create table todos (id text primary key, body text not null, done integer not null default 0)")
  local e = sync.create(db, {
    space = "my_app",
    tables = { todos = { pk = { "id" }, columns = { "body", "done" } } },
  })
  local d = {
    add = db.runner("insert into todos (id, body) values (lower(hex(randomblob(8))) || ?1, ?1)"),
    body = db.getter("select body from todos where body = ?1"),
  }
  d.step = function ()
    local peer = e.peers()[1]
    local push = peer and e.push(peer.peer) or nil
    local ok, resp = http.post(url, {
      headers = { ["content-type"] = "application/json" },
      body = cjson.encode({ request = e.request(peer and peer.peer), push = push }),
    })
    err.assert(ok, "sync failed", resp.status)
    local body = resp.body()
    local res = cjson.decode(body)
    e.ack(res.replica, push and push.seq or 0)
    return res, e.apply(res), body
  end
  return d
end

local function carries (res, body)
  for _, c in ipairs(res.changes) do
    if c.vals and c.vals.body == body then
      return true
    end
  end
  return false
end

test("sync endpoint", function ()

  local mark = "spec" .. utc.time()

  test("a first request gets the server's replica and a cursor", function ()
    local res = device().step()
    err.assert(type(res.replica) == "string" and type(res.seq) == "number" and res.err == nil, "response", res.err)
  end)

  test("a pushed row reaches another device and never comes back to its sender", function ()
    local a, b = device(), device()
    a.step()
    a.add("pushed " .. mark)
    local res, stats = a.step()
    err.assert(not carries(res, "pushed " .. mark), "the sync that pushed the row carried it back")
    err.assert(stats.applied == 0, "the sender applied its own row back", stats.applied)
    err.assert(not carries(a.step(), "pushed " .. mark), "the next sync carried the row again")
    b.step()
    err.assert(b.body("pushed " .. mark), "the row never reached the other device")
    err.assert(res.err == nil, "the push failed", res.err)
  end)

  test("a device with nothing new to pull gets changes as a JSON array", function ()
    local d = device()
    repeat
      local pulled = d.step()
    until not pulled.more
    local res, _, body = d.step()
    err.assert(#res.changes == 0 and str.find(body, '"changes":[]', 1, true), "changes", body)
  end)

  test("a body that fails answers 500 with its status", function ()
    local ok, resp = http.post(url, { body = "not json" })
    err.assert(not ok and resp.status == 500, "expected 500", resp.status)
    local st = cjson.decode(resp.body()).status
    err.assert(str.find(st, "failed: ", 1, true) == 1, "the body names the failure", st)
  end)

  test("GET is rejected", function ()
    local ok, resp = http.get(url)
    err.assert(not ok and resp.status == 403, "expected 403", resp.status)
  end)

  test("other api names are not found", function ()
    local ok, resp = http.post(str.gsub(url, "sync$", "list"), { body = "[]" })
    err.assert(not ok and resp.status == 404, "expected 404", resp.status)
  end)

end)

test("pages revalidate, so the next load after a rebuild gets the new bundle", function ()
  for _, path in ipairs({ "/", "/tags", "/settings", "/settings/sync" }) do
    local ok, resp = http.get("http://127.0.0.1:" .. env.var("PORT") .. path)
    err.assert(ok, "page failed", path, resp.status)
    err.assert(resp.headers["cache-control"] == "no-cache", "page is cached", path, resp.headers["cache-control"])
  end
end)
server/test/spec/offline.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")

err.assert(
  env.var("TOKU_CHROMIUM", nil),
  "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it"
)

local cdp = require("santoku.cdp")
local page = require("santoku.cdp.page")
local browser = fs.runfile("test/res/browser.lua")
local shadow = fs.runfile("test/res/shadow.lua")("todo-app")

local loaded = shadow.q("#status") .. "?.textContent === '' && !!" .. shadow.q("#views")

local function offline (s, on)
  s.call("Network.enable")
  s.call("Network.setCacheDisabled", { cacheDisabled = on })
  s.call("Network.emulateNetworkConditions", {
    offline = on,
    latency = 0,
    downloadThroughput = -1,
    uploadThroughput = -1,
  })
end

local function worker (port)
  for _, t in ipairs(cdp.targets({ port = port })) do
    if t.type == "service_worker" then
      return cdp.connect(t.webSocketDebuggerUrl)
    end
  end
  err.error("no service worker target")
end

test("the app boots offline after a first visit", function (defer)
  browser(defer, function (s, launched)
    local base = "http://127.0.0.1:" .. env.var("PORT")
    page.navigate(s, base .. "/")
    page.wait_until(s, loaded)
    page.wait_until(s, "navigator.serviceWorker.ready.then(r => !!r.active && !!navigator.serviceWorker.controller)")
    local w = worker(launched.port)
    offline(w, true)
    offline(s, true)
    for _, path in ipairs({ "/", "/settings/sync", "/tags", "/?tag=x" }) do
      page.navigate(s, base .. path)
      page.wait_until(s, loaded)
    end
    w.close()
  end)
end)

test("a failed service worker registration shows on the page", function (defer)
  browser(defer, function (s)
    s.call("Page.addScriptToEvaluateOnNewDocument", {
      source = "navigator.serviceWorker.register = () => Promise.reject(new Error('register broke'));",
    })
    page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
    page.wait_until(
      s,
      "(t => t.includes('service worker registration failed') && t.includes('register broke'))(" .. shadow.q("#error")
        .. "?.textContent ?? '')"
    )
  end)
end)
server/test/spec/page.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local utc = require("santoku.utc")
local cjson = require("cjson")

err.assert(
  env.var("TOKU_CHROMIUM", nil),
  "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it"
)

local page = require("santoku.cdp.page")
local input = require("santoku.cdp.input")
local browser = fs.runfile("test/res/browser.lua")
local shadow = fs.runfile("test/res/shadow.lua")("todo-app")
local q = shadow.q

local function pick (s, value)
  page.eval(
    s,
    "(() => { const e = " .. q("#sort") .. "; e.value = " .. cjson.encode(value)
      .. "; e.dispatchEvent(new Event('change', { bubbles: true })); })()"
  )
end

local function latency (s, ms)
  s.call("Network.emulateNetworkConditions", {
    offline = false,
    latency = ms,
    downloadThroughput = -1,
    uploadThroughput = -1,
  })
end

local function early (s)
  local url = "http://127.0.0.1:" .. env.var("PORT") .. "/settings"
  local loaded = "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...' && !!" .. q("#sort")
  page.navigate(s, url)
  page.wait_until(s, loaded)
  local was = page.eval(s, q("#sort") .. ".value")
  local want = was == "newest" and "oldest" or "newest"
  s.call("Network.enable")
  latency(s, 300)
  page.navigate(s, url)
  page.wait_until(s, "!!" .. q("#sort") .. "?.offsetParent")
  pick(s, want)
  page.wait_until(s, loaded)
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 1000))")
  latency(s, 0)
  err.assert(page.eval(s, q("#sort") .. ".value") == want, "a setting changed as the page loads is lost", was, want)
  page.navigate(s, url)
  page.wait_until(s, loaded)
  err.assert(page.eval(s, q("#sort") .. ".value") == want, "a changed setting is lost on reload", was, want)
  pick(s, was)
  page.wait_until(
    s,
    "new Promise(r => setTimeout(() => r(" .. q("#sort") .. ".value === " .. cjson.encode(was) .. "), 1000))"
  )
end

local function flows (s)
  local text = "browser spec " .. utc.time()
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...'")

  shadow.type(s, "#new-todo", text .. " #spec")
  input.click(s, shadow.center(s, "#composer button"))
  local key = page.wait_until(
    s,
    q("#new-todo") .. ".value === '' && " .. shadow.all("#todo-list li") .. ".filter(li => li.textContent.includes("
      .. cjson.encode(text) .. ")).map(li => li.dataset.key)[0]"
  )
  local row = '#todo-list li[data-key="' .. key .. '"]'
  err.assert(page.eval(s, q(row .. " a.tag") .. ".getAttribute('href')") == "/?tag=spec", "tag link")
  local shown = page.eval(s, "(" .. q(row) .. ".textContent.match(/#spec\\b/g) || []).length")
  err.assert(shown == 1, "the row shows its tag more than once", shown)

  input.click(s, shadow.center(s, row .. ' [data-action="toggle"]'))
  page.wait_until(s, q(row) .. ".classList.contains('done')")

  input.click(s, shadow.center(s, row .. " a.tag"))
  page.wait_until(s, "location.search === '?tag=spec' && !!" .. q("#filter"))

  input.click(s, shadow.center(s, "#all-tags"))
  page.wait_until(s, "location.pathname === '/tags' && !!" .. q('#tag-list li[data-key="spec"]'))

  input.click(s, shadow.center(s, "#settings-link"))
  page.wait_until(s, "location.pathname === '/settings' && " .. q("#settings") .. ".offsetParent !== null")

  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/?tag=spec")
  page.wait_until(s, "!!" .. q(row))
  input.click(s, shadow.center(s, row .. ' [data-action="remove"]'))
  page.wait_until(s, "!" .. q(row))
end

local function scroll (s)
  local tag = "scroll" .. utc.time()
  local list = "http://127.0.0.1:" .. env.var("PORT") .. "/?tag=" .. tag
  local rows = shadow.all("#todo-list li") .. ".length"
  s.call("Emulation.setDeviceMetricsOverride", { width = 400, height = 300, deviceScaleFactor = 1, mobile = false })
  page.navigate(s, list)
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...' && !!" .. q("#new-todo"))
  for i = 1, 20 do
    shadow.type(s, "#new-todo", "scroll row " .. i .. " #" .. tag)
    page.eval(s, q("#composer button") .. ".click()")
    page.wait_until(s, q("#new-todo") .. ".value === '' && " .. rows .. " === " .. i)
  end
  page.eval(s, "window.scrollTo(0, document.documentElement.scrollHeight)")
  local y = page.eval(s, "window.scrollY")
  err.assert(y > 100, "the list doesn't scroll", y)
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 500))")
  page.eval(s, q("#settings-link") .. ".click()")
  page.wait_until(s, "location.pathname === '/settings' && " .. q("#settings") .. ".offsetParent !== null")
  page.eval(s, "history.back()")
  page.wait_until(s, "location.pathname === '/' && " .. rows .. " === 20")
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 500))")
  local back = page.eval(s, "window.scrollY")
  err.assert(back == y, "Back didn't restore the list's scroll position", y, back)
  s.call("Emulation.clearDeviceMetricsOverride")
end

local function failure (s)
  local export = '#toolbar [data-action="export"]'
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "!!" .. q(export) .. "?.offsetParent")
  err.assert(not page.eval(s, "!!" .. q("#error")), "the page shows an error before anything failed")
  page.eval(s, "(() => { URL.createObjectURL = () => { throw new Error('export broke'); }; })()")
  input.click(s, shadow.center(s, export))
  page.wait_until(s, "!!" .. q("#error") .. "?.textContent.includes('export broke')")
end

local function stops (s)
  s.call("Page.addScriptToEvaluateOnNewDocument", {
    source = [[
(() => {
  const live = new Map();
  const add = EventTarget.prototype.addEventListener;
  const remove = EventTarget.prototype.removeEventListener;
  const count = (target, type, d) => {
    if (target === window) live.set(type, (live.get(type) || 0) + d);
  };
  EventTarget.prototype.addEventListener = function (type, fn, o) {
    count(this, type, 1);
    return add.call(this, type, fn, o);
  };
  EventTarget.prototype.removeEventListener = function (type, fn, o) {
    count(this, type, -1);
    return remove.call(this, type, fn, o);
  };
  window.__listening = (type) => live.get(type) || 0;
})()
]],
  })
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...'")
  local before = {}
  for _, name in ipairs({ "error", "unhandledrejection" }) do
    before[name] = page.eval(s, "window.__listening(" .. cjson.encode(name) .. ")")
    err.assert(before[name] > 0, "todo-app listens for no window event of this type", name)
  end
  page.eval(s, "(() => { document.querySelector('todo-app').remove(); })()")
  for name, n in pairs(before) do
    local after = page.eval(s, "window.__listening(" .. cjson.encode(name) .. ")")
    err.assert(after == n - 1, "a removed todo-app keeps its window listener", name, n, after)
  end
end

test("the page", function (defer)
  browser(defer, function (s)
    early(s)
    flows(s)
    scroll(s)
    failure(s)
    stops(s)
  end)
end)
server/test/spec/status.lua
local test = require("santoku.test")
local err = require("santoku.error")
local status = require("my_app.web.status")

test("a result picks the HTTP status, and nil with no write status is 404", function ()
  for _, c in ipairs({
    { 200, 7 },
    { 404, nil },
    { 200, false },
    { 503, nil, "full" },
    { 504, nil, "timeout" },
    { 504, nil, "lost" },
    { 500, nil, "failed: UNIQUE constraint failed: items.id" },
    { 200, nil, "committed: result exceeds slot_size" },
  }) do
    local code, e = status(c[2], c[3])
    err.assert(code == c[1], "wrong status", c[3], code)
    err.assert(e == c[3], "the status message is lost", c[3], e)
  end
  err.assert(not err.pcall(status, nil, "odd"), "an unknown status passes")
end)
server/test/spec/sync_page.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")

err.assert(
  env.var("TOKU_CHROMIUM", nil),
  "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it"
)

local page = require("santoku.cdp.page")
local input = require("santoku.cdp.input")
local browser = fs.runfile("test/res/browser.lua")
local shadow = fs.runfile("test/res/shadow.lua")("todo-app")
local q = shadow.q

test("the sync tab syncs on demand and shows the time in the browser's zone", function (defer)
  browser(defer, function (s)
    s.call("Emulation.setTimezoneOverride", { timezoneId = "Asia/Kolkata" })
    page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/settings")
    page.wait_until(s, q("#settings") .. "?.offsetParent != null")
    input.click(s, shadow.center(s, "#tab-sync"))
    page.wait_until(s, "location.pathname === '/settings/sync' && " .. q("#auto-sync") .. ".offsetParent !== null")
    input.click(s, shadow.center(s, '#settings-sync [data-action="sync"]'))
    page.wait_until(s, q("#last-sync") .. ".textContent.trim().endsWith('ok')")
    local skew = page.eval(
      s,
      "(() => { const m = /(\\d+)-(\\d+)-(\\d+) (\\d+):(\\d+):(\\d+)/.exec(" .. q("#last-sync")
        .. ".textContent); return Math.round(Math.abs(Date.now()"
        .. " - new Date(m[1], m[2] - 1, m[3], m[4], m[5], m[6])) / 1000); })()"
    )
    err.assert(skew < 120, "the last sync time is off the browser's local time by seconds", skew)
  end)
end)

A command that runs under OpenResty

A Lua rock whose command and specs run under OpenResty's resty CLI and fetch URLs at once.

libcliresty

Rocks: santoku-restysantoku-http

toku init --example resty my-tool
.gitignore
build/
lua_modules/
*.swp
*.swo
bin/my-tool.lua
local arr = require("santoku.array")
local fs = require("santoku.fs")
local str = require("santoku.string")
local sys = require("santoku.system")

local urls = arr.copy({}, arg)

if #urls == 0 then
  fs.stderr:write("usage: my_tool URL...\n")
  sys.exit(2)
end

local fetcher = require("my_tool")(require("santoku.resty.async"), require("santoku.resty.socket"))

local failed = false
local results = fetcher.fetch_all(urls)
for i = 1, #results do
  local r = results[i]
  fs.stdout:write(str.format("%d %d %s\n", r.status, r.bytes, r.url))
  failed = failed or not r.ok
end

sys.exit(failed and 1 or 0)
lib/my_tool.lua
local async = require("santoku.async")
local http = require("santoku.http")

return function (rt, backend)

  local a = async(rt)
  local client = http(backend)

  local function fetch_all (urls)
    local out, left = {}, #urls
    for i = 1, #urls do
      a.spawn(function ()
        local ok, resp = client.get(urls[i])
        out[i] = { url = urls[i], ok = ok, status = resp.status, bytes = ok and #resp.body() or 0 }
        left = left - 1
      end)
    end
    while left > 0 do
      a.sleep(5)
    end
    return out
  end

  return { fetch_all = fetch_all }

end
make.lua
local release = require("santoku.make.release")

local env = {
  name = "my-tool",
  version = "0.0.1-1",
  wasm = false,
  dependencies = {
    "lua == 5.1",
    "santoku >= 6.0.0, < 7.0.0",
    "santoku-http >= 4.0.1, < 5.0.0",
    "santoku-resty >= 5.0.0, < 6.0.0",
  },
}

env.homepage = "https://YOUR-HOMEPAGE.example/" .. env.name
env.release = { push = release.git_push(), host = release.gh_release(), registry = release.luarocks_upload() }

return { type = "lib", env = env }
test/spec/my_tool.resty.lua
local test = require("santoku.test")
local err = require("santoku.error")

local rt = require("santoku.resty.async")

test("my_tool", function ()

  local backend = {
    sleep = rt.sleep,
    fetch = function (url)
      local ms = tonumber(url)
      rt.sleep(ms)
      return true, {
        status = 200,
        headers = {},
        ok = true,
        body = function ()
          return url
        end,
      }
    end,
  }

  local fetcher = require("my_tool")(rt, backend)

  test("fetch_all runs every request at once", function ()
    local t0 = rt.now()
    local out = fetcher.fetch_all({ "300", "100", "200" })
    local took = rt.now() - t0
    err.assert(#out == 3, "three results", #out)
    for i = 1, #out do
      err.assert(out[i].ok and out[i].status == 200, "each request answers 200", out[i].url)
    end
    err.assert(out[2].url == "100" and out[2].bytes == 3, "results keep the request order", out[2].url)
    err.assert(took >= 300 and took < 550, "three waits overlap", took)
  end)

end)

A web app

A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server.

webwasmserversqlite

Rocks: santoku-websantoku-restysantoku-sqlitesantoku-migratesantoku-cdp

toku init --example web my-app
.gitignore
build/
lua_modules/
*.swp
*.swo
.tmp*
client/bin/bundle.lua
require("my_app.main")
client/lib/my_app/async.lua
return require("santoku.async")(require("santoku.web.async"))
client/lib/my_app/core.lua
local cjson = require("cjson")
local arr = require("santoku.array")
local err = require("santoku.error")
local js = require("santoku.web.js")
local dom = require("santoku.web.dom")
local async = require("my_app.async")
local http = require("santoku.web.http")

local function request (name, ...)
  return http.post("/api/" .. name, {
    headers = { ["content-type"] = "application/json" },
    body = cjson.encode({ ... }),
  })
end

local function results (name, ok, resp)
  err.assert(ok, "api call failed", name, resp.status)
  return arr.spread(cjson.decode(resp.body()))
end

local viewing = async.latest(request)

return setmetatable({

  ready = js.Promise:resolve(),

  view = function (...)
    return results("view", viewing("view", ...))
  end,

  on_restart = function (fn)
    return dom.listen("window", "pageshow", function (_, ev)
      if ev.persisted then
        fn()
      end
    end)
  end,

}, {
  __index = function (_, name)
    return function (...)
      return results(name, request(name, ...))
    end
  end,
})
client/lib/my_app/main.lua
require("santoku.web.app").define(require("my_app.todos")({}))
client/lib/my_app/templates.tk.lua
<%
  local loader = require("santoku.web.mustache.loader")
  return loader.templates("res/client", { readfile = readfile })
%>
client/lib/my_app/todos.lua
local arr = require("santoku.array")
local str = require("santoku.string")
local tbl = require("santoku.table")
local js = require("santoku.web.js")
local val = require("santoku.web.val")
local dom = require("santoku.web.dom")
local rt = require("santoku.web.async")
local async = require("my_app.async")
local history = require("santoku.web.history")
local router = require("santoku.web.router")
local app = require("santoku.web.app")
local core = require("my_app.core")
local tpl = require("my_app.templates")

return function (extra)

  local routes = router({ history = history({ mode = "query", batch = true }), scroll = true })
  local page = routes.scope("page", { primary = true })
  local filter = routes.scope("todos", { keys = { "tag" } })

  local function route (s)
    local top, sub = str.match(page.path(), "^/([^/]*)/?([^/]*)")
    s.view = top == "" and "list" or top
    s.tag = filter.path().tag
    if extra.route then
      extra.route(s, sub)
    end
  end

  local function apply (s, v)
    for k, x in pairs(v.settings) do
      s[k] = x
    end
    s.todos = v.todos
    s.top = v.top
    s.all = v.all
  end

  local function fetch (s)
    apply(s, core.view(s.tag, s.view == "tags"))
  end

  local function refresh (s)
    fetch(s)
    if extra.load then
      extra.load(s)
    end
  end

  local function reload (s)
    if s.view ~= "settings" then
      fetch(s)
    end
  end

  local function first_key (list)
    return (list.each()())
  end

  local function wrote (s, c)
    if extra.wrote then
      extra.wrote(s, c)
    end
  end

  return {

    tag = "todo-app",

    template = tpl.todo_app,

    sheets = { app.page },

    events = { "change" },

    state = function ()
      local s = tbl.assign({ status = "Loading..." }, extra.state or {})
      route(s)
      return s
    end,

    start = function (s, c)
      local function failed (_, ev)
        s.error = str.match(tostring(ev.reason or ev.message), "[^\n]*")
        c.commit()
      end
      c.on_stop(dom.listen("window", "unhandledrejection", failed))
      c.on_stop(dom.listen("window", "error", failed))
      local ok, e = core.ready:await()
      if not ok then
        s.status = "Couldn't start: " .. tostring(e)
        return
      end
      refresh(s)
      s.status = nil
      if extra.started then
        extra.started(s, c)
      end
      page.links(c.root)
      local function changed ()
        return rt.task(function ()
          route(s)
          reload(s)
          c.commit()
        end)
      end
      c.on_stop(page.on_change(changed))
      c.on_stop(filter.on_change(changed))
      c.on_stop(core.on_restart(function ()
        async.spawn(function ()
          refresh(s)
          c.commit()
        end)
      end))
      routes.wait()()
    end,

    actions = tbl.assign({

      add = function (s, c, ev)
        local body = ev.form.body
        if body ~= "" then
          dom.reset(ev.el)
          c.commit()
          local todo, top = core.add(body)
          if not s.tag or arr.includes(todo.tags, s.tag) then
            s.todos.insert(todo, s.sort == "newest" and first_key(s.todos) or nil)
          end
          s.top = top
          wrote(s, c)
        end
      end,

      toggle = function (s, c, ev)
        local todo = core.toggle(ev.key)
        if todo.done and not s.show_done then
          s.todos.remove(ev.key)
        else
          s.todos.update(ev.key, todo)
        end
        wrote(s, c)
      end,

      remove = function (s, c, ev)
        s.top = core.remove(ev.key)
        s.todos.remove(ev.key)
        wrote(s, c)
      end,

      set = function (s, c, ev)
        local name = ev.data.name
        local checkbox = ev.checked ~= nil
        if checkbox then
          s[name] = ev.checked
        else
          s[name] = ev.value
        end
        local todos = core.set(name, checkbox and (ev.checked and "1" or "0") or ev.value, s.tag)
        if name == "show_done" or name == "sort" then
          s.todos = todos
        elseif extra.changed then
          extra.changed(s, c, name)
        end
      end,

      ask_clear = function (s)
        s.confirm = true
      end,

      cancel_clear = function (s)
        s.confirm = false
      end,

      clear_done = function (s, c)
        s.confirm = false
        apply(s, core.clear_done(s.tag, s.view == "tags"))
        wrote(s, c)
      end,

      export = function ()
        local blob = js.Blob:new(val.pack({ core.export() }), val.pack({ type = "application/json" }))
        local url = js.URL:createObjectURL(blob)
        local a = js.document:createElement("a")
        a.href = url
        a.download = "my_app-export.json"
        a:click()
        js.URL:revokeObjectURL(url)
      end,

    }, extra.actions or {}),

  }

end
client/static/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="data:,">
    <title>my_app</title>
    <style>
      body { font-family: sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
      todo-app { display: block; }
      #error { color: #b00; }
      #composer { display: flex; gap: 0.5rem; }
      #new-todo { flex: 1; padding: 0.4rem; }
      #todo-list { list-style: none; padding: 0; }
      #todo-list li { display: flex; gap: 0.5rem; align-items: center; padding: 0.3rem 0; }
      #todo-list li span { flex: 1; }
      #todo-list li.done span { text-decoration: line-through; color: #888; }
      .tag { color: #06c; font-style: normal; }
      #toolbar { display: flex; gap: 0.5rem; align-items: center; margin-top: 1rem; }
      header { display: flex; justify-content: space-between; align-items: baseline; }
      h1 a { color: inherit; text-decoration: none; }
      #top-tags, #settings label { display: flex; gap: 0.5rem; margin: 0.5rem 0; }
      #views > section { display: none; }
      #views[data-view=list] #list, #views[data-view=tags] #tags, #views[data-view=settings] #settings { display: block; }
    </style>
  </head>
  <body>
    <todo-app></todo-app>
    <script src="/bundle.606e713e9c93.js"></script>
  </body>
</html>
make.common.lua
local env = require("santoku.env")

return {
  env = {

    name = "my-app",
    version = "0.0.1-1",

    dependencies = { "lua == 5.1" },

    build = { dependencies = { "santoku-web >= 13.0.0, < 14.0.0" } },

    server = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-sqlite >= 9.0.0, < 10.0.0",
        "santoku-migrate >= 0.1.3, < 0.2.0",
        "santoku-resty >= 5.0.0, < 6.0.0",
      },
      test = {
        dependencies = {
          "santoku-http >= 4.0.1, < 5.0.0",
          "santoku-socket >= 6.0.1, < 7.0.0",
          "santoku-cdp >= 0.5.1, < 0.6.0",
        },
      },
    },

    client = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-web >= 13.0.0, < 14.0.0",
        "lua-cjson == 2.1.0.10-1",
      },
      check_links = true,
    },

    nginx = { domain = env.var("DOMAIN", "localhost"), workers = env.var("WORKERS", nil) },

  },
}
make.lua
local fs = require("santoku.fs")
local tbl = require("santoku.table")

return tbl.merge({ env = { minify = false } }, fs.runfile("make.common.lua"))
make.prod.lua
local fs = require("santoku.fs")
local tbl = require("santoku.table")

return tbl.merge({ env = { minify = true } }, fs.runfile("make.common.lua"))
res/client/partials/settings.mustache
{{> partials.todo_settings.mustache}}
res/client/partials/todo_settings.mustache
<label><input id="show-done" type="checkbox" {{#show_done}}checked{{/show_done}} data-name="show_done" data-action="change:set"> Show done</label>
<label>Order
  <select id="sort" value="{{sort}}" data-name="sort" data-action="change:set">
    <option value="oldest">Oldest first</option>
    <option value="newest">Newest first</option>
  </select>
</label>
{{^confirm}}
<button id="clear-done" data-action="ask_clear">Clear done</button>
{{/confirm}}
{{#confirm}}
<span id="confirm">Delete every done todo? <button data-action="clear_done">Yes</button> <button data-action="cancel_clear">No</button></span>
{{/confirm}}
res/client/partials/toolbar.mustache
<button data-action="export">Export</button>
res/client/todo-app.html
<header>
  <h1><a href="/">my_app</a></h1>
  <a id="settings-link" href="/settings">Settings</a>
</header>
{{#error}}
  <p id="error">{{error}}</p>
{{/error}}
<p id="status">{{status}}</p>
{{^status}}
  <div id="views" data-view="{{view}}">
    <section id="list">
      <form id="composer" data-action="add">
        <input id="new-todo" name="body" autocomplete="off" placeholder="What needs doing? Use #tags">
        <button>Add</button>
      </form>
      <p id="top-tags">
        {{#top}}
          <a data-key="{{tag}}" href="/?tag={{tag}}">#{{tag}}</a>
        {{/top}}
        <a id="all-tags" href="/tags">view all</a>
      </p>
      {{#tag}}
        <p id="filter">Showing #{{tag}} <a href="/">all</a></p>
      {{/tag}}
      <ul id="todo-list">
        {{#todos}}
          <li data-key="{{id}}" class="{{#done}}done{{/done}}">
            <button data-action="toggle">{{#done}}undo{{/done}}{{^done}}done{{/done}}</button>
            <span>{{text}}</span>
            {{#tags}}<a class="tag" href="/?tag={{.}}">#{{.}}</a>{{/tags}}
            <button data-action="remove">x</button>
          </li>
        {{/todos}}
      </ul>
      {{^todos}}<p id="empty">Nothing yet.</p>{{/todos}}
      <div id="toolbar">
        {{> partials.toolbar.mustache}}
      </div>
    </section>
    <section id="tags">
      <h2>Tags</h2>
      <ul id="tag-list">
        {{#all}}
          <li data-key="{{tag}}"><a href="/?tag={{tag}}">#{{tag}}</a> {{n}}</li>
        {{/all}}
      </ul>
    </section>
    <section id="settings">
      {{> partials.settings.mustache}}
    </section>
  </div>
{{/status}}
res/server/migrations/0.0.1.sql
create table todos (
  id text primary key,
  body text not null,
  done integer not null default 0
);

create table settings (
  key text primary key,
  value text
);

create table todos_tags (
  todo_id text not null,
  tag text not null,
  primary key (todo_id, tag)
);

create index todos_tags_tag on todos_tags (tag);
res/server/nginx.mustache
daemon {{{nginx.daemon}}};
pid {{{nginx.pid}}};
{{#nginx.workers}}
worker_processes {{{nginx.workers}}};
{{/nginx.workers}}
error_log {{{nginx.error_log}}} info;
env DB_FILE;
env DB_WRITER;

events {}

http {

  include {{{openresty_dir}}}/nginx/conf/mime.types;

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

  brotli on;
  brotli_static on;
  brotli_comp_level 6;
  brotli_min_length 1000;
  brotli_types text/plain text/css text/xml text/javascript application/json
    application/javascript application/xml application/wasm image/svg+xml;

  access_log {{{nginx.access_log}}};

  client_max_body_size 1m;
  client_body_buffer_size 1m;
  client_body_temp_path temp/client_body;
  proxy_temp_path temp/proxy;
  fastcgi_temp_path temp/fastcgi;
  uwsgi_temp_path temp/uwsgi;
  scgi_temp_path temp/scgi;

  lua_package_path "{{{lua_package_path}}}";
  lua_package_cpath "{{{lua_package_cpath}}}";

  lua_shared_dict sqlite_retry 1m;

  init_by_lua_block { require("my_app.web.init") }
  init_worker_by_lua_block { require("my_app.web.init_worker") }

  server {

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

{{> pages}}
    location = /favicon.ico {
      access_log off;
      log_not_found off;
      return 204;
    }

    location ~ "^/api/[a-z_]+$" {
      limit_except POST { deny all; }
      content_by_lua_block { require("my_app.web.api")() }
    }

    location ~* "\.[a-f0-9]{12}\." {
      limit_except GET { deny all; }
      root public;
      expires 1y;
      add_header Cache-Control "public, immutable";
    }

  }
}
res/server/nginx/pages.mustache
    location ~ "^/(tags|settings)?$" {
      limit_except GET { deny all; }
      root public;
      try_files /{{{index}}} =404;
      add_header Cache-Control "no-cache";
    }

server/lib/my_app/migrations.tk.lua
<%
  local fs = require("santoku.fs")
  local serialize = require("santoku.serialize")
  local migrations = {}
  for fp in fs.files(depend("res/" .. component .. "/migrations")) do
    migrations[fs.basename(fp)] = readfile(fp)
  end
  t_migrations = serialize(migrations, true)
%>
return <% return t_migrations %>
server/lib/my_app/store.lua
local arr = require("santoku.array")
local str = require("santoku.string")

local function parse (body)
  local tags, seen = {}, {}
  for tag in str.gmatch(body, "#([%w-]+)") do
    tag = str.lower(tag)
    if not seen[tag] then
      seen[tag] = true
      arr.push(tags, tag)
    end
  end
  return str.trim((str.gsub(body, "%s*#[%w-]+", ""))), tags
end

local defaults = { show_done = "1", sort = "oldest" }

local function todo (r)
  local text, tags = parse(r.body)
  return { id = r.id, text = text, tags = tags, done = r.done == 1 }
end

return function (db)

  local rows = db.all([[
    select id, body, done from todos t
    where (?1 is null or id = ?1)
      and (?2 is null or exists (select 1 from todos_tags g where g.todo_id = t.id and g.tag = ?2))
      and (?3 = 1 or done = 0)
    order by case when ?4 = 1 then -rowid else rowid end
  ]], true)

  local get_setting = db.getter("select value from settings where key = ?1")
  local set_setting = db.runner("insert or replace into settings (key, value) values (?1, ?2)")

  local function setting (key)
    return get_setting(key) or defaults[key]
  end

  local tag_counts = db.all([[
    select tag, count(*) as n from todos_tags group by tag order by n desc, tag limit ?1
  ]], true)

  local drop_done = db.runner("delete from todos where done = 1")

  local drop_orphan_tags = db.runner([[
    delete from todos_tags where todo_id not in (select id from todos)
  ]])

  local insert = db.getter([[
    insert into todos (id, body, done) values (lower(hex(randomblob(8))), ?1, 0)
    returning id
  ]])

  local flip = db.runner("update todos set done = 1 - done where id = ?1")
  local drop = db.runner("delete from todos where id = ?1")
  local live_body = db.getter("select body from todos where id = ?1")
  local drop_tags = db.runner("delete from todos_tags where todo_id = ?1")
  local add_tag = db.runner("insert or ignore into todos_tags (todo_id, tag) values (?1, ?2)")

  local function retag (id)
    drop_tags(id)
    local body = live_body(id)
    if body then
      local _, tags = parse(body)
      for i = 1, #tags do
        add_tag(id, tags[i])
      end
    end
  end

  local function get (id)
    return todo(rows(id, nil, 1, 0)[1])
  end

  local export = db.getter([[
    select coalesce(json_group_array(json_object(
      'id', t.id, 'body', t.body, 'done', t.done,
      'tags', (select json_group_array(tag) from todos_tags g where g.todo_id = t.id)
    )), '[]') from todos t
  ]])

  local function list (tag)
    local show_done = setting("show_done") == "1" and 1 or 0
    local newest = setting("sort") == "newest" and 1 or 0
    return arr.map(rows(nil, tag, show_done, newest), todo)
  end

  local function settings ()
    return { show_done = setting("show_done") == "1", sort = setting("sort") }
  end

  local function view (tag, all)
    return { settings = settings(), todos = list(tag), top = tag_counts(10), all = all and tag_counts(-1) or nil }
  end

  return {

    read = {

      list = list,

      settings = settings,

      view = view,

      tags = function (limit)
        return tag_counts(limit)
      end,

      export = function ()
        return export()
      end,

    },

    write = {

      add = function (body)
        local id = insert(body)
        retag(id)
        return get(id), tag_counts(10)
      end,

      toggle = function (id)
        flip(id)
        return get(id)
      end,

      remove = function (id)
        drop(id)
        drop_tags(id)
        return tag_counts(10)
      end,

      set = function (key, value, tag)
        set_setting(key, value)
        return list(tag)
      end,

      clear_done = function (tag, all)
        drop_done()
        drop_orphan_tags()
        return view(tag, all)
      end,

      retag = retag,

    },

  }

end
server/lib/my_app/web/api.lua
local cjson = require("cjson")
local arr = require("santoku.array")
local str = require("santoku.string")
local status = require("my_app.web.status")
local db = require("my_app.web.db")

local lists = { todos = true, top = true, all = true, tags = true }

local writes = { add = true, toggle = true, remove = true, set = true, clear_done = true, retag = true }

local returns = { list = { true }, tags = { true }, add = { false, true }, remove = { true }, set = { true } }

local function mark (v, list)
  if type(v) == "table" then
    if list then
      setmetatable(v, cjson.array_mt)
    end
    for k, x in pairs(v) do
      mark(x, lists[k] or false)
    end
  end
  return v
end

local function results (name, ...)
  if not writes[name] then
    return status((...)), nil, { ... }
  end
  local ok, e = ...
  if not ok then
    return status(nil, e)
  end
  return 200, nil, { select(2, ...) }
end

return function ()
  local name = str.match(ngx.var.uri, "^/api/([a-z_]+)$")
  local fn = db[name]

  if not fn then
    return ngx.exit(ngx.HTTP_NOT_FOUND)
  end

  ngx.req.read_body()
  local args = cjson.decode(ngx.req.get_body_data() or "[]")
  local n = #args
  for i = 1, n do
    if args[i] == cjson.null then
      args[i] = nil
    end
  end
  local code, e, out = results(name, fn(arr.spread(args, 1, n)))
  ngx.status = code
  ngx.header.content_type = "application/json"
  if e then
    ngx.say(cjson.encode({ status = e }))
  else
    local list = returns[name] or {}
    for i = 1, #out do
      mark(out[i], list[i] or false)
    end
    ngx.say(cjson.encode(setmetatable(out, cjson.array_mt)))
  end
end
server/lib/my_app/web/db.lua
return require("santoku.resty.sqlite").store(require("my_app.store"))
server/lib/my_app/web/init.lua
local env = require("santoku.env")
local migrate = require("santoku.migrate")
local sqlite = require("santoku.resty.sqlite")
local migrations = require("my_app.migrations")

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

require("my_app.web.db")
server/lib/my_app/web/init_worker.lua
require("santoku.resty.sqlite").init_worker()
server/lib/my_app/web/status.lua
local err = require("santoku.error")
local str = require("santoku.string")

local codes = { full = 503, timeout = 504, lost = 504, failed = 500, committed = 200 }

return function (value, e)
  if value ~= nil then
    return 200
  end
  if type(e) ~= "string" then
    return 404
  end
  return err.assert(codes[str.match(e, "^%a+")], "a write returned an unknown status", e), e
end
server/nginx.tk.conf
<%
  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"),
  })
%>
server/test/res/browser.lua
local str = require("santoku.string")
local run = require("santoku.cdp.run")
local page = require("santoku.cdp.page")
local log = require("santoku.cdp.log")

local kinds = { "error: ", "exception: ", "netfail: ", "http " }

local function reported (line)
  for i = 1, #kinds do
    if str.sub(line, 1, #kinds[i]) == kinds[i] then
      return true
    end
  end
  return false
end

return function (defer, fn)
  local browser = run.launch()
  local drain, passed
  defer(function ()
    if drain and not passed then
      local lines = drain()
      local head = false
      for i = 1, #lines do
        if reported(lines[i]) then
          if not head then
            print("the page reported:")
            head = true
          end
          print(lines[i])
        end
      end
    end
    run.stop(browser)
  end)
  local s = page.open({ port = browser.port })
  drain = log.watch(s)
  fn(s, browser)
  passed = true
  s.close()
end
server/test/res/shadow.lua
local err = require("santoku.error")
local cjson = require("cjson")
local page = require("santoku.cdp.page")

return function (tag)

  local root = "document.querySelector(" .. cjson.encode(tag) .. ")?.shadowRoot"

  local function q (selector)
    return root .. "?.querySelector(" .. cjson.encode(selector) .. ")"
  end

  local function all (selector)
    return "[...(" .. root .. "?.querySelectorAll(" .. cjson.encode(selector) .. ") ?? [])]"
  end

  local function center (s, selector)
    local c = page.eval(
      s,
      "(() => { const e = " .. q(selector) .. ";"
        .. " if (!e) return false; e.scrollIntoView({ block: 'center', inline: 'center' });"
        .. " const r = e.getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2]; })()"
    )
    if not c then
      err.error("no element in " .. tag .. " matches", selector)
    end
    return c[1], c[2]
  end

  local function type_into (s, selector, value)
    local found = page.eval(
      s,
      "(() => { const e = " .. q(selector) .. ";"
        .. " if (!e) return false; e.focus(); return e.getRootNode().activeElement === e; })()"
    )
    if not found then
      err.error("no focusable element in " .. tag .. " matches", selector)
    end
    s.call("Input.insertText", { text = value })
  end

  return { q = q, all = all, center = center, type = type_into }

end
server/test/spec/db_file.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local str = require("santoku.string")

test("toku test's server keeps its database in its own run directory, so toku start's holds no spec rows", function ()
  local run = env.var("RUN_DIR")
  err.assert(str.endswith(run, "/test/run"), "the specs' server runs outside build/<env>/test/run", run)
  err.assert(
    fs.exists(fs.join(run, "data", "my_app.db")),
    "the specs' server opened no database of its own",
    run
  )
end)
server/test/spec/latest.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local utc = require("santoku.utc")
local cjson = require("cjson")
local http = require("santoku.http")(require("santoku.socket"))

err.assert(
  env.var("TOKU_CHROMIUM", nil),
  "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it"
)

local page = require("santoku.cdp.page")
local input = require("santoku.cdp.input")
local browser = fs.runfile("test/res/browser.lua")
local shadow = fs.runfile("test/res/shadow.lua")("todo-app")

local base = "http://127.0.0.1:" .. env.var("PORT")
local stamp = tostring(utc.time())
local first, second = "la" .. stamp, "lb" .. stamp

local function add (body)
  local ok, resp = http.post(base .. "/api/add", {
    headers = { ["content-type"] = "application/json" },
    body = cjson.encode({ body }),
  })
  err.assert(ok, "add failed", resp.status)
end

local function shows (tag)
  return "!!" .. shadow.q("#todo-list li a.tag[href=\"/?tag=" .. tag .. "\"]")
end

test("a newer view replaces an older one that answers last", function (defer)
  add("older list #" .. first)
  add("newer list #" .. second)
  browser(defer, function (s)
    page.navigate(s, base .. "/")
    page.wait_until(s, shows(first) .. " && " .. shows(second))
    local held = {}
    s.on("Fetch.requestPaused", function (p)
      held[#held + 1] = p.requestId
    end)
    s.call("Fetch.enable", { patterns = { { urlPattern = "*/api/view", requestStage = "Response" } } })
    input.click(s, shadow.center(s, "#todo-list li a.tag[href=\"/?tag=" .. first .. "\"]"))
    err.assert(s.wait(function ()
      return #held == 1
    end, 10000), "the first list never left")
    input.click(s, shadow.center(s, "#todo-list li a.tag[href=\"/?tag=" .. second .. "\"]"))
    err.assert(s.wait(function ()
      return #held == 2
    end, 10000), "the second list never left")
    s.call("Fetch.continueRequest", { requestId = held[2] })
    page.wait_until(s, shows(second) .. " && !" .. shows(first))
    s.send("Fetch.continueRequest", { requestId = held[1] })
    page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 1000))")
    err.assert(page.eval(s, "location.search") == "?tag=" .. second, "the route moved")
    err.assert(
      page.eval(s, shows(second) .. " && !" .. shows(first)),
      "the older list answered last and replaced the newer one"
    )
    s.call("Fetch.disable")
  end)
end)
server/test/spec/my_app.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local str = require("santoku.string")
local utc = require("santoku.utc")
local cjson = require("cjson")
local http = require("santoku.http")(require("santoku.socket"))

local url = "http://127.0.0.1:" .. env.var("PORT") .. "/api/"
local tag = "spec" .. utc.time()

local function call (name, args)
  local ok, resp = http.post(url .. name, { headers = { ["content-type"] = "application/json" }, body = args or "[]" })
  err.assert(ok, "api call failed", name, resp.status)
  return resp.body()
end

test("api endpoint", function ()

  test("empty lists answer as JSON arrays", function ()
    call("set", '["show_done","1"]')
    for _, t in ipairs(cjson.decode(call("list"))[1]) do
      call("remove", cjson.encode({ t.id }))
    end
    local body = call("view", "[null,true]")
    for _, want in ipairs({ '"todos":[]', '"top":[]', '"all":[]', '"settings":{' }) do
      err.assert(str.find(body, want, 1, true), "view on an empty db", want, body)
    end
    body = call("add", '["untagged"]')
    err.assert(str.find(body, '"tags":[]', 1, true) and str.find(body, "},[]]", 1, true), "add with no tags", body)
    body = call("remove", cjson.encode({ cjson.decode(body)[1].id }))
    err.assert(str.match(body, "^%[%[%]%]%s*$"), "remove on an empty db", body)
  end)

  test("add stores a todo and returns its row", function ()
    local body = call("add", '["write the spec #' .. tag .. '"]')
    err.assert(str.find(body, '"text":"write the spec"', 1, true), "tags leave the text", body)
  end)

  test("a null argument arrives as nil", function ()
    local body = call("view", "[null,false]")
    err.assert(str.find(body, '"todos":', 1, true), "view with no tag answers", body)
  end)

  test("list filters by tag", function ()
    local body = call("list", '["' .. tag .. '"]')
    err.assert(str.find(body, "write the spec", 1, true), "the tagged row comes back", body)
  end)

  test("settings persist on the server", function ()
    call("set", '["sort","newest"]')
    err.assert(str.find(call("settings"), '"sort":"newest"', 1, true), "sort reads back")
    call("set", '["sort","oldest"]')
  end)

  test("a write that fails answers 500 with its status", function ()
    local ok, resp = http.post(url .. "add", { body = "[null]" })
    err.assert(not ok and resp.status == 500, "expected 500", resp.status)
    local st = cjson.decode(resp.body()).status
    err.assert(str.find(st, "failed: ", 1, true) == 1, "the body names the failure", st)
  end)

  test("GET is rejected and unknown names are not found", function ()
    local ok, resp = http.get(url .. "list")
    err.assert(not ok and resp.status == 403, "expected 403", resp.status)
    ok, resp = http.post(url .. "nope", { body = "[]" })
    err.assert(not ok and resp.status == 404, "expected 404", resp.status)
  end)

end)

test("pages revalidate, so the next load after a rebuild gets the new bundle", function ()
  for _, path in ipairs({ "/", "/tags", "/settings" }) do
    local ok, resp = http.get("http://127.0.0.1:" .. env.var("PORT") .. path)
    err.assert(ok, "page failed", path, resp.status)
    err.assert(resp.headers["cache-control"] == "no-cache", "page is cached", path, resp.headers["cache-control"])
  end
end)
server/test/spec/page.browser.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local fs = require("santoku.fs")
local utc = require("santoku.utc")
local cjson = require("cjson")

err.assert(
  env.var("TOKU_CHROMIUM", nil),
  "browser specs need TOKU_CHROMIUM set to a Chromium command; the toku-web image sets it"
)

local page = require("santoku.cdp.page")
local input = require("santoku.cdp.input")
local browser = fs.runfile("test/res/browser.lua")
local shadow = fs.runfile("test/res/shadow.lua")("todo-app")
local q = shadow.q

local function pick (s, value)
  page.eval(
    s,
    "(() => { const e = " .. q("#sort") .. "; e.value = " .. cjson.encode(value)
      .. "; e.dispatchEvent(new Event('change', { bubbles: true })); })()"
  )
end

local function latency (s, ms)
  s.call("Network.emulateNetworkConditions", {
    offline = false,
    latency = ms,
    downloadThroughput = -1,
    uploadThroughput = -1,
  })
end

local function early (s)
  local url = "http://127.0.0.1:" .. env.var("PORT") .. "/settings"
  local loaded = "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...' && !!" .. q("#sort")
  page.navigate(s, url)
  page.wait_until(s, loaded)
  local was = page.eval(s, q("#sort") .. ".value")
  local want = was == "newest" and "oldest" or "newest"
  s.call("Network.enable")
  latency(s, 300)
  page.navigate(s, url)
  page.wait_until(s, "!!" .. q("#sort") .. "?.offsetParent")
  pick(s, want)
  page.wait_until(s, loaded)
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 1000))")
  latency(s, 0)
  err.assert(page.eval(s, q("#sort") .. ".value") == want, "a setting changed as the page loads is lost", was, want)
  page.navigate(s, url)
  page.wait_until(s, loaded)
  err.assert(page.eval(s, q("#sort") .. ".value") == want, "a changed setting is lost on reload", was, want)
  pick(s, was)
  page.wait_until(
    s,
    "new Promise(r => setTimeout(() => r(" .. q("#sort") .. ".value === " .. cjson.encode(was) .. "), 1000))"
  )
end

local function flows (s)
  local text = "browser spec " .. utc.time()
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...'")

  shadow.type(s, "#new-todo", text .. " #spec")
  input.click(s, shadow.center(s, "#composer button"))
  local key = page.wait_until(
    s,
    q("#new-todo") .. ".value === '' && " .. shadow.all("#todo-list li") .. ".filter(li => li.textContent.includes("
      .. cjson.encode(text) .. ")).map(li => li.dataset.key)[0]"
  )
  local row = '#todo-list li[data-key="' .. key .. '"]'
  err.assert(page.eval(s, q(row .. " a.tag") .. ".getAttribute('href')") == "/?tag=spec", "tag link")
  local shown = page.eval(s, "(" .. q(row) .. ".textContent.match(/#spec\\b/g) || []).length")
  err.assert(shown == 1, "the row shows its tag more than once", shown)

  input.click(s, shadow.center(s, row .. ' [data-action="toggle"]'))
  page.wait_until(s, q(row) .. ".classList.contains('done')")

  input.click(s, shadow.center(s, row .. " a.tag"))
  page.wait_until(s, "location.search === '?tag=spec' && !!" .. q("#filter"))

  input.click(s, shadow.center(s, "#all-tags"))
  page.wait_until(s, "location.pathname === '/tags' && !!" .. q('#tag-list li[data-key="spec"]'))

  input.click(s, shadow.center(s, "#settings-link"))
  page.wait_until(s, "location.pathname === '/settings' && " .. q("#settings") .. ".offsetParent !== null")

  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/?tag=spec")
  page.wait_until(s, "!!" .. q(row))
  input.click(s, shadow.center(s, row .. ' [data-action="remove"]'))
  page.wait_until(s, "!" .. q(row))
end

local function scroll (s)
  local tag = "scroll" .. utc.time()
  local list = "http://127.0.0.1:" .. env.var("PORT") .. "/?tag=" .. tag
  local rows = shadow.all("#todo-list li") .. ".length"
  s.call("Emulation.setDeviceMetricsOverride", { width = 400, height = 300, deviceScaleFactor = 1, mobile = false })
  page.navigate(s, list)
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...' && !!" .. q("#new-todo"))
  for i = 1, 20 do
    shadow.type(s, "#new-todo", "scroll row " .. i .. " #" .. tag)
    page.eval(s, q("#composer button") .. ".click()")
    page.wait_until(s, q("#new-todo") .. ".value === '' && " .. rows .. " === " .. i)
  end
  page.eval(s, "window.scrollTo(0, document.documentElement.scrollHeight)")
  local y = page.eval(s, "window.scrollY")
  err.assert(y > 100, "the list doesn't scroll", y)
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 500))")
  page.eval(s, q("#settings-link") .. ".click()")
  page.wait_until(s, "location.pathname === '/settings' && " .. q("#settings") .. ".offsetParent !== null")
  page.eval(s, "history.back()")
  page.wait_until(s, "location.pathname === '/' && " .. rows .. " === 20")
  page.wait_until(s, "new Promise(r => setTimeout(() => r(true), 500))")
  local back = page.eval(s, "window.scrollY")
  err.assert(back == y, "Back didn't restore the list's scroll position", y, back)
  s.call("Emulation.clearDeviceMetricsOverride")
end

local function failure (s)
  local export = '#toolbar [data-action="export"]'
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "!!" .. q(export) .. "?.offsetParent")
  err.assert(not page.eval(s, "!!" .. q("#error")), "the page shows an error before anything failed")
  page.eval(s, "(() => { URL.createObjectURL = () => { throw new Error('export broke'); }; })()")
  input.click(s, shadow.center(s, export))
  page.wait_until(s, "!!" .. q("#error") .. "?.textContent.includes('export broke')")
end

local function stops (s)
  s.call("Page.addScriptToEvaluateOnNewDocument", {
    source = [[
(() => {
  const live = new Map();
  const add = EventTarget.prototype.addEventListener;
  const remove = EventTarget.prototype.removeEventListener;
  const count = (target, type, d) => {
    if (target === window) live.set(type, (live.get(type) || 0) + d);
  };
  EventTarget.prototype.addEventListener = function (type, fn, o) {
    count(this, type, 1);
    return add.call(this, type, fn, o);
  };
  EventTarget.prototype.removeEventListener = function (type, fn, o) {
    count(this, type, -1);
    return remove.call(this, type, fn, o);
  };
  window.__listening = (type) => live.get(type) || 0;
})()
]],
  })
  page.navigate(s, "http://127.0.0.1:" .. env.var("PORT") .. "/")
  page.wait_until(s, "(" .. q("#status") .. "?.textContent ?? 'Loading...') !== 'Loading...'")
  local before = {}
  for _, name in ipairs({ "error", "unhandledrejection" }) do
    before[name] = page.eval(s, "window.__listening(" .. cjson.encode(name) .. ")")
    err.assert(before[name] > 0, "todo-app listens for no window event of this type", name)
  end
  page.eval(s, "(() => { document.querySelector('todo-app').remove(); })()")
  for name, n in pairs(before) do
    local after = page.eval(s, "window.__listening(" .. cjson.encode(name) .. ")")
    err.assert(after == n - 1, "a removed todo-app keeps its window listener", name, n, after)
  end
end

test("the page", function (defer)
  browser(defer, function (s)
    early(s)
    flows(s)
    scroll(s)
    failure(s)
    stops(s)
  end)
end)
server/test/spec/status.lua
local test = require("santoku.test")
local err = require("santoku.error")
local status = require("my_app.web.status")

test("a result picks the HTTP status, and nil with no write status is 404", function ()
  for _, c in ipairs({
    { 200, 7 },
    { 404, nil },
    { 200, false },
    { 503, nil, "full" },
    { 504, nil, "timeout" },
    { 504, nil, "lost" },
    { 500, nil, "failed: UNIQUE constraint failed: items.id" },
    { 200, nil, "committed: result exceeds slot_size" },
  }) do
    local code, e = status(c[2], c[3])
    err.assert(code == c[1], "wrong status", c[3], code)
    err.assert(e == c[3], "the status message is lost", c[3], e)
  end
  err.assert(not err.pcall(status, nil, "odd"), "an unknown status passes")
end)
server/test/spec/store.lua
local test = require("santoku.test")
local err = require("santoku.error")
local str = require("santoku.string")
local sqlite = require("santoku.sqlite.db")
local sql = require("santoku.sqlite")
local migrate = require("santoku.migrate")
local migrations = require("my_app.migrations")
local store = require("my_app.store")

test("the store", function ()

  local db = sql(err.assert(sqlite.open_memory()))
  migrate(db, migrations)
  local s = db.store(store)

  test("add returns the row the page renders", function ()
    local t = err.checkok(s.add("write docs #Docs #docs"))
    err.assert(#t.id == 16, "16-char hex id", t.id)
    err.assert(t.text == "write docs", "tags leave the text", t.text)
    err.assert(#t.tags == 1 and t.tags[1] == "docs", "tags are lowercased and unique")
    err.assert(t.done == false, "a new row is open")
  end)

  test("list, filter, toggle, remove", function ()
    local id = s.list()[1].id
    s.add("buy milk")
    local rows = s.list()
    err.assert(#rows == 2 and rows[2].text == "buy milk", "oldest first")
    err.assert(#s.list("docs") == 1 and s.list("docs")[1].id == id, "tag filter")
    err.assert(err.checkok(s.toggle(id)).done == true, "toggle returns the updated row")
    s.remove(id)
    err.assert(#s.list() == 1 and #s.list("docs") == 0, "remove drops the row and its tags")
  end)

  test("settings order the list, and tags count live todos", function ()
    local a = err.checkok(s.add("one #home"))
    s.add("two #home #work")
    s.toggle(a.id)
    local top = s.tags(10)
    err.assert(top[1].tag == "home" and top[1].n == 2 and top[2].tag == "work", "most used first")
    s.set("show_done", "0")
    err.assert(#s.list("home") == 1, "hide done")
    s.set("show_done", "1")
    s.set("sort", "newest")
    err.assert(s.list()[1].text == "two", "newest first")
    err.assert(s.settings().sort == "newest" and s.settings().show_done == true, "settings read back")
    s.clear_done()
    err.assert(#s.list("home") == 1 and s.tags(10)[1].n == 1, "clear done drops done rows and their tags")
  end)

  test("view and the writes return what the page renders next", function ()
    local t, top = err.checkok(s.add("five #view"))
    err.assert(t.text == "five" and #top >= 1, "add returns the row and the top tags")
    local v = s.view("view", true)
    err.assert(#v.todos == 1 and v.todos[1].id == t.id, "view filters by tag")
    err.assert(v.settings.sort and #v.top >= 1 and #v.all >= #v.top, "view carries settings and tags")
    err.assert(s.view().all == nil, "all tags only when asked")
    err.assert(#err.checkok(s.set("show_done", "1", "view")) == 1, "set returns the list it reorders")
    err.assert(
      #err.checkok(s.set("other", "x", "view")) == 1,
      "every setting returns the list, so the api never answers a write with nil"
    )
    local left = err.checkok(s.remove(t.id))
    for i = 1, #left do
      err.assert(left[i].tag ~= "view", "remove returns the tags without the row")
    end
    err.assert(err.checkok(s.clear_done()).todos, "clear done returns a fresh view")
  end)

  test("retag rebuilds a row's tags from its body", function ()
    local t = err.checkok(s.add("three #a"))
    db.exec(str.format("update todos set body = 'three #b' where id = '%s'", t.id))
    s.retag(t.id)
    err.assert(#s.list("a") == 0 and #s.list("b") == 1, "retag reads the stored body")
  end)

  test("a write that fails rolls back and says so", function ()
    local before = #s.list()
    local ok, e = s.add(nil)
    err.assert(ok == nil and str.find(e, "failed: ", 1, true) == 1, "a failed add reports failed", ok, e)
    err.assert(#s.list() == before, "the failed add left a row", #s.list(), before)
  end)

  db.close()

end)

A WebSocket echo server

An OpenResty server that echoes WebSocket messages, with a spec that talks to it from a native client.

serverwebsocket

Rocks: santoku-websocketsantoku-restysantoku-socket

toku init --example websocket my-websocket
.gitignore
build/
lua_modules/
*.swp
*.swo
.tmp*
make.lua
local env = require("santoku.env")

return {
  env = {

    name = "my-websocket",
    version = "0.0.1-1",

    dependencies = { "lua == 5.1" },

    server = {
      dependencies = {
        "lua == 5.1",
        "santoku >= 6.0.0, < 7.0.0",
        "santoku-websocket >= 0.2.1, < 0.3.0",
        "santoku-resty >= 5.0.0, < 6.0.0",
      },
      test = { dependencies = { "santoku-socket >= 6.0.1, < 7.0.0" } },
    },

    nginx = { domain = env.var("DOMAIN", "localhost"), workers = env.var("WORKERS", nil) },

  },
}
res/server/nginx.mustache
daemon {{{nginx.daemon}}};
pid {{{nginx.pid}}};
{{#nginx.workers}}
worker_processes {{{nginx.workers}}};
{{/nginx.workers}}
error_log {{{nginx.error_log}}} info;

events {}

http {

  access_log {{{nginx.access_log}}};

  client_body_temp_path temp/client_body;
  proxy_temp_path temp/proxy;
  fastcgi_temp_path temp/fastcgi;
  uwsgi_temp_path temp/uwsgi;
  scgi_temp_path temp/scgi;

  lua_package_path "{{{lua_package_path}}}";
  lua_package_cpath "{{{lua_package_cpath}}}";

  server {

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

    location = /echo {
      content_by_lua_block { require("my_websocket.web.echo")() }
    }

  }
}
server/lib/my_websocket/web/echo.lua
local err = require("santoku.error")
local ws = require("santoku.websocket")(require("santoku.resty.websocket"))

return function ()
  local conn
  ws.accept({
    message = function (data, kind)
      conn.send(data, kind)
    end,
  }, function (ok, c)
    err.assert(ok, "the websocket handshake failed", c)
    conn = c
  end)
end
server/nginx.tk.conf
<%
  return require("santoku.mustache")(readfile("res/server/nginx.mustache"))({
    nginx = nginx.nginx,
    openresty_dir = openresty_dir,
    lua_package_path = lua_package_path,
    lua_package_cpath = lua_package_cpath,
  })
%>
server/test/spec/my_websocket.lua
local test = require("santoku.test")
local err = require("santoku.error")
local env = require("santoku.env")
local arr = require("santoku.array")
local ws = require("santoku.websocket")(require("santoku.socket.websocket"))

test("the server echoes each message with its kind", function ()
  local got, closed = {}, nil
  local conn = ws.connect("ws://127.0.0.1:" .. env.var("PORT") .. "/echo", {
    message = function (data, kind)
      arr.push(got, kind .. " " .. data)
    end,
    closed = function (code)
      closed = code
    end,
  }, function (ok, e)
    err.assert(ok, "the websocket handshake failed", e)
  end)
  err.assert(conn.send("hello"), "send text")
  err.assert(conn.send("\1\2\3", "binary"), "send binary")
  err.assert(conn.wait(function ()
    return #got == 2
  end, 5000), "no echo arrived", #got)
  err.assert(got[1] == "text hello" and got[2] == "binary \1\2\3", "the echoes", got[1], got[2])
  conn.close(1000, "done")
  conn.wait(function ()
    return closed ~= nil
  end, 5000)
  err.assert(closed == 1000, "the server closed with another code", closed)
end)