Skip to main content

Extending the backend

How the pieces fit is described in Modules and composition. This page lists the steps for common changes.

Add a migration​

Every schema change ships with a SQL migration in the migrations of the module that owns the table, backend/modules/<module>/migrations/, named <version>_<slug>.sql with versions numbered sequentially after the module's 00001 baseline. The server's own tables (settings, jobs, events, the audit log) have theirs in backend/migrations/.

backend/modules/storage/migrations/00002_volume_labels.sql
-- +goose Up
ALTER TABLE volumes ADD COLUMN labels jsonb NOT NULL DEFAULT '{}';

-- +goose Down
ALTER TABLE volumes DROP COLUMN labels;

Then run make gen: sqlc reads the schema from the migrations, so the generated query code follows.

Each module's migrations are recorded in a version table of its own, goose_<module>, and run in the order of modules.Builtin, after the server's: a module references only the tables of the server and of the modules before it. Its block in sqlc.yaml lists the same migrations as its schema, so that a query of a table further up fails generation; backend/archtest checks the blocks. A new module with tables takes its place in that order, and embeds its migrations:

//go:embed migrations/*.sql
var migrations embed.FS

// in Module(): Migrations: module.Migrations(migrations),

Let the database hold the invariants: give every column a default it can have, and add constraints rather than checks in code. Tables with an updated_at column get the touch_updated_at trigger.

idekube migrate applies migrations; every API server pod runs it before serving. Concurrent runs serialize on a PostgreSQL advisory lock. During a rolling upgrade old replicas keep running against the new schema, so migrations only expand it: a step that drops, renames, retypes or newly requires a column says so on the line before with -- contract: and why, once no release that reads it runs; archtest checks it.

Add a query​

Write it in the module's queries.sql with a sqlc annotation, run make gen.sql, and call the generated method on store.New(tx):

-- name: ListLabelledVolumes :many
SELECT * FROM volumes WHERE labels ? @label::text ORDER BY created_at DESC;

Add a settings section​

  1. Declare a struct with JSON tags and a section for it, with the defaults:

    type Settings struct {
    Retention int `json:"retention_days" doc:"Records older than this are deleted."`
    }

    var Section = settings.New("reports", "Reports", func() Settings { return Settings{Retention: 30} })

    The defaults function must return a fresh value each time. Use the struct tags of the API for constraints (enum, minimum, pattern) and doc for the description operators read; tag a field without a default required:"true".

    The Settings page renders the fields in the order of the struct. Three more tags tell it how to show one simply: unit:"seconds" for a number it lets people write in a unit they pick (seconds, milliseconds, hours, days, bytes, mebibytes, millicores or percent), advanced:"true" for what few need, which stays folded, and when:"mode=failures|always" for a field that matters only while a sibling has one of these values.

  2. Add Section to the module's Settings.

  3. Read it with Section.Of(d.Settings) at the point of use, d being the module's module.Deps. Do not keep the result: the value changes at runtime. The section only declares the settings; their value lives in the store, so that nothing is shared between two platforms in one process, such as two tests. Tests change it with Section.Set(store, value).

