resource-engine-fastapi 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- resource_engine_fastapi/__init__.py +39 -0
- resource_engine_fastapi/access.py +110 -0
- resource_engine_fastapi/asyncapi.py +47 -0
- resource_engine_fastapi/auth.py +158 -0
- resource_engine_fastapi/authz.py +100 -0
- resource_engine_fastapi/caching.py +111 -0
- resource_engine_fastapi/docs.py +77 -0
- resource_engine_fastapi/documents.py +219 -0
- resource_engine_fastapi/email_events.py +85 -0
- resource_engine_fastapi/errors.py +178 -0
- resource_engine_fastapi/events.py +109 -0
- resource_engine_fastapi/explorer/__init__.py +441 -0
- resource_engine_fastapi/explorer/assets/auth.js +171 -0
- resource_engine_fastapi/explorer/assets/console.js +340 -0
- resource_engine_fastapi/explorer/assets/events.js +189 -0
- resource_engine_fastapi/explorer/assets/explorer.css +156 -0
- resource_engine_fastapi/explorer/assets/explorer.js +275 -0
- resource_engine_fastapi/explorer/assets/jobs.js +143 -0
- resource_engine_fastapi/explorer/assets/messages.js +85 -0
- resource_engine_fastapi/explorer/assets/publish.js +117 -0
- resource_engine_fastapi/explorer/data.py +84 -0
- resource_engine_fastapi/explorer/events.py +182 -0
- resource_engine_fastapi/explorer/jobs.py +167 -0
- resource_engine_fastapi/explorer/labels.py +198 -0
- resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
- resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
- resource_engine_fastapi/explorer/messages.py +73 -0
- resource_engine_fastapi/explorer/publish.py +85 -0
- resource_engine_fastapi/exports.py +186 -0
- resource_engine_fastapi/i18n.py +76 -0
- resource_engine_fastapi/py.typed +0 -0
- resource_engine_fastapi/router.py +1031 -0
- resource_engine_fastapi/versioning.py +49 -0
- resource_engine_fastapi-0.1.0.dist-info/METADATA +32 -0
- resource_engine_fastapi-0.1.0.dist-info/RECORD +39 -0
- resource_engine_fastapi-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_fastapi-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/* PUB: publishing an event by hand. R.publish(resource, event) is the body
|
|
2
|
+
of a PUB row: the schema version, a payload to start from, a dry run
|
|
3
|
+
against the event and its consumers, and publishing through the outbox
|
|
4
|
+
(it needs "Allow changes" and typing the event's name). */
|
|
5
|
+
(function () {
|
|
6
|
+
var R = window.ResourceExplorer;
|
|
7
|
+
if (!R || !R.config.publish) return;
|
|
8
|
+
var L = R.labels, el = R.el, P = R.config.publish;
|
|
9
|
+
|
|
10
|
+
function problemsTable(problems) {
|
|
11
|
+
var head = el("tr", {}, [L.check, L.field, L.message].map(function (h) {
|
|
12
|
+
return el("th", { text: h });
|
|
13
|
+
}));
|
|
14
|
+
var rows = problems.map(function (p) {
|
|
15
|
+
return el("tr", {}, [
|
|
16
|
+
el("td", { text: p.check === "event" ? L.check_event : p.check.replace("consumer:", L.check_consumer + " ") }),
|
|
17
|
+
el("td", {}, [el("code", { text: p.path || "—" })]),
|
|
18
|
+
el("td", { text: p.message }),
|
|
19
|
+
]);
|
|
20
|
+
});
|
|
21
|
+
return el("div", { className: "table-wrap" }, [
|
|
22
|
+
el("table", {}, [el("thead", {}, [head]), el("tbody", {}, rows)])]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function form(resource, event) {
|
|
26
|
+
var versions = event.versions;
|
|
27
|
+
var version = el("select", { "aria-label": L.filter_version });
|
|
28
|
+
versions.forEach(function (v) {
|
|
29
|
+
version.appendChild(el("option", { value: v.version,
|
|
30
|
+
text: "v" + v.version + (v.deprecated ? " · " + L.deprecated : "") }));
|
|
31
|
+
});
|
|
32
|
+
version.value = versions[versions.length - 1].version;
|
|
33
|
+
var payload = el("textarea", { rows: "8", spellcheck: "false", "aria-label": L.payload });
|
|
34
|
+
function fill() {
|
|
35
|
+
var chosen = versions.filter(function (v) { return v.version === version.value; })[0];
|
|
36
|
+
payload.value = JSON.stringify(chosen.example, null, 2);
|
|
37
|
+
}
|
|
38
|
+
version.addEventListener("change", fill);
|
|
39
|
+
fill();
|
|
40
|
+
var confirm = el("input", { type: "text", spellcheck: "false", "aria-label": L.confirm_type,
|
|
41
|
+
placeholder: event.type });
|
|
42
|
+
var output = el("div", { className: "console-output", "aria-live": "polite" });
|
|
43
|
+
var check = el("button", { type: "button", className: "secondary", text: L.dry_run });
|
|
44
|
+
var send = el("button", { type: "button", className: "execute", text: L.publish });
|
|
45
|
+
|
|
46
|
+
function body() {
|
|
47
|
+
try {
|
|
48
|
+
return { type: event.type, version: Number(version.value), payload: JSON.parse(payload.value || "{}") };
|
|
49
|
+
} catch (e) {
|
|
50
|
+
output.textContent = L.bad_json + ": " + e.message;
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
check.addEventListener("click", function () {
|
|
56
|
+
var request = body();
|
|
57
|
+
if (!request) return;
|
|
58
|
+
output.textContent = L.sending;
|
|
59
|
+
R.call("POST", P.dry_run, request).then(function (result) {
|
|
60
|
+
output.textContent = "";
|
|
61
|
+
if (!result.ok || !result.data) { R.show(output, result); return; }
|
|
62
|
+
var problems = result.data.problems || [];
|
|
63
|
+
if (!problems.length) {
|
|
64
|
+
output.appendChild(el("p", { className: "console-status ok", text: L.no_problems }));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
output.appendChild(el("p", {
|
|
68
|
+
className: "console-status " + (result.data.blocking ? "fail" : "ok"),
|
|
69
|
+
text: result.data.blocking ? L.problems_blocking : L.problems_consumers }));
|
|
70
|
+
output.appendChild(problemsTable(problems));
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
send.addEventListener("click", function () {
|
|
75
|
+
if (!P.enabled) { output.textContent = L.publish_off; return; }
|
|
76
|
+
if (!R.allowed()) { output.textContent = L.changes_off; return; }
|
|
77
|
+
if (confirm.value.trim() !== event.type) {
|
|
78
|
+
output.textContent = R.labels.confirm_needed.replace("{type}", event.type);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
var request = body();
|
|
82
|
+
if (!request) return;
|
|
83
|
+
output.textContent = L.sending;
|
|
84
|
+
R.call("POST", P.publish, request).then(function (result) {
|
|
85
|
+
output.textContent = "";
|
|
86
|
+
if (!result.ok || !result.data) {
|
|
87
|
+
R.show(output, result);
|
|
88
|
+
var details = result.data && result.data.error && result.data.error.details;
|
|
89
|
+
if (Array.isArray(details)) output.appendChild(problemsTable(details));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
var envelopes = result.data.envelopes || [];
|
|
93
|
+
output.appendChild(el("p", { className: "console-status ok", text: L.published }));
|
|
94
|
+
output.appendChild(el("pre", { text: envelopes.map(function (e) {
|
|
95
|
+
return e.type + " v" + e.schema_version + " · " + e.id;
|
|
96
|
+
}).join("\n") }));
|
|
97
|
+
confirm.value = "";
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
var actions = el("div", { className: "wide" }, [check, send]);
|
|
102
|
+
if (!P.enabled) actions.appendChild(el("span", { className: "note", text: " " + L.publish_off }));
|
|
103
|
+
else if (!R.allowed()) actions.appendChild(el("span", { className: "note", text: " " + L.changes_off }));
|
|
104
|
+
return el("div", { className: "try-it" }, [
|
|
105
|
+
el("div", { className: "console-form" }, [
|
|
106
|
+
el("label", {}, [el("span", { text: L.filter_version }), version]),
|
|
107
|
+
el("label", { className: "required" }, [el("span", { text: L.confirm_type }), confirm]),
|
|
108
|
+
el("label", { className: "wide" }, [el("span", { text: L.payload }), payload]),
|
|
109
|
+
actions,
|
|
110
|
+
]),
|
|
111
|
+
el("p", { className: "note", text: L.publish_note }),
|
|
112
|
+
output,
|
|
113
|
+
]);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
R.publish = form;
|
|
117
|
+
})();
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""What the explorer's operations panel needs, from the OpenAPI document."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from resource_engine.schema_examples import example
|
|
9
|
+
|
|
10
|
+
METHODS = ("get", "post", "put", "patch", "delete")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def console_data(openapi: Mapping[str, Any], resources: list[str]) -> dict[str, Any]:
|
|
14
|
+
"""What the try-it console needs, per resource: each operation's method,
|
|
15
|
+
path, parameters, a JSON body to start from, and its permission action
|
|
16
|
+
(for ``/authz/explain``)."""
|
|
17
|
+
schemas = openapi.get("components", {}).get("schemas", {})
|
|
18
|
+
out: dict[str, list[dict[str, Any]]] = {name: [] for name in resources}
|
|
19
|
+
for path, item in openapi.get("paths", {}).items():
|
|
20
|
+
for method in METHODS:
|
|
21
|
+
if method not in item:
|
|
22
|
+
continue
|
|
23
|
+
operation = item[method]
|
|
24
|
+
resource = (operation.get("tags") or [None])[0]
|
|
25
|
+
if resource not in out:
|
|
26
|
+
continue
|
|
27
|
+
body = None
|
|
28
|
+
content = operation.get("requestBody", {}).get("content", {})
|
|
29
|
+
if "application/json" in content:
|
|
30
|
+
body = example(content["application/json"].get("schema", {}), schemas)
|
|
31
|
+
ok = operation.get("responses", {}).get("200", {}).get("content", {})
|
|
32
|
+
out[resource].append(
|
|
33
|
+
{
|
|
34
|
+
# a file, not JSON: the console offers it for download
|
|
35
|
+
"download": bool(ok) and "application/json" not in ok,
|
|
36
|
+
# starting an export changes no data
|
|
37
|
+
"safe": method == "post" and path.endswith("/exports"),
|
|
38
|
+
"method": method.upper(),
|
|
39
|
+
"path": path,
|
|
40
|
+
"summary": operation.get("summary") or "",
|
|
41
|
+
"action": catalogue_action(resource, method.upper(), path),
|
|
42
|
+
"params": [
|
|
43
|
+
{
|
|
44
|
+
"name": p["name"],
|
|
45
|
+
"in": p["in"],
|
|
46
|
+
"required": bool(p.get("required")),
|
|
47
|
+
"description": p.get("description") or "",
|
|
48
|
+
}
|
|
49
|
+
for p in operation.get("parameters", [])
|
|
50
|
+
if p["in"] in ("path", "query", "header")
|
|
51
|
+
],
|
|
52
|
+
"body": body,
|
|
53
|
+
"upload": "multipart/form-data" in content,
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
return {"resources": out}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def catalogue_action(resource: str, method: str, path: str) -> str | None:
|
|
60
|
+
"""The permission action of a route: ``POST /invoices/{id}/transitions/approve``
|
|
61
|
+
→ ``invoices:transition:approve``."""
|
|
62
|
+
parts = [p for p in path.strip("/").split("/") if p]
|
|
63
|
+
if not parts or parts[0] != resource:
|
|
64
|
+
return None
|
|
65
|
+
rest = parts[1:]
|
|
66
|
+
if not rest:
|
|
67
|
+
return f"{resource}:{'list' if method == 'GET' else 'create'}"
|
|
68
|
+
if rest in (["export"], ["exports"]):
|
|
69
|
+
return f"{resource}:list"
|
|
70
|
+
if len(rest) == 3 and rest[1] == "printouts":
|
|
71
|
+
return f"{resource}:get"
|
|
72
|
+
if len(rest) == 1 and rest[0].startswith("{"):
|
|
73
|
+
return f"{resource}:" + {"GET": "get", "PATCH": "update", "PUT": "update"}.get(
|
|
74
|
+
method, "delete"
|
|
75
|
+
)
|
|
76
|
+
if len(rest) >= 3 and rest[1] in ("transitions", "actions"):
|
|
77
|
+
kind = "transition" if rest[1] == "transitions" else "action"
|
|
78
|
+
return f"{resource}:{kind}:{rest[2]}"
|
|
79
|
+
if len(rest) == 2 and rest[0] == "actions":
|
|
80
|
+
return f"{resource}:action:{rest[1]}"
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
__all__ = ["METHODS", "catalogue_action", "console_data", "example"]
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""The explorer's live events: committed events over server-sent events.
|
|
2
|
+
|
|
3
|
+
- ``GET <api>/events/stream``: ``text/event-stream``; each event is a frame
|
|
4
|
+
``event: event``, ``id: <envelope id>``, ``data: {"envelope", "resource",
|
|
5
|
+
"entity_id", "record", "payload_visible"}``. A comment every
|
|
6
|
+
``keepalive`` seconds keeps proxies from closing a quiet stream.
|
|
7
|
+
- ``GET <api>/events/{message_id}/deliveries``: which consumers handled an
|
|
8
|
+
event and how (an ``ActivityLog``).
|
|
9
|
+
|
|
10
|
+
Visibility is ``LiveEvents``'s: events about records the caller can read; the
|
|
11
|
+
payload, and events about no record, only with ``events:read``. Opening a
|
|
12
|
+
stream is audited.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import contextlib
|
|
19
|
+
import json
|
|
20
|
+
from collections.abc import AsyncIterator
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from fastapi import APIRouter, Depends, Query, Request
|
|
24
|
+
from fastapi.responses import StreamingResponse
|
|
25
|
+
from pydantic import TypeAdapter
|
|
26
|
+
from resource_engine.errors import PermissionDenied
|
|
27
|
+
from resource_engine.explorer import EVENTS_READ, allowed, require
|
|
28
|
+
from resource_engine.messaging import LiveEvent, LiveEvents
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _frame(event: LiveEvent) -> str:
|
|
32
|
+
envelope = event.envelope.to_dict()
|
|
33
|
+
if not event.payload_visible:
|
|
34
|
+
envelope.pop("payload", None)
|
|
35
|
+
record = event.record
|
|
36
|
+
if record is not None:
|
|
37
|
+
from resource_engine.integration import dump_read
|
|
38
|
+
|
|
39
|
+
record = dump_read(record)
|
|
40
|
+
data = {
|
|
41
|
+
"envelope": envelope,
|
|
42
|
+
"resource": event.resource,
|
|
43
|
+
"entity_id": event.entity_id,
|
|
44
|
+
"record": record,
|
|
45
|
+
"payload_visible": event.payload_visible,
|
|
46
|
+
}
|
|
47
|
+
body = json.dumps(TypeAdapter(Any).dump_python(data, mode="json"), ensure_ascii=False)
|
|
48
|
+
return f"event: event\nid: {event.envelope.id}\ndata: {body}\n\n"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_events_router(
|
|
52
|
+
manager: Any,
|
|
53
|
+
hub: Any,
|
|
54
|
+
*,
|
|
55
|
+
actor_dependency: Any,
|
|
56
|
+
activity: Any = None,
|
|
57
|
+
open: bool = False,
|
|
58
|
+
keepalive: float = 15.0,
|
|
59
|
+
) -> APIRouter:
|
|
60
|
+
"""The explorer's live events: a server-sent event stream and each message's deliveries."""
|
|
61
|
+
router = APIRouter(prefix="/events", tags=["explorer"])
|
|
62
|
+
live = LiveEvents(manager, hub)
|
|
63
|
+
|
|
64
|
+
async def check(actor: Any, resource: str | None, tenant: str | None) -> bool:
|
|
65
|
+
"""Whether ``actor`` holds ``events:read`` (everything); otherwise they
|
|
66
|
+
need ``get`` on the resource they filter on, or on some resource."""
|
|
67
|
+
if await allowed(manager, actor, EVENTS_READ.name, open=open):
|
|
68
|
+
return True
|
|
69
|
+
if manager.authorizer is None:
|
|
70
|
+
await require(manager, actor, EVENTS_READ.name, open=open) # raises
|
|
71
|
+
names = [resource] if resource else [d.name for d in manager.registry if d.exposed("get")]
|
|
72
|
+
for name in names:
|
|
73
|
+
if await manager.can(actor, name, "get", tenant=tenant):
|
|
74
|
+
return False
|
|
75
|
+
await manager.audit_event(actor, EVENTS_READ.name, "denied", details={"resource": resource})
|
|
76
|
+
raise PermissionDenied(
|
|
77
|
+
"Not allowed to see events" + (f" about {resource}" if resource else ""),
|
|
78
|
+
details={"action": f"{resource}:get" if resource else EVENTS_READ.name},
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
@router.get(
|
|
82
|
+
"/stream",
|
|
83
|
+
summary="Committed events, live (server-sent events)",
|
|
84
|
+
response_class=StreamingResponse,
|
|
85
|
+
responses={200: {"content": {"text/event-stream": {}}}},
|
|
86
|
+
operation_id="explorer_event_stream",
|
|
87
|
+
)
|
|
88
|
+
async def stream(
|
|
89
|
+
request: Request,
|
|
90
|
+
resource: str | None = Query(None, description="Only events about this resource"),
|
|
91
|
+
id: str | None = Query(None, description="Only events about this record (with resource)"),
|
|
92
|
+
type: list[str] = Query([], description="Only these event types"),
|
|
93
|
+
version: list[str] = Query([], description="Only these schema versions"),
|
|
94
|
+
tenant: str | None = Query(None, description="Tenant (cross-tenant callers)"),
|
|
95
|
+
actor: Any = Depends(actor_dependency),
|
|
96
|
+
) -> StreamingResponse:
|
|
97
|
+
if resource is not None:
|
|
98
|
+
manager.registry.get(resource) # RE-E002 for an unknown resource
|
|
99
|
+
everything = await check(actor, resource, tenant)
|
|
100
|
+
await manager.audit_event(
|
|
101
|
+
actor,
|
|
102
|
+
EVENTS_READ.name if everything else "events:stream",
|
|
103
|
+
details={"resource": resource, "id": id, "types": type, "versions": version},
|
|
104
|
+
)
|
|
105
|
+
events = live.stream(
|
|
106
|
+
actor,
|
|
107
|
+
tenant=tenant,
|
|
108
|
+
resource=resource,
|
|
109
|
+
entity_id=id if resource else None,
|
|
110
|
+
types=type,
|
|
111
|
+
versions=version,
|
|
112
|
+
everything=everything,
|
|
113
|
+
)
|
|
114
|
+
return StreamingResponse(
|
|
115
|
+
_sse(events, request, keepalive),
|
|
116
|
+
media_type="text/event-stream",
|
|
117
|
+
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
if activity is not None:
|
|
121
|
+
|
|
122
|
+
@router.get(
|
|
123
|
+
"/{message_id}/deliveries",
|
|
124
|
+
summary="Which consumers handled an event, and how",
|
|
125
|
+
operation_id="explorer_event_deliveries",
|
|
126
|
+
)
|
|
127
|
+
async def deliveries(
|
|
128
|
+
message_id: str, actor: Any = Depends(actor_dependency)
|
|
129
|
+
) -> list[dict[str, Any]]:
|
|
130
|
+
await check(actor, None, None)
|
|
131
|
+
return [
|
|
132
|
+
{
|
|
133
|
+
"consumer": d.consumer,
|
|
134
|
+
"event_type": d.event_type,
|
|
135
|
+
"outcome": d.outcome,
|
|
136
|
+
"seconds": d.seconds,
|
|
137
|
+
"error": d.error,
|
|
138
|
+
"at": d.at.isoformat(),
|
|
139
|
+
}
|
|
140
|
+
for d in await activity.deliveries(message_id)
|
|
141
|
+
]
|
|
142
|
+
|
|
143
|
+
return router
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def _sse(
|
|
147
|
+
events: AsyncIterator[LiveEvent], request: Request, keepalive: float
|
|
148
|
+
) -> AsyncIterator[str]:
|
|
149
|
+
"""Frames from ``events`` and a comment every ``keepalive`` seconds, until
|
|
150
|
+
the client goes away."""
|
|
151
|
+
yield ": connected\n\n"
|
|
152
|
+
iterator = events.__aiter__()
|
|
153
|
+
pending: asyncio.Task[LiveEvent] | None = None
|
|
154
|
+
try:
|
|
155
|
+
while True:
|
|
156
|
+
if pending is None:
|
|
157
|
+
pending = asyncio.ensure_future(iterator.__anext__())
|
|
158
|
+
done, _ = await asyncio.wait({pending}, timeout=keepalive)
|
|
159
|
+
if await request.is_disconnected():
|
|
160
|
+
return
|
|
161
|
+
if not done:
|
|
162
|
+
yield ": keepalive\n\n"
|
|
163
|
+
continue
|
|
164
|
+
try:
|
|
165
|
+
event = pending.result()
|
|
166
|
+
except StopAsyncIteration:
|
|
167
|
+
return
|
|
168
|
+
finally:
|
|
169
|
+
pending = None
|
|
170
|
+
yield _frame(event)
|
|
171
|
+
finally:
|
|
172
|
+
if pending is not None:
|
|
173
|
+
pending.cancel()
|
|
174
|
+
with contextlib.suppress(BaseException):
|
|
175
|
+
await pending
|
|
176
|
+
closing = getattr(iterator, "aclose", None)
|
|
177
|
+
if closing is not None:
|
|
178
|
+
with contextlib.suppress(BaseException):
|
|
179
|
+
await closing()
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
__all__ = ["build_events_router"]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The explorer's jobs: what the workers run, their runs, "run now", and
|
|
2
|
+
the timed transitions waiting on a record.
|
|
3
|
+
|
|
4
|
+
- ``GET <api>/jobs``: every job the workers registered, with its schedule
|
|
5
|
+
and last run (``jobs:read``).
|
|
6
|
+
- ``GET <api>/jobs/{name}/runs``: its recent runs (``jobs:read``).
|
|
7
|
+
- ``POST <api>/jobs/{name}/run``: ask a worker to run it now (``jobs:run``,
|
|
8
|
+
audited). The worker claims the request and runs the job through its
|
|
9
|
+
runner, so a ``single`` job's lease holds.
|
|
10
|
+
- ``GET <api>/jobs/requests/{id}``: that request's status (``jobs:read``).
|
|
11
|
+
- ``GET <api>/timers/{resource}/{id}``: the record's pending timed
|
|
12
|
+
transitions (``get`` on the record).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from fastapi import APIRouter, Depends, Query, status
|
|
20
|
+
from fastapi.responses import JSONResponse
|
|
21
|
+
from resource_engine.errors import EntityNotFound
|
|
22
|
+
from resource_engine.explorer import JOBS_READ, JOBS_RUN, require
|
|
23
|
+
from resource_engine.integration import pending_timers
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _iso(value: Any) -> str | None:
|
|
27
|
+
return value.isoformat() if value is not None else None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _run(run: Any) -> dict[str, Any]:
|
|
31
|
+
return {
|
|
32
|
+
"job": run.job,
|
|
33
|
+
"outcome": run.outcome,
|
|
34
|
+
"seconds": run.seconds,
|
|
35
|
+
"owner": run.owner,
|
|
36
|
+
"error": run.error,
|
|
37
|
+
"at": _iso(run.at),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _request(request: Any) -> dict[str, Any]:
|
|
42
|
+
return {
|
|
43
|
+
"id": request.id,
|
|
44
|
+
"job": request.job,
|
|
45
|
+
"status": request.status,
|
|
46
|
+
"requested_by": request.requested_by,
|
|
47
|
+
"requested_at": _iso(request.requested_at),
|
|
48
|
+
"claimed_by": request.claimed_by,
|
|
49
|
+
"finished_at": _iso(request.finished_at),
|
|
50
|
+
"error": request.error,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def build_jobs_router(
|
|
55
|
+
manager: Any, activity: Any, *, actor_dependency: Any, open: bool = False
|
|
56
|
+
) -> APIRouter:
|
|
57
|
+
"""The explorer's jobs: schedules, recent runs, run requests and a record's timers."""
|
|
58
|
+
router = APIRouter(tags=["explorer"])
|
|
59
|
+
|
|
60
|
+
async def known_jobs() -> dict[str, dict[str, Any]]:
|
|
61
|
+
jobs: dict[str, dict[str, Any]] = {}
|
|
62
|
+
for worker in await activity.workers():
|
|
63
|
+
for info in worker.jobs:
|
|
64
|
+
entry = jobs.setdefault(
|
|
65
|
+
info.name,
|
|
66
|
+
{
|
|
67
|
+
"name": info.name,
|
|
68
|
+
"every": info.every,
|
|
69
|
+
"single": info.single,
|
|
70
|
+
"ttl": info.ttl,
|
|
71
|
+
"run_at_start": info.run_at_start,
|
|
72
|
+
"workers": [],
|
|
73
|
+
},
|
|
74
|
+
)
|
|
75
|
+
entry["workers"].append(worker.owner)
|
|
76
|
+
return jobs
|
|
77
|
+
|
|
78
|
+
@router.get("/jobs", summary="The workers' jobs and their last runs",
|
|
79
|
+
operation_id="explorer_jobs") # fmt: skip
|
|
80
|
+
async def jobs(actor: Any = Depends(actor_dependency)) -> dict[str, Any]:
|
|
81
|
+
await require(manager, actor, JOBS_READ.name, open=open)
|
|
82
|
+
known = await known_jobs()
|
|
83
|
+
for name, entry in known.items():
|
|
84
|
+
last = await activity.job_runs(name, limit=1)
|
|
85
|
+
entry["last_run"] = _run(last[0]) if last else None
|
|
86
|
+
return {
|
|
87
|
+
"workers": [
|
|
88
|
+
{"owner": w.owner, "seen_at": _iso(w.seen_at), "jobs": [j.name for j in w.jobs]}
|
|
89
|
+
for w in await activity.workers()
|
|
90
|
+
],
|
|
91
|
+
"jobs": sorted(known.values(), key=lambda j: j["name"]),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
@router.get("/jobs/requests/{request_id}", summary="A run-now request",
|
|
95
|
+
operation_id="explorer_job_request") # fmt: skip
|
|
96
|
+
async def job_request(request_id: str, actor: Any = Depends(actor_dependency)) -> Any:
|
|
97
|
+
await require(manager, actor, JOBS_READ.name, open=open)
|
|
98
|
+
request = await activity.run_request(request_id)
|
|
99
|
+
if request is None:
|
|
100
|
+
raise EntityNotFound(f"Run request {request_id!r} does not exist")
|
|
101
|
+
return _request(request)
|
|
102
|
+
|
|
103
|
+
@router.get("/jobs/{name}/runs", summary="A job's recent runs",
|
|
104
|
+
operation_id="explorer_job_runs") # fmt: skip
|
|
105
|
+
async def job_runs(
|
|
106
|
+
name: str,
|
|
107
|
+
limit: int = Query(20, ge=1, le=200),
|
|
108
|
+
actor: Any = Depends(actor_dependency),
|
|
109
|
+
) -> list[dict[str, Any]]:
|
|
110
|
+
await require(manager, actor, JOBS_READ.name, open=open)
|
|
111
|
+
return [_run(r) for r in await activity.job_runs(name, limit=limit)]
|
|
112
|
+
|
|
113
|
+
@router.post(
|
|
114
|
+
"/jobs/{name}/run",
|
|
115
|
+
summary="Ask a worker to run a job now",
|
|
116
|
+
status_code=status.HTTP_202_ACCEPTED,
|
|
117
|
+
operation_id="explorer_run_job",
|
|
118
|
+
)
|
|
119
|
+
async def run_job(name: str, actor: Any = Depends(actor_dependency)) -> JSONResponse:
|
|
120
|
+
await require(manager, actor, JOBS_RUN.name, open=open)
|
|
121
|
+
if name not in await known_jobs():
|
|
122
|
+
raise EntityNotFound(
|
|
123
|
+
f"No worker runs a job named {name!r}",
|
|
124
|
+
hint="GET /jobs lists the jobs the running workers registered.",
|
|
125
|
+
)
|
|
126
|
+
from resource_engine.integration import actor_id
|
|
127
|
+
|
|
128
|
+
who = actor if isinstance(actor, str) else actor_id(actor)
|
|
129
|
+
request = await activity.request_run(name, who)
|
|
130
|
+
await manager.audit_event(
|
|
131
|
+
actor, JOBS_RUN.name, details={"job": name, "request": request.id}
|
|
132
|
+
)
|
|
133
|
+
return JSONResponse(_request(request), status_code=status.HTTP_202_ACCEPTED)
|
|
134
|
+
|
|
135
|
+
@router.get(
|
|
136
|
+
"/timers/{resource}/{entity_id}",
|
|
137
|
+
summary="The timed transitions waiting on a record",
|
|
138
|
+
operation_id="explorer_record_timers",
|
|
139
|
+
)
|
|
140
|
+
async def timers(
|
|
141
|
+
resource: str,
|
|
142
|
+
entity_id: str,
|
|
143
|
+
tenant: str | None = Query(None),
|
|
144
|
+
actor: Any = Depends(actor_dependency),
|
|
145
|
+
) -> list[dict[str, Any]]:
|
|
146
|
+
from pydantic import TypeAdapter
|
|
147
|
+
|
|
148
|
+
definition = manager.registry.get(resource)
|
|
149
|
+
typed = TypeAdapter(definition.id_type).validate_python(entity_id)
|
|
150
|
+
found = await pending_timers(manager, resource, typed, actor=actor, tenant=tenant)
|
|
151
|
+
return [
|
|
152
|
+
{
|
|
153
|
+
"event": t.event,
|
|
154
|
+
"due_at": _iso(t.due_at),
|
|
155
|
+
"overdue": t.overdue,
|
|
156
|
+
"since": t.since,
|
|
157
|
+
"after_seconds": t.after.total_seconds(),
|
|
158
|
+
"states": [str(getattr(s, "value", s)) for s in t.states],
|
|
159
|
+
"description": t.description,
|
|
160
|
+
}
|
|
161
|
+
for t in found
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
return router
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
__all__ = ["build_jobs_router"]
|