Skip to main content

Writing a plugin

A plugin adds a feature to the platform without changing it: its own tables, operations, settings, permissions, background work and pages, plus its part in what the platform does, such as templates, workspaces, their sidecars and the events that happen. Plugins are compiled in and turned on and off at runtime (see Plugins for administrators).

This page describes every place a plugin hooks in. The plugins of this repository live in backend/plugins/<name>/ and frontend/src/plugins/<name>/; backend/tests/plugins_test.go has a small plugin that uses every hook.

The module​

A plugin is a module with a Plugin description. Its constructor takes the shared dependencies and the built-in services it builds on:

backend/plugins/greeting/greeting.go
package greeting

func New(d *module.Deps, p *modules.Platform) *module.Module {
return &module.Module{
Name: "greeting",
Plugin: &plugin.Info{
Title: "Greetings",
Description: "Greets people when their workspace starts.",
Requires: []string{"notification"},
},
Migrations: migrations, // fs.FS of its goose migrations
Routes: routes,
Settings: []settings.Entry{Section},
Actions: []string{"greeting.send"},
Public: module.Tells(public), // under "greeting" in /v1/meta while it is on
Handlers: []events.Handler{{On: "workspace.running", Run: greet}},
}
}

modules.Platform holds the built-in services: Users, Teams, Workers, Templates, Workspaces and Volumes. The Name is also the plugin's name: in the plugins settings section, in its job kinds and in its tables.

plugin.InfoMeaning
Title, DescriptionShown on the plugins page.
RequiresPlugins it builds on. It turns on only after them, they turn off only after it, and it runs only while they are on.
DisableRuns in the transaction that turns it off. An error, for example a conflict with something it still manages, keeps it on.

While it is off​

  • Its operations answer 404 with the code plugin_disabled. Routes registered through a.HandleFunc, outside of Huma, answer the same; use that rather than a.Mux for form posts, callbacks and the like.
  • Its jobs are not claimed, cannot be started by hand, and those queued when it turned off fail.
  • Events do not reach its handlers, and the platform skips its template fields and its contributions to workspaces.
  • Its reconcilers keep running. Whatever it manages outside the database must converge to its off state there, for example by deleting what it created.

A flow through another site​

An authorization that sends the browser to another site and back, such as an OAuth flow that connects an account, binds itself to the browser that started it: api.Flow gives the cookie to set at the start and what the flow's state keeps, and the way back checks the browser's cookie with api.Bound. Without it, a link to a flow someone started would finish in whichever browser opened it, for whoever started it.

Tables​

A plugin's migrations live in its own directory and are applied after the built-in ones, in a version table of its own, goose_<name>. They run whether the plugin is on or not, so turning it on is instant and turning it off keeps its data. Two rules hold, and idekube migrate fails when a plugin breaks them:

  • Its tables are named <name>_..., so that plugins never collide.
  • A reference from its tables to another table is ON DELETE CASCADE or ON DELETE SET NULL. The platform deletes the rows of workspaces, volumes and others outright and never waits for a plugin.

Add a block to backend/sqlc.yaml whose schema lists the server's and the built-in modules' migrations, as the other plugins' blocks do, and the plugin's own, and run make gen. Embed the migrations with Migrations: module.Migrations(migrations).

Events​

A handler acts on the events of one type. Each runs as a job of its own kind, <plugin>.on.<type>, enqueued in the transaction of the change, so it hears of a change exactly when the change commits, and again if it fails.

  • Every audit record is published, its action being the event's type: workspace.stop with the reason in its detail, template.approve, auth.login, and so on.
  • The workspace module publishes what its reconciler observes: workspace.running and workspace.failed, once per start whatever the phase does in between.

Every type is declared by the module that publishes it, in Actions (what it audits) or Events (the rest); a plugin's are named <plugin>.*. Assembly fails on a handler of a type no module declares, so a misspelt On is found at once rather than never called. The API lists the audit actions as the enum AuditAction, from which the frontend's audit filter is generated.

An event's ID names the occurrence: a handler makes what it does idempotent on it, for example with a unique constraint on the event ID in its own table. The same occurrence published again within a week reaches no handler.

Templates​

A plugin adds a top-level field to the template language with a Go type:

type field struct {
Message string `json:"message" minLength:"1" maxLength:"200"`
}

p.Templates.Extend(template.Field("greeting", "greeting", func(f field) []template.Problem {
return nil // rules the type cannot state; paths are relative to the field
}))

The field is checked against its type and the plugin's rules when a template is written, and its problems are located like any other. GET /v1/template-language describes it to editors with its JSON Schema. Templates are never checked again when they are used, so turning on a stricter plugin breaks no workspace. While the plugin is off the field is an unknown one: kept, warned about and ignored. Read it from a workspace's stored document with template.Extract[field](document, "greeting").

Workspaces​

A plugin contributes to workspaces with p.Workspaces.Contribute(...). Every hook is optional and sees the workspace as a workspace.Seen, a copy of what a plugin may know of it: its ID, team, creator, template, worker, whether it is in its creator's personal team, and its spec. Plugin names the contributing module; a name that is no module of the build is off.

