Skip to content

API Reference parrot_formdesigner.services.registry

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_formdesigner.services.registry

View source

Form Registry for the forms abstraction layer.

Provides FormStorage (abstract persistence backend) and FormRegistry (in-memory registry with optional persistence and async callbacks).

Migrated from parrot/integrations/dialogs/registry.py with:

  • FormSchema instead of FormDefinition
  • async-first API (asyncio.Lock instead of threading.Lock)
  • FormStorage ABC for pluggable persistence backends
  • persist= parameter on register()
  • load_from_storage() for startup hydration
  • Async register/unregister callbacks

Multi-tenancy support (FEAT-183):

  • Internal state is dict[tenant, dict[form_id, FormSchema]] (nested dict).
  • Every public method accepts kwarg-only tenant: str | None = None.
  • tenant=None resolves strictly to default_tenant — never aggregates.
  • on_unregister callbacks receive (form_id, tenant) — BREAKING change.

Stable UUID identity (FEAT-389):

  • The primary index is now keyed by form_uid (immutable UUID4) instead of form_id (mutable, human-readable slug). Internal state is dict[tenant, dict[form_uid, FormSchema]].
  • A secondary _slug_index: dict[tenant_form_slug, form_uid] maps the composite key "{tenant}_{form_id}" to the owning form_uid, enforcing slug uniqueness per tenant and enabling :meth:get_by_slug.
  • get(), unregister(), contains(), and clone_form() now take form_uid — NOT form_id — as their primary lookup parameter. on_unregister callbacks now receive (form_uid, tenant).

Class FormAlreadyExistsError

Raised when registering a form whose slug (form_id) is already taken by a different form_uid within the same tenant.

Subclasses ValueError so existing except ValueError blocks keep working, but lets API handlers distinguish 409 Conflict (duplicate id) from 422 Unprocessable Entity (validation failure).

Class FormRegistry

Thread-safe, multi-tenant registry for FormSchema objects.

Supports in-memory registration scoped by tenant, optional persistence via FormStorage, async event callbacks, and YAML directory loading via YamlExtractor.

Internal state is dict[tenant, dict[form_uid, FormSchema]] — the primary index is keyed by the immutable form_uid (FEAT-389), NOT the mutable form_id slug. A secondary _slug_index maps "{tenant}_{form_id}" → form_uid for slug-based lookups via :meth:get_by_slug.

Every public read/write method accepts a kwarg-only tenant= parameter that resolves via: explicit kwarg > form.tenant (register paths) > default_tenant.

Example::

registry = FormRegistry()
await registry.register(form_schema)                     # requires form.tenant
form = await registry.get(form_schema.form_uid, tenant="navigator")
form = await registry.get_by_slug("my-form", tenant="navigator")

# With persistence
registry = FormRegistry(storage=PostgreSQLFormStorage(...))
await registry.register(form_schema, persist=True)
await registry.load_from_storage(tenant="navigator")

# Cross-tenant admin pattern (explicit loop — no aggregation via tenant=None):
all_forms: list[FormSchema] = []
for t in await registry.list_tenants():
    all_forms.extend(await registry.list_forms(tenant=t))
Parameter Type Default Description
storage FormStorage | None None Optional FormStorage backend for persistence.
app 'web.Application | None' None Optional aiohttp web.Application instance. When provided, the registry self-registers as app['form_registry'] and hooks :meth:on_startup / :meth:on_shutdown into the application's lifecycle signals automatically.
default_tenant str 'navigator' Tenant name used when callers pass tenant=None. Defaults to "navigator" to match PostgresFormStorage.DEFAULT_SCHEMA.
require_tenant bool True When True (default), :meth:register raises ValueError if the form's effective tenant would fall all the way through to default_tenant because BOTH the explicit tenant= kwarg AND form.tenant are None. When False, such forms are silently sealed to default_tenant.

Attributes:

Attribute Type Description
default_tenant str Tenant slug used when callers don't supply one explicitly. Exposed so HTTP handlers can enrich tenant-less requests at the boundary (e.g. anonymous or session-less calls), instead of relying on register()'s require_tenant=False escape hatch.
has_storage bool Return True if a FormStorage backend is configured. Use this instead of accessing _storage directly from external code.
storage 'FormStorage | None' Return the configured FormStorage backend, or None. Prefer :attr:has_storage for boolean checks and this property when you actually need to call the backend.

Method FormRegistry.register

Register a form schema under a specific tenant.

