functions

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 25 Imported by: 0 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

functions (Go)

Write functions for maxcloud, the homelab's run platform, in Go. It's the Go twin of @max-cloud/functions: the same kinds of function, the same queue table, and the same contract with mcloud, so one app's Node.js and Go parts can share a queue.

go get github.com/maxemiliang/maxcloud/functions@latest
package main

import (
	"context"
	"net/http"
	"time"

	"github.com/maxemiliang/maxcloud/functions"
)

func main() {
	// A Knative service: scales to zero, starts on the first request.
	functions.HTTPFunc("api", api, functions.Public())
	// A CronJob.
	functions.Schedule("nightly", "0 3 * * *", nightly, functions.Timeout(10*time.Minute))
	// A worker that KEDA starts when the queue has jobs.
	functions.Queue("resize", "images", resize, functions.Concurrency(2))
	functions.Start()
}

func api(w http.ResponseWriter, r *http.Request) {
	id, err := functions.Enqueue(r.Context(), "images", map[string]string{"key": r.URL.Query().Get("key")})
	...
}

func nightly(ctx context.Context) error { ... }

func resize(ctx context.Context, job *functions.Job) error {
	var p struct{ Key string }
	if err := job.Decode(&p); err != nil {
		return err
	}
	...
}

The name you register becomes the function's: its service, CronJob or worker. Use at most 40 lowercase letters, digits and dashes, starting with a letter; a bad name, a name registered twice or a bad cron schedule panics. functions.HTTP(name, handler) takes any http.Handler (a router, say); HTTPFunc takes a handler function. A handler that panics answers 500.

Options

Option Applies to Default
Public() HTTP private: cluster-local
MinInstances(n) HTTP 0 (scale to zero)
MaxInstances(n) HTTP, queue 3
Concurrency(n) HTTP: requests per instance; queue: jobs per instance 0 (no limit) / 1
Timeout(d) HTTP request (≤ 10m), scheduled run, job 5m / 1h / 5m
Memory(q), CPU(q) all the namespace's defaults
TimeZone(tz) schedule UTC
Retries(n) schedule 0
MaxAttempts(n) queue 5
Backoff(d) queue: first retry's delay, doubled each time (fractions of a second too) 10s
Proxied() HTTP: the public hostname behind Cloudflare (WAF, caching, Access); needs Public() off
HealthPath(p) HTTP: a path that answers 2xx when an instance can take requests (readiness, and a liveness probe that restarts a stuck one) none
MemoryLimit(q) all: memory above Memory (the request), for spikes Memory
User(id) all: run as this user id and group, for an image without a non-root USER the image's
ReadOnlyRootFilesystem() all: write only to volumes off
Volume(path, sizeLimit), MemoryVolume(path, sizeLimit) all: a scratch directory, empty at each start; MemoryVolume is in RAM and counts against the memory limit. Knative doesn't allow /tmp: point TMPDIR at a volume none

Options that don't apply to a function's kind are ignored. Timeouts are rounded up to whole seconds.

Queues

functions.Enqueue(ctx, queue, payload) adds a job and returns its id; the payload is stored as JSON, and the handler reads it with job.Decode(&v). A queue's name is lowercase letters, digits, dashes and underscores. Jobs live in the app's Postgres database ($DATABASE_URL; the app gets one with db: true in its maxcloud.yaml), in a table the SDK creates (maxcloud_jobs).

  • Retries: a job whose handler returns an error, panics, or passes its timeout is retried, and so is one whose worker died, once its lease (the timeout plus 30 seconds) runs out. Jobs can run more than once, so make handlers safe to repeat.
  • Return when ctx is done. A handler that ignores it keeps running in the background after its job has been counted as failed.
  • Shutting down: on SIGTERM the worker takes no new jobs, gives the ones in hand 25 seconds, then cancels their ctx and puts them back without counting the attempt.
  • Enqueue in your own transaction with functions.In(tx) (a pgx.Tx, *pgx.Conn or pool), and the job exists only if the transaction commits. The table must exist by then (a worker or an earlier Enqueue creates it).
  • Delay a job with functions.Delay(d).
  • Cleanup: a worker deletes jobs that finished more than 7 days ago when it starts. Failed jobs stay, with the error in last_error.
  • Connections: a worker claims and finishes jobs on a pool of its own, Concurrency(n) + 1 connections (one is its LISTEN). Handlers use functions.Pool, which pgx sizes to max(4, CPUs): with a high concurrency, handlers wait for each other there, not for the worker.