The section then appears in GET /v1/settings and on the Settings page, which renders a form from its JSON Schema: nested structs as groups of fields, lists of small structs as rows, others as a list edited beside it, and only what no control fits as YAML. Label every field among the messages of its module (frontend/src/modules/<name>/messages, a plugin's in frontend/src/plugins/<name>/), or in frontend/src/i18n/ for a module without a UI of its own, under settings.fields.<section>.<field>, and the fields of a nested struct under settings.fields.<section>.<Type>.<field>; a hint goes under settings.hints and the words of an option under settings.options at the same path, the empty option as _. A test fails on a field without a label. The module's UI definition names the group of the page's navigation the section is listed in (settings: { group }); a section of a module without a UI is listed in GROUPS of frontend/src/pages/Settings.vue. Use settings.Secret for secrets; they are masked in responses. If the chart should derive a value, add it to deploy/helm/idekube-platform/templates/settings.yaml.

Add an environment variable to core/config only for something the process needs before it can reach the database.

Add a permission​

  1. Protect the operation with it:

    api.Register(a, api.Operation(http.MethodGet, "/v1/reports", "list_reports", "reports"),
    api.Require("report:read"), list)

    Inside a handler, r.Actor.Can("report:manage") checks a permission conditionally.

  2. Grant it in the module: Grants: map[string][]string{"admin": {"report:read"}}.

super_admin needs no grant. The frontend's Permission type is generated from the permissions the modules declare, so can('report:read') type-checks once make gen has run.

Add an operation​

Register it with api.Register(a, op, access, handler). The handler receives the request's transaction and actor and its input; inputs and outputs are Go structs whose tags generate the OpenAPI document:

func list(ctx context.Context, r *api.Request, in *struct {
api.Paging
Q string `query:"q"`
}) (*api.Body[api.Page[ReportOut]], error)

Return an apierr error for anything the client should see, e.g. apierr.NotFound("not_found", "report not found"); anything else becomes a 500 that is logged. A database constraint a client may break, such as a unique name, is declared on the module by name, Constraints: map[string]*apierr.Error{"uq_reports_team_id_name": apierr.Conflict("name_taken", "")}; breaking any other constraint is the server's fault, logged and answered with a 500. apierr.Errors.Classify tells the API, jobs and reconcilers alike what an error means: what is shown, whether trying again may help (apierr.Permanent says it cannot), and whether it is a fault to log. Name output types the way the frontend refers to them, then run make gen so the client follows.

Add a feature​

A feature is a module of its own, built on those below it, so that two features made at once change no file in common but generated ones. What it adds is in its own directories and is declared, not listed elsewhere:

WhatWhere
Tables, queries, operations, settings, permissions, jobs, eventsIts module.Module, in backend/modules/<name>/ (a plugin's in backend/plugins/<name>/).
Its part in workspacesA workspace.Contribution: what a workspace starts with (Provision), what may be asked of it and what it tells (workspace.Extend), the workspaces it changes as parts of its own, which nobody changes alone (Manages).
What people are told ofIts Notices, each about one of its own events.
What workspaces of its own exchange past the network rulesNetwork.Peers.
What a worker must do for itA feature its agents list, at a version, and what of a resource asks for it (worker/features.go); what the leading agent does on its own for it is a worker.Routine of the driver.
Pages, sections of the platform's pages, and every wordfrontend/src/modules/<name>/ (a plugin's in frontend/src/plugins/<name>/), found by its place: routes, slots and its messages, with its error codes, audit actions, settings labels, phases and notices under their keys there.
Its settings' golden formA file of its own, backend/tests/testdata/settings/<section>.json, which go test ./tests -update writes.

A new module is still named in five places, each a line: modules.Builtin (or plugins.All), its block in backend/sqlc.yaml, its place in layers of backend/archtest when it has tables, its subsystem in scripts/test/groups.json when it has tests, and the documentation's sidebar; a module without a UI of its own also names its settings sections in GROUPS of frontend/src/pages/Settings.vue. What make gen writes changes with every feature: when two branches conflict there, take either side and run it again.

What it cannot add from its own directory is a new kind of thing a worker does: a field or a frame of the contract in proto/, what the driver makes of it, and what the chart lets the agent touch. Keep such a change to the files of its own concern (workspace.proto, volume.proto, a file of its own in worker/kubernetes), and give it a feature rather than a protocol.

Add a module​

  1. Create backend/modules/<name>/ with its queries.sql, its code, and a constructor that returns a *module.Module.
  2. Add it to modules.Builtin. Order matters for Release: a module whose resources reference another's goes first.
  3. Add its migrations and a block for its queries to sqlc.yaml, as in Add a migration, run make gen, and write tests.

A feature that connects the platform to what an installation may not have, and that administrators turn on and off, is a plugin instead; see Writing a plugin.

Conventions a module follows:

  • Services take the request's transaction and never commit.
  • Write the audit record with d.Audit.Record(ctx, tx, actor, "thing.action", target, detail) (core/audit) in the same transaction as the change; it is published as an event of type thing.action too. Declare the action in the module's Actions, and give it a label under audit.actions in the frontend's messages (a plugin under audit.<verb> in its own); a test fails while one is missing.
  • Every mutation of something a team holds starts with Teams.Lock(ctx, tx, team), then reads what it changes again, locked (team.Fetch does both). If it counts against the quota, call Teams.Admit(...) under that lock, and contribute to usage through the module's Usage hook.
  • Provide a Release hook if users own the module's resources, so that deleting a user tears them down.

A resource that exists outside the database​

  1. Give the table the reconciled columns core/reconcile lists: worker_id, generation, observed_generation, reconcile_at, lease_until, claims, failures, deleted_at, phase, status_code and status_message, and the reconcile_requested trigger.
  2. Write Handle(ctx, claimed) (Outcome, error), which reads the row, makes the outside world match it and reports what it saw, and Finalize(ctx, tx, id), which removes the row once the outside resource is gone. Both must be idempotent.
  3. Add a reconcile.Reconciler{Table, Kind, Handle, Finalize, Held: workers.Registry.Held} to the module's Reconcilers, and answer for its rows to the worker module with Workers.Resource (Nudge, Diff, Version, Rows, Forget, Load), as the workspace and storage modules do.
  4. In services, change the row and call reconcile.Request(...). Never call the cluster from a request handler.

If the resource lives in a worker's cluster, make it a kind of the contract: its spec in Apply (proto/), its name in worker (KindOf), and what the Kubernetes driver makes of it. The driver's Apply and Delete stay as they are; never import a Kubernetes client in the module.

Periodic work​

Add a jobs.Kind{Name, Every, Run} to the module's Jobs; leave Every out for work that is enqueued with Deps.Jobs.Enqueue. Any replica may run it, and a crash runs it again, so it must be idempotent. See Background jobs.

Fetch from the frontend​

Make a query of an endpoint with apiQuery, which keys it by the endpoint and what it asks, and name in an action the resources it changes, which invalidates their queries:

const { data } = useQuery({
...apiQuery('/v1/reports', () => ({ params: { query: { team_id: team.value } } })),
enabled: () => !!team.value,
})
const remove = useAction((id: string) => unwrap(api.DELETE('/v1/reports/{id}', { params: { path: { id } } })), {
invalidate: ['reports'],
})

A query that is not a GET of the API, e.g. of a workspace's sidecar, is named in src/api with a key of its own; lint keeps queryKey out of pages. A list the API describes, such as phases or permissions, comes from the generated src/api/schema.ts (workspaceOutPhaseValues, permissionNameValues); do not copy it.