Resolution order for the effective tenant:

  1. Explicit tenant= kwarg (if not None).
  2. form.tenant (if not None).
  3. self._default_tenant.

When require_tenant=True (the default), step 3 is only reached if BOTH the kwarg AND form.tenant are None — in that case a ValueError is raised to prevent accidental un-scoped registration.

If the explicit kwarg differs from form.tenant, a WARNING is logged and the kwarg wins. form.tenant is never mutated.

The primary index key is form.form_uid (immutable) — NOT form.form_id (FEAT-389). A secondary _slug_index entry ("{tenant}_{form_id}" → form_uid) is created/updated so the form is also reachable via :meth:get_by_slug. If form.form_id changed since this form_uid was last registered, the stale slug index entry is removed.

register(form: FormSchema, *, persist: bool = False, overwrite: bool = True, tenant: str | None = None) -> None

Parameter Type Default Description
form FormSchema FormSchema to register.
persist bool False If True, also save to storage backend. Logs a warning (does not raise) if no storage is configured.
overwrite bool True If True (default), permit updating THIS form_uid's own existing registration. Never grants permission to take a DIFFERENT form_uid's slug — see FormAlreadyExistsError below, which is raised unconditionally in that case.
tenant str | None None Explicit tenant override. None means "use form.tenant or default_tenant".

Raises:

  • ValueError — When require_tenant=True and both tenant= kwarg and form.tenant are None.
  • FormAlreadyExistsError — When form.form_id (slug) is already in use by a DIFFERENT form_uid within the resolved tenant (slug uniqueness enforcement, FEAT-389) — raised regardless of overwrite, which only governs updating this form_uid's own prior registration. Subclasses ValueError so existing except ValueError call sites keep working.

EXCEPTION (2026-08-12): a BRAND-NEW form (a form_uid this registry has never seen) registering with persist=True does not raise — its slug is numerically suffixed to the first free one instead (bug-report-form → bug-report-form-2), probing BOTH the in-memory index and the storage backend, and form.form_id is updated in place so the caller returns the real slug. Create-from-template mints canonical slugs on purpose; only RENAMES of existing forms keep the error.

Method FormRegistry.set_storage

Set the FormStorage backend for this registry.

set_storage(storage: FormStorage) -> None

Parameter Type Default Description
storage FormStorage FormStorage instance to use for persistence.

Method FormRegistry.set_public_toggle_callback

Register a callback invoked when a form's is_public flag changes.

The callback is called with (form_uid, True) when the form becomes public, and (form_uid, False) when it becomes private or is deleted. Only called when the is_public value actually changes (no-op on same-value re-registration). Keyed by form_uid (FEAT-389) since the callback drives URL-pattern auth exclusions and routes are form_uid-based (TASK-1976).

set_public_toggle_callback(callback: Callable[[uuid.UUID, bool], Awaitable[None]]) -> None

Parameter Type Default Description
callback Callable[[uuid.UUID, bool], Awaitable[None]] Async callable (form_uid: uuid.UUID, is_public: bool) -> None.

Method FormRegistry.on_startup

aiohttp on_startup signal handler.

Calls storage.initialize() (when the backend exposes it) and then :meth:load_from_storage to hydrate the in-memory cache for the registry's default_tenant. Registered automatically when an app is passed to :meth:__init__.

Safe to call when no storage is configured — early-returns instead of raising so app boot keeps working in storage-less test setups.

on_startup(app: 'web.Application') -> None

