ciaren 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 (285) hide show
  1. app/README.md +104 -0
  2. app/__init__.py +1 -0
  3. app/api/__init__.py +1 -0
  4. app/api/deps.py +72 -0
  5. app/api/errors.py +63 -0
  6. app/api/middleware.py +30 -0
  7. app/api/routers.py +52 -0
  8. app/api/routes/__init__.py +1 -0
  9. app/api/routes/catalog.py +55 -0
  10. app/api/routes/connections.py +105 -0
  11. app/api/routes/datasets.py +142 -0
  12. app/api/routes/flows.py +83 -0
  13. app/api/routes/health.py +37 -0
  14. app/api/routes/marketplace.py +213 -0
  15. app/api/routes/ml.py +67 -0
  16. app/api/routes/plugins.py +491 -0
  17. app/api/routes/projects.py +32 -0
  18. app/api/routes/runs.py +180 -0
  19. app/api/routes/schedules.py +63 -0
  20. app/api/routes/settings.py +39 -0
  21. app/api/routes/transformations.py +48 -0
  22. app/api/routes/webhooks.py +97 -0
  23. app/bootstrap/__init__.py +4 -0
  24. app/bootstrap/frontend.py +114 -0
  25. app/bootstrap/lifespan.py +100 -0
  26. app/bootstrap/seeding.py +99 -0
  27. app/bundled_plugins/__init__.py +2 -0
  28. app/bundled_plugins/community.hello-0.1.0-alpha.1.ciarenplugin +0 -0
  29. app/bundled_plugins/community.mlp-classifier-0.2.0.ciarenplugin +0 -0
  30. app/bundled_plugins/marketplace.json +57 -0
  31. app/cli.py +828 -0
  32. app/cli_plugin.py +495 -0
  33. app/connectors/__init__.py +48 -0
  34. app/connectors/azure_blob.py +120 -0
  35. app/connectors/base.py +70 -0
  36. app/connectors/confinement.py +55 -0
  37. app/connectors/gcs.py +120 -0
  38. app/connectors/local_storage.py +135 -0
  39. app/connectors/mongo.py +112 -0
  40. app/connectors/providers.py +239 -0
  41. app/connectors/rest_api.py +351 -0
  42. app/connectors/s3.py +114 -0
  43. app/connectors/sql.py +212 -0
  44. app/connectors/ssrf.py +96 -0
  45. app/connectors/storage_base.py +115 -0
  46. app/core/__init__.py +1 -0
  47. app/core/auth.py +94 -0
  48. app/core/config.py +234 -0
  49. app/core/csrf.py +88 -0
  50. app/core/database.py +135 -0
  51. app/core/enums.py +102 -0
  52. app/core/exceptions.py +56 -0
  53. app/core/logging.py +95 -0
  54. app/core/notifications.py +113 -0
  55. app/core/runtime_settings.py +384 -0
  56. app/core/secrets.py +419 -0
  57. app/db/__init__.py +1 -0
  58. app/db/migrations.py +135 -0
  59. app/db/models/__init__.py +1 -0
  60. app/db/models/app_setting.py +27 -0
  61. app/db/models/connection.py +41 -0
  62. app/db/models/dataset.py +59 -0
  63. app/db/models/dataset_version.py +51 -0
  64. app/db/models/flow.py +56 -0
  65. app/db/models/project.py +31 -0
  66. app/db/models/run.py +61 -0
  67. app/db/models/schedule.py +66 -0
  68. app/demo/__init__.py +13 -0
  69. app/demo/datasets.py +360 -0
  70. app/demo/loader.py +220 -0
  71. app/demo/resources/etl/01_clean_customers.flow.json +85 -0
  72. app/demo/resources/etl/02_order_revenue_by_month.flow.json +127 -0
  73. app/demo/resources/etl/03_customer_orders_join.flow.json +153 -0
  74. app/demo/resources/etl/04_full_sales_mart.flow.json +195 -0
  75. app/demo/resources/etl/05_lead_intake_cleanup.flow.json +231 -0
  76. app/demo/resources/etl/06_web_event_engagement.flow.json +223 -0
  77. app/demo/resources/etl/07_survey_quality_contracts.flow.json +209 -0
  78. app/demo/resources/etl/08_regional_target_variance.flow.json +182 -0
  79. app/demo/resources/etl/09_product_catalog_scoring.flow.json +118 -0
  80. app/demo/resources/ml/01_iris_quick_classifier.flow.json +61 -0
  81. app/demo/resources/ml/02_iris_train_validate_evaluate.flow.json +169 -0
  82. app/demo/resources/ml/03_house_prices_regression.flow.json +115 -0
  83. app/demo/resources/ml/04_iris_pca_explore.flow.json +77 -0
  84. app/demo/resources/ml/05_iris_cross_validation_report.flow.json +119 -0
  85. app/demo/resources/ml/06_iris_knn_encoded_species.flow.json +136 -0
  86. app/demo/resources/ml/07_house_price_feature_selection.flow.json +128 -0
  87. app/demo/resources/ml/08_house_price_customer_segments.flow.json +66 -0
  88. app/demo/resources/ml/09_house_price_pca_model.flow.json +66 -0
  89. app/demo/seed.py +167 -0
  90. app/engine/__init__.py +1 -0
  91. app/engine/backends/__init__.py +30 -0
  92. app/engine/backends/base.py +263 -0
  93. app/engine/backends/pandas_engine.py +655 -0
  94. app/engine/backends/polars_engine.py +742 -0
  95. app/engine/cancellation.py +104 -0
  96. app/engine/codegen.py +292 -0
  97. app/engine/codegen_common.py +535 -0
  98. app/engine/codegen_params.py +123 -0
  99. app/engine/executor.py +462 -0
  100. app/engine/graph.py +355 -0
  101. app/engine/ingest.py +213 -0
  102. app/engine/node_kinds.py +311 -0
  103. app/engine/node_metadata.py +658 -0
  104. app/engine/parameters.py +219 -0
  105. app/engine/polars_codegen.py +466 -0
  106. app/engine/preview_context.py +30 -0
  107. app/engine/process_pool.py +223 -0
  108. app/engine/profile.py +87 -0
  109. app/engine/registry.py +233 -0
  110. app/engine/run_context.py +44 -0
  111. app/engine/script_guard.py +238 -0
  112. app/engine/sql_codegen.py +142 -0
  113. app/engine/transformations/__init__.py +1 -0
  114. app/engine/transformations/base.py +210 -0
  115. app/engine/transformations/charts.py +696 -0
  116. app/engine/transformations/columns.py +255 -0
  117. app/engine/transformations/conditional.py +145 -0
  118. app/engine/transformations/join.py +92 -0
  119. app/engine/transformations/ml/__init__.py +9 -0
  120. app/engine/transformations/ml/base.py +253 -0
  121. app/engine/transformations/ml/cross_validation.py +455 -0
  122. app/engine/transformations/ml/evaluate.py +268 -0
  123. app/engine/transformations/ml/feature_engineering.py +330 -0
  124. app/engine/transformations/ml/importance.py +135 -0
  125. app/engine/transformations/ml/predict.py +150 -0
  126. app/engine/transformations/ml/split.py +128 -0
  127. app/engine/transformations/ml/train.py +513 -0
  128. app/engine/transformations/nulls.py +219 -0
  129. app/engine/transformations/numeric.py +232 -0
  130. app/engine/transformations/quality.py +489 -0
  131. app/engine/transformations/reshape.py +408 -0
  132. app/engine/transformations/rows.py +308 -0
  133. app/engine/transformations/script.py +113 -0
  134. app/engine/transformations/text.py +253 -0
  135. app/engine/transformations/window.py +342 -0
  136. app/flow_schema/__init__.py +57 -0
  137. app/flow_schema/document.py +186 -0
  138. app/flow_schema/migrations.py +84 -0
  139. app/flow_schema/validate.py +102 -0
  140. app/main.py +52 -0
  141. app/migrations/env.py +69 -0
  142. app/migrations/script.py.mako +26 -0
  143. app/migrations/versions/013616b14a34_baseline_schema.py +173 -0
  144. app/migrations/versions/a1f2c3d4e5b6_dataset_version_parse_options.py +30 -0
  145. app/migrations/versions/a7b8c9d0e1f2_disabled_by_project_id.py +58 -0
  146. app/migrations/versions/b8c9d0e1f2a3_webhook_idempotency_key.py +42 -0
  147. app/migrations/versions/c8d2e4f6a1b7_app_settings.py +36 -0
  148. app/migrations/versions/d4e5f6a7b8c9_dataset_name_unique_per_project.py +91 -0
  149. app/migrations/versions/e5f6a7b8c9d0_flow_disabled_reason.py +65 -0
  150. app/migrations/versions/f6a7b8c9d0e1_connection_test_result.py +34 -0
  151. app/ml/__init__.py +7 -0
  152. app/ml/availability.py +117 -0
  153. app/ml/loader.py +72 -0
  154. app/ml/models.py +333 -0
  155. app/ml/registry_deps.py +67 -0
  156. app/ml/security.py +124 -0
  157. app/ml/tracking.py +127 -0
  158. app/plugin_api/LICENSE +202 -0
  159. app/plugin_api/README.md +27 -0
  160. app/plugin_api/__init__.py +140 -0
  161. app/plugin_api/connector_runtime.py +79 -0
  162. app/plugin_api/events.py +117 -0
  163. app/plugin_api/manifest.py +156 -0
  164. app/plugin_api/model_ref.py +142 -0
  165. app/plugin_api/node_runtime.py +153 -0
  166. app/plugin_api/providers.py +157 -0
  167. app/plugin_api/registry.py +274 -0
  168. app/plugin_api/signing.py +89 -0
  169. app/plugin_api/specs.py +368 -0
  170. app/plugins/__init__.py +31 -0
  171. app/plugins/adapter.py +133 -0
  172. app/plugins/authoring.py +130 -0
  173. app/plugins/builtin.py +289 -0
  174. app/plugins/connectors.py +205 -0
  175. app/plugins/install.py +252 -0
  176. app/plugins/license_scan.py +74 -0
  177. app/plugins/licensing.py +208 -0
  178. app/plugins/loader.py +399 -0
  179. app/plugins/marketplace.py +236 -0
  180. app/plugins/model_store.py +189 -0
  181. app/plugins/package.py +369 -0
  182. app/plugins/permission_audit.py +171 -0
  183. app/plugins/runtime.py +221 -0
  184. app/plugins/state.py +236 -0
  185. app/scheduler/__init__.py +5 -0
  186. app/scheduler/cron.py +45 -0
  187. app/scheduler/runner.py +297 -0
  188. app/schemas/__init__.py +1 -0
  189. app/schemas/app_setting.py +38 -0
  190. app/schemas/connection.py +212 -0
  191. app/schemas/dataset.py +52 -0
  192. app/schemas/flow.py +100 -0
  193. app/schemas/parameter.py +20 -0
  194. app/schemas/preview.py +36 -0
  195. app/schemas/project.py +32 -0
  196. app/schemas/run.py +127 -0
  197. app/schemas/schedule.py +73 -0
  198. app/services/__init__.py +1 -0
  199. app/services/app_setting_service.py +88 -0
  200. app/services/codegen_service.py +187 -0
  201. app/services/connection_service.py +539 -0
  202. app/services/dataset_resolver.py +133 -0
  203. app/services/dataset_service.py +705 -0
  204. app/services/execution_service.py +666 -0
  205. app/services/flow_service.py +375 -0
  206. app/services/ml_service.py +386 -0
  207. app/services/preview_service.py +191 -0
  208. app/services/project_service.py +203 -0
  209. app/services/run_recovery.py +56 -0
  210. app/services/schedule_service.py +192 -0
  211. app/services/sql_resolver.py +172 -0
  212. app/services/storage_resolver.py +175 -0
  213. app/version.py +25 -0
  214. app/web/apple-touch-icon-180.png +0 -0
  215. app/web/assets/CollapsibleSection-vqaWJ9fi.js +1 -0
  216. app/web/assets/ColumnProfileList-yazk6Sh5.js +6 -0
  217. app/web/assets/ConfirmDialog-CilYvsKj.js +1 -0
  218. app/web/assets/ConnectionsPage-g6cNVbuB.js +28 -0
  219. app/web/assets/DataTable-CgurKSvb.js +1 -0
  220. app/web/assets/DatasetsPage-tNCku8ps.js +1 -0
  221. app/web/assets/DatasetsPanel-BmzeJfmg.js +11 -0
  222. app/web/assets/FilterBar-D0TyQvIn.js +6 -0
  223. app/web/assets/FlowEditorPage-mYk2tlNu.js +57 -0
  224. app/web/assets/FlowListPage-Bj0PGf_1.js +6 -0
  225. app/web/assets/ModelsPage-DZ4nSTtB.js +6 -0
  226. app/web/assets/PageState-C2DBJWDQ.js +11 -0
  227. app/web/assets/PluginsPage-Csoq7U_g.js +11 -0
  228. app/web/assets/ProjectDetailPage-DIwQKxBV.js +6 -0
  229. app/web/assets/ProjectsPage-1FM9eTvP.js +1 -0
  230. app/web/assets/RunDetailPage-DyoLfMH3.js +7 -0
  231. app/web/assets/RunsPage-Bgn6MXWQ.js +6 -0
  232. app/web/assets/ScheduleDetailPage-DV7WbG9q.js +6 -0
  233. app/web/assets/ScheduleFormDialog-DizTokxg.js +11 -0
  234. app/web/assets/SchedulesPage-Bey-8L5P.js +6 -0
  235. app/web/assets/SchemaConfigFields-BbnQOyNq.js +1 -0
  236. app/web/assets/SettingsPage-8N1RpE2i.js +1 -0
  237. app/web/assets/StatusBadge-CMlSozyl.js +6 -0
  238. app/web/assets/ViewToggle-CbtlU9aB.js +6 -0
  239. app/web/assets/arrow-left-BlhnJSst.js +6 -0
  240. app/web/assets/chartTheme-C5ap-Sga.css +1 -0
  241. app/web/assets/chartTheme-svibiOAC.js +51 -0
  242. app/web/assets/chevron-down-DDRzJCmh.js +6 -0
  243. app/web/assets/chevron-right-CK4sF3Hn.js +6 -0
  244. app/web/assets/copy-DibXw3HP.js +6 -0
  245. app/web/assets/createNode-B1vbHx_y.js +64 -0
  246. app/web/assets/dialog-BKMnXyX7.js +46 -0
  247. app/web/assets/file-spreadsheet-RWi-BAP6.js +21 -0
  248. app/web/assets/file-text-CjQnD38n.js +11 -0
  249. app/web/assets/flask-conical-BJEp0Ndc.js +6 -0
  250. app/web/assets/flow-ClI319QG.js +23 -0
  251. app/web/assets/folder-open-BhYU-V3D.js +6 -0
  252. app/web/assets/hooks-BiYo_vYS.js +1 -0
  253. app/web/assets/hooks-CUsR8CfO.js +1 -0
  254. app/web/assets/hooks-Cq4hkIuI.js +1 -0
  255. app/web/assets/hooks-D29uaTw7.js +1 -0
  256. app/web/assets/index-DGksfo5V.js +176 -0
  257. app/web/assets/index-b7AwFoCn.css +1 -0
  258. app/web/assets/input-UjPt6Mtg.js +1 -0
  259. app/web/assets/key-round-CE-7tLqG.js +6 -0
  260. app/web/assets/label-_ikWrJsu.js +6 -0
  261. app/web/assets/layout-grid-CxBwNepL.js +6 -0
  262. app/web/assets/lock-D_kWa8G5.js +6 -0
  263. app/web/assets/mouse-pointer-click-DOk2gLzP.js +11 -0
  264. app/web/assets/nodeCatalog-BMVr-j8h.js +23 -0
  265. app/web/assets/nodeVisuals-Bz6lN2IQ.js +206 -0
  266. app/web/assets/plus-VU2xTYQn.js +6 -0
  267. app/web/assets/power-DobDifhA.js +6 -0
  268. app/web/assets/projectColors-B3ogXQmw.js +1 -0
  269. app/web/assets/query-BmiXa-Ma.js +17 -0
  270. app/web/assets/react-Dm5zuiou.js +36 -0
  271. app/web/assets/rotate-ccw-wdbSoXek.js +6 -0
  272. app/web/assets/select-o0gBsI2_.js +1 -0
  273. app/web/assets/shield-x-BgpTReFE.js +16 -0
  274. app/web/assets/tabs-OgTraBmy.js +1 -0
  275. app/web/assets/tag-C_VHLlr1.js +11 -0
  276. app/web/assets/textarea-CNpbVqTI.js +1 -0
  277. app/web/assets/upload-BoUqQ4uA.js +6 -0
  278. app/web/assets/useFormatDateTime-BjU9-8e_.js +1 -0
  279. app/web/favicon.ico +0 -0
  280. app/web/favicon.svg +7 -0
  281. app/web/index.html +35 -0
  282. ciaren-0.1.0.dist-info/METADATA +396 -0
  283. ciaren-0.1.0.dist-info/RECORD +285 -0
  284. ciaren-0.1.0.dist-info/WHEEL +4 -0
  285. ciaren-0.1.0.dist-info/entry_points.txt +3 -0
