workers

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package workers provides a Cloudflare-Workers-style handler runtime on top of Ramune. User code is authored as an ES module with a default export:

export default {
    route: "/api/hello",
    async fetch(request, env, ctx) {
        return Response.json({ ok: true });
    },
};

Call Register with the module source and a *ramune.Runtime; the returned http.Handler dispatches incoming requests through fetch().

The ctx argument exposes waitUntil(promise): the Go HTTP handler returns as soon as the Response has been written, but the JavaScript executor continues draining pending promises up to WaitUntilTimeout.

This package does not provide its own HTTP server — use it inside any Go HTTP server (net/http, chi, Echo, the ramune CLI, etc.).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AttachPrepared

func AttachPrepared(rt *ramune.Runtime, p *Prepared, opts ...Option) (http.Handler, error)

AttachPrepared binds a previously-prepared module to rt. Safe to call with the same Prepared on multiple Runtimes; each gets its own copy of the module globals.

func BuildExtraEnvJS

func BuildExtraEnvJS(kv []TOMLKVBinding) string

BuildExtraEnvJS returns a JS snippet that installs a globalThis.__extraEnvBindings(env) function binding each declared KV namespace onto env under the requested property name. Bindings with non-identifier names are skipped silently.

func IsWorkersStyle

func IsWorkersStyle(code string) bool

IsWorkersStyle reports whether the source uses a default export, the signal that distinguishes Workers-style modules from old-style hook scripts. Since "export default" is illegal outside a module it has zero false positives against scripts.

func Register

func Register(rt *ramune.Runtime, filename, code string, opts ...Option) (http.Handler, error)

Register is a convenience that wraps Prepare + AttachPrepared. It returns an http.Handler that dispatches matching requests through the module's fetch export. If the module declares a cron expression and a scheduled() function, that handler is installed on the runtime's cron manager (requires Ramune's cron support).

The returned handler uses Go's http.ServeMux to apply the module's route pattern (Go 1.22+ syntax: /foo/{id}, /bar/{rest...}). If the module omits route, the handler matches every path.

func TranspileModule

func TranspileModule(filename string, code string) (string, error)

TranspileModule wraps a Workers-style source as an IIFE that sets globalThis.__workers_export = { default: <exported value> }.

export default { fetch(r,e){…} }

becomes

var __workers_export = (() => { … return { default: … }; })();

Returned code may be evaluated with Runtime.Exec in any context; it does not rely on ESM host support.

Types

type Config

type Config struct {
	// WaitUntilTimeout bounds how long the executor is held after the
	// HTTP response has been written, waiting for ctx.waitUntil
	// promises to settle. Non-positive disables the timeout.
	WaitUntilTimeout time.Duration

	// SecretsPrefix is the environment-variable prefix consulted when
	// building env.SECRETS. A variable named "<prefix>API_KEY=abc"
	// appears as env.SECRETS.API_KEY. Empty string uses the default
	// "RAMUNE_SECRET_".
	SecretsPrefix string

	// ExtraEnvJS is JavaScript appended to the env builder. It runs
	// once per runtime with the partially-built env object exposed via
	// the globalThis.__extraEnvBindings hook. Used by callers (e.g.
	// ramune.toml loaders) to attach named bindings.
	ExtraEnvJS string

	// SQLitePath, when non-empty, opens a SQLite database at the given
	// filesystem path and installs env.DB (D1-compatible) and env.KV
	// (Workers-KV-like). When empty, env.DB / env.KV access throws
	// unless a KVBackend / DBBackend has been supplied. Mutually
	// exclusive with KVBackend and DBBackend.
	SQLitePath string

	// KVBackend, when non-nil, provides the storage for env.KV. See
	// the [KVBackend] interface docs. Mutually exclusive with
	// SQLitePath.
	KVBackend KVBackend

	// DBBackend, when non-nil, provides the SQL engine for env.DB.
	// See [DBBackend]. Mutually exclusive with SQLitePath.
	DBBackend DBBackend
}

Config controls how Register wires up a Workers-style module.

type DBBackend

type DBBackend interface {
	// Query runs a read statement (SELECT) and returns every row as a
	// map keyed by column name. Values use JS-friendly Go types:
	// string, float64, bool, nil, []byte (coerced to string at the
	// boundary).
	Query(sql string, params []any) (rows []map[string]any, err error)
	// Exec runs a write statement. changes is the rows-affected count,
	// lastInsertID is the last auto-increment id, or 0 if unsupported.
	Exec(sql string, params []any) (changes, lastInsertID int64, err error)
}

DBBackend is the contract for an env.DB SQL backend.

SQL is passed through verbatim with ?-style positional parameters (D1 convention). Backends needing $1/$2 syntax (Postgres) should rewrite internally. Implementations must be safe for concurrent use.

Passing a DBBackend via WithDBBackend replaces the env.DB facade. WithSQLite + WithDBBackend is rejected.

type KVBackend

type KVBackend interface {
	// Get returns the value stored at (ns, key). ok is false when the
	// key does not exist; err is reserved for infrastructure failures.
	Get(ns, key string) (value string, ok bool, err error)
	// Put writes value at (ns, key), overwriting any existing value.
	Put(ns, key, value string) error
	// Delete removes (ns, key). Deleting a missing key must succeed.
	Delete(ns, key string) error
	// List returns up to limit keys within ns whose name starts with
	// prefix (empty prefix = all). Keys should be sorted ascending.
	List(ns, prefix string, limit int) (keys []string, err error)
}

KVBackend is the contract for an env.KV storage backend.

Methods operate on flat string values within a namespace. Implementations must be safe for concurrent use; each JS call into env.KV may run on a distinct goroutine.

Passing a KVBackend via WithKVBackend replaces the env.KV facade for the Runtime. WithSQLite already provides a KVBackend internally; supplying both WithSQLite and WithKVBackend is rejected to avoid hidden precedence.

type ModuleConfig

type ModuleConfig struct {
	Route        string
	Cron         string
	HasFetch     bool
	HasScheduled bool
}

ModuleConfig is the subset of a Workers-style module's default export that callers read once at Register time. Framework methods (Hono's route() / etc.) are filtered out so only primitive strings land here.

