Skip to content

API Reference parrot.services.comm_center.render

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

parrot.services.comm_center.render

View source

Render + validation core — the CommCenter "partial-render gateway".

This is the heart of the feature (spec §2 Overview, §3 Module 5). Everything downstream — bulk send, single send, and dry-run — routes through :func:prepare, so it must be pure: no Redis, no DB, no aiohttp. That purity is what makes dry_run (TASK-2162) a free short-circuit and what makes :class:~parrot.services.comm_center.CommCenterService usable outside HTTP (spec G12).

Two-pass render contract (spec §2): pass 1 (this module, once per batch) resolves computed functions ({{today}}) while leaving {{name}}, {{email}}, etc. literal via Jinja2's DebugUndefined; pass 2 (NotifyWorker -> AbstractProvider._render_, once per recipient) resolves the record placeholders from the row kwargs. Both passes run with autoescape=False — pass 2 is fixed that way by notify.templates, so pass 1 must match it or the preserved {{ }} braces would be HTML-escaped and corrupted.

Three verified traps live in :func:build_wire_payload (spec §6):

  1. username defaults to the Actor object in Notify's pass-2 context when a row has no username — always emit it, falling back to name.
  2. The wire key is recipient (singular) — NotifyWrapper pops exactly that key; a plural key silently sends to nobody.
  3. team_id is checked before channel_id — a dict carrying both always becomes a TeamsChannel, never a Channel.

Alias DATE_RESOLVERS

Re-exported from parrot.outputs.a2ui.recipes.params.DATE_RESOLVERS.

Alias PreparedBatch

Re-exported from parrot.services.comm_center.models.PreparedBatch.

Alias PreparedMessage

Re-exported from parrot.services.comm_center.models.PreparedMessage.

Alias RecipientIn

Re-exported from parrot.services.comm_center.models.RecipientIn.

Class RenderError

Raised when the template body fails to parse (handler maps to 400).

Nothing may be published when this is raised — it must surface before a single recipient is processed.

Alias SkippedRow

Re-exported from parrot.services.comm_center.models.SkippedRow.

Function build_preview

Render the exact text pass 2 would produce for one recipient (spec §3 Module 9).

Simulates AbstractProvider._render_'s context (notify/providers/base.py:177-183): {"recipient": to, "username": to, "message": message, "subject": subject, **kwargs}, where **kwargs is bound last and overrides the defaults. Uses the same payload :func:build_wire_payload produced — never a separately-constructed context — so the preview is guaranteed to match what a real send would deliver (spec §5 preview-fidelity criterion). Because build_wire_payload always emits a real username string (Trap 1 guard), the simulated default Actor-object binding is always overridden here too, exactly as it is in the real pass 2.

build_preview(payload: dict) -> str

Parameter Type Default Description
payload dict A wire payload from :func:build_wire_payload (the first queued recipient's, by convention).

Returns: str — The fully-rendered preview text.

Function build_wire_payload

Build the exact dict published via NotifyClient.stream() (one xadd).

Implements the per-provider recipient shape table (spec §2) and guards all three verified traps: the wire key is recipient (singular, Trap 2); username is always emitted, falling back to name (Trap 1); only the keys the target provider needs are emitted, so team_id is never accidentally present for a channel_id-based provider (Trap 3).

build_wire_payload(recipient: RecipientIn, provider: str, template: str, subject: str | None) -> dict

Parameter Type Default Description
recipient RecipientIn The normalized, already-validated recipient row.
provider str The resolved provider for this recipient (row override or batch default).
template str The already partially-rendered template string (pass 1 output) — the same string for every recipient in the batch.
subject str | None The message subject, if any.

Returns: dict — The complete wire payload dict, ready to be JSON-encoded and xadd-ed unchanged.

Function partial_render

Render template_string once, binding only the computed-function context.

Uses Environment(undefined=DebugUndefined, autoescape=False) so every placeholder not present in context (i.e. every per-recipient field) is re-emitted literally for the worker's second pass.

Deliberate deviation from the task/spec's literal enable_async=True on this Environment (see this task's Completion Note for the full reproduction): with enable_async=True, Jinja2's synchronous Template.render() internally calls asyncio.run(...), which raises RuntimeError: asyncio.run() cannot be called from a running event loop whenever this function is invoked from :func:prepare — an async def that is always awaited from within an already-running event loop in real usage (the aiohttp handler). Verified byte-for-byte identical rendered output with and without enable_async for the exact string from spec §6's executed verification; omitting it is required for :func:prepare to work at all and changes no rendered content.

partial_render(template_string: str, context: dict) -> str

Parameter Type Default Description
template_string str The raw Jinja2 template body (stored, inline, or from a TEMPLATE_DIR file's contents).
context dict The computed-function values to bind, typically the output of :func:resolve_functions.

Returns: str — The partially-rendered string: computed functions substituted, record placeholders preserved as literal {{ field }} text.

Raises:

  • RenderError — The template body is not valid Jinja2. Nothing may be published when this is raised.

Function prepare

Run every step short of publishing: render, validate, build payloads.

Shared by POST /sender, POST /message, and both endpoints' dry_run short-circuit (spec §2 "Shared-core requirement"). Performs no I/O and publishes nothing — it is safe to call from a plain unit test or a future non-HTTP caller (spec G12).

prepare(*, recipients: list, provider: str, template_source: str, subject: str | None = None, now: datetime | None = None, dry_run: bool = False) -> PreparedBatch

Parameter Type Default Description
recipients list The already-ingested, normalized recipient rows.
provider str The batch/request-level default provider.
template_source str The already-resolved template body (stored, inline, or file contents) — resolving which template to use is the caller's job; this function only renders it.
subject str | None None The message subject, if any.
now datetime | None None Injectable current time, threaded into :func:resolve_functions.
dry_run bool False When True, the returned :class:PreparedBatch carries dry_run=True and a preview of the first queued recipient's fully-rendered (both passes) text — None when nothing is queued (spec §3 Module 9). This flag is only ever recorded, never acted on here — :func:prepare never publishes regardless; the actual publish refusal is enforced in :mod:parrot.services.comm_center.dispatch (defense in depth), and the handler is what actually skips persistence/fan-out for a dry run.

Returns: PreparedBatch — class:PreparedBatch with the resolved functions, the partially-rendered template, and the queued/skipped split.

Raises:

  • RenderError — template_source is not valid Jinja2.

Alias resolve_date

Re-exported from parrot.outputs.a2ui.recipes.params.resolve_date.

Function resolve_functions

Resolve every computed function for the batch-level (pass 1) render.

Delegates every date-based entry to :func:resolve_date — date math is never reimplemented here. now and current_year are the two module-local extras (spec §3 Module 3).

resolve_functions(*, now: datetime | None = None) -> dict

Parameter Type Default Description
now datetime | None None Injectable current time for deterministic output.

Returns: dict — A dict mapping each computed-function name to its resolved string value ({"today": "2026-08-06", "now": "...", ...}).

Function validate_and_resolve_provider

Resolve each recipient's effective provider and validate its contact field.

validate_and_resolve_provider(recipients: list, default_provider: str) -> tuple

Parameter Type Default Description
recipients list The normalized recipient rows to validate.
default_provider str The batch/request-level provider, used when a row does not override it.

Returns: tuple — A (resolved, skipped) tuple: resolved is a list of (row_number, recipient, provider) for rows that passed validation; skipped is a list of :class:SkippedRow. Unknown providers are always skipped, never silently defaulted (spec G5).

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