servelet (Go)
The Go library for Let servelets. Module path: github.com/nirvanacp/let/go/servelet. It needs Go 1.24 or later.
A servelet is a small backend that Genesis, the Android app that runs Let applets, runs on the phone. You write an ordinary Go http.Handler. let-servelet build compiles it to a WebAssembly module (GOOS=wasip1 GOARCH=wasm). Genesis then:
- loads the module;
- calls it with one request at a time;
- gives it a SQLite database.
An applet calls it as a local service, with genesis.services.request.
The library connects your handler to Genesis, provides the database through database/sql, and names the applet that sent each request.
Install
There is nothing to install. let-servelet create writes a go.mod that does not require this module, and let-servelet build and check add it through a Go workspace file (dist/go.work). Do not add it to go.mod yourself; the build refuses that. @nirvanacp/servelet-tools carries the library, so its version always matches the tools.
Example
package main
import (
"database/sql"
"encoding/json"
"errors"
"net/http"
"github.com/nirvanacp/let/go/servelet"
)
var schema = []string{
`CREATE TABLE notes (owner TEXT NOT NULL, id TEXT NOT NULL, text TEXT NOT NULL, PRIMARY KEY (owner, id))`,
}
func init() {
if err := servelet.Migrate(schema...); err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
servelet.JSON(w, http.StatusOK, map[string]bool{"ready": true})
})
mux.HandleFunc("POST /v1/notes", func(w http.ResponseWriter, r *http.Request) {
var note struct{ ID, Text string }
if err := json.NewDecoder(r.Body).Decode(¬e); err != nil || note.ID == "" {
servelet.Fail(w, http.StatusBadRequest, "INVALID_NOTE", "send {\"id\", \"text\"}")
return
}
_, err := servelet.DB().Exec(`INSERT INTO notes (owner, id, text) VALUES (?, ?, ?)`, servelet.Caller(r), note.ID, note.Text)
if errors.Is(err, servelet.ErrConstraint) {
servelet.Fail(w, http.StatusConflict, "NOTE_EXISTS", "a note with this id exists")
return
}
if err != nil {
servelet.Fail(w, http.StatusInternalServerError, "INTERNAL", err.Error())
return
}
servelet.JSON(w, http.StatusCreated, note)
})
mux.HandleFunc("GET /v1/notes/{id}", func(w http.ResponseWriter, r *http.Request) {
var text string
err := servelet.DB().QueryRow(`SELECT text FROM notes WHERE owner = ? AND id = ?`, servelet.Caller(r), r.PathValue("id")).Scan(&text)
if errors.Is(err, sql.ErrNoRows) {
servelet.Fail(w, http.StatusNotFound, "NOT_FOUND", "no such note")
return
}
if err != nil {
servelet.Fail(w, http.StatusInternalServerError, "INTERNAL", err.Error())
return
}
servelet.JSON(w, http.StatusOK, map[string]string{"id": r.PathValue("id"), "text": text})
})
servelet.OnErase(func(caller string) error {
_, err := servelet.DB().Exec(`DELETE FROM notes WHERE owner = ?`, caller)
return err
})
servelet.Serve(mux)
}
func main() {}
Register everything in init and keep main empty. Genesis initializes the module once and then calls its handler for each request.
API
| Name |
Meaning |
Serve(h http.Handler) |
Registers the handler that answers every request. Call it once, from init |
Caller(r *http.Request) string |
The id of the applet that sent the request, such as hn-bookmarks. Genesis sets it, and an applet cannot choose it. It is empty when no applet sent the request, as with let-servelet check and run |
OnErase(fn func(caller string) error) |
Registers the function that deletes everything that belongs to one applet. Call it once, from init |
DB() *sql.DB |
The servelet's SQLite database |
Migrate(steps ...string) error |
Brings the schema up to date |
JSON(w, status, value) |
Writes value as JSON with the status. <, > and & are not escaped |
Fail(w, status, code, message) |
Writes {"error":{"code":code,"message":message}} with the status |
Logf(format, args...) |
Writes one line to Genesis's log at info level. Lines over 4096 bytes are cut |
Error |
A database error: { Code, Message }, with Code one of CONSTRAINT, BUSY, SQL or LIMIT |
ErrConstraint |
Matches, with errors.Is, a failed UNIQUE, NOT NULL, CHECK or FOREIGN KEY constraint. Answer it with 409 |
ErrBusy |
Matches a locked database |
Requests
Genesis sends each request as a method, a path with its query, and a JSON body. The library turns it into an http.Request:
| Field |
Value |
Method, URL, RequestURI |
As the applet sent them |
Body |
The JSON body; empty when the body is null |
Content-Type |
application/json when there is a body |
Host |
servelet |
RemoteAddr |
host |
| Other headers |
None |
The reply is the status and the body. A body that is valid JSON passes through; any other body becomes a JSON string, and an empty body becomes null. Response headers are not sent to the applet.
| Situation |
Reply |
| The handler panics |
500 INTERNAL, with the panic value as the message |
| The request is malformed |
400 INVALID_REQUEST |
Serve was never called |
503 NO_HANDLER |
The applet receives { status, body } from genesis.services.request.
The caller and shared data
Genesis keeps one database per servelet id. The first applet that uses it, and every applet that bundles the module (the same SHA-256) one of those runs now, talk to the same database, and each keeps it across its own newer builds; an applet with another build of the same id gets a database of its own. So use Caller(r) whenever data must stay with one applet: store it with each row, and filter on it. An applet cannot send another applet's id.
A servelet may also share data between applets on purpose. One way is a namespace that records the applet that created it as its owner:
- other applets get 404 for it;
- a request that would take another applet's namespace gets 409;
- a namespace without an owner goes to the first applet that writes to it.
OnErase is how a shared servelet forgets one applet. Genesis sends it, with the applet's id as the caller, when the user:
- clears that applet's data while the servelet is also bundled by another applet;
- removes that applet while another installed applet still bundles the servelet.
When the servelet belongs to only one applet, Genesis deletes the whole database instead.
OnErase result |
Reply |
Effect |
| No function registered |
501 NO_ERASER |
Genesis keeps the data |
| No caller |
400 INVALID_REQUEST |
|
fn returns an error |
500 INTERNAL |
|
fn returns nil |
204 |
|
Applets cannot send ERASE themselves.
SQL
DB() returns a *sql.DB over the driver let, with one connection.
- Call
DB() each time; do not keep the result.
- A transaction holds the only connection until
Commit or Rollback, so do not query outside it meanwhile.
- When a request ends with a transaction or rows still open, Genesis rolls the transaction back, the library replaces the pool, and a warning is logged.
| Rule |
Detail |
| Placeholders |
Positional ? only. Named arguments are refused |
| Argument types |
nil, int64, float64, string, bool (stored as 0 or 1), []byte, and time.Time (stored as RFC 3339 text in UTC). Other types fail |
| Text columns |
Read back as string. Scanning one into *time.Time fails: scan into a string and use time.Parse(time.RFC3339Nano, s), or store Unix milliseconds in an INTEGER column |
| Several statements |
Only in an Exec without arguments |
| Rows per query |
10 000 |
| Reply size |
4 MiB |
Migrate(steps...) uses SQLite's user_version. steps[i] moves the schema from version i to i+1, and each pending step runs in its own transaction. Only append steps; never edit or remove one that has shipped. It returns an error when the database is newer than the steps, for example after a downgrade.
What a servelet cannot do
- The handler runs synchronously. Goroutines it starts pause when it returns, and timers do not fire between requests.
- There are no files, sockets or network connections.
- Every request must finish within Genesis's limits: 5 seconds, 256 KiB of request body and 256 KiB of reply body, 256 MiB of memory.
- A build for your computer (
go build, go vet, go test) compiles, but every database or log call panics with "servelet: this build runs only inside the host; build it with let-servelet build".
Building and running
| Command |
What it does |
let-servelet build <dir> |
Writes <dir>/dist/servelet.wasm |
let-servelet check <dir> |
Builds, then sends the health request and checks.json over a throwaway database |
let-servelet run <dir> [--port 8790] [--database <file>] |
Serves it on http://127.0.0.1:8790 for testing; the database is <dir>/dist/run.sqlite3 by default |
The local runner sends no caller, so Caller(r) is empty there, and it never sends ERASE. The tools' README in packages/servelet-tools covers the commands in full.
Compatibility
This library is version 0.3.0 of Let and speaks the servelet interface version 1 that Genesis 0.3.0 runs.
Licence
MIT. Source: github.com/nirvanacp/let, in go/servelet.