Database

With db: true in the app's maxcloud.yaml, every function gets $DATABASE_URL. functions.Pool(ctx) is a pgx pool on it, made on first use and shared with Enqueue and the KV functions:

p, err := functions.Pool(ctx)
err = p.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)

It returns an error if $DATABASE_URL isn't set.

Migrations

Put SQL migrations in migrations/ at the app's root, named NUMBER_DESCRIPTION.sql with numbers of one width: 0001_init.sql, 0002_add_orders.sql. Embed them, since the built image has the binary and not the source, and hand them to the runtime before Start:

//go:embed migrations
var migrations embed.FS

func main() {
	functions.Migrations(migrations)
	functions.HTTPFunc("api", api)
	functions.Start()
}

Before Start runs a function, it applies the ones the database hasn't had: each once, in name order, in its own transaction, recorded in the table maxcloud_migrations (the one the connection's search_path finds, else a new one in its current schema: public on maxcloud). Only one process applies them at a time; the others wait, so no function starts on an older schema than its code expects. A migration that fails, a file edited after it was applied, or migrations without a $DATABASE_URL stop the process (exit 1). A migration the database has but the binary doesn't is left alone. MAXCLOUD_MIGRATE=0 in the environment turns it off. --describe lists the embedded files, and the deploy warns when migrations/ has one the binary doesn't.

Dev mode leaves them to mcloud dev, which applies them from migrations/ before it starts the app; mcloud db migrate applies them by hand (maxcloud's README, "Migrations", has the rules).

Buckets

An app's S3 buckets are listed in its maxcloud.yaml (buckets: [uploads, assets:public]); the maxcloud controller creates them as mc-<app>--<bucket> and gives every function the app's credentials as AWS_* environment variables, which the AWS SDK reads by itself. MAXCLOUD_APP, the app's name, is set on every function. functions.BucketName("uploads") returns the full name (or an error without MAXCLOUD_APP). Each bucket's full name is also in MAXCLOUD_BUCKET_<NAME> (MAXCLOUD_BUCKET_UPLOADS), for libraries configured by environment; a pod started before the bucket existed doesn't have it.

cfg, err := config.LoadDefaultConfig(ctx)
s3c := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true })
bucket, err := functions.BucketName("uploads") // "mc-shop--uploads"
_, err = s3c.PutObject(ctx, &s3.PutObjectInput{Bucket: &bucket, Key: aws.String("a.txt"), Body: r})
Public buckets

A bucket listed as assets:public can be read by anyone (not listed) at https://<bucket>--<app>.gronblom.dev/<key>, behind Cloudflare, which caches it. Writing still needs the app's credentials:

bucket, _ := functions.BucketName("assets")
key := "avatars/" + userID + "." + hash + ".png" // new content, new key: the CDN caches
_, err = s3c.PutObject(ctx, &s3.PutObjectInput{
	Bucket: &bucket, Key: &key, Body: png,
	ContentType:  aws.String("image/png"),
	CacheControl: aws.String("public, max-age=31536000, immutable"),
})
url := "https://assets--" + os.Getenv("MAXCLOUD_APP") + ".gronblom.dev/" + key

The objects are also readable straight from Object Storage, at <AWS_ENDPOINT_URL_S3>/<full bucket name>/<key> (not cached). Removing :public makes the bucket private again; its objects stay.

Key-value storage

KVGet, KVSet, KVDelete and KVList are a key-value store (like Workers KV) in the app's Postgres database (DATABASE_URL; the app needs db: true in its maxcloud.yaml). Values are JSON; reads see writes right away. Keys are 1 to 512 bytes.

err := functions.KVSet(ctx, "session:42", session, time.Hour) // 0: no expiry
found, err := functions.KVGet(ctx, "session:42", &session)   // false if missing or expired
existed, err := functions.KVDelete(ctx, "session:42")
keys, next, err := functions.KVList(ctx, "session:", "", 100)

KVList gives keys in order after the cursor ("" to start), up to the limit (0: 100; at most 1000), and the cursor for the next page, "" when there are no more. It's one table, maxcloud_kv, made on first use.

Secrets

