dap-engine 0.3.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.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
dap_engine/api/health.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from fastapi import APIRouter, Request
|
|
7
|
+
|
|
8
|
+
router = APIRouter()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@router.get("/health")
|
|
12
|
+
async def health(request: Request) -> dict[str, Any]:
|
|
13
|
+
dialect: str = getattr(request.app.state, "db_dialect", "sqlite")
|
|
14
|
+
return {
|
|
15
|
+
"status": "ok",
|
|
16
|
+
"service": "dap-engine",
|
|
17
|
+
"version": "0.0.1",
|
|
18
|
+
"db_dialect": dialect,
|
|
19
|
+
"timestamp": datetime.now(UTC).isoformat(),
|
|
20
|
+
}
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""REST CRUD for pipelines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from dap_types import Pipeline
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
from sqlalchemy.orm import Session
|
|
12
|
+
|
|
13
|
+
from dap_engine.api.agents import build_agent_export_payload
|
|
14
|
+
from dap_engine.api.deps import get_session
|
|
15
|
+
from dap_engine.api.schemas import (
|
|
16
|
+
PIPELINE_EXPORT_SCHEMA_VERSION,
|
|
17
|
+
AgentExportPayload,
|
|
18
|
+
PipelineExport,
|
|
19
|
+
PipelineExportPayload,
|
|
20
|
+
PipelineImportRequest,
|
|
21
|
+
)
|
|
22
|
+
from dap_engine.auth.users import current_active_user
|
|
23
|
+
from dap_engine.contracts import AgentCreate, PipelineCreate, PipelineUpdate
|
|
24
|
+
from dap_engine.execution import ValidationResult, validate_pipeline_dag
|
|
25
|
+
from dap_engine.persistence import repository as repo
|
|
26
|
+
from dap_engine.persistence.models import UserORM
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger("dap.engine.pipelines")
|
|
29
|
+
|
|
30
|
+
router = APIRouter(prefix="/pipelines", tags=["pipelines"])
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@router.get("")
|
|
34
|
+
def list_pipelines(
|
|
35
|
+
session: Session = Depends(get_session),
|
|
36
|
+
user: UserORM = Depends(current_active_user),
|
|
37
|
+
archived: bool = Query(default=False),
|
|
38
|
+
offset: int = Query(default=0, ge=0),
|
|
39
|
+
limit: int = Query(default=50, ge=1, le=500),
|
|
40
|
+
) -> dict[str, Any]:
|
|
41
|
+
items, total = repo.list_pipelines(
|
|
42
|
+
session,
|
|
43
|
+
actor_id=user.id,
|
|
44
|
+
is_admin=user.is_superuser,
|
|
45
|
+
archived=archived,
|
|
46
|
+
offset=offset,
|
|
47
|
+
limit=limit,
|
|
48
|
+
)
|
|
49
|
+
return {
|
|
50
|
+
"items": [p.model_dump(mode="json") for p in items],
|
|
51
|
+
"total": total,
|
|
52
|
+
"offset": offset,
|
|
53
|
+
"limit": limit,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _enforce_validation(payload: PipelineCreate, session: Session) -> ValidationResult:
|
|
58
|
+
"""Run the DAG validator and raise 422 on any errors.
|
|
59
|
+
|
|
60
|
+
Used by ``create_pipeline`` and ``update_pipeline`` so a structurally
|
|
61
|
+
broken or cohesion-incomplete pipeline can never land in the DB.
|
|
62
|
+
The standalone ``POST /pipelines/validate`` endpoint stays intact —
|
|
63
|
+
it's still useful for live feedback in the Pipeline Designer
|
|
64
|
+
*before* the user clicks Save.
|
|
65
|
+
|
|
66
|
+
Warnings are not fatal — they're operator hints (unused outputs,
|
|
67
|
+
conflicting writers, etc.) and get logged here so operators see
|
|
68
|
+
them in engine output. They also ride along on the 422 ``detail``
|
|
69
|
+
when validation does fail, in case a related warning makes the
|
|
70
|
+
error easier to interpret.
|
|
71
|
+
"""
|
|
72
|
+
result = validate_pipeline_dag(payload, session)
|
|
73
|
+
if result.warnings:
|
|
74
|
+
logger.warning(
|
|
75
|
+
"pipeline validation warnings: %s",
|
|
76
|
+
"; ".join(result.warnings),
|
|
77
|
+
)
|
|
78
|
+
if not result.valid:
|
|
79
|
+
raise HTTPException(
|
|
80
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
81
|
+
detail={
|
|
82
|
+
"errors": result.errors,
|
|
83
|
+
"warnings": result.warnings,
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
return result
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _update_to_create_shape(payload: PipelineUpdate) -> PipelineCreate:
|
|
90
|
+
"""Adapt a ``PipelineUpdate`` into a ``PipelineCreate`` for the validator.
|
|
91
|
+
|
|
92
|
+
The DAG validator only inspects ``entry_point`` / ``nodes`` /
|
|
93
|
+
``edges`` / ``defaults`` — fields shared between the two types.
|
|
94
|
+
Update-specific nullables (``name``, ``description``) get
|
|
95
|
+
placeholders that satisfy the Create model's ``min_length=1``
|
|
96
|
+
constraint without leaking into the actual DB write (the repo
|
|
97
|
+
handles the update via the original ``PipelineUpdate``).
|
|
98
|
+
"""
|
|
99
|
+
return PipelineCreate(
|
|
100
|
+
name=payload.name or "(unchanged)",
|
|
101
|
+
description=payload.description or "",
|
|
102
|
+
schema_version=payload.schema_version,
|
|
103
|
+
state_schema_ref=payload.state_schema_ref,
|
|
104
|
+
entry_point=payload.entry_point,
|
|
105
|
+
nodes=payload.nodes,
|
|
106
|
+
edges=payload.edges,
|
|
107
|
+
defaults=payload.defaults,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@router.post("", status_code=status.HTTP_201_CREATED, response_model=Pipeline)
|
|
112
|
+
def create_pipeline(
|
|
113
|
+
payload: PipelineCreate,
|
|
114
|
+
session: Session = Depends(get_session),
|
|
115
|
+
user: UserORM = Depends(current_active_user),
|
|
116
|
+
) -> Pipeline:
|
|
117
|
+
"""Create a pipeline (v1). Rejects invalid DAGs with 422 (#120).
|
|
118
|
+
|
|
119
|
+
Validation happens *before* the DB write so a broken pipeline
|
|
120
|
+
can never become persistent. The same checks the Pipeline
|
|
121
|
+
Designer surfaces interactively are now enforced server-side.
|
|
122
|
+
"""
|
|
123
|
+
_enforce_validation(payload, session)
|
|
124
|
+
return repo.create_pipeline(session, payload, user_id=user.id)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@router.post("/validate", response_model=ValidationResult)
|
|
128
|
+
def validate_pipeline(
|
|
129
|
+
payload: PipelineCreate,
|
|
130
|
+
session: Session = Depends(get_session),
|
|
131
|
+
_user: UserORM = Depends(current_active_user),
|
|
132
|
+
) -> ValidationResult:
|
|
133
|
+
"""Pre-save DAG validation — used by Pipeline Designer before submitting.
|
|
134
|
+
|
|
135
|
+
Returns 200 with `valid: false` and a list of errors when invalid;
|
|
136
|
+
422 only on Pydantic-level errors (malformed body). The save
|
|
137
|
+
endpoints (``POST`` / ``PUT``) call the same validator and turn
|
|
138
|
+
any errors into 422 — this endpoint stays as the live-feedback
|
|
139
|
+
surface so the Designer can show diagnostics without committing.
|
|
140
|
+
|
|
141
|
+
Auth-required even though it's read-only: the validator hits the
|
|
142
|
+
agents table to check ``node.agent_id`` references, so leaving it
|
|
143
|
+
open would leak which agent ids exist in the DB to anonymous
|
|
144
|
+
callers. The ``_user`` parameter exists purely to wire the auth
|
|
145
|
+
dependency — its value isn't read, the leading underscore signals
|
|
146
|
+
that to readers and to ``ruff`` rule ``PLW0613``.
|
|
147
|
+
"""
|
|
148
|
+
return validate_pipeline_dag(payload, session)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@router.post(
|
|
152
|
+
"/import",
|
|
153
|
+
status_code=status.HTTP_201_CREATED,
|
|
154
|
+
response_model=Pipeline,
|
|
155
|
+
)
|
|
156
|
+
def import_pipeline(
|
|
157
|
+
payload: PipelineImportRequest,
|
|
158
|
+
session: Session = Depends(get_session),
|
|
159
|
+
user: UserORM = Depends(current_active_user),
|
|
160
|
+
) -> Pipeline:
|
|
161
|
+
"""Create a new pipeline (v1) from an exported JSON payload (#124).
|
|
162
|
+
|
|
163
|
+
Two paths share this endpoint:
|
|
164
|
+
|
|
165
|
+
- **Pipeline-only** (``bundled_agents`` absent): same as Phase 1.
|
|
166
|
+
Referenced agents must already exist in this DB or the DAG
|
|
167
|
+
validator returns 422.
|
|
168
|
+
- **Bundle** (``bundled_agents`` present, #126): creates each
|
|
169
|
+
bundled agent first, builds an ``old_id → new_id`` remap,
|
|
170
|
+
rewrites every ``node.agent_id`` in the pipeline payload,
|
|
171
|
+
then runs the standard validator + create path. The whole
|
|
172
|
+
thing rides the request session, so a failure anywhere
|
|
173
|
+
(agent validation, pipeline validation, repo write) rolls
|
|
174
|
+
back the agents that were created earlier — no orphans
|
|
175
|
+
land in the DB.
|
|
176
|
+
|
|
177
|
+
Round-trips agents/pipeline through their ``Create`` types so
|
|
178
|
+
any future field added flows automatically rather than relying
|
|
179
|
+
on this function staying in lockstep with three models.
|
|
180
|
+
"""
|
|
181
|
+
bundled = payload.bundled_agents
|
|
182
|
+
pipeline_payload = payload.pipeline
|
|
183
|
+
|
|
184
|
+
# Bundle mode is keyed on *presence* of the field, not truthiness
|
|
185
|
+
# — the contract is "bundle if the caller chose to send it",
|
|
186
|
+
# which an empty dict still expresses (no agents to remap, but
|
|
187
|
+
# the user explicitly opted in). Keeps the contract documented
|
|
188
|
+
# in :class:`PipelineImportRequest` accurate.
|
|
189
|
+
if bundled is not None:
|
|
190
|
+
# Step 1 — create bundled agents (no inter-agent ordering
|
|
191
|
+
# required today). Build the remap from source ids to
|
|
192
|
+
# fresh local ids.
|
|
193
|
+
id_remap: dict[str, str] = {}
|
|
194
|
+
for source_id, agent_payload in bundled.items():
|
|
195
|
+
try:
|
|
196
|
+
agent_create = AgentCreate.model_validate(agent_payload.model_dump())
|
|
197
|
+
except ValidationError as exc:
|
|
198
|
+
# Keep the structured Pydantic error list intact
|
|
199
|
+
# under ``agent_validation_errors`` so frontends can
|
|
200
|
+
# surface field-level issues. ``errors`` keeps the
|
|
201
|
+
# human-friendly summary the rest of the import
|
|
202
|
+
# paths use, including the offending source id so
|
|
203
|
+
# operators know which entry in the bundle broke.
|
|
204
|
+
raise HTTPException(
|
|
205
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
206
|
+
detail={
|
|
207
|
+
"errors": [
|
|
208
|
+
f"bundled_agents['{source_id}'] is not a valid agent payload",
|
|
209
|
+
],
|
|
210
|
+
"warnings": [],
|
|
211
|
+
"agent_validation_errors": exc.errors(),
|
|
212
|
+
"source_id": source_id,
|
|
213
|
+
},
|
|
214
|
+
) from exc
|
|
215
|
+
new_agent = repo.create_agent(session, agent_create, user_id=user.id)
|
|
216
|
+
id_remap[source_id] = new_agent.id
|
|
217
|
+
|
|
218
|
+
# Step 2 — rewrite node.agent_id in the pipeline payload.
|
|
219
|
+
# Nodes whose agent_id isn't in the bundle keep their
|
|
220
|
+
# original string; the validator will catch them if they
|
|
221
|
+
# don't exist locally either (legitimate use case: a
|
|
222
|
+
# partial bundle that relies on some pre-existing agents).
|
|
223
|
+
rewritten_nodes = [
|
|
224
|
+
node.model_copy(
|
|
225
|
+
update={"agent_id": id_remap.get(node.agent_id, node.agent_id)},
|
|
226
|
+
)
|
|
227
|
+
for node in pipeline_payload.nodes
|
|
228
|
+
]
|
|
229
|
+
pipeline_payload = pipeline_payload.model_copy(update={"nodes": rewritten_nodes})
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
create_payload = PipelineCreate.model_validate(pipeline_payload.model_dump())
|
|
233
|
+
except ValidationError as exc:
|
|
234
|
+
raise HTTPException(
|
|
235
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
236
|
+
detail=exc.errors(),
|
|
237
|
+
) from exc
|
|
238
|
+
|
|
239
|
+
# ``_enforce_validation`` raises 422 on any DAG / cohesion
|
|
240
|
+
# error. The session-wide rollback in ``get_session`` then
|
|
241
|
+
# tears down the bundled agents created above — no orphans.
|
|
242
|
+
_enforce_validation(create_payload, session)
|
|
243
|
+
return repo.create_pipeline(session, create_payload, user_id=user.id)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@router.get("/{pipeline_id}", response_model=Pipeline)
|
|
247
|
+
def get_pipeline(
|
|
248
|
+
pipeline_id: str,
|
|
249
|
+
session: Session = Depends(get_session),
|
|
250
|
+
user: UserORM = Depends(current_active_user),
|
|
251
|
+
) -> Pipeline:
|
|
252
|
+
try:
|
|
253
|
+
return repo.get_pipeline(session, pipeline_id, actor_id=user.id, is_admin=user.is_superuser)
|
|
254
|
+
except repo.NotFoundError as exc:
|
|
255
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@router.put("/{pipeline_id}", response_model=Pipeline)
|
|
259
|
+
def update_pipeline(
|
|
260
|
+
pipeline_id: str,
|
|
261
|
+
payload: PipelineUpdate,
|
|
262
|
+
session: Session = Depends(get_session),
|
|
263
|
+
user: UserORM = Depends(current_active_user),
|
|
264
|
+
) -> Pipeline:
|
|
265
|
+
"""Update a pipeline (creates a new version). Rejects invalid DAGs with 422 (#120).
|
|
266
|
+
|
|
267
|
+
Same enforcement as ``POST /pipelines`` — a failed update never
|
|
268
|
+
rolls a new version. Existing pipeline keeps its current version
|
|
269
|
+
when validation fails.
|
|
270
|
+
|
|
271
|
+
Existence is checked **before** the validator: an unknown
|
|
272
|
+
``pipeline_id`` should always return 404 regardless of whether
|
|
273
|
+
the body would also fail DAG validation. Otherwise a typo in
|
|
274
|
+
the URL plus a typo in the body would surface as 422 and hide
|
|
275
|
+
the real "this id doesn't exist" cause.
|
|
276
|
+
|
|
277
|
+
Ownership gates are inside ``repo.get_pipeline`` /
|
|
278
|
+
``repo.update_pipeline``: a non-admin probing someone else's
|
|
279
|
+
pipeline_id gets 404, never 422 — the validator never runs on a
|
|
280
|
+
foreign id, so the body shape can't leak through error details.
|
|
281
|
+
"""
|
|
282
|
+
try:
|
|
283
|
+
repo.get_pipeline(session, pipeline_id, actor_id=user.id, is_admin=user.is_superuser)
|
|
284
|
+
except repo.NotFoundError as exc:
|
|
285
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
286
|
+
|
|
287
|
+
_enforce_validation(_update_to_create_shape(payload), session)
|
|
288
|
+
try:
|
|
289
|
+
return repo.update_pipeline(
|
|
290
|
+
session, pipeline_id, payload, actor_id=user.id, is_admin=user.is_superuser
|
|
291
|
+
)
|
|
292
|
+
except repo.NotFoundError as exc:
|
|
293
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@router.delete("/{pipeline_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
297
|
+
def archive_pipeline(
|
|
298
|
+
pipeline_id: str,
|
|
299
|
+
session: Session = Depends(get_session),
|
|
300
|
+
user: UserORM = Depends(current_active_user),
|
|
301
|
+
) -> Response:
|
|
302
|
+
try:
|
|
303
|
+
repo.archive_pipeline(session, pipeline_id, actor_id=user.id, is_admin=user.is_superuser)
|
|
304
|
+
except repo.NotFoundError as exc:
|
|
305
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
306
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@router.get("/{pipeline_id}/versions", response_model=list[Pipeline])
|
|
310
|
+
def list_pipeline_versions(
|
|
311
|
+
pipeline_id: str,
|
|
312
|
+
session: Session = Depends(get_session),
|
|
313
|
+
user: UserORM = Depends(current_active_user),
|
|
314
|
+
) -> list[Pipeline]:
|
|
315
|
+
try:
|
|
316
|
+
return repo.list_pipeline_versions(
|
|
317
|
+
session, pipeline_id, actor_id=user.id, is_admin=user.is_superuser
|
|
318
|
+
)
|
|
319
|
+
except repo.NotFoundError as exc:
|
|
320
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@router.get("/{pipeline_id}/versions/{version}", response_model=Pipeline)
|
|
324
|
+
def get_pipeline_version(
|
|
325
|
+
pipeline_id: str,
|
|
326
|
+
version: int,
|
|
327
|
+
session: Session = Depends(get_session),
|
|
328
|
+
user: UserORM = Depends(current_active_user),
|
|
329
|
+
) -> Pipeline:
|
|
330
|
+
try:
|
|
331
|
+
return repo.get_pipeline_version(
|
|
332
|
+
session, pipeline_id, version, actor_id=user.id, is_admin=user.is_superuser
|
|
333
|
+
)
|
|
334
|
+
except repo.NotFoundError as exc:
|
|
335
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@router.get(
|
|
339
|
+
"/{pipeline_id}/export",
|
|
340
|
+
response_model=PipelineExport,
|
|
341
|
+
# ``bundled_agents`` defaults to ``None`` on non-bundle exports;
|
|
342
|
+
# ``exclude_none`` strips it from the JSON so Phase 1 wire format
|
|
343
|
+
# stays exactly the way it was — no ``"bundled_agents": null``
|
|
344
|
+
# noise in pipeline-only exports, and the field appears only when
|
|
345
|
+
# the operator opted in via ``?bundle=true``.
|
|
346
|
+
response_model_exclude_none=True,
|
|
347
|
+
)
|
|
348
|
+
def export_pipeline(
|
|
349
|
+
pipeline_id: str,
|
|
350
|
+
bundle: bool = Query(
|
|
351
|
+
default=False,
|
|
352
|
+
description=(
|
|
353
|
+
"When true, include every agent the pipeline references in "
|
|
354
|
+
"``bundled_agents`` so a target installation that doesn't "
|
|
355
|
+
"have them yet can import the whole thing in one shot."
|
|
356
|
+
),
|
|
357
|
+
),
|
|
358
|
+
session: Session = Depends(get_session),
|
|
359
|
+
user: UserORM = Depends(current_active_user),
|
|
360
|
+
) -> PipelineExport:
|
|
361
|
+
"""Return a portable JSON shape of the pipeline (#124, #126).
|
|
362
|
+
|
|
363
|
+
Strips per-installation fields (id, version, timestamps,
|
|
364
|
+
archived_at) so the result can move between DAP installations
|
|
365
|
+
or be checked into git. ``node.agent_id`` strings still point
|
|
366
|
+
at the *source* installation's agent ids.
|
|
367
|
+
|
|
368
|
+
With ``bundle=true`` (#126) the response also carries a
|
|
369
|
+
``bundled_agents`` map keyed by source agent id. The importer
|
|
370
|
+
creates each agent, builds an ``old_id → new_id`` remap, and
|
|
371
|
+
rewrites every ``node.agent_id`` before persisting the
|
|
372
|
+
pipeline. Without the bundle, a target DB that's missing any
|
|
373
|
+
referenced agent gets the standard 422 from the DAG validator.
|
|
374
|
+
"""
|
|
375
|
+
try:
|
|
376
|
+
pipeline = repo.get_pipeline(
|
|
377
|
+
session, pipeline_id, actor_id=user.id, is_admin=user.is_superuser
|
|
378
|
+
)
|
|
379
|
+
except repo.NotFoundError as exc:
|
|
380
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
381
|
+
|
|
382
|
+
try:
|
|
383
|
+
payload = PipelineExportPayload(
|
|
384
|
+
name=pipeline.name,
|
|
385
|
+
description=pipeline.description,
|
|
386
|
+
schema_version=pipeline.schema_version,
|
|
387
|
+
state_schema_ref=pipeline.state_schema_ref,
|
|
388
|
+
entry_point=pipeline.entry_point,
|
|
389
|
+
nodes=list(pipeline.nodes),
|
|
390
|
+
edges=list(pipeline.edges),
|
|
391
|
+
defaults=pipeline.defaults,
|
|
392
|
+
ui_metadata=pipeline.ui_metadata,
|
|
393
|
+
)
|
|
394
|
+
except ValidationError as exc:
|
|
395
|
+
# Shouldn't happen — stored shape was validated on write —
|
|
396
|
+
# but if a future migration ever introduces a stored shape
|
|
397
|
+
# we can't export, surface it as 500 with details rather
|
|
398
|
+
# than crashing without context.
|
|
399
|
+
raise HTTPException(
|
|
400
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
401
|
+
detail=f"Stored pipeline could not be re-validated for export: {exc.errors()}",
|
|
402
|
+
) from exc
|
|
403
|
+
|
|
404
|
+
bundled_agents: dict[str, AgentExportPayload] | None = None
|
|
405
|
+
if bundle:
|
|
406
|
+
# One batched fetch for every unique agent_id in the pipeline
|
|
407
|
+
# — a 2-query lookup regardless of node count (#126 review).
|
|
408
|
+
# ``_check_agents`` at save time guarantees a valid pipeline
|
|
409
|
+
# has no archived references, so any id we don't find here
|
|
410
|
+
# would be a row that vanished after save (race / manual DB
|
|
411
|
+
# tinkering). Skip silently in that case; the importer falls
|
|
412
|
+
# back to "agent not found" 422 on the receiving end if the
|
|
413
|
+
# bundle ends up incomplete.
|
|
414
|
+
agent_ids = sorted({node.agent_id for node in payload.nodes})
|
|
415
|
+
agents_by_id = repo.get_agents_by_ids(
|
|
416
|
+
session, agent_ids, actor_id=user.id, is_admin=user.is_superuser
|
|
417
|
+
)
|
|
418
|
+
bundled_agents = {
|
|
419
|
+
agent_id: build_agent_export_payload(agents_by_id[agent_id])
|
|
420
|
+
for agent_id in agent_ids
|
|
421
|
+
if agent_id in agents_by_id
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return PipelineExport(
|
|
425
|
+
schema_version=PIPELINE_EXPORT_SCHEMA_VERSION,
|
|
426
|
+
pipeline=payload,
|
|
427
|
+
bundled_agents=bundled_agents,
|
|
428
|
+
)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""REST CRUD for projects (#63) + project-bound pipeline trigger (#66)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from dap_runtimes import RuntimeRegistry
|
|
8
|
+
from dap_types import Project, Run
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
|
10
|
+
from langgraph.checkpoint.base import BaseCheckpointSaver
|
|
11
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
12
|
+
|
|
13
|
+
from dap_engine.api.deps import (
|
|
14
|
+
get_checkpointer,
|
|
15
|
+
get_registry,
|
|
16
|
+
get_run_registry,
|
|
17
|
+
get_session,
|
|
18
|
+
get_session_factory,
|
|
19
|
+
)
|
|
20
|
+
from dap_engine.api.runs import trigger_run
|
|
21
|
+
from dap_engine.api.schemas import ProjectRunRequest
|
|
22
|
+
from dap_engine.auth.users import current_active_user
|
|
23
|
+
from dap_engine.contracts import ProjectCreate, ProjectUpdate, RunCreateRequest
|
|
24
|
+
from dap_engine.execution import RunRegistry
|
|
25
|
+
from dap_engine.persistence import repository as repo
|
|
26
|
+
from dap_engine.persistence.models import UserORM
|
|
27
|
+
|
|
28
|
+
router = APIRouter(prefix="/projects", tags=["projects"])
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@router.get("")
|
|
32
|
+
def list_projects(
|
|
33
|
+
session: Session = Depends(get_session),
|
|
34
|
+
user: UserORM = Depends(current_active_user),
|
|
35
|
+
archived: bool = Query(default=False),
|
|
36
|
+
offset: int = Query(default=0, ge=0),
|
|
37
|
+
limit: int = Query(default=50, ge=1, le=500),
|
|
38
|
+
) -> dict[str, Any]:
|
|
39
|
+
items, total = repo.list_projects(
|
|
40
|
+
session,
|
|
41
|
+
actor_id=user.id,
|
|
42
|
+
is_admin=user.is_superuser,
|
|
43
|
+
archived=archived,
|
|
44
|
+
offset=offset,
|
|
45
|
+
limit=limit,
|
|
46
|
+
)
|
|
47
|
+
return {
|
|
48
|
+
"items": [p.model_dump(mode="json") for p in items],
|
|
49
|
+
"total": total,
|
|
50
|
+
"offset": offset,
|
|
51
|
+
"limit": limit,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@router.post("", status_code=status.HTTP_201_CREATED, response_model=Project)
|
|
56
|
+
def create_project(
|
|
57
|
+
payload: ProjectCreate,
|
|
58
|
+
session: Session = Depends(get_session),
|
|
59
|
+
user: UserORM = Depends(current_active_user),
|
|
60
|
+
) -> Project:
|
|
61
|
+
try:
|
|
62
|
+
return repo.create_project(session, payload, user_id=user.id, is_admin=user.is_superuser)
|
|
63
|
+
except ValueError as exc:
|
|
64
|
+
raise HTTPException(
|
|
65
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
66
|
+
detail=str(exc),
|
|
67
|
+
) from exc
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@router.get("/{project_id}", response_model=Project)
|
|
71
|
+
def get_project(
|
|
72
|
+
project_id: str,
|
|
73
|
+
session: Session = Depends(get_session),
|
|
74
|
+
user: UserORM = Depends(current_active_user),
|
|
75
|
+
) -> Project:
|
|
76
|
+
try:
|
|
77
|
+
return repo.get_project(session, project_id, actor_id=user.id, is_admin=user.is_superuser)
|
|
78
|
+
except repo.NotFoundError as exc:
|
|
79
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@router.put("/{project_id}", response_model=Project)
|
|
83
|
+
def update_project(
|
|
84
|
+
project_id: str,
|
|
85
|
+
payload: ProjectUpdate,
|
|
86
|
+
session: Session = Depends(get_session),
|
|
87
|
+
user: UserORM = Depends(current_active_user),
|
|
88
|
+
) -> Project:
|
|
89
|
+
try:
|
|
90
|
+
return repo.update_project(
|
|
91
|
+
session, project_id, payload, actor_id=user.id, is_admin=user.is_superuser
|
|
92
|
+
)
|
|
93
|
+
except repo.NotFoundError as exc:
|
|
94
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
95
|
+
except ValueError as exc:
|
|
96
|
+
raise HTTPException(
|
|
97
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
98
|
+
detail=str(exc),
|
|
99
|
+
) from exc
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
103
|
+
def archive_project(
|
|
104
|
+
project_id: str,
|
|
105
|
+
session: Session = Depends(get_session),
|
|
106
|
+
user: UserORM = Depends(current_active_user),
|
|
107
|
+
) -> Response:
|
|
108
|
+
try:
|
|
109
|
+
repo.archive_project(session, project_id, actor_id=user.id, is_admin=user.is_superuser)
|
|
110
|
+
except repo.NotFoundError as exc:
|
|
111
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
112
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@router.post(
|
|
116
|
+
"/{project_id}/run/{kind}",
|
|
117
|
+
status_code=status.HTTP_201_CREATED,
|
|
118
|
+
response_model=Run,
|
|
119
|
+
)
|
|
120
|
+
async def trigger_project_run(
|
|
121
|
+
project_id: str,
|
|
122
|
+
kind: str,
|
|
123
|
+
payload: ProjectRunRequest | None = None,
|
|
124
|
+
session: Session = Depends(get_session),
|
|
125
|
+
registry: RuntimeRegistry = Depends(get_registry),
|
|
126
|
+
run_registry: RunRegistry = Depends(get_run_registry),
|
|
127
|
+
session_factory: sessionmaker[Session] = Depends(get_session_factory),
|
|
128
|
+
checkpointer: BaseCheckpointSaver[Any] = Depends(get_checkpointer),
|
|
129
|
+
user: UserORM = Depends(current_active_user),
|
|
130
|
+
) -> Run:
|
|
131
|
+
"""Trigger the project's bound pipeline for a given workflow kind (#66).
|
|
132
|
+
|
|
133
|
+
Convenience over POST /runs: looks up ``pipeline_id =
|
|
134
|
+
project.pipelines[kind]``, fills the engine's ``project_id`` slot,
|
|
135
|
+
seeds ``repo`` / ``branch`` from the project (overridable per
|
|
136
|
+
call), and delegates to the standard run-trigger flow.
|
|
137
|
+
|
|
138
|
+
Ownership: non-admins can only trigger projects they own. The
|
|
139
|
+
project lookup is gated by ``repo.get_project`` — same gate the
|
|
140
|
+
other CRUD endpoints use — so a cross-user probe surfaces 404
|
|
141
|
+
(anti-enumeration), never the structured "Project is archived"
|
|
142
|
+
422 that would leak existence. Sharing the gate avoids drift if
|
|
143
|
+
the ownership rule changes (Copilot review on PR #312).
|
|
144
|
+
"""
|
|
145
|
+
try:
|
|
146
|
+
project = repo.get_project(
|
|
147
|
+
session, project_id, actor_id=user.id, is_admin=user.is_superuser
|
|
148
|
+
)
|
|
149
|
+
except repo.NotFoundError as exc:
|
|
150
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
|
151
|
+
if project.archived_at is not None:
|
|
152
|
+
# 422 — same status as POST /runs returns when an archived project_id
|
|
153
|
+
# is in the payload. Aligning the two trigger paths so clients can
|
|
154
|
+
# share error-handling logic regardless of which endpoint they used. (#205)
|
|
155
|
+
raise HTTPException(
|
|
156
|
+
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
157
|
+
detail=f"Project is archived: {project_id}",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
bound_pipeline_id = project.pipelines.get(kind)
|
|
161
|
+
if not bound_pipeline_id:
|
|
162
|
+
bound_kinds = sorted(project.pipelines)
|
|
163
|
+
bound_msg = ", ".join(bound_kinds) if bound_kinds else "(none)"
|
|
164
|
+
raise HTTPException(
|
|
165
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
166
|
+
detail=(
|
|
167
|
+
f"Project '{project_id}' has no pipeline bound to kind "
|
|
168
|
+
f"'{kind}'. Bound kinds: {bound_msg}"
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
body = payload or ProjectRunRequest()
|
|
173
|
+
run_request = RunCreateRequest(
|
|
174
|
+
pipeline_id=bound_pipeline_id,
|
|
175
|
+
pipeline_version=body.pipeline_version,
|
|
176
|
+
project_id=project_id,
|
|
177
|
+
initial_state=body.initial_state,
|
|
178
|
+
)
|
|
179
|
+
# Delegate to the existing trigger flow — same validation, same
|
|
180
|
+
# background-task spawn, same Run shape on the way back. The
|
|
181
|
+
# archived-project check is duplicated there but unreachable
|
|
182
|
+
# because we already 422'd above.
|
|
183
|
+
return await trigger_run(
|
|
184
|
+
payload=run_request,
|
|
185
|
+
session=session,
|
|
186
|
+
registry=registry,
|
|
187
|
+
run_registry=run_registry,
|
|
188
|
+
session_factory=session_factory,
|
|
189
|
+
checkpointer=checkpointer,
|
|
190
|
+
user=user,
|
|
191
|
+
)
|