func ExtractModuleConfig

func ExtractModuleConfig(rt *ramune.Runtime) (*ModuleConfig, error)

ExtractModuleConfig reads __workers_export.default from rt, which must have just evaluated the IIFE emitted by TranspileModule. Exposed so embedders that run their own dispatch (e.g. Soda) can reuse the Ramune inspection instead of duplicating it.

type Option

type Option func(*Config)

Option configures Register.

func WithDBBackend

func WithDBBackend(b DBBackend) Option

WithDBBackend installs a pluggable SQL backend for env.DB. Cannot be combined with WithSQLite.

func WithExtraEnvJS

func WithExtraEnvJS(js string) Option

WithExtraEnvJS attaches JavaScript that extends the env object. The snippet must define globalThis.__extraEnvBindings(env) or mutate env directly. Runs once per Runtime, after the default env builders (SECRETS, and, if enabled, DB/KV) are installed.

func WithKVBackend

func WithKVBackend(b KVBackend) Option

WithKVBackend installs a pluggable storage backend for env.KV. Cannot be combined with WithSQLite.

func WithSQLite

func WithSQLite(path string) Option

WithSQLite opens a SQLite database at the given path and installs env.DB (a D1-compatible SQL facade) and env.KV (a Workers-KV-like key/value store backed by a single table __ramune_kv). Without this option, env.DB and env.KV access throws at runtime.

An empty path disables SQLite; ":memory:" uses an in-process DB. Multiple Register calls that pass the same path share a DB handle.

func WithSecretsPrefix

func WithSecretsPrefix(p string) Option

WithSecretsPrefix overrides the env.SECRETS variable prefix. The default is "RAMUNE_SECRET_".

func WithWaitUntilTimeout

func WithWaitUntilTimeout(d time.Duration) Option

WithWaitUntilTimeout sets the ctx.waitUntil promise timeout. Non-positive disables the timeout (wait indefinitely).

type Prepared

type Prepared struct {
	// contains filtered or unexported fields
}

Prepared is a transpiled Workers module ready to attach to one or more Runtimes. Transpile runs esbuild once; each Runtime reuses the same output via AttachPrepared. Callers with a single Runtime can use the Register shortcut which bundles Prepare + AttachPrepared.

func Prepare

func Prepare(filename, code string) (*Prepared, error)

Prepare runs esbuild on the source and returns a Prepared module that can be attached to one or more Runtimes via AttachPrepared. Use this when serving a single entry across N independent VMs (ramune serve --workers N) to avoid running esbuild per VM.

type RamuneTOML

type RamuneTOML struct {
	Dependencies map[string]string `toml:"dependencies"`
	Permissions  *TOMLPermissions  `toml:"permissions"`
	KVNamespaces []TOMLKVBinding   `toml:"kv_namespaces"`
	Secrets      *TOMLSecrets      `toml:"secrets"`
}

RamuneTOML mirrors the on-disk schema of ramune.toml, an optional declarative config placed next to the worker entrypoint.

Only fields understood by the workers package are listed here; the ramune CLI may parse additional top-level keys separately.

func LoadRamuneTOML

func LoadRamuneTOML(path string) (*RamuneTOML, error)

LoadRamuneTOML parses a ramune.toml file. Returns (nil, nil) if the file does not exist — the TOML is optional.

type TOMLDerived

type TOMLDerived struct {
	Dependencies []string
	Permissions  *ramune.Permissions
	Options      []Option
}

TOMLDerived is the subset of configuration derived from a ramune.toml file. Callers pass it to Register (in two parts: Permissions and NPM dependencies go to ramune.New, the rest become workers Options).

func ApplyRamuneTOML

func ApplyRamuneTOML(r *RamuneTOML) (TOMLDerived, error)

ApplyRamuneTOML converts a parsed TOML into the pieces the caller needs: npm packages to pass to ramune.Dependencies, ramune Permissions, and workers.Option values. Returns an empty TOMLDerived for a nil input so callers can unconditionally merge.

type TOMLKVBinding

type TOMLKVBinding struct {
	Binding   string `toml:"binding"`
	Namespace string `toml:"namespace"`
}

TOMLKVBinding declares a named KV binding exposed on env.

[[kv_namespaces]]
binding = "SESSIONS"
namespace = "sessions"

turns into env.SESSIONS backed by the "sessions" namespace of the shared SQLite KV store (requires WithSQLite).

type TOMLPermissions

type TOMLPermissions struct {
	Net   string `toml:"net"`
	Read  string `toml:"read"`
	Write string `toml:"write"`
	Env   string `toml:"env"`
	Run   string `toml:"run"`

	NetHosts   []string `toml:"net_hosts"`
	ReadPaths  []string `toml:"read_paths"`
	WritePaths []string `toml:"write_paths"`
	EnvVars    []string `toml:"env_vars"`
	RunCmds    []string `toml:"run_cmds"`
}

TOMLPermissions mirrors the [permissions] table.

type TOMLSecrets

type TOMLSecrets struct {
	Prefix string `toml:"prefix"`
}

TOMLSecrets configures how the SECRETS binding is populated. A blank prefix falls back to "RAMUNE_SECRET_".

Jump to

Keyboard shortcuts

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