Domain Addon Modules
Domain addon modules: scheduler, settings, storage, notifications, verification, links, metrics, search, i18n, apilog, content, workers, coordination, websockets, and flowexec.
github.com/redelay/go-modules provides domain-level feature modules that extend the Redelay framework. Each module is added via a blank import and works with zero configuration defaults.
Quick start
go get github.com/redelay/go-modules
import (
_ "github.com/redelay/go-modules/scheduler"
_ "github.com/redelay/go-modules/metrics"
// add more as needed
)
Module overview
| Module | Package | Purpose |
|---|---|---|
| scheduler | go-modules/scheduler | Distributed cron with leader election |
| settings | go-framework/modules/settings | Key-value settings API |
| storage | go-modules/storage | Object storage (S3/MinIO) with S3 list / head / copy / delete-many nodes |
| notifications | go-modules/notifications | Real-time SSE notifications |
| verification | go-modules/verification | Email address verification |
| links | go-modules/links | URL shortener |
| metrics | go-modules/metrics | Prometheus metrics |
| flowexec | go-flowdsl/flowexec/module | Flow CRUD, versioning, run launch, live SSE events |
| search | go-modules/search | Pluggable vector search (Qdrant today, OpenSearch planned) with index CRUD + FlowDSL upsert/query nodes |
| i18n | go-modules/i18n | Locale-resolution middleware, Mongo message catalog with fallback chain, admin CRUD, translate/resolve-locale nodes. Also drives customer-app UI-label i18n: write-once POST /i18n/report-keys (frontend auto-registers the $t keys it uses; I18N_AUTOREGISTER), admin POST /admin/i18n/translations/translate-missing (bulk AI-translate every active locale via the ai module), and a per-key Translation.Context hint. Reusable frontend $t plumbing — catalog + ICU plurals via Intl.PluralRules + interpolation + build-time extractor — ships in redelay-starter-kit/templates/nuxt-i18n. The admin Translations catalog adds a Default-text column, per-row Re-translate, and per-key context; localized admin fields (LocalizedField) take a per-field context. |
| flowtemplates | go-modules/flowtemplates | Curated starter flows surfaced via flowexec.TemplateProvider |
| coordination | go-modules/coordination | Cross-container Coordinator — pub/sub, streams, KV (NATS or Redis backend) |
| websockets | go-modules/ws | WebSocket hub — rooms + cross-replica fan-out, health/info/broadcast control plane |
| security | go-modules/security | Per-user security — activity log, trusted devices, rate limits, auto-restriction; security/admin for IP blocks + user restriction |
| eventadmin | go-modules/eventadmin | Event-bus admin (admin-api only) — event definitions, manual publish, event log, webhook subscriptions |
| metrics/admin | go-modules/metrics/admin | Database observability (admin-api only) — live ClickHouse/Mongo/Redis stats |
| apilog | go-modules/apilog | Time-series log of outbound external API calls, queryable in admin; Mask() redaction + apilog/record debug node |
| ai | go-modules/ai | Provider-agnostic, LLM-assisted content authoring on go-ai (stateless — no DB). ai/admin (admin-api only): POST /admin/ai/translate ({text,from,to,context?}) + POST /admin/ai/generate. Model selection via the ai.models settings group — profile (a named llm-chat profile: provider+model+creds+tuning, overrides the flat fields) / provider (options_ref llm.providers) / model / temperature — admin-editable, no restart; per-consumer profiles let each feature run its own model. translate validates format (placeholders / ICU-plural structure / HTML tags preserved — corrupt locales re-requested then omitted) and translates ICU-plural sources one locale per call; context disambiguates ambiguous terms. |
| content | go-modules/content | CMS-lite scope-scoped localized pages (/pages/{slug}) + reusable fragments (/fragments/{key}). Prose may embed [[ module.key ]] settings tokens, resolved per request against the PUBLIC settings gate. Fragment leaves are localized with an explicit _i18n marker; both pages and fragments carry crud.TranslationState (ready / stale / retranslate). See Localized content. |
| blog | go-modules/blog | Public per-channel blog over content pages of type blog: paginated/tag-filtered listing, post detail (reading time, related), tag counts, RSS |
| systemhealth | go-modules/systemhealth | Admin System → Health (admin-api only): services, sites, schedules, containers, data stores and nodes from Prometheus, plus the project's firing alerts |
| failures | go-modules/failures | Grouped error inbox — Record(), dead-letter review on any transport, failed scheduler runs; 15-min review → bell alerts (new / regressed / spike / critical), daily digest; failures/admin + js-admin System → Failures |
| workers | go-modules/workers | Cross-instance worker registry with heartbeat tracking |
audit (go-modules/audit) is a library package, not a module — it has no factory and
is not blank-imported. Entities embed History []audit.Event and append via audit.Push.
FlowDSL node subpackages
Each module (except metrics and flowexec) ships a flowdsl/ subpackage that registers FlowDSL
nodes as a companion module. Enable them with a blank import:
import (
_ "github.com/redelay/go-modules/scheduler"
_ "github.com/redelay/go-modules/scheduler/flowdsl" // 4 FlowDSL nodes
)
| Subpackage | Factory | Nodes | Kinds |
|---|---|---|---|
scheduler/flowdsl | scheduler-flowdsl | 4 | 2 source (with settings_schema), 2 action |
settings/flowdsl | settings-flowdsl | 3 | 1 transform (with NotFound), 2 action |
storage/flowdsl | storage-flowdsl | 8 | 4 upload/download/delete/presign + 4 S3 list / head / copy / delete-many |
notifications/flowdsl | notifications-flowdsl | 3 | 2 action, 1 source |
verification/flowdsl | verification-flowdsl | 2 | 1 action, 1 router (Valid/Invalid) |
links/flowdsl | links-flowdsl | 3 | 2 action, 1 transform (with NotFound) |
search/flowdsl | search-flowdsl | 2 | 2 action (search-upsert, search-query) |
failures/flowdsl | failures-flowdsl | 1 | 1 action (failures/record, passthrough) |
For the full node catalog — including core, events, redisops, mongoops, and every infrastructure module — browse the Node Catalog.
scheduler
Distributed cron job scheduler with MongoDB persistence and Redis-based leader election.
Only the elected leader runs jobs at any given time — all replicas coordinate automatically.
A schedule fires an event — event_type + event_action on a cron
expression or once at a fixed time. The event goes onto the bus, where any
consumer or FlowDSL flow can react to it. The scheduler is a timer, not an
executor: it decides when, the event bus decides what happens next.
Environment variables
| Variable | Default | Description |
|---|---|---|
SCHEDULER_COLLECTION | scheduler_schedules | MongoDB collection for schedule definitions |
SCHEDULER_LOG_COLLECTION | scheduler_logs | MongoDB collection for execution logs |
SCHEDULER_POLL_INTERVAL_SECONDS | 10 | How often to check for due schedules |
SCHEDULER_LOG_TTL_DAYS | 30 | How long execution history is kept. 0 keeps it forever |
SCHEDULER_LOCK_TTL_SECONDS | 30 | Redis leader-election lock TTL |
SCHEDULER_LOCK_KEY | redelay:<app-name>:scheduler:leader | Redis key for the leader lock. Namespaced by APP_NAME |
SCHEDULER_ENGINE | true | Run the polling loop in this process. false in services that only serve the admin API, so jobs run in dedicated workers |
SCHEDULER_LEADER_LOCK | true | Elect one dispatcher through Redis. Turn off when Redis is per node (one "leader" per node) — run claims keep each run single without it |
SCHEDULER_CLAIM_TTL_MINUTES | 360 | How long a run holds its occurrence; longer than the longest job. A crashed engine's run is retried after it |
SCHEDULER_RUN_NOW | inline | inline: "run now" publishes in the API process (as before). queue: it arms the schedule for the next engine poll, so an API without the engine never runs jobs |
SCHEDULER_WORKERS_COLLECTION | scheduler_workers | Engine heartbeats (GET /schedules/status), expire after an hour |
Run claims — exactly once without a shared lock
Before dispatching, an engine claims the occurrence with a compare-and-set on
the schedule's own next_run_at (claimed_by, claimed_until). Only the engine
whose update matched runs it; the claim holds while the run is in progress, so a
run longer than the poll interval is never started twice; it is released when the
schedule re-arms. A crashed engine's claim expires after
SCHEDULER_CLAIM_TTL_MINUTES and the run is picked up again. Claims are always
on; the Redis leader lock becomes optional (SCHEDULER_LEADER_LOCK=false for a
per-node Redis).
Code defaults — EnsureDefault
Modules declare their schedules in code and call scheduler.EnsureDefault(ctx, storage, Schedule{ID: scheduler.DefaultID("module:job"), …}) at startup (the
storage comes from registry.Get("scheduler").(*scheduler.Module).Storage()).
On every boot an unmodified row follows the code (a cron changed in code
reaches existing deployments); once an admin edits its definition it is marked
modified_from_default and the code no longer overwrites it — the code
definition is still kept (default) and POST /schedules/{id}/reset restores
it. Status (enabled / paused) is never synced.
Job results — scheduler.Report
A consumer can attach what a run did to its execution log:
scheduler.Report(ctx, "sent", n). Works when the bus delivers in-process and
synchronously (the memory transport) — the consumer runs inside the
scheduler's publish; with Kafka it is a no-op.
A run's outcome is the job's — failures, progress, notifications (v0.59.20)
A schedule that publishes is not a job that worked. With Kafka the consumer runs in another process after the publish returned; gymmer's nightly backup read "success, 113 ms" for fifteen nights while no backup happened. Since v0.59.20 the execution row reports the job:
- Automatic, no wiring. The scheduler's factory installs
ReportingMiddlewareon the go-events bus. Any consumer of a schedule's event (it carriesx-scheduler-execution) marks its runrunning, thenfailed(handler returned an error — the error is kept) orsucceeded. A run the job finished itself, or another consumer group already failed, is never turned green again. - Must be installed before consumers register. go-events copies the
middleware list into each consumer at
Register(the go-events module'sConfigure). v0.59.17–19 installed it atStartupand it reached nobody — use v0.59.20+. A non-go-events bus logs a warning; jobs can still report by hand. - Long jobs report progress and can be stopped:
run := scheduler.FromEvent(msg, nil) // or scheduler.RunFrom(ctx) inside the middleware scheduler.Beat(ctx, "mirroring media", map[string]any{"copied": n}) // ≤ 1 write / interval; returns ErrCancelled when a superuser asked to stop run.Done(ctx, map[string]any{"copied": n})
Arunningrun silent forStaleHeartbeatAfter(2 min) shows as stalled;POST /schedules/executions/{id}/cancelis cooperative (409 for a job that does not report). - Failures across every schedule:
GET /schedules/failures?days=7—failing(schedules whose latest runs failed: streak, since, last error) andruns(failed + stalled runs, newest first, with the schedule name). The js-admin Schedules page (≥ v0.7.12) shows Failing now / Recent failures and a sidebar badge with the failing count. - Notifications on transitions: the first failed run of an incident
publishes
scheduler.run_failed, the first success after failuresscheduler.run_recovered(once per run, not per retry).go-modules/notificationsturns them into a bell notification for every active superuser (NOTIFICATIONS_SCHEDULE_ALERTS,NOTIFICATIONS_USERS_COLLECTION,NOTIFICATIONS_SCHEDULE_LINK). Subscribe a flow to them for email / Slack. - Metrics (
SCHEDULER_METRICS=true, one process):scheduler_schedule_consecutive_failures,…_last_success_timestamp_seconds, and since v0.59.19scheduler_schedules_running/scheduler_schedule_running_seconds{schedule}— alert on a run older than its normal length, and let a deploy wait forscheduler_schedules_running == 0before restarting the workers (a rollout kills an in-process run; nameniac's deploy waits ≤ 25 min, see Deploying to production).
Suggested alert rules (Prometheus):
- alert: schedule_failing
expr: max by (schedule, id) (scheduler_schedule_consecutive_failures{job="<app>"}) >= 3
and on (schedule, id) max by (schedule, id) (scheduler_schedule_active{job="<app>"}) == 1
for: 5m
- alert: schedule_running_long
expr: max by (schedule) (scheduler_schedule_running_seconds{job="<app>"}) > 3 * 3600
for: 10m
A job that retries by design (a provider's file not published yet) should get
its own, later threshold instead of tripping schedule_failing every morning.
Leader election — read this before sharing a Redis
Every replica polls; the Redis lock decides which one dispatches. Three things
about that lock exist because each was got wrong once, and the failure they
produce is the same every time: schedules fire on time, every execution logs
success, and nothing is delivered.
The lock key is namespaced per app. It used to be the constant
redelay:scheduler:leader in every deployment, so any process reaching the same
Redis competed for one lock — a second app, a staging environment pointed at the
same instance, or a developer's go run left over from yesterday. Whichever won
dispatched everyone's schedules, into whatever transport it happened to have.
A 27-hour-old local build holding no Kafka connection at all once owned a
deployment's cron for hours this way.
The lock records its holder (host/pid-N), not 1. A lock that says
nothing about its owner cannot answer "which process is running my cron", and
answering it otherwise means stopping containers one at a time.
The lock is only renewed while still owned. A blind EXPIRE extends
whatever is there, so a replica that lost the lock would keep refreshing the new
leader's claim — two dispatchers, and a lock that never changes hands again.
Freezing schedules (before a migration, during an incident)
POST /schedules/{id}/pause and /resume set the state explicitly and are
idempotent — 200 when it is already there. Use these to script a freeze:
# Pause everything. Safe to re-run.
for id in $(curl -s -H "Authorization: Bearer $TOKEN" \
"$API/api/v1/schedules/?limit=200" | jq -r '.items[].id'); do
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
"$API/api/v1/schedules/$id/pause" > /dev/null
done
/toggle exists too but flips, which is right for a switch in a UI and
wrong for a script: re-running a toggle-based freeze turns everything back on,
and two operators running it at once can leave the fleet in either state.
resume deliberately leaves a completed one-time schedule completed —
re-arming it would fire it a second time for reasons nobody chose.
An update leaves status alone unless enabled is sent, so editing a cron
expression or a description during a freeze does not lift it.
Observability
GET /health includes a scheduler check. It is deliberately not unhealthy
for a follower — that is the normal state for every replica but one — but it
does fail when the lock is held by an owner that does not look like a peer,
which is the stale-build case above and is invisible everywhere else.
Each execution log row records host and topic. topic matters because a
schedule whose event_type resolves to nothing still logs success; without it
there is no way to tell a real publish from a no-op. Every dispatch is also
logged at INFO on success as well as failure — a scheduler whose whole job
is to publish used to be silent when it worked, so a deployment where every run
published into a void looked exactly like a healthy one.
If scheduled events stop arriving, check in this order:
GET /health→ theschedulercheck names a foreign lock holder.redis-cli get redelay:<app>:scheduler:leader→ who thinks it is leader.- The
hostfield on recentscheduler_logsrows → who actually dispatched. - A
duration_msof0on every row is a strong hint that publishing is a no-op: a real broker round-trip is not free.
HTTP surface — scheduler/admin (admin-api only)
The management API is a separate submodule, go-modules/scheduler/admin,
blank-imported from the admin-api binary only. The core scheduler module
runs the engine and mounts nothing; importing it on the public api gives you
reliable schedule firing without exposing schedule management there.
// cmd/admin-api only
import _ "github.com/redelay/go-modules/scheduler/admin"
The routes sit at /schedules/ (matching the API contract, not under the admin
prefix) and are gated on RequirePermission("admin:access"). A schedule
publishes an arbitrary event as an arbitrary actor on a timer, so managing them
is an admin capability — the permission check and the admin-api-only import
keep the surface off the public api.
| Method | Path | Purpose |
|---|---|---|
| GET | /schedules/ | List schedules (filter by enabled, tag, event_type, event_action) |
| POST | /schedules/ | Create a schedule |
| GET | /schedules/{schedule_id} | Get a schedule |
| PUT | /schedules/{schedule_id} | Update (partial; changing the timing re-arms the next run) |
| DELETE | /schedules/{schedule_id} | Delete the schedule and its execution history |
| POST | /schedules/{schedule_id}/execute | Fire now, without shifting the regular timing |
| GET | /schedules/{schedule_id}/executions | List execution log entries (newest first; manual, result, host, topic) |
| POST | /schedules/{schedule_id}/toggle | Enable / pause |
| POST | /schedules/{schedule_id}/pause · /resume | Idempotent pause / resume |
| POST | /schedules/{schedule_id}/reset | Restore a code-declared schedule's default definition |
| GET | /schedules/failures | Failing now + failed / stalled runs across every schedule (v0.59.17+) |
| POST | /schedules/executions/{execution_id}/cancel | Ask a reporting job to stop (cooperative; 409 when it does not report) |
| GET | /schedules/{schedule_id}/next-runs?count= | Preview the next fire times |
| GET | /schedules/stats?days= | Per schedule: runs, failures, avg / p95 / max duration, last status / error / result, recent durations |
| GET | /schedules/status | Engines seen in the last hour (heartbeats, alive), run-now mode, leader lock |
A schedule is either recurring (a 5-field cron_expression, read in its own
timezone) or one-time (one_time: true + an execution_time); a one-time
schedule moves to a terminal completed state after it fires. A failed publish
retries up to max_retries with retry_delay seconds between attempts before
waiting for the next occurrence. Six-field cron expressions are rejected — the
parser does not enable seconds, so a sixth field would silently shift every
position.
curl -X POST /api/v1/schedules/ -H 'Authorization: Bearer <admin>' -d '{
"name": "nightly-report",
"event_type": "report", "event_action": "generate",
"cron_expression": "0 3 * * *", "timezone": "Europe/Warsaw",
"event_payload": {"kind": "daily"}
}'
FlowDSL alternative
The same effect is available declaratively — a flow with a cron or interval source node, resolved natively by the flow engine:
nodes:
- id: nightly
nodeType: redelay/scheduler-cron-trigger
settings:
cron: "0 2 * * *"
- id: cleanup
nodeType: mongoops/delete
SchedulesProvider (Schedules() []*ir.Schedule) is metadata only — it
populates the module browser's IR and is not wired to the scheduler service.
settings
Key-value settings store backed by MongoDB with in-memory caching and cluster-wide invalidation.
Implements modules.SettingsReader — other modules resolve settings via dependency injection with automatic 3-layer precedence: DB override → environment variable → YAML default. Updates propagate to all workers instantly via the event bus without a restart.
Data model
type Setting struct {
ModuleID string // e.g. "ai-llm"
Key string // e.g. "openai_api_key"
Value any // JSON-serializable
UpdatedAt time.Time
}
Unique index on (module_id, key). Default collection: _settings.
3-layer resolution precedence
| Priority | Source | Notes |
|---|---|---|
| 1 (highest) | MongoDB (admin-saved) | Written via admin API |
| 2 | Environment variable | Explicit EnvVar field or implicit {MODULE}_{KEY} |
| 3 | YAML default | Declared in module's SettingsDefinition |
Implicit env var naming: module ai-llm + key openai_api_key → AI_LLM_OPENAI_API_KEY (hyphens → underscores, uppercased).
Caching and propagation
Settings are cached in memory per worker behind a sync.RWMutex. The cache is designed for correctness across three deployment shapes:
- Single binary (one cmd/api with admin imports) — local
Service.Setinvalidates the local cache; events are unnecessary. - Multi-binary local dev (cmd/api + cmd/admin-api with
TRANSPORT=memory) — each binary runs an isolated in-process event bus, so asettings.updatedevent published by admin-api never reaches cmd/api. The TTL (below) is the only invalidation mechanism in this mode. - Production cluster (N replicas with
TRANSPORT=kafka/nats/redis) — every replica subscribes with a uniquesettings-invalidator-{hostname}-{8-char-uuid}GroupID, so events fan out to all replicas in milliseconds. The TTL acts as a safety net for missed events (consumer restart mid-event, network blip, hostname collision).
Cache rules
| Resolution source | Cached? | Invalidated by |
|---|---|---|
db — admin-edited row in MongoDB | Yes, with TTL | local Service.Set, settings.updated event, TTL expiry |
env — environment variable | Yes, with TTL | TTL expiry (env doesn't change at runtime) |
default — YAML-declared default | Never cached | n/a — re-resolved on every miss |
Why defaults are not cached: a default returned before any DB row exists would shadow a future admin write whose invalidation event a peer binary failed to receive. Skipping the cache for defaults guarantees the next read after a peer save sees the new DB value immediately.
Save flow
- The value is written to MongoDB.
- The local cache entry is invalidated on the writing worker.
- A
settings.updatedevent is published to the event bus. - Every worker subscribed with a unique GroupID receives the event (fan-out, not round-robin) and invalidates its local cache entry.
- On next read, the cache miss triggers a MongoDB re-query.
Cache TTL
| Variable | Default | Notes |
|---|---|---|
SETTINGS_CACHE_TTL_SECONDS | 30 | Maximum staleness for a DB-sourced cache entry. Set to 0 to disable expiry — only safe in single-binary deployments OR a real-transport cluster where every replica has a unique hostname. |
Tuning guidance:
- Single-binary dev:
SETTINGS_CACHE_TTL_SECONDS=0is fine — local invalidation is authoritative. - Multi-binary dev (
TRANSPORT=memory, separate cmd/api + cmd/admin-api): leave at default30. Admin saves become visible to the public binary within 30 seconds even though no event crosses binaries. - Production with kafka/nats/redis: leave at default
30(or raise to300for less DB load). Events handle ~ms invalidation; the TTL is just a backstop for missed events.
Access control: public and sensitive flags
Settings default to admin-only. The public API exposes a setting only when its declared schema field opts in with public: true. Sensitive secrets opt in with sensitive: true and are masked on admin reads.
| Field flag | Public API (/settings/...) | Admin API (/admin/settings/...) |
|---|---|---|
| (none) | 404 | raw value |
public: true | resolved value (DB > ENV > default) | raw value |
sensitive: true | 404 | masked sentinel •••••••• |
public: true AND sensitive: true | rejected at startup by modval (MV054) | — |
Orphan DB rows (rows whose (module, key) is not declared in any module's SettingsDefinition) are invisible on the public API and visible verbatim on the admin API.
Mask passthrough: when an admin write submits the •••••••• sentinel as the value for a sensitive: true field, the existing stored value is preserved — admins can re-save a form without retyping every secret. Submitting any other string overwrites normally. Non-sensitive fields treat the sentinel as a literal string.
Example schema:
settings:
groups:
- id: ai-llm.openai
label: OpenAI
settings:
- key: openai_api_key
label: API key
type: string
env_var: OPENAI_API_KEY
sensitive: true # masked on admin reads, never readable on public API
- key: openai_default_model
label: Default model
type: string
public: true # readable by /settings/ai-llm/openai_default_model
Read-only public routes (core module)
Unauthenticated. Only fields declared with public: true AND sensitive: false are returned.
| Method | Path | Description |
|---|---|---|
GET | /settings/{module}/{key} | Get a public setting value (404 if not declared public: true) |
GET | /settings/{module} | List all public settings for a module (filtered to public: true) |
Admin routes (settings/admin submodule)
Require admin:access permission. Sensitive values are masked with •••••••• in responses.
| Method | Path | Description |
|---|---|---|
GET | /admin/settings/schemas | List settings schemas from all registered modules |
POST | /admin/settings/get | Bulk-get multiple settings by (module, key) pairs (masks sensitive) |
PUT | /admin/settings/{module}/{key} | Set or update a setting (mask passthrough) |
POST | /admin/settings/save | Alternative POST endpoint for save (mask passthrough) |
DELETE | /admin/settings/{module}/{key} | Delete a setting (scoped to module, 204) |
Internal (service-to-service) routes
Secret-gated, not user-authenticated: the callers are other services, which
have no user to act as. Gated on the x-api-secret header (constant-time
compare); disabled unless SETTINGS_INTERNAL_SECRET is set — an unset
secret refuses everything, so the internal API is opt-in.
| Method | Path | Description |
|---|---|---|
GET | /internal/settings/schemas | Every module's settings schema, as {settings, groups, subgroups} |
POST | /internal/settings/refresh-cache | Drop this instance's settings cache |
These are the service-to-service counterparts of the admin schemas /
refresh-cache endpoints — same effect, different caller. subgroups is always
empty: Redelay's settings IR has one level of grouping, and the key is present
only for wire compatibility with the legacy shape.
Events published
| Topic | Trigger | Payload |
|---|---|---|
settings.updated | Any save or delete | { moduleId, key, value, deleted } |
Environment variables
| Variable | Default | Description |
|---|---|---|
SETTINGS_COLLECTION | _settings | MongoDB collection name |
SETTINGS_CACHE_TTL_SECONDS | 30 | Resolution-cache staleness bound for DB-sourced values; 0 disables expiry. See Caching and propagation. |
SETTINGS_INTERNAL_SECRET | (unset) | Shared secret for the /internal/settings/* service-to-service routes. Unset disables them. |
Blank-import
import (
_ "github.com/redelay/go-framework/modules/settings" // core read-only routes
_ "github.com/redelay/go-framework/modules/settings/admin" // admin CRUD routes
_ "github.com/redelay/go-framework/modules/settings/flowdsl" // FlowDSL nodes
)
FlowDSL nodes (settings/flowdsl)
| Node | Kind | Description |
|---|---|---|
redelay/settings-get | transform | Read a setting by module + key; has NotFound output port |
redelay/settings-set | action | Write a setting value |
redelay/settings-delete | action | Remove a setting |
storage
Object storage module backed by MinIO (S3-compatible).
Implements modules.ObjectStorage — inject into other modules for file uploads and downloads.
Methods
PutObject(ctx, bucket, key string, r io.Reader, size int64) error
GetObject(ctx, bucket, key string) (io.ReadCloser, error)
DeleteObject(ctx, bucket, key string) error
PresignURL(ctx, bucket, key string, ttl time.Duration) (string, error)
Environment variables
| Variable | Default | Description |
|---|---|---|
MINIO_ENDPOINT | localhost:9000 | MinIO server endpoint |
MINIO_ACCESS_KEY | minioadmin | Access key ID |
MINIO_SECRET_KEY | minioadmin | Secret access key |
MINIO_BUCKET | redelay | Default bucket name |
MINIO_USE_SSL | false | Use TLS |
Derived image variants (v0.67.0+)
GET /media/<key>?v=<preset>&fmt=avif|webp|png serves a resized/converted
variant of an image. Without ?v the original is served exactly as before.
The URL space is closed: the app registers presets, and a request must name one plus a format that preset allows — anything else is a 400 and nothing is encoded or stored, so guessing parameters cannot make the server generate derivatives nobody uses.
st.RegisterPreset(storage.Preset{
Name: "card",
Formats: []string{storage.FormatAVIF, storage.FormatWebP},
Prepare: storage.FitWidth(480), // FitWidth / FitHeight / Scale never enlarge
})
// A preset can read named query args (part of the cache key) and refuse ones
// that do not apply with storage.ErrBadPresetArgs → 400:
// Args: []string{"view"}, Prepare: func(ctx, key, src, args) (image.Image, error) {…}
url, _ := st.DerivedURL(ctx, key, "card", storage.FormatAVIF, nil)
// → /media/<key>?fmt=avif&h=<source etag>&v=card
- Cache. The first request generates the variant and stores it under
_derived/<sha256(key, source ETag, preset, preset version, args, format)>; later requests serve the stored object. Replacing an original under the same key changes its ETag, so a stale variant is never served. BumpPreset.VersionwhenPreparechanges its output. - CDN. Only a URL whose
&h=matches the source's current ETag (whatDerivedURLbuilds) is servedpublic, max-age=31536000, immutable; an unversioned URL getsmax-age=86400. The format is in the URL, never negotiated fromAccept, so there is noVary. - Bounds. One encode per variant at a time (singleflight); at most
MEDIA_DERIVE_CONCURRENCYencodes per process — when all are busy the original is served (Cache-Control: no-store,X-Derived: original) rather than queueing. Source size (MEDIA_DERIVE_MAX_BYTES) and pixel count (MEDIA_DERIVE_MAX_PIXELS, read from the header before decoding) are capped. - Encoders. PNG in-process; WebP and AVIF through the native
cwebpandavifencbinaries (Alpine:libwebp-tools,libavif-apps), each run killed afterMEDIA_DERIVE_TIMEOUT_SECONDS; argv carries only constants and temp paths. A missing binary logs one startup warning and that format serves the original — never a 500. Do not swap in a wasm-in-Go encoder: compiling one was measured at ~94 GB RSS. - Derived objects take the original's ACL, are hidden from the admin media listing, and cannot themselves be derived.
- Fetch + encode + store share one deadline (2 ×
MEDIA_DERIVE_TIMEOUT_SECONDS- 30 s), so a hung storage call cannot hold an encode slot for good.
- JPEG EXIF orientation is not applied to preset variants. A photo stored
rotated with an orientation tag comes out rotated in its variants, while
browsers show the original upright. Normalise orientation at upload, or in
the preset's
Prepare, for user photos. (Path-style thumbnails below do apply it.) - The runtime image must contain
cwebp/avifencfor those formats (a distroless/static image has neither — add them in a build stage, or offer PNG only).
| Variable | Default | Description |
|---|---|---|
MEDIA_DERIVE_CONCURRENCY | 2 | Encodes at once per process |
MEDIA_DERIVE_MAX_BYTES | 33554432 | Largest source a variant is made from |
MEDIA_DERIVE_MAX_PIXELS | 40000000 | Largest source image (w × h) |
MEDIA_DERIVE_TIMEOUT_SECONDS | 30 | Per-encode limit |
Measured on 1.6–2.2 MB PNG sheets: decode + crop + scale 40–50 ms / ~18 MB, avifenc 0.08–0.14 s / ~20 MB, cwebp ~0.05 s / ~14 MB (M3 Max; expect 2–3× on older server cores).
Path-style thumbnails (v0.73.0+)
GET /thumb/<width>/<media key> serves a WebP thumbnail of a /media image
under a plain static-looking URL — no query string, one canonical URL per
(width, key) — for list and grid images that a CDN and the browser cache as
files. Opt-in: the route is mounted next to /media (top level, outside
ROUTE_PREFIX) only when at least one width is registered, so an app that
registers none keeps exactly its old routes.
// In a module's Configure (before the HTTP server is built — /thumb is
// mounted only if a width exists by then), or MEDIA_THUMB_SIZES=160,240,480,720:
st := registry.Get("storage").(*storage.Module)
if err := st.RegisterThumbSizes(160, 240, 480, 720); err != nil {
return err
}
url := st.ThumbURL(ctx, ex.ImageKey, 240)
// → https://gymmer.com/thumb/240/exercises/sq/squat-a1b2c3d4.jpg
// (the live public_url / MEDIA_PUBLIC_URL origin, as for /media; relative
// /thumb/240/<key> when unset; an unregistered width returns the /media URL)
- Closed URL space.
<width>must be a registered width spelled exactly as registered (160, never0160/+160) — anything else is a 400 and nothing is encoded or stored. Keys with./../ empty segments are a 400; empty keys, keys under_derived/, missing objects and non-images (by Content-Type, or extension when the type is generic) are a 404. - Output. Always
image/webp,<width>px wide as displayed, aspect kept, never upscaled: an original narrower than the width is re-encoded as WebP at its own width. Only JPEG and PNG originals are decoded; other images (WebP, AVIF, GIF, SVG) are served as they are withX-Derived: original. JPEG EXIF orientation is applied (scaled first, then turned), so a phone photo stored sideways comes out upright. - Cache. Same machinery as preset variants: generated once (singleflight +
the
MEDIA_DERIVE_*slots and limits), stored under_derived/<sha256(key, source ETag, width, thumb version)>.webpwith the original's ACL. Replacing an original under the same key makes a new thumb (and a new ETag); the old one is never served. - Headers.
Cache-Control: public, max-age=2592000, stale-while-revalidate=86400— long but notimmutable, because the URL stays the same when an original is replaced.ETagis the thumb's cache-key hash, identical whether it was just generated or read from the store;If-None-Match→304after a single stat of the original. - Failure. Slots busy, no
cwebp, source over the limits, or a failed decode/encode: the original is served withCache-Control: no-storeandX-Derived: original(no ETag) — never a 500.
| Variable | Default | Description |
|---|---|---|
MEDIA_THUMB_SIZES | — | Comma-separated widths in px; empty = no /thumb route. A malformed value fails the boot |
notifications
Real-time notifications via Server-Sent Events with MongoDB persistence.
Clients subscribe to GET /notifications/stream (under ROUTE_PREFIX, so
/api/v1/notifications/stream by default) and receive events in real time.
The module consumes notification.created events from the event bus and fans them out to
all connected clients for that user.
Routes
| Method | Path | Description |
|---|---|---|
GET | /notifications/stream | SSE stream for authenticated user |
GET | /notifications/ | List notifications (paginated) |
POST | /notifications/{id}/read | Mark notification as read |
Environment variables
| Variable | Default | Description |
|---|---|---|
NOTIFICATIONS_COLLECTION | notifications | MongoDB collection name |
Event schema (notification.created)
{
"user_id": "string",
"type": "string",
"title": "string",
"body": "string",
"data": {}
}
verification
Single-use token-based email verification.
Issues verification tokens, stores them in MongoDB, and optionally emits email.send events
(consumed by go-module-email) when a verification request is made via the HTTP API.
Routes
| Method | Path | Description |
|---|---|---|
POST | /verification/request | Create token and emit verification email |
POST | /verification/verify | Consume token and return verification result |
Store API (for other modules)
The verification module exposes its Store directly so other modules can manage the token
lifecycle themselves without going through the HTTP routes. Discover it via Configure():
func (m *MyModule) Configure(registry *modules.Registry) error {
for _, mod := range registry.All() {
if vm, ok := mod.(*verification.Module); ok {
m.verifyStore = vm.Store
}
}
return nil
}
// Create a token (returns *verification.VerificationToken):
vt, err := m.verifyStore.Create(ctx, email, verification.KindEmail, 32)
// Consume a token (returns nil if invalid/expired):
vt, err := m.verifyStore.Consume(ctx, token)
Environment variables
| Variable | Default | Description |
|---|---|---|
VERIFICATION_COLLECTION | verification_tokens | MongoDB collection name |
VERIFICATION_TOKEN_TTL_MINUTES | 30 | Token expiry in minutes |
VERIFICATION_TOKEN_BYTES | 32 | Random bytes for token generation |
channels
Multi-brand resolution. Middleware resolves each request's channel (brand):
the Rdl-Channel header (a channel code) wins; otherwise the request Host is
matched against active channels' domains; otherwise the default —
CHANNELS_DEFAULT_CODE if that row exists, else the active row flagged
is_default, else one synthesised from the app's config. Downstream code reads
it with channels.ChannelFromContext(ctx).
Resolution never reads the database per request (v0.72.1+). All channels
are loaded once into an in-memory snapshot (one cursor, on the primary) and
every lookup — known Host, unknown Host, code, default — is answered from
memory. Writes through the admin (Upsert/Delete) and InvalidateAll drop
the snapshot on every replica; each reloads on its next request. A failed load
serves the synthesised default and retries after 3 s.
Before v0.72.1 a Host that was no channel's domain (an API host such as
api-na.example.com, a probe's IP, any made-up Host) cost two uncached primary
reads per request — ~250 ms from a region far from the primary, invisible to the
metrics histogram because channels runs before metrics. Upgrade any
multi-region deployment.
blog
Public blog surface for any Redelay site. Posts are content pages of
type blog — written in the admin, by the editorial desk (including its
adapt step, which rewrites one story per brand) or by agents. This module
only reads them; content's Active flag stays the one visibility gate,
so drafts can never leak through it. Scope and locale come from
content.ResolveScope (the app's registered resolver), so one backend
serves every channel's blog — the site's proxy pins the channel with
Rdl-Channel.
Routes
| Method | Path | Description |
|---|---|---|
GET | /blog/posts?page=&limit=&tag=&topic=&facet=key:value | BlogPostList — newest first; every criterion ANDs (facet repeatable); tag/topic case-insensitive; items carry topic, facets, refs, reading_minutes; limit clamped; a malformed facet is 400 |
GET | /blog/posts/{slug} | BlogPost — body, SEO, reading_minutes, topic/facets/refs, up to 3 related (shared tag first). Non-blog pages 404 |
GET | /blog/facets | {topics: {name: count}, facets: {key: {value: count}}} over published posts — show only filter options that return something (v0.69.0) |
GET | /blog/tags | {items: [{tag, count}]} most-used first |
GET | /blog/feed.xml | RSS 2.0; links built from X-Forwarded-Host/-Proto, so every site's feed points at itself |
Requires the content module (503 without it). Blank-import
github.com/redelay/go-modules/blog.
Article metadata (go-modules v0.69.0) {#blog-metadata}
Every content page can carry three generic fields; the blog lists, filters and
counts them. The vocabulary is the app's, not the module's — a fitness app
has topics like training and a goals facet, a shop blog guides and a
category facet:
| Field | Shape | Meaning |
|---|---|---|
topic | slug | one category per article |
facets | {key: [slug, …]} | multi-valued labels; the first value is the primary one (order is kept). A facet filter matches a value in any position |
refs | {key: id} | links to app entities by id, e.g. {"program": "<id>"} (1–128 printable chars) |
Set the vocabulary with CONTENT_TAXONOMY (JSON) on the service that writes
pages (the admin-api):
{"topics": ["training", "nutrition"],
"facets": {"goals": ["build-muscle", "lose-fat"], "level": []},
"refs": ["program"]}
Writes (POST /admin/content/pages) are normalized (trimmed, lower-cased,
facet values de-duplicated keeping the first) and validated: a topic,
facet key or value, or ref key the taxonomy doesn't list is a 400, so a
typo never becomes a post that silently matches no filter. An empty facet
list ("level": []) allows any slug. Unset, every value only has to be a
slug ([a-z0-9-]). A malformed CONTENT_TAXONOMY stops the service at
boot. An editor that predates these fields does not blank them on save
(KeepUnsent).
Body embeds stay pass-through. Content stores page HTML as written
(behind the review gate); the site sanitizes it when rendering, exactly as it
already does for figure[data-chart]. A site that renders custom embeds
(figure[data-workout], aside[data-takeaways]…) owns an allowlist of the
data-* it understands, validates their JSON, and drops the rest.
Slugs: a page is unique on (scope, slug) with every locale in one
document, so an article has one slug for all languages of a channel.
Environment variables
| Variable | Default | Description |
|---|---|---|
BLOG_PAGE_SIZE | 12 | Default listing page size |
BLOG_MAX_PAGE_SIZE | 50 | Upper bound for limit |
BLOG_FEED_SIZE | 20 | Posts in the RSS feed |
BLOG_WORDS_PER_MINUTE | 220 | Reading-time basis |
links
URL shortener with click tracking.
Short links are stored in MongoDB. The redirect handler is mounted at /{code} (outside the API prefix) via MountProvider.
Routes
| Method | Path | Description |
|---|---|---|
POST | /links/ | Create a short link |
GET | /links/ | List short links (last 100) |
DELETE | /links/{code} | Delete a short link |
GET | /{code} | Redirect to target URL |
Environment variables
| Variable | Default | Description |
|---|---|---|
LINKS_COLLECTION | short_links | MongoDB collection name |
LINKS_CODE_LENGTH | 6 | Generated code length in bytes |
LINKS_BASE_URL | `` | Base URL prepended to short codes |
metrics
Prometheus-compatible metrics endpoint and HTTP request duration middleware.
Mounts /metrics (configurable) via MountProvider and wraps all routes with a
http_request_duration_seconds histogram labeled by method, path, and status code.
Environment variables
| Variable | Default | Description |
|---|---|---|
METRICS_PATH | /metrics | HTTP path for the metrics endpoint |
Exposed metrics
| Metric | Type | Labels |
|---|---|---|
http_request_duration_seconds | Histogram | method, path, status |
turnstile_decisions_total | Counter | route, outcome — only once metrics.TurnstileDecision is registered as a Turnstile observer. route is the matched pattern (≥ v0.83.1). A tokenless request that explains itself in X-Turnstile-Client is counted as client_unavailable / _timeout / _error / _superseded / _other rather than missing_token (≥ v0.84.2); a request carrying a token is decided by the token and the header ignored |
metrics.TurnstileDecision is an observer for go-framework's Turnstile guard
(turnstilemod.AddObserver(metrics.TurnstileDecision)). route is the matched
configured pattern (Event.Pattern, v0.83.1+), never the raw path, so a
wildcard pattern stays one series. outcome uses the guard's outcome names
(allowed, missing_token, invalid, expired, misconfigured,
unavailable, failed_open), not the HTTP error codes. See
Turnstile.
metrics/admin — database observability (admin-api only)
The metrics/admin submodule adds GET /admin/metrics/database (under the
admin prefix, admin:access), returning a live summary of ClickHouse, MongoDB,
and Redis activity. Import it from the admin-api binary only.
Every figure is read from the database's own statistics — Redelay does not instrument queries app-side — so a field is populated only where the backend natively reports it:
| Backend | Source | Real | Not available |
|---|---|---|---|
| ClickHouse | system.query_log | total, avg/max ms, error rate, slow %, top query kinds | — |
| Redis | INFO commandstats / stats | total ops, avg ms, top commands | max, error rate, slow % |
| MongoDB | serverStatus | total ops, ops/min | avg/max ms, error rate, slow % (need the profiler) |
A nil backend yields a zero-valued section rather than an error, so the endpoint works on a deployment running only some of the three.
systemhealth
Admin System → Health and the dashboard health card (js-admin ≥ v0.7.13, module
system-health). The backend reads the Prometheus you already run through a fixed
catalogue of queries — the browser asks for checks and trends by name and never sends
PromQL. Admin-api only, permission admin:access.
import _ "github.com/redelay/go-modules/systemhealth" // cmd/admin-api
Routes
| Method | Path | Returns |
|---|---|---|
| GET | /admin/system/health/ | Report: overall status, groups of checks (value, unit, items, threshold, help, link), firing alerts, pending count, available trends |
| GET | /admin/system/health/?summary=1 | Dashboard form: per group, the checks that are not ok with value · worst item · threshold |
| GET | /admin/system/health/series/{name}?hours=24 | A trend (≤ 168 h, ~120 points), one line per legend value |
Reports are cached for SYSTEMHEALTH_CACHE_SECONDS (15). A report where Prometheus is
unreachable is returned but never cached.
Presets — scoped by env
A shared Prometheus scrapes many projects. Each preset reads only its own scope, and a preset whose scope is unset contributes nothing rather than a page of "No data".
| Preset | Scope env | Checks | Trends |
|---|---|---|---|
app | SYSTEMHEALTH_APP_JOB | targets up (every job in SYSTEMHEALTH_JOBS), requests, p95, 5xx share per service | api_requests, api_p95 |
sites | SYSTEMHEALTH_PROJECT (blackbox project label) | probe success and duration per site | sites_time |
scheduler | SYSTEMHEALTH_APP_JOB | engine alive, schedules failing, schedules running | — |
containers | SYSTEMHEALTH_SERVICES (swarm service regex) | containers started in 1 h (crash loop), memory, CPU | service_cpu, service_memory |
nodes | SYSTEMHEALTH_NODES (nodename regex; empty = all) | CPU, load per core, memory, free disk | cpu, memory |
mongodb / redis | SYSTEMHEALTH_JOBS | exporter up (+ Redis memory) | — |
SYSTEMHEALTH_PRESETS defaults to app,sites,scheduler,containers,nodes.
SYSTEMHEALTH_PROMETHEUS_URL defaults to http://monitoring_prometheus:9090 (the
admin-api must share the monitoring network).
Alerts shown are those whose project label is SYSTEMHEALTH_PROJECT, else whose
job matches SYSTEMHEALTH_JOBS, plus node-level alerts (neither label). Another
project's alerts on the same Prometheus never appear.
The scheduler preset needs SCHEDULER_METRICS=true on the engine process; the
containers preset needs cAdvisor ≥ v0.52 on Docker 29 nodes (older cAdvisor speaks Docker
API 1.41, which Docker 29 refuses — it then reports no containers at all, silently).
Project checks
func init() {
systemhealth.RegisterGroups(systemhealth.Group{ID: "media", Name: "Media", Icon: "i-lucide-image", Order: 35})
systemhealth.RegisterChecks(systemhealth.Check{
ID: "mediagen_queue", Group: "media", Name: "Mediagen queue",
Query: `sum(mediagen_queued{job="shop"})`,
Rule: systemhealth.Rule{Warn: 10, Crit: 50}, Empty: systemhealth.StatusUnknown,
Help: "Jobs waiting for the GPU box", Link: "/marketing/mediagen",
})
systemhealth.RegisterTrend("mediagen", systemhealth.Trend{Title: "Mediagen jobs", Unit: "/h",
Query: `sum(rate(mediagen_jobs_total{job="shop"}[30m])) * 3600`, Order: 35})
}
Rule is Bool (1 = ok), thresholds (Warn/Crit, Lower: true when lower is worse)
or Info (a statistic). Item splits a vector into labelled rows ("{service}").
Empty is the status when the query returns nothing — ok for "list of failures"
queries, unknown for metrics that must exist — and EmptyText says what nothing means.
The catalogue is built at Startup; an unknown group, a duplicate id or an unknown preset
fails startup instead of serving half a page.
System → Events (v0.62.0)
GET /admin/system/events — js-admin system-events (≥ v0.7.15). Kafka topic rates
over the last hour against the same hour yesterday and a week ago, consumer lag of the
groups that still have members, and anomalies: events landing on the bare topic prefix
(a publisher could not resolve its topic), a topic gone quiet or spiking, a consumer
falling behind, handler or publish failures. The response also carries the page's chart
sections, so the page has no chart list of its own.
| Env | Meaning |
|---|---|
SYSTEMHEALTH_EVENTS_TOPIC_PREFIX | Enables the page (e.g. nameniac.events); unset → 404, nothing registered |
SYSTEMHEALTH_EVENTS_GROUPS | Consumer-group regex (default <first prefix segment>.*) |
SYSTEMHEALTH_EVENTS_RETIRED | Topics under the prefix nobody writes on purpose — kept out of the table and the "went quiet" anomalies |
Standard sections: Events (per topic, per action, failures, handler p95, lag) and,
with SYSTEMHEALTH_SERVICES, Services (CPU, memory, containers started, network).
Add your own:
systemhealth.RegisterTrend("catcher_attempts", systemhealth.Trend{Title: "Registration calls", Unit: "/s",
Query: `sum by (registrar, outcome) (rate(catcher_attempts_total[5m]))`, Legend: "{registrar} {outcome}", Hidden: true})
systemhealth.RegisterEventsSection(systemhealth.EventsSection{Title: "Drop-catch",
Charts: []systemhealth.EventsChart{{Name: "catcher_attempts", Help: "Calls by registrar and outcome."}}})
Every chart a section names must be a trend (checked at Startup). A project without
Kafka lists system-events in app.config adminModules.disabled.
Hide it from restricted sessions
The page shows your infrastructure. A project whose admin also serves restricted users
(e.g. a public demo) denies /admin/system to them server-side and lists
system-health in app.config adminModules.disabled for that admin.
failures
Since go-modules v0.84.0 (v0.84.1: review gauge seeded at startup). Admin page: js-admin ≥ v0.10.0, System → Failures.
One grouped error inbox for a deployment. Modules record what failed, dead
letters are read from <topic>.dlq, failed scheduler (and, once it implements
the interface, flowexec) runs are pulled in; every occurrence is grouped by a
fingerprint, a review every 15 minutes notifies about what is new, back,
spiking or critical, and a daily digest summarises the day. Notifications go
to the in-app bell of every active superuser — no SMS, no email.
import (
_ "github.com/redelay/go-modules/failures" // core: Record, DLQ consumer, review
_ "github.com/redelay/go-modules/failures/flowdsl" // failures/record node
_ "github.com/redelay/go-modules/failures/admin" // admin-api only: /admin/failures/*
_ "github.com/redelay/go-modules/notifications" // delivers failure.alert / failure.digest to the bell
)
Importing failures imports scheduler (like backup does): the review and
the digest are code-declared schedules.
Recording
failures.Record(ctx, failures.Failure{
Source: "whois", // fixed name — it is a metric label
Kind: failures.KindTimeout, // timeout | rate_limited | parse | validation | upstream_5xx | dlq | other
Key: domain, // optional entity key, kept on the sample only
Error: err.Error(),
Severity: failures.SeverityWarning, // info | warning | critical (default: the source's, else warning)
Topic: "whois.lookup", // optional, with Payload: makes the failure replayable
Payload: body,
})
failures.Record (package-level) uses the module of this process and is a
no-op before startup; (*failures.Module).Record / Service().Record are the
same call. Recording never blocks on I/O and never fails: occurrences go into
an in-memory buffer (FAILURES_BUFFER_SIZE) written every
FAILURES_FLUSH_INTERVAL; a full buffer drops and counts
failures_dropped_total. A failed write puts the batch back at the front of
the buffer (overflow dropped and counted); group writes are unordered, so one
bad document fails only its own group, whose occurrences are retried. An unknown kind becomes other; the source is
lower-cased and bounded.
Grouping. fingerprint = sha256(source, kind, topic, normalised error). The
normaliser lower-cases and replaces quoted values, emails, uuids, urls, ips,
domains, hex ids and numbers with placeholders, so timeout after 3012 ms for a.com and timeout after 2950 ms for b.org are one group. The key is never
part of it. Put the name of the thing that failed into the error when one
source covers many ("backup-daily: dump denied", "<flow>: <error>"), so
they stay separate groups.
A resolved group that recurs is reopened and marked regressed; a mute that has run out ends at the next occurrence (or at the next review).
Declaring a source
Any module (or app) implements failures.SourcesProvider; the module finds it
in the registry:
func (m *Module) FailureSources() []failures.Source {
return []failures.Source{{
Name: "whois",
DLQTopics: []string{"whois.lookup"}, // reviews whois.lookup.dlq
Severity: failures.SeverityWarning, // default for this source
Replayable: true, // admin may replay its samples
}}
}
Declaring is optional for Record; an undeclared source is recorded with
severity warning and its payloads are not stored (not replayable). Extra DLQ
topics without code: FAILURES_DLQ_TOPICS=whois.lookup,email.send (recorded
under source dlq, replayable). FAILURES_DLQ_DISCOVER=true adds every
module consumer's topic (EventsProvider.Consumers()); off by default because
on Kafka subscribing creates every <topic>.dlq. The event bus itself does not
expose its registrations, so runtime subscriptions (flow triggers) are not
discovered — declare them.
FlowDSL connectors: a module that ships flow nodes declares its topics the
same way, and flows record through the failures/record node.
Dead letters
At startup the module subscribes to every <topic>.dlq through
EventBus.Subscribe (any transport: kafka, nats, redis, memory) with the named
registration failures.dlq, group failures-dlq. Each dead letter becomes a
failure of kind dlq: error "<x-dlq-group>: <x-dlq-error>", attributes
group, attempts, failed_at, transport, event_id, key = the event's
entity id. The handler always acknowledges — decode or record problems
are logged, panics recovered — so a dead letter is never redelivered into
<topic>.dlq.dlq. The original envelope (event id, entity, action, actor,
headers without x-dlq-*, payload) is stored for replay.
Dead letters do not increment failures_total: go-events already counts
them as events_dead_lettered_total{topic,group}.
Failed runs
failures.FailedRunsSource — FailedRunsSince(ctx, since) ([]Failure, error)
— is implemented by anything that keeps its own record of failed runs. Every
module in the registry that implements it is asked at each review for the
look-back window (FAILURES_RUNS_LOOKBACK, 6 h); occurrences are deduplicated
by Failure.OccurrenceID (kept in failure_state, stored as soon as the
collected runs are written; a run the buffer dropped is not marked seen and
is offered again next review), so return the run id.
- scheduler (built in): failed runs from the scheduler's failures report
(source
scheduler, kindother, key = schedule id, error"<schedule>: <error>"); stalled runs (no heartbeat) as kindtimeout. - flowexec (to do, not in this repo): the interface returns
[]failures.Failure, so the implementer importsfailures. go-flowdsl cannot (go-modules already depends on go-flowdsl), and go-modules must not depend on flowexec — so the adapter is a small module in the app (or a future flowexec companion package) that reads flowexec's failed runs and returnsSource: "flowexec",Key: <flow id>,Error: "<flow name>: <error>",OccurrenceID: <run id>,At: <run start>. Registered as a module (factory +FailedRunsSince), it is picked up automatically.
Review and notifications
The failures-review schedule (FAILURES_REVIEW_CRON, every 15 min, UTC)
reviews; failures-digest (FAILURES_DIGEST_CRON, 07:00 UTC) digests. Both
are scheduler.EnsureDefault rows (an admin may retime or pause them). Without
the scheduler module in the registry each process runs them from an
in-process cron. Either way a claim in failure_state makes the review run
once per tick across replicas (5 min hold; digest 1 h).
A group notifies when it is open, not in its cooldown
(FAILURES_NOTIFY_COOLDOWN, 6 h), and one of:
| reason | when |
|---|---|
critical | a critical failure since the last review |
regressed | a resolved group seen again since the last review |
new | first seen since the last review |
spike | last hour ≥ FAILURES_SPIKE_MIN (20) and > FAILURES_SPIKE_FACTOR (5) × its hourly average over the 7 days before (or its age, if younger) |
"Since the last review" is widened by 2 minutes for clock skew between
replicas; an event the group's last notification already covered never
qualifies again, so the overlap cannot alert twice. A decision is stored on
the group as pending_alert (reason + time) before anything is published and
cleared only when the alert went out: an alert held back by the cooldown, cut
by FAILURES_NOTIFY_MAX (10 per review; critical first, then regressed,
spike, new; by count) or whose publish failed goes out at a later review.
Muting or resolving a group drops its pending alert; muted and resolved
groups never notify. Candidates are queried by condition (pending, or first
seen / regressed / critical since the last review) with no limit; spikes
come from a separate query of the 200 busiest groups of the last hour. The
spike baseline covers min(7 days, FAILURES_RETENTION_DAYS) and divides by
the hours it actually covers.
Each alert is the event failure.alert
(FailureAlertPayload: group_id, fingerprint, source, kind, severity, reason,
count, hour_count, sample_error, first/last seen). The digest is
failure.digest (FailureDigestPayload: since, until, total, top 10
groups with their 24-hour counts); a day with no failures publishes nothing.
go-modules/notifications (≥ this release) consumes both
(notifications.failure-alert / notifications.failure-digest, group
notifications-failures) and delivers a bell notification to every active
superuser (NOTIFICATIONS_FAILURE_ALERTS, default on; link
NOTIFICATIONS_FAILURE_LINK, default /system/failures/{id}). Flows react to
the same events with redelay/event-source (eventName: failure.alert).
A successful review sets failures_review_last_success_timestamp_seconds.
Only the replica that wins a review's claim sets it, so since v0.84.1
every process seeds it at Startup from the stored last review (a process
that has never seen a review exports 0) — otherwise every rollout read 0 for
up to 15 minutes. See Alerts.
Admin API (failures/admin, admin-api only, admin:access)
| Method | Path | |
|---|---|---|
| GET | /admin/failures/groups | status, source, kind, since (RFC3339), limit (50, max 200, clamps) + offset → {items, total}; newest last_seen first |
| GET | /admin/failures/groups/{id} | group with its 5 newest samples |
| POST | /admin/failures/groups/{id}/mute | {until} or {hours}; empty = until reopened |
| POST | /admin/failures/groups/{id}/resolve | recurrence reopens it as regressed |
| POST | /admin/failures/groups/{id}/reopen | |
| POST | /admin/failures/groups/{id}/replay | {limit} (≤ FAILURES_REPLAY_MAX) → {replayed, skipped}; 409 not replayable, 429 within FAILURES_REPLAY_INTERVAL |
| GET | /admin/failures/summary | open, new groups (24 h), by status / source / kind |
Replay re-publishes the stored samples (newest first) to their original topic
with header x-failures-replay: 1. A replay that publishes nothing does not
use up the interval. A dead letter keeps its event id, so with
EVENTS_DEDUPE the consumer groups that handled it the first time skip it and
only the group that failed runs again. Schemas: FailureGroupResponse,
FailureSampleResponse, FailureListResponse, FailureMuteInput,
FailureReplayInput, FailureReplayResponse, FailureSummaryResponse.
FlowDSL (failures/flowdsl, factory failures-flowdsl)
failures/record (action): reads source, kind, key, error
(or message / detail), severity from the packet, falling back to the
node settings (source defaults to flow:<workflow id>), records, and passes
the packet on through Recorded with failure_recorded. It never fails the
flow.
Storage
| Collection | Contents | Indexes |
|---|---|---|
failure_groups | one per fingerprint: source, kind, topic, severity, sample + normalised error, count, first/last seen, status (open/muted/resolved), muted_until, resolved_at, regressed_at, last_critical_at, last_notified_at/reason, pending_alert, last_replayed_at, replayable, 5 newest samples (key, error, attributes, time, replay envelope) | fingerprint unique; {status, last_seen}; last_seen |
failure_events | one per occurrence (fingerprint, source, kind, severity, key, at) — spikes and digest counts | at TTL FAILURES_RETENTION_DAYS (30; 0 = no events); {fingerprint, at} |
failure_state | review / digest claims, last run, failed-run dedupe sets | — |
Indexes are created by the migration 20261029_failures_indexes — never at
Startup. go-framework runs module migrations after the modules are built and
before any Startup, one replica at a time (withMigrationLock), so the
flusher cannot write failure_groups before the unique fingerprint index
exists. An app that starts modules some other way must keep that order, or
two replicas can insert the same fingerprint and the migration fails with
E11000. Pick FAILURES_RETENTION_DAYS before the first deploy: the TTL is
set by that migration. Changing
FAILURES_RETENTION_DAYS later does not change the existing TTL index (it
needs a collMod by an admin user).
Metrics
| Metric | |
|---|---|
failures_total{source,kind} | every recorded failure except dead letters; labels only source and kind (more than 64 sources per process export as other) |
failures_dropped_total | Record calls dropped (buffer full, or no database) |
failures_review_last_success_timestamp_seconds | last successful review |
Configuration {#failures-config}
| Variable | Default | |
|---|---|---|
FAILURES_GROUPS_COLLECTION | failure_groups | |
FAILURES_EVENTS_COLLECTION | failure_events | |
FAILURES_STATE_COLLECTION | failure_state | |
FAILURES_RETENTION_DAYS | 30 | occurrences TTL; 0 = none |
FAILURES_BUFFER_SIZE | 10000 | in-memory buffer |
FAILURES_FLUSH_INTERVAL | 2s | |
FAILURES_DLQ_TOPICS | — | extra topics whose .dlq is reviewed |
FAILURES_DLQ_DISCOVER | false | also every module consumer's topic |
FAILURES_REVIEW_CRON | */15 * * * * | UTC |
FAILURES_DIGEST_CRON | 0 7 * * * | UTC |
FAILURES_SPIKE_FACTOR | 5 | |
FAILURES_SPIKE_MIN | 20 | |
FAILURES_NOTIFY_COOLDOWN | 6h | per group |
FAILURES_NOTIFY_MAX | 10 | alerts per review |
FAILURES_RUNS_LOOKBACK | 6h | failed-run sources window |
FAILURES_REPLAY_MAX | 5 | per replay call |
FAILURES_REPLAY_INTERVAL | 1m | per group |
Alerts {#failures-alerts}
The shared Prometheus rules (redelay/infra monitoring/alert.yml, infra#67,
both warning; the project comes from the job):
| Rule | Expression |
|---|---|
failures_review_stopped | time() - max by (job) (failures_review_last_success_timestamp_seconds) > 2700 for 5m — max by (job) because only the claiming replica's gauge moves |
failures_dropped | increase(failures_dropped_total[15m]) > 0 |
Both compute nothing while the series are absent, so they cover an app only
once it runs the module. Dead letters stay on events_dead_lettered
(go-events). SMS stays with alert-sms (Prometheus criticals); the module
itself only notifies the bell.
Adopting it in an app
- Pin go-modules ≥ v0.84.1; blank-import
failureswhere the scheduler runs (the review consumer must be in the same process asnotificationswhen the app's own bus isTRANSPORT=memory),failures/adminin admin-api. - Record from the code paths that already "record and move on", or declare
a
SourcesProviderfor dead-letter topics. Keepsourcea fixed name and put the thing that failed (TLD, schedule, flow) into the error text so it survives the normaliser — e.g. Nameniac's failure feed writestld=<tld>: <error>for go-whois failures. - Set
FAILURES_RETENTION_DAYSfrom the expected volume before the first deploy. - Pin js-admin ≥ v0.10.0 for System → Failures.
security
Per-user security: an activity log, trusted devices, rate limiting, and automatic restriction of suspicious accounts.
The core module mounts under /user (relative to ROUTE_PREFIX) and records
request activity through a middleware, restricting a user once their suspicious
-activity count crosses a threshold.
Routes (core, authenticated)
| Method | Path | Description |
|---|---|---|
| GET | /user/activities | The caller's recent activity |
| GET | /user/rate-limits | The caller's current rate-limit status |
| GET | /user/security/profile | Suspicious count, restriction state, known devices |
| GET | /user/security/suspicious-activities | The caller's flagged activity |
| GET | /user/security/trusted-devices | List trusted devices |
| POST | /user/security/trusted-devices | Trust the current device |
| DELETE | /user/security/trusted-devices/{device_id} | Untrust a device |
security/admin (admin-api only)
Superuser operations under the admin prefix: per-user activity reports
(/admin/security/activities/{user_id} + summary), error/path reports, security
analytics, and enforcement — POST /admin/security/block-ip/{ip} and
POST /admin/security/restrict-user/{user_id}.
Environment variables
| Variable | Default | Description |
|---|---|---|
SECURITY_ACTIVITY_COLLECTION | user_activities | Activity log collection |
SECURITY_DEVICE_COLLECTION | trusted_devices | Trusted-device collection |
SECURITY_SUSPICIOUS_COLLECTION | suspicious_activities | Flagged-activity collection |
SECURITY_RESTRICTION_COLLECTION | security_restrictions | Active restrictions |
SECURITY_ACTIVITY_RETENTION_DAYS | 30 | Activity-log TTL |
SECURITY_RESTRICT_THRESHOLD | 10 | Suspicious events before auto-restriction |
SECURITY_USER_RATE_LIMIT | 1000 | Per-user request budget |
SECURITY_IP_RATE_LIMIT | 200 | Per-IP request budget |
eventadmin
Event-bus admin (admin-api only): browse event definitions, publish events by hand, browse the event log, and manage webhook subscriptions.
Mounts under /admin/events (admin:access). Import from the admin-api binary
only.
Routes
| Method | Path | Description |
|---|---|---|
| GET | /admin/events/definitions | Known event types — live registry + runtime-registered |
| POST | /admin/events/definition | Register a runtime event definition (?definition=<json>) |
| POST | /admin/events/publish | Publish an event → bus + log + webhook dispatch |
| GET | /admin/events/logs | Browse the event log (entity_type/action/limit filters) |
| GET | /admin/events/subscriptions | List webhook subscriptions |
| POST | /admin/events/subscription | Register a webhook (entity_type/action match; nil = any) |
Definitions are read from the live module registry at request time — after every module has registered — so the list is current without depending on module startup ordering.
audit module.Environment variables
| Variable | Default | Description |
|---|---|---|
EVENTADMIN_DEFINITION_COLLECTION | event_definitions | Runtime definitions |
EVENTADMIN_SUBSCRIPTION_COLLECTION | event_subscriptions | Webhook subscriptions |
EVENTADMIN_LOG_COLLECTION | event_logs | Event log |
EVENTADMIN_LOG_TTL_HOURS | 168 | Event-log retention (7 days) |
EVENTADMIN_WEBHOOK_TIMEOUT_SECONDS | 5 | Per-callback timeout on dispatch |
flowexec
Flow CRUD, immutable versioning, run launch, and live SSE event streaming for FlowDSL flows.
go-flowdsl/flowexec/module is the framework-side HTTP surface over
go-flowdsl/flowexec. It wires the executor, store, and
sink into your app and exposes them as REST + Server-Sent Events. Register it with a blank
import:
import (
_ "github.com/redelay/go-flowdsl/runtime" // your handlers register here
_ "github.com/redelay/go-flowdsl/flowexec/module"
)
At bootstrap it inspects deps.DB:
deps.DB | Store | Sink |
|---|---|---|
| non-nil | mongostore (indexes created automatically) | mongots time-series sink (falls back to noop on init error) |
| nil | memstore | noop |
App code registers node handlers on the engine exposed by the module:
m := modules.Registry().MustGet("flowexec").(*flowexec.Module)
m.Engine().RegisterHandler("charge_card", chargeCard)
m.Engine().RegisterKindHandler(ir.NodeKindAction, defaultAction)
Live SSE broadcaster
Between the executor and the downstream sink sits a broadcaster that tees every FlowEvent to
per-runID subscriber channels. The downstream sink still receives the canonical record.
Slow subscribers are dropped (non-blocking send) rather than backpressuring the run — the
durable event stream in the sink remains complete, subscribers see a live best-effort feed.
Routes
All routes are mounted relative to ROUTE_PREFIX.
| Method | Path | Description |
|---|---|---|
GET | /flows | List flows (cursor-paginated) |
POST | /flows | Create a flow — {name, description, labels} |
GET | /flows/{id} | Read a flow (head and published pointers) |
PATCH | /flows/{id} | Update flow metadata |
DELETE | /flows/{id} | Delete flow and all versions |
POST | /flows/{id}/versions | Save a new immutable version — {document, note, labels} |
GET | /flows/{id}/versions | List versions (newest first, documents omitted) |
GET | /flows/{id}/versions/{vid} | Read a version, full document included |
?format=spec query parameter
The version endpoints accept an optional ?format=spec query parameter. When present, the
API transparently converts between the Studio spec document format and the internal
ir.Workflow using go-flowdsl/spec.
Save a version in spec format:
curl -sX POST "$API/flows/$FLOW/versions?format=spec" \
-H 'Content-Type: application/json' \
-d @my-flow.spec.json
The request body is a spec.Document (with flowdsl, info, flows, components).
The server calls spec.ToWorkflow() and stores the resulting ir.Workflow.
Read a version in spec format:
curl -s "$API/flows/$FLOW/versions/$VID?format=spec"
The server calls spec.FromWorkflow() on the stored ir.Workflow and returns a
spec.Document in the response. This is the format the FlowDSL Studio editor expects.
Without ?format=spec, both endpoints use the raw ir.Workflow format.
| POST | /flows/{id}/publish | Flip published pointer — {versionID} |
| POST | /flows/{id}/runs | Launch run on the currently published version — {input, labels} |
| GET | /runs/{runID}/events | SSE live stream of FlowEvent payloads for a run |
POST /flows/{id}/runs resolves the published version, calls Executor.RunAsync, and returns
202 Accepted with {runID, versionID, versionHash}. If the flow has no published version
the response is 409 Conflict.
SSE stream
GET /runs/{runID}/events returns a text/event-stream that writes a : connected prelude,
then one SSE frame per FlowEvent:
event: node.started
data: {"runID":"run.abc","flowID":"flow.xyz","nodeID":"n1","timestamp":"2026-04-14T10:00:00Z",...}
Heartbeat : keep-alive lines are written every 15 seconds so intermediaries do not drop the
connection. The stream closes automatically when a run.completed or run.failed event
arrives.
Response shapes
POST /flows/{id}/runs:
{
"runID": "run.018f...",
"versionID": "v.018f...",
"versionHash": "f3e1b..."
}
Every event emitted on the SSE stream carries the same versionHash, so clients can tell at a
glance whether they are watching the same version they launched.
Usage with historical replay
The module does not serve paginated historical events — use the sink's Reader interface
(implemented by mongots) to back a replay endpoint in your own module when needed. The SSE
stream is strictly live.