Skip to content

Extension Development ​

An extension is an optional part of the platform shipped as its own Python package. It brings API routes, the permission actions that guard them, their audit decisions and vocabulary, its own settings and database tables, lifecycle hooks, access for container steps and web pages. A platform admin enables or disables an installed extension platform-wide, with no restart.

Plugins and extensions differ in what they add:

PluginExtension
Addsa type to an existing registry (a step handler, a secret backend, an inventory provider)a whole feature: routes, permissions, audit decisions, setup code
Switchedby installing the wheelby installing the package, then a platform admin enables it
Entry-point groupone per subsystem (hegemony.step_handlers, …)hegemony.extensions

This page covers contract 1. An extension ships no front-end code: it describes its pages and sidebar entries as data, and the web app draws them (see Pages and menu). What admins see is in Extensions.

Writing an extension ​

The package declares one entry point in the hegemony.extensions group. The entry-point name is the extension's id. It points at a register function:

toml
[project.entry-points."hegemony.extensions"]
demo = "hegemony_demo:register"
python
from packages.core.extensions import Extension, ExtensionContext, ExtensionRegistry


def _routers():
    from .routes import router  # heavy imports stay inside the callable

    return [router]


async def _on_enable(context: ExtensionContext) -> None:
    context.logger.info("demo enabled")


def register(registry: ExtensionRegistry) -> None:
    registry.register_extension(
        Extension(
            id="demo",
            name="Demo",
            description="Shows how an extension plugs in.",
            routers=_routers,
            actions={
                "demo:view": {"policy": "viewer", "description": "See demo items."},
                "demo:manage": {"policy": "admin", "description": "Add demo items."},
            },
            routes={
                "demo:view": ["GET /demo/items"],
                "demo:manage": ["POST /demo/items"],
            },
            audit_coverage={
                "audited": [
                    {
                        "route": "POST /demo/items",
                        "resource_type": "...",
                        "actions": ["create"],
                        "snapshot": "after",
                    }
                ]
            },
            on_enable=_on_enable,
        )
    )

The fields:

  • id: 2 to 40 lowercase letters, digits and single dashes, starting with a letter. It must equal the entry-point name.
  • name, description: shown to platform admins.
  • contract: the contract version the extension was written for. Leave the default.
  • routers: a callable that returns FastAPI APIRouter objects. It is called once, after the platform's own routers are mounted.
  • actions, routes: permission actions and the routes they guard, in the shape of apps/api/auth/actions.yaml and routes.yaml. See RBAC for the policies.
  • audit_coverage: the audit decision for each mutating route, in the shape of apps/api/audit_coverage.yaml. See Audit Logging.
  • audit_resource_types, audit_namespaces: the audit resource types and event-type namespaces of its own. See Audit vocabulary.
  • migrations: the directory of its Alembic revisions, for tables of its own. See Tables of its own.
  • on_enable, on_disable, startup, shutdown: async hooks that take an ExtensionContext: the id, the platform settings, the extension's own settings and a logger.
  • org_prefixes: path prefixes the extension owns whose routes are organization-scoped. See Organization routes.
  • settings: the extension's own settings class. See Settings.
  • step_access, revoke_step_access: what container steps get from the extension. See Step access.
  • pages, menu: the extension's web pages and sidebar entries, as data. See Pages and menu.

The entry-point module must not import apps.api at module level. The platform loads it while it builds its permission registry, and that import would be circular. Put heavy imports inside routers and the hooks.

What the platform checks ​

