common

package
v0.2.37 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 19 Imported by: 0

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

View Source
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.

View Source
const MaxJSONBody = 8 << 20

MaxJSONBody is the largest JSON request body the emulator reads.

View Source
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

View Source
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

func AfterCursor(created int64, sort string, cCreated int64, cSort string) bool

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 B64

func B64(b []byte) string

B64 encodes bytes as unpadded base64url (the JWT segment encoding).

func Base62

func Base62(n int) string

Base62 returns a base62 string of length n (used for search doc ids).

func Caller added in v0.2.35

func Caller(ctx context.Context) string

Caller is the surface WithCaller set, else "".

func CheckBool

func CheckBool(cfg map[string]any, key string, nullOK bool) error

CheckBool: absent or a boolean, and null too when nullOK (the hosted validators differ per field).

func CheckRateLimit

func CheckRateLimit(cfg map[string]any, key string) error

CheckRateLimit: absent/null, or a positive integer (requests per minute).

func CheckRegion

func CheckRegion(cfg map[string]any) error

CheckRegion: absent/null, or one of Regions.

func DecodeListCursor

func DecodeListCursor(cursor string) (created int64, sort string, ok bool)

DecodeListCursor returns the position and whether there was one to read.

func EncodeListCursor

func EncodeListCursor(created int64, sort string) string

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 FirstErr

func FirstErr(errs ...error) error

FirstErr returns the first non-nil error.

func Int

func Int(v any) (int64, bool)

Int reads a JSON number that is a whole number.

func LooksLikeJWT

func LooksLikeJWT(token string) bool

LooksLikeJWT reports whether a bearer credential is a JWT (three dot-separated segments) rather than an API key (`prefix.secret`, two segments).

func NamespaceFile

func NamespaceFile(dir, ns, stem string) string

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

func NamespaceFileName(ns string) string

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

func NamespaceFromFileName(stem string) (ns string, ok bool)

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 Number

func Number(v any) (float64, bool)

Number reads a JSON number.

func PageLimit

func PageLimit(raw string, def, max int) int

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

func ParseVersionedName(label string) (base string, version int, ok bool)

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

func PeekJWTPayload(token string) []byte

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

func PrepareDataDir(dir string) error

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 RandID

func RandID(n int) string

RandID returns n bytes of randomness as base64url (no padding).

func ReadJSON

func ReadJSON(r *http.Request, v any) error

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

func ReadJSONLimited(r *http.Request, v any, maxBytes int) error

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

func ReadShaped(r *http.Request, out any, validate func(any) error) error

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

func SignJWTPayload(payload []byte, secret string) string

SignJWTPayload wraps an already-marshalled claims payload in an HS256 JWT.

func Trigger added in v0.2.33

func Trigger(r *http.Request) string

Trigger is what invoked a function request: the trigger WithTrigger set, else "http".

func TriggerDepth added in v0.2.35

func TriggerDepth(ctx context.Context) int

TriggerDepth is the depth WithTriggerDepth set, else 0.

func UUID

func UUID() string

UUID returns a random RFC-4122 v4 UUID string.

func ValidateNamespace

func ValidateNamespace(ns string) error

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

func VerifyJWTPayload(token, secret string) []byte

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

func WithCaller(ctx context.Context, caller string) context.Context

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

func WithTrigger(r *http.Request, trigger string) *http.Request

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

func WithTriggerDepth(ctx context.Context, depth int) context.Context

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

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

func WriteFileAtomic(path string, data []byte, perm os.FileMode) error

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.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as JSON with the given status.

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 AlreadyExists(msg string) *APIError

func BadRequest

func BadRequest(msg string) *APIError

Common constructors matching the hosted API's status/code pairs.

func NewError

func NewError(status int, message, code string) *APIError

NewError builds an APIError. Code defaults to INVALID_ARGUMENT when empty.

func NotFound

func NotFound(msg string) *APIError

func PermissionDenied

func PermissionDenied(msg string) *APIError

func Precondition

func Precondition(msg string) *APIError

func Unauthenticated

func Unauthenticated(msg string) *APIError

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) WithDetails

func (e *APIError) WithDetails(d map[string]any) *APIError

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc is an http handler that returns an error, rendered via WriteError.

Jump to

Keyboard shortcuts

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