servelet

package module
v0.0.0-...-93cea3e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

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(&note); 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.

Documentation

Overview

Package servelet runs a Go HTTP handler as a Let servelet: a small backend that the host loads as a WebAssembly module and calls with one request at a time, with a SQLite database of its own.

A servelet registers its handler in init and keeps main empty:

func init() {
	if err := servelet.Migrate(schemaV1); 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})
	})
	servelet.Serve(mux)
}

func main() {}

Build it with let-servelet build. A build for the computer compiles, so go vet works, but every database or log call panics.

A servelet has one database per servelet id, which the applets that bundle that id share. The first applet to use it becomes a member; another applet joins only with the module (by its SHA-256) a member runs now, and a member keeps its access through its own updates. An applet the host does not admit gets a database of its own. Applets that bundle the same build talk to one running instance. Caller(r) names the applet that sent a request; the host sets it and an applet cannot, so a shared servelet records which applet owns each piece of data and refuses or hides other applets' data. OnErase registers what deletes one applet's data when the user clears or removes that applet while another still uses the servelet.

The driver binds a time.Time argument as RFC 3339 text in UTC and returns every text column as a string, so read such a column into a string and parse it with time.Parse(time.RFC3339Nano, s); scanning it into a *time.Time fails. Storing Unix milliseconds in an INTEGER column avoids both.

The handler runs synchronously. Goroutines it starts pause when it returns, timers do not fire between requests, and the module cannot open files, sockets or network connections.

Index

Constants

This section is empty.

Variables

View Source
var ErrBusy = errors.New("servelet: database busy")

ErrBusy matches a database error from a locked database.

View Source
var ErrConstraint = errors.New("servelet: constraint failed")

ErrConstraint matches, through errors.Is, a database error from a failed UNIQUE, NOT NULL, CHECK or FOREIGN KEY constraint. Answer it with 409.

Functions

func Caller

func Caller(r *http.Request) string

Caller returns the id of the applet that sent the request, such as "hn-bookmarks". The host sets it and an applet cannot choose it, so a servelet that several applets share can keep each applet's data to that applet. It is empty when no applet sent the request, as with the computer-side runner.

func DB

func DB() *sql.DB

DB returns the servelet's SQLite database. It has one connection, so a transaction holds it until Commit or Rollback; do not run queries outside the transaction meanwhile. Call DB each time instead of keeping the result: when a request ends with a transaction or rows still open, the host rolls the transaction back and the library replaces the pool, so the next request does not wait for a connection that never comes back.

func Fail

func Fail(w http.ResponseWriter, status int, code, message string)

Fail writes {"error":{"code":code,"message":message}} with the given status.

func JSON

func JSON(w http.ResponseWriter, status int, value any)

JSON writes value as a JSON response with the given status. `<`, `>` and `&` stay as they are: the body goes to an applet as JSON, not into HTML, and escaping would make it longer.

func Logf

func Logf(format string, args ...any)

Logf writes one line to the host's log. Lines longer than 4 KiB are cut.

func Migrate

func Migrate(steps ...string) error

Migrate brings the schema up to date. steps[i] moves the schema from version i to i+1; the version is SQLite's user_version. Each pending step runs in its own transaction. Only append steps: never edit or remove one that has shipped.

func OnErase

func OnErase(fn func(caller string) error)

OnErase registers the function that deletes everything that belongs to one applet. The host calls it when the user clears that applet's data or removes it while another applet still uses this servelet. Without it the host keeps the applet's data. Call it once, from init.

func Serve

func Serve(h http.Handler)

Serve registers the handler that answers every request. Call it once, from init.

Types

type Error

type Error struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Error is a database error from the host. Code is CONSTRAINT, BUSY, SQL or LIMIT.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL