Documentation
¶
Overview ¶
Package common holds cross-service primitives: the API error envelope, JSON request/response helpers, and small id/crypto utilities. Error shapes match the hosted altengine API exactly, so client SDKs written against production behave identically against the emulator.
Index ¶
- Constants
- Variables
- func AfterCursor(created int64, sort string, cCreated int64, cSort string) bool
- func B64(b []byte) string
- func Base62(n int) string
- func Caller(ctx context.Context) string
- func CheckBool(cfg map[string]any, key string, nullOK bool) error
- func CheckRateLimit(cfg map[string]any, key string) error
- func CheckRegion(cfg map[string]any) error
- func DecodeListCursor(cursor string) (created int64, sort string, ok bool)
- func EncodeListCursor(created int64, sort string) string
- func FirstErr(errs ...error) error
- func Int(v any) (int64, bool)
- func LooksLikeJWT(token string) bool
- func NamespaceFile(dir, ns, stem string) string
- func NamespaceFileName(ns string) string
- func NamespaceFromFileName(stem string) (ns string, ok bool)
- func Number(v any) (float64, bool)
- func PageLimit(raw string, def, max int) int
- func ParseVersionedName(label string) (base string, version int, ok bool)
- func PeekJWTPayload(token string) []byte
- func PrepareDataDir(dir string) error
- func RandID(n int) string
- func ReadJSON(r *http.Request, v any) error
- func ReadJSONLimited(r *http.Request, v any, maxBytes int) error
- func ReadShaped(r *http.Request, out any, validate func(any) error) error
- func SignJWTPayload(payload []byte, secret string) string
- func Trigger(r *http.Request) string
- func TriggerDepth(ctx context.Context) int
- func UUID() string
- func ValidateNamespace(ns string) error
- func VerifyJWTPayload(token, secret string) []byte
- func WithCaller(ctx context.Context, caller string) context.Context
- func WithTrigger(r *http.Request, trigger string) *http.Request
- func WithTriggerDepth(ctx context.Context, depth int) context.Context
- func Wrap(h HandlerFunc) http.HandlerFunc
- func WriteError(w http.ResponseWriter, err error)
- func WriteFileAtomic(path string, data []byte, perm os.FileMode) error
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type APIError
- type HandlerFunc
Constants ¶
const ( DataDirPerm os.FileMode = 0o700 DataFilePerm os.FileMode = 0o600 )
Data directories and the files in them are owner-only: control.json holds every channel and auth instance's signing secret, and the databases hold whatever the app under development put in them.
const MaxJSONBody = 8 << 20
MaxJSONBody is the largest JSON request body the emulator reads.
const NamespaceDefaultSegment = "_default"
NamespaceDefaultSegment is the reserved wire spelling of the default namespace ("") — a URL path cannot carry an empty segment — so it can never be a namespace of its own.
Variables ¶
var Regions = []string{"auto", "wnam", "enam", "sam", "weur", "eeur", "apac", "apac-ne", "apac-se", "oc", "afr", "me"}
Regions are the placement hints every service accepts. Locally they change nothing.
Functions ¶
func AfterCursor ¶
AfterCursor reports whether a row at (created, sort) falls after the cursor position, in the newest-first order these listings use. Same comparison the hosted API makes in SQL.
func CheckBool ¶
CheckBool: absent or a boolean, and null too when nullOK (the hosted validators differ per field).
func CheckRateLimit ¶
CheckRateLimit: absent/null, or a positive integer (requests per minute).
func CheckRegion ¶
CheckRegion: absent/null, or one of Regions.
func DecodeListCursor ¶
DecodeListCursor returns the position and whether there was one to read.
func EncodeListCursor ¶
ListCursor is the keyset position a paged listing hands back: the (created, sort) of the last row it returned. The hosted API encodes it the same way — base64url of [created, sort] — so a client that follows a cursor from the emulator follows one from production unchanged.
A cursor is a position, not a credential. Decoding is forgiving by design: anything that does not parse means "start at the beginning" rather than an error, because a truncated cursor in a URL should not fail a listing.
func LooksLikeJWT ¶
LooksLikeJWT reports whether a bearer credential is a JWT (three dot-separated segments) rather than an API key (`prefix.secret`, two segments).
func NamespaceFile ¶
NamespaceFile is the path of a namespace's database in dir, given the stem the store encodes it to. Two upgrades meet here:
- A namespace an older emulator stored verbatim and that is escaped now (mixed case, a device name) keeps using its old file when that is the one on disk, so its data still opens. The match is on the exact name, so on a case-insensitive filesystem `orders.db` is not taken for `Orders`.
- A namespace with characters older emulators replaced with "_" (`org:1` was `org_1.db`) cannot be mapped back — that file may as well belong to `org_1` itself — so it starts empty, and its first open logs where the old data is and the name it is listed under now.
func NamespaceFileName ¶
NamespaceFileName is the file-name stem a namespace's database is stored under. It is one-to-one, on case-insensitive filesystems too, so `a b`, `a/b`, `a_b`, `A_b` get four files. A name made only of [a-z0-9_.-] that is not a Windows device name is used as is — the stem it always had — and any other name is "~" plus its lowercase hex: "~" is never verbatim, and the longest valid namespace still fits a file name.
func NamespaceFromFileName ¶
NamespaceFromFileName maps a stem found on disk back to its namespace: one NamespaceFileName produced, or one an older emulator stored verbatim (see NamespaceFile). ok is false for a stem neither can have produced.
func PageLimit ¶
PageLimit reads a `limit` query parameter as hosted: anything that is not a finite number of at least 1 is the default — never "no limit" — and the result is capped at max.
func ParseVersionedName ¶
ParseVersionedName splits `myapp--v3` into ("myapp", 3). Hosted this is the instance label of a `{slug}--v{n}-{fn|web}` hostname; locally it is the instance segment of a public path, which stands in for that hostname. ok is false for anything that is not exactly that shape — `v0`, `v03`, a bare `my--app`.
func PeekJWTPayload ¶
PeekJWTPayload decodes a token's claims segment WITHOUT verifying the signature. Only ever use the result to find which secret to verify with — never to authorize.
func PrepareDataDir ¶
PrepareDataDir creates dir owner-only and, when it is the emulator's own directory, drops a .gitignore in it so its secrets are not committed by a `git add -A`.
"Its own" is a directory this call created, or one named .altengine*: a --data that points at an existing folder the developer chose (a project root, say) is not tightened or ignored wholesale.
func ReadJSON ¶
ReadJSON decodes the request body into v, returning a 400 on malformed JSON and a 413 on a body over MaxJSONBody. An empty body decodes to the zero value (the hosted API is tolerant the same way).
func ReadJSONLimited ¶
ReadJSONLimited is ReadJSON with a smaller cap, for public routes whose bodies are small by nature: a body over maxBytes is a 413, refused up front from Content-Length when it says so.
func ReadShaped ¶
ReadShaped reads a JSON body, checks its shape with validate (which sees the body as generic JSON, so a wrong type is named rather than failing the decode), then decodes it into out. An empty body decodes to the zero value, as ReadJSON does.
func SignJWTPayload ¶
SignJWTPayload wraps an already-marshalled claims payload in an HS256 JWT.
func Trigger ¶ added in v0.2.33
Trigger is what invoked a function request: the trigger WithTrigger set, else "http".
func TriggerDepth ¶ added in v0.2.35
TriggerDepth is the depth WithTriggerDepth set, else 0.
func ValidateNamespace ¶
ValidateNamespace enforces the hosted API's namespace rules, for datastore and search alike: printable ASCII, at most 100 bytes; "" (the default namespace) is allowed. Everything keyed on (namespace, name) NUL-joins the pair, so a namespace may never contain NUL.
func VerifyJWTPayload ¶
VerifyJWTPayload checks the HS256 signature and returns the claims segment, or nil. Expiry is NOT checked here — the caller owns its own `exp` semantics.
func WithCaller ¶ added in v0.2.35
WithCaller names the surface an in-process request comes from ("function", "mcp") — a task records where it was added, as hosted. Context only, so no network caller can claim one.
func WithTrigger ¶ added in v0.2.33
WithTrigger marks an in-process request to a function as a platform trigger ("container", "automation"). It rides the request context, which no caller over the network can set.
func WithTriggerDepth ¶ added in v0.2.35
WithTriggerDepth records the trigger-chain depth an in-process request runs at: a function run by a task carries the task's depth, and every write it makes through its env bindings carries it on, so the event that write fires is one deeper. Context only — no caller over the network can set or read it.
func Wrap ¶
func Wrap(h HandlerFunc) http.HandlerFunc
Wrap adapts a HandlerFunc to http.HandlerFunc, writing the error envelope on failure.
func WriteError ¶
func WriteError(w http.ResponseWriter, err error)
WriteError renders any error as the standard envelope. Non-APIError becomes a 500 INTERNAL.
func WriteFileAtomic ¶
WriteFileAtomic replaces path with data so that a reader — or the next start after a crash or a full disk — sees either the old file or the new one, never a truncated mix. It writes a temp file in the same directory (a rename is only atomic within one filesystem), fsyncs it, and renames it over path. On any error the previous file is left exactly as it was.
Types ¶
type APIError ¶
type APIError struct {
Status int `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
}
APIError is the emulator's structured API error. The global handler serializes it to {"error":{"code","message","details?}} with the given HTTP status.
func AlreadyExists ¶
func BadRequest ¶
Common constructors matching the hosted API's status/code pairs.
func PermissionDenied ¶
func Precondition ¶
func Unauthenticated ¶
type HandlerFunc ¶
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
HandlerFunc is an http handler that returns an error, rendered via WriteError.