Mail, cache, storage, events, queue, scheduler, encryption, rate limiting, i18n, logging and observability. All follow the manager/driver pattern: one typed config section, an interface, several drivers selected by config, a fake for tests. Drivers with heavy dependencies live in drivers/* modules.
| Subsystem | Phase | Core drivers | Driver modules | Fake |
|---|---|---|---|---|
Logging (log/slog) |
Prototype / ALPHA | text (dev), JSON (prod), multi; Telegram handler (ALPHA) | — | capture handler |
| Health | Prototype | /up + per-service checks |
— | — |
| ALPHA | SMTP (net/smtp), Resend and Mailtrap (HTTP APIs), log, array |
— | ✅ | |
| Cache | ALPHA | memory (LRU + TTL), database | redis | ✅ |
| Feature flags | v0.27 | code + FLAG_<NAME>, database (cached) |
— | any flags.Store |
| Storage | ALPHA / BETA | local (os.Root), memory |
s3 (AWS, R2, RustFS…) | ✅ |
| Events | ALPHA | in-process sync/async | — | ✅ (events.NewFake) |
| Queue | BETA | sync, memory, database (SQLite/Postgres, FOR UPDATE SKIP LOCKED on PG) |
redis | ✅ (queue.Fake) |
| Scheduler | BETA | in-process cron | — | clock |
| Encryption | BETA | AES-256-GCM with key rotation | — | — |
| Rate limiting | ALPHA / BETA | memory (GCRA) | redis | ✅ (memory + synctest) |
| i18n | BETA | JSON files, CLDR plural rules subset | — | i18n.New + Add |
| SSE | BETA | in-process hub | redis pub/sub | — |
| Tracing (OpenTelemetry) | BETA | — | otel | tracetest recorder |
app.Logis a*slog.Logger; the request line (middleware.Logger, messagerequest) hasmethod,path,status,duration,bytes,request_id,peer,ipand the matchedroutepattern, at ERROR for 5xx, WARN for 4xx, INFO otherwise;web.AddLogAttrs(ctx, attrs...)adds more fields (a hashed user id) from any middleware or handler under it. Site page:/docs/deployment/logging(alsoWithLogger, dedup, scheduler log lines); release and stability policy:/docs/deployment/releases-and-stability.- In a handler,
c.Log()returns the app logger. Secretvalues are redacted viaLogValuer.- Error aggregation:
logging.NewDedup(next, opts)is a stdlibslog.Handlerthat writes the first ERROR record of a kind (same level, message, handler attributes andevent/error/errvalues) and counts the repeats inside a window; when the window ends (a timer per window, orClose), onerepeatedrecord carriesmessage,countandwindow. Untracked kinds beyond 1024 per window pass through. The default logger uses it in production with a 1-minute window, in front of Telegram, andapp.Shutdownflushes pending summaries;LOG_DEDUP_WINDOWchanges the window (0disables, any duration enables it outside production). Loggers passed withWithLoggerare used as given. - OpenTelemetry:
drivers/otel(BETA) traces every request in a separate module to keep OTel out of core (OpenTelemetry). /upreturns 200 when the app booted (liveness, no dependency touched).app.AddHealthCheck/AddHealthCheckTimeoutregister readiness checks (app.DB()addsdb);app.ReadyHandler()(mount it at/ready) and/up?checks=1run them in parallel, each with its own timeout (default 3s), and answer 200 or 503 withok/failper check, never the error text.app.CheckHealth(ctx)returns the raw errors.
A slog.Handler (package logging/telegram) that sends selected records to Telegram chats, ported from the maintainer's TypeScript telegram-logger. Stdlib only (net/http).
Apps turn it on with environment variables; the app logger then fans out to stderr and Telegram (slog.NewMultiHandler):
TELEGRAM_BOT_TOKEN=123456:ABC... # config.Secret, never logged
TELEGRAM_CHAT_ID=-1001234567890
TELEGRAM_MIN_LEVEL=error # debug, info, warn, error
TELEGRAM_THREAD_ID=42 # optional forum topic
TELEGRAM_LOG=true # false: no log forwarding, app.Telegram only for Send/Contact
TELEGRAM_RATE_LIMIT=20 # optional cap on forwarded log records per minute (0: none)
TELEGRAM_API_URL=https://api.telegram.org # optional: self-hosted Bot API server or a fake; https outside development/testapp.Telegram.Contact(ctx, map[string]string{"name": in.Name, "message": in.Message}) // never filtered by level
app.Telegram.Send(ctx, "<b>Deploy</b> finished") // pre-formatted HTML
// In a queued job: deliver now and return the error so the job retries.
err := app.Telegram.ContactSync(ctx, fields) // or SendSync; telegram.ErrDisabled when not configured
// Only forward the records you mark (Filter sees log records, never Send/Contact).
vukem.WithTelegram(func(c *telegram.Config) {
c.Filter = func(_ context.Context, r slog.Record) bool { return r.Level >= telegram.LevelFatal }
})
// Panics carry panic=true (middleware.Recover). Send them to their own chat with a
// second handler, and keep them out of the main one:
panics := telegram.NewHandler(telegram.Config{
BotToken: token, ChatID: "-300", MinLevel: slog.LevelError, MinLevelSet: true,
Filter: func(_ context.Context, r slog.Record) bool { return hasPanicAttr(r) },
})
// hasPanicAttr walks r.Attrs for the "panic" key; negate it in the main handler's Filter.
// Standalone: per-level routing, silent mode, custom error handling.
tg := telegram.NewHandler(telegram.Config{
BotToken: token, ChatID: "-100", ChatIDs: map[slog.Level]string{telegram.LevelFatal: "-200"},
MinLevel: slog.LevelWarn, AppName: "Shop", Env: "production", Silent: true, OnError: report,
})
defer tg.Close(ctx)| Feature | Detail |
|---|---|
| Levels | debug, info, warn, error plus telegram.LevelSuccess and telegram.LevelFatal; MinLevel filter (slog.LevelInfo is the zero value: set MinLevelSet in a standalone config; vukem.New does it for TELEGRAM_MIN_LEVEL) |
| Routing | per-level chat ids, forum topic (ThreadID), Silent |
| Format | Telegram HTML: emoji and level, app name, environment, UTC time, then the message and attributes (groups dotted, error chains as "caused by") in a <pre> block; all content escaped; truncated to 4096 characters without cutting tags or entities; Send/SendSync truncate the caller's HTML outside tags and entities and close the tags left open |
| Reliability | bounded queue (QueueSize, drops and reports when full), per-request Timeout, one retry after HTTP 429 honouring retry_after capped by MaxRetryAfter, OnError (never reentrant; records logged from it or carrying its error are not forwarded, so it may log through the app logger), drained by app.Shutdown; SendSync / ContactSync skip the queue and return the error (bounded by Timeout per request and by ctx) |
| Log forwarding | on by default for records at MinLevel+; TELEGRAM_LOG=false turns it off; Filter and RateLimit/RatePeriod (TELEGRAM_RATE_LIMIT per minute, ErrRateLimited reported once per window) narrow it; vukem.WithTelegram edits the config in code |
| Security | token held as config.Secret; request errors are redacted, also from SendSync/ContactSync (TestSecurity_A09_TelegramTokenRedacted, TestSecurity_A09_TelegramSyncErrorRedactsToken); vukem about shows only on/off; disabled when token or chat is missing (app.Telegram is then a disabled handler, never nil: Configured() is false, Send drops, SendSync returns ErrDisabled); TELEGRAM_API_URL (default https://api.telegram.org, the token travels in its path) must be https outside development and test, without credentials, query or fragment, and a bad value fails boot without echoing it (TestSecurity_A04_TelegramAPIURLRequiresHTTPS); WithTelegram setting BaseURL still wins |
// app/mail/welcome.go — vukem make:mail Welcome (also creates resources/views/mail/welcome.html)
type Welcome struct{ User models.User }
func (m Welcome) Envelope() mail.Envelope {
return mail.Envelope{To: []string{m.User.Email}, Subject: "Welcome!", Tags: map[string]string{"kind": "welcome"}}
}
func (m Welcome) Content() mail.Content { return mail.View("mail/welcome", m) }
mailer, err := app.Mailer()
err = mailer.Send(ctx, Welcome{User: u})- Content:
mail.View(name, data)renders the app'shtml/templateview; the text part comes from<name>_textwhen it exists, otherwise from the HTML (links becometext (url)).mail.HTML(html, text)andmail.Text(text)for literal bodies. Mail views use{{/* layout: none */}}or a mail layout. - React Email:
vukem make:mail <Name> --reactwrites a.tsxcomponent whose default props are Go template actions (go(".Name"),t("key"));email export --dir resources/js/emails --outDir resources/emails(react-email 6.11.16, @react-email/components 1.0.12, pinned exactly) renders it at build time,vukem.WithReactEmails(fsys)serves the files without layouts andmail.React(name, props)sends them, sohtml/templateescapes every prop (TestSecurity_A03_ReactPropsEscaped) and no Node process runs on send. HTML comments, including Outlook<!--[if mso]>hints, are dropped; the text part is derived without the preview text. Site: Mail. - Attachments: implement
Attachments() []mail.Attachment; inline parts setInlineandContentIDand are referenced ascid:.... - Context: implement
EnvelopeContext(ctx) mail.Envelope(mail.ContextEnveloper) to build the envelope from the send's context, e.g. a subject in the request locale withi18n.T(ctx, key). The Mailer calls it instead ofEnvelope, which stays required as the context-free fallback.SendLaterrenders before queueing, so it uses the context of the call. Outside a request (a job, a command) set the recipient's locale first,ctx = i18n.WithLocale(i18n.WithBundle(ctx, app.I18n), user.Locale): the envelope and the view'st/localefunctions read it. - Addresses go through
net/mail(no header injection); subjects, tags and content ids with line breaks are rejected (TestSecurity_A05_MailHeaderInjection);Mailer.Renderchecks tags for every transport (non-empty name, no line break or colon), and the Resend transport also enforces Resend's charset (ASCII letters, digits,_,-) before the request.Bccis never written as a header.mail.ParseResendEventdecodes a verified Resend webhook body into a typedmail.Event(Suppress()for complaints and permanent bounces) andMailer.SetSuppressiondrops suppressed addresses inRender, failing closed when the check errors (TestSecurity_A04_SuppressionCheckFailsClosed); the list itself stays in the app.Envelope.Headers(extra headers, copied toMessage.Headers) are checked for every transport (ASCII token names, no control characters in values, mailer-owned names andX-Tag-*refused, no case-insensitive duplicates) and forwarded as Resend/Mailtrapheaders, SMTP headers and on the Array transport;Envelope.ListUnsubscribe(httpsURL, mailto)sets RFC 2369List-Unsubscribeand RFC 8058List-Unsubscribe-Postand rejects non-https URLs and URIs with spaces, commas or angle brackets (TestSecurity_A05_MailHeadersInjection). - Previews in development:
r.Handle("/_mail/", http.StripPrefix("/_mail/", mail.Preview(mailer, map[string]mail.Mailable{"welcome": sample}))). - Tests:
MAIL_MAILER=arrayby default invukemtest;app.Mails().SentTo("ana@example.com"). - Queued mail:
mailer.SendLater(ctx, mailable, opts...)(orapp.MailLater) renders now and sends from a retried queue job whose payload is encrypted withapp.Crypt(see Queue). A*mail.Mailerbuilt withmail.NewneedsSetEnqueue; otherwiseSendLaterreturnsmail.ErrNoQueue.mailer.SendLaterTx(ctx, tx, mailable)(orapp.MailLaterTx) queues it only if the transaction commits (SetEnqueueTx,Queue.DispatchKindTx).
MAIL_MAILER |
Transport | Settings |
|---|---|---|
smtp |
net/smtp, STARTTLS required (or implicit TLS on 465), AUTH PLAIN; multipart/mixed → related → alternative MIME, base64 parts |
SMTP_HOST, SMTP_PORT (587), SMTP_USERNAME, SMTP_PASSWORD (secret), SMTP_INSECURE (local catchers only; refused in production unless SMTP_HOST is loopback) |
resend |
Resend HTTP API (POST /emails): tags, reply-to, attachments with content ids, the message id as Idempotency-Key, retries on 429 (honouring Retry-After, capped), 5xx and network errors (safe thanks to the idempotency key), typed *mail.ResendError |
RESEND_API_KEY (secret, never logged: TestSecurity_A09_ResendKeyRedacted) |
mailtrap |
Mailtrap Email API (POST send.api.mailtrap.io/api/send, or sandbox.api.mailtrap.io/api/send/{inbox} with MAILTRAP_INBOX_ID): cc/bcc, one reply-to, attachments and inline images (disposition: inline + content_id), the category tag as category and other tags as custom_variables, retries on 429 (honouring Retry-After, capped), 5xx and failed connections (DNS, refused: the request never left; a reset or timeout after sending is not retried), a 2xx with success: false is a non-retryable error, typed *mail.MailtrapError (never the body or token; may quote addresses; at most 5 one-line items of 200 characters), redirects not followed. A sandbox inbox in production logs a warning. No idempotency key: a 5xx answered after delivery may send twice |
MAILTRAP_API_TOKEN (secret, required, never logged: TestSecurity_A09_MailtrapTokenRedacted), MAILTRAP_INBOX_ID (sandbox) |
log |
logs recipients and subject (bodies at debug) | default outside production |
array |
in-memory (tests) | default in vukemtest |
MAIL_FROM sets the default sender and MAIL_REPLY_TO the default Reply-To (used when the envelope sets none). Production must set MAIL_MAILER explicitly; a missing or unknown value is an error, never silent loss of mail. An explicit MAIL_MAILER that cannot work (resend without RESEND_API_KEY, mailtrap without MAILTRAP_API_TOKEN or with a negative MAILTRAP_INBOX_ID, an unknown name) fails app.Boot, so serve, workers and commands stop at startup instead of at the first email. WithMailTransport skips the check.
An unset MAIL_MAILER in production is refused where mail is actually sent:
| Process | When it is refused |
|---|---|
serve |
at boot, as soon as anything asks for app.Mailer() |
queue:work, schedule:work |
at boot, through app.RequireMailer() — a worker sends queued mail as its normal work |
| any other command | at the Send call, with the same message |
The last row is the point: install:auth registers routes that build a mailer, so refusing at construction stopped every command. about, whose whole job is to report configuration, exited 1 for a reason unrelated to what it does, and a freshly generated image could not smoke-test itself (docker run <image> about). An app that sends no mail never needs to configure one. Call app.RequireMailer() at the start of any long-running process of your own that sends mail, so it fails at deploy time rather than per job. Hosts that block outbound SMTP (Railway on some plans, other PaaS) time out on smtp; use an HTTP transport (resend or mailtrap) there.
c, err := app.Cache() // CACHE_STORE=memory (default) or database; CACHE_PREFIX, CACHE_TABLE, CACHE_MAX_ENTRIES
user, err := cache.Remember(ctx, c, "user:42", time.Hour, func(ctx context.Context) (models.User, error) {
return orm.QueryOf[models.User](db).Find(ctx, 42)
})
err = c.Put(ctx, "settings", settings, 10*time.Minute)
v, ok, err := cache.Get[Settings](ctx, c, "settings")
n, err := c.Increment(ctx, "visits", 1, 24*time.Hour)
lock := c.NewLock("reports:daily", time.Minute)
if ok, _ := lock.TryAcquire(ctx); ok {
defer lock.Release(ctx) // only the owner can release
}- Values are JSON.
cache.Add[T]is the atomic exclusive claim (one winner across servers; useNewLockonly when an owner or early release is needed);cache.Pull[T]is get+forget and not atomic, so claim withAddwhen one caller must act.Rememberrunsfnonce for concurrent misses of a key in the process (singleflight) and never caches errors. Waiters share the leader's error, except when the leader's own context ended while a waiter's is live: that waiter callsRememberagain and computes the value itself. A panic in the leader's function continues in the leader, and the waiters get the errorcache: Remember callback panicked. - Stores implement
cache.Store(Get,Set, atomicAdd,Delete, owner-checkedDeleteIf,Increment,Flush; optionalcache.PrefixDeleter(DeletePrefix) backsCache.ForgetPrefix, implemented by memory, database and Redis,cache.ErrPrefixUnsupportedotherwise):cache.NewMemory(maxEntries)(LRU + TTL) andcache.NewDatabase(db, table)(SQLite, Postgres and MySQL upserts;Incrementis one atomic upsert, so concurrent servers never read the same count;CreateTableindexesexpires_at, andcache.Migrationsships the same DDL for apps that manage thecachetable withmigrate(tables the framework owns);Pruneremoves expired rows in batches and every app withCACHE_STORE=databaseschedulescache:prunehourly). Redis comes withdrivers/redis(Redis).cache.Buffer[K](Add,Swap,Restore,Flush(ctx, write)) adds hot-path counts in memory for a scheduled task to write in one batch, restoring them when the write fails;MaxKeyscaps the pending keys (oldest dropped first, reported toOnDrop).cache/cachetest.Runis the conformance suite (concurrentIncrementincluded), run on memory, SQLite, Postgres, MySQL, MariaDB and Redis. - Shared stores:
cache.Shared(store)reports whether every server sees the same entries;OnOneServer()andRATE_LIMIT_STORE=cacheuse it. A store declares it by implementingcache.Sharer(Shared() bool): memoryfalse, database and Redistrue. A wrapper (metrics, tracing) forwards it with its ownShared()or by exposing the inner store withUnwrap() cache.Store; a store with neither is not shared (fail closed).cachetest.Runrequirescache.Sharer.
Typed flags declared in code with a default, overridden by configuration and by stored values; inspired by Laravel Pennant, without its per-flag resolver closures.
// app/features/features.go (vukem install:flags)
var (
NewCheckout = flags.Bool("new_checkout", false).Describe("Serve the new checkout")
UploadLimitMB = flags.Int("upload_limit_mb", 10)
AdminTwoFactor = flags.Bool("admin_two_factor", true).Lock() // never switchable
)
func All() []flags.AnyFlag { return []flags.AnyFlag{NewCheckout, UploadLimitMB, AdminTwoFactor} }
// bootstrap: vukem.WithFlags(features.All()...)
ff, err := app.Flags()
if ff.Enabled(ctx, features.NewCheckout) { ... }
limit := flags.Get(ctx, ff, features.UploadLimitMB)
r.Group("/checkout/v2", func(g *router.Group) { g.Use(ff.Require(features.NewCheckout)) }) // 404 while off
ctx = flags.WithScope(ctx, flags.Scope("user:"+u.AuthID())) // per-user values
_, err = flags.Put(ctx, ff, "tenant:7", features.UploadLimitMB, 50)- Kinds:
flags.Bool,flags.Int,flags.String(at most 1024 bytes), constrained byflags.Type. Names are lowercase letters, digits and_(up to 100).Describeadds the admin panel text,Lockpins the code default. - Resolution, lowest first: code default,
FLAG_<NAME>(FLAG_NEW_CHECKOUT=true), the stored global value, the stored value of the request scope (flags.WithScope(ctx, scope), oneflags.Scopeper request, such asuser:42ortenant:7). Locked flags always have their code default. - Scopes are internal ids, never raw user input: 1 to 191 bytes of
a-z 0-9 : . _ -(flags.Globalis""). A read with an invalid scope returns the default and logs a warning; a write fails withErrInvalid. - Boot errors (
vukem.New): invalid or duplicate names, aFLAG_<NAME>value of the wrong kind,FLAG_<NAME>for a locked flag, andFLAG_*keys in.envfiles that name no registered flag, also when no flag is registered at all (process variables cannot be listed, so a typo there is not caught). Reading a flag that was not registered returns its code default and logs an error once per name;RequireandSharelog it when called, at boot, and treat the flag as off. - Store:
flags.Store(Load,Save,Deleteby scope).app.Flags()usesflags.NewDatabaseStoreoverDB(), tablefeature_flags(flags.Migration, added byvukem install:flags;name,scope(""= global),value,updated_at, unique(name, scope); SQLite, Postgres and MySQL upserts). Without registered flagsapp.Flags()opens neither the database nor the cache. - Cache: stored values per scope are read through
app.Cache()withflags.DefaultTTL(30 s), under a key that carries a per-scope generation;Set,PutandResetbump it, so a load that was in flight during a write cannot cache the old values again. Instances sharing the cache (CACHE_STORE=databaseor Redis) see a change at once; with the default memory cache each instance sees it within the TTL, so use a shared cache when a flag is a kill switch that must apply immediately everywhere. - Known limit: a read costs one or two cache lookups (generation and values) plus a JSON decode of the scope's map; hot loops should read a flag once per request.
- Fail closed: when the store or the cache errors, reads return the default (the code default, or
FLAG_<NAME>when set), never a stored value. A kill switch must therefore default to its safe value in code (or beLocked): during an outage the code default wins over what the admin stored. A failed read logs a warning (deduplicated by the app logger) and never fails a request andRequireresponds 404. A stored value that no longer parses as the flag's kind is ignored.Set/ResetreturnErrUnknown,ErrLocked,ErrInvalid,ErrNoStoreor the store's error;States(the admin view) returns the store's error instead of guessing.ff.All()describes the registered flags as[]flags.Info. - Audit:
Changeholds the value before and after a write;Sensitiveis true for string flags, which must be logged or audited only redacted (the admin panel records length and a SHA-256 prefix). - Views and Inertia:
ff.Expose(ctx, features.NewCheckout)returnsmap[string]any{"new_checkout": false}for view data;ff.Share(features.NewCheckout)(afterinertia's middleware) adds it as theflagsprop of every page. Only the flags passed are exposed, never all of them. - Admin panel:
admin.Config{Flags: ff}adds/admin/_flagsbehind themanageFlagsgate ability (admin.md). - Tests: set
FLAG_<NAME>invukemtest.Options.Env, orflags.Put(ctx, ff, flags.Global, features.X, true)against the test database. - Out of scope: percentage rollouts, A/B variants and rule engines; build them in app code over
WithScopeand a flag's value.
Package notify: in-app notifications per user (the bell icon), with optional mail and real-time fan-out. Stdlib only; site page digging-deeper/notifications.
notify.Migration(id)createsnotifications(idULID primary key,user_idstring,kind,dataJSON,read_atnullable,created_at; index(user_id, id)).- A notification is any value with
Kind() string(at mostnotify.MaxKind= 100 bytes); its JSON encoding is stored asdata. nf := notify.New(db, now);nf.Send(ctx, userID, n, channels...)andnf.SendTx(ctx, tx, userID, n, channels...)run each channel in order and return thenotify.Storedrow; no channel isnotify.ErrNoChannels, an empty user id or kind is an error.- Channels:
notify.Database(insert, inside the transaction withSendTx),notify.Mail(mailer, build)(Mailer.SendLaterTx: queued only on commit;buildreturning a nil mailable skips; needs a queue,mail.ErrNoQueueotherwise),notify.Broadcast(publisher, channelFor)(*broadcast.Serverfits: publishes eventKindwith theStoredrow; insideSendTxafter the commit, and a publish error then is dropped because the row is the source of truth). Anotify.Channelis a plain func, so apps add their own. - Reads and writes always take the user id (
TestSecurity_A01_NotifyScopedToUser):Unread(ctx, userID),List(ctx, userID, cursor, limit)(newest first, keyset on the ULID id, limit 1..100 with 0 = 20, next cursor""on the last page),MarkRead(ctx, userID, ids...)(other users' ids are ignored),MarkAllRead(ctx, userID). Prune(ctx, cutoff)deletes rows created beforecutoff, read or not; schedule it:s.Func("notify:prune", func(ctx context.Context) error { _, err := nf.Prune(ctx, time.Now().AddDate(0, 0, -90)); return err }).Daily().- Non-goals: per-user channel preferences (decide in
buildor beforeSend), SMS and push.
disk, err := storage.NewLocal("storage/app/public", "/storage") // os.Root: no "..", no escaping symlinks
r.Handle("/storage/", http.StripPrefix("/storage", storage.Handler(disk, nil)))
path, err := storage.PutUploaded(ctx, disk, fileHeader, "avatars", storage.Images(2<<20))
url := disk.URL(path)
private, _ := storage.NewLocal("storage/app/private", "")
r.Handle("/files/", http.StripPrefix("/files", storage.Handler(private, signer)))
link, err := storage.TemporaryURL(signer, "/files", "invoices/42.pdf", 15*time.Minute)storage.Disk:Put(atomic rename on local disks, through a hidden.name.tmp-…file thatListandHandlerskip),Open,Exists,Delete,List,URL; helpersstorage.Getandstorage.PutBytes. Disks:NewLocalandNewMemory(tests); S3 indrivers/s3(S3).storage/storagetestholds the conformance and traversal suites (TestSecurity_A01_StorageTraversal).PutUploadednever uses the client's file name: random name, extension from the type detected in the content (http.DetectContentType), size checked from the header and again while copying, 422 for disallowed types or sizes.UploadRules.Typesis required: an empty list is an error, not "any type" (TestSecurity_A05_PutUploadedRequiresTypes).Handlernever serves dotfiles or directories, sends the file's real modification time asLast-Modified(none when the disk cannot report it) soIf-Modified-Sinceanswers 304 (non-seekable bodies too: anETag() stringmethod setsETagforIf-None-Match, aModTime() time.Timemethod setsLast-Modified; the S3 driver's objects have both), sendsX-Content-Type-Options: nosniff, and with asigned.Signeronly answers signed, unexpired URLs.HandlerWith(disk, signer, storage.Options{CacheControl: ...})addsCache-Controlto responses that serve a file (200, 206, 304), never to errors.storage.Check(ctx, disk)is the readiness check for a disk: it writes a small object under a unique key below.vukem-health/, reads it back, compares the bytes and deletes it, with the delete running throughcontext.WithoutCancelso an abandoned probe leaves nothing behind. Use it fromvukem.WithHealthCheck/app.AddHealthCheck, never in a liveness probe. The round trip is the point: the obvious check — does a known object exist? — passes when nothing works, because with the wrong credentials several S3 implementations answer "object does not exist" rather than refusing, and reading the bytes back also catches a disk that is up and returning the wrong object. Every error wrapsstorage.ErrUnhealthyand none wraps the driver's, which carries the endpoint, the bucket and sometimes the access key.- Decision: instead of
storage:link(a symlink, which needs extra privileges on Windows), public files are served bystorage.Handlerfrom the disk itself.
go get github.com/AlexGalhardo/vukem/drivers/s3: a storage.Disk on Amazon S3 or any S3-compatible service (Cloudflare R2, DigitalOcean Spaces, Backblaze B2, RustFS, SeaweedFS, Garage). No AWS SDK: requests are signed by a stdlib Signature Version 4 implementation verified against the AWS test suite.
cfg, err := config.Load[s3.Config](app.Source)
disk, err := s3.New(cfg) // validates config, no I/O
err = disk.Put(ctx, "videos/intro.mp4", file) // one PUT up to S3_PART_SIZE, multipart above
info, err := disk.Stat(ctx, "videos/intro.mp4") // HEAD: Size, ETag, ContentType, LastModified
up, err := disk.PresignPut("uploads/avatar.png", 5*time.Minute) // browser uploads straight to the bucket
up, err := disk.PresignPutWith("uploads/avatar.png", 5*time.Minute, s3.PresignPutOptions{
ContentType: "image/png", ContentLength: size, // signed: the upload must send exactly these
})
link, err := disk.PresignGet("invoices/42.pdf", time.Hour)| Variable | Default | Meaning |
|---|---|---|
S3_BUCKET |
— | bucket name (DNS-compatible: 3–63 of a-z 0-9 . -) |
S3_REGION |
us-east-1 |
signing region (auto for R2) |
S3_ENDPOINT |
https://s3.<region>.amazonaws.com |
bare origin of an S3-compatible service |
S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY |
— | required; S3_SESSION_TOKEN for temporary credentials |
S3_USE_PATH_STYLE |
false |
endpoint/bucket/key instead of bucket.endpoint/key (most self-hosted servers) |
S3_INSECURE_HTTP |
false |
allow an http:// endpoint (local development only) |
S3_PART_SIZE |
8 MiB | multipart part size, 5 MiB to 5 GiB |
S3_PUBLIC_URL |
— | prefix for disk.URL (CDN or public bucket); empty = private |
Putbuffers at most one part: small bodies go in one signedPUT, larger ones become a multipart upload that is aborted on any failure (part error, reader error, cancelled context, a200that carries an<Error>), so no orphaned parts are billed. Content type comes from the extension, else from the first bytes.Openstreams the object;Listuses ListObjectsV2 and follows continuation tokens; folder placeholder keys (ending in/) are skipped. Missing objects matchfs.ErrNotExist; other failures are*s3.Error(StatusCode,Code,Message,RequestID).disk.CreateBucket(ctx)creates the bucket inS3_REGION(aLocationConstraint, except forus-east-1andauto), for dev setup and tests against a fresh local S3 (RustFS, MinIO). A bucket the credentials already own is not an error; a name taken by another account is an*s3.ErrorwithCodeBucketAlreadyExists.- Keys go through
storage.Clean: no empty key, no leading/(so/aandacannot name different objects), no.., backslash or:. - Presigned URLs expire after 1 s to 7 days (the SigV4 maximum).
PresignGetandPresignPutsign only thehostheader, so aPresignPutURL accepts any type and size.PresignPutWithalso signsContent-Typeand/orContent-Length(s3.PresignPutOptions): the uploader must send exactly those values or S3 answers 403. Browsers setContent-Lengthfrom the body but must send theContent-Typeheader explicitly (fetch(url, {method: "PUT", headers: {"Content-Type": type}, body: file})); invalid options returns3.ErrInvalidPresign. A signedContent-Lengthis an exact size, not a ceiling: pass the real file size the client declared (after checking it against your maximum), never the maximum itself, or every smaller file gets 403. Credentials areconfig.Secret; errors and%+vnever show them. - Integration tests run against RustFS (
rustfs/rustfs, pinned in.config/compose.yaml;task services:up, port 59000); the driver passesstoragetest.Runandstoragetest.RunTraversal.
Package upload (BETA, stdlib only) goes beyond storage.PutUploaded: it never buffers a whole file.
rules := upload.Images(5 << 20) // MaxFileSize + Types are required: zero Rules reject everything
rules.MaxFiles, rules.Dir = 3, "photos"
rules.Scanner = upload.ClamAV("127.0.0.1:3310") // optional
form, err := upload.Receive(c, disk, rules) // form.Values, form.Files[i].Path/Name/Type/Size/SHA256Receivereadsr.MultipartReader()part by part and streams each file to thestorage.Disk(a 64 MiB upload allocates about 100 KiB).Rulesbound the file size, the whole request (MaxSize, defaultMaxFiles*MaxFileSize + 1 MiB; it replaces the router-wide body limit for that route), the file count, and field count/size. Sizes fail with 413, types/extensions/count with 422; on any error every file already written is deleted.- Type checks:
http.DetectContentTypeon the first 512 bytes must be inTypes, and the client's extension must be one of those known for that type (upload.Extensions("image/jpeg")→.jpg,.jpeg), plusExtensionswhen set. The client'sContent-Typeis ignored. Stored names are random with the canonical extension; the sanitized client name (upload.SanitizeName) is metadata only. Rules.Typesis only as strong as the detector, and says so. Detection ishttp.DetectContentType, whose vocabulary is narrow:image/avif,image/heic,image/heif,image/jxlandimage/tiffare not in it (measured on Go 1.27.2 — the detector answersapplication/octet-streamfor all five). A rule naming one of them used to be accepted and then match nothing, so the application believed it accepted AVIF and accepted none. Those types are now anupload.ErrUndetectableTypeconfiguration error listingupload.DetectableTypes(). The escape hatch is explicit:application/octet-streamis detectable (it is what the detector says when it cannot tell), so a service handling AVIF or TIFF allows that and checks the type itself with a real sniffer. Doing it deliberately is the point; a rule that quietly matches nothing is not.upload.Save(ctx, disk, rules, field, filename, r)applies the same checks to any reader (finished tus uploads, imports).- Scanning: with
Rules.Scanner, files are written toQuarantineDir/.<random>(dot-named, sostorage.Handlernever serves them), scanned, then copied toDirand the quarantined copy deleted.ErrInfected→ deleted + 422; a scanner error → deleted + 503 (fail closed), with the scanner error kept as the*errs.HTTPErrorcause for the log.upload.ClamAV(addr)speaks clamd'sINSTREAMover TCP with per-operation timeouts. - Nothing may read the body before
Receive:middleware.MethodOverrideleaves multipart bodies unread (multipart forms put_methodin the query string) and handlers must not callc.Input()/c.FormFile()first.
Resumable uploads implement tus 1.0 core with the creation, expiration and termination extensions:
tus, err := upload.Tus(upload.TusConfig{
Dir: "storage/app/tus", BasePath: "/uploads/tus/", MaxSize: 2 << 30,
Authorize: func(r *http.Request) error { /* session or token check */ return nil },
OnComplete: func(ctx context.Context, info upload.TusInfo, open func() (io.ReadCloser, error)) error {
rc, err := open()
if err != nil {
return err
}
defer rc.Close()
_, err = upload.Save(ctx, disk, rules, "file", info.Filename(), rc)
return err
},
})
r.Handle("/uploads/tus/", tus)
app.OnShutdown(func(context.Context) error { return tus.Close() })OPTIONSadvertisesTus-Version,Tus-Max-Size,Tus-Extension;POSTchecksUpload-Length(≤MaxSize) andUpload-Metadata(≤ 4 KiB, 32 pairs) and answers 201 withLocation: BasePath + <26-char random id>;HEADreturnsUpload-Offset/Upload-LengthwithCache-Control: no-store;PATCHneedsTus-Resumable: 1.0.0(412 otherwise),Content-Type: application/offset+octet-stream(415) and the currentUpload-Offset(409), and appends the body as it streams — an interrupted request keeps what arrived, and the client resumes from the offsetHEADreports. ConcurrentPATCHes on one upload get 423.- Partial data lives in
Dirthroughos.Root. The id is the capability, soAuthorizeis required (boot error when nil; returnnilexplicitly to allow everyone). Abandoned uploads expire afterExpiry(24h): requests on them get 404 andtus.Cleanup(ctx)(schedule it) deletes them. When the last byte arrivesOnCompleteruns; its error is sent to the client (422 for validation; 5xx errors are also logged with their cause through the request logger) and the partial data is deleted either way. Validation means*errs.ValidationError,z.FieldErrororz.Issues(the first message is the response text; a plainRefineerror reads "The value field is invalid."); anAuthorizeerror keeps its 4xx status (422 for z errors, anything else 403) but never its text.
Direct-to-storage uploads skip the app server: upload.Presigner (PresignPut(ctx, key, contentType, maxSize, ttl)) is an interface you implement for your storage provider; wrap drivers/s3's PresignPutWith(key, ttl, s3.PresignPutOptions{ContentType: contentType, ContentLength: maxSize}) and return Content-Type in headers, so the bucket enforces the type and size; plain PresignPut(key, expires) signs only the host. Despite its name, Direct passes the client's declared size (already checked against Rules.MaxFileSize) as maxSize, which is what a signed Content-Length needs: it is an exact size, so a wrapper that signed Rules.MaxFileSize would reject every smaller file with 403. The client must send exactly the size it declared. upload.Direct(DirectConfig{Presigner, Rules, Authorize}) answers POST {"filename","content_type","size"} with {"key","url","method":"PUT","headers","expires_at"} after checking the declared type, extension and size, under a random key in Rules.Dir (TTL 15 minutes, at most 1 hour). The declared type cannot be trusted, so call upload.Verify(ctx, disk, key, rules) when the client reports the upload done: it sniffs the stored object and deletes it when it breaks the rules.
The HTMX starter ships resources/views/components/upload.html (a data-upload form with a <progress>) and a /uploads demo page. resources/js/app.ts swaps htmx 4's fetch for XMLHttpRequest on those forms (htmx:before:request) to report upload progress; no inline scripts, so the CSP holds. The demo stores files under UPLOADS_DIR (default storage/app/uploads); UPLOADS_DISK=memory swaps in storage.NewMemory for tests (refused in production), so the generated TestUploads never writes to the filesystem: on Windows, antivirus filters briefly recreate just-deleted files, which can make t.TempDir cleanup fail with "directory is not empty". Use a memory disk the same way in your own upload tests. Validate files received through c.Input() with z.File().
entries, err := archive.Zip(readerAt, size, archive.Policy{
MaxEntries: 512, MaxTotalSize: 64 << 20, MaxEntrySize: 8 << 20,
})
// entries[i].Key is safe to use as an identifier; Open() is bounded by Size.archive.Zip reads the central directory under a policy and returns entries whose names are already safe keys. Every application that accepts a user-supplied archive needs the same defences, and getting any one wrong is a vulnerability rather than a bug, so they are here:
| Defence | What it does |
|---|---|
| entry count | MaxEntries, checked before anything is read |
| declared size | MaxEntrySize and MaxTotalSize, read from the central directory, so a bomb is refused on its claim rather than by inflating it |
| no paths | Zip takes no path of any kind and returns a key, so an entry name can never be an argument to a file operation (TestSecurity_A01_ArchiveTakesNoPath pins the signature) |
| name length and shape | MaxNameLength, plus a refusal for control characters and direction-changing runes — the name does not reach a path, but it does reach the metadata and from there a consumer's asset loader |
| key collisions | two entries resolving to one key are refused |
| bounded reads | Entry.Open is held to the declared size, so the declared total bounds what the archive can ever yield |
The collision one is the finding's own argument, and it is the one that corrupts instead of failing: walk/frame.png and jump/frame.png collapse to one key once the directory is dropped, so an app writes both frames under one name while its metadata describes one — every later frame off by one, a wrong result delivered as a correct one.
An escaping raw name (../../etc/passwd, an absolute path, a drive letter) is refused before Policy.Key sees it. The default Key is path.Base, which would quietly turn that into the perfectly valid key passwd: safe to use, an archive that should never have been accepted, and nothing in the log to say so.
Zip also refuses symbolic links, devices and encrypted entries (ErrUnsafeEntry) and, with Policy.MaxRatio, an entry compressed past that ratio; Entry.Mode and Entry.CompressedSize are exposed.
What stays with the application is the per-entry content rule: what a frame may contain, how big an image may be, which types are acceptable. Errors (ErrPolicy, ErrTooManyEntries, ErrTooLarge, ErrNameTooLong, ErrUnsafeName, ErrDuplicateKey, ErrUnsafeEntry, ErrRatio) never carry the raw entry name, which is attacker-controlled text a naive handler would put in a response body.
mediatype.Extension("image/avif") → .avif, mediatype.Label("image/avif") → AVIF image, mediatype.ByExtension(".avif") → image/avif. This is the other direction from upload.Extensions: what to call a file the application generated and hands back as a download, independent of what any detector can recognise.
It is deliberately not a set of types an application accepts, and it is built so it cannot be used as one — three lookups, no exported list, no iterator, no Known predicate, pinned by TestNoExportedListToMistakeForAnInputAllowlist. An input policy is per application and is often the only thing keeping a vulnerable decoder unreachable: an app may rely on "no tool here accepts XML input", and a shared list that grew a type would take that argument away with no edit to the app. Validate input with upload.Rules or a detector of your own.
Package export (stdlib only) streams downloads row by row from any iter.Seq2[T, error], such as orm Query.Each, so large exports never sit in memory. Guide: Exports.
export.CSV(w, r, name, header, rows, record),export.JSON(one array),export.NDJSON(application/x-ndjson), andexport.WriteCSV(w, r, name, fn)for multi-section CSV files.export.EncodeCSV(w io.Writer, header, rows, record, opts...)writes the same bytes (sameSafeCell,WithBOM,InsecureRawCells) to any writer outside a request: a ZIP entry, a storage upload, a queued job;export.EncodeNDJSON(w, rows)does the same for NDJSON; a JSON array there is plainencoding/json.- Attachments with
export.ContentDisposition(name)(RFC 6266, RFC 5987filename*for non-ASCII),Cache-Control: no-storeandnosniff. - CSV cells go through
export.SafeCell(OWASP CSV injection);InsecureRawCells()opts out. - Nothing is sent before the first row, so an early query error reaches the error handler. A failure after the first byte drops the connection: HTTP/1.x connections are hijacked and closed and the error wraps
export.ErrIncomplete; where hijacking is impossible (HTTP/2) the function panics withhttp.ErrAbortHandler, which net/http recovers to reset the stream. A cancelled request context (client gone) returns an error with status 499, logged below error level. FlushEvery(n)(500 rows),WriteTimeout(d)(1 minute, renewed before writes to the client at most everyd/4or 1s, cleared at the end, so long exports outlive the serverWriteTimeout),WithBOM()for Excel (CSV only).- The file-name sanitizer lives in
internal/dispositionand is shared withweb.Ctx.Download.
Package llmstxt (stdlib only) renders /llms.txt (https://llmstxt.org: H1 title, > summary, details, H2 link lists, ## Optional) and /llms-full.txt (header, then each Link.Content Markdown after a --- rule with a Source: line) from a llmstxt.Doc. llmstxt.Register(r, doc) adds both GET routes (text/plain; charset=utf-8, Cache-Control: public, max-age=3600, Last-Modified from Doc.LastModified); llms.txt is rendered once with a strong ETag and 304s, llms-full.txt streams per request and ends with TruncatedNote past Doc.MaxFullBytes (16 MiB default); a Content error is a bare 500 before the first byte and an aborted connection after. Titles, notes and summary are flattened to one line with link brackets escaped, URLs must be absolute http(s) or root-relative and are percent-escaped (TestSecurity_A03_LLMsTxtMarkdownInjection). Site page: site/content/docs/digging-deeper/llms-txt.mdx.
Package robots (stdlib plus router) renders /robots.txt (RFC 9309) from a robots.File (Groups of UserAgents, Allow, Disallow; Sitemaps); robots.Register(r, f) serves it with an ETag and Cache-Control: public, max-age=3600. Values must be single-line paths (/ or *, no #) and sitemaps absolute http(s) URLs (TestSecurity_A03_RobotsRefusesInjectedLines). File.NoIndex serves robots.DisallowAll; NOINDEX (Config.NoIndex) adds middleware.NoIndex() (X-Robots-Tag: noindex, nofollow) to the default server stack. Site page: site/content/docs/digging-deeper/sitemaps.mdx.
Package sitemap (stdlib only) streams XML sitemaps for catalogues too large to build in memory (https://www.sitemaps.org/protocol.html):
sitemap.NewWriter(w)writes one<urlset>;Add(sitemap.URL{Loc, LastMod, Alternates})writes a URL with<lastmod>(RFC 3339, UTC) andxhtml:linkhreflang alternates;Close()ends it. Wrapwingzip.NewWriterfor.xml.gzchunks.Addreturnssitemap.ErrFull(nothing written) atMaxURLs(50,000) orMaxBytes(50 MiB uncompressed): close the chunk and start the next one.sitemap.WriteIndex(w, []sitemap.Sitemap{...})writes the index of the chunks.- Only absolute
http/httpsURLs of at most 2048 bytes and hreflang tags of letters, digits and-are accepted; values are XML-escaped (TestWriterRejectsInvalidAndStopsWhenFull). Site page:site/content/docs/digging-deeper/sitemaps.mdx.
// app/events/order_shipped.go — vukem make:event OrderShipped
type OrderShipped struct{ OrderID int64 }
// app/listeners/notify_customer.go — vukem make:listener NotifyCustomer --event OrderShipped [--async]
func NotifyCustomer(ctx context.Context, e events.OrderShipped) error { ... }
// app/listeners/registry.go (make:listener appends), passed to vukem.WithListeners(listeners.All()...)
func All() []events.Registration { return []events.Registration{events.OnAsync(NotifyCustomer)} }
err := app.Events.Dispatch(ctx, events.OrderShipped{OrderID: 42})- Typed by generics:
events.On(fn)infers the event type from the function. Synchronous listeners run in registration order and the first error stops the chain and is returned (a panic is recovered, logged aslistener panickedand returned as an error); listeners are named by their function (listeners.SendWelcome) or, when queued, their job kind; async ones (OnAsync) run on a bounded pool with a context detached from the request, log their errors and panics, and are drained byapp.Shutdown; one dispatched while the bus is closing is dropped with aWARNlog, so none starts afterShutdownreturns. - Tests:
events.NewFake()records dispatches;events.Dispatched[OrderShipped](fake). - Queued listeners:
events.OnQueued("kind", fn)enqueues the event and runsfnin a queue worker (see Queue).
limiters, err := app.RateLimiters() // RATE_LIMIT_STORE=memory (default) or cache
loginIP, _ := auth.ThrottleKeys("email") // per email and IP; the second key is per email only
login := ratelimit.Middleware(limiters("login", 5, time.Minute), loginIP)
r.Post("/login", h.Login).Use(login)Limiters are keyed by ratelimit.ByIP (default), ByToken (after auth.Required only), ByUser(guard) or your own KeyFunc; responses include RateLimit-* headers, 429 adds Retry-After; a failing store denies.
Choosing the key is the whole decision:
| Key | Bucket | When |
|---|---|---|
ByIP |
client address (IPv6 grouped by web.Services.IPv6Prefix) |
anything reachable unauthenticated |
ByToken |
the bearer token, hashed; the IP when there is none | API routes, behind an IP limit |
ByUser(guard) |
the account the guard authenticated; the IP when nobody is | an authenticated action whose budget belongs to the account |
ByUser is the key for a limit like "10 new API keys an hour". ByIP punishes everybody behind one NAT while an attacker rotates addresses, and ByToken finds no bearer token on a session request, so it falls back to the IP and a stolen session can mint keys faster than the owner can revoke them. An unauthenticated caller gets its IP key, never a shared one: a constant key would let any caller exhaust everybody's budget and an empty one would skip the limit entirely — so put an IP limit in front as well when the route is reachable without authentication. install:auth and install:api throttle logins, mails and tokens by default, through app.RateLimiters(). vukem.WithRateLimiters(factory) replaces the RATE_LIMIT_STORE factory (a limiter of your own, or a fake in tests).
| Store | Algorithm | Shared by servers |
|---|---|---|
ratelimit.NewMemory(limit, window) (RATE_LIMIT_STORE=memory; a window of zero or less is one second, here and in the Redis limiter) |
GCRA, bursts up to limit (ratelimit.NewMemoryBurst(rate, window, burst) sets the burst apart) |
no |
ratelimit.NewWindow(counter, name, limit, window) (RATE_LIMIT_STORE=cache) |
fixed window on Increment; up to 2×limit around a window boundary |
yes, with CACHE_STORE=database (SQLite, PostgreSQL, MySQL) or a Redis cache store |
rc.RateLimiter(prefix, limit, window) (Redis) |
GCRA in a Lua script | yes |
GCRA needs compare-and-set, which cache.Store lacks, so the store-agnostic limiter uses fixed windows: correct with an atomic Increment alone (cache.Database.Increment is one upsert, so concurrent servers never read the same count). Window keys are hashed, limiter names are 1–64 of A-Z a-z 0-9 . _ -, and RATE_LIMIT_STORE=cache over the memory cache is a boot error.
challenge.Middleware(verifier, when) verifies a browser challenge on unsafe requests (signup, login, contact). challenge.Turnstile(secret) and challenge.HCaptcha(secret) return a *SiteVerify (siteverify protocol over httpclient.Safe, optional Hostname and Action checks; Action is the Turnstile widget's data-action, see https://developers.cloudflare.com/turnstile/get-started/server-side-validation/, read 2026-10-29); the token comes from the widget's form field or the X-Challenge-Token header (Inertia, JSON). A rejected token is a validation error on challenge (422 / redirect back), a provider failure a 503 (fail closed). when (nil: always) limits the check to suspicious clients, e.g. after a soft ratelimit budget runs out. Any type with Verify(*web.Ctx) error is a Verifier (errors wrapping challenge.ErrRejected are rejections). challenge.TurnstileConfig (env TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY, TURNSTILE_HOSTNAME, TURNSTILE_TIMEOUT, TURNSTILE_INSECURE_FAIL_OPEN; off until both keys are set) renders the nonce'd script (Script) and widget (Widget), returns CSP sources (CSPSources) and a per-action verifier (Verifier, Protect); siteverify calls carry remoteip and an idempotency_key and retry once on a network error or 5xx (https://developers.cloudflare.com/turnstile/get-started/server-side-validation/, read 2026-11-01). challenge.StepUp is the step-up hook: Require(c) serves a noindex, no-store interstitial unless the client holds a signed clearance cookie bound to its IP prefix and User-Agent; Handle verifies, sets the cookie and redirects to a local path (LocalPath). Site page: /docs/security/bot-challenge.
type SendInvoice struct{ OrderID int64 }
func (SendInvoice) Kind() string { return "send_invoice" }
// app/jobs/registry.go; bootstrap passes vukem.WithJobsFunc(jobs.All)
func All(app *vukem.App) []queue.Registration {
return []queue.Registration{
queue.Handle(HandleSendInvoice(app),
queue.Retries(5), queue.Backoff(queue.Exponential(time.Second)), queue.Timeout(time.Minute)),
}
}
q, err := app.Queue()
err = q.Dispatch(ctx, SendInvoice{OrderID: 1}, queue.OnQueue("billing"), queue.Delay(5*time.Minute))
err = q.DispatchTx(ctx, tx, SendInvoice{OrderID: 1}) // exists only if tx commits (every driver)
err = q.Dispatch(ctx, SendInvoice{OrderID: 1}, queue.Unique("order-1")) // no-op while one is queued, running or retrying-
Payloads are JSON;
Kind()maps to the registered handler (no reflection-based class names). Registering a kind twice is a boot error. -
queue.Unique(key)makes a dispatch idempotent (stable id from kind and key; the driver's primary key refuses the second copy; free again after ack or failure, no window).queue.Jitter(fn, fraction)spreads a backoff by ±fraction. -
Defaults: queue
default, 3 retries with exponential backoff from 1s (capped at 1h), 1-minute timeout per attempt; options onHandleset the defaults, options onDispatchoverride them. -
QUEUE_CONNECTION:sync(default; the job runs insideDispatchand its error is returned; a delayed job is refused withqueue.ErrInlineDelayinstead of running early, so usememory,databaseorqueue.Fakewhere jobs are delayed),memory(in process;serveruns workers,QUEUE_CONCURRENCYdefault 4,QUEUE_NAMESin priority order,QUEUE_LIMITS=ingest=2caps the running jobs of a queue per process so a slow queue cannot take every worker; same for every driver and forqueue:work),database(SQLite, Postgres or MySQL; see below). Any other value is anapp.Queue()error.vukem.WithQueueWork(queue.WorkOptions{Sleep: 200 * time.Millisecond, ...})sets the worker thatserveruns in code: a field that is set (Queues, Concurrency, Limits, Sleep, StopTimeout) replaces theQUEUE_*value, andSleepis the polling interval (1s by default). Redis is not aQUEUE_CONNECTIONvalue: wire it withvukem.WithQueueDriver/WithQueueDriverFunc(Redis). -
serveruns a queue worker: always formemory, and fordatabaseand custom drivers (WithQueueDriver, e.g. Redis) unlessQUEUE_IN_SERVE=false(defaulttrue, mirroringSCHEDULE_IN_SERVE). A worker inservenext toqueue:workprocesses is safe (atomic reservations with an owner token), it only adds workers. The runner exits at once for an inline driver. -
Permanent failures: a handler that wraps
queue.ErrPermanent(fmt.Errorf("convert %d: %w: %w", id, err, queue.ErrPermanent)) skips its remaining retries. The job is failed, not acked: it lands in the failed jobs with the handler's error, soqueue:failedstill shows it andqueue:retrycan re-run it once the input is fixed — acking would delete a job nobody ever saw fail. It beats both the retry budget and the free-interruption grace, since the handler's verdict is better information than either. On an Inline driver (sync) there are no retries to skip and the error reaches theDispatchcaller unchanged, wrapping the sentinel. -
Attempt in the handler's context:
a, ok := queue.AttemptFrom(ctx)returnsqueue.Attempt{Number, MaxRetries}plusa.Last()(Number > MaxRetries), so a handler can settle the row it owns on its last attempt instead of leaving itrunningforever when the retries run out.okis false outside a worker (a handler function called directly in a test), where a zeroAttemptwould read as a last attempt. The context carries it because every handler already takesctxfirst: the alternative — a wider handler signature — would breakqueue.Handle/HandleKindand every registered handler, including the framework's own (queued mail, queued listeners, webhook delivery). With an Inline driver (sync) the job gets exactly one attempt, soMaxRetriesis 0 andLast()is true whateverRetriessays; a handler that relies onLast()therefore behaves the same insyncdevelopment and in a worker. -
Workers (
q.Work) recover panics, retry with backoff, then move the job to the failed jobs with its last error. On shutdown they stop reserving and let running jobs finish (their context is not cancelled; the job timeout still applies) for up toWorkOptions.StopTimeout(SHUTDOWN_TIMEOUTinserveandqueue:work); then their context is cancelled. A job that fails with that cancellation (context.Canceled/DeadlineExceeded) is released without using an attempt,queue.MaxFreeInterruptions(3) times in a row (the count is kept inLastError, so no driver needs a schema change); later interruptions use attempts and other errors are retried or failed as usual. Interrupted jobs run again from the start: handlers must be idempotent and honorctx. EachAck/Release/Failof a worker is bounded by 10s, so a hanging store cannot holdqueue:workor the shutdown. -
Long jobs that must not run twice (a render, an export). Delivery is at least once, and the queue has no per-job progress and no cancellation by job id (the only cancellation is the worker context at shutdown). Until it does, keep that state in your own table: dispatch with
queue.Retries(0)so a failure is not retried, then start the handler with a conditional claim such asUPDATE renders SET state = 'running' WHERE id = ? AND state = 'queued'and do the work only when one row changed. Write progress to that row from the handler, and cancel by setting acancel_requestedflag the handler polls between steps. A job interrupted by shutdown is released without using an attempt (see above), so it runs again: the claim must tell a second delivery of the same job from a duplicate, for example by resetting the row toqueuedwhen the handler sees its context cancelled. -
Progress and cancel of a running job.
queue.Progress(ctx, fraction, message)in a handler reports how far the job is (fraction clamped to [0, 1], NaN ignored; a no-op outside a queue handler). It reaches the hook set withqueue.WithProgress(func(ctx, queue.JobProgress))onHandle/HandleKind(a handler option: a function is not stored with the job, so onDispatchit is ignored) and every observer that also implementsqueue.ProgressObserver(ObserveProgress).q.DispatchID(ctx, job, opts...)(andDispatchKindID) isDispatchthat returns the job id (the id of the existing job for aUniqueone).q.Cancel(id)cancels the context of that job's running attempt in this process, withcontext.Cause=queue.ErrCancelled; a handler that honours its context returns, and the job fails withErrCancelledandErrPermanent(no retries: it moves to the failed jobs); a handler that returns nil anyway completes normally. It returnsqueue.ErrNotRunningwhen the job is not running here. Limits: progress is not persisted or queryable (the hook decides what to keep; a restart loses it), there is no cross-process cancel (a worker in another process, or a job only queued, isErrNotRunning; a queued job is not removed), and a job run inline bySyncfinishes beforeDispatchreturns, so only theJobDispatchedevent of an observer shows its id in time. Handlers keep honouringctx: a cancel cannot stop code that ignores it. -
Time:
queue.Delay, retry backoff and the drivers' availability checks use one clock.app.Queue()sets the app clock (WithClock) withQueue.SetClockand on drivers implementingqueue.Clock(Memory,Database, RedisQueue), so fake clocks make delayed jobs due. -
Database driver (
QUEUE_CONNECTION=database, SQLite, Postgres and MySQL): tablesjobsandfailed_jobs(QUEUE_TABLE,QUEUE_FAILED_TABLE;jobscollides with the obvious name for a domain table, see tables the framework owns) are created atBoot(on first use when the app is not booted; an unreachable database then fails the boot of every command with an error namingQUEUE_CONNECTION=database), so the firstapp.Queue()never runs DDL inside a transaction (on SQLite that would wait for the writer connection the transaction holds). Jobs available and created in the same millisecond pop in push order within one process: the jobs table has aseq BIGINT NOT NULL DEFAULT 0column, a per-driver counter seeded by the wall clock, andPoporders byavailable_at, created_at, seq, id; across processes same-millisecond jobs interleave roughly by real time.CreateTablesaddsseqto a table created before v0.26.0 (existing rows keep 0 and still pop first, since they are older; any probe error other than an unknown column, such as a permission or connection error, failsCreateTablesinstead of triggering theALTER).queue:retrygives a retried batch oneseq, so retried jobs of the same millisecond pop in id order. A table created by your own migration needs the column, orPushfails;queue.Migrations(orstores.Migrations, see managing them with migrate) ships the right DDL, and the boot-time creation stays as the fallback for apps that do not register it. WithStopWhenEmpty(queue:work -once,-stop-when-empty) a reserve error endsWorkwith that error instead of looking like an empty queue. Workers reserve a job atomically (oneUPDATE … RETURNING; Postgres and MySQL useFOR UPDATE SKIP LOCKED), so any number ofqueue:workprocesses can share them. A job whose worker died is taken over after its timeout plus one minute: delivery is at least once, so make handlers idempotent. -
q.DispatchTx(ctx, tx, job)ties the job to the caller's transaction: it exists only if the transaction commits. The database driver inserts it in the transaction; drivers without transactional storage (sync,memory,queue.Fake, Redis) dispatch it fromdatabase.Tx.AfterCommit, so the same code works in tests and development. Onsyncthe job then runs right after the commit and a handler error is logged (the caller already returned). Errors known up front (unknown kind,ErrInlineDelay) are returned inside the transaction; with a*database.DBthe job is dispatched at once. -
JobEventcarriesAttempt,MaxRetriesandFinal, so a dashboard can tell a failure that will be retried from one that killed the job:Finalis true only when the job moved to the failed jobs (permanent, or out of retries), and false for an attempt a shutdown gave back — whichAttemptandMaxRetriesalone cannot distinguish from an exhausted one, since the free attempt is counted before it is given back. -
Job observers (
queue.Observer: dispatched, processed, failed; never the payload):q.AddObserverappends,q.SetObserverreplaces them all;app.Queue()adds devtools and theapp.Instrumenthooks. Nil observers, typed nil pointers included, are ignored. A panicking observer is logged (observer type, job kind and id, panic value) and skipped: the dispatch or attempt goes on and the observers after it still run. -
Progress is not a queue feature (decided, not an omission). The queue's contract is delivery:
Push/Pop/Ack/Release/Failplus the retry policy. A long job's percentage, phase and byte counters belong to the job's own domain row, not to the message, for four reasons:- The reader is the HTTP layer, usually in another process (
serveandqueue:workare separate services), so progress needs shared, queryable storage with its own shape and retention — which is a table, and the app already has one for the work being tracked. The message is deleted onAck, exactly when a UI still wants to show "done". - A hook on
queue.Observerwould not fix that: observers run in the worker process, on the caller's goroutine, so a progress value published through one never reaches the web process. It would look like a progress API and silently do nothing in the normal two-service deployment — worse than not having one. - Delivery is at least once and an interrupted or taken-over job runs again from the start, so a counter the queue owns would go backwards or lie after a retry. A row the handler owns is reset by the handler, in the same transaction as the work it describes.
- Carrying progress in the message would need a new
Drivermethod, breaking every driver (including third-party ones) for data the queue itself never reads.
The pattern that works, and the one to copy: the handler writes its own progress row (
UPDATE conversions SET phase = $1, done_bytes = $2 WHERE id = $3) withapp.DB(); HTTP reads that row, and streams it withsse.Hubplus ansse.Brokerwhen the producer and the consumer are different processes. Stampqueue.AttemptFrom(ctx)into the row so a restarted attempt is visible instead of looking like progress going backwards, and close the row onqueue.ErrPermanentor onAttempt.Last()so it never staysrunningafter the job is gone. - The reader is the HTTP layer, usually in another process (
-
Commands:
queue:work [-queue high,default] [-concurrency 4] [-once] [-stop-when-empty] [-sleep 1s](Ctrl+C drains running jobs),queue:failed [-json] [-limit 100],queue:retry <ids…|all>,queue:forget <ids…|all>. They run in their own process, so they need a shared driver (database, Redis):queue:workonsyncexits at once withQUEUE_CONNECTION=sync runs jobs during Dispatch, so queue:work has nothing to process, and the failed-job commands onsyncormemory(whose failed jobs live in the serving process) return an error wrappingvukem.ErrNoFailedStorethat names the setting. -
The
database/dbtestconformance suite covers the driver (exactly-once processing with concurrent workers,DispatchTxrollback, failed/retry/forget, takeover of abandoned jobs) on SQLite and Postgres. -
vukem make:job SendInvoicewritesapp/jobs/send_invoice.go(job type,Kind, andHandleSendInvoice(app *vukem.App)returning the handler) and registersqueue.Handle(HandleSendInvoice(app))inapp/jobs/registry.go, whoseAll(app)bootstrappasses tovukem.WithJobsFunc. Handlers reachapp.DB(),app.Now()andapp.Mailer()without globals; the function runs once, inside the firstapp.Queue()call (a panic in it becomes that call's error). It may getapp.DB(),app.Mailer(),app.Cryptandapp.Now(), but must not dispatch:app.Queue(),app.Events.Dispatchwith queued listeners,SendLater/MailLateror running scheduled jobs wait for the queue being built and deadlock (handlers may do all of that when they run). Projects whoseAll()takes no app keep getting dependency-free handlers registered withWithJobs. -
Queued mail:
mailer.SendLater(ctx, mailable)/app.MailLater(ctx, mailable)renders now and sends from a job (retried; the message ID is stable across retries). The payload is the rendered message sealed withapp.Crypt, so mail bodies and addresses never reach the jobs tables in clear text. Clear-text mail jobs (queued before v0.24.0) fail unlessQUEUE_ALLOW_LEGACY_MAIL=true, an upgrade window that logs a warning per job: drain the queue before upgrading, or set the flag until the old jobs are gone. The additional data is fixed, so someone with write access to the jobs table can replay a sealed mail (accepted: that access allows worse). -
Queued listeners:
events.OnQueued("update_stock", listeners.UpdateStock)(ormake:listener UpdateStock --event OrderShipped --queued) enqueues the event as JSON and runs the listener in a worker;Dispatchreturns only enqueue errors. -
Outgoing webhooks:
webhook.Senderregisters awebhook.deliverjob (s.Job()) ands.Send(ctx, q, webhook.Delivery{Endpoint, Payload})enqueues it. Each attempt looks the endpoint up by id (URL and secret never enter the jobs tables), signs it with the Standard Webhooks scheme and posts throughhttpclient.Safe: 2xx succeeds, 410 Gone stops (OnGone), anything else retries (8 times, exponential from 30s).webhook.SQLDeliveryLogrecords each attempt in its own table; apps with an existing deliveries table implementwebhook.DeliveryLog(or wrap a function inwebhook.DeliveryLogFunc) and mapAttemptonto their columns. See security.md. -
Testing: pass
vukem.WithQueueDriver(fake)withfake := queue.NewFake();queue.Dispatched[jobs.SendInvoice](fake)returns the dispatched jobs, andq.Work(ctx, queue.WorkOptions{StopWhenEmpty: true})runs them when the test wants to. -
Inspired by River (typed workers, transactional enqueue) and goqite (SQLite).
// routes/schedule.go (bootstrap passes it to vukem.WithSchedule)
func Schedule(s *schedule.Schedule, app *vukem.App) {
s.Command("reports:send", "--daily").DailyAt("08:00").WithoutOverlapping()
s.Job(jobs.PruneSessions{}).Hourly()
s.Func("ping", func(ctx context.Context) error { ... }).EveryFiveMinutes()
s.Func("invoices", sendInvoices).Cron("30 9 1 * *").In(saoPaulo)
}- Expressions: five-field cron (
*, values, ranges, steps, lists,JAN/MONnames,@daily-style macros; Vixie semantics: the day fields combine with OR only when both are restricted, and with AND when either starts with*, such as*/2) or helpers:EveryMinute,EveryFiveMinutes,Every(15*time.Minute)(whole minutes dividing an hour, or exactly24*time.Hour),Hourly,HourlyAt,Daily,DailyAt("HH:MM"),Weekdays,WeeklyOn,MonthlyOn. Bad expressions panic at boot. The parser is fuzzed. - Time zone:
SCHEDULE_TIMEZONE(IANA name, default UTC; the zone database is embedded, so it works on Windows hosts without one) or.In(loc)per task. - Daylight saving time follows Vixie cron: a task with a fixed hour runs once per wall-clock day, so it does not run twice when the clock goes back and runs right after the jump when the clock skips its time; a task with a wildcard hour (
*/15 * * * *) follows real time.Nextdoes not apply this rule. WithoutOverlapping()takes a lock (schedule:<app>:<task>) inApp.Cache(useCACHE_STORE=databaseor Redis when several servers run the schedule); a run is skipped while the previous one holds it.OnOneServer()takes a per-occurrence lock (schedule:one:<app>:<task>:<minute>, never released, expires after 1h) inApp.Cache: one scheduler runs the occurrence, the others skip it. It fails closed: with a lock storecache.Shareddoes not report as shared (the memory cache, or a store withoutcache.Sharer)Schedule.Validatereturnsschedule.ErrLocksNotShared,app.Schedule()fails (soserve,schedule:workandschedule:rundo not start) and the task refuses to run.- Lock keys carry
<app>, the normalizedAPP_NAME(schedule.Options.Namespace), so apps sharing one Redis or cache table keep their locks apart: give each app a uniqueAPP_NAME(orCACHE_PREFIX). Upgrading changes the keys, so a run in progress during that deploy is not seen by the new version. serveruns the scheduler in process by default (SCHEDULE_IN_SERVE=true), so a single-process deploy still runs the hourlysession:prune/cache:prune; it starts only when tasks exist and stops with the app (stops ticking, gives running tasksSHUTDOWN_TIMEOUT, then cancels theirctx;schedule.Options.StopTimeout, default 30s outside the app). Tasks must honorctx: one that ignores it holds shutdown. SetSCHEDULE_IN_SERVE=falsewhen a dedicated process runs the schedule instead:vukem schedule:work(ticks at the start of every minute, drains running tasks on shutdown withinSHUTDOWN_TIMEOUT) or one cron entry:* * * * * cd /app && ./app schedule:run.vukem schedule:listshows each task's next run.- Several replicas: each process running the scheduler fires every due task (no leader election). Tasks without
WithoutOverlapping()run once per replica;WithoutOverlapping()with a shared lock store only skips a run while another replica still holds the lock, so a short task can still run on several replicas in the same minute (with the in-memory cache, locks are per process). Built-in prune tasks are idempotent; for run-once tasks useOnOneServer()with a shared cache, or setSCHEDULE_IN_SERVE=falseand run a singleschedule:work. - Tasks run concurrently; failures and panics are logged and do not stop other tasks. Command tasks run in the same process through
App.Call.
go get github.com/AlexGalhardo/vukem/drivers/redis (go-redis v9; works with Redis 7+ and Valkey 8+, both run in CI).
rc, err := redis.Open(ctx, os.Getenv("REDIS_URL")) // redis://localhost:6379/0; any other host needs rediss:// (or ?insecure_plaintext=true)
app, err := vukem.New(
vukem.WithCacheStore(rc.CacheStore("cache:")), // also backs scheduler and cache locks
vukem.WithSessionStore(rc.SessionStore("")), // "session:" keys with TTL; revoke and list per user
vukem.WithQueueDriver(rc.Queue(redis.QueueOptions{})),
)
limiter := rc.RateLimiter("api:", 60, time.Minute) // ratelimit.Limiter shared by every server
msgs, err := rc.Subscribe(ctx, "orders") // pub/sub (SSE fan-out); rc.Publish(ctx, "orders", b)
presence := rc.PresenceStore("presence:", 0) // broadcast.Config.Presence: cluster-wide "here" listsos.Getenvruns beforevukem.Newloads.envandvukemtestsources.vukem.WithCacheStoreFunc,WithSessionStoreFuncandWithQueueDriverFunctakefunc(*App) (store, error)instead, called on the firstapp.Cache()/app.Sessions()/app.Queue()after configuration loaded, so the URL comes fromapp.Source.Get("REDIS_URL"); the function's error is returned by that call. The last of the eager and lazy option wins.- A lazy function returns
nil, vukem.ErrUseDefault(directly or through single%wwraps), e.g. whenREDIS_URLis empty, to keep the storeCACHE_STORE/SESSION_DRIVER/QUEUE_CONNECTIONchooses (memory cache, cookie sessions, sync queue by default); the app logs the choice, atWARNin production. Only that sentinel falls back: any other error (malformed URL,redis.Openagainst a server that is down), also one joined with the sentinel (errors.Join, several%w), fails the accessor, so a configured but broken Redis is a boot error or, withOpenLazy, a failing readiness check, never a silent switch.nil, niland a store returned withErrUseDefaultare errors. The fallback store keeps itscache.Shareranswer (memory:OnOneServerandRATE_LIMIT_STORE=cachefail at boot). WithQUEUE_CONNECTION=database, boot runs the queue function once and creates the queue tables only when it falls back (its error fails the boot). - Risk: a missing or misspelled
REDIS_URLin production also falls back, to per-process stores. ReturnErrUseDefaultonly when!app.Config.IsProduction()and an error otherwise, so production without Redis fails at boot. - The queue keeps jobs in sorted sets under
{queue}:(one Cluster slot) and reserves them with one Lua script; abandoned jobs are taken over after their timeout plus one minute (eachPoprecords the reservation deadline it handed the worker, andAck,ReleaseandFailact only while that is still the job's: a worker that lost its reservation getsqueue.ErrReservationLostand its result is dropped), failed jobs supportqueue:failed,queue:retryandqueue:forget. Flushdeletes only the store's prefix (SCAN+DEL), never the whole database, and refuses an empty prefix.rc.PresenceStore(prefix, ttl)is abroadcast.PresenceStore(broadcast.Config{Broker: rc, Presence: rc.PresenceStore("presence:", 0)}): each presence channel keeps three keys (a hash of member JSON and a hash of member IDs, both by connection, and a sorted set of expiry times) that one Lua script updates atomically, so "first connection" and "last connection" are exact when instances race. A connection not touched forttl(default 60 s; the broadcast heartbeat is 20 s, keep it under a third ofttl) is dropped, so the members of an instance that died disappear and nothing is announced for them. Redis Cluster is not supported (three keys per channel), and the expiry uses the app clocks, so keep them in sync (recommended). Each join and leave scans the channel's connections, fine for rooms up to a few thousand.Openpings the server, so the app does not boot while Redis is down; a malformed URL always fails.redis.OpenLazy(url)only parses the URL and connects on first use, so the process starts andrc.Pingreports the outage in a readiness check (app.AddHealthCheck("redis", rc.Ping)). go-redis retries a failed command 3 times with backoff, so thatPingtakes seconds while Redis is down; for a fast readiness answer set?dial_timeout=1s&max_retries=-1on the URL (or open a separate client with those options just for the check).- The driver passes the
cachetestandqueuetestconformance suites.
go get github.com/AlexGalhardo/vukem/drivers/otel (OpenTelemetry Go SDK v1.47, OTLP/HTTP exporter, semantic conventions v1.43).
app, err := vukem.New(
vukem.WithProviders(otel.New(otel.Config{})), // before routes: its middleware wraps the whole stack
vukem.WithRoutes(routes),
)
r.UseServer(otel.Middleware(tp)) // or bring your own trace.TracerProviderotel.Middleware(tp, opts...)isfunc(http.Handler) http.Handler: one server span per request, the trace continued from the incomingtraceparent(W3C TraceContext + Baggage by default,otel.WithPropagatorto change it).- The span is named
METHOD /route/{param}after the matched ServeMux pattern, or justMETHODwhen nothing matched; raw paths never become span names. Installed with bothRouter.UseServerandRouter.Use(what the provider does), the route-level copy names the span even when middleware in between replaced the request. - Attributes:
http.request.method(unknown methods as_OTHER),http.route,http.response.status_code,url.scheme,server.address,server.port,network.protocol.version,user_agent.original. Paths and query strings are not recorded: they can carry tokens and signatures. - 5xx responses and panics set the span status to Error with
error.type; 4xx stay unset, as the HTTP conventions ask. Panics are re-raised formiddleware.Recover. - The provider reads
OTEL_*settings fromapp.Source, so.envfiles work as well as the process environment:OTEL_EXPORTER_OTLP_TRACES_ENDPOINT(used as is) orOTEL_EXPORTER_OTLP_ENDPOINT(/v1/tracesappended);OTEL_EXPORTER_OTLP_[TRACES_]HEADERS(key=value,..., percent-decoded; collector API keys),OTEL_EXPORTER_OTLP_[TRACES_]TIMEOUT(milliseconds) andOTEL_EXPORTER_OTLP_[TRACES_]COMPRESSION(gzipornone);OTEL_TRACES_SAMPLER/OTEL_TRACES_SAMPLER_ARG(always_on,always_off,traceidratio,parentbased_always_on,parentbased_always_off,parentbased_traceidratio);OTEL_RESOURCE_ATTRIBUTES. A non-http(s) endpoint or a malformed value is a boot error that names the variable, never its value. With no endpoint tracing is off;OTEL_SDK_DISABLED=trueturns everything off. - The resource carries
deployment.environment.name(APP_ENV), thenOTEL_RESOURCE_ATTRIBUTES, andservice.namefromConfig.ServiceName, elseOTEL_SERVICE_NAME, else the attributes, elseAPP_NAME, andservice.versionfromConfig.ServiceVersion, elseOTEL_SERVICE_VERSION, else the attributes. Spans and metrics are batched and flushed byapp.Shutdown, whichapp.Runcalls after the HTTP server and queue worker have drained (withinSHUTDOWN_TIMEOUT); called with a context without deadline, the flush gives up after 10s. Config.Exporterreplaces OTLP (tests usetracetest.NewInMemoryExporter),Config.Samplerwins overOTEL_TRACES_SAMPLER(defaultParentBased(AlwaysSample)), andConfig.Globalalso sets the OpenTelemetry globals for libraries instrumented through them (off by default: no package-level state); only signals that are on are installed (tracer and propagator with tracing, meter with metrics), so a disabled one never replaces an existing global with a no-op.- Log correlation:
otel.LogHandler(next)addstrace_idandspan_id(hex) to records whose context carries a valid span; the provider wrapsapp.Logand the router'sweb.Ctx.Log()logger with it when tracing is on, so request logs andc.Log().InfoContext(c.Context(), ...)records link to their trace. Log with the*Contextmethods; records logged without a context are not correlated.
Core exposes neutral hook points and never imports OpenTelemetry: app.Instrument(vukem.Instrumentation{Queries, Jobs, Mail}) adds a database.QueryObserver, a queue.Observer and a mail transport wrapper next to devtools, and httpclient.Options.WrapTransport wraps a Safe client's transport; httpclient.Throttle (per-host rate and in-flight bound), httpclient.Retry (idempotent requests, Retry-After, jittered backoff) and httpclient.Breaker (per-host circuit, ErrCircuitOpen) are such wrappers, composed outermost-first as Retry(Breaker(Throttle(rt))). The wrapper must delegate to the transport it is given, where the SSRF check runs; one returning nil fails every request with httpclient.ErrNilTransport instead of falling back to http.DefaultTransport. Instrument must run before DB(), Queue() or Mailer() is first used, so call it from a provider's Register; a late hook fails with vukem.ErrInstrumentTooLate. The otel provider treats that as a boot error, not a warning (list otel.New first in WithProviders): a silently partial trace is harder to notice than a failed boot, and the providers it built are shut down.
The provider attaches an otel.Observer (build one with otel.NewObserver(tp, opts...) for a custom setup):
| Source | Span | Attributes (never values, addresses or payloads) |
|---|---|---|
DB() statements |
client span named after the operation (SELECT, INSERT...) |
db.system.name (from the DATABASE_URL scheme: postgresql, mysql, mariadb, sqlite; Config.DBSystem / otel.WithDBSystem to set it), db.operation.name; db.query.text only with Config.QueryText / otel.WithQueryText() |
Queue() dispatch |
producer send <queue> |
messaging.system=vukem, messaging.destination.name, messaging.message.id, vukem.job.kind |
Queue() attempt |
consumer process <queue> |
as above plus vukem.job.attempt; failures set Error and error.type |
Mailer() sends |
client mail send |
none (no recipient, subject or body) |
p.Transport(rt) / observer.Transport(rt) |
client METHOD |
http.request.method, url.scheme, server.address, server.port, http.response.status_code; 4xx/5xx set Error |
Database and job reports arrive after the work is done, so those spans are back-dated by the reported duration and parented to the caller's context (a query inside a request is a child of the request span). Jobs run by a worker start a new trace: the dispatching request's context is not carried in the job payload. Outbound requests never get the path or query string recorded, and traceparent/baggage are injected only with otel.WithClientPropagation() (trace ids and baggage would otherwise reach third parties).
client := &http.Client{Transport: tracing.Transport(nil)} // tracing := otel.New(cfg)
safe := httpclient.Safe(httpclient.Options{WrapTransport: tracing.Transport}) // user-supplied URLsMetrics are on when Config.MetricReader is set, or else when OTEL_EXPORTER_OTLP_METRICS_ENDPOINT (used as is) or else OTEL_EXPORTER_OTLP_ENDPOINT (/v1/metrics appended) selects an OTLP/HTTP collector: as in the OpenTelemetry spec, OTEL_METRICS_EXPORTER defaults to otlp and the generic endpoint applies to every signal (since v0.27; before, metrics also needed OTEL_METRICS_EXPORTER=otlp). OTEL_METRICS_EXPORTER=none turns metrics off. On Railway (RAILWAY_ENVIRONMENT or RAILWAY_SERVICE_ID set) the shared endpoint is traces only — the receiver accepts neither logs nor metrics — so metric export stays off unless OTEL_EXPORTER_OTLP_METRICS_ENDPOINT is set, even when OTEL_METRICS_EXPORTER is empty or otlp. Logs on Railway are the process JSON on stdout and stderr (standard error in production); resource and HTTP metrics are Railway's built-in metrics. Values other than otlp and none fail the boot. OTEL_EXPORTER_OTLP_[METRICS_]HEADERS, _TIMEOUT and _COMPRESSION follow the traces rules, and OTEL_METRIC_EXPORT_INTERVAL (milliseconds, default 60000) sets the export period. The provider builds a MeterProvider with the same resource and records, through the same hooks:
| Metric | Kind | Attributes |
|---|---|---|
http.server.request.duration (s) |
histogram | method, http.route, status code, url.scheme, error.type on 5xx and panics |
http.client.request.duration (s) |
histogram | method, server.address, server.port, status code, error.type |
db.client.operation.duration (s) |
histogram | db.system.name, db.operation.name, error.type |
messaging.process.duration (s) |
histogram | messaging.destination.name, vukem.job.kind, error.type |
vukem.queue.job.failures |
counter | as above |
Histogram counts are the request, query and job counts. The module ships the OTLP/HTTP metric exporter (otlpmetrichttp) used by the endpoint variables above; for another backend, pass Config.MetricReader (sdkmetric.NewPeriodicReader(exporter) with that backend's exporter), which wins over the variables. otel.Middleware(tp, otel.WithMeterProvider(mp)) records the server metric without the provider. Without a reader (and without an endpoint) the provider does nothing. Application metrics use the same provider: p.MeterProvider().Meter("app/area") taken inside WithRoutes or WithJobsFunc (after Register; before it the provider is a no-op and instruments made from it never record) exports through the same reader and resource.
Package crypt, stdlib only. app.Crypt is built at boot from a key derived with HKDF from APP_KEY (app.Key.Derive("crypt", 32)), plus the keys derived from APP_PREVIOUS_KEYS (configuration.md).
token := app.Crypt.EncryptString("4111 1111 1111 1111")
plain, err := app.Crypt.DecryptString(token) // err is crypt.ErrInvalid on any failure
// Additional data binds a token to its purpose; Open needs the same bytes.
token = app.Crypt.Seal(payload, []byte("invoice:42"))
payload, err = app.Crypt.Open(token, []byte("invoice:42"))
if app.Crypt.NeedsRotation(token) { // sealed with a previous key
token, err = app.Crypt.Rotate(token, []byte("invoice:42"))
}
// Encrypted cookies: the name is the additional data.
err = app.Crypt.SetCookie(w, r, http.Cookie{Name: "cart", Value: "3", Path: "/"})
cart, err := app.Crypt.Cookie(r, "cart") // http.ErrNoCookie or crypt.ErrInvalid- AES-256-GCM with a random 96-bit nonce per token (
cipher.NewGCMWithRandomNonce); keys must be 32 bytes (crypt.New(current, previous...)). - Token: unpadded base64url of
version (1) | key id (4) | nonce (12) | ciphertext | tag (16). The key id (truncated SHA-256 of the key) selects the key; the header is authenticated with the additional data. - Every failure (malformed, tampered, unknown key, other additional data) returns
crypt.ErrInvalid, without telling which. SetCookiealways setsHttpOnly, defaultsSameSiteto Lax, addsSecurewhen the request came over TLS (setSecureyourself behind a TLS-terminating proxy), refusesSameSite=NonewithoutSecureand values over 4 KB (crypt.ErrCookieTooLarge).- Database columns:
orm.Encrypted[T]. - Key rotation:
app.Cryptopens tokens sealed with anyAPP_PREVIOUS_KEYSentry and seals withAPP_KEY. Other keyed features take their previous keys fromapp.DerivePreviousKeys(purpose, n); see Key rotation for the full procedure andvukem key:rotate.
Package i18n, stdlib only. One JSON catalog per locale in resources/lang/<locale>.json (en.json, pt-BR.json; pt_BR.json is accepted); any other .json name at the root of the folder fails i18n.Load with file name is not a locale. Keys are nested objects or dotted names; values are strings with {name} placeholders, or plural objects.
{
"welcome": "Hello, {name}!",
"posts": {
"created": "Post created.",
"count": { "zero": "No posts", "one": "{count} post", "other": "{count} posts" }
}
}app, err := vukem.New(
vukem.WithTranslations(os.DirFS("resources/lang")), // App.I18n; APP_LOCALE is the default (en)
vukem.WithViews(resources.Views()),
vukem.WithRoutes(routes), // routes call vukem.DefaultMiddleware
)
c.Flash("status", i18n.T(c.Context(), "posts.created")) // handlers
b.T("pt-BR", "posts.count", "count", 3) // a Bundle directly<html lang="{{locale}}">
<p>{{t "welcome" "name" .User.Name}} · {{t "posts.count" "count" (len .Posts)}}</p>- Fallback chain: the locale, its shorter forms, then the default (
pt-BR→pt→en). A missing key returns the key and callsOptions.OnMissingwhen set; translating never panics. - Plurals: an object whose keys are CLDR categories (
zero,one,two,few,many,other;otherrequired: such an object withoutotherfails the load) is a plural message, chosen by the numericcountargument. Rules cover en, de, nl, sv, da, nb, fi, et, it, ca, es, el, hu, tr, bg, pt, pt-PT, fr, ru, uk, be, pl, cs, sk, ar, he, and ja, zh, ko, th, vi, id, ms (onlyother); other languages use the English rule. An explicitzeroform wins for 0 in every language. When a key falls back to another locale, the plural form is chosen with the rules of the locale the message came from, not the requested one.i18n.PluralCategory(locale, n)exposes the rules. - Arguments: key/value pairs (
"name", "Ana") or onemap[string]any; unknown placeholders stay as written. Output is plain text, sohtml/templateescapes it. - Locale resolution:
i18n.Middleware(bundle, i18n.MiddlewareConfig{})returns(middleware, error); the middleware checks, in order,?lang=, thelangcookie, the session valuelocale(when the session middleware runs first),Accept-Language(RFC 9110 q-values, at most 16 entries) and the default. Candidates must be valid tags matching an available catalog (Bundle.Match: exact, shorter form, then same language); invalid input is ignored. It stores the bundle and locale in the context (i18n.Locale,i18n.WithLocale,i18n.BundleFrom), setsContent-Language, addsVary: Cookiewhen the cookie or session was consulted andVary: Accept-Languagewhen the header was. Rename or disable ("-") sources withQuery,Cookie,SessionKey;Order(i18n.SourceQuery,SourceCookie,SourceSession,SourceHeader) picks the sources and their order (left out = off) andLocaleslimits the selectable locales (must include the default).MiddlewareConfig.Validate(bundle)reports bad entries (i18n.Middlewarereturns them;i18n.NewMiddlewareis a deprecated//go:fix inlinealias);vukem.MiddlewareOptions.I18npasses the config to the default stack and validates it at boot. Apps persist a choice by setting the cookie or session value themselves. - Locale URL prefixes:
MiddlewareConfig.PathPrefixes({"pt-br": "pt-BR"}) plusi18n.SourcePath(first in a nilOrder):i18n.StripPathPrefix, installed on the server stack byDefaultMiddlewareWith/APIMiddlewareWith, removes an exact first segment before routing (/pt-br/gamesroutes as/games,/pt-bras/) and records it; the resolver picks its locale withoutVary;i18n.PathPrefix(ctx)andi18n.LocalizePath(ctx, "/games")re-add it to generated URLs. Prefixes must be one plain segment of an available (and allowed) locale, or the boot fails (FuzzStripPathPrefix). - App wiring:
WithTranslationsloads the bundle at boot (bad JSON or file names failNew), gives views thetandlocalefunctions (view.Config.I18n) and makesDefaultMiddlewareinstall the middleware after sessions. - Validation: the middleware also translates
web.Parse/Bindmessages fromvalidation.*keys (validation.md). - Framework messages: errors from
auth,socialandorm.Unique/Existscarry message keys (auth.failed,auth.unauthenticated,auth.unverified,auth.token_abilitywith{ability},social.unknown_provider,social.state,social.denied,social.failed,social.not_allowed,auth.not_allowed,validation.unique,validation.existswith{field}) and keep their English text as the fallback.WithTranslationsadds the built-in English, Spanish and Brazilian Portuguese catalogs (Bundle.AddBuiltin) to the catalogs the app already has (pt-BR messages fillpt-BRandpt, notpt-PT; no catalog is created), never overriding a key the app defines for that locale or its language. The middleware installsBundle.Translator(locale)as the request'serrs.Translator: the error handler showserrs.NewKey(status, key, fallback, params)errors throughHTTPError.LocalizedText, and code with a context callserrs.Translate(ctx, key, fallback, params). Login and reset messages stay generic in every locale (no user enumeration). - Starters do not ship catalogs yet; add
resources/lang/en.jsonand passWithTranslations.
Separate module (github.com/AlexGalhardo/vukem/contrib/engine), standard library only and no core dependency. For an app that shells out to ffmpeg, yt-dlp, Ghostscript or ImageMagick.
tool, err := engine.Find(ctx, engine.Config{
Name: "ffmpeg", VersionArgs: []string{"-version"}, Log: app.Log,
CPUCount: cpu.Count(), // vukem/cpu
Limits: engine.Limits{CPUTime: 10 * time.Minute, AddressSpace: 2 << 30},
})
res, err := tool.Run(ctx, jobDir, "-i", in, "-threads", strconv.Itoa(tool.CPUCount()), out)Find is a boot call: a missing binary, or limits that cannot be applied here, stops the process instead of surfacing on the first request. It logs the resolved path and version, and the probe reads stderr as well as stdout, taking the first non-blank line — poppler's pdftotext and pdftoppm answer -v on stderr with exit 0, so a stdout-only probe records "unknown" for a tool that works.
Six things it does that are traps rather than preferences:
| What, and why it is not a preference | |
|---|---|
| no inherited environment | os.Environ() holds the database URL and the bucket credentials. The child sees PATH, the platform minimum (SystemRoot/windir on Windows), LANG/LC_ALL when set, HOME, the temp triple, and Config.Env — so widening it is a visible decision in the app's code |
| pinned temp directory | TMPDIR, TEMP and TMP point at the run's own directory. See below |
| native resource limits | syscall.Setrlimit applies to the caller and Go has no pre-exec hook, so a limit set in the parent bounds the server. Linux: prlimit applies them and then execs. Windows: every run is assigned to a Job Object: AddressSpace becomes ProcessMemoryLimit (committed memory per process; an allocation over it fails), Processes becomes ActiveProcessLimit (per run, counting the tool itself), CPUTime becomes PerProcessUserTimeLimit (user-mode time, rounded to 100 ns), and the job has kill-on-close, so cancelling a run, or a run that ends with a helper still alive, takes the whole tree down (this replaces the taskkill tree kill; taskkill stays only as the fallback when a run without limits cannot join its job). FileSize has no Job Object equivalent and is refused on Windows. The process is created suspended, put in the job and only then resumed, so it runs no code (spawns nothing, allocates nothing) before its limits apply; if it cannot join a limited job it is killed and the run fails. macOS keeps ErrLimitsUnsupported: RLIMIT_AS is not enforced there and there is no prlimit or job mechanism that bounds a child instead of the server. Find refuses limits it cannot apply: silently unlimited execution is the outcome worth refusing |
Config.Prepare |
not a trap: a hook that receives each run's finished *exec.Cmd before it starts, for what this package does not provide (SysProcAttr, or a macOS limit set by your own code). The Windows Job Object is built in and needs no hook |
| process-group cancellation | ffmpeg and yt-dlp spawn children; killing the parent leaves them holding the working directory open, which on Windows also blocks its removal |
Cmd.Cancel + Cmd.WaitDelay |
not a watcher goroutine, so the context stays on the call |
| bounded capture | Run keeps a tail (MaxOutput, default 64 KiB) with an [earlier output dropped] marker, because a progress line every 200 ms for a 40-minute transcode is megabytes per run. When the tool's product is its stdout, RunStream never buffers it; RunStreams also copies stderr to a writer while the tool runs (progress lines), and still keeps the tail. RunWith(ctx, RunOptions{Dir, Stdin, Stdout, Stderr}, args...) adds a per-run standard input for a tool that reads a pipe (ffmpeg -i pipe:0): the child sees end of file when the reader returns io.EOF, while a reader error or a cancelled context kills the process tree and ends the run with an error (a failed reader never looks like a finished stream). A reader blocked in Read must return once the context is done. A run whose context has no deadline stops after Config.Timeout (5 minutes by default), shorter than a long ingest or transcode: pass a context with the deadline you want |
Measured, not assumed. The same hostile PostScript document writing to an absolute /tmp path, the same -dSAFER:
| Ghostscript | TMPDIR |
Result |
|---|---|---|
| 10.05.1 | /tmp (the default) |
wrote the file and reported success |
| 10.05.1 | the run's directory | refused, Last OS error: Permission denied, exit 1 |
| 10.08.0 | either | refused |
So -dSAFER is not inert: on 10.05.1 it permits writes under whatever TMPDIR names, and TMPDIR defaults to /tmp, which made the whole tree writable by a document. 10.08.0 fixed it.
Do not read that as a workaround that expired. Pinning is worth having whatever the tool: ffmpeg's muxers, yt-dlp's fragments and ImageMagick's scratch files all land in the temp directory, so pinning keeps a run's temporary files inside the directory the caller is about to delete, keeps two concurrent runs from colliding on a shared name in /tmp, and contains a tool that writes where it should not by default rather than by a flag the next release might reinterpret.
Tool.CPUCount() reports the budget and this package never puts it in the arguments. It cannot: -threads is positional in ffmpeg (before an input it bounds that input's decoder, after the inputs it bounds the encoder, and the wrong one gives "at least one of its streams received no packets" with no cause named), and SVT-AV1 ignores -threads entirely and needs -svtav1-params lp=. Set Config.CPUCount from cpu.Count(), never from runtime.GOMAXPROCS, which rounds the quota up and never drops below 2.
Progress parsing is deliberately not here: it is the shape of a progress subsystem, not of a subprocess seam.
Separate module (github.com/AlexGalhardo/vukem/contrib/stripe), standard library only (no stripe-go). Use a restricted key (rk_…).
stripe.New(key, stripe.WithRetries(2)): every request pinsStripe-Version: 2026-08-26.dahlia(stripe.APIVersion), every POST carries anIdempotency-Key(generated per call, or yours:CreatePaymentIntent(ctx, params, "order-42"), orstripe.IdempotencyKey("order-42-transfer")onCalland the Connect methods; GETs never send one) so retries on 429/5xx/network errors are safe, honouringRetry-AfterandStripe-Should-Retry. Errors are*stripe.Error{Status, Type, Code, DeclineCode, Message, Param, RequestID}; test them witherrors.Is(err, stripe.ErrCardDeclined)(alsoErrInvalid,ErrRateLimited,ErrAuth,ErrNotFound). The client prints asrk_…abcd, never the key (TestSecurity_A09_StripeKeyRedacted).- Resources:
CreateCustomer/GetCustomer/UpdateCustomer,CreateCheckoutSession/GetCheckoutSession(never passpayment_method_types; dynamic payment methods come from the Dashboard),ListCheckoutSessions/ExpireCheckoutSession(expire a customer's open sessions before a new Checkout),ListSubscriptions/GetSubscription/UpdateSubscription/CancelSubscription(ListSubscriptionsneedsstatus: "all"to include canceled ones;Subscription.CreatedandCheckoutSession.Createdare Unix times),CreatePortalSession,CreatePaymentIntent/GetPaymentIntent,CreateRefund/GetRefund(Refund{Status, FailureReason, TransferReversal, …}; passIdempotencyKey, andOnAccountfor a direct charge's refund), andCall(ctx, method, path, params, &out, opts...)for any other endpoint (the path must start with/v1/or/v2/and contain no..,%2e,?,#,\or control characters, or the call fails withstripe.ErrInvalidRequestOption; a/v2/...path is API v2: writes are JSON, anilvalue is JSONnull, and POST and DELETE carry anIdempotency-Key; a DELETE without params sends no body) (Dois deprecated in favour ofCall;go fixinlines it). Expandable ids (customer,subscription,payment_intent,latest_charge,on_behalf_of,transfer_data.destination, a transfer'sdestination/destination_payment/source_transaction,price.product) stay strings: when you passexpand[]the typed structs decode the expanded object'sid; decode into your own struct or*json.RawMessagefor the full object. A generated key only protects the client's own retries; passIdempotencyKeytied to the business operation when a retried job must never charge or pay twice, e.g.c.Call(ctx, http.MethodPost, "/v1/checkout/sessions", params, &cs, stripe.IdempotencyKey("order-42-checkout")).stripe.Paramsnests (line_items[0][price]). - Connect, Accounts v2 (Stripe's current connected-account API; the marketplace showcase saw v1 account creation refused on a new platform):
CreateAccountV2(POST/v2/core/accounts, JSON:dashboard=express,defaults.responsibilities.fees_collector/losses_collector=application,identity.country,configuration.merchant/recipientcapabilities,include),GetAccountV2(ctx, "acct_…", []string{"configuration.recipient", "requirements"})(sent asinclude[0]=…; v2 returns configurations and requirements only when included, so a nilConfiguration.Recipientmeans not included),UpdateAccountV2,CreateAccountLinkV2(account,use_case.type=account_onboarding|account_updateand itsrefresh_url,return_urlandconfigurations, which the pinned2026-08-26.dahliarequires and2026-09-30.endiveremoves).AccountV2types the merchant (card_payments,stripe_balance.payouts) and recipient (stripe_balance.stripe_transfers, which must beactivebefore transfers) capabilities with theirstatus_details, andRequirements.Entries/Summary.MinimumDeadline; v2 timestamps decode astime.Time. Every request (v1 and v2) pins the sameStripe-Version, which v2 requires. v2 errors keep the{"error":{…}}envelope; the client maps the v2 typerate_limittorate_limit_errorand an empty or unknown type (e.g. codeinvalid_fields) to the HTTP status, soErrInvalid,ErrAuth,ErrRateLimitedand the newErrNotFound(any 404: v1resource_missing, v2not_found) match both APIs. A v2 account id works with the v1 endpoints below. - Connect, v1 (still supported; Stripe still requires v1 for OAuth, Treasury and card issuing, and discourages keeping both versions indefinitely):
CreateAccount(passcontroller[stripe_dashboard][type]=express,controller[fees][payer]=application,controller[losses][payments]=application, or the legacytype=express),GetAccount(ChargesEnabled,DetailsSubmitted,Requirements),CreateAccountLink(account,type=account_onboarding,refresh_url,return_url; single-use, give it only to the signed-in account holder),CreateLoginLink(ctx, "acct_…")(Express dashboard),CreateTransfer/GetTransfer(separate charges and transfers:destination,transfer_group,source_transaction),CreateTransferReversal(ctx, "tr_…", params)/GetTransferReversal(reverse the seller's share before refunding the buyer; passIdempotencyKey). Destination charges are plain params:application_fee_amountandtransfer_data[destination]on a PaymentIntent, orpayment_intent_data[application_fee_amount]on a Checkout Session;PaymentIntentdecodesApplicationFeeAmount,TransferData,OnBehalfOf,TransferGroup. Act as a connected account (direct charges, reads) withc.ForAccount("acct_…")or the per-requeststripe.OnAccount("acct_…"), which sendStripe-Account. The Connect methods (CreateAccount,GetAccount,CreateAccountLink,CreateLoginLink,CreateTransfer,GetTransfer, the…AccountV2/CreateAccountLinkV2methods and the transfer reversals) act on the platform account, so throughForAccountor withOnAccountthey fail withstripe.ErrInvalidRequestOptioninstead of acting on the wrong account (TestSecurity_A01_StripePlatformOnlyRefusesAccountScope). Account ids must beacct_+ alphanumerics (likewisetr_transfers,trr_reversals,re_/pyr_refunds) and idempotency keys printable ASCII up to 255 bytes; anything else fails withstripe.ErrInvalidRequestOptionbefore a request is sent (TestSecurity_A03_StripeRequestHeadersValidated). - Webhooks:
stripe.WebhookHandler(stripe.WebhookConfig{Secret, Store, Bus})verifiesStripe-Signature(HMAC-SHA256 oft.payload, any of severalv1signatures, ±5 min tolerance), claims the event id in acache.Store(memory, database or Redis) so a duplicate delivery is acknowledged without processing, dispatchesstripe.Received{Event}on theevents.Busand only then marks it done; a failing listener releases the claim and answers 500 so Stripe redelivers (TestSecurity_A08_StripeWebhookSignature). Decode the object withstripe.Decode[stripe.CheckoutSession](ev). For Connect, add the Connect endpoint's secret toSecrets(a platform endpoint and a Connect endpoint sign with different secrets even on the same URL; the payload must verify against one of them) and read the connected account fromEvent.Account(""for platform events), e.g.account.updateddecoded withstripe.Decode[stripe.Account]. Mount it outside CSRF protection; fulfil orders fromcheckout.session.completed/checkout.session.async_payment_succeeded, never from the success page.stripe.SignForTestsigns payloads for app tests. vukem install:billingscaffolds subscriptions on top of this module (plans, Checkout, Billing Portal, webhook sync,Subscribed/OnPlanmiddleware): see billing.md.