p.Workspaces.Contribute(workspace.Extend(workspace.Contribution{
Plugin: "greeting",
Provision: provisioned,
}, workspace.Extension[Asked, Told]{
Key: "greeting",
Admit: admit, // func(ctx, tx, *workspace.Admission, *Asked) error
Created: created, // func(ctx, tx, workspace.Seen, *Asked) error
Output: told, // func(ctx, q, ids) (map[string]Told, error)
}))
HookRuns
ProvisionWhenever the workspace's sidecar asks for what it serves, to add to what the workspace starts with through a workspace.Provisioning: environment variables, repositories to clone, archives to unpack, git credentials. When something it reads changes, raise the affected workspaces' config_revision in the same transaction; the platform does so when the plugin turns on or off.
ManagesWhen workspaces are shown or someone asks to change one, its variables or network rules, or grow its home. It names those it changes as parts of something of its own, which the API then refuses to change alone (workspace_managed) and shows as managed. What the platform does by itself, such as stopping an idle workspace, is not refused.

An Extension is the plugin's part of a workspace under its Key: what a request may ask of it in extensions when it creates a workspace (Asked), and what the plugin tells about one there when workspaces are read (Told). Both are Go types, which the API describes as the plugin's property of WorkspaceExtensionsAsked and WorkspaceExtensions; the frontend reads them from the generated types. What is asked is checked against its type before the hooks see it.

HookRuns
AdmitWhen a workspace is created, in the creating transaction once its team is locked and before quota is checked, with what was asked, or nil. It may refuse the workspace, or set its CPU and memory on the Admission. Rows of the plugin it locks come after the team and before the workspace.
CreatedAfter the workspace's row exists, to keep what the plugin holds about it.
OutputWhen workspaces are listed or read, to tell about those it has something about.

A request that asks something of a plugin that is not on is refused.

A plugin knows nothing of how a worker is told: it imports neither the worker contract (backend/gen) nor backend/worker, which archtest checks. The platform's own modules have two more hooks, Spec and Sidecar, which add to the messages of that contract itself and change with it: a workspace's network policy and a cluster's gang are added this way.

A module that governs workspaces, as clusters do, acts on them with Workspaces.Create (with Group for workspaces placed where all of them fit), CreateLike (another as one of them is), Fits, Start, Stop, Update, Delete, SetMounts, Reapply and Reconfigure, and on their variables and network rules with the services of those modules. These are not refused for the workspaces it manages: the module authorizes the actor and locks the team first.

Provisioning steps​

A sidecar puts files in place before the template's tasks run: one step after the other, as the workspace's user, each reported among the workspace's tasks. A step is done once its directory exists and leaves nothing behind when it fails, so it is retried at the next start. A contribution adds steps in its Provision hook:

func provisioned(ctx context.Context, q db.DBTX, w workspace.Seen, p *workspace.Provisioning) error {
p.Clone("repo", "project", url, "main")
return nil
}

The UI​

A plugin's UI is a definition in frontend/src/plugins/<name>/index.ts, found by its place:

export default defineModule({
name: 'greeting',
routes: [
{
path: 'greetings',
name: 'greetings',
component: () => import('./Greetings.vue'),
meta: { menu: { group: 'main', icon: Hand } },
},
],
slots: { 'workspace.form': defineAsyncComponent(() => import('./GreetingField.vue')) },
profileTabs: [{ value: 'greetings', component: defineAsyncComponent(() => import('./Tab.vue')) }],
messages: { en, zh, fr },
})
PartAppears
routesPages inside the shell, reachable only while the plugin is on. A route's meta.permission keeps it from whoever lacks it; meta.menu lists it in the sidebar, in the main or the admin group, to whoever may open it.
barePages on their own, outside the shell, reachable without signing in; each signs its visitor in itself, as a page another site lands people on does with a ticket. Those under /lti/ may be framed by any HTTPS site.
slots.headerThe page header, beside the preferences.
slots['workspace.form']A section of the form that creates a workspace. It gets asked, what the workspace asks of the plugin under its name, typed as the plugin's part of WorkspaceExtensionsAsked, and emits update:asked with it, or undefined to ask nothing; it also gets template and team. A plugin sees and sets only its own part.
slots['workspace.detail']A section of a workspace's drawer; it gets workspace.
slots['workspace.badge']Next to a workspace's name in the list; it gets workspace.
slots.logoThe platform's mark in the sidebar and on the sign-in page, instead of the default one; it gets size, sm or lg.
paintA function from what the plugin tells the UI to how every page is painted, the sign-in page's too: CSS custom properties set on <html> in the light and the dark theme, and the tab's icon. The platform applies it once it knows the plugin is on, takes it away once it is off, and keeps it in the browser to paint the next visit before anything loads.
settingsWhere the Settings page lists its sections: group names the group of its navigation (integrations unless it says), or page names its own route that edits them, which leaves them off the Settings page. Their labels are in its messages under settings, at the paths the platform's are.
profileTabsTabs of the profile page.
messagesMerged under modules.<name>: title and description name the plugin on the plugins page, nav.<route> labels its routes and tabs.<value> its tabs. Its errors join the platform's, which turn the code of an error into words.

Load components lazily, so that a plugin costs nothing until it shows. The permissions it checks are among those the generated API types list.

A distribution of your own​

Plugins outside this repository are Go modules and frontend folders of their own. A distribution is a copy of backend/cmd/idekube/main.go whose build appends them, and a frontend build that holds their UI in src/plugins. make gen then describes their operations in the OpenAPI document the frontend's client is generated from.