mcloud secrets set STRIPE_KEY (in the app's repo) stores a secret; every function gets it as an environment variable. functions.Secret("STRIPE_KEY") reads it, with an error that says how to set it when it's missing.

Running

functions.Start() runs the function named in $FUNCTION_TARGET (or --target):

  • HTTP: a server on $PORT (or --port, else 8080).
  • Schedule: one run, then it exits 0, or 1 on an error.
  • Queue: the worker loop.

First it applies the app's pending migrations (see Migrations). On SIGTERM an HTTP server or worker finishes what's in flight (up to 25 seconds) and exits 0; a scheduled run's ctx is cancelled. Start doesn't return: it exits the process, so deferred calls in main don't run. Put cleanup in functions.OnShutdown instead: it runs after the function stops (after SIGTERM, once what was in flight is done; after a schedule's run) and before the process exits.

functions.OnShutdown(func(ctx context.Context) error {
	return tracer.Shutdown(ctx) // close a pool, flush logs
})

Hooks run in the order they were registered, for at most 10 seconds together (ctx ends then). One that fails (an error or a panic) is logged and the rest still run. If one failed, or they're still running after 10 seconds, the process exits 1. The TypeScript SDK's onShutdown works the same way.

With --describe it prints the registered functions, their settings and the embedded migrations as JSON instead. With MAXCLOUD_DESCRIBE=1 in the environment it prints the same as one line, maxcloud:describe:{...}. That's how the deploy asks the built image: it runs it with that variable and the image's own command, so the image has to run your binary, and reads the line. Register functions in main before Start, and don't connect to anything before that: describing runs without the database or secrets. To see what a deploy would write:

go run . --describe | mcloud generate --from -

Local development

Run mcloud dev in the app's repo. It starts a local Postgres (in Docker) or port-forwards to a database branch, sets DATABASE_URL, MAXCLOUD_APP and the secrets from .env (keep it out of git), and runs the app in dev mode with go run .. It doesn't watch for changes: restart it yourself.

Dev mode is go run . --dev, or MAXCLOUD_DEV=1 in the environment. It runs the whole app in one process, with MAXCLOUD_DEV=1 set:

  • One server on 127.0.0.1, on --port, $PORT or 8080.
  • http://<name>.localhost:<port>/ reaches the HTTP function registered as <name>. The request goes through as it is (path, method, headers, body), so a router mounted at / works.
  • GET http://localhost:<port>/ lists the functions as JSON.
  • POST http://localhost:<port>/_run/<name> runs a scheduled function once. It answers 200 ok, or 500 with the error. Schedules never run on their cron in dev mode.
  • Queue workers run in the same process when DATABASE_URL is set. Without it they don't, and Enqueue fails as it would anywhere else.

At startup it prints each function and where to reach it. Ctrl-C finishes the requests and jobs in flight, then exits.

To run a single function, the way its container does:

FUNCTION_TARGET=api go run .

Documentation

Overview

Package functions writes HTTP, scheduled and queue functions for maxcloud, the homelab's run platform. Register them in main and call Start:

func main() {
	functions.HTTPFunc("hello", hello, functions.Public())
	functions.Schedule("nightly", "0 3 * * *", nightly)
	functions.Queue("resize", "images", resize)
	functions.Start()
}

Each function is deployed on its own: an HTTP function as a Knative service that scales to zero, a schedule as a CronJob, a queue function as a worker that KEDA starts when its queue has jobs. The container runs the same binary for all of them; Start runs the one named in $FUNCTION_TARGET.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BacklogQuery

func BacklogQuery(queue string) string

BacklogQuery is the query KEDA scales a queue's worker on: jobs due or being worked on. Counting running jobs too keeps a worker alive until its jobs finish.

func BucketName added in v0.2.0

func BucketName(name string) (string, error)

BucketName is the full name of one of the app's buckets: BucketName("uploads") is "mc-shop--uploads" in app shop.

An app asks for buckets in its maxcloud.yaml (buckets: [uploads]). The maxcloud controller puts the app's credentials in the Secret maxcloud-s3, which every function gets as the AWS_* environment variables the AWS SDK reads by itself (endpoint, region, keys, UpCloud's checksum settings). MAXCLOUD_APP, the app's name, is set on every function. With aws-sdk-go-v2:

cfg, _ := config.LoadDefaultConfig(ctx)
s3c := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true })
bucket, err := functions.BucketName("uploads")
...
s3c.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), ...})

func Enqueue

func Enqueue(ctx context.Context, queue string, payload any, opts ...EnqueueOption) (int64, error)

Enqueue adds a job to a queue and returns its id. The payload is stored as JSON.