app/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # Backend architecture guide
2
+
3
+ A short map of where things go and the boundaries between them. The layering rules
4
+ below are **enforced by tests** (`backend/tests/test_architecture_boundaries.py`), so
5
+ a violation fails CI rather than eroding the structure silently.
6
+
7
+ ## Layers
8
+
9
+ ```
10
+ HTTP ──▶ API layer app/api/ thin adapters: parse request → call a service → shape response
11
+ Application app/services/ use cases: validation, queries, transactions, orchestration
12
+ Engine app/engine/ execute / validate / codegen graphs; pure compute, no web
13
+ Integrations app/connectors/ external DBs, storage, REST; no web/DB-model knowledge
14
+ Persistence app/db/ SQLAlchemy models + Alembic migrations
15
+ Contracts app/schemas/ Pydantic request/response models
16
+ Plugins app/plugin_api/ + app/plugins/ extension contracts + runtime
17
+ Bootstrap app/bootstrap/ startup/shutdown lifecycle, seeding, frontend mount
18
+ ```
19
+
20
+ `app/main.py` is only a composition root: `create_app()` wires middleware
21
+ (`app/api/middleware.py`), error handlers (`app/api/errors.py`), routers
22
+ (`app/api/routers.py`), and the frontend mount (`app/bootstrap/frontend.py`); the
23
+ startup/shutdown sequence lives in `app/bootstrap/lifespan.py`.
24
+
25
+ ## Enforced boundary rules
26
+
27
+ 1. **Routes don't take a raw `AsyncSession`.** A route depends on a `*ServiceDep`
28
+ (see `app/api/deps.py`) and delegates DB work to the service. The one exception
29
+ is the `/ready` readiness probe, whose job *is* to check DB connectivity.
30
+ 2. **The engine imports no web/service/schema layer** (`fastapi`, `app.api`,
31
+ `app.services`, `app.schemas`). It operates on plain graph dicts and dataframes.
32
+ 3. **Connectors know nothing about the web or DB models** (no `fastapi`, `app.api`,
33
+ `app.db`, `app.schemas`). They speak `ConnectionSpec`/`StorageSpec` only.
34
+ 4. **Services stay below the API layer** (no `app.api` imports).
35
+ 5. **Plugins integrate only through `app.plugin_api`** contracts.
36
+
37
+ If one of these tests fails, move the logic to the right layer — don't relax the rule.
38
+
39
+ ## Transactions
40
+
41
+ A service method owns its transaction (commit/rollback). Routes never commit. When a
42
+ use case spans work that must be atomic within one request-scoped session, keep the
43
+ commit at the service boundary; use a SAVEPOINT (`db.begin_nested()`) for a
44
+ best-effort sub-step that must not poison the outer transaction (e.g. output-dataset
45
+ registration in `ExecutionService.run`).
46
+
47
+ ## REST / routing conventions
48
+
49
+ Routers are mounted in `app/api/routers.py`. Conventions:
50
+
51
+ - **Top-level collections** mount at `/api/<resource>`: `/api/flows`, `/api/datasets`,
52
+ `/api/projects`, `/api/connections`, `/api/transformations`, `/api/catalog`,
53
+ `/api/plugins`, `/api/marketplace`, `/api/settings`.
54
+ - **Nested / sibling paths** are owned by a router mounted at the bare `/api` prefix
55
+ that declares its full paths internally: e.g. `runs` owns both
56
+ `/api/flows/{id}/runs` and `/api/runs/...`; `ml`, `schedules`, and `webhooks`
57
+ likewise.
58
+ - **Non-CRUD actions** use an explicit verb sub-path: `/api/flows/{id}/duplicate`,
59
+ `/api/runs/{id}/cancel`, `/api/runs/{id}/retry`, `/api/datasets/{id}/restore`.
60
+ - **Health probes** are unprefixed: `/health` (liveness), `/ready` (readiness).
61
+ - Registration order matters: all API routers are included before the SPA catch-all
62
+ (`app/bootstrap/frontend.py`), so `/api/*` is never shadowed by the frontend.
63
+
64
+ The registered route set is snapshotted in
65
+ `backend/tests/test_route_snapshot.py` — an intentional route change updates the
66
+ snapshot; an accidental one (typo, collision, dropped route) fails the test.
67
+
68
+ ## Adding things
69
+
70
+ - **New endpoint**: thin route in `app/api/routes/`, logic in a service, contract in
71
+ `app/schemas/`, wired via a `*ServiceDep` in `app/api/deps.py` and included in
72
+ `app/api/routers.py`.
73
+ - **New node**: metadata (`engine/node_metadata.py`), config validation, pandas +
74
+ polars execution and codegen (with lazy safety), parity tests, docs, and the
75
+ frontend catalog fallback. A contract test (`backend/tests/test_node_catalog_contract.py`)
76
+ guards the backend catalog against drift.
77
+ - **New connector/plugin**: implement the `app/plugin_api` contract; declare driver
78
+ availability, permissions, and clear install/config error messages; add contract
79
+ tests.
80
+ - **Schema change**: an Alembic migration is the single source of truth
81
+ (`app/migrations/`); `init_db`'s additive-column pass is a dev convenience only.
82
+
83
+ ## Adding a node (checklist)
84
+
85
+ The backend is the authoritative catalog; the frontend only keeps a static fallback
86
+ for offline/first-paint. Do all of this so the two never diverge:
87
+
88
+ 1. **Transformation** — implement `BaseTransformation` in `app/engine/transformations/`:
89
+ `validate_config`, `execute` (pandas), plus the polars path and `to_python_code` /
90
+ `to_polars_code` (codegen), keeping lazy-safety in mind. Register it.
91
+ 2. **Metadata** — add the node's label, category, description, and default config in
92
+ `app/engine/node_metadata.py`; declare its handle topology (input/optional/model
93
+ handles, output handles) via `node_kinds` so the catalog reports it.
94
+ 3. **Parity tests** — validate + execute (pandas and polars) + codegen (pandas,
95
+ polars, lazy). Behavior must match across engines.
96
+ 4. **Catalog contract** — regenerate the catalog snapshot and reconcile the frontend
97
+ fallback:
98
+ - `CIAREN_UPDATE_NODE_CATALOG_SNAPSHOT=1 pytest tests/test_node_catalog_contract.py`
99
+ - update `frontend/src/features/flows/editor/nodeCatalog.ts` until
100
+ `frontend/src/features/flows/editor/__tests__/nodeCatalog.contract.test.ts` passes.
101
+ 5. **Docs** — document the node where user-facing node docs live.
102
+
103
+ The catalog contract test fails if the backend metadata changes without the snapshot
104
+ (and thus the frontend fallback) being reconciled — that's the drift guard.
app/__init__.py ADDED
@@ -0,0 +1 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
app/api/__init__.py ADDED
@@ -0,0 +1 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
app/api/deps.py ADDED
@@ -0,0 +1,72 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ from typing import Annotated
3
+
4
+ from fastapi import Depends
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from app.core.database import get_db
8
+ from app.services.app_setting_service import AppSettingService
9
+ from app.services.codegen_service import CodegenService
10
+ from app.services.connection_service import ConnectionService
11
+ from app.services.dataset_service import DatasetService
12
+ from app.services.execution_service import ExecutionService
13
+ from app.services.flow_service import FlowService
14
+ from app.services.ml_service import MLService
15
+ from app.services.preview_service import PreviewService
16
+ from app.services.project_service import ProjectService
17
+ from app.services.schedule_service import ScheduleService
18
+
19
+ # Raw DB session — only used internally by service factories, never in routes directly.
20
+ _DbSession = Annotated[AsyncSession, Depends(get_db)]
21
+
22
+
23
+ def _dataset_service(db: _DbSession) -> DatasetService:
24
+ return DatasetService(db)
25
+
26
+
27
+ def _flow_service(db: _DbSession) -> FlowService:
28
+ return FlowService(db)
29
+
30
+
31
+ def _execution_service(db: _DbSession) -> ExecutionService:
32
+ return ExecutionService(db)
33
+
34
+
35
+ def _preview_service(db: _DbSession) -> PreviewService:
36
+ return PreviewService(db)
37
+
38
+
39
+ def _codegen_service(db: _DbSession) -> CodegenService:
40
+ return CodegenService(db)
41
+
42
+
43
+ def _project_service(db: _DbSession) -> ProjectService:
44
+ return ProjectService(db)
45
+
46
+
47
+ def _schedule_service(db: _DbSession) -> ScheduleService:
48
+ return ScheduleService(db)
49
+
50
+
51
+ def _connection_service(db: _DbSession) -> ConnectionService:
52
+ return ConnectionService(db)
53
+
54
+
55
+ def _ml_service(db: _DbSession) -> MLService:
56
+ return MLService(db)
57
+
58
+
59
+ def _app_setting_service(db: _DbSession) -> AppSettingService:
60
+ return AppSettingService(db)
61
+
62
+
63
+ DatasetServiceDep = Annotated[DatasetService, Depends(_dataset_service)]
64
+ FlowServiceDep = Annotated[FlowService, Depends(_flow_service)]
65
+ ExecutionServiceDep = Annotated[ExecutionService, Depends(_execution_service)]
66
+ PreviewServiceDep = Annotated[PreviewService, Depends(_preview_service)]
67
+ CodegenServiceDep = Annotated[CodegenService, Depends(_codegen_service)]
68
+ ProjectServiceDep = Annotated[ProjectService, Depends(_project_service)]
69
+ ScheduleServiceDep = Annotated[ScheduleService, Depends(_schedule_service)]
70
+ ConnectionServiceDep = Annotated[ConnectionService, Depends(_connection_service)]
71
+ MLServiceDep = Annotated[MLService, Depends(_ml_service)]
72
+ AppSettingServiceDep = Annotated[AppSettingService, Depends(_app_setting_service)]
app/api/errors.py ADDED
@@ -0,0 +1,63 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """Domain-exception → HTTP-response mapping.
3
+
4
+ Keeps the translation from internal exception types to status codes in one place,
5
+ out of ``app.main``. Register on the app with :func:`register_exception_handlers`.
6
+ """
7
+
8
+ from fastapi import FastAPI, Request
9
+ from fastapi.exceptions import RequestValidationError
10
+ from fastapi.responses import JSONResponse
11
+
12
+ from app.core.exceptions import (
13
+ ConflictError,
14
+ DatasetParseError,
15
+ FileTooLargeError,
16
+ MLNotEnabledError,
17
+ NotFoundError,
18
+ UnsupportedFileTypeError,
19
+ ValidationError,
20
+ )
21
+
22
+
23
+ def register_exception_handlers(app: FastAPI) -> None:
24
+ @app.exception_handler(NotFoundError)
25
+ async def not_found_handler(request: Request, exc: NotFoundError) -> JSONResponse:
26
+ return JSONResponse(status_code=404, content={"detail": str(exc)})
27
+
28
+ @app.exception_handler(UnsupportedFileTypeError)
29
+ async def unsupported_type_handler(request: Request, exc: UnsupportedFileTypeError) -> JSONResponse:
30
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
31
+
32
+ @app.exception_handler(FileTooLargeError)
33
+ async def file_too_large_handler(request: Request, exc: FileTooLargeError) -> JSONResponse:
34
+ return JSONResponse(status_code=413, content={"detail": str(exc)})
35
+
36
+ @app.exception_handler(DatasetParseError)
37
+ async def parse_error_handler(request: Request, exc: DatasetParseError) -> JSONResponse:
38
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
39
+
40
+ @app.exception_handler(ValidationError)
41
+ async def validation_error_handler(request: Request, exc: ValidationError) -> JSONResponse:
42
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
43
+
44
+ @app.exception_handler(RequestValidationError)
45
+ async def request_validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
46
+ # Redact the echoed request input from validation errors. FastAPI's default
47
+ # 422 body includes the offending `input` (and `ctx`) verbatim — for a body
48
+ # carrying a plaintext secret (e.g. POST /api/connections/keyring) that would
49
+ # leak the secret into a response. Keep loc/msg/type so clients still see
50
+ # what failed, but never the submitted value.
51
+ safe = [
52
+ {"loc": list(err.get("loc", [])), "msg": str(err.get("msg", "")), "type": str(err.get("type", ""))}
53
+ for err in exc.errors()
54
+ ]
55
+ return JSONResponse(status_code=422, content={"detail": safe})
56
+
57
+ @app.exception_handler(ConflictError)
58
+ async def conflict_handler(request: Request, exc: ConflictError) -> JSONResponse:
59
+ return JSONResponse(status_code=409, content={"detail": str(exc)})
60
+
61
+ @app.exception_handler(MLNotEnabledError)
62
+ async def ml_not_enabled_handler(request: Request, exc: MLNotEnabledError) -> JSONResponse:
63
+ return JSONResponse(status_code=501, content={"detail": str(exc)})
app/api/middleware.py ADDED
@@ -0,0 +1,30 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """HTTP middleware wiring (CORS, gzip, security headers).
3
+
4
+ Register on the app with :func:`register_middleware`. Kept out of ``app.main`` so
5
+ the middleware stack is described in one readable place.
6
+ """
7
+
8
+ from fastapi import FastAPI, Request, Response
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.middleware.gzip import GZipMiddleware
11
+
12
+
13
+ def register_middleware(app: FastAPI, settings: object) -> None:
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=getattr(settings, "CORS_ORIGINS", []),
17
+ allow_credentials=True,
18
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
19
+ allow_headers=["Content-Type", "Authorization", "Accept", "X-Ciaren-Secret", "X-Ciaren-Token"],
20
+ )
21
+ # Compress responses (the served JS/CSS bundle and large JSON payloads).
22
+ app.add_middleware(GZipMiddleware, minimum_size=1024)
23
+
24
+ @app.middleware("http")
25
+ async def add_security_headers(request: Request, call_next: object) -> Response:
26
+ response: Response = await call_next(request) # type: ignore[operator]
27
+ response.headers["X-Content-Type-Options"] = "nosniff"
28
+ response.headers["X-Frame-Options"] = "DENY"
29
+ response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
30
+ return response
app/api/routers.py ADDED
@@ -0,0 +1,52 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """Single place that mounts every API router onto the app.
3
+
4
+ Registration order matters: the frontend SPA catch-all (mounted later, in
5
+ :func:`app.bootstrap.frontend.mount_frontend`) only takes paths the routers here
6
+ didn't claim, so all ``/api/*`` and health routes must be included first.
7
+
8
+ Prefix conventions (see app/README.md):
9
+ - Top-level collections mount at ``/api/<resource>`` (projects, flows, datasets, …).
10
+ - Routers that own nested/sibling paths (runs → ``/api/flows/{id}/runs`` +
11
+ ``/api/runs``; ml, schedules, webhooks) mount at the bare ``/api`` prefix and
12
+ declare their full paths internally.
13
+ """
14
+
15
+ from fastapi import FastAPI
16
+
17
+ from app.api.routes import (
18
+ catalog,
19
+ connections,
20
+ datasets,
21
+ flows,
22
+ health,
23
+ marketplace,
24
+ ml,
25
+ plugins,
26
+ projects,
27
+ runs,
28
+ schedules,
29
+ transformations,
30
+ webhooks,
31
+ )
32
+ from app.api.routes import settings as settings_routes
33
+
34
+
35
+ def register_routers(app: FastAPI) -> None:
36
+ app.include_router(health.router)
37
+ app.include_router(projects.router, prefix="/api/projects", tags=["projects"])
38
+ app.include_router(flows.router, prefix="/api/flows", tags=["flows"])
39
+ app.include_router(datasets.router, prefix="/api/datasets", tags=["datasets"])
40
+ app.include_router(connections.router, prefix="/api/connections", tags=["connections"])
41
+ app.include_router(runs.router, prefix="/api", tags=["runs"])
42
+ app.include_router(ml.router, prefix="/api", tags=["ml"])
43
+ app.include_router(schedules.router, prefix="/api", tags=["schedules"])
44
+ app.include_router(transformations.router, prefix="/api/transformations", tags=["transformations"])
45
+ app.include_router(catalog.router, prefix="/api/catalog", tags=["catalog"])
46
+ app.include_router(plugins.router, prefix="/api/plugins", tags=["plugins"])
47
+ app.include_router(marketplace.router, prefix="/api/marketplace", tags=["marketplace"])
48
+ app.include_router(webhooks.router, prefix="/api", tags=["webhook"])
49
+ # Registered after webhooks so the legacy GET /api/settings/webhook keeps
50
+ # resolving there; the settings router has no GET /{key}, so today there is
51
+ # no overlap — keep it that way (add-only PUT/DELETE per key).
52
+ app.include_router(settings_routes.router, prefix="/api/settings", tags=["settings"])
@@ -0,0 +1 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
@@ -0,0 +1,55 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ """Backend-fed catalog: node / connector / category metadata for the editor.
3
+
4
+ The frontend renders what the backend (plus installed plugins) reports here
5
+ instead of hard-coding the node list, so a plugin that registers a node makes it
6
+ appear in the palette without a frontend rebuild. ML nodes are gated the same way
7
+ as ``GET /api/transformations`` — hidden unless the ML extension is ready.
8
+ """
9
+
10
+ from fastapi import APIRouter
11
+ from pydantic import BaseModel
12
+
13
+ from app.engine.node_metadata import CATEGORY_LABELS, CATEGORY_ORDER
14
+ from app.ml.availability import ml_extension_ready
15
+ from app.plugin_api import ConnectorSpec, ExporterSpec, NodeSpec
16
+ from app.plugins import get_registry
17
+
18
+ router = APIRouter()
19
+
20
+
21
+ class CategorySpec(BaseModel):
22
+ id: str
23
+ label: str
24
+
25
+
26
+ @router.get("/nodes", response_model=list[NodeSpec])
27
+ async def list_catalog_nodes(category: str | None = None) -> list[NodeSpec]:
28
+ """The full node catalog. ML nodes are omitted unless the ML extension is
29
+ ready; an optional ``category`` filter narrows to one palette group."""
30
+ specs = get_registry().node_specs()
31
+ if not ml_extension_ready():
32
+ specs = [s for s in specs if not s.requires_ml]
33
+ if category is not None:
34
+ specs = [s for s in specs if s.category == category]
35
+ return specs
36
+
37
+
38
+ @router.get("/connectors", response_model=list[ConnectorSpec])
39
+ async def list_catalog_connectors() -> list[ConnectorSpec]:
40
+ """Connectors contributed by the core and any installed plugins, including
41
+ driver availability and the connection-form metadata the UI needs."""
42
+ return get_registry().connector_specs()
43
+
44
+
45
+ @router.get("/exporters", response_model=list[ExporterSpec])
46
+ async def list_catalog_exporters() -> list[ExporterSpec]:
47
+ """Code/artifact exporters contributed by the core and any installed plugins
48
+ (python, eager-polars, lazy-polars today)."""
49
+ return get_registry().exporter_specs()
50
+
51
+
52
+ @router.get("/categories", response_model=list[CategorySpec])
53
+ async def list_catalog_categories() -> list[CategorySpec]:
54
+ """Palette categories in display order."""
55
+ return [CategorySpec(id=cid, label=CATEGORY_LABELS[cid]) for cid in CATEGORY_ORDER]
@@ -0,0 +1,105 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ from fastapi import APIRouter, status
3
+
4
+ from app.api.deps import ConnectionServiceDep
5
+ from app.schemas.connection import (
6
+ ConnectionCreate,
7
+ ConnectionRead,
8
+ ConnectionTestResult,
9
+ ConnectionUpdate,
10
+ KeyringAvailability,
11
+ KeyringSecretStatus,
12
+ KeyringSecretWrite,
13
+ TableInfo,
14
+ )
15
+
16
+ router = APIRouter()
17
+
18
+
19
+ @router.get("", response_model=list[ConnectionRead])
20
+ async def list_connections(service: ConnectionServiceDep) -> list[ConnectionRead]:
21
+ return await service.list_all()
22
+
23
+
24
+ @router.post("", response_model=ConnectionRead, status_code=status.HTTP_201_CREATED)
25
+ async def create_connection(body: ConnectionCreate, service: ConnectionServiceDep) -> ConnectionRead:
26
+ return await service.create(body)
27
+
28
+
29
+ @router.get("/providers")
30
+ async def list_providers(service: ConnectionServiceDep) -> list[dict[str, object]]:
31
+ """Supported providers and whether each driver is installed (for the UI)."""
32
+ return service.providers()
33
+
34
+
35
+ @router.post("/test-config", response_model=ConnectionTestResult)
36
+ async def test_connection_config(body: ConnectionCreate, service: ConnectionServiceDep) -> ConnectionTestResult:
37
+ """Test an unsaved connection payload before saving it."""
38
+ return await service.test_config(body)
39
+
40
+
41
+ # -- OS keychain secrets (static paths declared before /{connection_id}) --------
42
+
43
+
44
+ @router.get("/keyring", response_model=KeyringAvailability)
45
+ async def keyring_availability(service: ConnectionServiceDep) -> KeyringAvailability:
46
+ """Whether this host has a usable OS keychain (so the UI can offer or hide
47
+ the 'save to keychain' action)."""
48
+ return await service.keyring_status()
49
+
50
+
51
+ @router.post("/keyring", response_model=KeyringSecretStatus, status_code=status.HTTP_201_CREATED)
52
+ async def store_keyring_secret(body: KeyringSecretWrite, service: ConnectionServiceDep) -> KeyringSecretStatus:
53
+ """Store a secret in the OS keychain and return its ``keyring:NAME`` reference.
54
+
55
+ The value is written to the platform keychain and never persisted by Ciaren,
56
+ returned, or logged. Refused with 409 if the name is already taken unless
57
+ ``overwrite`` is set.
58
+ """
59
+ return await service.store_keyring_secret(body)
60
+
61
+
62
+ @router.get("/keyring/{name}", response_model=KeyringSecretStatus)
63
+ async def keyring_secret_status(name: str, service: ConnectionServiceDep) -> KeyringSecretStatus:
64
+ """Whether a keychain secret exists — never returns its value."""
65
+ return await service.keyring_secret_status(name)
66
+
67
+
68
+ @router.delete("/keyring/{name}", status_code=status.HTTP_204_NO_CONTENT)
69
+ async def delete_keyring_secret(name: str, service: ConnectionServiceDep) -> None:
70
+ await service.remove_keyring_secret(name)
71
+
72
+
73
+ @router.get("/{connection_id}", response_model=ConnectionRead)
74
+ async def get_connection(connection_id: str, service: ConnectionServiceDep) -> ConnectionRead:
75
+ return await service.get(connection_id)
76
+
77
+
78
+ @router.patch("/{connection_id}", response_model=ConnectionRead)
79
+ async def update_connection(
80
+ connection_id: str, body: ConnectionUpdate, service: ConnectionServiceDep
81
+ ) -> ConnectionRead:
82
+ return await service.update(connection_id, body)
83
+
84
+
85
+ @router.delete("/{connection_id}", status_code=status.HTTP_204_NO_CONTENT)
86
+ async def delete_connection(connection_id: str, service: ConnectionServiceDep, force: bool = False) -> None:
87
+ """Delete a connection. Refused with 409 while flows still reference it,
88
+ unless ``?force=true`` (those flows then fail at run time until repointed)."""
89
+ await service.delete(connection_id, force=force)
90
+
91
+
92
+ @router.post("/{connection_id}/test", response_model=ConnectionTestResult)
93
+ async def test_connection(connection_id: str, service: ConnectionServiceDep) -> ConnectionTestResult:
94
+ return await service.test(connection_id)
95
+
96
+
97
+ @router.get("/{connection_id}/tables", response_model=list[TableInfo])
98
+ async def list_connection_tables(connection_id: str, service: ConnectionServiceDep) -> list[TableInfo]:
99
+ return await service.list_tables(connection_id)
100
+
101
+
102
+ @router.get("/{connection_id}/objects", response_model=list[str])
103
+ async def list_connection_objects(connection_id: str, service: ConnectionServiceDep, prefix: str = "") -> list[str]:
104
+ """List files/objects in a storage connection (S3 bucket, local folder, …)."""
105
+ return await service.list_objects(connection_id, prefix)
@@ -0,0 +1,142 @@
1
+ # SPDX-License-Identifier: AGPL-3.0-only
2
+ from typing import Any
3
+
4
+ from fastapi import APIRouter, Query, UploadFile, status
5
+ from fastapi.responses import FileResponse
6
+
7
+ from app.api.deps import DatasetServiceDep, FlowServiceDep
8
+ from app.core.exceptions import NotFoundError
9
+ from app.schemas.dataset import DatasetRead, DatasetUpdate, DatasetVersionRead
10
+ from app.schemas.flow import FlowRead
11
+
12
+ router = APIRouter()
13
+
14
+
15
+ @router.post("/upload", response_model=DatasetRead, status_code=status.HTTP_201_CREATED)
16
+ async def upload_dataset(
17
+ file: UploadFile,
18
+ service: DatasetServiceDep,
19
+ project_id: str | None = None,
20
+ delimiter: str | None = None,
21
+ encoding: str | None = None,
22
+ decimal: str | None = None,
23
+ sheet: str | None = None,
24
+ ) -> DatasetRead:
25
+ """Store an upload. Dialect options are optional: CSV/TSV delimiter,
26
+ encoding and decimal mark are auto-detected when omitted; Excel reads the
27
+ first sheet unless ``sheet`` (name or 0-based index) says otherwise."""
28
+ parse_options = {
29
+ k: v
30
+ for k, v in {"delimiter": delimiter, "encoding": encoding, "decimal": decimal, "sheet": sheet}.items()
31
+ if v is not None
32
+ }
33
+ return await service.upload(file, project_id, parse_options=parse_options)
34
+
35
+
36
+ @router.get("", response_model=list[DatasetRead])
37
+ async def list_datasets(
38
+ service: DatasetServiceDep, project_id: str | None = None, include_deleted: bool = False
39
+ ) -> list[DatasetRead]:
40
+ return await service.list_all(project_id, include_deleted=include_deleted)
41
+
42
+
43
+ @router.post("/purge-expired")
44
+ async def purge_expired_datasets(service: DatasetServiceDep) -> dict[str, int]:
45
+ """Hard-delete soft-deleted datasets past the retention window (removes files)."""
46
+ return {"purged": await service.purge_expired()}
47
+
48
+
49
+ @router.patch("/{dataset_id}", response_model=DatasetRead)
50
+ async def patch_dataset(
51
+ dataset_id: str,
52
+ body: DatasetUpdate,
53
+ service: DatasetServiceDep,
54
+ flow_service: FlowServiceDep,
55
+ ) -> DatasetRead:
56
+ """Partial-update a dataset. Disabling cascades to flows that use it as input."""
57
+ result = await service.update(dataset_id, body)
58
+ if body.is_disabled is True:
59
+ await flow_service.disable_flows_for_dataset(dataset_id)
60
+ return result
61
+
62
+
63
+ @router.delete("/{dataset_id}", status_code=status.HTTP_204_NO_CONTENT)
64
+ async def delete_dataset(
65
+ dataset_id: str,
66
+ service: DatasetServiceDep,
67
+ flow_service: FlowServiceDep,
68
+ purge: bool = False,
69
+ force: bool = False,
70
+ ) -> None:
71
+ """Soft-delete a dataset (retained for restore); ``?purge=true`` deletes it and
72
+ its files immediately. Refuses with 409 if a Production model was trained on it,
73
+ unless ``?force=true``.
74
+
75
+ Deleting a dataset disables the flows that use it as input — same cascade as
76
+ disabling it via PATCH — so "out of use" means the same thing on both paths and
77
+ a dependent flow can't silently keep running against a removed dataset."""
78
+ await service.delete(dataset_id, purge=purge, force=force)
79
+ await flow_service.disable_flows_for_dataset(dataset_id)
80
+
81
+
82
+ @router.post("/{dataset_id}/restore", response_model=DatasetRead)
83
+ async def restore_dataset(dataset_id: str, service: DatasetServiceDep) -> DatasetRead:
84
+ return await service.restore(dataset_id)
85
+
86
+
87
+ @router.get("/{dataset_id}/flows", response_model=list[FlowRead])
88
+ async def list_dataset_flows(
89
+ dataset_id: str, dataset_service: DatasetServiceDep, flow_service: FlowServiceDep
90
+ ) -> list[FlowRead]:
91
+ # 404 if the dataset doesn't exist, then return flows that reference it.
92
+ await dataset_service.get(dataset_id)
93
+ return await flow_service.list_using_dataset(dataset_id)
94
+
95
+
96
+ @router.get("/{dataset_id}", response_model=DatasetRead)
97
+ async def get_dataset(dataset_id: str, service: DatasetServiceDep) -> DatasetRead:
98
+ return await service.get(dataset_id)
99
+
100
+
101
+ @router.get("/{dataset_id}/versions", response_model=list[DatasetVersionRead])
102
+ async def list_dataset_versions(
103
+ dataset_id: str,
104
+ service: DatasetServiceDep,
105
+ limit: int = Query(default=100, ge=1, le=1000),
106
+ offset: int = Query(default=0, ge=0),
107
+ ) -> list[DatasetVersionRead]:
108
+ return await service.list_versions(dataset_id, limit=limit, offset=offset)
109
+
110
+
111
+ @router.get("/{dataset_id}/versions/{version_number}/download")
112
+ async def download_dataset_version(dataset_id: str, version_number: int, service: DatasetServiceDep) -> FileResponse:
113
+ """Stream a specific dataset version's file as a download."""
114
+ file_path = await service.get_version_location(dataset_id, version_number)
115
+ if not file_path.exists():
116
+ raise NotFoundError("Dataset version file", f"{dataset_id}/v{version_number}")
117
+ return FileResponse(
118
+ path=str(file_path),
119
+ filename=file_path.name,
120
+ media_type="application/octet-stream",
121
+ )
122
+
123
+
124
+ @router.get("/{dataset_id}/schema")
125
+ async def get_dataset_schema(
126
+ dataset_id: str, service: DatasetServiceDep, version: int | None = None
127
+ ) -> list[dict[str, Any]]:
128
+ return await service.get_schema(dataset_id, version)
129
+
130
+
131
+ @router.get("/{dataset_id}/sample")
132
+ async def get_dataset_sample(
133
+ dataset_id: str, service: DatasetServiceDep, version: int | None = None
134
+ ) -> list[dict[str, Any]]:
135
+ return await service.get_sample(dataset_id, version)
136
+
137
+
138
+ @router.get("/{dataset_id}/profile")
139
+ async def get_dataset_profile(
140
+ dataset_id: str, service: DatasetServiceDep, version: int | None = None
141
+ ) -> list[dict[str, Any]]:
142
+ return await service.get_profile(dataset_id, version)