dagron-sdk 0.2.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.
dagron.py ADDED
@@ -0,0 +1,629 @@
1
+ """dagron Python SDK — author DAGs in code and drive the full dagron control plane.
2
+
3
+ Two layers, both standard-library only (``json`` + ``urllib``):
4
+
5
+ * :class:`Dag` — a fluent builder for a dagron workflow spec. ``to_json()`` emits
6
+ valid dagron input (dagron parses YAML, and JSON is a YAML subset) and the
7
+ builder validates the graph (unique names, known deps, leaf-xor-chain, acyclic)
8
+ client-side, mirroring the server's ``validate_graph``.
9
+
10
+ * :class:`Client` — a thin, typed wrapper over the **dagron-api** gateway
11
+ (``/api/...``, JWT-authenticated). It covers the same surface the web UI uses —
12
+ login, runs, workflows, schedules, dead-letters, GitOps repos, metrics — so an
13
+ automation can do anything the UI can without hand-rolling REST calls.
14
+
15
+ from dagron import Dag, Client
16
+
17
+ dag = Dag("etl")
18
+ extract = dag.task("extract", image="alpine", command=["echo", "hi"])
19
+ dag.task("load", image="alpine", command=["true"], depends_on=[extract])
20
+
21
+ api = Client("http://localhost:8080")
22
+ api.login("admin@example.com", "hunter2222") # stores the session token
23
+ run_id = api.submit_run(dag) # trigger an ad-hoc run
24
+ run = api.wait_for_run(run_id) # poll to a terminal state
25
+ print(run["status"])
26
+
27
+ The gateway expects a DAG submitted as ``{"yaml": "<spec>"}``; the SDK wraps that
28
+ for you, so callers pass a :class:`Dag`, a spec ``dict``, or a YAML/JSON string.
29
+
30
+ Targeting the no-auth engine ops API instead (``/runs``, raw-body submit) is on the
31
+ roadmap (see ``ROADMAP.md``); today the client speaks the gateway dialect.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import copy
37
+ import json
38
+ import time
39
+ import urllib.error
40
+ import urllib.parse
41
+ import urllib.request
42
+ from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Union
43
+
44
+ __all__ = ["Dag", "Client", "DagronError", "SpecLike", "__version__"]
45
+ __version__ = "0.2.0"
46
+
47
+ #: Run statuses the engine treats as terminal (no further transitions).
48
+ TERMINAL_RUN_STATUSES = frozenset({"succeeded", "failed", "cancelled"})
49
+
50
+ #: Anything accepted where a DAG spec is expected: a builder, a spec mapping, or
51
+ #: an already-serialised YAML/JSON string.
52
+ SpecLike = Union["Dag", Mapping[str, Any], str]
53
+
54
+
55
+ # ── Builder ───────────────────────────────────────────────────────────────────
56
+
57
+
58
+ class Dag:
59
+ """Build a dagron workflow spec in code.
60
+
61
+ Add tasks with :meth:`task`; ``to_spec()`` / ``to_json()`` validate the graph
62
+ and emit the spec. Pass the builder straight to :meth:`Client.submit_run` or
63
+ :meth:`Client.create_workflow`.
64
+ """
65
+
66
+ def __init__(self, name: str) -> None:
67
+ """Create an empty DAG named ``name`` (raises if the name is empty)."""
68
+ if not name:
69
+ raise ValueError("Dag requires a name")
70
+ self.name = name
71
+ self._tasks: List[Dict[str, Any]] = []
72
+ self._names: set[str] = set()
73
+
74
+ def task(
75
+ self,
76
+ name: str,
77
+ *,
78
+ image: Optional[str] = None,
79
+ command: Optional[Sequence[str]] = None,
80
+ depends_on: Optional[Sequence[str]] = None,
81
+ workflow_ref: Optional[str] = None,
82
+ input: Optional[Any] = None,
83
+ max_attempts: Optional[int] = None,
84
+ retry_delay_secs: Optional[int] = None,
85
+ timeout_secs: Optional[int] = None,
86
+ env: Optional[Union[Mapping[str, str], Sequence[Mapping[str, str]]]] = None,
87
+ resources: Optional[Mapping[str, Any]] = None,
88
+ service_account: Optional[str] = None,
89
+ ) -> str:
90
+ """Add a task; returns its name (pass it to a later task's ``depends_on``).
91
+
92
+ A task is either a *leaf* (runs ``command``) or a *chain* (``workflow_ref``
93
+ inlines another saved workflow), never both — enforced at build time by
94
+ :meth:`to_spec`, mirroring the server. The remaining keyword arguments map
95
+ one-to-one onto the engine's ``TaskSpec`` and are omitted from the emitted
96
+ spec when left unset so the JSON stays minimal.
97
+ """
98
+ if not name:
99
+ raise ValueError("task requires a name")
100
+ # str/bytes are sequences, so list("echo") would silently split into
101
+ # characters — reject the scalar instead of building a broken spec.
102
+ if isinstance(command, (str, bytes)):
103
+ raise TypeError("command must be a sequence of strings, not a single string")
104
+ if isinstance(depends_on, (str, bytes)):
105
+ raise TypeError("depends_on must be a sequence of task names, not a single string")
106
+ if name in self._names:
107
+ raise ValueError(f"duplicate task '{name}'")
108
+ self._names.add(name)
109
+
110
+ t: Dict[str, Any] = {"name": name}
111
+ if image:
112
+ t["docker_image"] = image
113
+ if command:
114
+ t["command"] = list(command)
115
+ if depends_on:
116
+ t["depends_on"] = list(depends_on)
117
+ if workflow_ref:
118
+ t["workflow_ref"] = workflow_ref
119
+ if input is not None:
120
+ t["input"] = input
121
+ if max_attempts is not None:
122
+ if max_attempts < 1:
123
+ raise ValueError("max_attempts must be >= 1")
124
+ t["max_attempts"] = max_attempts
125
+ if retry_delay_secs is not None:
126
+ t["retry_delay_secs"] = retry_delay_secs
127
+ if timeout_secs is not None:
128
+ t["timeout_secs"] = timeout_secs
129
+ if env is not None:
130
+ t["env"] = _normalize_env(env)
131
+ if resources is not None:
132
+ t["resources"] = dict(resources)
133
+ if service_account:
134
+ t["service_account"] = service_account
135
+
136
+ self._tasks.append(t)
137
+ return name
138
+
139
+ def to_spec(self) -> Dict[str, Any]:
140
+ """Build the validated dagron spec dict.
141
+
142
+ Runs the same structural checks the gateway runs server-side, so a bad DAG
143
+ fails locally with a clear message instead of a 400 round-trip:
144
+
145
+ * every task is exactly one of leaf (``command``) or chain (``workflow_ref``);
146
+ * every ``depends_on`` names a real task;
147
+ * the dependency graph is acyclic.
148
+ """
149
+ for t in self._tasks:
150
+ is_leaf = bool(t.get("command"))
151
+ is_chain = bool(t.get("workflow_ref"))
152
+ if is_leaf and is_chain:
153
+ raise ValueError(
154
+ f"task '{t['name']}' sets both command and workflow_ref — use exactly one"
155
+ )
156
+ if not is_leaf and not is_chain:
157
+ raise ValueError(
158
+ f"task '{t['name']}' needs a command (leaf) or a workflow_ref (chain)"
159
+ )
160
+ for d in t.get("depends_on", []):
161
+ if d not in self._names:
162
+ raise ValueError(f"task '{t['name']}' depends on unknown task '{d}'")
163
+ self._assert_acyclic()
164
+ # Deep-copy so callers can't mutate our internal task state via the
165
+ # returned spec (to_json/submit both go through here).
166
+ return copy.deepcopy({"name": self.name, "tasks": self._tasks})
167
+
168
+ def _assert_acyclic(self) -> None:
169
+ """DFS colouring; raise on the first back-edge (a dependency cycle)."""
170
+ adjacency: Dict[str, List[str]] = {t["name"]: list(t.get("depends_on", [])) for t in self._tasks}
171
+ WHITE, GREY, BLACK = 0, 1, 2
172
+ color: Dict[str, int] = {name: WHITE for name in adjacency}
173
+
174
+ def visit(node: str) -> None:
175
+ """Depth-first visit; a GREY neighbour is a back-edge, i.e. a cycle."""
176
+ color[node] = GREY
177
+ for dep in adjacency[node]:
178
+ if color[dep] == GREY:
179
+ raise ValueError(f"DAG '{self.name}' contains a cycle (through '{dep}')")
180
+ if color[dep] == WHITE:
181
+ visit(dep)
182
+ color[node] = BLACK
183
+
184
+ for name in adjacency:
185
+ if color[name] == WHITE:
186
+ visit(name)
187
+
188
+ def to_json(self) -> str:
189
+ """dagron spec as JSON (valid dagron input — YAML is a JSON superset)."""
190
+ return json.dumps(self.to_spec())
191
+
192
+ def submit(self, api_url: str, token: Optional[str] = None, *, timeout: float = 30) -> str:
193
+ """Submit the DAG as an ad-hoc run; returns the new ``run_id``.
194
+
195
+ Convenience one-liner equivalent to ``Client(api_url, token).submit_run(self)``.
196
+ """
197
+ return Client(api_url, token=token, timeout=timeout).submit_run(self)
198
+
199
+
200
+ # ── Client ────────────────────────────────────────────────────────────────────
201
+
202
+
203
+ class DagronError(Exception):
204
+ """A non-2xx response (or transport failure) from dagron-api.
205
+
206
+ ``status`` is the HTTP code (``0`` for a transport-level failure), ``message``
207
+ the server's error text (unwrapped from ``{"error": ...}`` when present), and
208
+ ``body`` the raw response body for inspection.
209
+ """
210
+
211
+ def __init__(self, status: int, message: str, *, body: Optional[str] = None) -> None:
212
+ """Store the HTTP ``status`` (``0`` for transport failures), ``message``, and raw ``body``."""
213
+ self.status = status
214
+ self.message = message
215
+ self.body = body
216
+ super().__init__(f"dagron-api {status}: {message}" if status else message)
217
+
218
+ @classmethod
219
+ def _from_body(cls, status: int, raw: bytes) -> "DagronError":
220
+ """Build an error from a response body, unwrapping ``{"error": ...}`` when present."""
221
+ text = raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else (raw or "")
222
+ message = text
223
+ try:
224
+ parsed = json.loads(text)
225
+ if isinstance(parsed, dict) and isinstance(parsed.get("error"), str):
226
+ message = parsed["error"]
227
+ except (ValueError, TypeError):
228
+ pass
229
+ message = (message or "").strip() or f"HTTP {status}"
230
+ return cls(status, message, body=text)
231
+
232
+
233
+ class Client:
234
+ """Typed client for the dagron-api gateway (``/api/...``).
235
+
236
+ Construct with the gateway base URL (``http://host:port``) and either a session
237
+ JWT (``token=``) or call :meth:`login` to obtain one. Every authed call sends
238
+ ``Authorization: Bearer <token>``; the token can be rotated via :attr:`token`.
239
+ """
240
+
241
+ def __init__(self, base_url: str, token: Optional[str] = None, *, timeout: float = 30) -> None:
242
+ """Bind the client to a gateway ``base_url`` (http/https) with an optional session token."""
243
+ # urlopen also speaks file://, ftp://, … — restrict to HTTP(S) so a bad
244
+ # base_url can't leak the bearer token or reach local files (SSRF).
245
+ scheme = urllib.parse.urlparse(base_url).scheme
246
+ if scheme not in ("http", "https"):
247
+ raise ValueError("base_url must use http or https")
248
+ self.base_url = base_url.rstrip("/")
249
+ self.token = token
250
+ self.timeout = timeout
251
+
252
+ # ── auth ──────────────────────────────────────────────────────────────────
253
+
254
+ def login(self, email: str, password: str) -> str:
255
+ """Exchange credentials for a session token, store it, and return it.
256
+
257
+ After this call the client is authenticated for every other method.
258
+ """
259
+ body = self._request("POST", "/api/login", body={"email": email, "password": password}, auth=False)
260
+ token = body.get("token") if isinstance(body, dict) else None
261
+ if not token:
262
+ raise DagronError(0, "login succeeded but no token was returned")
263
+ self.token = token
264
+ return token
265
+
266
+ def logout(self) -> None:
267
+ """Clear the session cookie server-side and drop the local token.
268
+
269
+ Sends the bearer token so the call is authenticated and consistent with
270
+ the rest of the client. dagron's session JWT is stateless, so logout is a
271
+ cookie clear today (no server-side denylist to revoke against); dropping
272
+ the local token is what ends the bearer session for this client.
273
+ """
274
+ self._request("POST", "/api/logout", parse_json=False)
275
+ self.token = None
276
+
277
+ def me(self) -> Dict[str, Any]:
278
+ """Return the authenticated session's claims (``sub``/``email``/``groups``/…)."""
279
+ return self._request("GET", "/api/me")
280
+
281
+ def create_user(
282
+ self, email: str, password: str, name: str, groups: Optional[Sequence[str]] = None
283
+ ) -> Dict[str, Any]:
284
+ """Create a user (caller must be in the ``admin`` group). Returns ``{"id": ...}``."""
285
+ return self._request(
286
+ "POST",
287
+ "/api/users",
288
+ body={"email": email, "password": password, "name": name, "groups": list(groups or [])},
289
+ )
290
+
291
+ # ── runs ──────────────────────────────────────────────────────────────────
292
+
293
+ def submit_run(self, spec: SpecLike) -> str:
294
+ """Submit a DAG as an ad-hoc run; returns the new ``run_id``.
295
+
296
+ ``spec`` may be a :class:`Dag`, a spec mapping, or a YAML/JSON string.
297
+ """
298
+ resp = self._request("POST", "/api/runs", body={"yaml": _spec_to_str(spec)})
299
+ return resp["run_id"]
300
+
301
+ def list_runs(
302
+ self, *, status: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None
303
+ ) -> List[Dict[str, Any]]:
304
+ """List runs newest-first, optionally filtered by ``status`` and paged."""
305
+ return self._request(
306
+ "GET", "/api/runs", params={"status": status, "limit": limit, "offset": offset}
307
+ )
308
+
309
+ def get_run(self, run_id: str) -> Dict[str, Any]:
310
+ """Fetch one run plus its task rows."""
311
+ return self._request("GET", f"/api/runs/{_seg(run_id)}")
312
+
313
+ def get_run_graph(self, run_id: str) -> Dict[str, Any]:
314
+ """Fetch the run's task nodes + dependency edges (for graph rendering)."""
315
+ return self._request("GET", f"/api/runs/{_seg(run_id)}/graph")
316
+
317
+ def get_task_logs(self, run_id: str, task_id: str) -> Dict[str, Any]:
318
+ """Fetch one task's captured output, scoped to its run."""
319
+ return self._request("GET", f"/api/runs/{_seg(run_id)}/tasks/{_seg(task_id)}/logs")
320
+
321
+ def cancel_run(self, run_id: str) -> int:
322
+ """Cancel a run; returns the number of tasks flipped to ``cancelled``."""
323
+ return self._request("POST", f"/api/runs/{_seg(run_id)}/cancel")["cancelled"]
324
+
325
+ def rerun_run(self, run_id: str, *, params: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]:
326
+ """Cascade-rerun a failed/cancelled run from its failure frontier.
327
+
328
+ Succeeded tasks are kept; failed/cancelled tasks (and what they blocked)
329
+ reset and re-run. Optional ``params`` is deep-merged into each reset task's
330
+ input for a fix-forward rerun. Returns ``{"run_id", "rerun": <tasks reset>}``.
331
+ """
332
+ body: Dict[str, Any] = {"params": dict(params)} if params else {}
333
+ return self._request("POST", f"/api/runs/{_seg(run_id)}/rerun", body=body)
334
+
335
+ def resubmit_run(self, run_id: str) -> str:
336
+ """Start a brand-new run from this run's stored definition; returns the new ``run_id``."""
337
+ return self._request("POST", f"/api/runs/{_seg(run_id)}/resubmit")["run_id"]
338
+
339
+ def retry_task(self, run_id: str, task_id: str) -> bool:
340
+ """Resurrect a single failed/cancelled task within a run."""
341
+ return self._request("POST", f"/api/runs/{_seg(run_id)}/tasks/{_seg(task_id)}/retry")["retried"]
342
+
343
+ def stream_run(self, run_id: str, *, timeout: Optional[float] = None) -> Iterator[Dict[str, Any]]:
344
+ """Yield live task-state events for a run as Server-Sent Events.
345
+
346
+ Each item is ``{"event": <name>, "data": <parsed JSON or raw str>}``. The
347
+ generator runs until the connection closes; pass ``timeout`` to bound an
348
+ idle read. A ``resync`` event means the client fell behind and should
349
+ refetch the full graph via :meth:`get_run_graph`.
350
+ """
351
+ url = f"{self.base_url}/api/runs/{_seg(run_id)}/stream"
352
+ headers = {"accept": "text/event-stream"}
353
+ if self.token:
354
+ headers["authorization"] = f"Bearer {self.token}"
355
+ req = urllib.request.Request(url, headers=headers, method="GET")
356
+ # Normalise connection/HTTP failures to DagronError, same as _request, so
357
+ # callers see one exception type across the whole client API.
358
+ try:
359
+ resp = urllib.request.urlopen(req, timeout=timeout) # noqa: S310 (scheme checked in __init__)
360
+ except urllib.error.HTTPError as e:
361
+ raise DagronError._from_body(e.code, e.read()) from None
362
+ except urllib.error.URLError as e:
363
+ raise DagronError(0, f"request to {url} failed: {e.reason}") from None
364
+ try:
365
+ yield from _parse_sse(resp)
366
+ finally:
367
+ resp.close()
368
+
369
+ def wait_for_run(
370
+ self, run_id: str, *, poll_interval: float = 2.0, timeout: Optional[float] = 300.0
371
+ ) -> Dict[str, Any]:
372
+ """Poll :meth:`get_run` until the run reaches a terminal state; return it.
373
+
374
+ Raises :class:`TimeoutError` if ``timeout`` seconds elapse first (``None``
375
+ waits forever). A lightweight alternative to :meth:`stream_run` for scripts.
376
+ """
377
+ deadline = None if timeout is None else time.monotonic() + timeout
378
+ while True:
379
+ run = self.get_run(run_id)
380
+ if run.get("status") in TERMINAL_RUN_STATUSES:
381
+ return run
382
+ if deadline is not None and time.monotonic() >= deadline:
383
+ raise TimeoutError(f"run '{run_id}' did not finish within {timeout}s")
384
+ time.sleep(poll_interval)
385
+
386
+ # ── workflows (first-class, saved definitions) ────────────────────────────
387
+
388
+ def list_workflows(self) -> List[Dict[str, Any]]:
389
+ """List saved workflows enriched with schedule + recent-run digest."""
390
+ return self._request("GET", "/api/workflows")
391
+
392
+ def get_workflow(self, workflow_id: str) -> Dict[str, Any]:
393
+ """Fetch one saved workflow including its spec."""
394
+ return self._request("GET", f"/api/workflows/{_seg(workflow_id)}")
395
+
396
+ def create_workflow(
397
+ self, spec: SpecLike, *, name: Optional[str] = None, description: Optional[str] = None
398
+ ) -> Dict[str, Any]:
399
+ """Save a new workflow. ``name`` defaults to the spec's name. 409 on a dup name."""
400
+ return self._request(
401
+ "POST",
402
+ "/api/workflows",
403
+ body={"spec": _spec_to_str(spec), "name": name, "description": description},
404
+ )
405
+
406
+ def update_workflow(
407
+ self,
408
+ workflow_id: str,
409
+ spec: SpecLike,
410
+ *,
411
+ name: Optional[str] = None,
412
+ description: Optional[str] = None,
413
+ ) -> Dict[str, Any]:
414
+ """Replace a saved workflow's spec (and optionally rename it)."""
415
+ return self._request(
416
+ "PUT",
417
+ f"/api/workflows/{_seg(workflow_id)}",
418
+ body={"spec": _spec_to_str(spec), "name": name, "description": description},
419
+ )
420
+
421
+ def delete_workflow(self, workflow_id: str) -> None:
422
+ """Delete a saved workflow."""
423
+ self._request("DELETE", f"/api/workflows/{_seg(workflow_id)}", parse_json=False)
424
+
425
+ def run_workflow(self, workflow_id: str) -> Dict[str, Any]:
426
+ """Trigger a saved workflow as a run. Returns ``{"run_id", "workflow_id"}``."""
427
+ return self._request("POST", f"/api/workflows/{_seg(workflow_id)}/run")
428
+
429
+ def sync_workflow_to_git(self, workflow_id: str) -> Dict[str, Any]:
430
+ """Open a PR committing the workflow's raw spec to the configured GitOps repo."""
431
+ return self._request("POST", f"/api/workflows/{_seg(workflow_id)}/sync-to-git")
432
+
433
+ # ── schedules ─────────────────────────────────────────────────────────────
434
+
435
+ def list_schedules(self, *, workflow_id: Optional[str] = None) -> List[Dict[str, Any]]:
436
+ """List all schedules, or just one workflow's."""
437
+ return self._request("GET", "/api/schedules", params={"workflow_id": workflow_id})
438
+
439
+ def create_schedule(self, workflow_id: str, cron_expr: str, *, enabled: bool = True) -> Dict[str, Any]:
440
+ """Attach a cron schedule to a saved workflow."""
441
+ return self._request(
442
+ "POST",
443
+ "/api/schedules",
444
+ body={"workflow_id": workflow_id, "cron_expr": cron_expr, "enabled": enabled},
445
+ )
446
+
447
+ def update_schedule(
448
+ self, schedule_id: str, *, cron_expr: Optional[str] = None, enabled: Optional[bool] = None
449
+ ) -> Dict[str, Any]:
450
+ """Change a schedule's cron expression and/or enabled flag."""
451
+ body: Dict[str, Any] = {}
452
+ if cron_expr is not None:
453
+ body["cron_expr"] = cron_expr
454
+ if enabled is not None:
455
+ body["enabled"] = enabled
456
+ return self._request("PUT", f"/api/schedules/{_seg(schedule_id)}", body=body)
457
+
458
+ def delete_schedule(self, schedule_id: str) -> None:
459
+ """Remove a schedule."""
460
+ self._request("DELETE", f"/api/schedules/{_seg(schedule_id)}", parse_json=False)
461
+
462
+ def backfill_schedule(
463
+ self, schedule_id: str, frm: str, to: str, *, max_runs: Optional[int] = None
464
+ ) -> Dict[str, Any]:
465
+ """Materialise a schedule's missed runs across ``[frm, to]`` (RFC3339).
466
+
467
+ Re-issuing the same window is safe — already-materialised fire-times are
468
+ reported as ``skipped`` rather than double-run.
469
+ """
470
+ body: Dict[str, Any] = {"from": frm, "to": to}
471
+ if max_runs is not None:
472
+ body["max_runs"] = max_runs
473
+ return self._request("POST", f"/api/schedules/{_seg(schedule_id)}/backfill", body=body)
474
+
475
+ # ── dead letters ──────────────────────────────────────────────────────────
476
+
477
+ def list_dead_letters(self, *, limit: int = 100) -> List[Dict[str, Any]]:
478
+ """List parked poison submissions, newest failure first."""
479
+ return self._request("GET", "/api/dead-letters", params={"limit": limit})
480
+
481
+ def redrive_dead_letter(self, dead_letter_id: str) -> Dict[str, Any]:
482
+ """Re-attempt a parked payload as a fresh run. Returns ``{"run_id", "redriven_from"}``."""
483
+ return self._request("POST", f"/api/dead-letters/{_seg(dead_letter_id)}/redrive")
484
+
485
+ def discard_dead_letter(self, dead_letter_id: str) -> None:
486
+ """Discard a parked payload."""
487
+ self._request("DELETE", f"/api/dead-letters/{_seg(dead_letter_id)}", parse_json=False)
488
+
489
+ # ── GitOps repository registry ────────────────────────────────────────────
490
+
491
+ def list_git_repos(self) -> List[Dict[str, Any]]:
492
+ """List tracked GitOps repositories."""
493
+ return self._request("GET", "/api/git-repos")
494
+
495
+ def connect_git_repo(
496
+ self, url: str, *, branch: Optional[str] = None, auto_sync: bool = False
497
+ ) -> Dict[str, Any]:
498
+ """Register (connect) a Git repository."""
499
+ return self._request(
500
+ "POST", "/api/git-repos", body={"url": url, "branch": branch, "auto_sync": auto_sync}
501
+ )
502
+
503
+ def sync_git_repo(self, repo_id: str) -> Dict[str, Any]:
504
+ """Mark a tracked repo synced now."""
505
+ return self._request("POST", f"/api/git-repos/{_seg(repo_id)}/sync")
506
+
507
+ def disconnect_git_repo(self, repo_id: str) -> None:
508
+ """Stop tracking (disconnect) a repo."""
509
+ self._request("DELETE", f"/api/git-repos/{_seg(repo_id)}", parse_json=False)
510
+
511
+ # ── observability ─────────────────────────────────────────────────────────
512
+
513
+ def metrics(self) -> Dict[str, Any]:
514
+ """Live run/task counts by status plus the dead-letter total (JSON gauges)."""
515
+ return self._request("GET", "/api/metrics")
516
+
517
+ def healthz(self) -> str:
518
+ """Liveness probe (``"ok"`` while the gateway is serving). Unauthenticated."""
519
+ return self._request("GET", "/healthz", parse_json=False, auth=False)
520
+
521
+ # ── transport ─────────────────────────────────────────────────────────────
522
+
523
+ def _request(
524
+ self,
525
+ method: str,
526
+ path: str,
527
+ *,
528
+ body: Optional[Any] = None,
529
+ params: Optional[Mapping[str, Any]] = None,
530
+ parse_json: bool = True,
531
+ auth: bool = True,
532
+ ) -> Any:
533
+ """Issue one request; return parsed JSON (or text), or raise :class:`DagronError`."""
534
+ url = self.base_url + path
535
+ if params:
536
+ query = {k: v for k, v in params.items() if v is not None}
537
+ if query:
538
+ url += "?" + urllib.parse.urlencode(query)
539
+
540
+ data = None
541
+ headers: Dict[str, str] = {"accept": "application/json"}
542
+ if body is not None:
543
+ data = json.dumps(body).encode("utf-8")
544
+ headers["content-type"] = "application/json"
545
+ if auth and self.token:
546
+ headers["authorization"] = f"Bearer {self.token}"
547
+
548
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
549
+ try:
550
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp: # noqa: S310 (scheme checked)
551
+ raw = resp.read()
552
+ except urllib.error.HTTPError as e:
553
+ raise DagronError._from_body(e.code, e.read()) from None
554
+ except urllib.error.URLError as e:
555
+ raise DagronError(0, f"request to {url} failed: {e.reason}") from None
556
+
557
+ if not parse_json:
558
+ return raw.decode("utf-8")
559
+ if not raw:
560
+ return None
561
+ return json.loads(raw)
562
+
563
+
564
+ # ── helpers ───────────────────────────────────────────────────────────────────
565
+
566
+
567
+ def _spec_to_str(spec: SpecLike) -> str:
568
+ """Coerce a Dag / mapping / string into the YAML-or-JSON spec string the API wants."""
569
+ if isinstance(spec, Dag):
570
+ return spec.to_json()
571
+ if isinstance(spec, str):
572
+ return spec
573
+ if isinstance(spec, Mapping):
574
+ return json.dumps(spec)
575
+ raise TypeError("spec must be a Dag, a mapping, or a YAML/JSON string")
576
+
577
+
578
+ def _normalize_env(
579
+ env: Union[Mapping[str, str], Sequence[Mapping[str, str]]],
580
+ ) -> List[Dict[str, str]]:
581
+ """Accept env as a ``{name: value}`` map or a list of ``{"name", "value"}`` and
582
+ normalise to the engine's ``[{"name", "value"}]`` shape."""
583
+ if isinstance(env, Mapping):
584
+ return [{"name": str(k), "value": str(v)} for k, v in env.items()]
585
+ out: List[Dict[str, str]] = []
586
+ for item in env:
587
+ if not isinstance(item, Mapping) or "name" not in item or "value" not in item:
588
+ raise TypeError("env list items must be {'name': ..., 'value': ...} mappings")
589
+ out.append({"name": str(item["name"]), "value": str(item["value"])})
590
+ return out
591
+
592
+
593
+ def _seg(value: str) -> str:
594
+ """Percent-encode a single path segment (ids are UUIDs, but never trust input)."""
595
+ return urllib.parse.quote(str(value), safe="")
596
+
597
+
598
+ def _parse_sse(lines: Iterable[bytes]) -> Iterator[Dict[str, Any]]:
599
+ """Minimal Server-Sent-Events parser: group ``event:``/``data:`` lines into
600
+ one dict per blank-line-delimited event, JSON-decoding the data when possible."""
601
+ event: Optional[str] = None
602
+ data_lines: List[str] = []
603
+ for raw_line in lines:
604
+ line = raw_line.decode("utf-8", "replace").rstrip("\r\n")
605
+ if line == "": # dispatch on the blank line that terminates an event
606
+ if data_lines:
607
+ payload = "\n".join(data_lines)
608
+ yield {"event": event or "message", "data": _maybe_json(payload)}
609
+ event, data_lines = None, []
610
+ continue
611
+ if line.startswith(":"): # comment / keep-alive ping
612
+ continue
613
+ field, _, rest = line.partition(":")
614
+ value = rest[1:] if rest.startswith(" ") else rest
615
+ if field == "event":
616
+ event = value
617
+ elif field == "data":
618
+ data_lines.append(value)
619
+ # Flush a trailing event with no terminating blank line.
620
+ if data_lines:
621
+ yield {"event": event or "message", "data": _maybe_json("\n".join(data_lines))}
622
+
623
+
624
+ def _maybe_json(text: str) -> Any:
625
+ """Parse ``text`` as JSON, returning the raw string when it isn't valid JSON."""
626
+ try:
627
+ return json.loads(text)
628
+ except (ValueError, TypeError):
629
+ return text
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: dagron-sdk
3
+ Version: 0.2.0
4
+ Summary: Author dagron DAGs in Python and drive the dagron-api control plane (runs, workflows, schedules).
5
+ License: Apache-2.0
6
+ Project-URL: Roadmap, https://github.com/lucheeseng827/nick-rust-project
7
+ Keywords: dagron,workflow,dag,scheduler,orchestration
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+
11
+ # dagron Python SDK
12
+
13
+ Author dagron workflows in Python and drive the whole dagron control plane —
14
+ trigger runs, manage workflows and schedules, redrive dead letters, wire up
15
+ GitOps — without writing REST calls by hand.
16
+
17
+ - **Zero dependencies.** Standard library only (`json` + `urllib`).
18
+ - **Two layers:** `Dag` (a validating spec builder) and `Client` (a typed wrapper
19
+ over the authenticated `dagron-api` gateway).
20
+ - **Full coverage.** `v0.2` covers 100% of the current `dagron-api` HTTP surface —
21
+ see [`ROADMAP.md`](ROADMAP.md) for the coverage matrix and what's next.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install -e . # from sdks/python
27
+ ```
28
+
29
+ ## Author a DAG
30
+
31
+ ```python
32
+ from dagron import Dag
33
+
34
+ dag = Dag("etl")
35
+ extract = dag.task("extract", image="alpine", command=["echo", "hi"])
36
+ dag.task("load", image="alpine", command=["true"], depends_on=[extract])
37
+
38
+ print(dag.to_json()) # valid dagron input (YAML is a JSON superset)
39
+ ```
40
+
41
+ `task()` maps onto the engine's full `TaskSpec` — `image`, `command`, `depends_on`,
42
+ plus `input`, `max_attempts`, `retry_delay_secs`, `timeout_secs`, `env`,
43
+ `resources`, `service_account`, and `workflow_ref` (chain another saved workflow).
44
+ `to_spec()`/`to_json()` validate the graph client-side (unique names, known deps,
45
+ leaf-xor-chain, acyclic), mirroring the server so a bad DAG fails fast.
46
+
47
+ ## Drive the control plane
48
+
49
+ ```python
50
+ import os
51
+ from dagron import Client
52
+
53
+ api = Client("http://localhost:8080")
54
+ api.login("admin@example.com", os.environ["DAGRON_PASSWORD"]) # stores the token
55
+ # ...or skip login: Client("http://localhost:8080", token=os.environ["DAGRON_TOKEN"])
56
+
57
+ # Trigger an ad-hoc run and wait for it to finish.
58
+ run_id = api.submit_run(dag)
59
+ run = api.wait_for_run(run_id)
60
+ print(run["status"]) # succeeded | failed | cancelled
61
+
62
+ # Save it as a reusable workflow and schedule it nightly.
63
+ wf = api.create_workflow(dag, description="nightly ETL")
64
+ api.create_schedule(wf["id"], "0 0 0 * * *")
65
+
66
+ # Observe.
67
+ for ev in api.stream_run(run_id): # live Server-Sent Events
68
+ print(ev["event"], ev["data"])
69
+ ```
70
+
71
+ Every method maps one `dagron-api` endpoint to one call and returns the server's
72
+ JSON. Non-2xx responses raise `DagronError(status, message)`:
73
+
74
+ ```python
75
+ from dagron import DagronError
76
+
77
+ try:
78
+ api.submit_run({"name": "x", "tasks": []})
79
+ except DagronError as e:
80
+ print(e.status, e.message) # e.g. 400 "DAG 'x' contains a cycle"
81
+ ```
82
+
83
+ ### What `Client` covers
84
+
85
+ `login` · `logout` · `me` · `create_user` · `submit_run` · `list_runs` · `get_run`
86
+ · `get_run_graph` · `get_task_logs` · `cancel_run` · `rerun_run` · `resubmit_run`
87
+ · `retry_task` · `stream_run` · `wait_for_run` · `list_workflows` · `get_workflow`
88
+ · `create_workflow` · `update_workflow` · `delete_workflow` · `run_workflow`
89
+ · `sync_workflow_to_git` · `list_schedules` · `create_schedule` · `update_schedule`
90
+ · `delete_schedule` · `backfill_schedule` · `list_dead_letters`
91
+ · `redrive_dead_letter` · `discard_dead_letter` · `list_git_repos`
92
+ · `connect_git_repo` · `sync_git_repo` · `disconnect_git_repo` · `metrics` · `healthz`
93
+
94
+ ## Test
95
+
96
+ ```bash
97
+ python -m unittest # from sdks/python
98
+ ```
99
+
100
+ The suite validates the builder and runs `Client` against a threaded in-process
101
+ fake gateway (real sockets), so request construction is exercised end-to-end.
102
+
103
+ ## Release
104
+
105
+ Publishing `dagron-sdk` to PyPI (the `pip` repository) is documented step-by-step
106
+ in [`RELEASING.md`](RELEASING.md) — version bump, `python -m build`, a TestPyPI
107
+ dry-run, the `twine upload`, tagging, and the move to OIDC Trusted Publishing.
@@ -0,0 +1,5 @@
1
+ dagron.py,sha256=ZUAIp8m5F8w-m4ZSET_lJXHPVSK3h9oZ-IATJrbUMu0,29727
2
+ dagron_sdk-0.2.0.dist-info/METADATA,sha256=Ob0gIvOlS2GrkLR8e0ew7EaBmfqLMFOYDolh18znIxI,4087
3
+ dagron_sdk-0.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
4
+ dagron_sdk-0.2.0.dist-info/top_level.txt,sha256=CCeR54-ftffBFu68F7K8fA24LnP49o5UuLQQcPZk5fo,7
5
+ dagron_sdk-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ dagron