func HTTP

func HTTP(name string, h http.Handler, opts ...Option)

HTTP registers an HTTP function. The name becomes its service's name.

func HTTPFunc

func HTTPFunc(name string, f func(http.ResponseWriter, *http.Request), opts ...Option)

HTTPFunc registers an HTTP function from a handler function.

func KVDelete added in v0.3.0

func KVDelete(ctx context.Context, key string) (bool, error)

KVDelete removes key and reports whether it was there.

func KVGet added in v0.3.0

func KVGet(ctx context.Context, key string, v any) (bool, error)

KVGet reads key into v (as JSON). It reports false, and leaves v alone, if the key isn't there or has expired.

func KVList added in v0.3.0

func KVList(ctx context.Context, prefix, cursor string, limit int) (keys []string, next string, err error)

KVList returns up to limit keys (default 100, also for 0; max 1000) in order that start with prefix and come after cursor (""), and the cursor for the next page ("" when there are no more).

func KVSet added in v0.3.0

func KVSet(ctx context.Context, key string, v any, ttl time.Duration) error

KVSet stores v (as JSON) under key, replacing what was there. ttl > 0 forgets it after ttl; 0 keeps it.

func Migrations added in v0.5.0

func Migrations(fsys fs.FS)

Migrations gives Start the app's SQL migrations: fsys holds a migrations directory of NUMBER_DESCRIPTION.sql files (0001_init.sql, ...), the way //go:embed gives one:

//go:embed migrations
var migrations embed.FS

func main() {
	functions.Migrations(migrations)
	...
	functions.Start()
}

Before it runs a function, Start applies the ones the database hasn't had, each once, in name order, the same way mcloud db migrate does (and recorded in the same table, maxcloud_migrations). Only one process applies them at a time; the others wait, so no function runs on an older schema than its code expects. A migration that fails stops the process. Dev mode leaves them to mcloud dev, which applies them before it starts the app. MAXCLOUD_MIGRATE=0 in the environment turns it off.

func OnShutdown added in v0.6.0

func OnShutdown(fn func(ctx context.Context) error)

OnShutdown runs fn when the function stops (after SIGTERM, once the requests or jobs in flight are done; after a schedule's run), before the process exits: close a pool, flush logs. Start exits with os.Exit, so deferred calls in main never run; this is where that cleanup goes.

Hooks run in the order they were registered, for at most 10 seconds together; ctx ends at that deadline. A hook that returns an error or panics is logged and the rest still run. If one failed, or they're still running at the deadline, the process exits 1 (or with the function's own non-zero code).

func Pool

func Pool(ctx context.Context) (*pgxpool.Pool, error)

Pool is the app's database: the connection pool on $DATABASE_URL, made on first use and shared with Enqueue and the KV functions.

func Queue

func Queue(name, queue string, f func(ctx context.Context, job *Job) error, opts ...Option)

Queue registers a worker for a queue. Add jobs with Enqueue. A job whose handler returns an error, panics or passes its timeout is retried with backoff; one whose worker died is claimed again once its lease runs out. Jobs can run more than once, so make handlers safe to repeat, and let them return when ctx is done.

func Schedule

func Schedule(name, schedule string, f func(ctx context.Context) error, opts ...Option)

Schedule registers a function run on a five-field cron schedule, e.g. "0 3 * * *". A run that returns an error exits 1.

func Secret added in v0.3.0

func Secret(name string) (string, error)

Secret returns the app's secret name (mcloud secrets set NAME), which reaches every function as an environment variable, or an error that says how to set it. Read it where it's used, not at package init: MAXCLOUD_DESCRIBE runs the app without its secrets.

func Start

func Start()

Start runs the function named in $FUNCTION_TARGET (or --target) and exits when it's done: an HTTP function serves on $PORT until SIGTERM, a schedule runs once, a queue worker runs until SIGTERM. On SIGTERM it finishes what's in flight and exits 0, so pods don't end in Error.

Start calls os.Exit, so deferred calls in main don't run: register cleanup with OnShutdown instead.

Before it runs the function, it applies the app's pending SQL migrations (see Migrations).

With --describe, or MAXCLOUD_DESCRIBE=1 in the environment, it prints the registered functions as JSON instead, which is how mcloud deploys them.

