Design decisions
A starter is mostly decisions. These are the ones worth knowing before you change something,
numbered so code comments and reviews can refer to them. Each says what was decided and
why; when a decision changes, edit it here (and in AGENTS.md) in the same pull request.
- Explicit query scoping instead of global scopes; explicit tenancy params everywhere.
- Tenant/audit stamping in services, not model observers.
ActingGlobalimpersonation is a read-only, all-tenant view; writes need acting headers.- Bigserial sequences are synced after explicit-id seeding (
SyncIDSequence). - Subscribe validates and charges before deactivating previous subscriptions; gateway failure cancels the fresh pending subscription.
- E-mail is not changeable through user update.
order_by/order_directionare whitelisted per endpoint.- One error universe: RFC 9457 everywhere.
- OTP codes are cache-only; delivery goes through the queue (
mail.send). - Local scheduler heartbeat visibility requires a shared cache driver (memory is per-process).
- Notification fan-out counters are idempotent (
INSERT ... ON CONFLICT ... RETURNING); reads are user-scoped (never branch-scoped); mark-all-read is scoped + idempotent; unread counters recompute from the database on cache miss. Import/export job rows report real progress and an honest FAILED status; downloads require COMPLETED + file. - One
filestable with polymorphic attachments (owner_type/owner_id/collection) with a Go collection registry, single-file collections enforced by service + partial unique index; no conversions/custom-properties. The resource is/v1/fileswithfile.*permissions (legacyupload.*rows are retired by migration). - i18n catalogs cover the API-relevant message groups (
messages,http-statuses,validation; ~390 keys × en/bn); validator tags map tovalidation.*keys via go-i18n. - Legacy
.xlsimports are rejected (xlsx/csv supported); per-row import errors use a[{row, errors:{...}}]shape; filter snapshots live indata_processing_jobs. - Storage disks (
config/storage.go,platform/storage) work like Laravel’sconfig/filesystems.php: each disk has a name, a driver (local|s3) and a visibility. Built-ins areprivate,publicands3(fromS3_*);STORAGE_DISKS=r2,minioadds more fromSTORAGE_<NAME>_*.FILES_DISK/DATA_PROCESSING_DISKname any disk, so moving uploads to S3, Cloudflare R2, MinIO, Spaces or B2 is a.envchange. Private disks (local or bucket) never hand out URLs; files are read through the authorized download route, and avatars go toFILES_PUBLIC_DISK. The S3 driver supports a key prefix (ROOT), presignedTemporaryURLs, and only sends checksums when required (S3-compatible services reject the SDK default). File URLs are computed from disk + path (no storedurlsnapshot). - Contract.
api/openapi.yamlis canonical and served verbatim; oapi-codegen runs types-only (the handwritten chi chain +Responderown the HTTP layer) and its output is diff-gated in CI. Docs are served via Scalar from a CDN (config-gated withDOCS_ENABLED). - Observability.
/metricsis a small dependency-free Prometheus text exporter (internal/platform/metrics, low cardinality: method/route/status only), config-gated withMETRICS_ENABLED. A Content-Security-Policy header is deliberately omitted so the docs UI can load its CDN assets; baseline headers (nosniff, frame-deny, referrer, HSTS-over-TLS) are on. - Tenant isolation (no RLS). Postgres row-level security was evaluated and
deliberately dropped: a correct setup needs a dedicated non-owner application role, a
fail-closed policy, and the tenant GUC set on every connection (not just transactions) —
and even then it would only backstop the explicit filters below. Instead, explicit tenant
scoping is the only isolation boundary: every tenant-scoped query MUST receive and filter on
an explicit
tenant_id(andbranch_idwhen branch-scoped), and a missing filter is a security bug. Coverage is enforced by the per-module isolation tests, not by the database. - Deployment. Single binary + systemd (units:
ims-go-api,-scheduler,-worker); a build-on-serverdeploy/scripts/release.sh(no container/artifact host) that builds a static binary, runs migrations as a gated release step, atomically switches thecurrentsymlink, restarts units and health-checks. Writable state lives under/var/lib/ims/ims-go-api(never inside a release directory). Runbooks live in Operations. - Trusted proxies. Forwarded headers (
X-Forwarded-For/X-Real-IP) are honoured only when the immediate peer is listed inHTTP_TRUSTED_PROXIES, and the client IP is resolved right-to-left skipping trusted hops (an explicit, reviewable policy rather than chi’s defaultmiddleware.RealIP). The resolved IP drives login throttling, rate limiting and access logs. - Generators.
ims gen module --fields="name:string,price:decimal,…"scaffolds a goose migration, sqlc queries and a full module package, non-interactive and CI-friendly, then runssqlc generateso the output compiles. Generated modules use explicittenant_idscoping,httpx.Kithandlers and route-level permissions (r.With(h.can(...))); the generated service test needs no database. - SQLite deferred. v1 is PostgreSQL-only. SQLite was scoped and
deliberately deferred to a future version: with sqlc it needs a second, permanently-duplicated
repository set (per-module), and an ORM-style alternative would mean rewriting the whole data
layer and giving up compile-time SQL + explicit tenant scoping.
DATABASE_DRIVER=sqliteis rejected at startup; the schema/queries remain Postgres-only. - Authorization at the HTTP edge. Permissions are declared on routes
(
r.With(h.can(perm))→authz.Require), mirroring Laravel’scan:middleware; a handler callsMustCanitself only when the permission depends on the payload. CLI commands, queue jobs and scheduled tasks are trusted callers and do not re-check permissions. Services remain permission-free unless they need a Gate-style decision, in which case they take*authz.Checkerexplicitly. Services and SQL always enforce tenant scoping and business invariants (Super-Admin protection, no self-escalation) regardless of caller. A route-coverage integration test asserts every protected route returns 403 to a token without permissions, so a forgotten handler check fails CI. - Laravel-style handlers. Handlers embed
httpx.Kit(Bind,Validate,PathIDand the responder methods) and readauthn.UserID(r)/tenancy.From(r); config is split one file per section likeconfig/*.php; CLI commands share onewithPlatformhelper. - Feature-flag rollout. An enabled flag can carry a percentage; subjects hash to a stable bucket per flag, so raising the percentage only adds users (see §6).
- Quotas under advisory locks.
users.max/branches.maxcount-check-insert runs under a per-tenant Postgres advisory lock (TxManager.WithTenantLock), so concurrent creates cannot exceed a plan limit. The plan limit is read before the lock (Guard.QuotaFor) and every query inside it runs on the locked transaction, so lock holders never wait for a second pool connection (TestQuotaUnderConcurrencyruns 8 creates on a 3-connection pool). - Dashboard audit. Every dashboard mutation and dashboard sign-in (including failures, never
the password) is written to
dev_actionswith IP and browser, kept forDEV_DASHBOARD_AUDIT_RETENTION_DAYS. - Inactive tenants.
tenants.is_activeis stored and shown but not yet enforced at request time. - One version, one file.
VERSION(semver, nov) is the single source of truth. Release builds stamp it with-ldflags; every other build reports<version>-dev, so a local binary is never mistaken for a release. See Releases. - Docs live in the repository.
docs/is plain Markdown that reads on GitHub;website/is only the site shell (Astro Starlight) that renders it, so code and docs change in the same pull request. Reference pages (CLI, configuration, permissions, Make targets) are generated from the code byims gen docsand checked bymake gen-check, like sqlc and OpenAPI output.