marthouse 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.
Files changed (48) hide show
  1. marthouse/__init__.py +3 -0
  2. marthouse/api/__init__.py +0 -0
  3. marthouse/api/account.py +165 -0
  4. marthouse/api/common.py +23 -0
  5. marthouse/api/dbt.py +155 -0
  6. marthouse/api/jobs_api.py +89 -0
  7. marthouse/api/pipelines_api.py +253 -0
  8. marthouse/api/projects_api.py +268 -0
  9. marthouse/api/schedules_api.py +120 -0
  10. marthouse/api/system.py +110 -0
  11. marthouse/api/tools_api.py +109 -0
  12. marthouse/api/work_api.py +588 -0
  13. marthouse/appsettings.py +60 -0
  14. marthouse/cli.py +40 -0
  15. marthouse/config.py +59 -0
  16. marthouse/db.py +60 -0
  17. marthouse/dbt/__init__.py +0 -0
  18. marthouse/dbt/artifacts.py +435 -0
  19. marthouse/dbt/detect.py +244 -0
  20. marthouse/dbt/install.py +116 -0
  21. marthouse/dlt/__init__.py +1 -0
  22. marthouse/dlt/codegen.py +223 -0
  23. marthouse/dlt/destinations.py +91 -0
  24. marthouse/dlt/inspector.py +57 -0
  25. marthouse/dlt/service.py +382 -0
  26. marthouse/dlt/tool.py +161 -0
  27. marthouse/events.py +107 -0
  28. marthouse/jobs.py +514 -0
  29. marthouse/main.py +71 -0
  30. marthouse/models.py +109 -0
  31. marthouse/profiles.py +265 -0
  32. marthouse/projects.py +294 -0
  33. marthouse/scheduler.py +195 -0
  34. marthouse/schema_yml.py +166 -0
  35. marthouse/secrets_store.py +91 -0
  36. marthouse/security.py +124 -0
  37. marthouse/staging.py +79 -0
  38. marthouse/static/assets/index-CLdMRE6z.css +1 -0
  39. marthouse/static/assets/index-D_M_Ym86.js +45 -0
  40. marthouse/static/icon.svg +1 -0
  41. marthouse/static/index.html +15 -0
  42. marthouse/visual.py +191 -0
  43. marthouse/workers/__init__.py +0 -0
  44. marthouse/workers/worker.py +36 -0
  45. marthouse-0.1.0.dist-info/METADATA +26 -0
  46. marthouse-0.1.0.dist-info/RECORD +48 -0
  47. marthouse-0.1.0.dist-info/WHEEL +4 -0
  48. marthouse-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,253 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import re
5
+
6
+ from fastapi import APIRouter, Depends, HTTPException
7
+ from pydantic import BaseModel
8
+ from sqlalchemy.orm import Session
9
+
10
+ from .. import jobs
11
+ from ..config import get_settings
12
+ from ..db import get_db
13
+ from ..dlt import codegen, service
14
+ from ..models import Job, Project, Schedule
15
+ from ..security import Ctx, ctx, need
16
+ from .common import get_project
17
+ from .jobs_api import job_dict
18
+
19
+ router = APIRouter(prefix="/api/projects/{project_id}/pipelines", tags=["pipelines"])
20
+
21
+
22
+ def _err(e: Exception) -> HTTPException:
23
+ return HTTPException(400, str(e))
24
+
25
+
26
+ def _summary(db: Session, p: Project, spec: dict) -> dict:
27
+ c = service.cached(p, spec["name"]) or {}
28
+ last = (db.query(Job).filter(Job.project_id == p.id, Job.kind.in_(("pipeline", "chain")))
29
+ .order_by(Job.created_at.desc()).limit(40).all())
30
+ last_job = next((j for j in last if any(st.get("pipeline") == spec["name"] for st in j.command)), None)
31
+ rows = (c.get("trace") or {}).get("rows") or {}
32
+ scheds = [s for s in db.query(Schedule).filter(Schedule.project_id == p.id, Schedule.enabled.is_(True))
33
+ if any(st.get("type") == "pipeline" and st.get("name") == spec["name"] for st in s.steps)]
34
+ nxt = min((s.next_run_at for s in scheds if s.next_run_at), default=None)
35
+ return {"name": spec["name"], "kind": spec.get("kind"), "dataset": spec.get("dataset"), "destination": spec.get("destination") or {"type": "dbt"},
36
+ "error": spec.get("error"), "tables": len(c.get("tables") or []), "rows": sum(rows.values()),
37
+ "last_job": job_dict(last_job) if last_job else None, "loaded_at": (c.get("trace") or {}).get("finished_at"),
38
+ "next_run": nxt}
39
+
40
+
41
+ @router.get("")
42
+ def list_pipelines(p: Project = Depends(get_project), db: Session = Depends(get_db)) -> list[dict]:
43
+ return [_summary(db, p, s) for s in service.list_specs(p)]
44
+
45
+
46
+ class SpecBody(BaseModel):
47
+ spec: dict
48
+ secrets: dict[str, str] = {}
49
+
50
+
51
+ @router.post("/preview")
52
+ def preview(body: SpecBody, p: Project = Depends(get_project), db: Session = Depends(get_db)) -> dict:
53
+ spec = body.spec
54
+ errs = codegen.validate(spec)
55
+ try:
56
+ dest, env = service.resolve_destination(db, p, spec)
57
+ dest_err = ""
58
+ except Exception as e:
59
+ dest, env, dest_err = "duckdb", {}, str(e)
60
+ code = ""
61
+ if not errs and spec.get("kind") != "verified":
62
+ try:
63
+ code = codegen.generate(spec, dest)
64
+ except Exception as e:
65
+ errs.append(str(e))
66
+ env_names = sorted(set(re.findall(r'os\.environ\["([A-Z0-9_]+)"\]', code)) | {k for k in env})
67
+ return {"code": code, "errors": errs, "destination": dest, "destination_error": dest_err,
68
+ "secrets": codegen.secret_fields(spec), "env": env_names}
69
+
70
+
71
+ @router.get("/{name}")
72
+ def get_pipeline(name: str, p: Project = Depends(get_project), db: Session = Depends(get_db)) -> dict:
73
+ try:
74
+ spec = service.get_spec(p, name)
75
+ except service.PipelineError as e:
76
+ raise HTTPException(404, str(e)) from e
77
+ from .. import secrets_store
78
+
79
+ script = service.script_path(p, spec)
80
+ secrets = [{**f, "stored": secrets_store.has_secret(db, p.workspace_id, codegen.secret_env(name, f["key"]))}
81
+ for f in codegen.secret_fields(spec)]
82
+ return {"spec": spec, "summary": _summary(db, p, spec), "inspect": service.cached(p, name),
83
+ "code": script.read_text() if script.exists() else "", "script": script.name, "secrets": secrets}
84
+
85
+
86
+ @router.put("/{name}")
87
+ def save(name: str, body: SpecBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member")),
88
+ db: Session = Depends(get_db)) -> dict:
89
+ spec = {**body.spec, "name": name}
90
+ try:
91
+ return {"spec": service.save(db, p, spec, body.secrets)}
92
+ except Exception as e:
93
+ raise _err(e) from e
94
+
95
+
96
+ @router.delete("/{name}")
97
+ def delete(name: str, p: Project = Depends(get_project), c: Ctx = Depends(need("member"))) -> dict:
98
+ try:
99
+ service.delete(p, name)
100
+ except service.PipelineError as e:
101
+ raise HTTPException(404, str(e)) from e
102
+ return {"ok": True}
103
+
104
+
105
+ class RunBody(BaseModel):
106
+ refresh: bool = False
107
+ then_build: bool = False # load, then dbt build everything that reads this dataset
108
+
109
+
110
+ @router.post("/{name}/run")
111
+ async def run(name: str, body: RunBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member")),
112
+ db: Session = Depends(get_db)) -> dict:
113
+ try:
114
+ spec = service.get_spec(p, name)
115
+ step = service.run_step(db, p, spec)
116
+ step["refresh"] = body.refresh
117
+ steps = [step]
118
+ kind, title = "pipeline", f"Load {name}" + (" (full refresh)" if body.refresh else "")
119
+ if body.then_build:
120
+ dbt = jobs.resolve_dbt(db, p, c.ws)
121
+ params = {"select": f"source:{spec['dataset']}+"}
122
+ steps.append({"label": jobs.describe("build", params), "argv": jobs.dbt_argv(dbt, "build", params, p), "dbt": "build"})
123
+ kind, title = "chain", f"Load {name}, then build what reads it"
124
+ job = jobs.create(db, c.ws, kind, {"pipeline": name}, p, steps=steps, title=title)
125
+ except (service.PipelineError, jobs.JobError) as e:
126
+ raise _err(e) from e
127
+ await jobs.dispatch(job.id)
128
+ return job_dict(job)
129
+
130
+
131
+ @router.post("/{name}/inspect")
132
+ async def inspect(name: str, p: Project = Depends(get_project), db: Session = Depends(get_db)) -> dict:
133
+ try:
134
+ return await asyncio.to_thread(service.inspect, db, p, name)
135
+ except Exception as e:
136
+ raise _err(e) from e
137
+
138
+
139
+ class QueryBody(BaseModel):
140
+ table: str
141
+ limit: int = 100
142
+
143
+
144
+ @router.post("/{name}/data")
145
+ async def data(name: str, body: QueryBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member")),
146
+ db: Session = Depends(get_db)) -> dict:
147
+ """Preview a loaded table. Uses dbt show when there's a dbt project on the same connection."""
148
+ spec = service.get_spec(p, name)
149
+ if not re.fullmatch(r"[a-z0-9_]+", body.table):
150
+ raise HTTPException(400, "Bad table name.")
151
+ from ..projects import info
152
+
153
+ if not info(p.path)["has_dbt"]:
154
+ raise HTTPException(409, "Previewing rows needs a dbt project on the same connection.")
155
+ sql = f"select * from {spec['dataset']}.{body.table}"
156
+ job = await jobs.run_now(db, c.ws, "show", {"inline": sql, "limit": min(body.limit, 1000)}, p)
157
+ rows = (job.result or {}).get("rows") or []
158
+ errs = [l.split("\t", 1)[-1] for l in (job.log or "").splitlines() if l.startswith("err\t")]
159
+ return {"rows": rows, "columns": list(rows[0].keys()) if rows else [], "errors": errs, "sql": sql}
160
+
161
+
162
+ @router.post("/{name}/dbt-sources")
163
+ def dbt_sources(name: str, p: Project = Depends(get_project), c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
164
+ spec = service.get_spec(p, name)
165
+ try:
166
+ dest, _ = service.resolve_destination(db, p, spec)
167
+ adapter = {"mssql": "sqlserver", "motherduck": "duckdb"}.get(dest, dest)
168
+ return service.generate_sources(p, name, adapter)
169
+ except Exception as e:
170
+ raise _err(e) from e
171
+
172
+
173
+ class TryBody(BaseModel):
174
+ url: str
175
+ headers: dict[str, str] = {}
176
+ auth: dict = {}
177
+ secret: str = ""
178
+
179
+
180
+ @router.post("/try-request")
181
+ async def try_request(body: TryBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member"))) -> dict:
182
+ headers = dict(body.headers)
183
+ t = body.auth.get("type")
184
+ if t == "bearer" and body.secret:
185
+ headers["Authorization"] = f"Bearer {body.secret}"
186
+ elif t == "api_key" and body.secret and body.auth.get("location", "header") == "header":
187
+ headers[body.auth.get("name") or "X-API-Key"] = body.secret
188
+ url = body.url
189
+ if t == "api_key" and body.secret and body.auth.get("location") == "query":
190
+ url += ("&" if "?" in url else "?") + f"{body.auth.get('name') or 'api_key'}={body.secret}"
191
+ try:
192
+ return await asyncio.to_thread(service.try_request, url, headers, get_settings().hosted)
193
+ except service.PipelineError as e:
194
+ raise _err(e) from e
195
+ except Exception as e:
196
+ raise HTTPException(400, f"The request failed: {e}") from e
197
+
198
+
199
+ @router.get("-verified")
200
+ async def verified(p: Project = Depends(get_project), c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> list[dict]:
201
+ try:
202
+ py = service.default_python(db, c.ws, p)
203
+ return await asyncio.to_thread(service.verified_sources, py)
204
+ except Exception as e:
205
+ raise _err(e) from e
206
+
207
+
208
+ class InitBody(BaseModel):
209
+ source: str
210
+ name: str
211
+ dataset: str
212
+ destination: dict = {"type": "dbt"}
213
+
214
+
215
+ @router.post("-verified")
216
+ async def init_verified(body: InitBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member")),
217
+ db: Session = Depends(get_db)) -> dict:
218
+ """Runs `dlt init <source> <destination>` in pipelines/ and records a spec for it."""
219
+ if not re.fullmatch(r"[a-z0-9_]+", body.source) or not codegen.NAME_RE.match(body.name):
220
+ raise HTTPException(400, "Use lowercase letters, numbers and _.")
221
+ spec = {"name": body.name, "kind": "verified", "dataset": body.dataset, "destination": body.destination,
222
+ "verified": {"source": body.source, "script": f"{body.source}_pipeline.py"}}
223
+ try:
224
+ dest, _ = service.resolve_destination(db, p, spec)
225
+ py = service.default_python(db, c.ws, p)
226
+ except Exception as e:
227
+ raise _err(e) from e
228
+ from pathlib import Path
229
+
230
+ d = service.pdir(p)
231
+ d.mkdir(parents=True, exist_ok=True)
232
+ dlt_bin = str(Path(py).with_name("dlt"))
233
+ steps = [{"label": f"dlt init {body.source} {dest}", "argv": [dlt_bin, "--non-interactive", "--yes", "init", body.source, dest], "cwd": str(d)}]
234
+ job = jobs.create(db, c.ws, "dlt_init", {"source": body.source, "name": body.name}, p, steps=steps, title=f"Add the {body.source} source")
235
+ service.save(db, p, spec, {})
236
+ await jobs.dispatch(job.id)
237
+ return {"job_id": job.id}
238
+
239
+
240
+ @router.post("/{name}/verified-refresh")
241
+ def verified_refresh(name: str, p: Project = Depends(get_project), c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
242
+ """After dlt init: find the pipeline name in the script and the secrets it expects."""
243
+ spec = service.get_spec(p, name)
244
+ v = spec.get("verified") or {}
245
+ script = service.script_path(p, spec)
246
+ if not script.exists():
247
+ raise HTTPException(409, "dlt init hasn't written the script yet.")
248
+ m = re.findall(r'pipeline_name\s*=\s*["\']([A-Za-z0-9_]+)["\']', script.read_text())
249
+ v["pipeline_name"] = m[0] if m else v.get("pipeline_name") or name
250
+ v["secret_keys"] = service.read_verified_secrets(p, v["source"])
251
+ spec["verified"] = v
252
+ service.save(db, p, spec, {})
253
+ return {"spec": spec}
@@ -0,0 +1,268 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ from fastapi import APIRouter, Depends, HTTPException
8
+ from pydantic import BaseModel
9
+ from sqlalchemy.orm import Session
10
+
11
+ from .. import appsettings, jobs, projects, secrets_store
12
+ from ..config import get_settings
13
+ from ..db import get_db
14
+ from ..dbt import artifacts
15
+ from ..models import Project, now
16
+ from ..security import Ctx, ctx, need
17
+ from .common import get_project, tp
18
+
19
+ router = APIRouter(prefix="/api/projects", tags=["projects"])
20
+
21
+
22
+ def project_dict(db: Session, p: Project, full: bool = False) -> dict:
23
+ d = {"id": p.id, "name": p.name, "path": p.path if not get_settings().hosted else "", "git_url": p.git_url,
24
+ "last_opened": p.last_opened, "exists": Path(p.path).is_dir()}
25
+ if not d["exists"]:
26
+ return d
27
+ try:
28
+ i = projects.info(p.path)
29
+ d.update({"profile": i["profile"], "n_models": i["n_models"]})
30
+ except projects.ProjectError as e:
31
+ d["error"] = str(e)
32
+ return d
33
+ g = projects.git_info(p.path)
34
+ d["branch"] = g["branch"] if g else None
35
+ if full:
36
+ d["git"] = g
37
+ d["stale"] = projects.stale_files(p.path)
38
+ d["has_manifest"] = artifacts.manifest(p.path, tp(p)) is not None
39
+ d["info"] = i
40
+ try:
41
+ d["dbt"] = jobs.resolve_dbt(db, p, p.workspace_id)
42
+ d["dbt_missing"] = False
43
+ except jobs.JobError as e:
44
+ d["dbt"], d["dbt_missing"], d["dbt_error"] = None, True, str(e)
45
+ d["dbt_override"] = p.dbt_path
46
+ d["venv_has_dbt"] = (Path(p.path) / ".venv" / "bin" / "dbt").exists()
47
+ d["venv_exists"] = (Path(p.path) / ".venv").exists()
48
+ d["requirements"] = (Path(p.path) / "requirements.txt").exists()
49
+ d["profiles_path"] = str(jobs.profiles_path(p)) if not get_settings().hosted else "profiles.yml"
50
+ return d
51
+
52
+
53
+ @router.get("")
54
+ def list_projects(c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> list[dict]:
55
+ rows = db.query(Project).filter(Project.workspace_id == c.ws).order_by(Project.last_opened.desc()).all()
56
+ return [project_dict(db, p) for p in rows]
57
+
58
+
59
+ @router.get("/{project_id}")
60
+ def get(p: Project = Depends(get_project), db: Session = Depends(get_db)) -> dict:
61
+ p.last_opened = now()
62
+ db.commit()
63
+ appsettings.update(db, {"last_project": p.id}, p.workspace_id)
64
+ return project_dict(db, p, full=True)
65
+
66
+
67
+ def _register(db: Session, c: Ctx, path: Path, git_url: str = "") -> Project:
68
+ info = projects.info(path)
69
+ existing = db.query(Project).filter(Project.workspace_id == c.ws, Project.path == str(path)).first()
70
+ if existing:
71
+ existing.last_opened = now()
72
+ db.commit()
73
+ return existing
74
+ p = Project(workspace_id=c.ws, name=info["name"], path=str(path), git_url=git_url)
75
+ db.add(p)
76
+ db.commit()
77
+ return p
78
+
79
+
80
+ class OpenBody(BaseModel):
81
+ path: str
82
+
83
+
84
+ @router.post("/open")
85
+ def open_project(body: OpenBody, c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
86
+ if get_settings().hosted:
87
+ raise HTTPException(400, "In the hosted app, add projects from Git.")
88
+ path = Path(body.path).expanduser().resolve()
89
+ try:
90
+ return project_dict(db, _register(db, c, path))
91
+ except projects.ProjectError as e:
92
+ raise HTTPException(400, str(e)) from e
93
+
94
+
95
+ class NewBody(BaseModel):
96
+ name: str
97
+ parent: str = "~"
98
+ kind: str = "dbt" # dbt | pipelines
99
+
100
+
101
+ @router.post("/new")
102
+ def new_project(body: NewBody, c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
103
+ parent = Path(body.parent).expanduser()
104
+ if get_settings().hosted:
105
+ parent = get_settings().workspaces_dir / c.ws / "projects"
106
+ try:
107
+ root = projects.scaffold_pipelines_only(parent, body.name) if body.kind == "pipelines" else projects.scaffold(parent, body.name)
108
+ return project_dict(db, _register(db, c, root))
109
+ except projects.ProjectError as e:
110
+ raise HTTPException(400, str(e)) from e
111
+
112
+
113
+ class CloneBody(BaseModel):
114
+ url: str
115
+ branch: str = ""
116
+ token: str = ""
117
+ parent: str = "~/code"
118
+ subdir: str = "" # dbt project inside the repo, if not at its root
119
+
120
+
121
+ @router.post("/clone")
122
+ async def clone(body: CloneBody, c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
123
+ import asyncio
124
+ import re
125
+
126
+ name = re.sub(r"\.git$", "", body.url.rstrip("/").split("/")[-1]) or "project"
127
+ name = re.sub(r"[^A-Za-z0-9_.-]", "_", name)
128
+ if get_settings().hosted:
129
+ if not body.url.startswith("https://"):
130
+ raise HTTPException(400, "Use an https:// Git URL.")
131
+ parent = get_settings().workspaces_dir / c.ws / "projects"
132
+ else:
133
+ parent = Path(body.parent).expanduser()
134
+ parent.mkdir(parents=True, exist_ok=True)
135
+ dest = parent / name
136
+ n = 2
137
+ while dest.exists():
138
+ dest = parent / f"{name}-{n}"
139
+ n += 1
140
+ try:
141
+ await asyncio.to_thread(projects.git_clone, body.url, dest, body.branch, body.token or None)
142
+ root = dest / body.subdir if body.subdir else dest
143
+ p = _register(db, c, root.resolve(), git_url=body.url)
144
+ except projects.ProjectError as e:
145
+ if dest.exists() and get_settings().hosted:
146
+ shutil.rmtree(dest, ignore_errors=True)
147
+ raise HTTPException(400, str(e)) from e
148
+ if body.token:
149
+ secrets_store.set_secret(db, c.ws, f"GIT_{p.id}", body.token)
150
+ return project_dict(db, p)
151
+
152
+
153
+ class PatchBody(BaseModel):
154
+ dbt_path: str | None = None
155
+ profiles_dir: str | None = None
156
+ name: str | None = None
157
+
158
+
159
+ @router.patch("/{project_id}")
160
+ def patch(body: PatchBody, p: Project = Depends(get_project), c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
161
+ if body.dbt_path is not None:
162
+ if body.dbt_path and not os.access(body.dbt_path, os.X_OK):
163
+ raise HTTPException(400, "No dbt at that path.")
164
+ p.dbt_path = body.dbt_path
165
+ if body.profiles_dir is not None and not get_settings().hosted:
166
+ p.profiles_dir = body.profiles_dir
167
+ if body.name:
168
+ p.name = body.name
169
+ db.commit()
170
+ return project_dict(db, p, full=True)
171
+
172
+
173
+ @router.delete("/{project_id}")
174
+ def forget(p: Project = Depends(get_project), c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
175
+ """Removes the project from Lineage. Local files are kept; hosted checkouts are deleted."""
176
+ if get_settings().hosted:
177
+ shutil.rmtree(p.path, ignore_errors=True)
178
+ db.delete(p)
179
+ db.commit()
180
+ return {"ok": True}
181
+
182
+
183
+ # ---------- files ----------
184
+
185
+ @router.get("/{project_id}/tree")
186
+ def tree(p: Project = Depends(get_project)) -> list[dict]:
187
+ return projects.tree(p.path)
188
+
189
+
190
+ @router.get("/{project_id}/file")
191
+ def read_file(path: str, p: Project = Depends(get_project)) -> dict:
192
+ try:
193
+ f = projects.read_file(p.path, path)
194
+ except projects.ProjectError as e:
195
+ raise HTTPException(400, str(e)) from e
196
+ f["node"] = artifacts.node_for_path(p.path, path, tp(p))
197
+ if path.endswith(".sql"):
198
+ from .. import visual
199
+
200
+ v = visual.parse(f["content"])
201
+ f["visual"] = {"edited": v["edited"]} if v else None
202
+ return f
203
+
204
+
205
+ class WriteBody(BaseModel):
206
+ path: str
207
+ content: str
208
+
209
+
210
+ @router.put("/{project_id}/file")
211
+ def write_file(body: WriteBody, p: Project = Depends(get_project), _: Ctx = Depends(need("member"))) -> dict:
212
+ try:
213
+ return projects.write_file(p.path, body.path, body.content)
214
+ except projects.ProjectError as e:
215
+ raise HTTPException(400, str(e)) from e
216
+
217
+
218
+ class RenameBody(BaseModel):
219
+ path: str
220
+ new_path: str
221
+
222
+
223
+ @router.post("/{project_id}/file/rename")
224
+ def rename(body: RenameBody, p: Project = Depends(get_project), _: Ctx = Depends(need("member"))) -> dict:
225
+ try:
226
+ projects.rename_file(p.path, body.path, body.new_path)
227
+ except (projects.ProjectError, OSError) as e:
228
+ raise HTTPException(400, str(e)) from e
229
+ return {"ok": True}
230
+
231
+
232
+ @router.delete("/{project_id}/file")
233
+ def delete(path: str, p: Project = Depends(get_project), _: Ctx = Depends(need("member"))) -> dict:
234
+ try:
235
+ projects.delete_file(p.path, path)
236
+ except projects.ProjectError as e:
237
+ raise HTTPException(400, str(e)) from e
238
+ return {"ok": True}
239
+
240
+
241
+ # ---------- git ----------
242
+
243
+ @router.get("/{project_id}/git")
244
+ def git(p: Project = Depends(get_project)) -> dict | None:
245
+ return projects.git_info(p.path)
246
+
247
+
248
+ @router.post("/{project_id}/git/pull")
249
+ def pull(p: Project = Depends(get_project), c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
250
+ try:
251
+ return {"output": projects.git_pull(p.path, secrets_store.get_secret(db, c.ws, f"GIT_{p.id}"))}
252
+ except projects.ProjectError as e:
253
+ raise HTTPException(400, str(e)) from e
254
+
255
+
256
+ class CommitBody(BaseModel):
257
+ message: str
258
+ push: bool = True
259
+
260
+
261
+ @router.post("/{project_id}/git/commit")
262
+ def commit(body: CommitBody, p: Project = Depends(get_project), c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
263
+ author = f"{c.user.name or c.user.email} <{c.user.email}>" if c.user else ""
264
+ try:
265
+ return {"output": projects.git_commit_push(p.path, body.message, author,
266
+ secrets_store.get_secret(db, c.ws, f"GIT_{p.id}"), body.push)}
267
+ except projects.ProjectError as e:
268
+ raise HTTPException(400, str(e)) from e
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
4
+
5
+ from fastapi import APIRouter, Depends, HTTPException
6
+ from pydantic import BaseModel
7
+ from sqlalchemy.orm import Session
8
+
9
+ from .. import jobs, scheduler, secrets_store
10
+ from ..db import get_db
11
+ from ..models import Job, Project, Schedule
12
+ from ..security import Ctx, ctx, need
13
+ from .common import get_project
14
+ from .jobs_api import job_dict
15
+
16
+ router = APIRouter(prefix="/api/projects/{project_id}/schedules", tags=["schedules"])
17
+
18
+
19
+ def sched_dict(db: Session, s: Schedule) -> dict:
20
+ last = db.get(Job, s.last_job_id) if s.last_job_id else None
21
+ return {"id": s.id, "name": s.name, "cadence": s.cadence, "steps": s.steps, "enabled": s.enabled,
22
+ "description": scheduler.describe(s.cadence), "next_run_at": s.next_run_at, "last_run_at": s.last_run_at,
23
+ "last_job": job_dict(last) if last else None, "alert_on_failure": s.alert_on_failure,
24
+ "has_webhook": secrets_store.has_secret(db, s.workspace_id, f"WEBHOOK_{s.id}")}
25
+
26
+
27
+ @router.get("")
28
+ def list_schedules(p: Project = Depends(get_project), db: Session = Depends(get_db)) -> list[dict]:
29
+ return [sched_dict(db, s) for s in db.query(Schedule).filter(Schedule.project_id == p.id).order_by(Schedule.created_at)]
30
+
31
+
32
+ class Body(BaseModel):
33
+ name: str
34
+ cadence: dict
35
+ steps: list[dict]
36
+ enabled: bool = True
37
+ alert_on_failure: bool = False
38
+ webhook_url: str = ""
39
+
40
+
41
+ def _check(body: Body, db: Session, p: Project, ws: str) -> datetime:
42
+ if not body.name.strip():
43
+ raise HTTPException(400, "Give the schedule a name.")
44
+ try:
45
+ nxt = scheduler.next_run(body.cadence, datetime.now(timezone.utc))
46
+ scheduler.build_steps(db, p, body.steps, ws)
47
+ except (scheduler.CadenceError, jobs.JobError, ValueError) as e:
48
+ raise HTTPException(400, str(e)) from e
49
+ except Exception as e: # e.g. a pipeline that no longer exists
50
+ raise HTTPException(400, str(e)) from e
51
+ if body.webhook_url and not body.webhook_url.startswith("https://"):
52
+ raise HTTPException(400, "Use an https:// webhook URL.")
53
+ return nxt
54
+
55
+
56
+ @router.post("")
57
+ def create(body: Body, p: Project = Depends(get_project), c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
58
+ nxt = _check(body, db, p, c.ws)
59
+ s = Schedule(workspace_id=c.ws, project_id=p.id, name=body.name.strip(), cadence=body.cadence, steps=body.steps,
60
+ enabled=body.enabled, alert_on_failure=body.alert_on_failure, next_run_at=nxt if body.enabled else None)
61
+ db.add(s)
62
+ db.commit()
63
+ if body.webhook_url:
64
+ secrets_store.set_secret(db, c.ws, f"WEBHOOK_{s.id}", body.webhook_url)
65
+ return sched_dict(db, s)
66
+
67
+
68
+ def _get(db: Session, p: Project, sid: str) -> Schedule:
69
+ s = db.get(Schedule, sid)
70
+ if s is None or s.project_id != p.id:
71
+ raise HTTPException(404, "Schedule not found.")
72
+ return s
73
+
74
+
75
+ @router.put("/{sid}")
76
+ def update(sid: str, body: Body, p: Project = Depends(get_project), c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
77
+ s = _get(db, p, sid)
78
+ nxt = _check(body, db, p, c.ws)
79
+ s.name, s.cadence, s.steps, s.enabled, s.alert_on_failure = body.name.strip(), body.cadence, body.steps, body.enabled, body.alert_on_failure
80
+ s.next_run_at = nxt if body.enabled else None
81
+ db.commit()
82
+ if body.webhook_url:
83
+ secrets_store.set_secret(db, c.ws, f"WEBHOOK_{s.id}", body.webhook_url)
84
+ return sched_dict(db, s)
85
+
86
+
87
+ @router.delete("/{sid}")
88
+ def delete(sid: str, p: Project = Depends(get_project), c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
89
+ s = _get(db, p, sid)
90
+ secrets_store.delete_secret(db, c.ws, f"WEBHOOK_{s.id}")
91
+ db.delete(s)
92
+ db.commit()
93
+ return {"ok": True}
94
+
95
+
96
+ @router.post("/{sid}/run")
97
+ async def run_now(sid: str, p: Project = Depends(get_project), c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
98
+ s = _get(db, p, sid)
99
+ try:
100
+ job = await scheduler.start(db, s, manual=True)
101
+ except jobs.JobError as e:
102
+ raise HTTPException(400, str(e)) from e
103
+ return job_dict(job)
104
+
105
+
106
+ class PreviewBody(BaseModel):
107
+ cadence: dict
108
+
109
+
110
+ @router.post("-preview")
111
+ def preview(body: PreviewBody, p: Project = Depends(get_project), c: Ctx = Depends(ctx)) -> dict:
112
+ try:
113
+ t = datetime.now(timezone.utc)
114
+ runs = []
115
+ for _ in range(3):
116
+ t = scheduler.next_run(body.cadence, t)
117
+ runs.append(t)
118
+ return {"next": runs, "description": scheduler.describe(body.cadence), "cron": scheduler.to_cron(body.cadence)}
119
+ except scheduler.CadenceError as e:
120
+ raise HTTPException(400, str(e)) from e