An extension that does not fit is refused. It is not loaded, its routes are not mounted, and a platform admin sees the reason. The other extensions still load, and the platform still starts. An extension is refused when:

  • its id is malformed, or two installed packages claim the same id;
  • it was written for another contract version;
  • its register function raises, or registers nothing;
  • a field has the wrong type (a name that is not text, a hook that is not callable, actions or routes that are not mappings of the shapes above);
  • one of its action keys is already taken, or one of its routes names an action it did not declare, or the merged permission registry does not build;
  • one of its organization prefixes does not fit (see Organization routes);
  • one of its declared routes outside its own organization prefixes can resolve under an organization-scoped prefix (/devices, /flows, …, or another extension's). A leading placeholder counts: /{scope}/settings can resolve to /devices/settings, so start every route with a fixed segment of your own, such as /demo/…;
  • its settings do not validate (the reason names the fields, never the values given; pydantic's own messages, such as a bound, are shown, a validator's own message is not, since it may quote the value);
  • it declares only one of step_access and revoke_step_access;
  • its audit vocabulary does not fit (see Audit vocabulary), or another extension, earlier by id, declares the same name;
  • its migrations is not a directory path, or the directory does not exist;
  • one of its jobs does not fit (see Background jobs);
  • one of its declared routes uses a path converter that spans segments, such as {name:path}. The permission check reads every placeholder as one segment; str, int, float and uuid are fine;
  • one of its declared routes overlaps, for the same method, a route the platform or an earlier extension already declares, or one of its own routes under another of its actions. GET /demo/{id} overlaps GET /demo/items, because one path matches both. Overlaps under one action share its policy and are allowed;
  • its audit decisions do not parse, or name a route that is already classified;
  • its routers callable raises, returns something other than FastAPI APIRouter objects, or a router holds a route that is not an HTTP route;
  • a router has its own lifespan or startup/shutdown handlers, directly or through a router it includes. FastAPI merges those into the application's own lifespan, where they would run even while the extension is disabled; use the extension's startup and shutdown hooks instead. Routers composed of plain routers (parent.include_router(child)) are fine;
  • one of its routes is guarded by a platform action instead of its own, or a mutating route (POST, PUT, PATCH, DELETE) has no audit decision;
  • one of its pages or menu entries does not fit: see What the platform checks in pages.

The overlap check keeps an extension from weakening a platform route: a more specific rule would win the permission lookup while the platform's handler, mounted first, still served the request. The last two checks run on the actual routes, so an extension cannot shadow a platform route either.

At its start, the API also refuses an extension with tables of its own whose revisions do not load, have more than one head, or are not all applied yet. See Tables of its own.

Organization routes ​

A route is organization-scoped or platform-scoped, which decides what its policy means. Under an organization-scoped prefix (/devices, /secrets, …) a request needs an active organization (the X-Org-Id header the web app sends), and a role policy such as admin means the caller's membership role in that organization: an organization admin satisfies it. Everywhere else the same policy means the platform-wide role.

An extension's routes are platform-scoped unless it owns an organization prefix:

python
Extension(
    ...,
    org_prefixes=["/demo-items"],
    routes={
        "demo:view": ["GET /demo-items", "GET /demo-items/{item_id}"],
        "demo:manage": ["DELETE /demo-items/{item_id}", "GET /demo/settings"],
    },
)

Here /demo-items… is organization-scoped and /demo/settings stays platform-scoped. Keep each organization's data apart in the routes under the prefix: the platform resolves the organization, the extension's handlers must filter by it.

A prefix is fixed path segments of lowercase letters, digits and single dashes. The extension is refused when one of its prefixes:

  • lies in, or contains, a prefix the platform keeps for itself (/settings, /internal, /auth, /orgs, /platform, …), an organization prefix of the platform (/devices, /inventory/objects, …) or one an earlier extension owns;
  • covers a route the platform or an earlier extension already declares, which would change that route's scope;
  • holds a route whose action is public, internal or custom: those routes have no signed-in user to resolve an organization for (worker callbacks and webhooks belong under a platform-scoped path).

Settings ​

An extension reads its own configuration from the environment through its own settings class, typically a pydantic-settings BaseSettings with its own prefix:

python
from pydantic_settings import BaseSettings, SettingsConfigDict


class DemoSettings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="HEGEMONY_DEMO_")

    api_url: str = "http://demo:8080"
    retries: int = 3


Extension(..., settings=DemoSettings)

The platform builds it once, when it discovers the extension, and hands the instance to every hook as context.extension_settings. Settings that do not validate refuse the extension; the reason names each field and what is wrong with it, never the value given, since the reason is shown to platform admins.

Step access ​