Parameter Type Default Description
app 'web.Application' aiohttp application (provided by aiohttp's signal machinery).

Method FormRegistry.on_shutdown

aiohttp on_shutdown signal handler.

Calls storage.close() to release backend-held resources (e.g. an asyncpg pool). Registered automatically when an app is passed to :meth:__init__.

on_shutdown(app: 'web.Application') -> None

Parameter Type Default Description
app 'web.Application' aiohttp application (provided by aiohttp's signal machinery).

Method FormRegistry.unregister

Unregister a form schema from a specific tenant.

If removing the form leaves the tenant bucket empty, the outer key is deleted so :meth:list_tenants never reports empty tenants. The corresponding _slug_index entry is also removed (FEAT-389).

unregister(form_uid: uuid.UUID, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_uid uuid.UUID form_uid (immutable UUID) of the form to remove. NOT form_id — use :meth:get_by_slug first to resolve a slug to its form_uid if needed.
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: bool — True if removed, False if not found.

Method FormRegistry.clone_form

Clone an existing form under a new form_id (slug) AND a fresh form_uid (FEAT-389).

Creates a deep copy of the source form, assigns new_form_id as its slug, generates a brand-new form_uid via uuid.uuid4(), resets version to "1.0" and created_at to None, records meta["cloned_from"] for provenance, optionally applies an RFC 7396 merge-patch, validates the result, and registers it.

Source lookup and clone registration share the same resolved tenant, so cloning happens within a single tenant scope.

clone_form(source_form_uid: uuid.UUID, new_form_id: str, patch: dict[str, Any] | None = None, *, persist: bool = True, tenant: str | None = None) -> FormSchema

Parameter Type Default Description
source_form_uid uuid.UUID form_uid (immutable UUID) of the form to clone. NOT form_id — use :meth:get_by_slug first to resolve a slug to its form_uid if needed.
new_form_id str form_id (slug) to assign to the cloned form. The clone always gets a brand-new form_uid, independent of this slug.
patch dict[str, Any] | None None Optional RFC 7396 merge-patch dict to apply on top of the cloned form before validation. form_id, form_uid, and created_at in the patch are ignored.
persist bool True If True (default), persist the cloned form via the configured storage backend.
tenant str | None None Tenant scope for both source lookup and clone registration. None resolves to default_tenant.

Returns: FormSchema — The newly cloned and registered FormSchema (with a fresh form_uid).

Raises:

  • KeyError — When source_form_uid is not found under tenant.
  • FormAlreadyExistsError — When new_form_id (slug) already exists under tenant.
  • ValueError — When FormValidator.check_schema reports structural errors, or when the patch produces an invalid schema.

Method FormRegistry.get

Get a form schema by form_uid (primary key) within a tenant.

Read-through (2026-08-13): on a cache miss, when a storage backend is attached, the form is loaded from storage and admitted into the cache — see :meth:_read_through. The in-memory index alone made every uid-gated handler (delete/update/validate/render/clone) 404 on any persisted form the boot-time hydration did not cover, and a restart was required before a form created by another process (or seeded directly) became visible at all.

get(form_uid: uuid.UUID, *, tenant: str | None = None) -> FormSchema | None

Parameter Type Default Description
form_uid uuid.UUID The form's immutable form_uid (UUID). NOT form_id — use :meth:get_by_slug for slug-based lookups.
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: FormSchema | None — FormSchema if found under the resolved tenant (cache first, then storage), None otherwise. A form registered under "epson" is invisible to get(form_uid, tenant="pokemon").

Method FormRegistry.get_by_slug

Get a form schema by its slug (form_id) within a tenant.

Resolves form_id → tenant_form_slug → form_uid via _slug_index, then looks up the primary index (FEAT-389). On a cache miss, falls through to storage (:meth:_read_through) — same rationale as :meth:get.

get_by_slug(form_id: str, *, tenant: str | None = None) -> FormSchema | None

Parameter Type Default Description
form_id str The form's human-readable slug.
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: FormSchema | None — FormSchema if a form with this slug exists under the resolved tenant (cache first, then storage), None otherwise.

Method FormRegistry.list_forms

List all registered form schemas for a specific tenant.

Never aggregates across tenants. To iterate all tenants, loop over :meth:list_tenants and call list_forms(tenant=t) for each.

list_forms(*, tenant: str | None = None) -> list[FormSchema]

Parameter Type Default Description
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: list[FormSchema] — List of FormSchema objects registered under the resolved tenant.

Method FormRegistry.list_form_ids

List all registered form slugs (form_id) for a specific tenant.

list_form_ids(*, tenant: str | None = None) -> list[str]

Parameter Type Default Description
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: list[str] — List of form_id (slug) strings under the resolved tenant, derived from the primary form_uid-keyed index (FEAT-389).

Method FormRegistry.list_form_uids

List all registered form_uid values for a specific tenant.

list_form_uids(*, tenant: str | None = None) -> list[uuid.UUID]

Parameter Type Default Description
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: list[uuid.UUID] — List of form_uid values under the resolved tenant.

Method FormRegistry.contains

Check if a form is registered under a specific tenant.

contains(form_uid: uuid.UUID, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_uid uuid.UUID form_uid (immutable UUID) to check. NOT form_id — use :meth:get_by_slug for slug-based checks.
tenant str | None None Tenant scope. None resolves to default_tenant.

Returns: bool — True if the form is registered under the resolved tenant.

Method FormRegistry.clear

Clear all registered forms for a specific tenant only.

Never aggregates. Drops only resolved_tenant's forms and removes the outer key so :meth:list_tenants stays accurate. Also drops the cleared forms' _slug_index/_uid_to_slug entries (code-review fix, FEAT-389) — leaving them behind let a subsequent register(overwrite=False) for the SAME slug in this now-empty tenant incorrectly raise "already in use" against a form_uid that no longer exists anywhere in _forms.

clear(*, tenant: str | None = None) -> None

Parameter Type Default Description
tenant str | None None Tenant scope. None resolves to default_tenant.

Method FormRegistry.clear_all

Drop every tenant's forms.

Use for test teardown and maintenance only — not for single-tenant operations (use :meth:clear for those). Also drops _slug_index/_uid_to_slug entirely (code-review fix, FEAT-389) — see :meth:clear's docstring for why leaving them behind is a correctness bug, not just clutter.

clear_all() -> None

Method FormRegistry.list_tenants

Return a sorted list of tenants that have at least one registered form.

list_tenants() -> list[str]

Returns: list[str] — Alphabetically sorted list of tenant strings. Empty when the registry has no forms.

Method FormRegistry.load_from_directory

Load YAML form definitions from a directory using YamlExtractor.

If YamlExtractor is not available, logs a warning and returns 0.

Tenant resolution per file:

  1. YAML's own tenant: field wins (carried on FormSchema.tenant after extraction).
  2. Otherwise the tenant= kwarg passed to this method supplies a default.
  3. Otherwise, if require_tenant=True, the file is skipped with a WARNING log. If require_tenant=False, the form is sealed to default_tenant by the :meth:register call.

load_from_directory(path: str | Path, *, recursive: bool = True, overwrite: bool = False, tenant: str | None = None) -> int

Parameter Type Default Description
path str | Path Directory path containing .yaml/.yml form files.
recursive bool True If True, search subdirectories.
overwrite bool False If True, overwrite existing registrations.
tenant str | None None Default tenant for YAML files that don't declare tenant: at the top level.

Returns: int — Number of forms successfully loaded (skipped files are NOT counted).

Method FormRegistry.load_from_storage

Load all persisted forms from storage into memory for a tenant.

Consecutive calls for different tenants do not overwrite each other — each call lands results in _forms[resolved_tenant].

load_from_storage(*, tenant: str | None = None) -> int

Parameter Type Default Description
tenant str | None None Tenant slug forwarded to the storage backend so per-tenant schemas (epson.form_schemas) hydrate correctly. None resolves to default_tenant.

Returns: int — Number of forms loaded from storage.

Method FormRegistry.on_register

Register a callback invoked when a form is registered.

on_register(callback: Callable[[FormSchema], Awaitable[None]]) -> None

Parameter Type Default Description
callback Callable[[FormSchema], Awaitable[None]] Async callable receiving the registered FormSchema. The form's .tenant attribute is populated with the resolved tenant at registration time (may still be None if require_tenant=False and no tenant was resolved yet).

Method FormRegistry.on_unregister

Register a callback invoked when a form is unregistered.

BREAKING change from the pre-FEAT-183 signature: callbacks now receive (form_uid, tenant) rather than just form_id.

on_unregister(callback: Callable[[uuid.UUID, str], Awaitable[None]]) -> None

Parameter Type Default Description
callback Callable[[uuid.UUID, str], Awaitable[None]] Async callable receiving (form_uid: uuid.UUID, tenant: str) — the tenant is the resolved tenant captured at :meth:unregister call time (never None).

Alias FormSchema

Re-exported from parrot_formdesigner.core.schema.FormSchema.

Class FormStorage

Abstract base class for form persistence backends.

Implementations provide save/load/delete/list operations on persisted FormSchema objects. Used by FormRegistry when persist=True.

Example implementation: PostgreSQLFormStorage (TASK-529).

Method FormStorage.save

Persist a form schema.

save(form: FormSchema, style: StyleSchema | None = None, *, tenant: str | None = None) -> str

Parameter Type Default Description
form FormSchema FormSchema to persist.
style StyleSchema | None None Optional associated StyleSchema.
tenant str | None None Optional tenant slug used by Postgres-backed storages to resolve the target schema. Implementations that don't segregate by tenant may ignore it.

Returns: str — The form_id of the saved form.

Method FormStorage.load

Load a form schema by ID.

load(form_id: str, version: str | None = None, *, tenant: str | None = None) -> FormSchema | None

Parameter Type Default Description
form_id str Identifier of the form to load.
version str | None None Optional version string. If None, loads the latest.
tenant str | None None Optional tenant slug used by Postgres-backed storages to resolve the target schema.

Returns: FormSchema | None — FormSchema if found, None otherwise.

Method FormStorage.delete

Delete a persisted form.

delete(form_id: str, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_id str Identifier of the form to delete.
tenant str | None None Optional tenant slug used by Postgres-backed storages to resolve the target schema.

Returns: bool — True if deleted, False if not found.

Method FormStorage.list_forms

List all persisted forms.

Each dict in the returned list MUST include form_id and version (required keys). Implementations SHOULD also include title, description, and created_at when the backend has them available.

description may be None when the form has no description. created_at is an ISO-8601 string produced via datetime.isoformat() (e.g. "2026-04-12T10:31:00+00:00") or None when not available.

list_forms(*, tenant: str | None = None) -> list[dict[str, Any]]

Parameter Type Default Description
tenant str | None None

Returns: list[dict[str, Any]] — List of dicts with at minimum form_id and version. Optional keys: title, description, created_at.

Method FormStorage.list_versions

Enumerate every stored version of one form (FEAT-433 Module 2).

Replaces reconstructing history by probing load() one candidate version at a time. Concrete backends that persist multiple versions per form (e.g. PostgresFormStorage) should override this with a single ordered query; the base (default) implementation returns an empty list, which is correct for backends — real or test doubles — that don't persist per-version history (FormVersionService falls back to its in-process _meta cache in that case).

Not abstract (unlike save/load/delete/list_forms): existing FormStorage subclasses that predate this method must keep instantiating without having to implement it.

list_versions(form_uid: uuid.UUID, *, tenant: str | None = None) -> list[dict[str, Any]]

Parameter Type Default Description
form_uid uuid.UUID The form's immutable UUID (FEAT-389).
tenant str | None None Optional tenant slug used by Postgres-backed storages to resolve the target schema.

Returns: list[dict[str, Any]] — Every stored version of the form, oldest first, ordered by the parsed (major, minor) integers — never by the raw version string. Each row is a dict with keys version, created_at, updated_at, form_id, published_version, published_at. The base implementation always returns [].

Method FormStorage.promote

Promote a version to published, in place (FEAT-433 Module 6).

FEAT-433 §8 Q5 (closed 2026-08-19): publish() no longer creates a new row at a bumped tag — it stamps the CURRENT live version (draft or never-before-persisted) as published. This is the guarded write behind that. It is effectively an upsert with one extra rule: it refuses to touch a row that is ALREADY published, so a published snapshot can never be silently re-promoted or overwritten. A version with no existing row at all (the form's very first publish, or a form never separately saved by the editor) is NOT rejected — there is nothing published yet to protect, so this writes it, same as an insert would.

Not abstract, like :meth:list_versions: this default implementation is built from :meth:load/:meth:save (correct, but NOT atomic under concurrent writers). PostgresFormStorage overrides this with a single guarded INSERT ... ON CONFLICT DO UPDATE ... WHERE (an upsert whose update half is skipped when the existing row is already published), which IS atomic — a real backend serving concurrent publishes SHOULD override this the same way.

promote(form_uid: uuid.UUID, version: str, schema_json: str, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_uid uuid.UUID The form's immutable UUID (FEAT-389).
version str The version tag being promoted.
schema_json str The new (already published_version-stamped) schema, serialized (FormSchema.model_dump_json()).
tenant str | None None Optional tenant slug used by Postgres-backed storages to resolve the target schema.

Returns: bool — True if the row was written (promoted, or written for the first time); False if no row was affected — the version is ALREADY published (the guard).

Method FormStorage.close

Release any resources held by this storage backend.

Default implementation is a no-op. Subclasses that hold resources (e.g. asyncpg pools, file handles) should override this method. Called automatically by :meth:FormRegistry.on_shutdown when the aiohttp application shuts down.

close() -> None

Alias FormValidator

Re-exported from parrot_formdesigner.services.validators.FormValidator.

Alias StyleSchema

Re-exported from parrot_formdesigner.core.style.StyleSchema.

Alias derive_stable_identities

Re-exported from parrot_formdesigner.core.schema.derive_stable_identities.

Attribute logger

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally