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
marthouse/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Marthouse: a GUI for dbt Core and dlt."""
2
+
3
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,165 @@
1
+ """Team mode: accounts, workspaces and members."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from fastapi import APIRouter, Depends, HTTPException, Request, Response
7
+ from pydantic import BaseModel
8
+ from sqlalchemy.orm import Session
9
+
10
+ from ..config import get_settings
11
+ from ..db import get_db
12
+ from ..models import Membership, User, Workspace
13
+ from ..security import COOKIE, ROLES, Ctx, ctx, end_session, hash_password, need, new_session, verify_password
14
+
15
+ router = APIRouter(prefix="/api", tags=["account"])
16
+ EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
17
+
18
+
19
+ def _hosted() -> None:
20
+ if not get_settings().hosted:
21
+ raise HTTPException(404, "Accounts are only used in the hosted app.")
22
+
23
+
24
+ def _set_cookie(resp: Response, token: str) -> None:
25
+ resp.set_cookie(COOKIE, token, httponly=True, samesite="lax", secure=get_settings().cookie_secure, max_age=30 * 86400)
26
+
27
+
28
+ class SignupBody(BaseModel):
29
+ email: str
30
+ password: str
31
+ name: str = ""
32
+ workspace: str = ""
33
+
34
+
35
+ @router.post("/auth/signup")
36
+ def signup(body: SignupBody, resp: Response, db: Session = Depends(get_db)) -> dict:
37
+ _hosted()
38
+ email = body.email.strip().lower()
39
+ if not EMAIL.match(email):
40
+ raise HTTPException(400, "Enter a valid email address.")
41
+ if len(body.password) < 10:
42
+ raise HTTPException(400, "Use at least 10 characters for the password.")
43
+ if db.query(User).filter(User.email == email).first():
44
+ raise HTTPException(409, "There's already an account with this email. Sign in instead.")
45
+ u = User(email=email, name=body.name.strip(), password_hash=hash_password(body.password))
46
+ db.add(u)
47
+ db.flush()
48
+ w = Workspace(name=body.workspace.strip() or (f"{body.name.split()[0]}'s workspace" if body.name.strip() else "My workspace"))
49
+ db.add(w)
50
+ db.flush()
51
+ db.add(Membership(workspace_id=w.id, user_id=u.id, role="owner"))
52
+ db.commit()
53
+ _set_cookie(resp, new_session(db, u))
54
+ return {"ok": True, "workspace": w.id}
55
+
56
+
57
+ class LoginBody(BaseModel):
58
+ email: str
59
+ password: str
60
+
61
+
62
+ @router.post("/auth/login")
63
+ def login(body: LoginBody, resp: Response, db: Session = Depends(get_db)) -> dict:
64
+ _hosted()
65
+ u = db.query(User).filter(User.email == body.email.strip().lower()).first()
66
+ if u is None or not verify_password(u.password_hash, body.password):
67
+ raise HTTPException(401, "That email and password don't match.")
68
+ _set_cookie(resp, new_session(db, u))
69
+ return {"ok": True}
70
+
71
+
72
+ @router.post("/auth/logout")
73
+ def logout(request: Request, resp: Response, db: Session = Depends(get_db)) -> dict:
74
+ tok = request.cookies.get(COOKIE)
75
+ if tok:
76
+ end_session(db, tok)
77
+ resp.delete_cookie(COOKIE)
78
+ return {"ok": True}
79
+
80
+
81
+ class WsBody(BaseModel):
82
+ name: str
83
+
84
+
85
+ @router.post("/workspaces")
86
+ def create_ws(body: WsBody, c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> dict:
87
+ _hosted()
88
+ w = Workspace(name=body.name.strip() or "Workspace")
89
+ db.add(w)
90
+ db.flush()
91
+ db.add(Membership(workspace_id=w.id, user_id=c.user.id, role="owner"))
92
+ db.commit()
93
+ return {"id": w.id, "name": w.name, "role": "owner"}
94
+
95
+
96
+ @router.patch("/workspace")
97
+ def rename_ws(body: WsBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
98
+ _hosted()
99
+ c.workspace.name = body.name.strip() or c.workspace.name
100
+ db.commit()
101
+ return {"ok": True}
102
+
103
+
104
+ @router.get("/workspace")
105
+ def workspace(c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> dict:
106
+ _hosted()
107
+ rows = db.query(Membership, User).join(User, User.id == Membership.user_id).filter(Membership.workspace_id == c.ws).all()
108
+ w = c.workspace
109
+ return {"id": w.id, "name": w.name, "role": c.role,
110
+ "members": [{"id": u.id, "email": u.email, "name": u.name, "role": m.role, "you": u.id == c.user.id} for m, u in rows]}
111
+
112
+
113
+ class MemberBody(BaseModel):
114
+ email: str
115
+ role: str = "member"
116
+
117
+
118
+ @router.post("/workspace/members")
119
+ def add_member(body: MemberBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
120
+ _hosted()
121
+ if body.role not in ROLES or (body.role == "owner" and c.role != "owner"):
122
+ raise HTTPException(400, "Choose another role.")
123
+ u = db.query(User).filter(User.email == body.email.strip().lower()).first()
124
+ if u is None:
125
+ raise HTTPException(404, "Ask them to sign up first, then add them here.")
126
+ if db.query(Membership).filter(Membership.workspace_id == c.ws, Membership.user_id == u.id).first():
127
+ raise HTTPException(409, "They're already a member.")
128
+ db.add(Membership(workspace_id=c.ws, user_id=u.id, role=body.role))
129
+ db.commit()
130
+ return {"ok": True}
131
+
132
+
133
+ class RoleBody(BaseModel):
134
+ role: str
135
+
136
+
137
+ @router.patch("/workspace/members/{user_id}")
138
+ def set_role(user_id: str, body: RoleBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
139
+ _hosted()
140
+ m = db.query(Membership).filter(Membership.workspace_id == c.ws, Membership.user_id == user_id).first()
141
+ if m is None or body.role not in ROLES:
142
+ raise HTTPException(404)
143
+ if (m.role == "owner" or body.role == "owner") and c.role != "owner":
144
+ raise HTTPException(403, "Only an owner can change owners.")
145
+ if m.role == "owner" and body.role != "owner":
146
+ owners = db.query(Membership).filter(Membership.workspace_id == c.ws, Membership.role == "owner").count()
147
+ if owners <= 1:
148
+ raise HTTPException(400, "A workspace needs at least one owner.")
149
+ m.role = body.role
150
+ db.commit()
151
+ return {"ok": True}
152
+
153
+
154
+ @router.delete("/workspace/members/{user_id}")
155
+ def remove_member(user_id: str, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
156
+ _hosted()
157
+ m = db.query(Membership).filter(Membership.workspace_id == c.ws, Membership.user_id == user_id).first()
158
+ if m is None:
159
+ raise HTTPException(404)
160
+ if m.role == "owner" and db.query(Membership).filter(Membership.workspace_id == c.ws, Membership.role == "owner").count() <= 1:
161
+ raise HTTPException(400, "A workspace needs at least one owner.")
162
+ db.delete(m)
163
+ db.commit()
164
+ return {"ok": True}
165
+
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import Depends, HTTPException
4
+ from sqlalchemy.orm import Session
5
+
6
+ from ..db import get_db
7
+ from ..models import Project
8
+ from ..projects import info
9
+ from ..security import Ctx, ctx
10
+
11
+
12
+ def get_project(project_id: str, c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> Project:
13
+ p = db.get(Project, project_id)
14
+ if p is None or p.workspace_id != c.ws:
15
+ raise HTTPException(404, "Project not found.")
16
+ return p
17
+
18
+
19
+ def tp(p: Project) -> str:
20
+ try:
21
+ return info(p.path)["target_path"]
22
+ except Exception:
23
+ return "target"
marthouse/api/dbt.py ADDED
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
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
12
+ from ..config import get_settings
13
+ from ..db import get_db
14
+ from ..dbt import detect, install
15
+ from ..models import Project
16
+ from ..security import Ctx, ctx, need
17
+
18
+ router = APIRouter(prefix="/api/dbt", tags=["dbt"])
19
+
20
+
21
+ def _project_dirs(db: Session, ws: str) -> list[str]:
22
+ return [p.path for p in db.query(Project).filter(Project.workspace_id == ws).order_by(Project.last_opened.desc()).limit(20)]
23
+
24
+
25
+ def _decorate(installs: list[dict], st: dict) -> list[dict]:
26
+ hidden = set(st.get("hidden_installs") or [])
27
+ default = st.get("default_dbt") or ""
28
+ if not default:
29
+ ok = [i for i in installs if i["status"] == "ok"]
30
+ default = ok[0]["path"] if ok else ""
31
+ for i in installs:
32
+ i["default"] = i["path"] == default
33
+ i["hidden"] = i["path"] in hidden
34
+ i["allowed"] = detect.allowed(i.get("core"), st.get("allowed_versions"))
35
+ return installs
36
+
37
+
38
+ @router.get("/locations")
39
+ def locations(c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> list[dict]:
40
+ if get_settings().hosted:
41
+ return [{"id": "private", "label": "Workspace installs", "detail": "dbt installed on Marthouse's servers"}]
42
+ return [l.__dict__ for l in detect.locations(_project_dirs(db, c.ws))]
43
+
44
+
45
+ @router.get("/scan")
46
+ async def scan(loc: str | None = None, c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> list[dict]:
47
+ """One location at a time (so the first-run screen can tick them off), or everything."""
48
+ dirs = _project_dirs(db, c.ws)
49
+ st = appsettings.get_all(db, c.ws)
50
+ locs = ["private"] if get_settings().hosted else ([loc] if loc else [l.id for l in detect.locations(dirs)])
51
+
52
+ def work() -> list[dict]:
53
+ seen: set[str] = set()
54
+ out: list[dict] = []
55
+ for l in locs:
56
+ out += [i.to_dict() for i in detect.scan_location(l, dirs, seen)]
57
+ return out
58
+
59
+ found = await asyncio.to_thread(work)
60
+ custom = st.get("default_dbt")
61
+ if not loc and custom and all(os.path.realpath(i["path"]) != os.path.realpath(custom) for i in found) and os.path.exists(custom):
62
+ found.append(detect.inspect(custom, "custom").to_dict())
63
+ return _decorate(found, st)
64
+
65
+
66
+ class PathBody(BaseModel):
67
+ path: str
68
+
69
+
70
+ @router.post("/inspect")
71
+ async def inspect(body: PathBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
72
+ if get_settings().hosted:
73
+ raise HTTPException(404)
74
+ p = Path(body.path).expanduser()
75
+ if p.is_dir():
76
+ p = p / "bin" / "dbt" if (p / "bin" / "dbt").exists() else p / "dbt"
77
+ private = get_settings().private_dbt_dir.resolve()
78
+ kind = "private" if private in p.resolve().parents else "project" if ".venv" in p.parts else "custom"
79
+ inst = await asyncio.to_thread(detect.inspect, str(p), kind)
80
+ return _decorate([inst.to_dict()], appsettings.get_all(db, c.ws))[0]
81
+
82
+
83
+ @router.post("/default")
84
+ def set_default(body: PathBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
85
+ appsettings.update(db, {"default_dbt": body.path}, c.ws)
86
+ return {"ok": True}
87
+
88
+
89
+ class HideBody(BaseModel):
90
+ path: str
91
+ hidden: bool = True
92
+
93
+
94
+ @router.post("/hide")
95
+ def hide(body: HideBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
96
+ cur = set(appsettings.get(db, "hidden_installs", c.ws) or [])
97
+ (cur.add if body.hidden else cur.discard)(body.path)
98
+ appsettings.update(db, {"hidden_installs": sorted(cur)}, c.ws)
99
+ return {"ok": True}
100
+
101
+
102
+ @router.get("/versions")
103
+ async def versions(c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> dict:
104
+ st = appsettings.get_all(db, c.ws)
105
+ return await asyncio.to_thread(install.available_versions, st["allowed_versions"], st["index_url"])
106
+
107
+
108
+ @router.get("/adapters")
109
+ def adapters() -> list[dict]:
110
+ return install.ADAPTERS
111
+
112
+
113
+ class InstallBody(BaseModel):
114
+ version: str
115
+ adapters: list[str]
116
+ location: str = "private" # private|project
117
+ project_id: str | None = None
118
+ python: str = "3.12"
119
+ make_default: bool = True
120
+ offline_folder: str | None = None
121
+
122
+
123
+ def _plan(body: InstallBody, c: Ctx, db: Session) -> tuple[list[dict], Path]:
124
+ st = appsettings.get_all(db, c.ws)
125
+ target = None
126
+ if body.location == "project":
127
+ if get_settings().hosted:
128
+ raise HTTPException(400, "The hosted app installs dbt for the whole workspace.")
129
+ proj = db.get(Project, body.project_id or "")
130
+ if proj is None or proj.workspace_id != c.ws:
131
+ raise HTTPException(400, "Choose a project first.")
132
+ target = str(Path(proj.path) / ".venv")
133
+ try:
134
+ steps, root = install.install_steps(body.version, body.adapters, python=body.python, index_url=st["index_url"],
135
+ offline_folder=body.offline_folder if body.offline_folder is not None else st["offline_folder"],
136
+ target_dir=target)
137
+ except ValueError as e:
138
+ raise HTTPException(400, str(e)) from e
139
+ return steps, root
140
+
141
+
142
+ @router.post("/install/plan")
143
+ def install_plan(body: InstallBody, c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> dict:
144
+ steps, root = _plan(body, c, db)
145
+ return {"root": str(root), "steps": [{"label": s["label"], "display": install.display(s["argv"])} for s in steps]}
146
+
147
+
148
+ @router.post("/install")
149
+ async def do_install(body: InstallBody, c: Ctx = Depends(need("admin")), db: Session = Depends(get_db)) -> dict:
150
+ steps, root = _plan(body, c, db)
151
+ job = jobs.create(db, c.ws, "install", {"root": str(root), "version": body.version, "adapters": body.adapters,
152
+ "make_default": body.make_default}, steps=steps,
153
+ title=f"Install dbt-core {body.version} with {', '.join(body.adapters)}")
154
+ await jobs.dispatch(job.id)
155
+ return {"job_id": job.id, "root": str(root)}
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect
4
+ from sqlalchemy.orm import Session
5
+
6
+ from .. import jobs
7
+ from ..config import get_settings
8
+ from ..db import SessionLocal, get_db
9
+ from ..events import hub
10
+ from ..models import Job, Membership
11
+ from ..security import COOKIE, LOCAL_COOKIE, Ctx, ctx, current_user, need
12
+
13
+ router = APIRouter(prefix="/api/jobs", tags=["jobs"])
14
+
15
+
16
+ def job_dict(j: Job, full: bool = False) -> dict:
17
+ d = {"id": j.id, "project_id": j.project_id, "kind": j.kind, "title": j.title, "status": j.status,
18
+ "created_at": j.created_at, "started_at": j.started_at, "finished_at": j.finished_at, "params": j.params,
19
+ "summary": (j.result or {}).get("summary"),
20
+ "command": [s.get("display") for s in j.command]}
21
+ if full:
22
+ d["log"] = [{"level": l.split("\t", 1)[0], "text": l.split("\t", 1)[-1]} for l in (j.log or "").splitlines()]
23
+ d["nodes"] = j.nodes
24
+ d["result"] = {k: v for k, v in (j.result or {}).items()}
25
+ d["steps"] = [{"label": s["label"], "display": s.get("display")} for s in j.command]
26
+ return d
27
+
28
+
29
+ @router.get("")
30
+ def list_jobs(project_id: str | None = None, kinds: str | None = None, limit: int = 50,
31
+ c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> list[dict]:
32
+ q = db.query(Job).filter(Job.workspace_id == c.ws)
33
+ if project_id:
34
+ q = q.filter(Job.project_id == project_id)
35
+ ks = kinds.split(",") if kinds else sorted(jobs.HISTORY_KINDS)
36
+ q = q.filter(Job.kind.in_(ks))
37
+ return [job_dict(j) for j in q.order_by(Job.created_at.desc()).limit(min(limit, 200))]
38
+
39
+
40
+ @router.get("/{job_id}")
41
+ def get_job(job_id: str, c: Ctx = Depends(ctx), db: Session = Depends(get_db)) -> dict:
42
+ j = db.get(Job, job_id)
43
+ if j is None or j.workspace_id != c.ws:
44
+ raise HTTPException(404, "Job not found.")
45
+ return job_dict(j, full=True)
46
+
47
+
48
+ @router.post("/{job_id}/cancel")
49
+ async def cancel(job_id: str, c: Ctx = Depends(need("member")), db: Session = Depends(get_db)) -> dict:
50
+ j = db.get(Job, job_id)
51
+ if j is None or j.workspace_id != c.ws:
52
+ raise HTTPException(404, "Job not found.")
53
+ return {"ok": await jobs.cancel(job_id)}
54
+
55
+
56
+ @router.websocket("/{job_id}/ws")
57
+ async def stream(ws: WebSocket, job_id: str) -> None:
58
+ s = get_settings()
59
+ # authorise like ctx(), using the cookies the browser sends with the upgrade
60
+ with SessionLocal() as db:
61
+ j = db.get(Job, job_id)
62
+ ok = j is not None
63
+ if ok and not s.hosted:
64
+ ok = s.no_token or ws.cookies.get(LOCAL_COOKIE) == s.launch_token
65
+ elif ok:
66
+ from starlette.requests import Request
67
+
68
+ class _R: # minimal shim for current_user
69
+ cookies = ws.cookies
70
+
71
+ user = current_user(_R(), db) # type: ignore[arg-type]
72
+ ok = user is not None and db.query(Membership).filter(Membership.user_id == user.id, Membership.workspace_id == j.workspace_id).first() is not None
73
+ status = j.status if j else None
74
+ if not ok:
75
+ await ws.close(code=4403)
76
+ return
77
+ await ws.accept()
78
+ try:
79
+ if status in ("success", "error", "cancelled") and not getattr(hub(), "has", lambda _: True)(job_id):
80
+ with SessionLocal() as db:
81
+ j = db.get(Job, job_id)
82
+ await ws.send_json({"type": "status", "status": j.status, "nodes": j.nodes, "replay": True})
83
+ await ws.close()
84
+ return
85
+ async for ev in hub().subscribe(job_id):
86
+ await ws.send_json(ev)
87
+ await ws.close()
88
+ except WebSocketDisconnect:
89
+ return