A container step (container.run, ansible.playbook, tf.plan, …) can get access an extension provides:

  • a login for a container registry, written into the step's Docker configuration;
  • an image cache: a registry that keeps copies of the images the step pulls (the step SDK's ImageCache);
  • for a step that builds an image, a build target: where the image goes (the step SDK's ImageBuild).

Before such a step runs, the worker asks the API once (POST /internal/runs/{run_id}/step-access). The API asks every enabled extension that declares step_access, in id order, and hands the worker what they grant. When the step ends, the worker hands each grant's handle back and the API calls the extension's revoke_step_access, even when the extension was disabled meanwhile. No extension code runs in the worker.

python
from packages.core.extensions import (
    ImageCacheAccess,
    RegistryLogin,
    StepAccess,
    StepAccessRefused,
)


async def step_access(context, db, request):
    if not request.org_slug:
        raise StepAccessRefused("the run has no organization")
    token = await issue_token(db, request.run_id, ttl=request.ttl_seconds)
    return StepAccess(
        handle=token.id,
        logins=[RegistryLogin("mirror.example", "step", token.secret)],
        image_cache=ImageCacheAccess(
            registry="mirror.example",
            api_url="http://mirror:5000",
            namespace=f"orgs/{request.org_slug}",
        ),
    )


async def revoke_step_access(context, db, run_id, handle):
    await revoke_token(db, handle)
  • request says which run and step ask, the run's organization, how long the access should last (ttl_seconds, at most the step's timeout plus a margin) and whether the step builds an image.
  • db is an open database session. The API commits what the hook did once it answers, and rolls it back when it raises. Until then the run's row is locked, so the run cannot end while the hook grants: a run that has ended is refused before the hook is asked. The session is scoped to the run's organization, as in an organization's request, and so is the session revoke_step_access gets.
  • Each hook has 10 seconds, and all of them together 20 seconds, so the answer reaches the worker within its 30-second wait. A hook that runs out of time is cancelled, its work is rolled back and its lock released, and it is reported as a problem. An extension the time no longer covers is not asked, and is reported too. Make the hook safe to cancel: create anything outside the database (a token at a remote service, say) last, with a short lifetime, since a cancelled hook's handle never reaches the worker.
  • Return None to grant nothing. A handle is 1 to 200 characters without /; a build target only goes to a step that builds an image.
  • Raise StepAccessRefused("…") to refuse on purpose: the step's log quotes the message. Any other exception is logged with its traceback, and the step's log names only its type, since its message may carry what the hook was given.

A refusal, or an answer that does not fit, is reported to the worker as a problem, and the other extensions still grant. The step then runs without that access: it pulls images from their own registries, and a step that builds an image gets no build target, even one another extension granted, so it fails saying it cannot push rather than building somewhere unplanned. When several extensions grant an image cache or a build target, the first one in id order counts.

One extension speaks for each registry host: the first in id order whose grant names it, by a login, an image cache or a build target. A later grant naming the same host is left out there, its login with its cache and target, so a target never goes with another extension's credentials, and the step's log names both extensions. A building step whose only build target was left out this way is told its access is missing, as above.

Enabling and disabling ​

The switch is one row per extension in the platform_extensions table. No row means disabled. The row stays when the package is uninstalled, so a reinstalled extension comes back in the state the admin left it.

RouteWhoWhat
GET /extensionsanyone signed inthe enabled extensions (id, name, description, version), with their pages and menu entries
GET /settings/extensionsoperatorevery installed extension, with its state; refused ones say why
PUT /settings/extensions/{id}platform admin{"enabled": true} or false

The switch is audited as entity.updated on resource type platform_extension, with the before and after state.

Every route an extension mounts carries a gate. While the extension is disabled, the gate answers 404 "The Demo extension is not enabled". The gate reads the switch from the database on each request, so a switch takes effect at once in every API replica. The gate ends its database read before the handler runs, so a handler that first reads a large request body (the registry's image upload, say) holds no database connection meanwhile.

Lifecycle hooks ​

HookRunsIf it raises
on_enableonce, in the API process that handles the switch, before the switch is stored; or at API start, before startup, when HEGEMONY_EXTENSIONS_ENABLE names an extension never switchedthe extension stays disabled; the admin gets a 409 with the error (at API start: the log says why, and the next start tries again)
on_disableonce, in that process, before the switch is storedthe extension stays enabled; 409
startupin every API process: at its start while the extension is enabled, right after the switch in the process that handled it, and soon after it in every other processlogged; the extension stays enabled, and that process does not try again until the switch changes
shutdownin every API process: at its stop, right after a disable in the process that handled it, and soon after it in every other processlogged; the extension counts as still running there, and that process tries again at its next check

on_enable and on_disable run before the switch is committed. If the commit then fails, the hook has run but the switch did not change, so the hooks must be safe to run again.

Switches of one extension never overlap, in any API replica. Before a hook runs, the extension's row in platform_extensions is locked until the switch commits; an extension that was never switched first gets a disabled row to lock. A second request for the same extension waits for the first, then either finds the switch already where it wanted it (nothing runs) or switches it back with its own hook. So the stored switch and what the hooks set up always agree.

Several API replicas ​

Every API replica follows the switch, background work included. Each one compares the stored switches with what it runs, and runs startup or shutdown for an extension switched elsewhere:

  • On PostgreSQL, a switch sends a notification when it commits (pg_notify on the channel hegemony_extension_switch). Every replica listens, so it follows within moments.
  • Every replica also checks every HEGEMONY_EXTENSION_RECONCILE_SECONDS (default 10). This catches a notification lost while a replica's listening connection was down.

A replica remembers the last switch it acted on. A startup that failed is tried again only once the switch changes, not on every check. A shutdown that failed is tried again at every check until it succeeds, since what it was to stop may still be running. If an extension was disabled and enabled again between two checks, a replica that had it running runs shutdown, then startup, as if it had seen both switches.

So, for a short time after a switch, replicas can disagree: one runs the extension's background work while another has not started it yet. The route gate does not wait for this; it follows the switch at once. An extension whose routes need per-process state should still create it lazily, on first use.

Within one process, an extension's startup and shutdown never overlap. After a switch, the process waits for any transition still running, then reads the switch as stored and acts on that, not on the value the request asked for. A disable that arrives while startup still runs therefore ends with shutdown, and the extension stopped.

Pages and menu ​

An extension describes its pages as data; the web app draws them at /x/<extension id>/<page id>, with the platform's own table, buttons and dialogs. Three kinds of page exist:

KindShowsNeeds
tablethe list a GET route returns, one row per itemsource, columns
detailthe one object a GET route returns, one field per columnsource, columns
forminputs, sent as a JSON body to a routeinputs, submit
python
from dataclasses import replace

from packages.core.extensions import (
    ExtensionMenuItem,
    ExtensionPage,
    PageAction,
    PageColumn,
    PageInput,
    PageLink,
)

delete = PageAction(
    "Delete",
    "DELETE",
    "/demo/items/{name}",
    confirm="The item is gone for good.",
    destructive=True,
)

pages = [
    ExtensionPage(
        id="items",
        title="Demo Items",
        kind="table",
        source="/demo/items",  # returns {"items": [...]}
        columns=[
            PageColumn("name", "Name"),
            PageColumn("size", "Size", "bytes"),
            PageColumn("created_at", "Created", "datetime"),
        ],
        row_link=PageLink("Open", "item", {"name": "name"}),
        row_actions=[delete],
        links=[PageLink("New item", "new")],
    ),
    ExtensionPage(
        id="item",
        title="Demo Item",
        kind="detail",
        source="/demo/item",
        source_query={"name": "name"},  # ?name= from this page's URL
        columns=[PageColumn("name", "Name"), PageColumn("origin.kind", "Origin", "code")],
        actions=[replace(delete, next_page="items")],
    ),
    ExtensionPage(
        id="new",
        title="New Demo Item",
        kind="form",
        inputs=[
            PageInput("name", "Name", required=True),
            PageInput("size", "Size", "number", help="In bytes."),
        ],
        submit=PageAction("Create", "POST", "/demo/items", next_page="item"),
    ),
]
menu = [ExtensionMenuItem("Demo Items", "items", group="extensions", icon="box")]

Pass both to Extension(..., pages=pages, menu=menu).

Paths are your declared routes. Every source and every action's method and path must be one of the extension's routes, written the same way (/demo/items/{name}, not a filled-in path). A page can therefore call only its own extension's API, and the web app asks the caller's capabilities about that exact route: a menu entry is hidden when the caller may not load its page, and a button is locked when the caller may not call its route.

Values come by key. A route's {name} placeholders, an action's query, a link's params and a source_query each name a value key. The key is looked up in the row (row actions and the row link), or in the loaded object (a detail page's actions and links, a table's header links and buttons, which read its whole response), or in a form's values; failing that, in the page's own URL query parameters. A dotted key walks into nested objects (origin.kind). A button whose route needs a value that is missing is left out. A path placeholder takes exactly one segment: a value is URL-encoded, and one that is empty, . or .. (which the browser resolves away) or holds a / (which the API decodes before it matches a route) counts as missing, since it would reach a route other than the declared one. Pass a value that may hold a / (an image name, a file path) as a query parameter instead (/demo/item?name=… rather than /demo/items/{name}).

Showing only where it applies. A link or a button can carry when conditions on the same values, all of which must hold for it to show on a row or an object: can_manage (the value is true, a number other than 0, a non-empty list, an object, or a text other than empty, false and 0: URL parameters are text, so ?allowed=false reads as false), !finished (it is not), kind=global (its text is global) or kind!=global. A row link whose conditions do not hold leaves that row unclickable. A form's submit reads what is entered, then the page's URL parameters: its button shows only while its conditions hold, and the form sends nothing otherwise, by Enter included. Conditions only hide what a caller should not see; the routes still check everything.

Downloads and uploads. A PageAction with download=True is a GET of one of the extension's routes: the web app saves what it answers as a file, named as its Content-Disposition header says. A form with a file input sends the chosen file as the request body itself (with its own content type), showing the upload's progress; so it has at most one, its submit is a POST or PUT, and its other inputs reach the route through the submit's path or query. The file's name is the value key <input key>.name:

python
upload = ExtensionPage(
    id="import",
    title="Import",
    kind="form",
    inputs=[
        PageInput("tag", "Tag", required=True),
        PageInput("archive", "Archive", "file", required=True, accept=".tar"),
    ],
    submit=PageAction(
        "Import",
        "POST",
        "/demo/imports",
        query={"tag": "tag", "filename": "archive.name"},
        next_page="imports",
    ),
)

Pages that follow progress. A table or detail page with refresh_seconds (2 to 3600) reloads its data that often while it is open: a list of transfers, say, with a progress column.

After an action. next_page names the page to open after the call succeeds. It gets this page's URL query parameters, plus a form's submitted values; so a form that creates name can open the detail page that loads by name. With no next_page, the page reloads. An action with confirm asks first, with that text (a form's submit too, after its inputs are checked); a DELETE action must have it. destructive draws the button in red.

Fields:

  • ExtensionPage: id (lowercase letters, digits and single dashes, up to 40), title, kind, description, source, source_query, items_key (where the list is in a table's response; "" when the response is the list itself; default items), item_key (a table's field that identifies each item, such as id: a row then keeps its place, and its buttons their item, when the page reloads; required for a table that reloads and has row actions), columns, row_link, row_actions, links (header buttons leading to other pages), actions (the header buttons of a table or detail page), inputs, submit, refresh_seconds (a table or detail page's reload interval; 0, the default, never).
  • PageColumn(key, label, format): format is text, code, number, bytes, datetime (an ISO 8601 string), boolean, badge (the text in a badge) or progress (a number from 0 to 100 as a bar). In a table, a code value shows each digest in it (a word with 24 or more hex characters in a row, such as sha256:…) as its start and end. Hovering shows it whole, and a button next to it copies it whole. A detail page shows the value whole; filters and sorting use it whole.
  • PageInput(key, label, type, required, options, help, accept): type is text, textarea, number, boolean, select (with options) or file (accept lists the file types the picker offers). A URL query parameter with the input's key fills it in (not a file). Empty optional inputs are left out of the body; numbers are sent as numbers, booleans as booleans.
  • PageLink(label, page, params, when): params maps the target page's URL query parameters to value keys.
  • PageAction(label, method, path, query, confirm, destructive, next_page, when, download): method is POST, PUT, PATCH or DELETE, in upper case, or GET for a download.
  • ExtensionMenuItem(label, page, group, icon): group is runtime, build, resources, artifacts, inventory (the sidebar's sections; the entry goes last in its section) or extensions (a section of its own, above Settings). icon is one of archive, box, boxes, container, database, file, folder, globe, hard-drive, layers, list, network, package, puzzle, server, shield, tag, wrench.

What the platform checks in pages ​

The extension is refused when:

  • a page id is malformed or used twice, or a page has an unknown kind;
  • a table or detail page has no source, or its source is not one of its declared GET routes, or it has no columns;
  • a column has an unknown format, or an input an unknown type, or a select input has no options or an empty one;
  • a form has no inputs or no submit;
  • a form has more than one file input, or one whose submit is not a POST or PUT, or whose other inputs its submit's path and query do not use, or another input keyed <file input key>.name, the key that holds the file's name;
  • an action's method is not POST, PUT, PATCH or DELETE in upper case (GET for a download, which opens no next_page), or its method and path are not one of its declared routes, or a DELETE action has no confirm text;
  • a when condition is not key, !key, key=text or key!=text;
  • a form has a refresh_seconds, or a table or detail page one outside 2 to 3600;
  • a table that reloads and has row actions has no item_key, or a page that is not a table has one;
  • a link, an action's next_page or a menu entry names a page the extension does not declare;
  • a menu entry names an unknown group or icon;
  • a field has the wrong type.

Tables of its own ​

An extension keeps its records in tables of its own. It declares a directory of Alembic revisions, with one head:

python
from pathlib import Path

Extension(
    id="demo",
    ...,
    migrations=str(Path(__file__).parent / "migrations"),
)

Each file in the directory is an ordinary Alembic revision (revision, down_revision, upgrade(), downgrade()). The first one has down_revision = None. There is no env.py: the platform runs them.

python
"""Create demo_items.

Revision ID: 0001_items
Revises:
"""

import sqlalchemy as sa
from alembic import op

revision = "0001_items"
down_revision = None


def upgrade() -> None:
    op.create_table(
        "demo_items",
        sa.Column("id", sa.Integer, primary_key=True),
        sa.Column(
            "org_id",
            sa.Uuid,
            sa.ForeignKey("organizations.id", ondelete="CASCADE"),
            nullable=False,
        ),
    )


def downgrade() -> None:
    op.drop_table("demo_items")

Who applies them. The platform's migrate command, python -m apps.api.migrate. It is what the compose migrate service runs (task db:migrate). It applies the platform's own migrations first, then each installed extension's revisions. It does this whether the extension is enabled or not, so its tables are ready before an admin enables it.

  • Each extension's version is kept in a table of its own: alembic_version_<prefix>, where the prefix is the id with - turned into _ (alembic_version_demo).
  • One extension's revisions run in one transaction. On PostgreSQL, a revision that fails leaves that extension's tables as they were. The command reports the error, goes on with the other extensions, and exits with status 1.
  • The command holds a PostgreSQL advisory lock for the whole run, the platform's migrations included, so two runs never change the same tables at once.
  • It names every extension the platform refuses, with the reason, and leaves that extension's tables alone. This does not fail the command.

The API never changes the schema. At its start, it compares each extension's version table with the extension's newest revision. It refuses an extension whose tables are behind ("its tables are at revision …, not its newest …: run the migrate command"). None of a refused extension's routes, hooks or step access run, so its code never meets tables it does not expect. Run the migrate command, then restart the API.

Going back. python -m apps.api.migrate downgrade <extension> <revision> (task db:downgrade:extension -- <extension> <revision>) runs one extension's downgrade() functions back to the revision; base removes all of its tables. It leaves the platform's tables alone. The API refuses the extension from its next start until the tables are upgraded again.

Rules for the tables:

  • Name every table, index and constraint with the extension's prefix (demo_items, ix_demo_items_org_id), so two extensions never collide. The platform's autogenerate (task db:revision) then leaves the tables alone (see Autogenerate and extensions' tables).
  • A foreign key to a platform table (organizations.id, say) is fine. Never change a platform table.
  • Deleting an organization deletes the rows that refer to it with ON DELETE CASCADE, as the example does. Without it, the extension's rows keep the organization from being deleted (409).
  • The tables are not platform models: the platform's tenancy guards do not scope them. Filter every query by organization yourself.
  • Use a DeclarativeBase of the extension's own for its models, not the platform's Base.

The registry's registry_image_transfers table is an example (extensions/registry/src/hegemony_registry/models.py and migrations/). Its first revision takes over the table the platform kept for it while the registry was built in (image_transfers), and renames it.

Background jobs ​

An extension can have the platform do work in the background, a cleanup say, through the same maintenance runner as the platform's own jobs: the scheduler's tick runs a due job in one API process at a time, under a lease, and only while the extension is enabled.

python
from packages.core.extensions import ExtensionJob, ExtensionJobResult


async def _prune(context, db, now):
    from .services.pruning import prune  # import the heavy parts here

    removed = await prune(db, context.extension_settings, now)
    return ExtensionJobResult(
        scanned=removed.seen, affected=removed.count, notes={"removed": removed.count}
    )


Extension(
    id="demo",
    ...,
    jobs=(
        ExtensionJob(
            "prune",
            "Deletes demo items nobody opened for a year.",
            _prune,
            interval_seconds=86400,
        ),
    ),
)

A job gets the hooks' context, an open database session (it commits what it writes) and the tick's time, and returns an ExtensionJobResult: counts and notes (JSON values) the platform keeps with the job's state. An exception marks the run failed with its message. Its audit entries are attributed to system:maintenance. The job runs in whichever API process the tick reaches, so it must not rely on what the startup hook set up in that process.

The platform lists the job as <extension id>:<job name> (demo:prune) in Settings → Maintenance Jobs while the extension is on. It runs once interval_seconds have passed since its last run finished, or at the next tick after request_job_run(db, "demo:prune") (apps.api.services.maintenance) asked for it, which a "Run now" route of the extension can call. list_job_states reads its last run back, for a page that shows it.

The platform refuses an extension whose jobs is not a list of ExtensionJob, or one of whose jobs has a name that is not 2 to 48 lowercase letters, digits and underscores starting with a letter, a name it declares twice, no description, a run that is not callable, or an interval that is not a whole number of at least 60 seconds.

Audit vocabulary ​

An extension that audits its own kind of object declares the resource types and event namespaces it uses:

python
Extension(
    id="demo-shop",
    ...,
    audit_resource_types=("demo_shop_item",),
    audit_namespaces=("demo_shop",),
)
  • A resource type is 2 to 64 lowercase letters, digits and underscores, starting with a letter. It must not be one of the platform's (AuditResourceType). Start it with the extension's prefix, so two extensions do not want the same one.
  • A namespace must be the extension's prefix (the id with - turned into _), or start with the prefix and _. Event types are then demo_shop.item_published, say. It must not be one of the platform's.
  • The extension's audit_coverage may name its own resource types and the platform's, but no other extension's.
  • If two extensions declare the same name, the one earlier by id keeps it and the other is refused.

emit_audit_log accepts an installed extension's vocabulary, enabled or not, as it does the platform's. A refused extension's vocabulary is not accepted. Entries keep their resource_type and event_type when the extension is disabled or uninstalled; the audit log shows them as written.

The registry declares container_image this way (extensions/registry/src/hegemony_registry/permissions.py).

Where the code lives ​

  • packages/core/extensions/contract.py: the Extension declaration.
  • packages/core/extensions/registry.py: discovery and refusal.
  • apps/api/auth/permissions.py, apps/api/audit_coverage.py: the merge into the RBAC and audit registries.
  • apps/api/services/extensions.py: the switch, the gate, the hooks, following switches across replicas, and mounting.
  • apps/api/extension_migrations.py, apps/api/migrate.py: extensions' own tables, and the migrate command.
  • apps/api/services/maintenance/__init__.py: extensions' background jobs in the maintenance runner, and request_job_run.
  • apps/api/audit.py: the audit vocabulary check, extensions' included.
  • apps/api/routers/extensions.py: the routes above.
  • apps/api/auth/org_scope.py: which routes are organization-scoped, extensions' prefixes included.
  • apps/api/services/step_access.py, apps/api/routers/step_access.py: step access; apps/worker/step_handlers/docker_config.py applies it.
  • apps/ui/src/pages/ExtensionPage.tsx, apps/ui/src/lib/extensions.tsx: the page renderer and the sidebar entries.
  • apps/ui/src/pages/SettingsExtensions.tsx: Settings → Extensions.
  • extensions/registry: the container registry, an extension the platform ships with and a complete example: its own settings, organization routes under /images, platform routes, a custom-policy token route, step access, lifecycle hooks, tables of its own, a daily background job (jobs.py), and pages described as data (pages.py). It is an editable path dependency of the API (pyproject.toml), installed in the API image like any other extension package.

Released as open source under the AGPL-3.0-or-later license. Development is sponsored by Rexonix s.r.o. Contact — [email protected].