With --dev, or MAXCLOUD_DEV=1, it runs the whole app locally instead, on 127.0.0.1:$PORT (or --port, or 8080): http://<name>.localhost:<port>/ reaches an HTTP function, GET / lists the functions, POST /_run/<name> runs a schedule once, and queue workers run when $DATABASE_URL is set. mcloud dev runs it this way.

Types

type DB

type DB interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

DB runs queries: a *pgxpool.Pool, a *pgx.Conn or a pgx.Tx.

type EnqueueOption

type EnqueueOption func(*enqueueOptions)

An EnqueueOption changes how Enqueue adds a job.

func Delay

func Delay(d time.Duration) EnqueueOption

Delay makes the job wait at least d before it runs.

func In

func In(db DB) EnqueueOption

In inserts the job with db, e.g. your own transaction, so the job exists only if it commits. The table must already exist (any worker, or an earlier Enqueue without In, creates it).

type Job

type Job struct {
	ID        int64
	Queue     string
	Payload   json.RawMessage
	Attempt   int // 1 on the first try
	CreatedAt time.Time
}

A Job is one entry in a queue.

func (*Job) Decode

func (j *Job) Decode(v any) error

Decode unmarshals the job's payload into v.

type Option

type Option func(*options)

An Option tunes a function. Options that don't apply to a function's kind are ignored.

func Backoff

func Backoff(d time.Duration) Option

Backoff is the delay before a job's first retry, doubled for each later one (default 10s).

func CPU

func CPU(q string) Option

CPU the container requests, e.g. "100m".

func Concurrency

func Concurrency(n int) Option

Concurrency is, for an HTTP function, the requests one instance takes at once before another starts (default 0: no limit); for a queue function, the jobs one instance works on at once (default 1).

func HealthPath added in v0.5.0

func HealthPath(p string) Option

HealthPath is a path that answers 2xx when an HTTP function's instance can take requests: it gets traffic only after that, and is restarted when it stops answering.

func MaxAttempts

func MaxAttempts(n int) Option

MaxAttempts is how often a job is tried before it's marked failed (default 5).

func MaxInstances

func MaxInstances(n int) Option

MaxInstances caps an HTTP or queue function's instances (default 3).

func Memory

func Memory(q string) Option

Memory the container requests and is limited to, e.g. "256Mi".

func MemoryLimit added in v0.5.0

func MemoryLimit(q string) Option

MemoryLimit lets a function's container use more memory than Memory (its request), for spikes, e.g. "1536Mi".

func MemoryVolume added in v0.5.0

func MemoryVolume(path, sizeLimit string) Option

MemoryVolume is a Volume in RAM (tmpfs), counted against the container's memory: a bigger /dev/shm for Chromium, say.

func MinInstances

func MinInstances(n int) Option

MinInstances keeps n instances of an HTTP function running when idle (default 0: scale to zero).

func Proxied added in v0.5.0

func Proxied() Option

Proxied puts a public HTTP function's hostname behind Cloudflare (its DNS record is proxied): WAF, caching, Cloudflare Access. Needs Public.

func Public

func Public() Option

Public makes an HTTP function reachable from the internet, at https://<name>--<app>.gronblom.dev. Without it, it's cluster-local.

func ReadOnlyRootFilesystem added in v0.5.0

func ReadOnlyRootFilesystem() Option

ReadOnlyRootFilesystem makes a function's root filesystem read-only; write to a Volume (and point TMPDIR at one).

func Retries

func Retries(n int) Option

Retries is how often a failed scheduled run is retried (default 0).

func TimeZone

func TimeZone(tz string) Option

TimeZone for a schedule, an IANA name (default UTC).

func Timeout

func Timeout(d time.Duration) Option

Timeout limits one request (default 5m, at most 10m), one scheduled run (default 1h) or one job (default 5m).

func User added in v0.5.0

func User(id int64) Option

User runs a function's container as this user id (and group), for an image whose Dockerfile has no non-root USER.

func Volume added in v0.5.0

func Volume(path, sizeLimit string) Option

Volume mounts an empty scratch directory at path in a function's container, at most sizeLimit ("1Gi"; "" for no limit). Knative doesn't allow /tmp.

Directories

Path Synopsis
internal
migrate
Package migrate applies an app's SQL migrations: the files in its migrations directory, each once, in name order, recorded in the table maxcloud_migrations.
Package migrate applies an app's SQL migrations: the files in its migrations directory, each once, in name order, recorded in the table maxcloud_migrations.

Jump to

Keyboard shortcuts

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