Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
11 kB 254 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255#!/usr/bin/env -S uv run --script --quiet# /// script# requires-python = ">=3.12"# dependencies = ["httpx", "prefect>=3.0"]# ///"""End-to-end test for automation-based send-notification actions.
This drives the same surface area a real Prefect client/UI uses:
1. Create a DiscordWebhook block type/schema/document. 2. Create an event automation with a `send-notification` action. 3. Emit a matching event with flow-run, deployment, and state labels. 4. Poll for the `prefect.automation.action.executed` audit event.
For a real outbound HTTP assertion, start the zig server with:
PREFECT_DISCORD_WEBHOOK_BASE_URL=http://127.0.0.1:<receiver>/api/webhooks
The action will POST to:
/api/webhooks/<webhook_id>/<webhook_token>
usage: PREFECT_API_URL=http://localhost:4200/api ./scripts/test-notifications
With the local test receiver, --receiver-mode error|redirect|oversized|stallasserts the corresponding failure audit event. --capture <receiver JSONL>also checks the POST count, rendered payload, and request headers."""import argparseimport asyncioimport jsonimport osfrom pathlib import Pathimport sysimport timeimport uuid
import httpxfrom prefect import get_clientfrom prefect.events import emit_eventfrom prefect.events.actions import SendNotificationfrom prefect.events.schemas.automations import ( AutomationCore, EventTrigger, Posture,)
os.environ.setdefault("PREFECT_API_URL", "http://localhost:4200/api")API_URL = os.environ["PREFECT_API_URL"].rstrip("/")CACHE_WAIT_SECONDS = 3FAILURES = { "error": "NotificationFailed", "redirect": "RedirectRefused", "oversized": "ResponseTooLarge", "stall": "ResponseHeadTimeout",}
def auth() -> httpx.BasicAuth | None: """Auth for the raw httpx calls below.
The prefect client reads PREFECT_API_AUTH_STRING itself; direct httpx calls do not, so an authenticated server 401s every request and the failure surfaces as whatever this script was measuring. """ raw = os.environ.get("PREFECT_API_AUTH_STRING") if not raw: return None user, sep, password = raw.partition(":") if not sep: raise RuntimeError("PREFECT_API_AUTH_STRING must be user:password") return httpx.BasicAuth(user, password)
async def ensure_discord_block(h: httpx.AsyncClient, suffix: str) -> str: # The server action accepts Python-compatible DiscordWebhook by slug/name. # Use the canonical slug, falling back to the existing type if a previous # test run already created it. canonical = await h.get(f"{API_URL}/block_types/slug/discord-webhook") if canonical.status_code == 404: canonical = await h.post( f"{API_URL}/block_types/", json={"name": "Discord Webhook", "slug": "discord-webhook"}, ) canonical.raise_for_status() bt = canonical.json()
resp = await h.post( f"{API_URL}/block_schemas/", json={ "block_type_id": bt["id"], "fields": { "type": "object", "properties": { "webhook_id": {"type": "string"}, "webhook_token": {"type": "string"}, }, }, "capabilities": ["notify"], "version": f"test-{suffix}", }, ) resp.raise_for_status() bs = resp.json()
resp = await h.post( f"{API_URL}/block_documents/", json={ "name": f"discord-alerts-{suffix}", "block_type_id": bt["id"], "block_schema_id": bs["id"], "data": { "webhook_id": f"webhook-{suffix}", "webhook_token": f"token-{suffix}", }, }, ) resp.raise_for_status() return resp.json()["id"]
async def main(mode: str = "webhook", capture: Path | None = None) -> int: suffix = f"{mode}-{uuid.uuid4().hex[:8]}" expected_error = FAILURES.get(mode) expected_event = "prefect.automation.action.failed" if expected_error else "prefect.automation.action.executed" event_name = f"prefect.test.notification.{suffix}"
print(f"=== test-notifications ({suffix}) ===") print(f"API URL: {API_URL}")
async with httpx.AsyncClient(timeout=10, auth=auth()) as h: block_document_id = await ensure_discord_block(h, suffix) print(f"block_document: {block_document_id}")
async with get_client() as client: automation = AutomationCore( name=f"notification-{suffix}", trigger=EventTrigger( expect={event_name}, posture=Posture.Reactive, threshold=1, within=60, ), actions=[ SendNotification( block_document_id=uuid.UUID(block_document_id), subject="{{ deployment.name }} failed", body="{{ flow_run.name }} reached {{ state.name }}: {{ state.message }}", ) ], ) automation_id = await client.create_automation(automation) print(f"automation: {automation_id}")
print(f"waiting {CACHE_WAIT_SECONDS}s for automations cache refresh...") await asyncio.sleep(CACHE_WAIT_SECONDS)
emit_event( event=event_name, resource={ "prefect.resource.id": f"prefect.flow-run.{uuid.uuid4()}", "prefect.resource.name": f"notification-run-{suffix}", "prefect.state-type": "FAILED", "prefect.state-name": "Failed", }, related=[ { "prefect.resource.id": f"prefect.deployment.{uuid.uuid4()}", "prefect.resource.name": f"notification-deployment-{suffix}", "prefect.resource.role": "deployment", } ], payload={"validated_state": {"message": f"boom-{suffix}"}}, ) print(f"emitted: {event_name}")
deadline = time.time() + 20 async with httpx.AsyncClient(timeout=10, auth=auth()) as h: while time.time() < deadline: await asyncio.sleep(1) resp = await h.post( f"{API_URL}/events/filter", json={ "filter": {"event": {"name": ["prefect.automation.action.executed", "prefect.automation.action.failed"]}}, "limit": 200, }, ) if resp.status_code in (401, 403): print(f"✗ /events/filter returned {resp.status_code} — check PREFECT_API_AUTH_STRING") return 1 if resp.status_code != 200: continue for event in resp.json().get("events", []): resource = event.get("resource") or {} if resource.get("prefect.resource.id") == f"prefect.automation.{automation_id}": payload = event.get("payload") or {} related = event.get("related") or [] related_ids = {item.get("prefect.resource.id") for item in related if isinstance(item, dict)} if resource.get("prefect.trigger-type") != "event": print(f"✗ audit event missing trigger type: {resource}") return 1 if resource.get("prefect.posture") != "reactive": print(f"✗ audit event missing posture: {resource}") return 1 if payload.get("action_index") != 0: print(f"✗ audit event missing action_index: {payload}") return 1 if payload.get("invocation") is None: print(f"✗ audit event missing invocation: {payload}") return 1 if event.get("event") != expected_event or payload.get("reason") != expected_error: print(f"✗ expected {expected_event} / {expected_error}, got {event.get('event')} / {payload.get('reason')}") return 1 if capture is not None: records = [json.loads(line) for line in capture.read_text().splitlines()] sends = [record for record in records if f"token-{suffix}" in record["path"]] if len(sends) != 1: print(f"✗ expected exactly one webhook POST, got {len(sends)}") return 1 sent = sends[0] headers = {key.lower(): value for key, value in sent["headers"].items()} expected_content = f"**notification-deployment-{suffix} failed**\n\nnotification-run-{suffix} reached Failed: boom-{suffix}" if json.loads(sent["body"]) != {"content": expected_content}: print("✗ notification content changed") return 1 if headers.get("content-type") != "application/json" or headers.get("user-agent") != "prefect-zig-server": print("✗ notification request headers changed") return 1 if not sent["path"].endswith("?wait=true"): print("✗ Discord confirmation parameter missing") return 1 if expected_error: print(f"✓ send-notification failed with {expected_error}") return 0 if f"prefect.block-document.{block_document_id}" not in related_ids: print(f"✗ audit event missing block related resource: {related}") return 1 if "prefect.block-type.discord-webhook" not in related_ids: print(f"✗ audit event missing block-type related resource: {related}") return 1 print("✓ send-notification action executed") return 0
print(f"✗ no `{expected_event}` audit event for our automation within 20s") return 1
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--receiver-mode", choices=["webhook", *FAILURES], default="webhook") parser.add_argument("--capture", type=Path, help="Assert the local receiver captured one correctly formed POST") args = parser.parse_args() sys.exit(asyncio.run(main(args.receiver_mode, args.capture)))