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 ¶
- func BacklogQuery(queue string) string
- func BucketName(name string) (string, error)
- func Enqueue(ctx context.Context, queue string, payload any, opts ...EnqueueOption) (int64, error)
- func HTTP(name string, h http.Handler, opts ...Option)
- func HTTPFunc(name string, f func(http.ResponseWriter, *http.Request), opts ...Option)
- func KVDelete(ctx context.Context, key string) (bool, error)
- func KVGet(ctx context.Context, key string, v any) (bool, error)
- func KVList(ctx context.Context, prefix, cursor string, limit int) (keys []string, next string, err error)
- func KVSet(ctx context.Context, key string, v any, ttl time.Duration) error
- func Migrations(fsys fs.FS)
- func OnShutdown(fn func(ctx context.Context) error)
- func Pool(ctx context.Context) (*pgxpool.Pool, error)
- func Queue(name, queue string, f func(ctx context.Context, job *Job) error, ...)
- func Schedule(name, schedule string, f func(ctx context.Context) error, opts ...Option)
- func Secret(name string) (string, error)
- func Start()
- type DB
- type EnqueueOption
- type Job
- type Option
- func Backoff(d time.Duration) Option
- func CPU(q string) Option
- func Concurrency(n int) Option
- func HealthPath(p string) Option
- func MaxAttempts(n int) Option
- func MaxInstances(n int) Option
- func Memory(q string) Option
- func MemoryLimit(q string) Option
- func MemoryVolume(path, sizeLimit string) Option
- func MinInstances(n int) Option
- func Proxied() Option
- func Public() Option
- func ReadOnlyRootFilesystem() Option
- func Retries(n int) Option
- func TimeZone(tz string) Option
- func Timeout(d time.Duration) Option
- func User(id int64) Option
- func Volume(path, sizeLimit string) Option
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BacklogQuery ¶
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
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 KVGet ¶ added in v0.3.0
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
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
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
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 ¶
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 ¶
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 ¶
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
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.
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 ¶
Backoff is the delay before a job's first retry, doubled for each later one (default 10s).
func Concurrency ¶
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
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 ¶
MaxAttempts is how often a job is tried before it's marked failed (default 5).
func MaxInstances ¶
MaxInstances caps an HTTP or queue function's instances (default 3).
func MemoryLimit ¶ added in v0.5.0
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
MemoryVolume is a Volume in RAM (tmpfs), counted against the container's memory: a bigger /dev/shm for Chromium, say.
func MinInstances ¶
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 Timeout ¶
Timeout limits one request (default 5m, at most 10m), one scheduled run (default 1h) or one job (default 5m).
Source Files
¶
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. |