srdp 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.
- srdp/__init__.py +1 -0
- srdp/api/__init__.py +1 -0
- srdp/api/main.py +318 -0
- srdp/assets/__init__.py +1 -0
- srdp/io/__init__.py +1 -0
- srdp/io/ducklake.py +381 -0
- srdp/io/storage.py +35 -0
- srdp/lineage/__init__.py +39 -0
- srdp/lineage/openlineage_bridge.py +183 -0
- srdp/resources/__init__.py +1 -0
- srdp/resources/k8s.py +64 -0
- srdp-0.3.0.dist-info/METADATA +132 -0
- srdp-0.3.0.dist-info/RECORD +14 -0
- srdp-0.3.0.dist-info/WHEEL +4 -0
srdp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""SRDP core platform library."""
|
srdp/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Read-only FastAPI surface over the DuckLake catalog and Dagster."""
|
srdp/api/main.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Read-only FastAPI surface: DuckLake catalog info and basic Dagster status.
|
|
2
|
+
|
|
3
|
+
Demo-scoped implementation of ADR-0002's "Level 1" unified API surface: enough
|
|
4
|
+
to browse what's in the catalog and what Dagster has been doing, without the
|
|
5
|
+
capability-token/JWT validation machinery ADR-0002/0008 describe for a
|
|
6
|
+
production deployment. Sits behind the same Traefik/oauth2-proxy edge gate as
|
|
7
|
+
every other service, same as Marimo/Streamlit (ADR-0007 Tier A read path).
|
|
8
|
+
|
|
9
|
+
Only the platform's own, tenant-agnostic endpoints live here. A project adds
|
|
10
|
+
its own endpoints (e.g. `projects/cbs-example/api/app.py`) by building an
|
|
11
|
+
`APIRouter` and passing it to `create_app`, rather than adding routes to this
|
|
12
|
+
module, so `srdp.api` stays free of any one tenant's specifics.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
from html import escape
|
|
19
|
+
|
|
20
|
+
import duckdb
|
|
21
|
+
import httpx
|
|
22
|
+
from fastapi import APIRouter, FastAPI, HTTPException, Request
|
|
23
|
+
from fastapi.responses import HTMLResponse
|
|
24
|
+
|
|
25
|
+
from srdp.io.ducklake import setup_ducklake
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger("srdp.api")
|
|
28
|
+
|
|
29
|
+
DAGSTER_GRAPHQL_URL = os.environ.get("DAGSTER_GRAPHQL_URL", "http://dagster-webserver:3000/graphql")
|
|
30
|
+
DAGSTER_REPOSITORY_LOCATION = os.environ.get("DAGSTER_REPOSITORY_LOCATION", "grpc:srdp-dagster-code:3030")
|
|
31
|
+
DAGSTER_REPOSITORY_NAME = os.environ.get("DAGSTER_REPOSITORY_NAME", "__repository__")
|
|
32
|
+
|
|
33
|
+
router = APIRouter()
|
|
34
|
+
|
|
35
|
+
_conn: duckdb.DuckDBPyConnection | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_connection() -> duckdb.DuckDBPyConnection:
|
|
39
|
+
"""Return the shared DuckLake connection, creating it on first use.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
A DuckDB connection with the ``ducklake`` catalog attached.
|
|
43
|
+
"""
|
|
44
|
+
global _conn # noqa: PLW0603
|
|
45
|
+
if _conn is None:
|
|
46
|
+
_conn = setup_ducklake()
|
|
47
|
+
return _conn
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _table_exists(conn: duckdb.DuckDBPyConnection, schema: str, table: str) -> bool:
|
|
51
|
+
row = conn.execute(
|
|
52
|
+
"SELECT 1 FROM information_schema.tables "
|
|
53
|
+
"WHERE table_catalog = 'ducklake' AND table_schema = ? AND table_name = ?",
|
|
54
|
+
[schema, table],
|
|
55
|
+
).fetchone()
|
|
56
|
+
return row is not None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _quote_identifier(name: str) -> str:
|
|
60
|
+
return '"' + name.replace('"', '""') + '"'
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def dagster_graphql(query: str, variables: dict | None = None) -> dict:
|
|
64
|
+
"""Run a GraphQL query/mutation against Dagster's webserver.
|
|
65
|
+
|
|
66
|
+
Exposed (not module-private) so a tenant's own `APIRouter` can launch
|
|
67
|
+
runs or read Dagster state without duplicating the HTTP client setup.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
query: The GraphQL document.
|
|
71
|
+
variables: Query variables, if any.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
The response's `data` payload.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
HTTPException: 502 if Dagster returns GraphQL errors.
|
|
78
|
+
"""
|
|
79
|
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
80
|
+
response = await client.post(DAGSTER_GRAPHQL_URL, json={"query": query, "variables": variables or {}})
|
|
81
|
+
response.raise_for_status()
|
|
82
|
+
payload = response.json()
|
|
83
|
+
if "errors" in payload:
|
|
84
|
+
raise HTTPException(status_code=502, detail=payload["errors"])
|
|
85
|
+
return payload["data"]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@router.get("/health")
|
|
89
|
+
def health() -> dict:
|
|
90
|
+
"""Liveness check, does not touch the catalog or Dagster.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
A static status payload.
|
|
94
|
+
"""
|
|
95
|
+
return {"status": "ok"}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@router.get("/token", response_class=HTMLResponse)
|
|
99
|
+
def token_page(request: Request) -> str:
|
|
100
|
+
"""Show the signed-in user their own access token, for calling the API outside a browser.
|
|
101
|
+
|
|
102
|
+
Reads the identity/token headers Traefik's forward-auth already
|
|
103
|
+
established for this request (oauth2-proxy's `--set-xauthrequest`
|
|
104
|
+
output, listed on the `zitadel-auth` middleware's
|
|
105
|
+
`authResponseHeaders`). oauth2-proxy also accepts this same token back
|
|
106
|
+
as a `Bearer` header on future requests (`--skip-jwt-bearer-tokens` +
|
|
107
|
+
`--extra-jwt-issuers`), so no separate API-key system exists, this is
|
|
108
|
+
the user's own Zitadel access token.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
request: The incoming request, read for the forwarded headers.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
An HTML page with the token and example `curl` usage.
|
|
115
|
+
"""
|
|
116
|
+
email = request.headers.get("x-auth-request-email") or request.headers.get("x-auth-request-user") or "unknown"
|
|
117
|
+
token = request.headers.get("x-auth-request-access-token")
|
|
118
|
+
|
|
119
|
+
if not token:
|
|
120
|
+
body = "<p>No access token on this request. Reload after signing in via the hub.</p>"
|
|
121
|
+
else:
|
|
122
|
+
example = f'curl -H "Authorization: Bearer {token}" \\\n https://api.srdp.localhost/catalog/tables'
|
|
123
|
+
body = f"""
|
|
124
|
+
<p>Signed in as <strong>{escape(email)}</strong>.</p>
|
|
125
|
+
<p>This is your own Zitadel access token, short-lived (Zitadel's default token lifetime).
|
|
126
|
+
Reload this page for a fresh one once it expires.</p>
|
|
127
|
+
<pre><code>{escape(token)}</code></pre>
|
|
128
|
+
<p>Use it as a <code>Bearer</code> token to call the API from outside the browser:</p>
|
|
129
|
+
<pre><code>{escape(example)}</code></pre>
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
return f"""<!doctype html>
|
|
133
|
+
<html><head><meta charset="utf-8"><title>SRDP API access</title>
|
|
134
|
+
<style>
|
|
135
|
+
body {{ font-family: system-ui, sans-serif; max-width: 46rem; margin: 3rem auto; padding: 0 1rem; }}
|
|
136
|
+
pre {{ background: #1a1a1a; color: #eee; padding: 1rem; border-radius: 6px; overflow-x: auto; }}
|
|
137
|
+
code {{ font-family: "JetBrains Mono", monospace; }}
|
|
138
|
+
</style></head>
|
|
139
|
+
<body>
|
|
140
|
+
<h1>SRDP API</h1>
|
|
141
|
+
{body}
|
|
142
|
+
<p><a href="/docs">Interactive API docs (Swagger UI)</a></p>
|
|
143
|
+
</body></html>"""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@router.get("/catalog/schemas")
|
|
147
|
+
def list_schemas() -> dict:
|
|
148
|
+
"""List every schema in the DuckLake catalog.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
A dict with the schema name list under ``schemas``.
|
|
152
|
+
"""
|
|
153
|
+
conn = get_connection()
|
|
154
|
+
rows = conn.execute(
|
|
155
|
+
"SELECT schema_name FROM information_schema.schemata WHERE catalog_name = 'ducklake' ORDER BY schema_name",
|
|
156
|
+
).fetchall()
|
|
157
|
+
return {"schemas": [r[0] for r in rows]}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@router.get("/catalog/tables")
|
|
161
|
+
def list_tables(schema: str | None = None) -> dict:
|
|
162
|
+
"""List tables in the DuckLake catalog, optionally filtered to one schema.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
schema: Restrict results to this schema, if given.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
A dict with the table list under ``tables``, each entry a
|
|
169
|
+
``{schema, table}`` pair.
|
|
170
|
+
"""
|
|
171
|
+
conn = get_connection()
|
|
172
|
+
if schema is not None:
|
|
173
|
+
rows = conn.execute(
|
|
174
|
+
"SELECT table_schema, table_name FROM information_schema.tables "
|
|
175
|
+
"WHERE table_catalog = 'ducklake' AND table_schema = ? ORDER BY table_schema, table_name",
|
|
176
|
+
[schema],
|
|
177
|
+
).fetchall()
|
|
178
|
+
else:
|
|
179
|
+
rows = conn.execute(
|
|
180
|
+
"SELECT table_schema, table_name FROM information_schema.tables "
|
|
181
|
+
"WHERE table_catalog = 'ducklake' ORDER BY table_schema, table_name",
|
|
182
|
+
).fetchall()
|
|
183
|
+
return {"tables": [{"schema": r[0], "table": r[1]} for r in rows]}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@router.get("/catalog/tables/{schema}/{table}")
|
|
187
|
+
def table_info(schema: str, table: str) -> dict:
|
|
188
|
+
"""Return column schema and row count for one DuckLake table.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
schema: Schema the table lives in.
|
|
192
|
+
table: Table name.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
A dict with ``schema``, ``table``, ``row_count``, and ``columns``
|
|
196
|
+
(each a ``{name, type}`` pair).
|
|
197
|
+
|
|
198
|
+
Raises:
|
|
199
|
+
HTTPException: 404 if the table does not exist in the catalog.
|
|
200
|
+
"""
|
|
201
|
+
conn = get_connection()
|
|
202
|
+
if not _table_exists(conn, schema, table):
|
|
203
|
+
raise HTTPException(status_code=404, detail=f"Table {schema}.{table} not found")
|
|
204
|
+
|
|
205
|
+
ref = f"ducklake.{_quote_identifier(schema)}.{_quote_identifier(table)}"
|
|
206
|
+
described = conn.sql(f"DESCRIBE {ref}").fetchall()
|
|
207
|
+
row_count = conn.sql(f"SELECT COUNT(*) FROM {ref}").fetchone() # noqa: S608
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
"schema": schema,
|
|
211
|
+
"table": table,
|
|
212
|
+
"row_count": row_count[0] if row_count else 0,
|
|
213
|
+
"columns": [{"name": col_name, "type": col_type} for col_name, col_type, *_ in described],
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@router.get("/catalog/tables/{schema}/{table}/preview")
|
|
218
|
+
def table_preview(schema: str, table: str, limit: int = 10) -> dict:
|
|
219
|
+
"""Return a row preview for one DuckLake table.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
schema: Schema the table lives in.
|
|
223
|
+
table: Table name.
|
|
224
|
+
limit: Maximum rows to return, capped at 100.
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
A dict with ``rows``, each a JSON-friendly dict keyed by column name.
|
|
228
|
+
|
|
229
|
+
Raises:
|
|
230
|
+
HTTPException: 404 if the table does not exist in the catalog.
|
|
231
|
+
"""
|
|
232
|
+
conn = get_connection()
|
|
233
|
+
if not _table_exists(conn, schema, table):
|
|
234
|
+
raise HTTPException(status_code=404, detail=f"Table {schema}.{table} not found")
|
|
235
|
+
|
|
236
|
+
ref = f"ducklake.{_quote_identifier(schema)}.{_quote_identifier(table)}"
|
|
237
|
+
capped_limit = min(limit, 100)
|
|
238
|
+
result = conn.sql(f"SELECT * FROM {ref} LIMIT {capped_limit}") # noqa: S608
|
|
239
|
+
columns = [d[0] for d in result.description]
|
|
240
|
+
rows = [dict(zip(columns, row, strict=True)) for row in result.fetchall()]
|
|
241
|
+
return {"schema": schema, "table": table, "rows": rows}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@router.get("/dagster/runs")
|
|
245
|
+
async def dagster_runs(limit: int = 10) -> dict:
|
|
246
|
+
"""Return the most recent Dagster runs.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
limit: Maximum runs to return, capped at 50.
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
A dict with the run list under ``runs``.
|
|
253
|
+
"""
|
|
254
|
+
query = """
|
|
255
|
+
query RecentRuns($limit: Int!) {
|
|
256
|
+
runsOrError(limit: $limit) {
|
|
257
|
+
... on Runs {
|
|
258
|
+
results {
|
|
259
|
+
runId
|
|
260
|
+
status
|
|
261
|
+
pipelineName
|
|
262
|
+
startTime
|
|
263
|
+
endTime
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
"""
|
|
269
|
+
data = await dagster_graphql(query, {"limit": min(limit, 50)})
|
|
270
|
+
return {"runs": data["runsOrError"].get("results", [])}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
@router.get("/dagster/assets")
|
|
274
|
+
async def dagster_assets() -> dict:
|
|
275
|
+
"""Return the full Dagster asset key list.
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
A dict with the asset key list under ``assets``, each entry a
|
|
279
|
+
list of key path segments.
|
|
280
|
+
"""
|
|
281
|
+
query = """
|
|
282
|
+
query Assets {
|
|
283
|
+
assetsOrError {
|
|
284
|
+
... on AssetConnection {
|
|
285
|
+
nodes {
|
|
286
|
+
key { path }
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
"""
|
|
292
|
+
data = await dagster_graphql(query)
|
|
293
|
+
nodes = data["assetsOrError"].get("nodes", [])
|
|
294
|
+
return {"assets": [n["key"]["path"] for n in nodes]}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def create_app(extra_routers: Iterable[APIRouter] = ()) -> FastAPI:
|
|
298
|
+
"""Build the SRDP API: the platform's own endpoints plus any tenant add-ons.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
extra_routers: Tenant-owned routers to mount alongside the core
|
|
302
|
+
platform endpoints, each behind the same auth edge and appearing
|
|
303
|
+
in the same OpenAPI docs.
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
A configured FastAPI app.
|
|
307
|
+
"""
|
|
308
|
+
app = FastAPI(
|
|
309
|
+
title="SRDP API",
|
|
310
|
+
description="Basic read-only info on the DuckLake catalog and Dagster.",
|
|
311
|
+
)
|
|
312
|
+
app.include_router(router)
|
|
313
|
+
for extra_router in extra_routers:
|
|
314
|
+
app.include_router(extra_router)
|
|
315
|
+
return app
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
app = create_app()
|
srdp/assets/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Base asset patterns and utilities."""
|
srdp/io/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""IO managers for SRDP-supported storage backends."""
|
srdp/io/ducklake.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""DuckLake catalog settings, connection management, and Dagster IO manager."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import time
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import duckdb
|
|
8
|
+
import polars as pl
|
|
9
|
+
import psycopg2
|
|
10
|
+
from dagster import (
|
|
11
|
+
InitResourceContext,
|
|
12
|
+
InputContext,
|
|
13
|
+
IOManager,
|
|
14
|
+
MetadataValue,
|
|
15
|
+
OutputContext,
|
|
16
|
+
TableColumn,
|
|
17
|
+
TableSchema,
|
|
18
|
+
io_manager,
|
|
19
|
+
)
|
|
20
|
+
from psycopg2 import sql
|
|
21
|
+
from pydantic import Field
|
|
22
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
23
|
+
|
|
24
|
+
from srdp.io.storage import StorageBackend
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("srdp.io.ducklake")
|
|
27
|
+
|
|
28
|
+
_CATALOG = "ducklake"
|
|
29
|
+
_DEFAULT_SCHEMA = "main"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
# Settings
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DuckLakeSettings(BaseSettings):
|
|
38
|
+
"""DuckLake catalog settings.
|
|
39
|
+
|
|
40
|
+
All fields can be overridden via environment variables prefixed
|
|
41
|
+
with ``DUCKLAKE_`` (e.g. ``DUCKLAKE_PG_HOST``).
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
model_config = SettingsConfigDict(
|
|
45
|
+
env_prefix="DUCKLAKE_",
|
|
46
|
+
env_file=".env",
|
|
47
|
+
env_file_encoding="utf-8",
|
|
48
|
+
extra="ignore",
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
pg_host: str = Field(default="localhost")
|
|
52
|
+
pg_port: int = Field(default=5432)
|
|
53
|
+
pg_user: str = Field(default="postgres")
|
|
54
|
+
pg_password: str
|
|
55
|
+
pg_db: str = Field(default="ducklake")
|
|
56
|
+
data_path: str = Field(default=".data/ducklake")
|
|
57
|
+
|
|
58
|
+
target_file_size: int | None = None
|
|
59
|
+
parquet_compression: str | None = None
|
|
60
|
+
per_thread_output: bool | None = None
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def pg_connection_string(self) -> str:
|
|
64
|
+
"""Build the libpq connection string for DuckLake metadata.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
A space-separated libpq keyword/value connection string.
|
|
68
|
+
"""
|
|
69
|
+
return (
|
|
70
|
+
f"host={self.pg_host} port={self.pg_port} "
|
|
71
|
+
f"dbname={self.pg_db} user={self.pg_user} password={self.pg_password}"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---------------------------------------------------------------------------
|
|
76
|
+
# Storage backend — local filesystem
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class LocalStorageBackend(StorageBackend):
|
|
81
|
+
"""Store DuckLake data files on the local filesystem.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
base_path: Root directory for file storage. Created automatically
|
|
85
|
+
if it does not exist.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, base_path: str) -> None:
|
|
89
|
+
"""See class docstring for `base_path`."""
|
|
90
|
+
self._base_path = Path(base_path).resolve()
|
|
91
|
+
self._base_path.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
|
|
93
|
+
def get_base_path(self) -> str:
|
|
94
|
+
"""Return the absolute path to the storage root directory.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Absolute filesystem path used as DuckLake's DATA_PATH.
|
|
98
|
+
"""
|
|
99
|
+
return str(self._base_path)
|
|
100
|
+
|
|
101
|
+
def configure_duckdb(self, conn: duckdb.DuckDBPyConnection) -> None:
|
|
102
|
+
"""No-op — local filesystem needs no extra DuckDB configuration.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
conn: An open DuckDB connection (unused for local storage).
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Connection helpers
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def ensure_database(settings: DuckLakeSettings) -> None:
|
|
115
|
+
"""Create the DuckLake PostgreSQL metadata database if it does not exist.
|
|
116
|
+
|
|
117
|
+
Connects to the default ``postgres`` database to check for and optionally
|
|
118
|
+
create the target database. Uses autocommit because ``CREATE DATABASE``
|
|
119
|
+
cannot run inside a transaction.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
settings: DuckLake settings with PostgreSQL connection details.
|
|
123
|
+
"""
|
|
124
|
+
conn = psycopg2.connect(
|
|
125
|
+
host=settings.pg_host,
|
|
126
|
+
port=settings.pg_port,
|
|
127
|
+
user=settings.pg_user,
|
|
128
|
+
password=settings.pg_password,
|
|
129
|
+
dbname="postgres",
|
|
130
|
+
)
|
|
131
|
+
conn.autocommit = True
|
|
132
|
+
try:
|
|
133
|
+
with conn.cursor() as cur:
|
|
134
|
+
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (settings.pg_db,))
|
|
135
|
+
if cur.fetchone():
|
|
136
|
+
logger.info("DuckLake database '%s' already exists.", settings.pg_db)
|
|
137
|
+
return
|
|
138
|
+
cur.execute(
|
|
139
|
+
sql.SQL("CREATE DATABASE {}").format(sql.Identifier(settings.pg_db)),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
logger.info("Created DuckLake database '%s'.", settings.pg_db)
|
|
143
|
+
finally:
|
|
144
|
+
conn.close()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _apply_tuning_options(conn: duckdb.DuckDBPyConnection, settings: DuckLakeSettings) -> None:
|
|
148
|
+
tuning: list[tuple[str, int | str | bool]] = []
|
|
149
|
+
if settings.target_file_size is not None:
|
|
150
|
+
tuning.append(("target_file_size", settings.target_file_size))
|
|
151
|
+
if settings.parquet_compression is not None:
|
|
152
|
+
tuning.append(("parquet_compression", settings.parquet_compression))
|
|
153
|
+
if settings.per_thread_output is not None:
|
|
154
|
+
tuning.append(("per_thread_output", settings.per_thread_output))
|
|
155
|
+
|
|
156
|
+
for option, value in tuning:
|
|
157
|
+
if isinstance(value, str):
|
|
158
|
+
sql_value = f"'{value}'"
|
|
159
|
+
elif isinstance(value, bool):
|
|
160
|
+
sql_value = str(value).lower()
|
|
161
|
+
else:
|
|
162
|
+
sql_value = str(value)
|
|
163
|
+
conn.execute(f"CALL ducklake_set_option('ducklake', '{option}', {sql_value})")
|
|
164
|
+
logger.info("DuckLake option %s = %s", option, value)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def create_connection(
|
|
168
|
+
settings: DuckLakeSettings,
|
|
169
|
+
backend: StorageBackend | None = None,
|
|
170
|
+
) -> duckdb.DuckDBPyConnection:
|
|
171
|
+
"""Create a DuckDB connection with the DuckLake catalog attached.
|
|
172
|
+
|
|
173
|
+
Installs and loads the DuckLake extension, applies storage-specific DuckDB
|
|
174
|
+
configuration, and attaches the catalog with retry logic to handle
|
|
175
|
+
concurrent init races.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
settings: DuckLake settings with PostgreSQL connection details.
|
|
179
|
+
backend: Storage backend to use. Resolved from ``settings`` if not provided.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
A ready-to-use DuckDB connection with the ``ducklake`` catalog attached.
|
|
183
|
+
|
|
184
|
+
Raises:
|
|
185
|
+
duckdb.Error: If the catalog cannot be attached after all retries.
|
|
186
|
+
"""
|
|
187
|
+
if backend is None:
|
|
188
|
+
backend = LocalStorageBackend(settings.data_path)
|
|
189
|
+
|
|
190
|
+
conn = duckdb.connect()
|
|
191
|
+
conn.execute("INSTALL ducklake")
|
|
192
|
+
conn.execute("LOAD ducklake")
|
|
193
|
+
backend.configure_duckdb(conn)
|
|
194
|
+
|
|
195
|
+
attach_query = (
|
|
196
|
+
f"ATTACH 'ducklake:postgres:{settings.pg_connection_string}' "
|
|
197
|
+
f"AS {_CATALOG} (DATA_PATH '{backend.get_base_path()}', OVERRIDE_DATA_PATH TRUE)"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
max_retries = 3
|
|
201
|
+
for attempt in range(max_retries):
|
|
202
|
+
try:
|
|
203
|
+
conn.execute(attach_query)
|
|
204
|
+
break
|
|
205
|
+
except duckdb.Error as exc:
|
|
206
|
+
if "already exists" in str(exc) and attempt < max_retries - 1:
|
|
207
|
+
logger.warning("DuckLake catalog init race (attempt %d), retrying...", attempt + 1)
|
|
208
|
+
time.sleep(1)
|
|
209
|
+
conn.close()
|
|
210
|
+
conn = duckdb.connect()
|
|
211
|
+
conn.execute("INSTALL ducklake")
|
|
212
|
+
conn.execute("LOAD ducklake")
|
|
213
|
+
backend.configure_duckdb(conn)
|
|
214
|
+
else:
|
|
215
|
+
raise
|
|
216
|
+
|
|
217
|
+
_apply_tuning_options(conn, settings)
|
|
218
|
+
logger.info(
|
|
219
|
+
"Attached DuckLake catalog (db=%s, data_path=%s).",
|
|
220
|
+
settings.pg_db,
|
|
221
|
+
backend.get_base_path(),
|
|
222
|
+
)
|
|
223
|
+
return conn
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def setup_ducklake(
|
|
227
|
+
settings: DuckLakeSettings | None = None,
|
|
228
|
+
) -> duckdb.DuckDBPyConnection:
|
|
229
|
+
"""Full DuckLake setup: ensure the metadata database exists, then connect.
|
|
230
|
+
|
|
231
|
+
This is the main entry point — call it from the Dagster IO manager
|
|
232
|
+
factory or from a CLI init command.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
settings: Loaded from environment variables if not provided.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
A ready-to-use DuckDB connection with the ``ducklake`` catalog attached.
|
|
239
|
+
"""
|
|
240
|
+
if settings is None:
|
|
241
|
+
settings = DuckLakeSettings() # ty: ignore[missing-argument]
|
|
242
|
+
ensure_database(settings)
|
|
243
|
+
backend = LocalStorageBackend(settings.data_path)
|
|
244
|
+
return create_connection(settings, backend)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ---------------------------------------------------------------------------
|
|
248
|
+
# Dagster IO manager
|
|
249
|
+
# ---------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def asset_key_path_to_table_ref(asset_key_path: list[str]) -> str:
|
|
253
|
+
"""Derive a fully-qualified DuckLake table reference from an asset key path.
|
|
254
|
+
|
|
255
|
+
The single naming convention every DuckLake consumer (the IO manager, the
|
|
256
|
+
OpenLineage bridge) must share:
|
|
257
|
+
|
|
258
|
+
- ``["orders"]`` → ``ducklake.main.orders``
|
|
259
|
+
- ``["raw", "orders"]`` → ``ducklake.raw.orders``
|
|
260
|
+
- ``["raw", "eu", "orders"]`` → ``ducklake.raw.eu_orders``
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
asset_key_path: Asset key path segments, e.g. ``["raw", "orders"]``.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Fully-qualified reference like ``ducklake.raw.orders``.
|
|
267
|
+
"""
|
|
268
|
+
if len(asset_key_path) == 1:
|
|
269
|
+
schema, table = _DEFAULT_SCHEMA, asset_key_path[0]
|
|
270
|
+
else:
|
|
271
|
+
schema = asset_key_path[0]
|
|
272
|
+
table = "_".join(asset_key_path[1:])
|
|
273
|
+
return f"{_CATALOG}.{schema}.{table}"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class DuckLakeIOManager(IOManager):
|
|
277
|
+
"""Dagster IO manager that persists asset outputs as DuckLake tables.
|
|
278
|
+
|
|
279
|
+
Asset key path segments are resolved to a fully-qualified table reference:
|
|
280
|
+
|
|
281
|
+
- ``["orders"]`` → ``ducklake.main.orders``
|
|
282
|
+
- ``["raw", "orders"]`` → ``ducklake.raw.orders``
|
|
283
|
+
- ``["raw", "eu", "orders"]`` → ``ducklake.raw.eu_orders``
|
|
284
|
+
|
|
285
|
+
Outputs are written as ``CREATE OR REPLACE TABLE``.
|
|
286
|
+
Inputs are returned as ``pl.LazyFrame`` — operations are pushed down
|
|
287
|
+
to DuckDB at ``.collect()`` time, enabling DuckLake file pruning.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
def __init__(self, conn: duckdb.DuckDBPyConnection) -> None:
|
|
291
|
+
"""Wrap an already-connected DuckDB connection with the `ducklake` catalog attached."""
|
|
292
|
+
self._conn = conn
|
|
293
|
+
|
|
294
|
+
def _table_ref(self, asset_key_path: list[str]) -> str:
|
|
295
|
+
return asset_key_path_to_table_ref(asset_key_path)
|
|
296
|
+
|
|
297
|
+
def _ensure_schema(self, schema: str) -> None:
|
|
298
|
+
"""Create the DuckLake schema if it does not already exist.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
schema: Schema name to create inside the ``ducklake`` catalog.
|
|
302
|
+
"""
|
|
303
|
+
self._conn.execute(f"CREATE SCHEMA IF NOT EXISTS {_CATALOG}.{schema}")
|
|
304
|
+
|
|
305
|
+
def handle_output(self, context: OutputContext, obj: pl.DataFrame | pl.LazyFrame) -> None:
|
|
306
|
+
"""Write a Polars DataFrame or LazyFrame to a DuckLake table.
|
|
307
|
+
|
|
308
|
+
Accepts both eager and lazy frames. When a ``pl.LazyFrame`` is provided,
|
|
309
|
+
DuckDB evaluates the query plan internally, so data never fully
|
|
310
|
+
materialises in Python memory.
|
|
311
|
+
|
|
312
|
+
Attaches schema and row-count metadata to the output automatically, for
|
|
313
|
+
every asset that goes through this IO manager, regardless of what the
|
|
314
|
+
asset function itself returns — this is the "automatic" half of the
|
|
315
|
+
platform's lineage/observability story; column lineage is the opt-in half
|
|
316
|
+
(see ``srdp.lineage``), since it needs the producing expressions, which
|
|
317
|
+
this method never sees, only the resulting frame.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
context: Dagster output context containing the asset key.
|
|
321
|
+
obj: The Polars DataFrame or LazyFrame to persist.
|
|
322
|
+
"""
|
|
323
|
+
path = list(context.asset_key.path)
|
|
324
|
+
ref = self._table_ref(path)
|
|
325
|
+
schema = ref.split(".")[1]
|
|
326
|
+
self._ensure_schema(schema)
|
|
327
|
+
self._conn.register("_data", obj)
|
|
328
|
+
self._conn.execute(f"CREATE OR REPLACE TABLE {ref} AS SELECT * FROM _data") # noqa: S608
|
|
329
|
+
self._conn.unregister("_data")
|
|
330
|
+
|
|
331
|
+
described = self._conn.sql(f"DESCRIBE {ref}").fetchall()
|
|
332
|
+
row_count = self._conn.sql(f"SELECT COUNT(*) FROM {ref}").fetchone() # noqa: S608
|
|
333
|
+
row_count = row_count[0] if row_count else 0
|
|
334
|
+
|
|
335
|
+
column_names = [col_name for col_name, *_ in described]
|
|
336
|
+
quoted = [name.replace('"', '""') for name in column_names]
|
|
337
|
+
null_count_exprs = ", ".join(f'COUNT(*) FILTER (WHERE "{q}" IS NULL)' for q in quoted)
|
|
338
|
+
null_counts_row = self._conn.sql(f"SELECT {null_count_exprs} FROM {ref}").fetchone() # noqa: S608
|
|
339
|
+
null_counts = dict(zip(column_names, null_counts_row, strict=True)) if null_counts_row else {}
|
|
340
|
+
|
|
341
|
+
context.add_output_metadata(
|
|
342
|
+
{
|
|
343
|
+
"dagster/row_count": row_count,
|
|
344
|
+
"dagster/column_schema": TableSchema(
|
|
345
|
+
columns=[TableColumn(name=col_name, type=col_type) for col_name, col_type, *_ in described],
|
|
346
|
+
),
|
|
347
|
+
"null_counts": MetadataValue.json(null_counts),
|
|
348
|
+
},
|
|
349
|
+
)
|
|
350
|
+
logger.info("Wrote %d rows to %s.", row_count, ref)
|
|
351
|
+
|
|
352
|
+
def load_input(self, context: InputContext) -> pl.LazyFrame:
|
|
353
|
+
"""Load a DuckLake table as a Polars LazyFrame.
|
|
354
|
+
|
|
355
|
+
Uses DuckDB's ``pl(lazy=True)`` to return a lazy frame with projection
|
|
356
|
+
and filter pushdown support. Operations chained on the result are pushed
|
|
357
|
+
down to DuckDB at ``.collect()`` time, enabling DuckLake file pruning.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
context: Dagster input context containing the upstream asset key.
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
A lazy view of the table. Call ``.collect()`` to materialise.
|
|
364
|
+
"""
|
|
365
|
+
ref = self._table_ref(list(context.asset_key.path))
|
|
366
|
+
result = self._conn.sql(f"SELECT * FROM {ref}").pl(lazy=True) # noqa: S608
|
|
367
|
+
logger.info("Loaded lazy frame from %s.", ref)
|
|
368
|
+
return result
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
@io_manager
|
|
372
|
+
def ducklake_io_manager(_init_context: InitResourceContext) -> DuckLakeIOManager:
|
|
373
|
+
"""Dagster IO manager factory — sets up DuckLake and returns the IO manager.
|
|
374
|
+
|
|
375
|
+
Reads configuration from ``DUCKLAKE_*`` environment variables.
|
|
376
|
+
|
|
377
|
+
Register under the ``"io_manager"`` key, not a custom one, so it's every
|
|
378
|
+
asset's default rather than an opt-in.
|
|
379
|
+
"""
|
|
380
|
+
conn = setup_ducklake()
|
|
381
|
+
return DuckLakeIOManager(conn)
|
srdp/io/storage.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Abstract base class for pluggable storage backends."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
import duckdb
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class StorageBackend(ABC):
|
|
9
|
+
"""Base class for DuckLake storage backends.
|
|
10
|
+
|
|
11
|
+
Each backend defines where DuckLake stores its Parquet data files
|
|
12
|
+
and how DuckDB connects to that storage.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def get_base_path(self) -> str:
|
|
17
|
+
"""Return the root path for DuckLake file storage.
|
|
18
|
+
|
|
19
|
+
For local storage this is a filesystem path.
|
|
20
|
+
For cloud storage this is a URI (e.g. ``s3://bucket/prefix/``).
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
The root path or URI used as DuckLake's DATA_PATH.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def configure_duckdb(self, conn: duckdb.DuckDBPyConnection) -> None:
|
|
28
|
+
"""Configure a DuckDB connection to access this storage.
|
|
29
|
+
|
|
30
|
+
Install and load any required extensions and set any credentials
|
|
31
|
+
needed to reach the storage location.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
conn: An open DuckDB connection to configure.
|
|
35
|
+
"""
|
srdp/lineage/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Column-level lineage for Polars assets, built on `Expr.meta`.
|
|
2
|
+
|
|
3
|
+
Single-hop only: each output column is traced back to the input columns the given
|
|
4
|
+
expression directly references (`Expr.meta.root_names()`). This does not resolve
|
|
5
|
+
transitive multi-step chains (an expression built from an already-derived column
|
|
6
|
+
only reports that intermediate column, not its own origin) or full pipeline-plan
|
|
7
|
+
lineage across joins. It is opt-in by necessity: a materialized `pl.DataFrame`
|
|
8
|
+
carries no record of the expressions that produced it, so only the asset author,
|
|
9
|
+
who still has those expressions in scope, can supply the mapping.
|
|
10
|
+
|
|
11
|
+
See docs/reviews/poc-build-plan.md ("srdp.lineage: what Polars provides,
|
|
12
|
+
precisely") for the full scoping rationale.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import polars as pl
|
|
16
|
+
from dagster import AssetKey, MetadataValue, TableColumnDep, TableColumnLineage
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def column_lineage_metadata(
|
|
20
|
+
exprs: dict[str, pl.Expr],
|
|
21
|
+
upstream_asset_key: AssetKey | str | list[str],
|
|
22
|
+
) -> dict[str, MetadataValue]:
|
|
23
|
+
"""Build Dagster column-lineage metadata from the expressions that produced an asset's output.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
exprs: Mapping of output column name to the Polars expression that produced it.
|
|
27
|
+
upstream_asset_key: The single upstream asset every output column was derived from.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
A one-entry metadata dict (key ``"dagster/column_lineage"``) to merge into an
|
|
31
|
+
`Output`'s metadata — renders as the column lineage graph in the Dagster UI.
|
|
32
|
+
"""
|
|
33
|
+
deps_by_column = {
|
|
34
|
+
output_col: [
|
|
35
|
+
TableColumnDep(asset_key=upstream_asset_key, column_name=root_name) for root_name in expr.meta.root_names()
|
|
36
|
+
]
|
|
37
|
+
for output_col, expr in exprs.items()
|
|
38
|
+
}
|
|
39
|
+
return {"dagster/column_lineage": MetadataValue.column_lineage(TableColumnLineage(deps_by_column=deps_by_column))}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Dagster → OpenLineage bridge.
|
|
2
|
+
|
|
3
|
+
Per ADR-0003, lineage is captured at the Dagster asset boundary, not inside each
|
|
4
|
+
library: this module never talks to DuckLake or Polars directly. It reads whatever
|
|
5
|
+
a materialization event already carries — dataset-level dependencies from the asset
|
|
6
|
+
graph, plus whatever metadata `DuckLakeIOManager` (schema, row count, null counts)
|
|
7
|
+
and `srdp.lineage.column_lineage_metadata` (opt-in column lineage) already attached
|
|
8
|
+
to it — and translates that into OpenLineage `RunEvent`s for a backend like Marquez.
|
|
9
|
+
|
|
10
|
+
Register `emit_openlineage_events` as a `@run_status_sensor(run_status=DagsterRunStatus.SUCCESS)`
|
|
11
|
+
in a project's `definitions.py`; this module does not register sensors itself, since
|
|
12
|
+
that has to happen per code location.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import uuid
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from collections.abc import Set as AbstractSet
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
|
|
21
|
+
from dagster import (
|
|
22
|
+
DagsterInstance,
|
|
23
|
+
DagsterRun,
|
|
24
|
+
IntMetadataValue,
|
|
25
|
+
MetadataValue,
|
|
26
|
+
RepositoryDefinition,
|
|
27
|
+
TableColumnLineageMetadataValue,
|
|
28
|
+
TableSchemaMetadataValue,
|
|
29
|
+
)
|
|
30
|
+
from dagster._core.events import DagsterEventType
|
|
31
|
+
from openlineage.client import OpenLineageClient
|
|
32
|
+
from openlineage.client.event_v2 import (
|
|
33
|
+
InputDataset,
|
|
34
|
+
Job,
|
|
35
|
+
OutputDataset,
|
|
36
|
+
Run,
|
|
37
|
+
RunEvent,
|
|
38
|
+
RunState,
|
|
39
|
+
)
|
|
40
|
+
from openlineage.client.facet_v2 import (
|
|
41
|
+
column_lineage_dataset,
|
|
42
|
+
job_type_job,
|
|
43
|
+
output_statistics_output_dataset,
|
|
44
|
+
schema_dataset,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
from srdp.io.ducklake import asset_key_path_to_table_ref
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger("srdp.lineage.openlineage_bridge")
|
|
50
|
+
|
|
51
|
+
_NAMESPACE = "ducklake"
|
|
52
|
+
_JOB_NAMESPACE = "srdp"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _job_facets(kinds: AbstractSet[str]) -> dict:
|
|
56
|
+
"""Build the JobType facet from an asset's Dagster kind tags.
|
|
57
|
+
|
|
58
|
+
This is the "filter by Polars vs. dbt" mechanism: `kinds` comes straight off
|
|
59
|
+
the asset graph (`kinds={"polars"}` set explicitly on our assets;
|
|
60
|
+
`kinds={"dbt", "duckdb"}` set automatically by dagster-dbt), so Marquez ends up
|
|
61
|
+
with the same categorization Dagster's own UI already shows.
|
|
62
|
+
"""
|
|
63
|
+
if "dbt" in kinds:
|
|
64
|
+
integration = "dbt"
|
|
65
|
+
job_type = "MODEL"
|
|
66
|
+
elif "polars" in kinds:
|
|
67
|
+
integration = "dagster"
|
|
68
|
+
job_type = "polars"
|
|
69
|
+
else:
|
|
70
|
+
integration = "dagster"
|
|
71
|
+
job_type = "ASSET"
|
|
72
|
+
return {
|
|
73
|
+
"jobType": job_type_job.JobTypeJobFacet(
|
|
74
|
+
processingType="BATCH",
|
|
75
|
+
integration=integration,
|
|
76
|
+
jobType=job_type,
|
|
77
|
+
),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _dataset_facets(metadata: Mapping[str, MetadataValue]) -> dict:
|
|
82
|
+
"""Translate `DuckLakeIOManager`'s automatic metadata into OpenLineage dataset facets."""
|
|
83
|
+
facets = {}
|
|
84
|
+
schema = metadata.get("dagster/column_schema")
|
|
85
|
+
if isinstance(schema, TableSchemaMetadataValue):
|
|
86
|
+
facets["schema"] = schema_dataset.SchemaDatasetFacet(
|
|
87
|
+
fields=[
|
|
88
|
+
schema_dataset.SchemaDatasetFacetFields(name=col.name, type=col.type) for col in schema.value.columns
|
|
89
|
+
],
|
|
90
|
+
)
|
|
91
|
+
lineage = metadata.get("dagster/column_lineage")
|
|
92
|
+
if isinstance(lineage, TableColumnLineageMetadataValue):
|
|
93
|
+
fields = {
|
|
94
|
+
output_col: column_lineage_dataset.Fields(
|
|
95
|
+
inputFields=[
|
|
96
|
+
column_lineage_dataset.InputField(
|
|
97
|
+
namespace=_NAMESPACE,
|
|
98
|
+
name=dep.asset_key.to_user_string(),
|
|
99
|
+
field=dep.column_name,
|
|
100
|
+
)
|
|
101
|
+
for dep in deps
|
|
102
|
+
],
|
|
103
|
+
)
|
|
104
|
+
for output_col, deps in lineage.value.deps_by_column.items()
|
|
105
|
+
}
|
|
106
|
+
if fields:
|
|
107
|
+
facets["columnLineage"] = column_lineage_dataset.ColumnLineageDatasetFacet(fields=fields)
|
|
108
|
+
return facets
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _output_facets(metadata: Mapping[str, MetadataValue]) -> dict:
|
|
112
|
+
row_count = metadata.get("dagster/row_count")
|
|
113
|
+
if not isinstance(row_count, IntMetadataValue):
|
|
114
|
+
return {}
|
|
115
|
+
return {
|
|
116
|
+
"outputStatistics": output_statistics_output_dataset.OutputStatisticsOutputDatasetFacet(
|
|
117
|
+
rowCount=row_count.value,
|
|
118
|
+
),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def emit_openlineage_events(
|
|
123
|
+
dagster_run: DagsterRun,
|
|
124
|
+
instance: DagsterInstance,
|
|
125
|
+
repository_def: RepositoryDefinition,
|
|
126
|
+
marquez_url: str,
|
|
127
|
+
) -> None:
|
|
128
|
+
"""Translate every asset materialized in a successful run into an OpenLineage RunEvent.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
dagster_run: The completed run.
|
|
132
|
+
instance: The Dagster instance to read materialization events from.
|
|
133
|
+
repository_def: Used to read each asset's upstream dependencies and kind tags.
|
|
134
|
+
marquez_url: Base URL of the Marquez (or any OpenLineage-compatible) backend.
|
|
135
|
+
"""
|
|
136
|
+
client = OpenLineageClient(url=marquez_url)
|
|
137
|
+
asset_graph = repository_def.asset_graph
|
|
138
|
+
event_records = instance.get_records_for_run(
|
|
139
|
+
run_id=dagster_run.run_id,
|
|
140
|
+
of_type=DagsterEventType.ASSET_MATERIALIZATION,
|
|
141
|
+
).records
|
|
142
|
+
|
|
143
|
+
for record in event_records:
|
|
144
|
+
asset_key = record.asset_key
|
|
145
|
+
asset_materialization = record.asset_materialization
|
|
146
|
+
if asset_key is None or asset_materialization is None:
|
|
147
|
+
logger.warning("Skipping materialization record with no asset key or materialization event.")
|
|
148
|
+
continue
|
|
149
|
+
metadata = asset_materialization.metadata
|
|
150
|
+
node = asset_graph.get(asset_key)
|
|
151
|
+
|
|
152
|
+
job = Job(namespace=_JOB_NAMESPACE, name=asset_key.to_user_string(), facets=_job_facets(node.kinds))
|
|
153
|
+
run = Run(runId=str(uuid.uuid5(uuid.NAMESPACE_URL, f"{dagster_run.run_id}:{asset_key.to_user_string()}")))
|
|
154
|
+
|
|
155
|
+
has_dataset = "dagster/row_count" in metadata or "dagster/column_schema" in metadata
|
|
156
|
+
outputs = None
|
|
157
|
+
if has_dataset:
|
|
158
|
+
table_ref = asset_key_path_to_table_ref(list(asset_key.path))
|
|
159
|
+
outputs = [
|
|
160
|
+
OutputDataset(
|
|
161
|
+
namespace=_NAMESPACE,
|
|
162
|
+
name=table_ref,
|
|
163
|
+
facets=_dataset_facets(metadata),
|
|
164
|
+
outputFacets=_output_facets(metadata),
|
|
165
|
+
),
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
inputs = [
|
|
169
|
+
InputDataset(namespace=_NAMESPACE, name=asset_key_path_to_table_ref(list(parent.key.path)))
|
|
170
|
+
for parent in asset_graph.get_parents(node)
|
|
171
|
+
] or None
|
|
172
|
+
|
|
173
|
+
event = RunEvent(
|
|
174
|
+
eventTime=datetime.fromtimestamp(record.timestamp, tz=UTC).isoformat(),
|
|
175
|
+
producer="https://github.com/srdp-hub/srdp",
|
|
176
|
+
run=run,
|
|
177
|
+
job=job,
|
|
178
|
+
eventType=RunState.COMPLETE,
|
|
179
|
+
inputs=inputs,
|
|
180
|
+
outputs=outputs,
|
|
181
|
+
)
|
|
182
|
+
client.emit(event)
|
|
183
|
+
logger.info("Emitted OpenLineage event for %s (run %s).", asset_key.to_user_string(), dagster_run.run_id)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared Dagster resources."""
|
srdp/resources/k8s.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Kubernetes run config profiles for Dagster job tags.
|
|
2
|
+
|
|
3
|
+
Import these in any project's definitions.py and apply them as job tags:
|
|
4
|
+
|
|
5
|
+
srdp_job = define_asset_job(
|
|
6
|
+
"srdp_job",
|
|
7
|
+
tags={"dagster-k8s/config": BASE_RUN_K8S_CONFIG, "dagster/priority": "0"},
|
|
8
|
+
)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
BASE_RUN_K8S_CONFIG = {
|
|
12
|
+
"container_config": {
|
|
13
|
+
"resources": {
|
|
14
|
+
"requests": {"cpu": "250m", "memory": "256Mi"},
|
|
15
|
+
"limits": {"cpu": "500m", "memory": "512Mi"},
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"job_metadata": {
|
|
19
|
+
"labels": {
|
|
20
|
+
"workload": "etl",
|
|
21
|
+
"team": "data-platform",
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
FAST_LANE_K8S_CONFIG = {
|
|
27
|
+
**BASE_RUN_K8S_CONFIG,
|
|
28
|
+
"container_config": {
|
|
29
|
+
"resources": {
|
|
30
|
+
"requests": {"cpu": "500m", "memory": "512Mi"},
|
|
31
|
+
"limits": {"cpu": "1", "memory": "1Gi"},
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"job_spec_config": {
|
|
35
|
+
"ttl_seconds_after_finished": 600,
|
|
36
|
+
"active_deadline_seconds": 900,
|
|
37
|
+
},
|
|
38
|
+
"job_metadata": {
|
|
39
|
+
"labels": {
|
|
40
|
+
"workload": "etl-fast-lane",
|
|
41
|
+
"team": "data-platform",
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
BACKFILL_K8S_CONFIG = {
|
|
47
|
+
**BASE_RUN_K8S_CONFIG,
|
|
48
|
+
"container_config": {
|
|
49
|
+
"resources": {
|
|
50
|
+
"requests": {"cpu": "750m", "memory": "1Gi"},
|
|
51
|
+
"limits": {"cpu": "2", "memory": "2Gi"},
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"job_spec_config": {
|
|
55
|
+
"ttl_seconds_after_finished": 3600,
|
|
56
|
+
"active_deadline_seconds": 7200,
|
|
57
|
+
},
|
|
58
|
+
"job_metadata": {
|
|
59
|
+
"labels": {
|
|
60
|
+
"workload": "etl-backfill",
|
|
61
|
+
"team": "data-platform",
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: srdp
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Single Repo Data Platform: a composable, self-hostable data stack
|
|
5
|
+
Author: Yannick Vinkesteijn
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Requires-Dist: dagster>=1.12.17
|
|
8
|
+
Requires-Dist: polars>=1.32.3
|
|
9
|
+
Requires-Dist: fastapi>=0.115.0 ; extra == 'api'
|
|
10
|
+
Requires-Dist: uvicorn[standard]>=0.32.0 ; extra == 'api'
|
|
11
|
+
Requires-Dist: httpx>=0.27.0 ; extra == 'api'
|
|
12
|
+
Requires-Dist: azure-identity>=1.25.0 ; extra == 'azure'
|
|
13
|
+
Requires-Dist: azure-storage-blob>=12.28.0 ; extra == 'azure'
|
|
14
|
+
Requires-Dist: dagster-postgres>=0.28.17 ; extra == 'dagster-postgres'
|
|
15
|
+
Requires-Dist: dagster-dbt>=0.29.20 ; extra == 'dbt'
|
|
16
|
+
Requires-Dist: dbt-duckdb>=1.11.0 ; extra == 'dbt'
|
|
17
|
+
Requires-Dist: duckdb>=1.4.0 ; extra == 'ducklake'
|
|
18
|
+
Requires-Dist: psycopg2-binary>=2.9.0 ; extra == 'ducklake'
|
|
19
|
+
Requires-Dist: pydantic-settings>=2.9.0 ; extra == 'ducklake'
|
|
20
|
+
Requires-Dist: pyarrow>=23.0.0 ; extra == 'ducklake'
|
|
21
|
+
Requires-Dist: dagster-k8s>=0.28.17 ; extra == 'infra'
|
|
22
|
+
Requires-Dist: dagster-postgres>=0.28.17 ; extra == 'infra'
|
|
23
|
+
Requires-Dist: dagster-webserver>=1.12.17 ; extra == 'infra'
|
|
24
|
+
Requires-Dist: dagster-graphql>=1.12.17 ; extra == 'infra'
|
|
25
|
+
Requires-Dist: openlineage-python>=1.53.0 ; extra == 'openlineage'
|
|
26
|
+
Requires-Python: >=3.12, <3.13
|
|
27
|
+
Project-URL: Homepage, https://srdphub.com
|
|
28
|
+
Project-URL: Repository, https://github.com/srdp-hub/srdp
|
|
29
|
+
Project-URL: Issues, https://github.com/srdp-hub/srdp/issues
|
|
30
|
+
Project-URL: Documentation, https://docs.srdphub.com
|
|
31
|
+
Provides-Extra: api
|
|
32
|
+
Provides-Extra: azure
|
|
33
|
+
Provides-Extra: dagster-postgres
|
|
34
|
+
Provides-Extra: dbt
|
|
35
|
+
Provides-Extra: ducklake
|
|
36
|
+
Provides-Extra: infra
|
|
37
|
+
Provides-Extra: openlineage
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# The Single Repo Data Platform (SRDP)
|
|
41
|
+
|
|
42
|
+
> _aka the serendipitous data platform_
|
|
43
|
+
|
|
44
|
+
Because your data stack shouldn't require a PhD in Kubernetes and a second mortgage.
|
|
45
|
+
|
|
46
|
+
Welcome, weary data traveler. You've stumbled upon something serendipitous, a quixotic quest to build a sane, powerful, and actually usable data platform from the best open-source components we can find. All from the comfort of a single Git repository.[^1]
|
|
47
|
+
|
|
48
|
+
What's the big idea? To stop gluing together 87 different services with YAML, duct tape, and desperate Stack Overflow searches at 3 AM. We're assembling a dream team of data tools that play nicely together, so you can spend less time wrangling infrastructure and more time doing... well, whatever it is you data people do. Probably making fancy charts.
|
|
49
|
+
|
|
50
|
+
[^1]: We take inspiration from [Instant OpenHIE](https://openhie.github.io/instant/) project who have done the same for open source health information exchange platforms.
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## The Dream Team: Our All-Star Roster
|
|
54
|
+
We didn't just pick these tools out of a hat. Okay, maybe a little. But mostly, we chose them because they're fast, modern, and don't make us want to throw our laptops out the window. Think of them as the Avengers of the data world, if the Avengers were less about smashing aliens and more about smashing GROUP BY queries.
|
|
55
|
+
|
|
56
|
+
Here's the lineup of our chosen champions:
|
|
57
|
+
|
|
58
|
+
| Component | Role in the SRDP | Our Unsolicited Opinion |
|
|
59
|
+
|:---|:---|:---|
|
|
60
|
+
| Zitadel |The Bouncer / Identity & Access Management | Manages who gets to touch the precious data. Because "SELECT * FROM users;" should require more than just a password of password123. |
|
|
61
|
+
| Traefik |The Traffic Cop / Cloud Native Proxy | Directs all the incoming requests so services don't crash into each other. It's the only traffic jam you'll actually enjoy.|
|
|
62
|
+
| Polars |The Speed Demon / Dataframe Library | It's like pandas, but it actually uses all your CPU cores and doesn't take a coffee break on df.groupby(). Written in Rust, because of course it is.|
|
|
63
|
+
| DuckDB |The Pocket Rocket / In-Process OLAP DB | An incredibly fast analytical database that runs inside your application. It's the power of a warehouse in the body of a library. Quack-tastic!|
|
|
64
|
+
| Dagster |The Conductor / Data Orchestrator | The sensible, type-aware adult in the room of chaotic data pipelines. It knows what your data assets are and helps you not set the whole factory on fire.|
|
|
65
|
+
| dlt-hub |The Plumber / Data Loading Library | Gets your data from "over there" to "right here" with surprisingly little fuss. Turns messy APIs into clean tables faster than you can say "ETL is dead".|
|
|
66
|
+
| dbt | The Transformer / Data Transformation Tool | The "T" in ELT that everyone's talking about. It turns your analysts into data engineering heroes with the power of SELECT statements and Jinja.|
|
|
67
|
+
| marimo |The Mad Scientist's Notebook | A next-gen reactive Python notebook. Change one cell, and the whole notebook updates. It's like magic, but with fewer rabbits and more legible code.|
|
|
68
|
+
| Quarto |The Storyteller / Scientific Publishing | Turns your brilliant analysis into beautiful reports, presentations, and websites. Because data that isn't shared is just sad, lonely numbers.|
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Deployment Targets
|
|
73
|
+
|
|
74
|
+
SRDP ships deployment scripts for two targets.
|
|
75
|
+
|
|
76
|
+
### Docker Compose
|
|
77
|
+
|
|
78
|
+
Located in `deploy/docker/`, this stack runs SRDP via Docker compose, but without Dagster. This was the first iteration of SRDP, focusing on the integration of Traefik and Zitadel.
|
|
79
|
+
|
|
80
|
+
| File | Purpose |
|
|
81
|
+
|:---|:---|
|
|
82
|
+
| `deploy/docker/docker-compose.yml` | Main Compose definition for all services |
|
|
83
|
+
| `deploy/docker/docker-compose.override.yml` | Local TLS: mounts self-signed mkcert certificates into Traefik |
|
|
84
|
+
| `deploy/docker/docker-compose.prod.yml` | Production override: switches Traefik to Let's Encrypt ACME for TLS |
|
|
85
|
+
| `deploy/docker/.env.example` | Template for required environment variables (secrets, OIDC client config) |
|
|
86
|
+
| `config/traefik/traefik.yml` | Traefik static configuration (entrypoints, TLS, ACME, dashboard) |
|
|
87
|
+
|
|
88
|
+
An OpenTofu script is provided in `deploy/opentofu/gcp/` to deploy this Docker
|
|
89
|
+
Compose stack to a **Google Cloud Compute Engine** VM. It provisions a Debian
|
|
90
|
+
`e2-medium` instance with a static IP and firewall rules for ports 80 and 443,
|
|
91
|
+
then bootstraps Docker and Docker Compose via a startup script that clones the
|
|
92
|
+
repository, injects secrets, and starts the production Compose stack with
|
|
93
|
+
Let's Encrypt TLS.
|
|
94
|
+
|
|
95
|
+
### Kubernetes + OpenTofu
|
|
96
|
+
|
|
97
|
+
Located in `deploy/kubernetes/`, this target deploys the full platform on a managed
|
|
98
|
+
Kubernetes cluster. Infrastructure is provisioned with [OpenTofu](https://opentofu.org/);
|
|
99
|
+
applications are deployed via a Helm umbrella chart.
|
|
100
|
+
|
|
101
|
+
| Directory / File | Purpose |
|
|
102
|
+
|:---|:---|
|
|
103
|
+
| `deploy/opentofu/scaleway/` | OpenTofu configuration to provision a **Scaleway Kapsule** managed Kubernetes cluster, VPC, autoscaling node pool, and container registry |
|
|
104
|
+
| `deploy/kubernetes/srdp-chart/` | Helm umbrella chart bundling Traefik, Zitadel, PostgreSQL, OAuth2-Proxy, and Dagster as upstream dependencies, plus custom templates for Marimo, Quarto, and TLS certificate bootstrapping |
|
|
105
|
+
| `projects/cbs-example/` | Dagster user code deployment (assets, jobs, schedules) built as a separate container image |
|
|
106
|
+
|
|
107
|
+
A `Justfile` at the repository root provides convenience commands for both targets:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
just local-deploy # Deploy to a local Kubernetes cluster (e.g. kind/k3s)
|
|
111
|
+
just prod-full # Full production deploy on Scaleway
|
|
112
|
+
just prod-apply # Provision Scaleway infrastructure with OpenTofu
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Documentation
|
|
118
|
+
|
|
119
|
+
Full documentation is available at **[srdp-hub.github.io/srdp](https://srdp-hub.github.io/srdp/)**.
|
|
120
|
+
|
|
121
|
+
**Preview locally:**
|
|
122
|
+
```bash
|
|
123
|
+
uvx zensical serve
|
|
124
|
+
```
|
|
125
|
+
Opens the site at `localhost:8000` with live reload.
|
|
126
|
+
|
|
127
|
+
**Deployment:**
|
|
128
|
+
Documentation is built with [Zensical](https://zensical.org/) and deployed automatically to GitHub Pages on every push to `main` via the [Build and deploy Documentation](.github/workflows/docs.yml) GitHub Actions workflow.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+

|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
srdp/__init__.py,sha256=9ezkuPh9VbYgrq91bAt-XqmzPowFPxp7MY3Gi4bmjf8,34
|
|
2
|
+
srdp/api/__init__.py,sha256=ORaCLEb_YxzpxnposMqyQewnV03T_IzONOvOIDQZcu0,71
|
|
3
|
+
srdp/api/main.py,sha256=ZbN6zJ6veEBReA6DKV5_cRVohdMYBCbTOsWFA0D6XmM,10792
|
|
4
|
+
srdp/assets/__init__.py,sha256=zzeE-d_8GAP4DI_NXED2tDrLGCBxFH1LCuP4xaQt_LM,41
|
|
5
|
+
srdp/io/__init__.py,sha256=xEE3U6MMvN1-ZjwX3KjDk8j8xGH4WkOaILjSD8CbPYs,55
|
|
6
|
+
srdp/io/ducklake.py,sha256=YLMBTxhhiXzcIRF0pQRRPshoKm1C4QjNnksxHp9dKP4,13771
|
|
7
|
+
srdp/io/storage.py,sha256=bvg5mX4Q5N7g4ohoo2rHNAF0A2A3AwdbequRrXUkI64,1011
|
|
8
|
+
srdp/lineage/__init__.py,sha256=BGHoXMa-C7TOXeebZRmDIlcqIBdUNXA-8cQNE2tRcAw,1816
|
|
9
|
+
srdp/lineage/openlineage_bridge.py,sha256=-rOw6qltceb7LYFj22utT_k5mBMXVZOpWki8ljAGKL0,6703
|
|
10
|
+
srdp/resources/__init__.py,sha256=9zU_Z8ARCXEOjE1EccUZuAtXmD-srP8UxYI01vOVdZE,32
|
|
11
|
+
srdp/resources/k8s.py,sha256=k7jpa_wTdSdb_g1kLzdr_Y0ydoorlrotgI10xuPDXXk,1585
|
|
12
|
+
srdp-0.3.0.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
|
|
13
|
+
srdp-0.3.0.dist-info/METADATA,sha256=NLsVxz4ud761dg5KBmOn6nFCp3lu1qx6A1UOTiBIqk8,7727
|
|
14
|
+
srdp-0.3.0.dist-info/RECORD,,
|