Initialize governed Dataflow module
This commit is contained in:
35
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
35
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
@@ -0,0 +1,35 @@
|
||||
---
|
||||
name: "Bug"
|
||||
about: "Report a reproducible defect, regression, or incorrect behavior"
|
||||
title: "[Bug] "
|
||||
labels:
|
||||
- type/bug
|
||||
- status/triage
|
||||
- module/dataflow
|
||||
---
|
||||
|
||||
## Scope
|
||||
|
||||
- Repository:
|
||||
- Area/module:
|
||||
- Affected version or commit:
|
||||
|
||||
## Behavior
|
||||
|
||||
Expected:
|
||||
|
||||
Actual:
|
||||
|
||||
## Reproduction
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, screenshots, traces, or failing test output:
|
||||
|
||||
## Verification Target
|
||||
|
||||
Command or workflow that should pass when fixed:
|
||||
1
.gitea/ISSUE_TEMPLATE/config.yaml
Normal file
1
.gitea/ISSUE_TEMPLATE/config.yaml
Normal file
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
27
.gitea/ISSUE_TEMPLATE/docs_workflow.md
Normal file
27
.gitea/ISSUE_TEMPLATE/docs_workflow.md
Normal file
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: "Docs / workflow"
|
||||
about: "Request documentation, process, or developer workflow changes"
|
||||
title: "[Docs] "
|
||||
labels:
|
||||
- type/docs
|
||||
- status/triage
|
||||
- module/dataflow
|
||||
- area/docs
|
||||
---
|
||||
|
||||
## Scope
|
||||
|
||||
- Repository:
|
||||
- Document or workflow:
|
||||
|
||||
## Current State
|
||||
|
||||
What is missing, unclear, duplicated, or stale?
|
||||
|
||||
## Desired State
|
||||
|
||||
What should the docs or workflow make clear?
|
||||
|
||||
## Verification Target
|
||||
|
||||
How should this be checked?
|
||||
32
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
32
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: "Feature"
|
||||
about: "Propose new user-visible behavior or platform capability"
|
||||
title: "[Feature] "
|
||||
labels:
|
||||
- type/feature
|
||||
- status/triage
|
||||
- module/dataflow
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
What user, operator, or developer problem should this solve?
|
||||
|
||||
## Proposed Capability
|
||||
|
||||
What should exist when this is done?
|
||||
|
||||
## Ownership
|
||||
|
||||
- Owning repository:
|
||||
- Related module repositories:
|
||||
- Extension point or integration boundary:
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ]
|
||||
- [ ]
|
||||
|
||||
## Verification Target
|
||||
|
||||
Command, scenario, or UI flow that should prove completion:
|
||||
28
.gitea/ISSUE_TEMPLATE/task.md
Normal file
28
.gitea/ISSUE_TEMPLATE/task.md
Normal file
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: "Task"
|
||||
about: "Track implementation, maintenance, or migration work"
|
||||
title: "[Task] "
|
||||
labels:
|
||||
- type/task
|
||||
- status/triage
|
||||
- module/dataflow
|
||||
---
|
||||
|
||||
## Objective
|
||||
|
||||
What needs to be completed?
|
||||
|
||||
## Scope
|
||||
|
||||
- Owning repository:
|
||||
- In-scope:
|
||||
- Out-of-scope:
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ]
|
||||
- [ ]
|
||||
|
||||
## Verification Target
|
||||
|
||||
Command or manual check:
|
||||
25
.gitea/ISSUE_TEMPLATE/tech_debt.md
Normal file
25
.gitea/ISSUE_TEMPLATE/tech_debt.md
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: "Tech debt"
|
||||
about: "Track cleanup, refactoring, risk reduction, or deferred engineering work"
|
||||
title: "[Debt] "
|
||||
labels:
|
||||
- type/debt
|
||||
- status/triage
|
||||
- module/dataflow
|
||||
---
|
||||
|
||||
## Current Cost
|
||||
|
||||
What does this make harder, riskier, slower, or more fragile?
|
||||
|
||||
## Desired Shape
|
||||
|
||||
What should the code, tests, or architecture look like afterwards?
|
||||
|
||||
## Constraints
|
||||
|
||||
What behavior, compatibility, or module boundary must be preserved?
|
||||
|
||||
## Verification Target
|
||||
|
||||
Focused checks that should pass:
|
||||
15
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
15
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Issue
|
||||
|
||||
Closes #
|
||||
|
||||
## Summary
|
||||
|
||||
-
|
||||
|
||||
## Verification
|
||||
|
||||
-
|
||||
|
||||
## Notes
|
||||
|
||||
Follow-up issues:
|
||||
12
.gitignore
vendored
Normal file
12
.gitignore
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
.env
|
||||
.venv/
|
||||
node_modules/
|
||||
dist/
|
||||
*.tsbuildinfo
|
||||
webui/.test-build/
|
||||
22
AGENTS.md
Normal file
22
AGENTS.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# GovOPlaN Dataflow Codex Guide
|
||||
|
||||
## Scope
|
||||
|
||||
This repository owns canonical pipeline definitions, immutable revisions,
|
||||
validation, constrained SQL compilation, preview and run diagnostics, and
|
||||
lineage references.
|
||||
|
||||
Keep external connection profiles and credentials in `govoplan-connectors`,
|
||||
analytical presentation in `govoplan-reporting`, process orchestration in
|
||||
`govoplan-workflow`, and sanctions review semantics in
|
||||
`govoplan-risk-compliance`.
|
||||
|
||||
## Working Rules
|
||||
|
||||
- Never pass user-entered SQL directly to a database.
|
||||
- Keep previews bounded by rows, bytes, nodes, and execution time.
|
||||
- Do not persist preview row contents unless a future explicit retention policy
|
||||
requires it.
|
||||
- Optional module integrations use manifest interfaces and capabilities, not
|
||||
direct imports.
|
||||
- Gitea issues are the canonical backlog and implementation state.
|
||||
235
LICENSE
Normal file
235
LICENSE
Normal file
@@ -0,0 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
govoplan-core
|
||||
Copyright (C) 2026 add-ideas
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||
41
README.md
Normal file
41
README.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# GovOPlaN Dataflow
|
||||
|
||||
GovOPlaN Dataflow defines and runs governed tabular transformation pipelines.
|
||||
Power users can work with the same pipeline as a graphical node graph or as a
|
||||
constrained SQL query. Every saved change produces an immutable revision, and
|
||||
every preview records diagnostics and reproducibility metadata without storing
|
||||
the previewed row contents.
|
||||
|
||||
## Boundary
|
||||
|
||||
- **Dataflow:** pipeline graphs, revisions, validation, constrained SQL,
|
||||
previews/runs, diagnostics, and lineage.
|
||||
- **Connectors:** source connections, credentials, discovery, health, and
|
||||
bounded source access.
|
||||
- **Reporting:** governed datasets, analytical views, dashboards, and exports.
|
||||
- **Workflow:** orchestration, resumability, approvals, and module handoffs.
|
||||
- **Risk Compliance:** sanctions matching policy, review, dispositions, and
|
||||
legal evidence.
|
||||
|
||||
The first implementation supports bounded inline tabular sources and the
|
||||
`filter`, `select`, `aggregate`, `sort`, `limit`, and `output` transforms. The
|
||||
connector-backed source contract is tracked separately so credentials never
|
||||
become part of a pipeline definition.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
/mnt/DATA/git/govoplan/.venv/bin/python -m pip install -e .
|
||||
/mnt/DATA/git/govoplan/.venv/bin/python -m unittest discover -s tests
|
||||
```
|
||||
|
||||
WebUI:
|
||||
|
||||
```bash
|
||||
cd webui
|
||||
PATH=/mnt/DATA/git/govoplan-core/webui/node_modules/.bin:$PATH npm run typecheck
|
||||
npm run test:structure
|
||||
```
|
||||
|
||||
The implementation epic is
|
||||
[`govoplan-dataflow#1`](https://git.add-ideas.de/GovOPlaN/govoplan-dataflow/issues/1).
|
||||
25
pyproject.toml
Normal file
25
pyproject.toml
Normal file
@@ -0,0 +1,25 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=69", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "govoplan-dataflow"
|
||||
version = "0.1.14"
|
||||
description = "Governed graphical and SQL data pipelines for GovOPlaN."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
license = "AGPL-3.0-or-later"
|
||||
authors = [{ name = "GovOPlaN" }]
|
||||
dependencies = [
|
||||
"govoplan-core>=0.1.14",
|
||||
"sqlglot>=30.14,<31",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
govoplan_dataflow = ["py.typed"]
|
||||
|
||||
[project.entry-points."govoplan.modules"]
|
||||
dataflow = "govoplan_dataflow.backend.manifest:get_manifest"
|
||||
3
src/govoplan_dataflow/__init__.py
Normal file
3
src/govoplan_dataflow/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.14"
|
||||
1
src/govoplan_dataflow/backend/__init__.py
Normal file
1
src/govoplan_dataflow/backend/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from __future__ import annotations
|
||||
5
src/govoplan_dataflow/backend/db/__init__.py
Normal file
5
src/govoplan_dataflow/backend/db/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from govoplan_dataflow.backend.db.models import DataflowPipeline, DataflowPipelineRevision, DataflowRun
|
||||
|
||||
__all__ = ["DataflowPipeline", "DataflowPipelineRevision", "DataflowRun"]
|
||||
114
src/govoplan_dataflow/backend/db/models.py
Normal file
114
src/govoplan_dataflow/backend/db/models.py
Normal file
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from govoplan_core.db.base import Base, TimestampMixin
|
||||
|
||||
|
||||
def new_uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class DataflowPipeline(Base, TimestampMixin):
|
||||
__tablename__ = "dataflow_pipelines"
|
||||
__table_args__ = (
|
||||
Index("ix_dataflow_pipelines_tenant_status", "tenant_id", "status"),
|
||||
Index("ix_dataflow_pipelines_tenant_updated", "tenant_id", "updated_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(300), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default="draft", nullable=False, index=True)
|
||||
current_revision: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
|
||||
updated_by: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
|
||||
metadata_: Mapped[dict[str, Any]] = mapped_column("metadata", JSON, default=dict, nullable=False)
|
||||
|
||||
revisions: Mapped[list["DataflowPipelineRevision"]] = relationship(
|
||||
back_populates="pipeline",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="DataflowPipelineRevision.revision",
|
||||
)
|
||||
runs: Mapped[list["DataflowRun"]] = relationship(
|
||||
back_populates="pipeline",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="DataflowRun.created_at",
|
||||
)
|
||||
|
||||
|
||||
class DataflowPipelineRevision(Base, TimestampMixin):
|
||||
__tablename__ = "dataflow_pipeline_revisions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("pipeline_id", "revision", name="uq_dataflow_pipeline_revision"),
|
||||
Index("ix_dataflow_revisions_tenant_pipeline", "tenant_id", "pipeline_id"),
|
||||
Index("ix_dataflow_revisions_content_hash", "tenant_id", "content_hash"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
pipeline_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("dataflow_pipelines.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
schema_version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
|
||||
graph: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||
sql_text: Mapped[str | None] = mapped_column(Text)
|
||||
editor_mode: Mapped[str] = mapped_column(String(20), default="graph", nullable=False)
|
||||
content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
created_by: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
|
||||
|
||||
pipeline: Mapped[DataflowPipeline] = relationship(back_populates="revisions")
|
||||
|
||||
|
||||
class DataflowRun(Base, TimestampMixin):
|
||||
__tablename__ = "dataflow_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_dataflow_runs_tenant_status", "tenant_id", "status"),
|
||||
Index("ix_dataflow_runs_pipeline_created", "pipeline_id", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
pipeline_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("dataflow_pipelines.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
pipeline_revision_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("dataflow_pipeline_revisions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
run_type: Mapped[str] = mapped_column(String(30), default="preview", nullable=False, index=True)
|
||||
status: Mapped[str] = mapped_column(String(30), nullable=False, index=True)
|
||||
executor_version: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
definition_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
source_fingerprints: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, nullable=False)
|
||||
result_schema: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, nullable=False)
|
||||
diagnostics: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, nullable=False)
|
||||
input_row_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
output_row_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
error: Mapped[str | None] = mapped_column(Text)
|
||||
created_by: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
|
||||
|
||||
pipeline: Mapped[DataflowPipeline] = relationship(back_populates="runs")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DataflowPipeline",
|
||||
"DataflowPipelineRevision",
|
||||
"DataflowRun",
|
||||
"new_uuid",
|
||||
]
|
||||
312
src/govoplan_dataflow/backend/executor.py
Normal file
312
src/govoplan_dataflow/backend/executor.py
Normal file
@@ -0,0 +1,312 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from govoplan_dataflow.backend.graph import graph_input_map, topological_order, validate_graph
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
DataflowDiagnostic,
|
||||
NodePreviewDiagnostic,
|
||||
PipelineGraph,
|
||||
PreviewColumn,
|
||||
)
|
||||
|
||||
|
||||
EXECUTOR_VERSION = "dataflow-preview-v1"
|
||||
MAX_EXECUTION_SECONDS = 2.0
|
||||
MAX_RESULT_BYTES = 1_000_000
|
||||
|
||||
|
||||
class PipelineExecutionError(RuntimeError):
|
||||
def __init__(self, message: str, *, node_id: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.node_id = node_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PipelineExecutionResult:
|
||||
rows: list[dict[str, Any]]
|
||||
total_rows: int
|
||||
truncated: bool
|
||||
columns: list[PreviewColumn]
|
||||
diagnostics: list[DataflowDiagnostic]
|
||||
node_diagnostics: list[NodePreviewDiagnostic]
|
||||
source_fingerprints: list[dict[str, Any]]
|
||||
input_row_count: int
|
||||
|
||||
|
||||
def execute_preview(graph: PipelineGraph, *, row_limit: int) -> PipelineExecutionResult:
|
||||
validation = validate_graph(graph)
|
||||
errors = [item for item in validation if item.severity == "error"]
|
||||
if errors:
|
||||
raise PipelineExecutionError(errors[0].message, node_id=errors[0].node_id)
|
||||
|
||||
node_by_id = {node.id: node for node in graph.nodes}
|
||||
inputs = graph_input_map(graph)
|
||||
ordered, cyclic = topological_order(graph)
|
||||
if cyclic:
|
||||
raise PipelineExecutionError("Pipeline graph contains a cycle")
|
||||
|
||||
outputs: dict[str, list[dict[str, Any]]] = {}
|
||||
node_diagnostics: list[NodePreviewDiagnostic] = []
|
||||
source_fingerprints: list[dict[str, Any]] = []
|
||||
started = time.monotonic()
|
||||
input_row_count = 0
|
||||
|
||||
for node_id in ordered:
|
||||
if time.monotonic() - started > MAX_EXECUTION_SECONDS:
|
||||
raise PipelineExecutionError("Preview exceeded the two-second execution limit", node_id=node_id)
|
||||
node = node_by_id[node_id]
|
||||
node_started = time.monotonic()
|
||||
input_rows = [] if node.type.startswith("source.") else outputs[inputs[node_id]]
|
||||
try:
|
||||
if node.type == "source.inline":
|
||||
output_rows = [dict(row) for row in node.config.get("rows", [])]
|
||||
input_row_count += len(output_rows)
|
||||
source_fingerprints.append(
|
||||
{
|
||||
"node_id": node.id,
|
||||
"source_name": node.config.get("source_name"),
|
||||
"kind": "inline",
|
||||
"fingerprint": _rows_fingerprint(output_rows),
|
||||
"row_count": len(output_rows),
|
||||
}
|
||||
)
|
||||
elif node.type == "source.reference":
|
||||
raise PipelineExecutionError(
|
||||
"This connector-backed source is not available to the local preview executor.",
|
||||
node_id=node.id,
|
||||
)
|
||||
elif node.type == "filter":
|
||||
output_rows = _filter_rows(input_rows, node.config, node_id=node.id)
|
||||
elif node.type == "select":
|
||||
output_rows = _select_rows(input_rows, node.config)
|
||||
elif node.type == "aggregate":
|
||||
output_rows = _aggregate_rows(input_rows, node.config, node_id=node.id)
|
||||
elif node.type == "sort":
|
||||
output_rows = _sort_rows(input_rows, node.config)
|
||||
elif node.type == "limit":
|
||||
output_rows = input_rows[: int(node.config["count"])]
|
||||
elif node.type == "output":
|
||||
output_rows = [dict(row) for row in input_rows]
|
||||
else:
|
||||
raise PipelineExecutionError(f"Unsupported node type: {node.type}", node_id=node.id)
|
||||
except PipelineExecutionError:
|
||||
raise
|
||||
except (ArithmeticError, TypeError, ValueError) as exc:
|
||||
raise PipelineExecutionError(str(exc), node_id=node.id) from exc
|
||||
|
||||
if len(json.dumps(output_rows, default=str).encode("utf-8")) > MAX_RESULT_BYTES:
|
||||
raise PipelineExecutionError(
|
||||
"A preview node exceeded the one-megabyte result limit.",
|
||||
node_id=node.id,
|
||||
)
|
||||
outputs[node.id] = output_rows
|
||||
node_diagnostics.append(
|
||||
NodePreviewDiagnostic(
|
||||
node_id=node.id,
|
||||
status="succeeded",
|
||||
input_rows=len(input_rows),
|
||||
output_rows=len(output_rows),
|
||||
duration_ms=round((time.monotonic() - node_started) * 1000, 3),
|
||||
columns=infer_columns(output_rows),
|
||||
)
|
||||
)
|
||||
|
||||
output_node = next(node for node in graph.nodes if node.type == "output")
|
||||
all_rows = outputs[output_node.id]
|
||||
rows = all_rows[:row_limit]
|
||||
return PipelineExecutionResult(
|
||||
rows=rows,
|
||||
total_rows=len(all_rows),
|
||||
truncated=len(rows) < len(all_rows),
|
||||
columns=infer_columns(all_rows),
|
||||
diagnostics=[],
|
||||
node_diagnostics=node_diagnostics,
|
||||
source_fingerprints=source_fingerprints,
|
||||
input_row_count=input_row_count,
|
||||
)
|
||||
|
||||
|
||||
def infer_columns(rows: list[dict[str, Any]]) -> list[PreviewColumn]:
|
||||
names: list[str] = []
|
||||
for row in rows:
|
||||
for name in row:
|
||||
if name not in names:
|
||||
names.append(name)
|
||||
columns: list[PreviewColumn] = []
|
||||
for name in names:
|
||||
values = [row.get(name) for row in rows]
|
||||
concrete = [value for value in values if value is not None]
|
||||
inferred = _type_name(concrete[0]) if concrete else "unknown"
|
||||
if any(_type_name(value) != inferred for value in concrete[1:]):
|
||||
inferred = "mixed"
|
||||
columns.append(
|
||||
PreviewColumn(
|
||||
name=name,
|
||||
type=inferred,
|
||||
nullable=len(concrete) != len(values),
|
||||
)
|
||||
)
|
||||
return columns
|
||||
|
||||
|
||||
def _filter_rows(
|
||||
rows: list[dict[str, Any]],
|
||||
config: dict[str, Any],
|
||||
*,
|
||||
node_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
column = str(config["column"])
|
||||
operator = str(config["operator"])
|
||||
expected = config.get("value")
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
actual = row.get(column)
|
||||
try:
|
||||
matches = _compare(actual, operator, expected)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise PipelineExecutionError(
|
||||
f"Cannot apply {operator!r} to column {column!r}: {exc}",
|
||||
node_id=node_id,
|
||||
) from exc
|
||||
if matches:
|
||||
result.append(dict(row))
|
||||
return result
|
||||
|
||||
|
||||
def _compare(actual: Any, operator: str, expected: Any) -> bool:
|
||||
if operator == "is_null":
|
||||
return actual is None
|
||||
if operator == "not_null":
|
||||
return actual is not None
|
||||
if operator == "eq":
|
||||
return actual == expected
|
||||
if operator == "ne":
|
||||
return actual != expected
|
||||
if operator == "contains":
|
||||
return expected is not None and str(expected).casefold() in str(actual or "").casefold()
|
||||
if actual is None or expected is None:
|
||||
return False
|
||||
if operator == "gt":
|
||||
return actual > expected
|
||||
if operator == "gte":
|
||||
return actual >= expected
|
||||
if operator == "lt":
|
||||
return actual < expected
|
||||
if operator == "lte":
|
||||
return actual <= expected
|
||||
raise ValueError(f"unknown operator {operator!r}")
|
||||
|
||||
|
||||
def _select_rows(rows: list[dict[str, Any]], config: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
fields = config["fields"]
|
||||
normalized = [
|
||||
(
|
||||
field if isinstance(field, str) else str(field["column"]),
|
||||
field if isinstance(field, str) else str(field.get("alias") or field["column"]),
|
||||
)
|
||||
for field in fields
|
||||
]
|
||||
return [
|
||||
{alias: row.get(column) for column, alias in normalized}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def _aggregate_rows(
|
||||
rows: list[dict[str, Any]],
|
||||
config: dict[str, Any],
|
||||
*,
|
||||
node_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
group_by = [str(item) for item in config.get("group_by", [])]
|
||||
aggregates = list(config["aggregates"])
|
||||
grouped: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
|
||||
if rows:
|
||||
for row in rows:
|
||||
grouped[tuple(row.get(column) for column in group_by)].append(row)
|
||||
elif not group_by:
|
||||
grouped[()] = []
|
||||
|
||||
output: list[dict[str, Any]] = []
|
||||
for key, group_rows in grouped.items():
|
||||
result = {column: value for column, value in zip(group_by, key, strict=True)}
|
||||
for aggregate in aggregates:
|
||||
function = str(aggregate["function"])
|
||||
column = aggregate.get("column")
|
||||
alias = str(aggregate["alias"])
|
||||
values = [row.get(column) for row in group_rows if column is not None and row.get(column) is not None]
|
||||
try:
|
||||
if function == "count":
|
||||
result[alias] = len(group_rows) if column in (None, "", "*") else len(values)
|
||||
elif function == "sum":
|
||||
result[alias] = sum(values) if values else 0
|
||||
elif function == "avg":
|
||||
result[alias] = sum(values) / len(values) if values else None
|
||||
elif function == "min":
|
||||
result[alias] = min(values) if values else None
|
||||
elif function == "max":
|
||||
result[alias] = max(values) if values else None
|
||||
except (ArithmeticError, TypeError, ValueError) as exc:
|
||||
raise PipelineExecutionError(
|
||||
f"Cannot calculate {function.upper()} for {column!r}: {exc}",
|
||||
node_id=node_id,
|
||||
) from exc
|
||||
output.append(result)
|
||||
return output
|
||||
|
||||
|
||||
def _sort_rows(rows: list[dict[str, Any]], config: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
result = [dict(row) for row in rows]
|
||||
for field in reversed(config["fields"]):
|
||||
column = str(field["column"])
|
||||
reverse = field.get("direction", "asc") == "desc"
|
||||
result.sort(
|
||||
key=lambda row: (row.get(column) is None, _sortable_value(row.get(column))),
|
||||
reverse=reverse,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _sortable_value(value: Any) -> tuple[str, Any]:
|
||||
if isinstance(value, (int, float, Decimal, str)):
|
||||
return type(value).__name__, value
|
||||
return type(value).__name__, str(value)
|
||||
|
||||
|
||||
def _rows_fingerprint(rows: list[dict[str, Any]]) -> str:
|
||||
encoded = json.dumps(rows, sort_keys=True, separators=(",", ":"), default=str)
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _type_name(value: Any) -> str:
|
||||
if value is None:
|
||||
return "unknown"
|
||||
if isinstance(value, bool):
|
||||
return "boolean"
|
||||
if isinstance(value, int):
|
||||
return "integer"
|
||||
if isinstance(value, (float, Decimal)):
|
||||
return "number"
|
||||
if isinstance(value, str):
|
||||
return "string"
|
||||
if isinstance(value, list):
|
||||
return "array"
|
||||
if isinstance(value, dict):
|
||||
return "object"
|
||||
return type(value).__name__.lower()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"EXECUTOR_VERSION",
|
||||
"PipelineExecutionError",
|
||||
"PipelineExecutionResult",
|
||||
"execute_preview",
|
||||
"infer_columns",
|
||||
]
|
||||
325
src/govoplan_dataflow/backend/graph.py
Normal file
325
src/govoplan_dataflow/backend/graph.py
Normal file
@@ -0,0 +1,325 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections import deque
|
||||
from typing import Any
|
||||
|
||||
from govoplan_dataflow.backend.schemas import DataflowDiagnostic, GraphNode, PipelineGraph
|
||||
|
||||
|
||||
SUPPORTED_NODE_TYPES = frozenset(
|
||||
{
|
||||
"source.inline",
|
||||
"source.reference",
|
||||
"filter",
|
||||
"select",
|
||||
"aggregate",
|
||||
"sort",
|
||||
"limit",
|
||||
"output",
|
||||
}
|
||||
)
|
||||
FILTER_OPERATORS = frozenset(
|
||||
{"eq", "ne", "gt", "gte", "lt", "lte", "contains", "is_null", "not_null"}
|
||||
)
|
||||
AGGREGATE_FUNCTIONS = frozenset({"count", "sum", "avg", "min", "max"})
|
||||
|
||||
|
||||
def canonical_graph_payload(graph: PipelineGraph) -> dict[str, Any]:
|
||||
return graph.model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
def definition_hash(graph: PipelineGraph, sql_text: str | None = None) -> str:
|
||||
payload = {
|
||||
"graph": canonical_graph_payload(graph),
|
||||
"sql_text": (sql_text or "").strip() or None,
|
||||
}
|
||||
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def validate_graph(graph: PipelineGraph) -> list[DataflowDiagnostic]:
|
||||
diagnostics: list[DataflowDiagnostic] = []
|
||||
nodes = {node.id: node for node in graph.nodes}
|
||||
if len(nodes) != len(graph.nodes):
|
||||
diagnostics.append(_error("graph.duplicate_node", "Node identifiers must be unique."))
|
||||
|
||||
edge_ids = {edge.id for edge in graph.edges}
|
||||
if len(edge_ids) != len(graph.edges):
|
||||
diagnostics.append(_error("graph.duplicate_edge", "Edge identifiers must be unique."))
|
||||
|
||||
incoming: dict[str, list[str]] = {node_id: [] for node_id in nodes}
|
||||
outgoing: dict[str, list[str]] = {node_id: [] for node_id in nodes}
|
||||
for edge in graph.edges:
|
||||
if edge.source not in nodes:
|
||||
diagnostics.append(
|
||||
_error("edge.unknown_source", f"Edge {edge.id!r} references an unknown source node.")
|
||||
)
|
||||
continue
|
||||
if edge.target not in nodes:
|
||||
diagnostics.append(
|
||||
_error("edge.unknown_target", f"Edge {edge.id!r} references an unknown target node.")
|
||||
)
|
||||
continue
|
||||
if edge.source == edge.target:
|
||||
diagnostics.append(
|
||||
_error("edge.self_reference", "A node cannot connect to itself.", node_id=edge.source)
|
||||
)
|
||||
continue
|
||||
outgoing[edge.source].append(edge.target)
|
||||
incoming[edge.target].append(edge.source)
|
||||
|
||||
if not graph.nodes:
|
||||
diagnostics.append(_error("graph.empty", "Add a source and an output before saving the pipeline."))
|
||||
return diagnostics
|
||||
|
||||
source_nodes = [node for node in graph.nodes if node.type.startswith("source.")]
|
||||
output_nodes = [node for node in graph.nodes if node.type == "output"]
|
||||
if len(source_nodes) != 1:
|
||||
diagnostics.append(
|
||||
_error(
|
||||
"graph.source_count",
|
||||
"The first release supports exactly one source node per pipeline.",
|
||||
)
|
||||
)
|
||||
if len(output_nodes) != 1:
|
||||
diagnostics.append(
|
||||
_error("graph.output_count", "A pipeline must contain exactly one output node.")
|
||||
)
|
||||
|
||||
for node in graph.nodes:
|
||||
if node.type not in SUPPORTED_NODE_TYPES:
|
||||
diagnostics.append(
|
||||
_error(
|
||||
"node.unsupported_type",
|
||||
f"Node type {node.type!r} is not supported by this executor.",
|
||||
node_id=node.id,
|
||||
field="type",
|
||||
)
|
||||
)
|
||||
continue
|
||||
if node.type.startswith("source."):
|
||||
if incoming.get(node.id):
|
||||
diagnostics.append(
|
||||
_error("node.source_has_input", "Source nodes cannot have incoming edges.", node_id=node.id)
|
||||
)
|
||||
elif len(incoming.get(node.id, [])) != 1:
|
||||
diagnostics.append(
|
||||
_error(
|
||||
"node.input_count",
|
||||
"This transform requires exactly one incoming edge.",
|
||||
node_id=node.id,
|
||||
)
|
||||
)
|
||||
diagnostics.extend(_validate_node_config(node))
|
||||
|
||||
ordered, cyclic = topological_order(graph)
|
||||
if cyclic:
|
||||
diagnostics.append(_error("graph.cycle", "Pipeline edges must form an acyclic graph."))
|
||||
elif source_nodes and output_nodes:
|
||||
reachable = _reachable_from(source_nodes[0].id, outgoing)
|
||||
if len(reachable) != len(nodes):
|
||||
diagnostics.append(
|
||||
_error("graph.disconnected", "Every node must be connected to the pipeline source.")
|
||||
)
|
||||
reaches_output = _reachable_from(output_nodes[0].id, incoming)
|
||||
if len(reaches_output) != len(nodes):
|
||||
diagnostics.append(
|
||||
_error("graph.dead_end", "Every node must lead to the pipeline output.")
|
||||
)
|
||||
if ordered and ordered[-1] != output_nodes[0].id:
|
||||
diagnostics.append(
|
||||
_error("graph.output_not_terminal", "The output node must be the terminal transform.")
|
||||
)
|
||||
return diagnostics
|
||||
|
||||
|
||||
def topological_order(graph: PipelineGraph) -> tuple[list[str], bool]:
|
||||
node_ids = [node.id for node in graph.nodes]
|
||||
incoming_count = {node_id: 0 for node_id in node_ids}
|
||||
outgoing: dict[str, list[str]] = {node_id: [] for node_id in node_ids}
|
||||
for edge in graph.edges:
|
||||
if edge.source in outgoing and edge.target in incoming_count and edge.source != edge.target:
|
||||
outgoing[edge.source].append(edge.target)
|
||||
incoming_count[edge.target] += 1
|
||||
|
||||
ready = deque(node_id for node_id in node_ids if incoming_count[node_id] == 0)
|
||||
ordered: list[str] = []
|
||||
while ready:
|
||||
node_id = ready.popleft()
|
||||
ordered.append(node_id)
|
||||
for target in outgoing[node_id]:
|
||||
incoming_count[target] -= 1
|
||||
if incoming_count[target] == 0:
|
||||
ready.append(target)
|
||||
return ordered, len(ordered) != len(node_ids)
|
||||
|
||||
|
||||
def graph_input_map(graph: PipelineGraph) -> dict[str, str]:
|
||||
return {edge.target: edge.source for edge in graph.edges}
|
||||
|
||||
|
||||
def _reachable_from(start: str, adjacency: dict[str, list[str]]) -> set[str]:
|
||||
seen: set[str] = set()
|
||||
pending = [start]
|
||||
while pending:
|
||||
node_id = pending.pop()
|
||||
if node_id in seen:
|
||||
continue
|
||||
seen.add(node_id)
|
||||
pending.extend(adjacency.get(node_id, ()))
|
||||
return seen
|
||||
|
||||
|
||||
def _validate_node_config(node: GraphNode) -> list[DataflowDiagnostic]:
|
||||
config = node.config
|
||||
diagnostics: list[DataflowDiagnostic] = []
|
||||
if node.type in {"source.inline", "source.reference"}:
|
||||
source_name = config.get("source_name")
|
||||
if not isinstance(source_name, str) or not source_name.strip():
|
||||
diagnostics.append(
|
||||
_error(
|
||||
"source.name_required",
|
||||
"A source needs a logical SQL name.",
|
||||
node_id=node.id,
|
||||
field="source_name",
|
||||
)
|
||||
)
|
||||
if node.type == "source.reference":
|
||||
return diagnostics
|
||||
rows = config.get("rows")
|
||||
if not isinstance(rows, list):
|
||||
diagnostics.append(
|
||||
_error("source.rows_required", "Inline source rows must be a list.", node_id=node.id, field="rows")
|
||||
)
|
||||
elif len(rows) > 250:
|
||||
diagnostics.append(
|
||||
_error("source.row_limit", "Inline sources are limited to 250 rows.", node_id=node.id, field="rows")
|
||||
)
|
||||
elif any(not isinstance(row, dict) for row in rows):
|
||||
diagnostics.append(
|
||||
_error("source.row_shape", "Every inline source row must be an object.", node_id=node.id, field="rows")
|
||||
)
|
||||
if len(json.dumps(config, default=str).encode("utf-8")) > 512_000:
|
||||
diagnostics.append(
|
||||
_error("source.byte_limit", "Inline source configuration is limited to 512 KiB.", node_id=node.id)
|
||||
)
|
||||
elif node.type == "filter":
|
||||
if not _non_empty_text(config.get("column")):
|
||||
diagnostics.append(_node_field_error(node, "filter.column", "Choose a column.", "column"))
|
||||
operator = config.get("operator")
|
||||
if operator not in FILTER_OPERATORS:
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "filter.operator", "Choose a supported comparison operator.", "operator")
|
||||
)
|
||||
if operator not in {"is_null", "not_null"} and "value" not in config:
|
||||
diagnostics.append(_node_field_error(node, "filter.value", "Enter a comparison value.", "value"))
|
||||
elif node.type == "select":
|
||||
fields = config.get("fields")
|
||||
if not isinstance(fields, list) or not fields:
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "select.fields", "Select at least one output column.", "fields")
|
||||
)
|
||||
else:
|
||||
for field in fields:
|
||||
column = field if isinstance(field, str) else field.get("column") if isinstance(field, dict) else None
|
||||
if not _non_empty_text(column):
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "select.field", "Selected fields need a source column.", "fields")
|
||||
)
|
||||
break
|
||||
elif node.type == "aggregate":
|
||||
group_by = config.get("group_by", [])
|
||||
aggregates = config.get("aggregates")
|
||||
if not isinstance(group_by, list) or any(not _non_empty_text(item) for item in group_by):
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "aggregate.group_by", "Group-by columns must be named.", "group_by")
|
||||
)
|
||||
if not isinstance(aggregates, list) or not aggregates:
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "aggregate.required", "Add at least one aggregate.", "aggregates")
|
||||
)
|
||||
else:
|
||||
for aggregate in aggregates:
|
||||
if not isinstance(aggregate, dict) or aggregate.get("function") not in AGGREGATE_FUNCTIONS:
|
||||
diagnostics.append(
|
||||
_node_field_error(
|
||||
node,
|
||||
"aggregate.function",
|
||||
"Choose COUNT, SUM, AVG, MIN, or MAX.",
|
||||
"aggregates",
|
||||
)
|
||||
)
|
||||
break
|
||||
if aggregate.get("function") != "count" and not _non_empty_text(aggregate.get("column")):
|
||||
diagnostics.append(
|
||||
_node_field_error(
|
||||
node,
|
||||
"aggregate.column",
|
||||
"This aggregate needs a source column.",
|
||||
"aggregates",
|
||||
)
|
||||
)
|
||||
break
|
||||
if not _non_empty_text(aggregate.get("alias")):
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "aggregate.alias", "Every aggregate needs an alias.", "aggregates")
|
||||
)
|
||||
break
|
||||
elif node.type == "sort":
|
||||
fields = config.get("fields")
|
||||
if not isinstance(fields, list) or not fields:
|
||||
diagnostics.append(_node_field_error(node, "sort.fields", "Add at least one sort field.", "fields"))
|
||||
elif any(
|
||||
not isinstance(item, dict)
|
||||
or not _non_empty_text(item.get("column"))
|
||||
or item.get("direction", "asc") not in {"asc", "desc"}
|
||||
for item in fields
|
||||
):
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "sort.field", "Sort fields need a column and direction.", "fields")
|
||||
)
|
||||
elif node.type == "limit":
|
||||
count = config.get("count")
|
||||
if not isinstance(count, int) or isinstance(count, bool) or not 1 <= count <= 100_000:
|
||||
diagnostics.append(
|
||||
_node_field_error(node, "limit.count", "Limit must be between 1 and 100,000.", "count")
|
||||
)
|
||||
return diagnostics
|
||||
|
||||
|
||||
def _non_empty_text(value: object) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def _node_field_error(node: GraphNode, code: str, message: str, field: str) -> DataflowDiagnostic:
|
||||
return _error(code, message, node_id=node.id, field=field)
|
||||
|
||||
|
||||
def _error(
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
node_id: str | None = None,
|
||||
field: str | None = None,
|
||||
) -> DataflowDiagnostic:
|
||||
return DataflowDiagnostic(
|
||||
severity="error",
|
||||
code=code,
|
||||
message=message,
|
||||
node_id=node_id,
|
||||
field=field,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AGGREGATE_FUNCTIONS",
|
||||
"FILTER_OPERATORS",
|
||||
"SUPPORTED_NODE_TYPES",
|
||||
"canonical_graph_payload",
|
||||
"definition_hash",
|
||||
"graph_input_map",
|
||||
"topological_order",
|
||||
"validate_graph",
|
||||
]
|
||||
240
src/govoplan_dataflow/backend/manifest.py
Normal file
240
src/govoplan_dataflow/backend/manifest.py
Normal file
@@ -0,0 +1,240 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from govoplan_core.core.module_guards import (
|
||||
drop_table_retirement_provider,
|
||||
persistent_table_uninstall_guard,
|
||||
)
|
||||
from govoplan_core.core.modules import (
|
||||
DocumentationTopic,
|
||||
FrontendModule,
|
||||
MigrationSpec,
|
||||
ModuleInterfaceProvider,
|
||||
ModuleManifest,
|
||||
NavItem,
|
||||
PermissionDefinition,
|
||||
RoleTemplate,
|
||||
)
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_dataflow.backend.db import models as dataflow_models
|
||||
|
||||
|
||||
MODULE_ID = "dataflow"
|
||||
MODULE_NAME = "Dataflow"
|
||||
MODULE_VERSION = "0.1.14"
|
||||
|
||||
READ_SCOPE = "dataflow:pipeline:read"
|
||||
WRITE_SCOPE = "dataflow:pipeline:write"
|
||||
RUN_SCOPE = "dataflow:pipeline:run"
|
||||
ADMIN_SCOPE = "dataflow:pipeline:admin"
|
||||
|
||||
|
||||
def _permission(scope: str, label: str, description: str) -> PermissionDefinition:
|
||||
module_id, resource, action = scope.split(":", 2)
|
||||
return PermissionDefinition(
|
||||
scope=scope,
|
||||
label=label,
|
||||
description=description,
|
||||
category="Dataflow",
|
||||
level="tenant",
|
||||
module_id=module_id,
|
||||
resource=resource,
|
||||
action=action,
|
||||
)
|
||||
|
||||
|
||||
PERMISSIONS = (
|
||||
_permission(
|
||||
READ_SCOPE,
|
||||
"View data pipelines",
|
||||
"Read pipeline definitions, revisions, validation diagnostics, and run summaries.",
|
||||
),
|
||||
_permission(
|
||||
WRITE_SCOPE,
|
||||
"Manage data pipelines",
|
||||
"Create, edit, version, archive, and remove data pipeline definitions.",
|
||||
),
|
||||
_permission(
|
||||
RUN_SCOPE,
|
||||
"Run data pipelines",
|
||||
"Validate and execute bounded previews or approved pipeline runs.",
|
||||
),
|
||||
_permission(
|
||||
ADMIN_SCOPE,
|
||||
"Administer Dataflow",
|
||||
"Manage every tenant pipeline and future execution, retention, and publication policies.",
|
||||
),
|
||||
)
|
||||
|
||||
ROLE_TEMPLATES = (
|
||||
RoleTemplate(
|
||||
slug="dataflow_designer",
|
||||
name="Dataflow designer",
|
||||
description="Design, validate, and preview governed data pipelines.",
|
||||
permissions=(READ_SCOPE, WRITE_SCOPE, RUN_SCOPE),
|
||||
),
|
||||
RoleTemplate(
|
||||
slug="dataflow_operator",
|
||||
name="Dataflow operator",
|
||||
description="Inspect and run approved data pipelines without changing their definitions.",
|
||||
permissions=(READ_SCOPE, RUN_SCOPE),
|
||||
),
|
||||
RoleTemplate(
|
||||
slug="dataflow_viewer",
|
||||
name="Dataflow viewer",
|
||||
description="Inspect pipeline definitions, revisions, diagnostics, and run summaries.",
|
||||
permissions=(READ_SCOPE,),
|
||||
),
|
||||
)
|
||||
|
||||
DOCUMENTATION = (
|
||||
DocumentationTopic(
|
||||
id="dataflow.module-boundary",
|
||||
title="Dataflow module boundary",
|
||||
summary="Versioned tabular transformations with graphical and constrained SQL editing.",
|
||||
body=(
|
||||
"Dataflow owns canonical pipeline graphs, immutable revisions, validation, constrained "
|
||||
"SQL compilation, preview and run diagnostics, and lineage references. Connectors owns "
|
||||
"source connections and credentials; Reporting owns analytical presentation and exports; "
|
||||
"Workflow owns orchestration and human handoffs; Risk Compliance owns sanctions review "
|
||||
"semantics and policy gates. User SQL is compiled into approved transforms and is never "
|
||||
"passed unchecked to a backing database."
|
||||
),
|
||||
layer="available",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("operator", "module_admin", "power_user", "product_owner"),
|
||||
order=75,
|
||||
related_modules=(
|
||||
"connectors",
|
||||
"files",
|
||||
"reporting",
|
||||
"workflow",
|
||||
"risk_compliance",
|
||||
"notifications",
|
||||
"policy",
|
||||
"audit",
|
||||
),
|
||||
metadata={
|
||||
"first_slice": "Inline source, filter, select, aggregate, sort, limit, output, revisioning, and bounded preview.",
|
||||
"sql_safety": "Constrained AST compilation only; no pass-through execution.",
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _dataflow_router(_context):
|
||||
from govoplan_dataflow.backend.router import router
|
||||
|
||||
return router
|
||||
|
||||
|
||||
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
|
||||
return {
|
||||
"dataflow_pipelines": (
|
||||
session.query(dataflow_models.DataflowPipeline)
|
||||
.filter(
|
||||
dataflow_models.DataflowPipeline.tenant_id == tenant_id,
|
||||
dataflow_models.DataflowPipeline.deleted_at.is_(None),
|
||||
)
|
||||
.count()
|
||||
),
|
||||
"dataflow_runs": (
|
||||
session.query(dataflow_models.DataflowRun)
|
||||
.filter(dataflow_models.DataflowRun.tenant_id == tenant_id)
|
||||
.count()
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
manifest = ModuleManifest(
|
||||
id=MODULE_ID,
|
||||
name=MODULE_NAME,
|
||||
version=MODULE_VERSION,
|
||||
dependencies=(),
|
||||
optional_dependencies=(
|
||||
"access",
|
||||
"audit",
|
||||
"connectors",
|
||||
"files",
|
||||
"notifications",
|
||||
"policy",
|
||||
"reporting",
|
||||
"risk_compliance",
|
||||
"workflow",
|
||||
),
|
||||
provides_interfaces=(
|
||||
ModuleInterfaceProvider(name="dataflow.pipeline_catalog", version=MODULE_VERSION),
|
||||
ModuleInterfaceProvider(name="dataflow.pipeline_preview", version=MODULE_VERSION),
|
||||
ModuleInterfaceProvider(name="dataflow.run_lifecycle", version=MODULE_VERSION),
|
||||
ModuleInterfaceProvider(name="dataflow.dataset_output", version=MODULE_VERSION),
|
||||
),
|
||||
permissions=PERMISSIONS,
|
||||
role_templates=ROLE_TEMPLATES,
|
||||
nav_items=(
|
||||
NavItem(
|
||||
path="/dataflow",
|
||||
label="Dataflow",
|
||||
icon="waypoints",
|
||||
required_any=(READ_SCOPE, ADMIN_SCOPE),
|
||||
order=72,
|
||||
),
|
||||
),
|
||||
frontend=FrontendModule(
|
||||
module_id=MODULE_ID,
|
||||
package_name="@govoplan/dataflow-webui",
|
||||
nav_items=(
|
||||
NavItem(
|
||||
path="/dataflow",
|
||||
label="Dataflow",
|
||||
icon="waypoints",
|
||||
required_any=(READ_SCOPE, ADMIN_SCOPE),
|
||||
order=72,
|
||||
),
|
||||
),
|
||||
),
|
||||
route_factory=_dataflow_router,
|
||||
tenant_summary_providers=(_tenant_summary,),
|
||||
migration_spec=MigrationSpec(
|
||||
module_id=MODULE_ID,
|
||||
metadata=Base.metadata,
|
||||
script_location=str(Path(__file__).with_name("migrations") / "versions"),
|
||||
retirement_supported=True,
|
||||
retirement_provider=drop_table_retirement_provider(
|
||||
dataflow_models.DataflowRun,
|
||||
dataflow_models.DataflowPipelineRevision,
|
||||
dataflow_models.DataflowPipeline,
|
||||
label="Dataflow",
|
||||
),
|
||||
retirement_notes=(
|
||||
"Destructive retirement drops Dataflow definitions, revisions, and run evidence "
|
||||
"after the installer captures a database snapshot."
|
||||
),
|
||||
),
|
||||
uninstall_guard_providers=(
|
||||
persistent_table_uninstall_guard(
|
||||
dataflow_models.DataflowPipeline,
|
||||
dataflow_models.DataflowPipelineRevision,
|
||||
dataflow_models.DataflowRun,
|
||||
label="Dataflow",
|
||||
),
|
||||
),
|
||||
documentation=DOCUMENTATION,
|
||||
)
|
||||
|
||||
|
||||
def get_manifest() -> ModuleManifest:
|
||||
return manifest
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ADMIN_SCOPE",
|
||||
"MODULE_ID",
|
||||
"MODULE_NAME",
|
||||
"MODULE_VERSION",
|
||||
"READ_SCOPE",
|
||||
"RUN_SCOPE",
|
||||
"WRITE_SCOPE",
|
||||
"get_manifest",
|
||||
"manifest",
|
||||
]
|
||||
1
src/govoplan_dataflow/backend/migrations/__init__.py
Normal file
1
src/govoplan_dataflow/backend/migrations/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from __future__ import annotations
|
||||
@@ -0,0 +1 @@
|
||||
from __future__ import annotations
|
||||
@@ -0,0 +1,143 @@
|
||||
"""v0.1.14 Dataflow baseline
|
||||
|
||||
Revision ID: d4f7a1c8e2b0
|
||||
Revises: None
|
||||
Create Date: 2026-07-28 00:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "d4f7a1c8e2b0"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"dataflow_pipelines",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("name", sa.String(length=300), nullable=False),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("status", sa.String(length=32), nullable=False),
|
||||
sa.Column("current_revision", sa.Integer(), nullable=False),
|
||||
sa.Column("created_by", sa.String(length=255), nullable=True),
|
||||
sa.Column("updated_by", sa.String(length=255), nullable=True),
|
||||
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("metadata", sa.JSON(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_dataflow_pipelines")),
|
||||
)
|
||||
op.create_index(op.f("ix_dataflow_pipelines_created_by"), "dataflow_pipelines", ["created_by"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipelines_deleted_at"), "dataflow_pipelines", ["deleted_at"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipelines_status"), "dataflow_pipelines", ["status"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipelines_tenant_id"), "dataflow_pipelines", ["tenant_id"], unique=False)
|
||||
op.create_index("ix_dataflow_pipelines_tenant_status", "dataflow_pipelines", ["tenant_id", "status"], unique=False)
|
||||
op.create_index("ix_dataflow_pipelines_tenant_updated", "dataflow_pipelines", ["tenant_id", "updated_at"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipelines_updated_by"), "dataflow_pipelines", ["updated_by"], unique=False)
|
||||
|
||||
op.create_table(
|
||||
"dataflow_pipeline_revisions",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("pipeline_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("revision", sa.Integer(), nullable=False),
|
||||
sa.Column("schema_version", sa.Integer(), nullable=False),
|
||||
sa.Column("graph", sa.JSON(), nullable=False),
|
||||
sa.Column("sql_text", sa.Text(), nullable=True),
|
||||
sa.Column("editor_mode", sa.String(length=20), nullable=False),
|
||||
sa.Column("content_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("created_by", sa.String(length=255), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["pipeline_id"],
|
||||
["dataflow_pipelines.id"],
|
||||
name=op.f("fk_dataflow_pipeline_revisions_pipeline_id_dataflow_pipelines"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_dataflow_pipeline_revisions")),
|
||||
sa.UniqueConstraint("pipeline_id", "revision", name="uq_dataflow_pipeline_revision"),
|
||||
)
|
||||
op.create_index(op.f("ix_dataflow_pipeline_revisions_created_by"), "dataflow_pipeline_revisions", ["created_by"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipeline_revisions_pipeline_id"), "dataflow_pipeline_revisions", ["pipeline_id"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_pipeline_revisions_tenant_id"), "dataflow_pipeline_revisions", ["tenant_id"], unique=False)
|
||||
op.create_index("ix_dataflow_revisions_content_hash", "dataflow_pipeline_revisions", ["tenant_id", "content_hash"], unique=False)
|
||||
op.create_index("ix_dataflow_revisions_tenant_pipeline", "dataflow_pipeline_revisions", ["tenant_id", "pipeline_id"], unique=False)
|
||||
|
||||
op.create_table(
|
||||
"dataflow_runs",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("pipeline_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("pipeline_revision_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("run_type", sa.String(length=30), nullable=False),
|
||||
sa.Column("status", sa.String(length=30), nullable=False),
|
||||
sa.Column("executor_version", sa.String(length=40), nullable=False),
|
||||
sa.Column("definition_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("source_fingerprints", sa.JSON(), nullable=False),
|
||||
sa.Column("result_schema", sa.JSON(), nullable=False),
|
||||
sa.Column("diagnostics", sa.JSON(), nullable=False),
|
||||
sa.Column("input_row_count", sa.Integer(), nullable=False),
|
||||
sa.Column("output_row_count", sa.Integer(), nullable=False),
|
||||
sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("error", sa.Text(), nullable=True),
|
||||
sa.Column("created_by", sa.String(length=255), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["pipeline_id"],
|
||||
["dataflow_pipelines.id"],
|
||||
name=op.f("fk_dataflow_runs_pipeline_id_dataflow_pipelines"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["pipeline_revision_id"],
|
||||
["dataflow_pipeline_revisions.id"],
|
||||
name=op.f("fk_dataflow_runs_pipeline_revision_id_dataflow_pipeline_revisions"),
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_dataflow_runs")),
|
||||
)
|
||||
op.create_index(op.f("ix_dataflow_runs_created_by"), "dataflow_runs", ["created_by"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_runs_pipeline_id"), "dataflow_runs", ["pipeline_id"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_runs_pipeline_revision_id"), "dataflow_runs", ["pipeline_revision_id"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_runs_run_type"), "dataflow_runs", ["run_type"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_runs_status"), "dataflow_runs", ["status"], unique=False)
|
||||
op.create_index(op.f("ix_dataflow_runs_tenant_id"), "dataflow_runs", ["tenant_id"], unique=False)
|
||||
op.create_index("ix_dataflow_runs_pipeline_created", "dataflow_runs", ["pipeline_id", "created_at"], unique=False)
|
||||
op.create_index("ix_dataflow_runs_tenant_status", "dataflow_runs", ["tenant_id", "status"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_dataflow_runs_tenant_status", table_name="dataflow_runs")
|
||||
op.drop_index("ix_dataflow_runs_pipeline_created", table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_tenant_id"), table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_status"), table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_run_type"), table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_pipeline_revision_id"), table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_pipeline_id"), table_name="dataflow_runs")
|
||||
op.drop_index(op.f("ix_dataflow_runs_created_by"), table_name="dataflow_runs")
|
||||
op.drop_table("dataflow_runs")
|
||||
|
||||
op.drop_index("ix_dataflow_revisions_tenant_pipeline", table_name="dataflow_pipeline_revisions")
|
||||
op.drop_index("ix_dataflow_revisions_content_hash", table_name="dataflow_pipeline_revisions")
|
||||
op.drop_index(op.f("ix_dataflow_pipeline_revisions_tenant_id"), table_name="dataflow_pipeline_revisions")
|
||||
op.drop_index(op.f("ix_dataflow_pipeline_revisions_pipeline_id"), table_name="dataflow_pipeline_revisions")
|
||||
op.drop_index(op.f("ix_dataflow_pipeline_revisions_created_by"), table_name="dataflow_pipeline_revisions")
|
||||
op.drop_table("dataflow_pipeline_revisions")
|
||||
|
||||
op.drop_index(op.f("ix_dataflow_pipelines_updated_by"), table_name="dataflow_pipelines")
|
||||
op.drop_index("ix_dataflow_pipelines_tenant_updated", table_name="dataflow_pipelines")
|
||||
op.drop_index("ix_dataflow_pipelines_tenant_status", table_name="dataflow_pipelines")
|
||||
op.drop_index(op.f("ix_dataflow_pipelines_tenant_id"), table_name="dataflow_pipelines")
|
||||
op.drop_index(op.f("ix_dataflow_pipelines_status"), table_name="dataflow_pipelines")
|
||||
op.drop_index(op.f("ix_dataflow_pipelines_deleted_at"), table_name="dataflow_pipelines")
|
||||
op.drop_index(op.f("ix_dataflow_pipelines_created_by"), table_name="dataflow_pipelines")
|
||||
op.drop_table("dataflow_pipelines")
|
||||
264
src/govoplan_dataflow/backend/router.py
Normal file
264
src/govoplan_dataflow/backend/router.py
Normal file
@@ -0,0 +1,264 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.audit.logging import audit_event
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
|
||||
from govoplan_core.db.session import get_session
|
||||
from govoplan_dataflow.backend.manifest import ADMIN_SCOPE, READ_SCOPE, RUN_SCOPE, WRITE_SCOPE
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
PipelineCreateRequest,
|
||||
PipelineDeleteResponse,
|
||||
PipelineDraftRequest,
|
||||
PipelineListResponse,
|
||||
PipelinePreviewRequest,
|
||||
PipelinePreviewResponse,
|
||||
PipelineResponse,
|
||||
PipelineSqlResponse,
|
||||
PipelineUpdateRequest,
|
||||
PipelineValidationResponse,
|
||||
)
|
||||
from govoplan_dataflow.backend.service import (
|
||||
DataflowConflictError,
|
||||
DataflowError,
|
||||
DataflowNotFoundError,
|
||||
DataflowValidationError,
|
||||
compile_sql_draft,
|
||||
create_pipeline,
|
||||
delete_pipeline,
|
||||
get_pipeline,
|
||||
list_pipelines,
|
||||
pipeline_response,
|
||||
preview_pipeline,
|
||||
render_graph_sql,
|
||||
update_pipeline,
|
||||
validate_draft,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/dataflow", tags=["dataflow"])
|
||||
|
||||
|
||||
def _require_any_scope(principal: ApiPrincipal, *scopes: str) -> None:
|
||||
if any(has_scope(principal, scope) for scope in scopes):
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Missing one of the required scopes: {', '.join(scopes)}",
|
||||
)
|
||||
|
||||
|
||||
def _actor_id(principal: ApiPrincipal) -> str | None:
|
||||
return (
|
||||
principal.account_id
|
||||
or principal.membership_id
|
||||
or getattr(principal.user, "id", None)
|
||||
or principal.identity_id
|
||||
)
|
||||
|
||||
|
||||
def _http_error(exc: DataflowError) -> HTTPException:
|
||||
if isinstance(exc, DataflowNotFoundError):
|
||||
return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
|
||||
if isinstance(exc, DataflowConflictError):
|
||||
return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
|
||||
if isinstance(exc, DataflowValidationError):
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail={
|
||||
"message": str(exc),
|
||||
"diagnostics": [item.model_dump(mode="json") for item in exc.diagnostics],
|
||||
},
|
||||
)
|
||||
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
|
||||
|
||||
|
||||
@router.get("/pipelines", response_model=PipelineListResponse)
|
||||
def api_list_pipelines(
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineListResponse:
|
||||
_require_any_scope(principal, READ_SCOPE, ADMIN_SCOPE)
|
||||
pipelines = list_pipelines(session, tenant_id=principal.tenant_id)
|
||||
return PipelineListResponse(
|
||||
pipelines=[pipeline_response(session, pipeline) for pipeline in pipelines]
|
||||
)
|
||||
|
||||
|
||||
@router.post("/pipelines", response_model=PipelineResponse, status_code=status.HTTP_201_CREATED)
|
||||
def api_create_pipeline(
|
||||
payload: PipelineCreateRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineResponse:
|
||||
_require_any_scope(principal, WRITE_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
pipeline = create_pipeline(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
actor_id=_actor_id(principal),
|
||||
payload=payload,
|
||||
)
|
||||
except DataflowError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
user_id=getattr(principal.user, "id", None),
|
||||
api_key_id=principal.api_key_id,
|
||||
action="dataflow.pipeline.created",
|
||||
object_type="dataflow_pipeline",
|
||||
object_id=pipeline.id,
|
||||
details={"revision": pipeline.current_revision, "status": pipeline.status},
|
||||
)
|
||||
response = pipeline_response(session, pipeline)
|
||||
session.commit()
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/pipelines/{pipeline_id}", response_model=PipelineResponse)
|
||||
def api_get_pipeline(
|
||||
pipeline_id: str,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineResponse:
|
||||
_require_any_scope(principal, READ_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
pipeline = get_pipeline(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
pipeline_id=pipeline_id,
|
||||
)
|
||||
return pipeline_response(session, pipeline)
|
||||
except DataflowError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
|
||||
|
||||
@router.put("/pipelines/{pipeline_id}", response_model=PipelineResponse)
|
||||
def api_update_pipeline(
|
||||
pipeline_id: str,
|
||||
payload: PipelineUpdateRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineResponse:
|
||||
_require_any_scope(principal, WRITE_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
pipeline = update_pipeline(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
pipeline_id=pipeline_id,
|
||||
actor_id=_actor_id(principal),
|
||||
payload=payload,
|
||||
)
|
||||
except DataflowError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
user_id=getattr(principal.user, "id", None),
|
||||
api_key_id=principal.api_key_id,
|
||||
action="dataflow.pipeline.updated",
|
||||
object_type="dataflow_pipeline",
|
||||
object_id=pipeline.id,
|
||||
details={"revision": pipeline.current_revision, "status": pipeline.status},
|
||||
)
|
||||
response = pipeline_response(session, pipeline)
|
||||
session.commit()
|
||||
return response
|
||||
|
||||
|
||||
@router.delete("/pipelines/{pipeline_id}", response_model=PipelineDeleteResponse)
|
||||
def api_delete_pipeline(
|
||||
pipeline_id: str,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineDeleteResponse:
|
||||
_require_any_scope(principal, WRITE_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
pipeline = delete_pipeline(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
pipeline_id=pipeline_id,
|
||||
actor_id=_actor_id(principal),
|
||||
)
|
||||
except DataflowError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
user_id=getattr(principal.user, "id", None),
|
||||
api_key_id=principal.api_key_id,
|
||||
action="dataflow.pipeline.deleted",
|
||||
object_type="dataflow_pipeline",
|
||||
object_id=pipeline.id,
|
||||
details={"revision": pipeline.current_revision},
|
||||
)
|
||||
session.commit()
|
||||
return PipelineDeleteResponse(deleted=True, pipeline_id=pipeline.id)
|
||||
|
||||
|
||||
@router.post("/validate", response_model=PipelineValidationResponse)
|
||||
def api_validate_pipeline(
|
||||
payload: PipelineDraftRequest,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineValidationResponse:
|
||||
_require_any_scope(principal, READ_SCOPE, WRITE_SCOPE, RUN_SCOPE, ADMIN_SCOPE)
|
||||
return validate_draft(payload)
|
||||
|
||||
|
||||
@router.post("/sql/compile", response_model=PipelineSqlResponse)
|
||||
def api_compile_pipeline_sql(
|
||||
payload: PipelineDraftRequest,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineSqlResponse:
|
||||
_require_any_scope(principal, READ_SCOPE, WRITE_SCOPE, RUN_SCOPE, ADMIN_SCOPE)
|
||||
return compile_sql_draft(payload)
|
||||
|
||||
|
||||
@router.post("/sql/render", response_model=PipelineSqlResponse)
|
||||
def api_render_pipeline_sql(
|
||||
payload: PipelineDraftRequest,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelineSqlResponse:
|
||||
_require_any_scope(principal, READ_SCOPE, WRITE_SCOPE, RUN_SCOPE, ADMIN_SCOPE)
|
||||
return render_graph_sql(payload)
|
||||
|
||||
|
||||
@router.post("/preview", response_model=PipelinePreviewResponse)
|
||||
def api_preview_pipeline(
|
||||
payload: PipelinePreviewRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> PipelinePreviewResponse:
|
||||
_require_any_scope(principal, RUN_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
response = preview_pipeline(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
actor_id=_actor_id(principal),
|
||||
payload=payload,
|
||||
)
|
||||
except DataflowError as exc:
|
||||
raise _http_error(exc) from exc
|
||||
if response.pipeline_id:
|
||||
audit_event(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
user_id=getattr(principal.user, "id", None),
|
||||
api_key_id=principal.api_key_id,
|
||||
action="dataflow.pipeline.previewed",
|
||||
object_type="dataflow_pipeline",
|
||||
object_id=response.pipeline_id,
|
||||
details={
|
||||
"revision": response.revision,
|
||||
"run_id": response.run_id,
|
||||
"status": response.status,
|
||||
"output_row_count": response.total_rows,
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
return response
|
||||
|
||||
|
||||
__all__ = ["router"]
|
||||
161
src/govoplan_dataflow/backend/schemas.py
Normal file
161
src/govoplan_dataflow/backend/schemas.py
Normal file
@@ -0,0 +1,161 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
PipelineStatus = Literal["draft", "active", "archived"]
|
||||
EditorMode = Literal["graph", "sql"]
|
||||
DiagnosticSeverity = Literal["info", "warning", "error"]
|
||||
|
||||
|
||||
class GraphPosition(BaseModel):
|
||||
x: float
|
||||
y: float
|
||||
|
||||
@field_validator("x", "y")
|
||||
@classmethod
|
||||
def finite_coordinate(cls, value: float) -> float:
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("Graph coordinates must be finite")
|
||||
return value
|
||||
|
||||
|
||||
class GraphNode(BaseModel):
|
||||
id: str = Field(min_length=1, max_length=100, pattern=r"^[A-Za-z0-9_.:-]+$")
|
||||
type: str = Field(min_length=1, max_length=80)
|
||||
label: str = Field(min_length=1, max_length=200)
|
||||
position: GraphPosition
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class GraphEdge(BaseModel):
|
||||
id: str = Field(min_length=1, max_length=120, pattern=r"^[A-Za-z0-9_.:-]+$")
|
||||
source: str = Field(min_length=1, max_length=100)
|
||||
target: str = Field(min_length=1, max_length=100)
|
||||
source_port: str = Field(default="output", min_length=1, max_length=80)
|
||||
target_port: str = Field(default="input", min_length=1, max_length=80)
|
||||
|
||||
|
||||
class PipelineGraph(BaseModel):
|
||||
schema_version: Literal[1] = 1
|
||||
nodes: list[GraphNode] = Field(default_factory=list, max_length=100)
|
||||
edges: list[GraphEdge] = Field(default_factory=list, max_length=200)
|
||||
|
||||
|
||||
class DataflowDiagnostic(BaseModel):
|
||||
severity: DiagnosticSeverity
|
||||
code: str
|
||||
message: str
|
||||
node_id: str | None = None
|
||||
field: str | None = None
|
||||
|
||||
|
||||
class PipelineRevisionResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: str
|
||||
revision: int
|
||||
schema_version: int
|
||||
graph: PipelineGraph
|
||||
sql_text: str | None
|
||||
editor_mode: EditorMode
|
||||
content_hash: str
|
||||
created_by: str | None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class PipelineResponse(BaseModel):
|
||||
id: str
|
||||
tenant_id: str
|
||||
name: str
|
||||
description: str | None
|
||||
status: PipelineStatus
|
||||
current_revision: int
|
||||
created_by: str | None
|
||||
updated_by: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
revision: PipelineRevisionResponse
|
||||
|
||||
|
||||
class PipelineListResponse(BaseModel):
|
||||
pipelines: list[PipelineResponse]
|
||||
|
||||
|
||||
class PipelineCreateRequest(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=300)
|
||||
description: str | None = Field(default=None, max_length=4000)
|
||||
status: PipelineStatus = "draft"
|
||||
graph: PipelineGraph
|
||||
sql_text: str | None = Field(default=None, max_length=100_000)
|
||||
editor_mode: EditorMode = "graph"
|
||||
|
||||
|
||||
class PipelineUpdateRequest(PipelineCreateRequest):
|
||||
expected_revision: int = Field(ge=1)
|
||||
|
||||
|
||||
class PipelineDraftRequest(BaseModel):
|
||||
graph: PipelineGraph | None = None
|
||||
sql_text: str | None = Field(default=None, max_length=100_000)
|
||||
source_nodes: list[GraphNode] = Field(default_factory=list, max_length=20)
|
||||
|
||||
|
||||
class PipelineValidationResponse(BaseModel):
|
||||
valid: bool
|
||||
graph: PipelineGraph | None
|
||||
sql_text: str | None
|
||||
diagnostics: list[DataflowDiagnostic]
|
||||
|
||||
|
||||
class PipelineSqlResponse(PipelineValidationResponse):
|
||||
pass
|
||||
|
||||
|
||||
class PipelinePreviewRequest(BaseModel):
|
||||
pipeline_id: str | None = None
|
||||
revision: int | None = Field(default=None, ge=1)
|
||||
graph: PipelineGraph | None = None
|
||||
sql_text: str | None = Field(default=None, max_length=100_000)
|
||||
source_nodes: list[GraphNode] = Field(default_factory=list, max_length=20)
|
||||
row_limit: int = Field(default=100, ge=1, le=500)
|
||||
|
||||
|
||||
class PreviewColumn(BaseModel):
|
||||
name: str
|
||||
type: str
|
||||
nullable: bool = True
|
||||
|
||||
|
||||
class NodePreviewDiagnostic(BaseModel):
|
||||
node_id: str
|
||||
status: Literal["succeeded", "failed", "skipped"]
|
||||
input_rows: int = 0
|
||||
output_rows: int = 0
|
||||
duration_ms: float = 0
|
||||
columns: list[PreviewColumn] = Field(default_factory=list)
|
||||
messages: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PipelinePreviewResponse(BaseModel):
|
||||
run_id: str | None
|
||||
pipeline_id: str | None
|
||||
revision: int | None
|
||||
status: Literal["succeeded", "failed"]
|
||||
columns: list[PreviewColumn]
|
||||
rows: list[dict[str, Any]]
|
||||
total_rows: int
|
||||
truncated: bool
|
||||
diagnostics: list[DataflowDiagnostic]
|
||||
node_diagnostics: list[NodePreviewDiagnostic]
|
||||
definition_hash: str
|
||||
executor_version: str
|
||||
|
||||
|
||||
class PipelineDeleteResponse(BaseModel):
|
||||
deleted: bool
|
||||
pipeline_id: str
|
||||
511
src/govoplan_dataflow/backend/service.py
Normal file
511
src/govoplan_dataflow/backend/service.py
Normal file
@@ -0,0 +1,511 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.db.base import utcnow
|
||||
from govoplan_dataflow.backend.db.models import (
|
||||
DataflowPipeline,
|
||||
DataflowPipelineRevision,
|
||||
DataflowRun,
|
||||
)
|
||||
from govoplan_dataflow.backend.executor import (
|
||||
EXECUTOR_VERSION,
|
||||
PipelineExecutionError,
|
||||
execute_preview,
|
||||
)
|
||||
from govoplan_dataflow.backend.graph import canonical_graph_payload, definition_hash, validate_graph
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
DataflowDiagnostic,
|
||||
GraphNode,
|
||||
PipelineCreateRequest,
|
||||
PipelineDraftRequest,
|
||||
PipelineGraph,
|
||||
PipelinePreviewRequest,
|
||||
PipelinePreviewResponse,
|
||||
PipelineResponse,
|
||||
PipelineRevisionResponse,
|
||||
PipelineSqlResponse,
|
||||
PipelineUpdateRequest,
|
||||
PipelineValidationResponse,
|
||||
)
|
||||
from govoplan_dataflow.backend.sql_compiler import (
|
||||
SqlCompilationError,
|
||||
compile_sql,
|
||||
render_sql,
|
||||
)
|
||||
|
||||
|
||||
class DataflowError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class DataflowNotFoundError(DataflowError):
|
||||
pass
|
||||
|
||||
|
||||
class DataflowConflictError(DataflowError):
|
||||
pass
|
||||
|
||||
|
||||
class DataflowValidationError(DataflowError):
|
||||
def __init__(self, diagnostics: list[DataflowDiagnostic]) -> None:
|
||||
super().__init__(diagnostics[0].message if diagnostics else "Pipeline validation failed")
|
||||
self.diagnostics = diagnostics
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NormalizedDefinition:
|
||||
graph: PipelineGraph
|
||||
sql_text: str | None
|
||||
diagnostics: list[DataflowDiagnostic]
|
||||
|
||||
|
||||
def list_pipelines(session: Session, *, tenant_id: str) -> list[DataflowPipeline]:
|
||||
return list(
|
||||
session.scalars(
|
||||
select(DataflowPipeline)
|
||||
.where(
|
||||
DataflowPipeline.tenant_id == tenant_id,
|
||||
DataflowPipeline.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(DataflowPipeline.updated_at.desc(), DataflowPipeline.name)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_pipeline(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
pipeline_id: str,
|
||||
) -> DataflowPipeline:
|
||||
pipeline = session.scalar(
|
||||
select(DataflowPipeline).where(
|
||||
DataflowPipeline.id == pipeline_id,
|
||||
DataflowPipeline.tenant_id == tenant_id,
|
||||
DataflowPipeline.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
if pipeline is None:
|
||||
raise DataflowNotFoundError("Dataflow pipeline not found")
|
||||
return pipeline
|
||||
|
||||
|
||||
def get_pipeline_revision(
|
||||
session: Session,
|
||||
*,
|
||||
pipeline: DataflowPipeline,
|
||||
revision: int | None = None,
|
||||
) -> DataflowPipelineRevision:
|
||||
revision_number = revision or pipeline.current_revision
|
||||
item = session.scalar(
|
||||
select(DataflowPipelineRevision).where(
|
||||
DataflowPipelineRevision.pipeline_id == pipeline.id,
|
||||
DataflowPipelineRevision.tenant_id == pipeline.tenant_id,
|
||||
DataflowPipelineRevision.revision == revision_number,
|
||||
)
|
||||
)
|
||||
if item is None:
|
||||
raise DataflowNotFoundError("Dataflow pipeline revision not found")
|
||||
return item
|
||||
|
||||
|
||||
def create_pipeline(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
actor_id: str | None,
|
||||
payload: PipelineCreateRequest,
|
||||
) -> DataflowPipeline:
|
||||
definition = normalize_definition(
|
||||
graph=payload.graph,
|
||||
sql_text=payload.sql_text,
|
||||
editor_mode=payload.editor_mode,
|
||||
)
|
||||
content_hash = definition_hash(definition.graph, definition.sql_text)
|
||||
pipeline = DataflowPipeline(
|
||||
tenant_id=tenant_id,
|
||||
name=payload.name.strip(),
|
||||
description=_clean_optional(payload.description),
|
||||
status=payload.status,
|
||||
current_revision=1,
|
||||
created_by=actor_id,
|
||||
updated_by=actor_id,
|
||||
metadata_={},
|
||||
)
|
||||
revision = DataflowPipelineRevision(
|
||||
tenant_id=tenant_id,
|
||||
revision=1,
|
||||
schema_version=definition.graph.schema_version,
|
||||
graph=canonical_graph_payload(definition.graph),
|
||||
sql_text=definition.sql_text,
|
||||
editor_mode=payload.editor_mode,
|
||||
content_hash=content_hash,
|
||||
created_by=actor_id,
|
||||
)
|
||||
pipeline.revisions.append(revision)
|
||||
session.add(pipeline)
|
||||
session.flush()
|
||||
return pipeline
|
||||
|
||||
|
||||
def update_pipeline(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
pipeline_id: str,
|
||||
actor_id: str | None,
|
||||
payload: PipelineUpdateRequest,
|
||||
) -> DataflowPipeline:
|
||||
pipeline = get_pipeline(session, tenant_id=tenant_id, pipeline_id=pipeline_id)
|
||||
if payload.expected_revision != pipeline.current_revision:
|
||||
raise DataflowConflictError(
|
||||
f"Pipeline changed on the server; expected revision {payload.expected_revision}, "
|
||||
f"current revision is {pipeline.current_revision}"
|
||||
)
|
||||
definition = normalize_definition(
|
||||
graph=payload.graph,
|
||||
sql_text=payload.sql_text,
|
||||
editor_mode=payload.editor_mode,
|
||||
)
|
||||
content_hash = definition_hash(definition.graph, definition.sql_text)
|
||||
current = get_pipeline_revision(session, pipeline=pipeline)
|
||||
pipeline.name = payload.name.strip()
|
||||
pipeline.description = _clean_optional(payload.description)
|
||||
pipeline.status = payload.status
|
||||
pipeline.updated_by = actor_id
|
||||
if current.content_hash != content_hash or current.editor_mode != payload.editor_mode:
|
||||
pipeline.current_revision += 1
|
||||
pipeline.revisions.append(
|
||||
DataflowPipelineRevision(
|
||||
tenant_id=tenant_id,
|
||||
revision=pipeline.current_revision,
|
||||
schema_version=definition.graph.schema_version,
|
||||
graph=canonical_graph_payload(definition.graph),
|
||||
sql_text=definition.sql_text,
|
||||
editor_mode=payload.editor_mode,
|
||||
content_hash=content_hash,
|
||||
created_by=actor_id,
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
return pipeline
|
||||
|
||||
|
||||
def delete_pipeline(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
pipeline_id: str,
|
||||
actor_id: str | None,
|
||||
) -> DataflowPipeline:
|
||||
pipeline = get_pipeline(session, tenant_id=tenant_id, pipeline_id=pipeline_id)
|
||||
pipeline.deleted_at = utcnow()
|
||||
pipeline.updated_by = actor_id
|
||||
session.flush()
|
||||
return pipeline
|
||||
|
||||
|
||||
def pipeline_response(session: Session, pipeline: DataflowPipeline) -> PipelineResponse:
|
||||
revision = get_pipeline_revision(session, pipeline=pipeline)
|
||||
return PipelineResponse(
|
||||
id=pipeline.id,
|
||||
tenant_id=pipeline.tenant_id,
|
||||
name=pipeline.name,
|
||||
description=pipeline.description,
|
||||
status=pipeline.status,
|
||||
current_revision=pipeline.current_revision,
|
||||
created_by=pipeline.created_by,
|
||||
updated_by=pipeline.updated_by,
|
||||
created_at=pipeline.created_at,
|
||||
updated_at=pipeline.updated_at,
|
||||
revision=PipelineRevisionResponse.model_validate(revision),
|
||||
)
|
||||
|
||||
|
||||
def validate_draft(payload: PipelineDraftRequest) -> PipelineValidationResponse:
|
||||
if payload.sql_text and payload.sql_text.strip():
|
||||
try:
|
||||
graph, sql_text, diagnostics = compile_sql(
|
||||
payload.sql_text,
|
||||
source_nodes=_source_nodes(payload.graph, payload.source_nodes),
|
||||
)
|
||||
except SqlCompilationError as exc:
|
||||
return PipelineValidationResponse(
|
||||
valid=False,
|
||||
graph=payload.graph,
|
||||
sql_text=payload.sql_text,
|
||||
diagnostics=exc.diagnostics,
|
||||
)
|
||||
return PipelineValidationResponse(
|
||||
valid=True,
|
||||
graph=graph,
|
||||
sql_text=sql_text,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
if payload.graph is None:
|
||||
diagnostic = DataflowDiagnostic(
|
||||
severity="error",
|
||||
code="definition.required",
|
||||
message="Provide a graph or SQL query.",
|
||||
)
|
||||
return PipelineValidationResponse(
|
||||
valid=False,
|
||||
graph=None,
|
||||
sql_text=None,
|
||||
diagnostics=[diagnostic],
|
||||
)
|
||||
diagnostics = validate_graph(payload.graph)
|
||||
sql_text: str | None = None
|
||||
if not any(item.severity == "error" for item in diagnostics):
|
||||
try:
|
||||
sql_text, render_diagnostics = render_sql(payload.graph)
|
||||
diagnostics.extend(render_diagnostics)
|
||||
except SqlCompilationError as exc:
|
||||
diagnostics.extend(
|
||||
DataflowDiagnostic(
|
||||
severity="warning",
|
||||
code=item.code,
|
||||
message=item.message,
|
||||
node_id=item.node_id,
|
||||
field=item.field,
|
||||
)
|
||||
for item in exc.diagnostics
|
||||
)
|
||||
return PipelineValidationResponse(
|
||||
valid=not any(item.severity == "error" for item in diagnostics),
|
||||
graph=payload.graph,
|
||||
sql_text=sql_text,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
|
||||
|
||||
def compile_sql_draft(payload: PipelineDraftRequest) -> PipelineSqlResponse:
|
||||
if not payload.sql_text:
|
||||
diagnostic = DataflowDiagnostic(
|
||||
severity="error",
|
||||
code="sql.empty",
|
||||
message="Enter a SELECT query.",
|
||||
field="sql_text",
|
||||
)
|
||||
return PipelineSqlResponse(valid=False, graph=payload.graph, sql_text="", diagnostics=[diagnostic])
|
||||
try:
|
||||
graph, sql_text, diagnostics = compile_sql(
|
||||
payload.sql_text,
|
||||
source_nodes=_source_nodes(payload.graph, payload.source_nodes),
|
||||
)
|
||||
except SqlCompilationError as exc:
|
||||
return PipelineSqlResponse(
|
||||
valid=False,
|
||||
graph=payload.graph,
|
||||
sql_text=payload.sql_text,
|
||||
diagnostics=exc.diagnostics,
|
||||
)
|
||||
return PipelineSqlResponse(valid=True, graph=graph, sql_text=sql_text, diagnostics=diagnostics)
|
||||
|
||||
|
||||
def render_graph_sql(payload: PipelineDraftRequest) -> PipelineSqlResponse:
|
||||
if payload.graph is None:
|
||||
diagnostic = DataflowDiagnostic(
|
||||
severity="error",
|
||||
code="graph.required",
|
||||
message="Provide a graph to render.",
|
||||
)
|
||||
return PipelineSqlResponse(valid=False, graph=None, sql_text=None, diagnostics=[diagnostic])
|
||||
try:
|
||||
sql_text, diagnostics = render_sql(payload.graph)
|
||||
except SqlCompilationError as exc:
|
||||
return PipelineSqlResponse(
|
||||
valid=False,
|
||||
graph=payload.graph,
|
||||
sql_text=None,
|
||||
diagnostics=exc.diagnostics,
|
||||
)
|
||||
return PipelineSqlResponse(valid=True, graph=payload.graph, sql_text=sql_text, diagnostics=diagnostics)
|
||||
|
||||
|
||||
def preview_pipeline(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
actor_id: str | None,
|
||||
payload: PipelinePreviewRequest,
|
||||
) -> PipelinePreviewResponse:
|
||||
pipeline: DataflowPipeline | None = None
|
||||
revision: DataflowPipelineRevision | None = None
|
||||
if payload.pipeline_id:
|
||||
pipeline = get_pipeline(session, tenant_id=tenant_id, pipeline_id=payload.pipeline_id)
|
||||
revision = get_pipeline_revision(session, pipeline=pipeline, revision=payload.revision)
|
||||
graph = PipelineGraph.model_validate(revision.graph)
|
||||
sql_text = revision.sql_text
|
||||
else:
|
||||
draft = PipelineDraftRequest(
|
||||
graph=payload.graph,
|
||||
sql_text=payload.sql_text,
|
||||
source_nodes=payload.source_nodes,
|
||||
)
|
||||
validated = validate_draft(draft)
|
||||
if not validated.valid or validated.graph is None:
|
||||
return PipelinePreviewResponse(
|
||||
run_id=None,
|
||||
pipeline_id=None,
|
||||
revision=None,
|
||||
status="failed",
|
||||
columns=[],
|
||||
rows=[],
|
||||
total_rows=0,
|
||||
truncated=False,
|
||||
diagnostics=validated.diagnostics,
|
||||
node_diagnostics=[],
|
||||
definition_hash="",
|
||||
executor_version=EXECUTOR_VERSION,
|
||||
)
|
||||
graph = validated.graph
|
||||
sql_text = validated.sql_text
|
||||
|
||||
graph_hash = definition_hash(graph, sql_text)
|
||||
started_at = utcnow()
|
||||
run: DataflowRun | None = None
|
||||
try:
|
||||
result = execute_preview(graph, row_limit=payload.row_limit)
|
||||
status = "succeeded"
|
||||
error = None
|
||||
diagnostics = result.diagnostics
|
||||
columns = result.columns
|
||||
rows = result.rows
|
||||
total_rows = result.total_rows
|
||||
truncated = result.truncated
|
||||
node_diagnostics = result.node_diagnostics
|
||||
source_fingerprints = result.source_fingerprints
|
||||
input_row_count = result.input_row_count
|
||||
except PipelineExecutionError as exc:
|
||||
status = "failed"
|
||||
error = str(exc)
|
||||
diagnostics = [
|
||||
DataflowDiagnostic(
|
||||
severity="error",
|
||||
code="preview.execution",
|
||||
message=str(exc),
|
||||
node_id=exc.node_id,
|
||||
)
|
||||
]
|
||||
columns = []
|
||||
rows = []
|
||||
total_rows = 0
|
||||
truncated = False
|
||||
node_diagnostics = []
|
||||
source_fingerprints = []
|
||||
input_row_count = 0
|
||||
|
||||
if pipeline is not None and revision is not None:
|
||||
run = DataflowRun(
|
||||
tenant_id=tenant_id,
|
||||
pipeline_id=pipeline.id,
|
||||
pipeline_revision_id=revision.id,
|
||||
run_type="preview",
|
||||
status=status,
|
||||
executor_version=EXECUTOR_VERSION,
|
||||
definition_hash=graph_hash,
|
||||
source_fingerprints=source_fingerprints,
|
||||
result_schema=[item.model_dump(mode="json") for item in columns],
|
||||
diagnostics=[item.model_dump(mode="json") for item in diagnostics],
|
||||
input_row_count=input_row_count,
|
||||
output_row_count=total_rows,
|
||||
started_at=started_at,
|
||||
finished_at=utcnow(),
|
||||
error=error,
|
||||
created_by=actor_id,
|
||||
)
|
||||
session.add(run)
|
||||
session.flush()
|
||||
|
||||
return PipelinePreviewResponse(
|
||||
run_id=run.id if run else None,
|
||||
pipeline_id=pipeline.id if pipeline else None,
|
||||
revision=revision.revision if revision else None,
|
||||
status=status,
|
||||
columns=columns,
|
||||
rows=rows,
|
||||
total_rows=total_rows,
|
||||
truncated=truncated,
|
||||
diagnostics=diagnostics,
|
||||
node_diagnostics=node_diagnostics,
|
||||
definition_hash=graph_hash,
|
||||
executor_version=EXECUTOR_VERSION,
|
||||
)
|
||||
|
||||
|
||||
def normalize_definition(
|
||||
*,
|
||||
graph: PipelineGraph,
|
||||
sql_text: str | None,
|
||||
editor_mode: str,
|
||||
) -> NormalizedDefinition:
|
||||
if editor_mode == "sql":
|
||||
try:
|
||||
compiled_graph, normalized_sql, diagnostics = compile_sql(
|
||||
sql_text or "",
|
||||
source_nodes=_source_nodes(graph, ()),
|
||||
)
|
||||
except SqlCompilationError as exc:
|
||||
raise DataflowValidationError(exc.diagnostics) from exc
|
||||
return NormalizedDefinition(
|
||||
graph=compiled_graph,
|
||||
sql_text=normalized_sql,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
diagnostics = validate_graph(graph)
|
||||
errors = [item for item in diagnostics if item.severity == "error"]
|
||||
if errors:
|
||||
raise DataflowValidationError(diagnostics)
|
||||
try:
|
||||
rendered_sql, render_diagnostics = render_sql(graph)
|
||||
diagnostics.extend(render_diagnostics)
|
||||
except SqlCompilationError:
|
||||
rendered_sql = None
|
||||
return NormalizedDefinition(graph=graph, sql_text=rendered_sql, diagnostics=diagnostics)
|
||||
|
||||
|
||||
def _source_nodes(
|
||||
graph: PipelineGraph | None,
|
||||
explicit_nodes: list[GraphNode] | tuple[()],
|
||||
) -> list[GraphNode]:
|
||||
nodes = list(explicit_nodes)
|
||||
if graph is not None:
|
||||
known = {node.id for node in nodes}
|
||||
nodes.extend(
|
||||
node
|
||||
for node in graph.nodes
|
||||
if node.type.startswith("source.") and node.id not in known
|
||||
)
|
||||
return nodes
|
||||
|
||||
|
||||
def _clean_optional(value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
cleaned = value.strip()
|
||||
return cleaned or None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DataflowConflictError",
|
||||
"DataflowError",
|
||||
"DataflowNotFoundError",
|
||||
"DataflowValidationError",
|
||||
"compile_sql_draft",
|
||||
"create_pipeline",
|
||||
"delete_pipeline",
|
||||
"get_pipeline",
|
||||
"get_pipeline_revision",
|
||||
"list_pipelines",
|
||||
"normalize_definition",
|
||||
"pipeline_response",
|
||||
"preview_pipeline",
|
||||
"render_graph_sql",
|
||||
"update_pipeline",
|
||||
"validate_draft",
|
||||
]
|
||||
483
src/govoplan_dataflow/backend/sql_compiler.py
Normal file
483
src/govoplan_dataflow/backend/sql_compiler.py
Normal file
@@ -0,0 +1,483 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterable
|
||||
|
||||
import sqlglot
|
||||
from sqlglot import exp
|
||||
from sqlglot.errors import ParseError
|
||||
|
||||
from govoplan_dataflow.backend.graph import topological_order, validate_graph
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
DataflowDiagnostic,
|
||||
GraphEdge,
|
||||
GraphNode,
|
||||
GraphPosition,
|
||||
PipelineGraph,
|
||||
)
|
||||
|
||||
|
||||
class SqlCompilationError(ValueError):
|
||||
def __init__(self, diagnostics: list[DataflowDiagnostic]) -> None:
|
||||
super().__init__(diagnostics[0].message if diagnostics else "SQL compilation failed")
|
||||
self.diagnostics = diagnostics
|
||||
|
||||
|
||||
def compile_sql(
|
||||
sql_text: str,
|
||||
*,
|
||||
source_nodes: Iterable[GraphNode] = (),
|
||||
) -> tuple[PipelineGraph, str, list[DataflowDiagnostic]]:
|
||||
source_text = sql_text.strip()
|
||||
if not source_text:
|
||||
raise SqlCompilationError([_sql_error("sql.empty", "Enter a SELECT query.")])
|
||||
try:
|
||||
statements = sqlglot.parse(source_text, read="duckdb")
|
||||
except ParseError as exc:
|
||||
detail = exc.errors[0] if exc.errors else {}
|
||||
line = detail.get("line")
|
||||
column = detail.get("col")
|
||||
location = f" at line {line}, column {column}" if line and column else ""
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.parse", f"SQL could not be parsed{location}: {detail.get('description') or exc}")]
|
||||
) from exc
|
||||
if len(statements) != 1 or not isinstance(statements[0], exp.Select):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.select_only", "Dataflow SQL accepts exactly one SELECT statement.")]
|
||||
)
|
||||
query = statements[0]
|
||||
_reject_unsupported_query_shape(query)
|
||||
|
||||
tables = list(query.find_all(exp.Table))
|
||||
if len(tables) != 1:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.source_count", "The first release supports exactly one logical source.")]
|
||||
)
|
||||
table = tables[0]
|
||||
if table.catalog or table.db:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.qualified_source", "Use the logical source name without a catalog or schema.")]
|
||||
)
|
||||
source_name = table.name
|
||||
preserved_source = next(
|
||||
(
|
||||
node.model_copy(deep=True)
|
||||
for node in source_nodes
|
||||
if node.type.startswith("source.")
|
||||
and str(node.config.get("source_name", "")).casefold() == source_name.casefold()
|
||||
),
|
||||
None,
|
||||
)
|
||||
source_node = preserved_source or GraphNode(
|
||||
id="source",
|
||||
type="source.reference",
|
||||
label=source_name,
|
||||
position=GraphPosition(x=80, y=180),
|
||||
config={"source_name": source_name},
|
||||
)
|
||||
|
||||
nodes = [source_node]
|
||||
conditions = _flatten_and(query.args.get("where").this) if query.args.get("where") else []
|
||||
for index, condition in enumerate(conditions, start=1):
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id=f"filter-{index}",
|
||||
type="filter",
|
||||
label=f"Filter {index}",
|
||||
position=_position(len(nodes)),
|
||||
config=_condition_config(condition),
|
||||
)
|
||||
)
|
||||
|
||||
group = query.args.get("group")
|
||||
group_by = [_column_name(item, context="GROUP BY") for item in group.expressions] if group else []
|
||||
aggregate_specs: list[dict[str, Any]] = []
|
||||
projection_fields: list[dict[str, str]] = []
|
||||
saw_star = False
|
||||
saw_aggregate = False
|
||||
for item in query.expressions:
|
||||
inner = item.this if isinstance(item, exp.Alias) else item
|
||||
alias = item.alias if isinstance(item, exp.Alias) else ""
|
||||
aggregate = _aggregate_config(inner, alias=alias)
|
||||
if aggregate is not None:
|
||||
saw_aggregate = True
|
||||
aggregate_specs.append(aggregate)
|
||||
continue
|
||||
if isinstance(inner, exp.Star):
|
||||
saw_star = True
|
||||
continue
|
||||
if not isinstance(inner, exp.Column):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.select_expression", "SELECT supports columns and COUNT/SUM/AVG/MIN/MAX only.")]
|
||||
)
|
||||
column = _column_name(inner, context="SELECT")
|
||||
projection_fields.append({"column": column, "alias": alias or column})
|
||||
|
||||
if saw_star and len(query.expressions) != 1:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.star_mix", "SELECT * cannot be mixed with other expressions in this dialect.")]
|
||||
)
|
||||
if saw_aggregate or group_by:
|
||||
if saw_star:
|
||||
raise SqlCompilationError([_sql_error("sql.aggregate_star", "SELECT * cannot be grouped.")])
|
||||
plain_columns = [field["column"] for field in projection_fields]
|
||||
if any(column not in group_by for column in plain_columns):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.grouping", "Every non-aggregate SELECT column must appear in GROUP BY.")]
|
||||
)
|
||||
if any(field["alias"] != field["column"] for field in projection_fields):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.group_alias", "Aliases for GROUP BY columns are not supported yet.")]
|
||||
)
|
||||
if not aggregate_specs:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.aggregate_required", "GROUP BY requires at least one aggregate in this dialect.")]
|
||||
)
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id="aggregate",
|
||||
type="aggregate",
|
||||
label="Aggregate",
|
||||
position=_position(len(nodes)),
|
||||
config={"group_by": group_by, "aggregates": aggregate_specs},
|
||||
)
|
||||
)
|
||||
elif not saw_star:
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id="select",
|
||||
type="select",
|
||||
label="Select columns",
|
||||
position=_position(len(nodes)),
|
||||
config={"fields": projection_fields},
|
||||
)
|
||||
)
|
||||
|
||||
order = query.args.get("order")
|
||||
if order:
|
||||
fields: list[dict[str, str]] = []
|
||||
for item in order.expressions:
|
||||
if not isinstance(item, exp.Ordered):
|
||||
raise SqlCompilationError([_sql_error("sql.order", "Unsupported ORDER BY expression.")])
|
||||
fields.append(
|
||||
{
|
||||
"column": _column_name(item.this, context="ORDER BY"),
|
||||
"direction": "desc" if item.args.get("desc") else "asc",
|
||||
}
|
||||
)
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id="sort",
|
||||
type="sort",
|
||||
label="Sort",
|
||||
position=_position(len(nodes)),
|
||||
config={"fields": fields},
|
||||
)
|
||||
)
|
||||
|
||||
limit = query.args.get("limit")
|
||||
if limit:
|
||||
expression = limit.args.get("expression")
|
||||
if not isinstance(expression, exp.Literal) or expression.is_string:
|
||||
raise SqlCompilationError([_sql_error("sql.limit", "LIMIT must be a positive integer.")])
|
||||
try:
|
||||
count = int(expression.this)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise SqlCompilationError([_sql_error("sql.limit", "LIMIT must be a positive integer.")]) from exc
|
||||
if not 1 <= count <= 100_000:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.limit_range", "LIMIT must be between 1 and 100,000.")]
|
||||
)
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id="limit",
|
||||
type="limit",
|
||||
label="Limit",
|
||||
position=_position(len(nodes)),
|
||||
config={"count": count},
|
||||
)
|
||||
)
|
||||
|
||||
nodes.append(
|
||||
GraphNode(
|
||||
id="output",
|
||||
type="output",
|
||||
label="Preview output",
|
||||
position=_position(len(nodes)),
|
||||
config={},
|
||||
)
|
||||
)
|
||||
edges = [
|
||||
GraphEdge(
|
||||
id=f"edge-{source.id}-{target.id}",
|
||||
source=source.id,
|
||||
target=target.id,
|
||||
)
|
||||
for source, target in zip(nodes, nodes[1:])
|
||||
]
|
||||
graph = PipelineGraph(nodes=nodes, edges=edges)
|
||||
diagnostics = validate_graph(graph)
|
||||
if any(item.severity == "error" for item in diagnostics):
|
||||
raise SqlCompilationError(diagnostics)
|
||||
return graph, query.sql(dialect="duckdb", pretty=True), diagnostics
|
||||
|
||||
|
||||
def render_sql(graph: PipelineGraph) -> tuple[str, list[DataflowDiagnostic]]:
|
||||
diagnostics = validate_graph(graph)
|
||||
if any(item.severity == "error" for item in diagnostics):
|
||||
raise SqlCompilationError(diagnostics)
|
||||
ordered, cyclic = topological_order(graph)
|
||||
if cyclic:
|
||||
raise SqlCompilationError([_sql_error("graph.cycle", "A cyclic graph cannot be rendered as SQL.")])
|
||||
node_by_id = {node.id: node for node in graph.nodes}
|
||||
source = node_by_id[ordered[0]]
|
||||
source_name = str(source.config.get("source_name", "")).strip()
|
||||
if not source_name:
|
||||
raise SqlCompilationError([_sql_error("source.name_required", "The source needs a logical SQL name.")])
|
||||
|
||||
where_conditions: list[exp.Expression] = []
|
||||
select_expressions: list[exp.Expression] = [exp.Star()]
|
||||
group_by: list[exp.Expression] = []
|
||||
order_by: list[exp.Expression] = []
|
||||
limit: int | None = None
|
||||
selected = False
|
||||
|
||||
for node_id in ordered[1:]:
|
||||
node = node_by_id[node_id]
|
||||
if node.type == "filter":
|
||||
if selected:
|
||||
raise SqlCompilationError(
|
||||
[_node_sql_error(node.id, "sql.filter_order", "Filters after projection or aggregation are not representable yet.")]
|
||||
)
|
||||
where_conditions.append(_condition_expression(node.config))
|
||||
elif node.type == "select":
|
||||
if selected:
|
||||
raise SqlCompilationError(
|
||||
[_node_sql_error(node.id, "sql.multiple_select", "Only one select or aggregate transform is supported.")]
|
||||
)
|
||||
select_expressions = []
|
||||
for field in node.config["fields"]:
|
||||
column = field if isinstance(field, str) else str(field["column"])
|
||||
alias = column if isinstance(field, str) else str(field.get("alias") or column)
|
||||
expression: exp.Expression = exp.column(column)
|
||||
if alias != column:
|
||||
expression = expression.as_(alias)
|
||||
select_expressions.append(expression)
|
||||
selected = True
|
||||
elif node.type == "aggregate":
|
||||
if selected:
|
||||
raise SqlCompilationError(
|
||||
[_node_sql_error(node.id, "sql.multiple_select", "Only one select or aggregate transform is supported.")]
|
||||
)
|
||||
select_expressions = [exp.column(column) for column in node.config.get("group_by", [])]
|
||||
group_by = [exp.column(column) for column in node.config.get("group_by", [])]
|
||||
for aggregate in node.config["aggregates"]:
|
||||
function = str(aggregate["function"])
|
||||
column = aggregate.get("column")
|
||||
argument: exp.Expression = exp.Star() if function == "count" and column in (None, "", "*") else exp.column(str(column))
|
||||
aggregate_expression = _aggregate_expression(function, argument)
|
||||
select_expressions.append(aggregate_expression.as_(str(aggregate["alias"])))
|
||||
selected = True
|
||||
elif node.type == "sort":
|
||||
order_by = [
|
||||
exp.Ordered(
|
||||
this=exp.column(str(field["column"])),
|
||||
desc=field.get("direction", "asc") == "desc",
|
||||
nulls_first=False,
|
||||
)
|
||||
for field in node.config["fields"]
|
||||
]
|
||||
elif node.type == "limit":
|
||||
limit = int(node.config["count"])
|
||||
elif node.type != "output":
|
||||
raise SqlCompilationError(
|
||||
[_node_sql_error(node.id, "sql.node_not_representable", f"{node.type!r} cannot be rendered as SQL.")]
|
||||
)
|
||||
|
||||
query = exp.select(*select_expressions).from_(exp.to_table(source_name))
|
||||
if where_conditions:
|
||||
query = query.where(_combine_and(where_conditions))
|
||||
if group_by:
|
||||
query = query.group_by(*group_by)
|
||||
if order_by:
|
||||
query = query.order_by(*order_by)
|
||||
if limit is not None:
|
||||
query = query.limit(limit)
|
||||
return query.sql(dialect="duckdb", pretty=True), diagnostics
|
||||
|
||||
|
||||
def _reject_unsupported_query_shape(query: exp.Select) -> None:
|
||||
unsupported_args = {
|
||||
"with_": "WITH queries",
|
||||
"distinct": "DISTINCT",
|
||||
"having": "HAVING",
|
||||
"qualify": "QUALIFY",
|
||||
"offset": "OFFSET",
|
||||
"windows": "window definitions",
|
||||
"locks": "locking clauses",
|
||||
}
|
||||
for key, label in unsupported_args.items():
|
||||
if query.args.get(key):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.unsupported_clause", f"{label} are not supported by the first Dataflow dialect.")]
|
||||
)
|
||||
if any(True for _ in query.find_all(exp.Join)):
|
||||
raise SqlCompilationError([_sql_error("sql.join", "JOIN support belongs to the comparison/reconciliation slice.")])
|
||||
if any(True for _ in query.find_all(exp.Subquery)):
|
||||
raise SqlCompilationError([_sql_error("sql.subquery", "Subqueries are not supported by the first Dataflow dialect.")])
|
||||
|
||||
|
||||
def _flatten_and(expression: exp.Expression) -> list[exp.Expression]:
|
||||
if isinstance(expression, exp.And):
|
||||
return [*_flatten_and(expression.this), *_flatten_and(expression.expression)]
|
||||
if isinstance(expression, exp.Or):
|
||||
raise SqlCompilationError([_sql_error("sql.or", "OR conditions are not supported yet; use separate pipelines.")])
|
||||
return [expression]
|
||||
|
||||
|
||||
def _condition_config(expression: exp.Expression) -> dict[str, Any]:
|
||||
if isinstance(expression, exp.Not) and isinstance(expression.this, exp.Is):
|
||||
inner = expression.this
|
||||
if isinstance(inner.this, exp.Column) and isinstance(inner.expression, exp.Null):
|
||||
return {"column": _column_name(inner.this, context="WHERE"), "operator": "not_null"}
|
||||
if isinstance(expression, exp.Is):
|
||||
if isinstance(expression.this, exp.Column) and isinstance(expression.expression, exp.Null):
|
||||
return {"column": _column_name(expression.this, context="WHERE"), "operator": "is_null"}
|
||||
mapping: tuple[tuple[type[exp.Expression], str], ...] = (
|
||||
(exp.EQ, "eq"),
|
||||
(exp.NEQ, "ne"),
|
||||
(exp.GT, "gt"),
|
||||
(exp.GTE, "gte"),
|
||||
(exp.LT, "lt"),
|
||||
(exp.LTE, "lte"),
|
||||
)
|
||||
for expression_type, operator in mapping:
|
||||
if isinstance(expression, expression_type):
|
||||
if not isinstance(expression.this, exp.Column):
|
||||
break
|
||||
return {
|
||||
"column": _column_name(expression.this, context="WHERE"),
|
||||
"operator": operator,
|
||||
"value": _literal_value(expression.expression),
|
||||
}
|
||||
if isinstance(expression, exp.Like) and isinstance(expression.this, exp.Column):
|
||||
value = _literal_value(expression.expression)
|
||||
if not isinstance(value, str) or not (value.startswith("%") and value.endswith("%")):
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.like", "LIKE is supported only as a contains pattern: LIKE '%value%'.")]
|
||||
)
|
||||
return {
|
||||
"column": _column_name(expression.this, context="WHERE"),
|
||||
"operator": "contains",
|
||||
"value": value[1:-1],
|
||||
}
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.condition", "WHERE supports simple column comparisons joined with AND.")]
|
||||
)
|
||||
|
||||
|
||||
def _condition_expression(config: dict[str, Any]) -> exp.Expression:
|
||||
column = exp.column(str(config["column"]))
|
||||
operator = str(config["operator"])
|
||||
if operator == "is_null":
|
||||
return exp.Is(this=column, expression=exp.Null())
|
||||
if operator == "not_null":
|
||||
return exp.Not(this=exp.Is(this=column, expression=exp.Null()))
|
||||
value = exp.convert(config.get("value"))
|
||||
mapping: dict[str, type[exp.Expression]] = {
|
||||
"eq": exp.EQ,
|
||||
"ne": exp.NEQ,
|
||||
"gt": exp.GT,
|
||||
"gte": exp.GTE,
|
||||
"lt": exp.LT,
|
||||
"lte": exp.LTE,
|
||||
}
|
||||
if operator in mapping:
|
||||
return mapping[operator](this=column, expression=value)
|
||||
if operator == "contains":
|
||||
return exp.Like(this=column, expression=exp.Literal.string(f"%{config.get('value', '')}%"))
|
||||
raise SqlCompilationError([_sql_error("filter.operator", f"Unsupported filter operator {operator!r}.")])
|
||||
|
||||
|
||||
def _literal_value(expression: exp.Expression) -> Any:
|
||||
if isinstance(expression, exp.Null):
|
||||
return None
|
||||
if isinstance(expression, exp.Boolean):
|
||||
return bool(expression.this)
|
||||
if not isinstance(expression, exp.Literal):
|
||||
raise SqlCompilationError([_sql_error("sql.literal", "Comparisons require a literal value.")])
|
||||
if expression.is_string:
|
||||
return str(expression.this)
|
||||
text = str(expression.this)
|
||||
try:
|
||||
return int(text)
|
||||
except ValueError:
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError as exc:
|
||||
raise SqlCompilationError([_sql_error("sql.literal", f"Unsupported literal {text!r}.")]) from exc
|
||||
|
||||
|
||||
def _aggregate_config(expression: exp.Expression, *, alias: str) -> dict[str, Any] | None:
|
||||
mapping: tuple[tuple[type[exp.Expression], str], ...] = (
|
||||
(exp.Count, "count"),
|
||||
(exp.Sum, "sum"),
|
||||
(exp.Avg, "avg"),
|
||||
(exp.Min, "min"),
|
||||
(exp.Max, "max"),
|
||||
)
|
||||
for expression_type, function in mapping:
|
||||
if not isinstance(expression, expression_type):
|
||||
continue
|
||||
argument = expression.this
|
||||
if isinstance(argument, exp.Star):
|
||||
column = "*"
|
||||
elif isinstance(argument, exp.Column):
|
||||
column = _column_name(argument, context=function.upper())
|
||||
else:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.aggregate_argument", f"{function.upper()} requires a column or * argument.")]
|
||||
)
|
||||
output_alias = alias or (f"{function}_all" if column == "*" else f"{function}_{column}")
|
||||
return {"function": function, "column": column, "alias": output_alias}
|
||||
return None
|
||||
|
||||
|
||||
def _aggregate_expression(function: str, argument: exp.Expression) -> exp.Expression:
|
||||
mapping: dict[str, type[exp.Expression]] = {
|
||||
"count": exp.Count,
|
||||
"sum": exp.Sum,
|
||||
"avg": exp.Avg,
|
||||
"min": exp.Min,
|
||||
"max": exp.Max,
|
||||
}
|
||||
return mapping[function](this=argument)
|
||||
|
||||
|
||||
def _column_name(expression: exp.Expression, *, context: str) -> str:
|
||||
if not isinstance(expression, exp.Column) or expression.table:
|
||||
raise SqlCompilationError(
|
||||
[_sql_error("sql.column", f"{context} accepts unqualified column names only.")]
|
||||
)
|
||||
return expression.name
|
||||
|
||||
|
||||
def _position(index: int) -> GraphPosition:
|
||||
return GraphPosition(x=80 + index * 220, y=180)
|
||||
|
||||
|
||||
def _combine_and(expressions: list[exp.Expression]) -> exp.Expression:
|
||||
combined = expressions[0]
|
||||
for expression in expressions[1:]:
|
||||
combined = exp.And(this=combined, expression=expression)
|
||||
return combined
|
||||
|
||||
|
||||
def _sql_error(code: str, message: str) -> DataflowDiagnostic:
|
||||
return DataflowDiagnostic(severity="error", code=code, message=message, field="sql_text")
|
||||
|
||||
|
||||
def _node_sql_error(node_id: str, code: str, message: str) -> DataflowDiagnostic:
|
||||
return DataflowDiagnostic(severity="error", code=code, message=message, node_id=node_id)
|
||||
|
||||
|
||||
__all__ = ["SqlCompilationError", "compile_sql", "render_sql"]
|
||||
1
src/govoplan_dataflow/py.typed
Normal file
1
src/govoplan_dataflow/py.typed
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
125
tests/test_graph_and_sql.py
Normal file
125
tests/test_graph_and_sql.py
Normal file
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from govoplan_dataflow.backend.executor import execute_preview
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
GraphEdge,
|
||||
GraphNode,
|
||||
GraphPosition,
|
||||
PipelineGraph,
|
||||
)
|
||||
from govoplan_dataflow.backend.sql_compiler import SqlCompilationError, compile_sql, render_sql
|
||||
|
||||
|
||||
def inline_source() -> GraphNode:
|
||||
return GraphNode(
|
||||
id="source",
|
||||
type="source.inline",
|
||||
label="Monthly input",
|
||||
position=GraphPosition(x=40, y=160),
|
||||
config={
|
||||
"source_name": "monthly_files",
|
||||
"rows": [
|
||||
{"department": "A", "status": "open", "amount": 10},
|
||||
{"department": "A", "status": "closed", "amount": 5},
|
||||
{"department": "B", "status": "open", "amount": 20},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class DataflowGraphAndSqlTests(unittest.TestCase):
|
||||
def test_compiles_renders_and_executes_grouped_query(self) -> None:
|
||||
sql = """
|
||||
SELECT department, COUNT(*) AS records, SUM(amount) AS total
|
||||
FROM monthly_files
|
||||
WHERE status = 'open'
|
||||
GROUP BY department
|
||||
ORDER BY total DESC
|
||||
LIMIT 50
|
||||
"""
|
||||
graph, normalized, diagnostics = compile_sql(sql, source_nodes=[inline_source()])
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
self.assertEqual(
|
||||
["source.inline", "filter", "aggregate", "sort", "limit", "output"],
|
||||
[node.type for node in graph.nodes],
|
||||
)
|
||||
self.assertEqual(normalized, render_sql(graph)[0])
|
||||
|
||||
result = execute_preview(graph, row_limit=100)
|
||||
self.assertEqual(
|
||||
[
|
||||
{"department": "B", "records": 1, "total": 20},
|
||||
{"department": "A", "records": 1, "total": 10},
|
||||
],
|
||||
result.rows,
|
||||
)
|
||||
self.assertEqual(2, result.total_rows)
|
||||
self.assertFalse(result.truncated)
|
||||
self.assertEqual(3, result.input_row_count)
|
||||
self.assertEqual(6, len(result.node_diagnostics))
|
||||
self.assertEqual(1, len(result.source_fingerprints))
|
||||
|
||||
def test_rejects_effectful_or_multi_statement_sql(self) -> None:
|
||||
for sql in (
|
||||
"DELETE FROM monthly_files",
|
||||
"SELECT * FROM monthly_files; DROP TABLE monthly_files",
|
||||
"INSERT INTO target SELECT * FROM monthly_files",
|
||||
):
|
||||
with self.subTest(sql=sql), self.assertRaises(SqlCompilationError):
|
||||
compile_sql(sql, source_nodes=[inline_source()])
|
||||
|
||||
def test_rejects_join_until_comparison_slice(self) -> None:
|
||||
with self.assertRaisesRegex(SqlCompilationError, "JOIN support"):
|
||||
compile_sql(
|
||||
"SELECT * FROM monthly_files JOIN other ON monthly_files.id = other.id",
|
||||
source_nodes=[inline_source()],
|
||||
)
|
||||
|
||||
def test_graph_validation_rejects_cycle(self) -> None:
|
||||
source = inline_source()
|
||||
output = GraphNode(
|
||||
id="output",
|
||||
type="output",
|
||||
label="Output",
|
||||
position=GraphPosition(x=300, y=160),
|
||||
config={},
|
||||
)
|
||||
graph = PipelineGraph(
|
||||
nodes=[source, output],
|
||||
edges=[
|
||||
GraphEdge(id="forward", source="source", target="output"),
|
||||
GraphEdge(id="back", source="output", target="source"),
|
||||
],
|
||||
)
|
||||
|
||||
from govoplan_dataflow.backend.graph import validate_graph
|
||||
|
||||
codes = {item.code for item in validate_graph(graph)}
|
||||
self.assertIn("graph.cycle", codes)
|
||||
|
||||
def test_preview_truncates_response_without_changing_pipeline_limit(self) -> None:
|
||||
source = inline_source()
|
||||
output = GraphNode(
|
||||
id="output",
|
||||
type="output",
|
||||
label="Output",
|
||||
position=GraphPosition(x=300, y=160),
|
||||
config={},
|
||||
)
|
||||
graph = PipelineGraph(
|
||||
nodes=[source, output],
|
||||
edges=[GraphEdge(id="edge", source="source", target="output")],
|
||||
)
|
||||
|
||||
result = execute_preview(graph, row_limit=2)
|
||||
|
||||
self.assertEqual(2, len(result.rows))
|
||||
self.assertEqual(3, result.total_rows)
|
||||
self.assertTrue(result.truncated)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
34
tests/test_manifest.py
Normal file
34
tests/test_manifest.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from govoplan_core.core.modules import ModuleManifest
|
||||
from govoplan_dataflow.backend.manifest import get_manifest
|
||||
|
||||
|
||||
class DataflowManifestTests(unittest.TestCase):
|
||||
def test_manifest_declares_independent_dataflow_boundary(self) -> None:
|
||||
manifest = get_manifest()
|
||||
|
||||
self.assertIsInstance(manifest, ModuleManifest)
|
||||
self.assertEqual(manifest.id, "dataflow")
|
||||
self.assertEqual(manifest.dependencies, ())
|
||||
self.assertIn("connectors", manifest.optional_dependencies)
|
||||
self.assertIn("reporting", manifest.optional_dependencies)
|
||||
self.assertIn("workflow", manifest.optional_dependencies)
|
||||
self.assertEqual(manifest.frontend.package_name, "@govoplan/dataflow-webui")
|
||||
self.assertIsNotNone(manifest.route_factory)
|
||||
self.assertIsNotNone(manifest.migration_spec)
|
||||
self.assertEqual(
|
||||
{
|
||||
"dataflow.pipeline_catalog",
|
||||
"dataflow.pipeline_preview",
|
||||
"dataflow.run_lifecycle",
|
||||
"dataflow.dataset_output",
|
||||
},
|
||||
{item.name for item in manifest.provides_interfaces},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
47
tests/test_migrations.py
Normal file
47
tests/test_migrations.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from alembic.runtime.migration import MigrationContext
|
||||
from sqlalchemy import create_engine, inspect
|
||||
|
||||
from govoplan_core.db.migrations import migrate_database
|
||||
from govoplan_dataflow.backend.manifest import get_manifest
|
||||
|
||||
|
||||
class DataflowMigrationTests(unittest.TestCase):
|
||||
def test_baseline_creates_dataflow_tables_and_head(self) -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="govoplan-dataflow-migration-") as directory:
|
||||
url = f"sqlite:///{Path(directory) / 'dataflow.db'}"
|
||||
migrate_database(
|
||||
database_url=url,
|
||||
enabled_modules=("dataflow",),
|
||||
manifest_factories=(get_manifest,),
|
||||
)
|
||||
engine = create_engine(url)
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
self.assertIn(
|
||||
"d4f7a1c8e2b0",
|
||||
set(MigrationContext.configure(connection).get_current_heads()),
|
||||
)
|
||||
self.assertEqual(
|
||||
{
|
||||
"dataflow_pipelines",
|
||||
"dataflow_pipeline_revisions",
|
||||
"dataflow_runs",
|
||||
},
|
||||
{
|
||||
name
|
||||
for name in inspect(connection).get_table_names()
|
||||
if name.startswith("dataflow_")
|
||||
},
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
198
tests/test_service.py
Normal file
198
tests/test_service.py
Normal file
@@ -0,0 +1,198 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from sqlalchemy import create_engine, func, select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_dataflow.backend.db.models import (
|
||||
DataflowPipeline,
|
||||
DataflowPipelineRevision,
|
||||
DataflowRun,
|
||||
)
|
||||
from govoplan_dataflow.backend.schemas import (
|
||||
GraphEdge,
|
||||
GraphNode,
|
||||
GraphPosition,
|
||||
PipelineCreateRequest,
|
||||
PipelineGraph,
|
||||
PipelinePreviewRequest,
|
||||
PipelineUpdateRequest,
|
||||
)
|
||||
from govoplan_dataflow.backend.service import (
|
||||
DataflowConflictError,
|
||||
DataflowNotFoundError,
|
||||
create_pipeline,
|
||||
get_pipeline,
|
||||
preview_pipeline,
|
||||
update_pipeline,
|
||||
)
|
||||
|
||||
|
||||
def sample_graph(*, minimum: int = 10) -> PipelineGraph:
|
||||
return PipelineGraph(
|
||||
nodes=[
|
||||
GraphNode(
|
||||
id="source",
|
||||
type="source.inline",
|
||||
label="Monthly input",
|
||||
position=GraphPosition(x=40, y=160),
|
||||
config={
|
||||
"source_name": "monthly_files",
|
||||
"rows": [
|
||||
{"id": 1, "amount": 5},
|
||||
{"id": 2, "amount": 15},
|
||||
{"id": 3, "amount": 25},
|
||||
],
|
||||
},
|
||||
),
|
||||
GraphNode(
|
||||
id="filter",
|
||||
type="filter",
|
||||
label="Minimum amount",
|
||||
position=GraphPosition(x=260, y=160),
|
||||
config={"column": "amount", "operator": "gte", "value": minimum},
|
||||
),
|
||||
GraphNode(
|
||||
id="output",
|
||||
type="output",
|
||||
label="Output",
|
||||
position=GraphPosition(x=480, y=160),
|
||||
config={},
|
||||
),
|
||||
],
|
||||
edges=[
|
||||
GraphEdge(id="source-filter", source="source", target="filter"),
|
||||
GraphEdge(id="filter-output", source="filter", target="output"),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class DataflowServiceTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
self.engine,
|
||||
tables=[
|
||||
DataflowPipeline.__table__,
|
||||
DataflowPipelineRevision.__table__,
|
||||
DataflowRun.__table__,
|
||||
],
|
||||
)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
self.session: Session = self.Session()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.session.close()
|
||||
Base.metadata.drop_all(
|
||||
self.engine,
|
||||
tables=[
|
||||
DataflowRun.__table__,
|
||||
DataflowPipelineRevision.__table__,
|
||||
DataflowPipeline.__table__,
|
||||
],
|
||||
)
|
||||
self.engine.dispose()
|
||||
|
||||
def _create(self, *, tenant_id: str = "tenant-1") -> DataflowPipeline:
|
||||
pipeline = create_pipeline(
|
||||
self.session,
|
||||
tenant_id=tenant_id,
|
||||
actor_id="user-1",
|
||||
payload=PipelineCreateRequest(
|
||||
name="Monthly comparison",
|
||||
description="First governed pipeline",
|
||||
graph=sample_graph(),
|
||||
editor_mode="graph",
|
||||
),
|
||||
)
|
||||
self.session.commit()
|
||||
return pipeline
|
||||
|
||||
def test_create_and_update_make_immutable_revisions(self) -> None:
|
||||
pipeline = self._create()
|
||||
|
||||
updated = update_pipeline(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
pipeline_id=pipeline.id,
|
||||
actor_id="user-2",
|
||||
payload=PipelineUpdateRequest(
|
||||
name="Monthly comparison",
|
||||
description="Changed threshold",
|
||||
graph=sample_graph(minimum=20),
|
||||
editor_mode="graph",
|
||||
expected_revision=1,
|
||||
),
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
revisions = list(
|
||||
self.session.scalars(
|
||||
select(DataflowPipelineRevision)
|
||||
.where(DataflowPipelineRevision.pipeline_id == pipeline.id)
|
||||
.order_by(DataflowPipelineRevision.revision)
|
||||
)
|
||||
)
|
||||
self.assertEqual(2, updated.current_revision)
|
||||
self.assertEqual([1, 2], [item.revision for item in revisions])
|
||||
self.assertNotEqual(revisions[0].content_hash, revisions[1].content_hash)
|
||||
self.assertEqual(10, revisions[0].graph["nodes"][1]["config"]["value"])
|
||||
self.assertEqual(20, revisions[1].graph["nodes"][1]["config"]["value"])
|
||||
|
||||
def test_stale_revision_is_rejected(self) -> None:
|
||||
pipeline = self._create()
|
||||
|
||||
with self.assertRaises(DataflowConflictError):
|
||||
update_pipeline(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
pipeline_id=pipeline.id,
|
||||
actor_id="user-2",
|
||||
payload=PipelineUpdateRequest(
|
||||
name="Stale edit",
|
||||
graph=sample_graph(minimum=30),
|
||||
editor_mode="graph",
|
||||
expected_revision=2,
|
||||
),
|
||||
)
|
||||
|
||||
def test_pipeline_lookup_is_tenant_isolated(self) -> None:
|
||||
pipeline = self._create()
|
||||
|
||||
with self.assertRaises(DataflowNotFoundError):
|
||||
get_pipeline(
|
||||
self.session,
|
||||
tenant_id="tenant-2",
|
||||
pipeline_id=pipeline.id,
|
||||
)
|
||||
|
||||
def test_saved_preview_records_lineage_but_not_result_rows(self) -> None:
|
||||
pipeline = self._create()
|
||||
|
||||
response = preview_pipeline(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
actor_id="user-1",
|
||||
payload=PipelinePreviewRequest(pipeline_id=pipeline.id, row_limit=1),
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
run = self.session.scalar(select(DataflowRun).where(DataflowRun.id == response.run_id))
|
||||
self.assertEqual("succeeded", response.status)
|
||||
self.assertEqual([{"id": 2, "amount": 15}], response.rows)
|
||||
self.assertEqual(2, response.total_rows)
|
||||
self.assertTrue(response.truncated)
|
||||
self.assertEqual(2, run.output_row_count)
|
||||
self.assertEqual(3, run.input_row_count)
|
||||
self.assertEqual(1, len(run.source_fingerprints))
|
||||
self.assertFalse(hasattr(run, "result_rows"))
|
||||
self.assertEqual(
|
||||
1,
|
||||
self.session.scalar(select(func.count()).select_from(DataflowRun)),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
34
webui/package.json
Normal file
34
webui/package.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@govoplan/dataflow-webui",
|
||||
"version": "0.1.14",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"module": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
},
|
||||
"./styles/dataflow.css": "./src/styles/dataflow.css"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test:structure": "node scripts/test-dataflow-page-structure.mjs"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@govoplan/core-webui": "^0.1.14",
|
||||
"@xyflow/react": "^12.11.2",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^7.1.1",
|
||||
"typescript": "^5.7.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@govoplan/core-webui": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
25
webui/scripts/test-dataflow-page-structure.mjs
Normal file
25
webui/scripts/test-dataflow-page-structure.mjs
Normal file
@@ -0,0 +1,25 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const page = readFileSync(new URL("../src/features/dataflow/DataflowPage.tsx", import.meta.url), "utf8");
|
||||
const canvas = readFileSync(new URL("../src/features/dataflow/DataflowCanvas.tsx", import.meta.url), "utf8");
|
||||
const css = readFileSync(new URL("../src/styles/dataflow.css", import.meta.url), "utf8");
|
||||
|
||||
const checks = [
|
||||
[page.includes("<DataflowCanvas"), "graph canvas"],
|
||||
[page.includes("Apply SQL"), "SQL workbench"],
|
||||
[page.includes("<NodeInspector"), "node inspector"],
|
||||
[page.includes("previewDataflowPipeline"), "preview action"],
|
||||
[page.includes("useUnsavedDraftGuard"), "unsaved-change guard"],
|
||||
[canvas.includes("application/x-govoplan-dataflow-node"), "palette drop handling"],
|
||||
[canvas.includes("isValidConnection"), "edge validation"],
|
||||
[canvas.includes("connectionRadius={32}"), "visible connection drop radius"],
|
||||
[css.includes("height: calc(100vh - 115px)"), "full-height workspace"],
|
||||
[css.includes(".dataflow-preview-table-wrap"), "bounded preview scrolling"]
|
||||
];
|
||||
|
||||
const missing = checks.filter(([present]) => !present).map(([, label]) => label);
|
||||
if (missing.length) {
|
||||
throw new Error(`Dataflow UI structure is missing: ${missing.join(", ")}`);
|
||||
}
|
||||
|
||||
console.log("Dataflow page structure checks passed.");
|
||||
187
webui/src/api/dataflow.ts
Normal file
187
webui/src/api/dataflow.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { apiFetch, type ApiSettings } from "@govoplan/core-webui";
|
||||
|
||||
export type PipelineStatus = "draft" | "active" | "archived";
|
||||
export type EditorMode = "graph" | "sql";
|
||||
|
||||
export type GraphPosition = { x: number; y: number };
|
||||
export type PipelineGraphNode = {
|
||||
id: string;
|
||||
type: string;
|
||||
label: string;
|
||||
position: GraphPosition;
|
||||
config: Record<string, unknown>;
|
||||
};
|
||||
export type PipelineGraphEdge = {
|
||||
id: string;
|
||||
source: string;
|
||||
target: string;
|
||||
source_port?: string;
|
||||
target_port?: string;
|
||||
};
|
||||
export type PipelineGraph = {
|
||||
schema_version: 1;
|
||||
nodes: PipelineGraphNode[];
|
||||
edges: PipelineGraphEdge[];
|
||||
};
|
||||
|
||||
export type DataflowDiagnostic = {
|
||||
severity: "info" | "warning" | "error";
|
||||
code: string;
|
||||
message: string;
|
||||
node_id?: string | null;
|
||||
field?: string | null;
|
||||
};
|
||||
|
||||
export type PipelineRevision = {
|
||||
id: string;
|
||||
revision: number;
|
||||
schema_version: number;
|
||||
graph: PipelineGraph;
|
||||
sql_text?: string | null;
|
||||
editor_mode: EditorMode;
|
||||
content_hash: string;
|
||||
created_by?: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type Pipeline = {
|
||||
id: string;
|
||||
tenant_id: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
status: PipelineStatus;
|
||||
current_revision: number;
|
||||
created_by?: string | null;
|
||||
updated_by?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
revision: PipelineRevision;
|
||||
};
|
||||
|
||||
export type PipelinePayload = {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
status: PipelineStatus;
|
||||
graph: PipelineGraph;
|
||||
sql_text?: string | null;
|
||||
editor_mode: EditorMode;
|
||||
};
|
||||
|
||||
export type PipelineValidation = {
|
||||
valid: boolean;
|
||||
graph?: PipelineGraph | null;
|
||||
sql_text?: string | null;
|
||||
diagnostics: DataflowDiagnostic[];
|
||||
};
|
||||
|
||||
export type PreviewColumn = {
|
||||
name: string;
|
||||
type: string;
|
||||
nullable: boolean;
|
||||
};
|
||||
|
||||
export type NodePreviewDiagnostic = {
|
||||
node_id: string;
|
||||
status: "succeeded" | "failed" | "skipped";
|
||||
input_rows: number;
|
||||
output_rows: number;
|
||||
duration_ms: number;
|
||||
columns: PreviewColumn[];
|
||||
messages: string[];
|
||||
};
|
||||
|
||||
export type PipelinePreview = {
|
||||
run_id?: string | null;
|
||||
pipeline_id?: string | null;
|
||||
revision?: number | null;
|
||||
status: "succeeded" | "failed";
|
||||
columns: PreviewColumn[];
|
||||
rows: Record<string, unknown>[];
|
||||
total_rows: number;
|
||||
truncated: boolean;
|
||||
diagnostics: DataflowDiagnostic[];
|
||||
node_diagnostics: NodePreviewDiagnostic[];
|
||||
definition_hash: string;
|
||||
executor_version: string;
|
||||
};
|
||||
|
||||
export async function listDataflowPipelines(settings: ApiSettings): Promise<Pipeline[]> {
|
||||
const response = await apiFetch<{ pipelines: Pipeline[] }>(settings, "/api/v1/dataflow/pipelines");
|
||||
return response.pipelines;
|
||||
}
|
||||
|
||||
export function createDataflowPipeline(
|
||||
settings: ApiSettings,
|
||||
payload: PipelinePayload
|
||||
): Promise<Pipeline> {
|
||||
return apiFetch<Pipeline>(settings, "/api/v1/dataflow/pipelines", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateDataflowPipeline(
|
||||
settings: ApiSettings,
|
||||
pipelineId: string,
|
||||
payload: PipelinePayload & { expected_revision: number }
|
||||
): Promise<Pipeline> {
|
||||
return apiFetch<Pipeline>(settings, `/api/v1/dataflow/pipelines/${encodeURIComponent(pipelineId)}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteDataflowPipeline(settings: ApiSettings, pipelineId: string): Promise<{ deleted: boolean }> {
|
||||
return apiFetch<{ deleted: boolean }>(
|
||||
settings,
|
||||
`/api/v1/dataflow/pipelines/${encodeURIComponent(pipelineId)}`,
|
||||
{ method: "DELETE" }
|
||||
);
|
||||
}
|
||||
|
||||
export function validateDataflowPipeline(
|
||||
settings: ApiSettings,
|
||||
payload: { graph?: PipelineGraph; sql_text?: string; source_nodes?: PipelineGraphNode[] }
|
||||
): Promise<PipelineValidation> {
|
||||
return apiFetch<PipelineValidation>(settings, "/api/v1/dataflow/validate", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function compileDataflowSql(
|
||||
settings: ApiSettings,
|
||||
payload: { graph?: PipelineGraph; sql_text: string; source_nodes?: PipelineGraphNode[] }
|
||||
): Promise<PipelineValidation> {
|
||||
return apiFetch<PipelineValidation>(settings, "/api/v1/dataflow/sql/compile", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function renderDataflowSql(
|
||||
settings: ApiSettings,
|
||||
graph: PipelineGraph
|
||||
): Promise<PipelineValidation> {
|
||||
return apiFetch<PipelineValidation>(settings, "/api/v1/dataflow/sql/render", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ graph })
|
||||
});
|
||||
}
|
||||
|
||||
export function previewDataflowPipeline(
|
||||
settings: ApiSettings,
|
||||
payload: {
|
||||
pipeline_id?: string;
|
||||
revision?: number;
|
||||
graph?: PipelineGraph;
|
||||
sql_text?: string;
|
||||
source_nodes?: PipelineGraphNode[];
|
||||
row_limit?: number;
|
||||
}
|
||||
): Promise<PipelinePreview> {
|
||||
return apiFetch<PipelinePreview>(settings, "/api/v1/dataflow/preview", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
210
webui/src/features/dataflow/DataflowCanvas.tsx
Normal file
210
webui/src/features/dataflow/DataflowCanvas.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import { useMemo, useState, type DragEvent } from "react";
|
||||
import {
|
||||
addEdge,
|
||||
applyEdgeChanges,
|
||||
applyNodeChanges,
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
ConnectionLineType,
|
||||
Controls,
|
||||
MiniMap,
|
||||
ReactFlow,
|
||||
type Connection,
|
||||
type Edge,
|
||||
type ReactFlowInstance
|
||||
} from "@xyflow/react";
|
||||
import type {
|
||||
DataflowDiagnostic,
|
||||
NodePreviewDiagnostic,
|
||||
PipelineGraph,
|
||||
PipelineGraphNode
|
||||
} from "../../api/dataflow";
|
||||
import DataflowNode, { type DataflowFlowNode } from "./DataflowNode";
|
||||
import { newNode } from "./model";
|
||||
|
||||
const nodeTypes = { dataflow: DataflowNode };
|
||||
|
||||
type DataflowCanvasProps = {
|
||||
graph: PipelineGraph;
|
||||
diagnostics: DataflowDiagnostic[];
|
||||
nodeDiagnostics: NodePreviewDiagnostic[];
|
||||
selectedNodeId: string | null;
|
||||
readOnly: boolean;
|
||||
onGraphChange: (graph: PipelineGraph) => void;
|
||||
onSelectNode: (nodeId: string | null) => void;
|
||||
};
|
||||
|
||||
export default function DataflowCanvas({
|
||||
graph,
|
||||
diagnostics,
|
||||
nodeDiagnostics,
|
||||
selectedNodeId,
|
||||
readOnly,
|
||||
onGraphChange,
|
||||
onSelectNode
|
||||
}: DataflowCanvasProps) {
|
||||
const [instance, setInstance] = useState<ReactFlowInstance<DataflowFlowNode, Edge> | null>(null);
|
||||
const errorNodeIds = useMemo(
|
||||
() => new Set(diagnostics.filter((item) => item.severity === "error" && item.node_id).map((item) => item.node_id)),
|
||||
[diagnostics]
|
||||
);
|
||||
const rowCounts = useMemo(
|
||||
() => new Map(nodeDiagnostics.map((item) => [item.node_id, item.output_rows])),
|
||||
[nodeDiagnostics]
|
||||
);
|
||||
const nodes = useMemo<DataflowFlowNode[]>(
|
||||
() => graph.nodes.map((node) => ({
|
||||
id: node.id,
|
||||
type: "dataflow",
|
||||
position: node.position,
|
||||
selected: node.id === selectedNodeId,
|
||||
data: {
|
||||
label: node.label,
|
||||
transformType: node.type,
|
||||
config: node.config,
|
||||
hasError: errorNodeIds.has(node.id),
|
||||
outputRows: rowCounts.get(node.id)
|
||||
}
|
||||
})),
|
||||
[errorNodeIds, graph.nodes, rowCounts, selectedNodeId]
|
||||
);
|
||||
const edges = useMemo<Edge[]>(
|
||||
() => graph.edges.map((edge) => ({
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
type: "smoothstep",
|
||||
className: "dataflow-edge"
|
||||
})),
|
||||
[graph.edges]
|
||||
);
|
||||
|
||||
const updateNodes = (nextNodes: DataflowFlowNode[]) => {
|
||||
const ids = new Set(nextNodes.map((node) => node.id));
|
||||
const nextGraphNodes = nextNodes.map((flowNode) => {
|
||||
const current = graph.nodes.find((node) => node.id === flowNode.id);
|
||||
if (!current) {
|
||||
throw new Error(`Unknown Dataflow node: ${flowNode.id}`);
|
||||
}
|
||||
return { ...current, position: flowNode.position };
|
||||
});
|
||||
onGraphChange({
|
||||
...graph,
|
||||
nodes: nextGraphNodes,
|
||||
edges: graph.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target))
|
||||
});
|
||||
};
|
||||
|
||||
const updateEdges = (nextEdges: Edge[]) => {
|
||||
onGraphChange({
|
||||
...graph,
|
||||
edges: nextEdges.map((edge) => ({
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
source_port: edge.sourceHandle ?? "output",
|
||||
target_port: edge.targetHandle ?? "input"
|
||||
}))
|
||||
});
|
||||
};
|
||||
|
||||
const isValidConnection = (connection: Connection | Edge): boolean => {
|
||||
if (readOnly || !connection.source || !connection.target || connection.source === connection.target) return false;
|
||||
const source = graph.nodes.find((node) => node.id === connection.source);
|
||||
const target = graph.nodes.find((node) => node.id === connection.target);
|
||||
if (!source || !target || source.type === "output" || target.type.startsWith("source.")) return false;
|
||||
const targetAlreadyConnected = graph.edges.some(
|
||||
(edge) => edge.target === connection.target && edge.source !== connection.source
|
||||
);
|
||||
return !targetAlreadyConnected;
|
||||
};
|
||||
|
||||
const onConnect = (connection: Connection) => {
|
||||
if (!isValidConnection(connection)) return;
|
||||
const next = addEdge(
|
||||
{
|
||||
...connection,
|
||||
id: `edge-${connection.source}-${connection.target}-${crypto.randomUUID()}`,
|
||||
type: "smoothstep"
|
||||
},
|
||||
edges
|
||||
);
|
||||
updateEdges(next);
|
||||
};
|
||||
|
||||
const onDrop = (event: DragEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
if (readOnly || !instance) return;
|
||||
const type = event.dataTransfer.getData("application/x-govoplan-dataflow-node");
|
||||
if (!type) return;
|
||||
const position = instance.screenToFlowPosition({ x: event.clientX, y: event.clientY });
|
||||
const node = newNode(type, position);
|
||||
onGraphChange({ ...graph, nodes: [...graph.nodes, node] });
|
||||
onSelectNode(node.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="dataflow-canvas"
|
||||
onDragOver={(event) => {
|
||||
if (event.dataTransfer.types.includes("application/x-govoplan-dataflow-node")) {
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
}}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<ReactFlow<DataflowFlowNode, Edge>
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onInit={setInstance}
|
||||
onNodesChange={(changes) => {
|
||||
if (readOnly) return;
|
||||
updateNodes(applyNodeChanges(changes, nodes));
|
||||
}}
|
||||
onEdgesChange={(changes) => {
|
||||
if (readOnly) return;
|
||||
updateEdges(applyEdgeChanges(changes, edges));
|
||||
}}
|
||||
onConnect={onConnect}
|
||||
isValidConnection={isValidConnection}
|
||||
onNodeClick={(_event, node) => onSelectNode(node.id)}
|
||||
onPaneClick={() => onSelectNode(null)}
|
||||
nodesDraggable={!readOnly}
|
||||
nodesConnectable={!readOnly}
|
||||
elementsSelectable
|
||||
deleteKeyCode={readOnly ? null : ["Backspace", "Delete"]}
|
||||
connectionLineType={ConnectionLineType.SmoothStep}
|
||||
connectionLineStyle={{ stroke: "var(--accent)", strokeWidth: 3 }}
|
||||
connectionRadius={32}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.22, maxZoom: 1.25 }}
|
||||
minZoom={0.25}
|
||||
maxZoom={1.8}
|
||||
>
|
||||
<Background variant={BackgroundVariant.Dots} gap={20} size={1.3} />
|
||||
<MiniMap
|
||||
pannable
|
||||
zoomable
|
||||
nodeStrokeWidth={2}
|
||||
nodeColor={(node) => node.data.hasError ? "var(--danger)" : "var(--accent)"}
|
||||
/>
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
{!graph.nodes.length ? (
|
||||
<div className="dataflow-canvas-empty">Drop a source here</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function updateGraphNode(
|
||||
graph: PipelineGraph,
|
||||
updatedNode: PipelineGraphNode
|
||||
): PipelineGraph {
|
||||
return {
|
||||
...graph,
|
||||
nodes: graph.nodes.map((node) => node.id === updatedNode.id ? updatedNode : node)
|
||||
};
|
||||
}
|
||||
87
webui/src/features/dataflow/DataflowNode.tsx
Normal file
87
webui/src/features/dataflow/DataflowNode.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import type { ComponentType } from "react";
|
||||
import {
|
||||
Braces,
|
||||
Columns3,
|
||||
Database,
|
||||
Filter,
|
||||
ListEnd,
|
||||
Sigma,
|
||||
SortAsc,
|
||||
Unplug
|
||||
} from "lucide-react";
|
||||
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
|
||||
|
||||
export type DataflowNodeData = {
|
||||
label: string;
|
||||
transformType: string;
|
||||
config: Record<string, unknown>;
|
||||
hasError?: boolean;
|
||||
outputRows?: number;
|
||||
};
|
||||
|
||||
export type DataflowFlowNode = Node<DataflowNodeData, "dataflow">;
|
||||
|
||||
const iconByType: Record<string, ComponentType<{ size?: number; strokeWidth?: number }>> = {
|
||||
"source.inline": Braces,
|
||||
"source.reference": Database,
|
||||
filter: Filter,
|
||||
select: Columns3,
|
||||
aggregate: Sigma,
|
||||
sort: SortAsc,
|
||||
limit: ListEnd,
|
||||
output: Unplug
|
||||
};
|
||||
|
||||
export default function DataflowNode({ data, selected }: NodeProps<DataflowFlowNode>) {
|
||||
const Icon = iconByType[data.transformType] ?? Braces;
|
||||
const isSource = data.transformType.startsWith("source.");
|
||||
const isOutput = data.transformType === "output";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
"dataflow-node",
|
||||
`dataflow-node-${data.transformType.replace(".", "-")}`,
|
||||
selected ? "is-selected" : "",
|
||||
data.hasError ? "has-error" : ""
|
||||
].filter(Boolean).join(" ")}
|
||||
>
|
||||
{!isSource ? (
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Left}
|
||||
className="dataflow-node-handle dataflow-node-handle-input"
|
||||
/>
|
||||
) : null}
|
||||
<span className="dataflow-node-icon" aria-hidden="true">
|
||||
<Icon size={17} strokeWidth={1.8} />
|
||||
</span>
|
||||
<span className="dataflow-node-copy">
|
||||
<strong>{data.label}</strong>
|
||||
<small>{transformLabel(data.transformType)}</small>
|
||||
</span>
|
||||
{typeof data.outputRows === "number" ? (
|
||||
<span className="dataflow-node-count">{data.outputRows}</span>
|
||||
) : null}
|
||||
{!isOutput ? (
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Right}
|
||||
className="dataflow-node-handle dataflow-node-handle-output"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function transformLabel(type: string): string {
|
||||
if (type === "source.inline") return "Inline source";
|
||||
if (type === "source.reference") return "Connector source";
|
||||
if (type === "filter") return "Filter";
|
||||
if (type === "select") return "Projection";
|
||||
if (type === "aggregate") return "Aggregation";
|
||||
if (type === "sort") return "Sort";
|
||||
if (type === "limit") return "Limit";
|
||||
if (type === "output") return "Output";
|
||||
return type;
|
||||
}
|
||||
775
webui/src/features/dataflow/DataflowPage.tsx
Normal file
775
webui/src/features/dataflow/DataflowPage.tsx
Normal file
@@ -0,0 +1,775 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ComponentType,
|
||||
type DragEvent
|
||||
} from "react";
|
||||
import {
|
||||
Braces,
|
||||
CheckCircle2,
|
||||
Code2,
|
||||
Columns3,
|
||||
Database,
|
||||
Filter,
|
||||
ListEnd,
|
||||
Network,
|
||||
Play,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Save,
|
||||
Sigma,
|
||||
SortAsc,
|
||||
Trash2,
|
||||
TriangleAlert
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
DismissibleAlert,
|
||||
IconButton,
|
||||
LoadingFrame,
|
||||
SegmentedControl,
|
||||
StatusBadge,
|
||||
hasScope,
|
||||
isApiError,
|
||||
useUnsavedChanges,
|
||||
useUnsavedDraftGuard,
|
||||
type ApiSettings,
|
||||
type AuthInfo
|
||||
} from "@govoplan/core-webui";
|
||||
import { ReactFlowProvider } from "@xyflow/react";
|
||||
import {
|
||||
compileDataflowSql,
|
||||
createDataflowPipeline,
|
||||
deleteDataflowPipeline,
|
||||
listDataflowPipelines,
|
||||
previewDataflowPipeline,
|
||||
renderDataflowSql,
|
||||
updateDataflowPipeline,
|
||||
validateDataflowPipeline,
|
||||
type DataflowDiagnostic,
|
||||
type EditorMode,
|
||||
type NodePreviewDiagnostic,
|
||||
type Pipeline,
|
||||
type PipelineGraphNode,
|
||||
type PipelinePreview
|
||||
} from "../../api/dataflow";
|
||||
import DataflowCanvas, { updateGraphNode } from "./DataflowCanvas";
|
||||
import NodeInspector from "./NodeInspector";
|
||||
import {
|
||||
NODE_LABELS,
|
||||
PALETTE_NODE_TYPES,
|
||||
draftFingerprint,
|
||||
draftFromPipeline,
|
||||
newNode,
|
||||
pipelinePayload,
|
||||
sampleDraft,
|
||||
sourceNodes,
|
||||
type PipelineDraft
|
||||
} from "./model";
|
||||
|
||||
type ResultTab = "preview" | "diagnostics";
|
||||
|
||||
const paletteIcons: Record<string, ComponentType<{ size?: number; strokeWidth?: number }>> = {
|
||||
"source.inline": Braces,
|
||||
filter: Filter,
|
||||
select: Columns3,
|
||||
aggregate: Sigma,
|
||||
sort: SortAsc,
|
||||
limit: ListEnd,
|
||||
output: Network
|
||||
};
|
||||
|
||||
export default function DataflowPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) {
|
||||
const { requestNavigation, requestDiscard } = useUnsavedChanges();
|
||||
const [pipelines, setPipelines] = useState<Pipeline[]>([]);
|
||||
const [draft, setDraft] = useState<PipelineDraft | null>(null);
|
||||
const [savedDraft, setSavedDraft] = useState<PipelineDraft | null>(null);
|
||||
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [working, setWorking] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const [diagnostics, setDiagnostics] = useState<DataflowDiagnostic[]>([]);
|
||||
const [nodeDiagnostics, setNodeDiagnostics] = useState<NodePreviewDiagnostic[]>([]);
|
||||
const [preview, setPreview] = useState<PipelinePreview | null>(null);
|
||||
const [resultOpen, setResultOpen] = useState(false);
|
||||
const [resultTab, setResultTab] = useState<ResultTab>("preview");
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const canWrite = hasScope(auth, "dataflow:pipeline:write") || hasScope(auth, "dataflow:pipeline:admin");
|
||||
const canRun = hasScope(auth, "dataflow:pipeline:run") || hasScope(auth, "dataflow:pipeline:admin");
|
||||
const dirty = Boolean(draft) && draftFingerprint(draft) !== draftFingerprint(savedDraft);
|
||||
const selectedNode = useMemo(
|
||||
() => draft?.graph.nodes.find((node) => node.id === selectedNodeId) ?? null,
|
||||
[draft, selectedNodeId]
|
||||
);
|
||||
const filteredPipelines = useMemo(() => {
|
||||
const query = search.trim().toLocaleLowerCase();
|
||||
if (!query) return pipelines;
|
||||
return pipelines.filter((pipeline) =>
|
||||
`${pipeline.name} ${pipeline.description ?? ""} ${pipeline.status}`.toLocaleLowerCase().includes(query)
|
||||
);
|
||||
}, [pipelines, search]);
|
||||
|
||||
const loadPipelines = useCallback(async (preferredId?: string | null) => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const items = await listDataflowPipelines(settings);
|
||||
setPipelines(items);
|
||||
const selected = items.find((item) => item.id === (preferredId ?? draft?.id)) ?? items[0];
|
||||
if (selected) {
|
||||
const next = draftFromPipeline(selected);
|
||||
setDraft(next);
|
||||
setSavedDraft(structuredClone(next));
|
||||
setSelectedNodeId(next.graph.nodes[0]?.id ?? null);
|
||||
} else if (!draft?.id) {
|
||||
setDraft(null);
|
||||
setSavedDraft(null);
|
||||
setSelectedNodeId(null);
|
||||
}
|
||||
} catch (loadError) {
|
||||
setError(apiErrorMessage(loadError));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [draft?.id, settings]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadPipelines();
|
||||
}, []);
|
||||
|
||||
const discardDraft = useCallback(() => {
|
||||
if (savedDraft) {
|
||||
const reset = structuredClone(savedDraft);
|
||||
setDraft(reset);
|
||||
setSelectedNodeId(reset.graph.nodes[0]?.id ?? null);
|
||||
} else {
|
||||
setDraft(null);
|
||||
setSelectedNodeId(null);
|
||||
}
|
||||
setDiagnostics([]);
|
||||
setNodeDiagnostics([]);
|
||||
setPreview(null);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
}, [savedDraft]);
|
||||
|
||||
const saveDraft = useCallback(async (): Promise<boolean> => {
|
||||
if (!draft || !canWrite || !draft.name.trim()) {
|
||||
setError(!draft?.name.trim() ? "Pipeline name is required." : "You cannot save this pipeline.");
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const payload = pipelinePayload(draft);
|
||||
const saved = draft.id && draft.currentRevision
|
||||
? await updateDataflowPipeline(settings, draft.id, {
|
||||
...payload,
|
||||
expected_revision: draft.currentRevision
|
||||
})
|
||||
: await createDataflowPipeline(settings, payload);
|
||||
const next = draftFromPipeline(saved);
|
||||
setDraft(next);
|
||||
setSavedDraft(structuredClone(next));
|
||||
setPipelines((current) => [saved, ...current.filter((item) => item.id !== saved.id)]);
|
||||
setSelectedNodeId((current) => current && next.graph.nodes.some((node) => node.id === current)
|
||||
? current
|
||||
: next.graph.nodes[0]?.id ?? null);
|
||||
setDiagnostics([]);
|
||||
setSuccess(`Saved revision ${saved.current_revision}.`);
|
||||
return true;
|
||||
} catch (saveError) {
|
||||
setError(apiErrorMessage(saveError));
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [canWrite, draft, settings]);
|
||||
|
||||
useUnsavedDraftGuard({
|
||||
dirty,
|
||||
title: "Unsaved pipeline",
|
||||
message: "Save or discard the pipeline changes before leaving this workspace.",
|
||||
onSave: saveDraft,
|
||||
onDiscard: discardDraft
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!dirty) return;
|
||||
event.preventDefault();
|
||||
event.returnValue = "";
|
||||
};
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
return () => window.removeEventListener("beforeunload", beforeUnload);
|
||||
}, [dirty]);
|
||||
|
||||
const selectPipeline = (pipeline: Pipeline) => {
|
||||
requestNavigation(() => {
|
||||
const next = draftFromPipeline(pipeline);
|
||||
setDraft(next);
|
||||
setSavedDraft(structuredClone(next));
|
||||
setSelectedNodeId(next.graph.nodes[0]?.id ?? null);
|
||||
setDiagnostics([]);
|
||||
setNodeDiagnostics([]);
|
||||
setPreview(null);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
});
|
||||
};
|
||||
|
||||
const createNew = () => {
|
||||
requestNavigation(() => {
|
||||
const next = sampleDraft();
|
||||
setDraft(next);
|
||||
setSavedDraft(null);
|
||||
setSelectedNodeId(next.graph.nodes[0]?.id ?? null);
|
||||
setDiagnostics([]);
|
||||
setNodeDiagnostics([]);
|
||||
setPreview(null);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
});
|
||||
};
|
||||
|
||||
const updateDraft = (patch: Partial<PipelineDraft>) => {
|
||||
setDraft((current) => current ? { ...current, ...patch } : current);
|
||||
setSuccess("");
|
||||
};
|
||||
|
||||
const updateGraph = (graph: PipelineDraft["graph"]) => {
|
||||
updateDraft({ graph });
|
||||
setDiagnostics([]);
|
||||
setNodeDiagnostics([]);
|
||||
};
|
||||
|
||||
const validate = async () => {
|
||||
if (!draft) return;
|
||||
setWorking(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const response = await validateDataflowPipeline(settings, draft.editorMode === "sql"
|
||||
? { graph: draft.graph, sql_text: draft.sqlText, source_nodes: sourceNodes(draft.graph) }
|
||||
: { graph: draft.graph });
|
||||
setDiagnostics(response.diagnostics);
|
||||
if (response.valid) setSuccess("Pipeline definition is valid.");
|
||||
setResultOpen(true);
|
||||
setResultTab("diagnostics");
|
||||
} catch (validationError) {
|
||||
setError(apiErrorMessage(validationError));
|
||||
} finally {
|
||||
setWorking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const applySql = async (switchToGraph = false): Promise<boolean> => {
|
||||
if (!draft) return false;
|
||||
setWorking(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const response = await compileDataflowSql(settings, {
|
||||
graph: draft.graph,
|
||||
sql_text: draft.sqlText,
|
||||
source_nodes: sourceNodes(draft.graph)
|
||||
});
|
||||
setDiagnostics(response.diagnostics);
|
||||
setResultOpen(true);
|
||||
setResultTab("diagnostics");
|
||||
if (!response.valid || !response.graph) return false;
|
||||
updateDraft({
|
||||
graph: response.graph,
|
||||
sqlText: response.sql_text ?? draft.sqlText,
|
||||
editorMode: switchToGraph ? "graph" : "sql"
|
||||
});
|
||||
setSelectedNodeId(response.graph.nodes[0]?.id ?? null);
|
||||
setSuccess("SQL compiled into the pipeline graph.");
|
||||
return true;
|
||||
} catch (compileError) {
|
||||
setError(apiErrorMessage(compileError));
|
||||
return false;
|
||||
} finally {
|
||||
setWorking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const changeEditorMode = async (mode: EditorMode) => {
|
||||
if (!draft || mode === draft.editorMode) return;
|
||||
if (mode === "sql") {
|
||||
setWorking(true);
|
||||
setError("");
|
||||
try {
|
||||
const response = await renderDataflowSql(settings, draft.graph);
|
||||
setDiagnostics(response.diagnostics);
|
||||
if (!response.valid || !response.sql_text) {
|
||||
setResultOpen(true);
|
||||
setResultTab("diagnostics");
|
||||
return;
|
||||
}
|
||||
updateDraft({ editorMode: "sql", sqlText: response.sql_text });
|
||||
} catch (renderError) {
|
||||
setError(apiErrorMessage(renderError));
|
||||
} finally {
|
||||
setWorking(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await applySql(true);
|
||||
};
|
||||
|
||||
const runPreview = async () => {
|
||||
if (!draft || !canRun) return;
|
||||
setWorking(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const response = await previewDataflowPipeline(settings, !dirty && draft.id && draft.currentRevision
|
||||
? { pipeline_id: draft.id, revision: draft.currentRevision, row_limit: 100 }
|
||||
: {
|
||||
graph: draft.graph,
|
||||
sql_text: draft.editorMode === "sql" ? draft.sqlText : undefined,
|
||||
source_nodes: sourceNodes(draft.graph),
|
||||
row_limit: 100
|
||||
});
|
||||
setPreview(response);
|
||||
setDiagnostics(response.diagnostics);
|
||||
setNodeDiagnostics(response.node_diagnostics);
|
||||
setResultOpen(true);
|
||||
setResultTab(response.status === "succeeded" ? "preview" : "diagnostics");
|
||||
if (response.status === "succeeded") {
|
||||
setSuccess(`Preview produced ${response.total_rows} row${response.total_rows === 1 ? "" : "s"}.`);
|
||||
}
|
||||
} catch (previewError) {
|
||||
setError(apiErrorMessage(previewError));
|
||||
} finally {
|
||||
setWorking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removePipeline = async () => {
|
||||
if (!draft?.id) return;
|
||||
setSaving(true);
|
||||
setError("");
|
||||
try {
|
||||
await deleteDataflowPipeline(settings, draft.id);
|
||||
const remaining = pipelines.filter((item) => item.id !== draft.id);
|
||||
setPipelines(remaining);
|
||||
const next = remaining[0] ? draftFromPipeline(remaining[0]) : null;
|
||||
setDraft(next);
|
||||
setSavedDraft(next ? structuredClone(next) : null);
|
||||
setSelectedNodeId(next?.graph.nodes[0]?.id ?? null);
|
||||
setDeleteOpen(false);
|
||||
setPreview(null);
|
||||
setDiagnostics([]);
|
||||
} catch (deleteError) {
|
||||
setError(apiErrorMessage(deleteError));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const addNode = (type: string) => {
|
||||
if (!draft || !canWrite || uniqueNodeExists(draft, type)) return;
|
||||
const node = newNode(type, {
|
||||
x: 120 + draft.graph.nodes.length * 70,
|
||||
y: 100 + (draft.graph.nodes.length % 4) * 80
|
||||
});
|
||||
updateGraph({ ...draft.graph, nodes: [...draft.graph.nodes, node] });
|
||||
setSelectedNodeId(node.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="dataflow-page">
|
||||
<div className="dataflow-shell">
|
||||
<aside className="dataflow-pipeline-panel" aria-label="Data pipelines">
|
||||
<div className="dataflow-panel-toolbar">
|
||||
<strong>Pipelines</strong>
|
||||
<span className="dataflow-toolbar-actions">
|
||||
<IconButton
|
||||
label="Refresh pipelines"
|
||||
icon={<RefreshCw size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => requestNavigation(() => void loadPipelines(draft?.id))}
|
||||
disabled={loading}
|
||||
/>
|
||||
<IconButton
|
||||
label="New pipeline"
|
||||
icon={<Plus size={17} />}
|
||||
variant="primary"
|
||||
onClick={createNew}
|
||||
disabled={!canWrite}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
<div className="dataflow-pipeline-search">
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search pipelines"
|
||||
aria-label="Search pipelines"
|
||||
/>
|
||||
</div>
|
||||
<LoadingFrame loading={loading} label="Loading pipelines" className="dataflow-pipeline-list-frame">
|
||||
<div className="dataflow-pipeline-list">
|
||||
{filteredPipelines.map((pipeline) => (
|
||||
<button
|
||||
key={pipeline.id}
|
||||
type="button"
|
||||
className={pipeline.id === draft?.id ? "is-selected" : ""}
|
||||
onClick={() => selectPipeline(pipeline)}
|
||||
>
|
||||
<span>
|
||||
<strong>{pipeline.name}</strong>
|
||||
<small>Revision {pipeline.current_revision}</small>
|
||||
</span>
|
||||
<StatusBadge status={pipeline.status} />
|
||||
</button>
|
||||
))}
|
||||
{!loading && !filteredPipelines.length ? (
|
||||
<div className="dataflow-pipeline-empty">
|
||||
{search ? "No matching pipelines" : "No pipelines yet"}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</LoadingFrame>
|
||||
</aside>
|
||||
|
||||
<section className="dataflow-workspace">
|
||||
{draft ? (
|
||||
<>
|
||||
<div className="dataflow-workspace-toolbar">
|
||||
<div className="dataflow-identity-fields">
|
||||
<input
|
||||
className="dataflow-name-input"
|
||||
value={draft.name}
|
||||
onChange={(event) => updateDraft({ name: event.target.value })}
|
||||
aria-label="Pipeline name"
|
||||
disabled={!canWrite}
|
||||
/>
|
||||
<input
|
||||
className="dataflow-description-input"
|
||||
value={draft.description}
|
||||
onChange={(event) => updateDraft({ description: event.target.value })}
|
||||
placeholder="Description"
|
||||
aria-label="Pipeline description"
|
||||
disabled={!canWrite}
|
||||
/>
|
||||
<select
|
||||
value={draft.status}
|
||||
onChange={(event) => updateDraft({ status: event.target.value as PipelineDraft["status"] })}
|
||||
aria-label="Pipeline status"
|
||||
disabled={!canWrite}
|
||||
>
|
||||
<option value="draft">Draft</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="archived">Archived</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="dataflow-command-bar">
|
||||
<SegmentedControl<EditorMode>
|
||||
ariaLabel="Pipeline editor mode"
|
||||
options={[
|
||||
{ id: "graph", label: <><Network size={15} /> Graph</> },
|
||||
{ id: "sql", label: <><Code2 size={15} /> SQL</> }
|
||||
]}
|
||||
value={draft.editorMode}
|
||||
onChange={(mode) => void changeEditorMode(mode)}
|
||||
disabled={working}
|
||||
/>
|
||||
<Button onClick={() => void validate()} disabled={working}>
|
||||
<CheckCircle2 size={16} /> Validate
|
||||
</Button>
|
||||
<Button variant="primary" onClick={() => void runPreview()} disabled={working || !canRun}>
|
||||
<Play size={16} /> Preview
|
||||
</Button>
|
||||
<IconButton
|
||||
label="Discard changes"
|
||||
icon={<RotateCcw size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => requestDiscard(() => undefined)}
|
||||
disabled={!dirty || saving}
|
||||
/>
|
||||
{draft.id ? (
|
||||
<IconButton
|
||||
label="Delete pipeline"
|
||||
icon={<Trash2 size={16} />}
|
||||
variant="danger"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
disabled={!canWrite || saving}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => void saveDraft()}
|
||||
disabled={saving || working || !dirty || !canWrite}
|
||||
>
|
||||
<Save size={16} /> {saving ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{(error || success) ? (
|
||||
<div className="dataflow-alerts">
|
||||
{error ? <DismissibleAlert tone="danger" resetKey={error}>{error}</DismissibleAlert> : null}
|
||||
{success ? <DismissibleAlert tone="success" resetKey={success}>{success}</DismissibleAlert> : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={`dataflow-editor ${draft.editorMode === "sql" ? "is-sql" : ""}`}>
|
||||
{draft.editorMode === "graph" ? (
|
||||
<aside className="dataflow-palette" aria-label="Transform palette">
|
||||
<div className="dataflow-panel-heading">
|
||||
<strong>Transforms</strong>
|
||||
</div>
|
||||
<div className="dataflow-palette-items">
|
||||
{PALETTE_NODE_TYPES.map((type) => {
|
||||
const Icon = paletteIcons[type] ?? Database;
|
||||
const disabled = !canWrite || uniqueNodeExists(draft, type);
|
||||
return (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
draggable={!disabled}
|
||||
disabled={disabled}
|
||||
onDragStart={(event) => startPaletteDrag(event, type)}
|
||||
onClick={() => addNode(type)}
|
||||
>
|
||||
<Icon size={16} />
|
||||
<span>{NODE_LABELS[type]}</span>
|
||||
<Plus size={14} className="dataflow-palette-add" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</aside>
|
||||
) : null}
|
||||
<section className="dataflow-editor-surface">
|
||||
{draft.editorMode === "graph" ? (
|
||||
<ReactFlowProvider>
|
||||
<DataflowCanvas
|
||||
graph={draft.graph}
|
||||
diagnostics={diagnostics}
|
||||
nodeDiagnostics={nodeDiagnostics}
|
||||
selectedNodeId={selectedNodeId}
|
||||
readOnly={!canWrite}
|
||||
onGraphChange={updateGraph}
|
||||
onSelectNode={setSelectedNodeId}
|
||||
/>
|
||||
</ReactFlowProvider>
|
||||
) : (
|
||||
<div className="dataflow-sql-workbench">
|
||||
<div className="dataflow-sql-toolbar">
|
||||
<span>Constrained Dataflow SQL</span>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => void applySql(false)}
|
||||
disabled={working || !canWrite}
|
||||
>
|
||||
<Code2 size={16} /> Apply SQL
|
||||
</Button>
|
||||
</div>
|
||||
<textarea
|
||||
value={draft.sqlText}
|
||||
onChange={(event) => updateDraft({ sqlText: event.target.value })}
|
||||
spellCheck={false}
|
||||
disabled={!canWrite}
|
||||
aria-label="Dataflow SQL"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<NodeInspector
|
||||
node={selectedNode}
|
||||
readOnly={!canWrite}
|
||||
onChange={(node: PipelineGraphNode) => updateGraph(updateGraphNode(draft.graph, node))}
|
||||
onDelete={(nodeId) => {
|
||||
updateGraph({
|
||||
...draft.graph,
|
||||
nodes: draft.graph.nodes.filter((node) => node.id !== nodeId),
|
||||
edges: draft.graph.edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId)
|
||||
});
|
||||
setSelectedNodeId(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{resultOpen ? (
|
||||
<ResultPanel
|
||||
tab={resultTab}
|
||||
onTabChange={setResultTab}
|
||||
preview={preview}
|
||||
diagnostics={diagnostics}
|
||||
nodeDiagnostics={nodeDiagnostics}
|
||||
onClose={() => setResultOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<div className="dataflow-workspace-empty">
|
||||
<Network size={30} />
|
||||
<strong>No pipeline selected</strong>
|
||||
<Button variant="primary" onClick={createNew} disabled={!canWrite}>
|
||||
<Plus size={16} /> New pipeline
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{working ? <div className="dataflow-working-indicator" role="status">Working...</div> : null}
|
||||
</section>
|
||||
</div>
|
||||
<ConfirmDialog
|
||||
open={deleteOpen}
|
||||
title="Delete pipeline"
|
||||
message={`Delete ${draft?.name ?? "this pipeline"} and all of its saved revisions and run evidence?`}
|
||||
confirmLabel="Delete"
|
||||
tone="danger"
|
||||
busy={saving}
|
||||
onCancel={() => setDeleteOpen(false)}
|
||||
onConfirm={() => void removePipeline()}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultPanel({
|
||||
tab,
|
||||
onTabChange,
|
||||
preview,
|
||||
diagnostics,
|
||||
nodeDiagnostics,
|
||||
onClose
|
||||
}: {
|
||||
tab: ResultTab;
|
||||
onTabChange: (tab: ResultTab) => void;
|
||||
preview: PipelinePreview | null;
|
||||
diagnostics: DataflowDiagnostic[];
|
||||
nodeDiagnostics: NodePreviewDiagnostic[];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<section className="dataflow-results" aria-label="Pipeline results">
|
||||
<div className="dataflow-results-toolbar">
|
||||
<SegmentedControl<ResultTab>
|
||||
ariaLabel="Result view"
|
||||
options={[
|
||||
{ id: "preview", label: `Preview${preview ? ` (${preview.total_rows})` : ""}` },
|
||||
{ id: "diagnostics", label: `Diagnostics (${diagnostics.length + nodeDiagnostics.length})` }
|
||||
]}
|
||||
value={tab}
|
||||
onChange={onTabChange}
|
||||
/>
|
||||
<Button variant="ghost" onClick={onClose}>Close</Button>
|
||||
</div>
|
||||
{tab === "preview" ? (
|
||||
<PreviewTable preview={preview} />
|
||||
) : (
|
||||
<DiagnosticsPanel diagnostics={diagnostics} nodeDiagnostics={nodeDiagnostics} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewTable({ preview }: { preview: PipelinePreview | null }) {
|
||||
if (!preview) return <div className="dataflow-results-empty">No preview has been run.</div>;
|
||||
if (preview.status === "failed") return <div className="dataflow-results-empty">Preview failed.</div>;
|
||||
return (
|
||||
<div className="dataflow-preview-table-wrap">
|
||||
<table className="dataflow-preview-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{preview.columns.map((column) => (
|
||||
<th key={column.name}>
|
||||
<span>{column.name}</span>
|
||||
<small>{column.type}{column.nullable ? " · nullable" : ""}</small>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.rows.map((row, rowIndex) => (
|
||||
<tr key={rowIndex}>
|
||||
{preview.columns.map((column) => (
|
||||
<td key={column.name}>{formatCell(row[column.name])}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{preview.truncated ? (
|
||||
<div className="dataflow-preview-truncated">Showing {preview.rows.length} of {preview.total_rows} rows</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagnosticsPanel({
|
||||
diagnostics,
|
||||
nodeDiagnostics
|
||||
}: {
|
||||
diagnostics: DataflowDiagnostic[];
|
||||
nodeDiagnostics: NodePreviewDiagnostic[];
|
||||
}) {
|
||||
if (!diagnostics.length && !nodeDiagnostics.length) {
|
||||
return <div className="dataflow-results-empty">No diagnostics.</div>;
|
||||
}
|
||||
return (
|
||||
<div className="dataflow-diagnostics-list">
|
||||
{diagnostics.map((item, index) => (
|
||||
<div key={`${item.code}-${item.node_id ?? "pipeline"}-${index}`} className={`is-${item.severity}`}>
|
||||
{item.severity === "error" ? <TriangleAlert size={15} /> : <CheckCircle2 size={15} />}
|
||||
<span>
|
||||
<strong>{item.code}</strong>
|
||||
<small>{item.message}</small>
|
||||
</span>
|
||||
{item.node_id ? <code>{item.node_id}</code> : null}
|
||||
</div>
|
||||
))}
|
||||
{nodeDiagnostics.map((item) => (
|
||||
<div key={item.node_id} className={`is-${item.status}`}>
|
||||
<CheckCircle2 size={15} />
|
||||
<span>
|
||||
<strong>{item.node_id}</strong>
|
||||
<small>{item.input_rows} in · {item.output_rows} out · {item.duration_ms.toFixed(2)} ms</small>
|
||||
</span>
|
||||
<code>{item.columns.length} columns</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function uniqueNodeExists(draft: PipelineDraft, type: string): boolean {
|
||||
if (type === "output") return draft.graph.nodes.some((node) => node.type === "output");
|
||||
if (type.startsWith("source.")) return draft.graph.nodes.some((node) => node.type.startsWith("source."));
|
||||
return false;
|
||||
}
|
||||
|
||||
function startPaletteDrag(event: DragEvent<HTMLButtonElement>, type: string) {
|
||||
event.dataTransfer.setData("application/x-govoplan-dataflow-node", type);
|
||||
event.dataTransfer.effectAllowed = "copy";
|
||||
}
|
||||
|
||||
function formatCell(value: unknown): string {
|
||||
if (value === null || value === undefined) return "—";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function apiErrorMessage(error: unknown): string {
|
||||
if (!isApiError(error)) return error instanceof Error ? error.message : "The request failed.";
|
||||
try {
|
||||
const parsed = JSON.parse(error.body) as { detail?: string | { message?: string } };
|
||||
if (typeof parsed.detail === "string") return parsed.detail;
|
||||
if (parsed.detail?.message) return parsed.detail.message;
|
||||
} catch {
|
||||
// Fall through to the API error message.
|
||||
}
|
||||
return error.message;
|
||||
}
|
||||
316
webui/src/features/dataflow/NodeInspector.tsx
Normal file
316
webui/src/features/dataflow/NodeInspector.tsx
Normal file
@@ -0,0 +1,316 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { Button, DismissibleAlert, FormField } from "@govoplan/core-webui";
|
||||
import type { PipelineGraphNode } from "../../api/dataflow";
|
||||
|
||||
type NodeInspectorProps = {
|
||||
node: PipelineGraphNode | null;
|
||||
readOnly: boolean;
|
||||
onChange: (node: PipelineGraphNode) => void;
|
||||
onDelete: (nodeId: string) => void;
|
||||
};
|
||||
|
||||
export default function NodeInspector({ node, readOnly, onChange, onDelete }: NodeInspectorProps) {
|
||||
const [rowsText, setRowsText] = useState("");
|
||||
const [aggregateText, setAggregateText] = useState("");
|
||||
const [sortText, setSortText] = useState("");
|
||||
const [localError, setLocalError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setRowsText(node ? JSON.stringify(node.config.rows ?? [], null, 2) : "");
|
||||
setAggregateText(node ? aggregatesToText(node.config.aggregates) : "");
|
||||
setSortText(node ? sortFieldsToText(node.config.fields) : "");
|
||||
setLocalError("");
|
||||
}, [node?.id]);
|
||||
|
||||
if (!node) {
|
||||
return (
|
||||
<aside className="dataflow-inspector" aria-label="Node inspector">
|
||||
<div className="dataflow-panel-heading">
|
||||
<strong>Inspector</strong>
|
||||
</div>
|
||||
<div className="dataflow-inspector-empty">No node selected</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
const updateConfig = (patch: Record<string, unknown>) => {
|
||||
onChange({ ...node, config: { ...node.config, ...patch } });
|
||||
};
|
||||
|
||||
const commitRows = () => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(rowsText);
|
||||
if (!Array.isArray(parsed) || parsed.some((item) => !isRecord(item))) {
|
||||
throw new Error("Rows must be a JSON array of objects.");
|
||||
}
|
||||
setLocalError("");
|
||||
updateConfig({ rows: parsed });
|
||||
} catch (error) {
|
||||
setLocalError(error instanceof Error ? error.message : "Rows could not be parsed.");
|
||||
}
|
||||
};
|
||||
|
||||
const commitAggregates = () => {
|
||||
try {
|
||||
const parsed = aggregatesFromText(aggregateText);
|
||||
setLocalError("");
|
||||
updateConfig({ aggregates: parsed });
|
||||
} catch (error) {
|
||||
setLocalError(error instanceof Error ? error.message : "Aggregates could not be parsed.");
|
||||
}
|
||||
};
|
||||
|
||||
const commitSort = () => {
|
||||
try {
|
||||
const parsed = sortFieldsFromText(sortText);
|
||||
setLocalError("");
|
||||
updateConfig({ fields: parsed });
|
||||
} catch (error) {
|
||||
setLocalError(error instanceof Error ? error.message : "Sort fields could not be parsed.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="dataflow-inspector" aria-label="Node inspector">
|
||||
<div className="dataflow-panel-heading">
|
||||
<span>
|
||||
<strong>Inspector</strong>
|
||||
<small>{node.type}</small>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="dataflow-inspector-delete"
|
||||
onClick={() => onDelete(node.id)}
|
||||
disabled={readOnly}
|
||||
aria-label="Delete node"
|
||||
title="Delete node"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="dataflow-inspector-fields">
|
||||
{localError ? (
|
||||
<DismissibleAlert tone="danger" resetKey={localError}>
|
||||
{localError}
|
||||
</DismissibleAlert>
|
||||
) : null}
|
||||
<FormField label="Name">
|
||||
<input
|
||||
value={node.label}
|
||||
onChange={(event) => onChange({ ...node, label: event.target.value })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
{node.type.startsWith("source.") ? (
|
||||
<FormField label="Logical source name">
|
||||
<input
|
||||
value={textValue(node.config.source_name)}
|
||||
onChange={(event) => updateConfig({ source_name: event.target.value })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
{node.type === "source.inline" ? (
|
||||
<FormField label="Rows">
|
||||
<textarea
|
||||
className="dataflow-json-editor"
|
||||
value={rowsText}
|
||||
onChange={(event) => setRowsText(event.target.value)}
|
||||
onBlur={commitRows}
|
||||
spellCheck={false}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
{node.type === "filter" ? (
|
||||
<>
|
||||
<FormField label="Column">
|
||||
<input
|
||||
value={textValue(node.config.column)}
|
||||
onChange={(event) => updateConfig({ column: event.target.value })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Operator">
|
||||
<select
|
||||
value={textValue(node.config.operator) || "eq"}
|
||||
onChange={(event) => updateConfig({ operator: event.target.value })}
|
||||
disabled={readOnly}
|
||||
>
|
||||
<option value="eq">equals</option>
|
||||
<option value="ne">does not equal</option>
|
||||
<option value="gt">greater than</option>
|
||||
<option value="gte">greater than or equal</option>
|
||||
<option value="lt">less than</option>
|
||||
<option value="lte">less than or equal</option>
|
||||
<option value="contains">contains</option>
|
||||
<option value="is_null">is null</option>
|
||||
<option value="not_null">is not null</option>
|
||||
</select>
|
||||
</FormField>
|
||||
{!["is_null", "not_null"].includes(textValue(node.config.operator)) ? (
|
||||
<FormField label="Value">
|
||||
<input
|
||||
value={displayScalar(node.config.value)}
|
||||
onChange={(event) => updateConfig({ value: parseScalar(event.target.value) })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{node.type === "select" ? (
|
||||
<FormField label="Columns">
|
||||
<input
|
||||
value={selectFieldsToText(node.config.fields)}
|
||||
onChange={(event) => updateConfig({ fields: selectFieldsFromText(event.target.value) })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
{node.type === "aggregate" ? (
|
||||
<>
|
||||
<FormField label="Group by">
|
||||
<input
|
||||
value={stringList(node.config.group_by).join(", ")}
|
||||
onChange={(event) => updateConfig({ group_by: commaList(event.target.value) })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Aggregates">
|
||||
<textarea
|
||||
className="dataflow-expression-editor"
|
||||
value={aggregateText}
|
||||
onChange={(event) => setAggregateText(event.target.value)}
|
||||
onBlur={commitAggregates}
|
||||
spellCheck={false}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
</>
|
||||
) : null}
|
||||
{node.type === "sort" ? (
|
||||
<FormField label="Sort fields">
|
||||
<textarea
|
||||
className="dataflow-expression-editor"
|
||||
value={sortText}
|
||||
onChange={(event) => setSortText(event.target.value)}
|
||||
onBlur={commitSort}
|
||||
spellCheck={false}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
{node.type === "limit" ? (
|
||||
<FormField label="Maximum rows">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={100000}
|
||||
value={numberValue(node.config.count, 100)}
|
||||
onChange={(event) => updateConfig({ count: Number(event.target.value) })}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
</FormField>
|
||||
) : null}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function textValue(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function numberValue(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function displayScalar(value: unknown): string {
|
||||
if (value === null) return "null";
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||
return "";
|
||||
}
|
||||
|
||||
function parseScalar(value: string): string | number | boolean | null {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === "null") return null;
|
||||
if (trimmed === "true") return true;
|
||||
if (trimmed === "false") return false;
|
||||
if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) return Number(trimmed);
|
||||
return value;
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
|
||||
}
|
||||
|
||||
function commaList(value: string): string[] {
|
||||
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function selectFieldsToText(value: unknown): string {
|
||||
if (!Array.isArray(value)) return "";
|
||||
return value.map((item) => {
|
||||
if (typeof item === "string") return item;
|
||||
if (!isRecord(item)) return "";
|
||||
const column = textValue(item.column);
|
||||
const alias = textValue(item.alias);
|
||||
return alias && alias !== column ? `${column} as ${alias}` : column;
|
||||
}).filter(Boolean).join(", ");
|
||||
}
|
||||
|
||||
function selectFieldsFromText(value: string): Array<{ column: string; alias: string }> {
|
||||
return commaList(value).map((item) => {
|
||||
const match = item.match(/^(.+?)\s+as\s+(.+)$/i);
|
||||
const column = (match?.[1] ?? item).trim();
|
||||
return { column, alias: (match?.[2] ?? column).trim() };
|
||||
});
|
||||
}
|
||||
|
||||
function aggregatesToText(value: unknown): string {
|
||||
if (!Array.isArray(value)) return "";
|
||||
return value.map((item) => {
|
||||
if (!isRecord(item)) return "";
|
||||
return `${textValue(item.function)}(${textValue(item.column) || "*"}) as ${textValue(item.alias)}`;
|
||||
}).filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function aggregatesFromText(value: string): Array<Record<string, string>> {
|
||||
const lines = value.split("\n").map((line) => line.trim()).filter(Boolean);
|
||||
if (!lines.length) throw new Error("Add at least one aggregate.");
|
||||
return lines.map((line) => {
|
||||
const match = line.match(/^(count|sum|avg|min|max)\(([^)]+)\)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/i);
|
||||
if (!match) throw new Error(`Invalid aggregate: ${line}`);
|
||||
return {
|
||||
function: match[1].toLowerCase(),
|
||||
column: match[2].trim(),
|
||||
alias: match[3]
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sortFieldsToText(value: unknown): string {
|
||||
if (!Array.isArray(value)) return "";
|
||||
return value.map((item) => {
|
||||
if (!isRecord(item)) return "";
|
||||
return `${textValue(item.column)} ${textValue(item.direction) || "asc"}`;
|
||||
}).filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function sortFieldsFromText(value: string): Array<Record<string, string>> {
|
||||
const lines = value.split("\n").map((line) => line.trim()).filter(Boolean);
|
||||
if (!lines.length) throw new Error("Add at least one sort field.");
|
||||
return lines.map((line) => {
|
||||
const match = line.match(/^(.+?)(?:\s+(asc|desc))?$/i);
|
||||
const column = match?.[1]?.trim() ?? "";
|
||||
if (!column) throw new Error(`Invalid sort field: ${line}`);
|
||||
return { column, direction: (match?.[2] ?? "asc").toLowerCase() };
|
||||
});
|
||||
}
|
||||
177
webui/src/features/dataflow/model.ts
Normal file
177
webui/src/features/dataflow/model.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
import type {
|
||||
EditorMode,
|
||||
Pipeline,
|
||||
PipelineGraph,
|
||||
PipelineGraphNode,
|
||||
PipelinePayload,
|
||||
PipelineStatus
|
||||
} from "../../api/dataflow";
|
||||
|
||||
export type PipelineDraft = {
|
||||
id: string | null;
|
||||
currentRevision: number | null;
|
||||
name: string;
|
||||
description: string;
|
||||
status: PipelineStatus;
|
||||
graph: PipelineGraph;
|
||||
sqlText: string;
|
||||
editorMode: EditorMode;
|
||||
};
|
||||
|
||||
export const NODE_LABELS: Record<string, string> = {
|
||||
"source.inline": "Inline source",
|
||||
"source.reference": "Connector source",
|
||||
filter: "Filter rows",
|
||||
select: "Select columns",
|
||||
aggregate: "Aggregate",
|
||||
sort: "Sort rows",
|
||||
limit: "Limit rows",
|
||||
output: "Output"
|
||||
};
|
||||
|
||||
export const PALETTE_NODE_TYPES = [
|
||||
"source.inline",
|
||||
"filter",
|
||||
"select",
|
||||
"aggregate",
|
||||
"sort",
|
||||
"limit",
|
||||
"output"
|
||||
] as const;
|
||||
|
||||
export function draftFromPipeline(pipeline: Pipeline): PipelineDraft {
|
||||
return {
|
||||
id: pipeline.id,
|
||||
currentRevision: pipeline.current_revision,
|
||||
name: pipeline.name,
|
||||
description: pipeline.description ?? "",
|
||||
status: pipeline.status,
|
||||
graph: structuredClone(pipeline.revision.graph),
|
||||
sqlText: pipeline.revision.sql_text ?? "",
|
||||
editorMode: pipeline.revision.editor_mode
|
||||
};
|
||||
}
|
||||
|
||||
export function sampleDraft(): PipelineDraft {
|
||||
return {
|
||||
id: null,
|
||||
currentRevision: null,
|
||||
name: "Monthly case overview",
|
||||
description: "Filter open cases and aggregate their value by district.",
|
||||
status: "draft",
|
||||
editorMode: "graph",
|
||||
sqlText: "",
|
||||
graph: {
|
||||
schema_version: 1,
|
||||
nodes: [
|
||||
{
|
||||
id: "source",
|
||||
type: "source.inline",
|
||||
label: "Monthly cases",
|
||||
position: { x: 60, y: 170 },
|
||||
config: {
|
||||
source_name: "monthly_cases",
|
||||
rows: [
|
||||
{ case_id: "A-1001", district: "North", status: "open", amount: 1200 },
|
||||
{ case_id: "A-1002", district: "South", status: "closed", amount: 800 },
|
||||
{ case_id: "A-1003", district: "North", status: "open", amount: 450 },
|
||||
{ case_id: "A-1004", district: "West", status: "open", amount: 2100 },
|
||||
{ case_id: "A-1005", district: "South", status: "open", amount: 650 }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "filter-open",
|
||||
type: "filter",
|
||||
label: "Only open cases",
|
||||
position: { x: 300, y: 170 },
|
||||
config: { column: "status", operator: "eq", value: "open" }
|
||||
},
|
||||
{
|
||||
id: "aggregate-district",
|
||||
type: "aggregate",
|
||||
label: "Totals by district",
|
||||
position: { x: 540, y: 170 },
|
||||
config: {
|
||||
group_by: ["district"],
|
||||
aggregates: [
|
||||
{ function: "count", column: "*", alias: "cases" },
|
||||
{ function: "sum", column: "amount", alias: "total_amount" }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "sort-total",
|
||||
type: "sort",
|
||||
label: "Largest total first",
|
||||
position: { x: 780, y: 170 },
|
||||
config: { fields: [{ column: "total_amount", direction: "desc" }] }
|
||||
},
|
||||
{
|
||||
id: "output",
|
||||
type: "output",
|
||||
label: "Preview output",
|
||||
position: { x: 1020, y: 170 },
|
||||
config: {}
|
||||
}
|
||||
],
|
||||
edges: [
|
||||
{ id: "source-filter", source: "source", target: "filter-open" },
|
||||
{ id: "filter-aggregate", source: "filter-open", target: "aggregate-district" },
|
||||
{ id: "aggregate-sort", source: "aggregate-district", target: "sort-total" },
|
||||
{ id: "sort-output", source: "sort-total", target: "output" }
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function pipelinePayload(draft: PipelineDraft): PipelinePayload {
|
||||
return {
|
||||
name: draft.name.trim(),
|
||||
description: draft.description.trim() || null,
|
||||
status: draft.status,
|
||||
graph: draft.graph,
|
||||
sql_text: draft.sqlText.trim() || null,
|
||||
editor_mode: draft.editorMode
|
||||
};
|
||||
}
|
||||
|
||||
export function sourceNodes(graph: PipelineGraph): PipelineGraphNode[] {
|
||||
return graph.nodes.filter((node) => node.type.startsWith("source."));
|
||||
}
|
||||
|
||||
export function draftFingerprint(draft: PipelineDraft | null): string {
|
||||
if (!draft) return "";
|
||||
return JSON.stringify({
|
||||
name: draft.name,
|
||||
description: draft.description,
|
||||
status: draft.status,
|
||||
graph: draft.graph,
|
||||
sqlText: draft.sqlText,
|
||||
editorMode: draft.editorMode
|
||||
});
|
||||
}
|
||||
|
||||
export function newNode(type: string, position: { x: number; y: number }): PipelineGraphNode {
|
||||
const id = `${type.replace(".", "-")}-${crypto.randomUUID()}`;
|
||||
const config: Record<string, unknown> = defaultNodeConfig(type);
|
||||
return {
|
||||
id,
|
||||
type,
|
||||
label: NODE_LABELS[type] ?? type,
|
||||
position,
|
||||
config
|
||||
};
|
||||
}
|
||||
|
||||
function defaultNodeConfig(type: string): Record<string, unknown> {
|
||||
if (type === "source.inline") return { source_name: "new_source", rows: [] };
|
||||
if (type === "filter") return { column: "", operator: "eq", value: "" };
|
||||
if (type === "select") return { fields: [{ column: "", alias: "" }] };
|
||||
if (type === "aggregate") {
|
||||
return { group_by: [], aggregates: [{ function: "count", column: "*", alias: "row_count" }] };
|
||||
}
|
||||
if (type === "sort") return { fields: [{ column: "", direction: "asc" }] };
|
||||
if (type === "limit") return { count: 100 };
|
||||
return {};
|
||||
}
|
||||
2
webui/src/index.ts
Normal file
2
webui/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { dataflowModule as default, dataflowModule } from "./module";
|
||||
export * from "./api/dataflow";
|
||||
38
webui/src/module.ts
Normal file
38
webui/src/module.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { createElement, lazy } from "react";
|
||||
import type { PlatformWebModule } from "@govoplan/core-webui";
|
||||
import "./styles/dataflow.css";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
|
||||
const DataflowPage = lazy(() => import("./features/dataflow/DataflowPage"));
|
||||
|
||||
const readScopes = ["dataflow:pipeline:read", "dataflow:pipeline:admin"];
|
||||
|
||||
export const dataflowModule: PlatformWebModule = {
|
||||
id: "dataflow",
|
||||
label: "Dataflow",
|
||||
version: "0.1.14",
|
||||
optionalDependencies: [
|
||||
"access",
|
||||
"audit",
|
||||
"connectors",
|
||||
"files",
|
||||
"notifications",
|
||||
"policy",
|
||||
"reporting",
|
||||
"risk_compliance",
|
||||
"workflow"
|
||||
],
|
||||
navItems: [
|
||||
{ to: "/dataflow", label: "Dataflow", iconName: "waypoints", anyOf: readScopes, order: 72 }
|
||||
],
|
||||
routes: [
|
||||
{
|
||||
path: "/dataflow",
|
||||
anyOf: readScopes,
|
||||
order: 72,
|
||||
render: ({ settings, auth }) => createElement(DataflowPage, { settings, auth })
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
export default dataflowModule;
|
||||
853
webui/src/styles/dataflow.css
Normal file
853
webui/src/styles/dataflow.css
Normal file
@@ -0,0 +1,853 @@
|
||||
.dataflow-page {
|
||||
position: relative;
|
||||
height: calc(100vh - 115px);
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.dataflow-page *,
|
||||
.dataflow-page *::before,
|
||||
.dataflow-page *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.dataflow-shell {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(250px, 300px) minmax(0, 1fr);
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
border: var(--border-line);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.dataflow-pipeline-panel,
|
||||
.dataflow-workspace,
|
||||
.dataflow-editor,
|
||||
.dataflow-editor-surface,
|
||||
.dataflow-canvas,
|
||||
.dataflow-pipeline-list-frame {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border-right: var(--border-line);
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
|
||||
.dataflow-panel-toolbar,
|
||||
.dataflow-workspace-toolbar,
|
||||
.dataflow-results-toolbar,
|
||||
.dataflow-sql-toolbar,
|
||||
.dataflow-panel-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex: 0 0 auto;
|
||||
border-bottom: var(--border-line);
|
||||
background: var(--panel-header);
|
||||
}
|
||||
|
||||
.dataflow-panel-toolbar {
|
||||
min-height: 52px;
|
||||
padding: 8px 10px 8px 14px;
|
||||
}
|
||||
|
||||
.dataflow-toolbar-actions,
|
||||
.dataflow-command-bar,
|
||||
.dataflow-identity-fields,
|
||||
.dataflow-results-toolbar .segmented-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-search {
|
||||
padding: 10px;
|
||||
border-bottom: var(--border-line);
|
||||
}
|
||||
|
||||
.dataflow-pipeline-search input {
|
||||
min-height: 34px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list-frame {
|
||||
flex: 1 1 auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list > button {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 56px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
padding: 8px 9px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list > button:hover,
|
||||
.dataflow-pipeline-list > button:focus-visible {
|
||||
background: var(--primary-soft);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list > button.is-selected {
|
||||
background: var(--primary-soft-strong);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list > button > span:first-child {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list strong,
|
||||
.dataflow-pipeline-list small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list strong {
|
||||
color: var(--text-strong);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list small {
|
||||
margin-top: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-list .status-badge {
|
||||
max-width: 74px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.dataflow-pipeline-empty,
|
||||
.dataflow-inspector-empty,
|
||||
.dataflow-results-empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 100px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.dataflow-workspace {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.dataflow-workspace-toolbar {
|
||||
min-height: 58px;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.dataflow-identity-fields {
|
||||
min-width: 260px;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.dataflow-identity-fields input,
|
||||
.dataflow-identity-fields select {
|
||||
min-height: 34px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
|
||||
.dataflow-name-input {
|
||||
max-width: 260px;
|
||||
color: var(--text-strong);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dataflow-description-input {
|
||||
min-width: 140px;
|
||||
flex: 1 1 240px;
|
||||
}
|
||||
|
||||
.dataflow-identity-fields select {
|
||||
width: 104px;
|
||||
flex: 0 0 104px;
|
||||
}
|
||||
|
||||
.dataflow-command-bar {
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.dataflow-command-bar .btn,
|
||||
.dataflow-sql-toolbar .btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 34px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-command-bar .segmented-control-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.dataflow-alerts {
|
||||
position: absolute;
|
||||
z-index: 12;
|
||||
top: 66px;
|
||||
right: 12px;
|
||||
display: grid;
|
||||
width: min(500px, calc(100% - 24px));
|
||||
gap: 6px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.dataflow-alerts .alert {
|
||||
pointer-events: auto;
|
||||
box-shadow: var(--shadow-popover);
|
||||
}
|
||||
|
||||
.dataflow-editor {
|
||||
flex: 1 1 auto;
|
||||
display: grid;
|
||||
grid-template-columns: 170px minmax(0, 1fr) minmax(260px, 310px);
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.dataflow-editor.is-sql {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(260px, 310px);
|
||||
}
|
||||
|
||||
.dataflow-palette,
|
||||
.dataflow-inspector {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
|
||||
.dataflow-palette {
|
||||
border-right: var(--border-line);
|
||||
}
|
||||
|
||||
.dataflow-inspector {
|
||||
border-left: var(--border-line);
|
||||
}
|
||||
|
||||
.dataflow-panel-heading {
|
||||
min-height: 44px;
|
||||
padding: 8px 10px 8px 12px;
|
||||
}
|
||||
|
||||
.dataflow-panel-heading > span {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dataflow-panel-heading strong,
|
||||
.dataflow-panel-heading small {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.dataflow-panel-heading strong {
|
||||
color: var(--text-strong);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.dataflow-panel-heading small {
|
||||
overflow: hidden;
|
||||
margin-top: 2px;
|
||||
color: var(--muted);
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 10px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-palette-items {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding: 8px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.dataflow-palette-items button {
|
||||
display: grid;
|
||||
grid-template-columns: 18px minmax(0, 1fr) 14px;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 38px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
cursor: grab;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
padding: 7px 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dataflow-palette-items button:hover:not(:disabled),
|
||||
.dataflow-palette-items button:focus-visible:not(:disabled) {
|
||||
background: var(--primary-soft);
|
||||
color: var(--text-strong);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.dataflow-palette-items button:active:not(:disabled) {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.dataflow-palette-items button:disabled {
|
||||
cursor: default;
|
||||
opacity: .42;
|
||||
}
|
||||
|
||||
.dataflow-palette-add {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.dataflow-editor-surface {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.dataflow-canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__background {
|
||||
color: var(--line-dark);
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__controls,
|
||||
.dataflow-canvas .react-flow__minimap {
|
||||
overflow: hidden;
|
||||
border: var(--border-line);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow-xs);
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__controls-button {
|
||||
border-bottom: var(--border-line);
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__minimap-mask {
|
||||
fill: color-mix(in srgb, var(--bg) 76%, transparent);
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__edge-path {
|
||||
stroke: var(--line-dark);
|
||||
stroke-width: 2;
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__edge.selected .react-flow__edge-path,
|
||||
.dataflow-canvas .react-flow__edge:hover .react-flow__edge-path {
|
||||
stroke: var(--accent);
|
||||
stroke-width: 3;
|
||||
}
|
||||
|
||||
.dataflow-canvas .react-flow__connection-path {
|
||||
stroke: var(--accent);
|
||||
stroke-width: 3;
|
||||
}
|
||||
|
||||
.dataflow-canvas-empty {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.dataflow-node {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
width: 180px;
|
||||
min-height: 54px;
|
||||
border: 1px solid var(--line-dark);
|
||||
border-left: 4px solid #3d6f9e;
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow-xs);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.dataflow-node-source-inline,
|
||||
.dataflow-node-source-reference {
|
||||
border-left-color: #2f7d6d;
|
||||
}
|
||||
|
||||
.dataflow-node-filter {
|
||||
border-left-color: #b7791f;
|
||||
}
|
||||
|
||||
.dataflow-node-aggregate {
|
||||
border-left-color: #76569b;
|
||||
}
|
||||
|
||||
.dataflow-node-sort {
|
||||
border-left-color: #3d6f9e;
|
||||
}
|
||||
|
||||
.dataflow-node-output {
|
||||
border-left-color: #9d4e63;
|
||||
}
|
||||
|
||||
.dataflow-node.is-selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 24%, transparent), var(--shadow-xs);
|
||||
}
|
||||
|
||||
.dataflow-node.has-error {
|
||||
border-color: var(--danger-text);
|
||||
}
|
||||
|
||||
.dataflow-node-icon {
|
||||
display: grid;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex: 0 0 28px;
|
||||
place-items: center;
|
||||
border-radius: 5px;
|
||||
background: var(--panel-soft);
|
||||
color: var(--text-strong);
|
||||
}
|
||||
|
||||
.dataflow-node-copy {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.dataflow-node-copy strong,
|
||||
.dataflow-node-copy small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-node-copy strong {
|
||||
color: var(--text-strong);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.dataflow-node-copy small {
|
||||
margin-top: 3px;
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.dataflow-node-count {
|
||||
min-width: 22px;
|
||||
border-radius: 999px;
|
||||
background: var(--primary-soft);
|
||||
color: var(--text-strong);
|
||||
font-size: 10px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
padding: 3px 5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.dataflow-node-handle {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 3px solid var(--panel);
|
||||
background: var(--line-dark);
|
||||
}
|
||||
|
||||
.dataflow-node-handle:hover,
|
||||
.dataflow-node-handle.connectingto,
|
||||
.dataflow-node-handle.valid {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
height: calc(100% - 44px);
|
||||
overflow: auto;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields .form-field {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields input,
|
||||
.dataflow-inspector-fields select,
|
||||
.dataflow-inspector-fields textarea {
|
||||
margin-top: 5px;
|
||||
padding: 7px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.dataflow-json-editor {
|
||||
min-height: 190px;
|
||||
resize: vertical;
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
line-height: 1.45;
|
||||
tab-size: 2;
|
||||
}
|
||||
|
||||
.dataflow-expression-editor {
|
||||
min-height: 78px;
|
||||
resize: vertical;
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.dataflow-inspector-delete {
|
||||
color: var(--danger-text);
|
||||
}
|
||||
|
||||
.dataflow-sql-workbench {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dataflow-sql-toolbar {
|
||||
min-height: 44px;
|
||||
padding: 7px 10px 7px 14px;
|
||||
color: var(--text-strong);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dataflow-sql-workbench > textarea {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
resize: none;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text-strong);
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.65;
|
||||
padding: 20px;
|
||||
tab-size: 2;
|
||||
}
|
||||
|
||||
.dataflow-sql-workbench > textarea:focus {
|
||||
outline: 2px solid color-mix(in srgb, var(--accent) 46%, transparent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.dataflow-results {
|
||||
flex: 0 0 clamp(190px, 28vh, 320px);
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border-top: var(--border-line-dark);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.dataflow-results-toolbar {
|
||||
min-height: 42px;
|
||||
padding: 5px 9px;
|
||||
}
|
||||
|
||||
.dataflow-results-toolbar .btn {
|
||||
min-height: 30px;
|
||||
}
|
||||
|
||||
.dataflow-preview-table-wrap,
|
||||
.dataflow-diagnostics-list {
|
||||
min-height: 0;
|
||||
flex: 1 1 auto;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.dataflow-preview-table {
|
||||
width: 100%;
|
||||
min-width: max-content;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.dataflow-preview-table th,
|
||||
.dataflow-preview-table td {
|
||||
min-width: 130px;
|
||||
max-width: 360px;
|
||||
border-right: var(--border-line);
|
||||
border-bottom: var(--border-line);
|
||||
padding: 7px 10px;
|
||||
overflow: hidden;
|
||||
text-align: left;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-preview-table th {
|
||||
position: sticky;
|
||||
z-index: 2;
|
||||
top: 0;
|
||||
background: var(--panel-soft);
|
||||
color: var(--text-strong);
|
||||
}
|
||||
|
||||
.dataflow-preview-table th span,
|
||||
.dataflow-preview-table th small {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.dataflow-preview-table th small {
|
||||
margin-top: 2px;
|
||||
color: var(--muted);
|
||||
font-size: 9px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.dataflow-preview-table tbody tr:hover {
|
||||
background: var(--primary-soft);
|
||||
}
|
||||
|
||||
.dataflow-preview-truncated {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
padding: 6px 10px;
|
||||
border-top: var(--border-line);
|
||||
background: var(--panel-header);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list > div {
|
||||
display: grid;
|
||||
grid-template-columns: 18px minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 44px;
|
||||
border-bottom: var(--border-line);
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list > div.is-error {
|
||||
color: var(--danger-text);
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list > div.is-warning {
|
||||
color: var(--warning-deep);
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list span {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list strong,
|
||||
.dataflow-diagnostics-list small {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list small {
|
||||
margin-top: 2px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.dataflow-diagnostics-list code {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dataflow-workspace-empty {
|
||||
display: grid;
|
||||
place-content: center;
|
||||
justify-items: center;
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.dataflow-workspace-empty strong {
|
||||
color: var(--text-strong);
|
||||
}
|
||||
|
||||
.dataflow-workspace-empty .btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.dataflow-working-indicator {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
right: 12px;
|
||||
bottom: 10px;
|
||||
border: var(--border-line-dark);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow-popover);
|
||||
color: var(--text-strong);
|
||||
font-size: 12px;
|
||||
padding: 7px 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.dataflow-shell {
|
||||
grid-template-columns: 240px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.dataflow-workspace-toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dataflow-command-bar {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.dataflow-editor {
|
||||
grid-template-columns: 150px minmax(0, 1fr) 270px;
|
||||
}
|
||||
|
||||
.dataflow-editor.is-sql {
|
||||
grid-template-columns: minmax(0, 1fr) 270px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.dataflow-shell {
|
||||
grid-template-columns: 210px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.dataflow-editor {
|
||||
grid-template-columns: 135px minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr) minmax(170px, 32%);
|
||||
}
|
||||
|
||||
.dataflow-editor.is-sql {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr) minmax(170px, 32%);
|
||||
}
|
||||
|
||||
.dataflow-inspector {
|
||||
grid-column: 1 / -1;
|
||||
border-top: var(--border-line);
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
height: calc(100% - 44px);
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields .alert,
|
||||
.dataflow-inspector-fields .dataflow-json-editor {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.dataflow-page {
|
||||
height: calc(100vh - 94px);
|
||||
}
|
||||
|
||||
.dataflow-shell {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: minmax(150px, 24%) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.dataflow-pipeline-panel {
|
||||
border-right: 0;
|
||||
border-bottom: var(--border-line);
|
||||
}
|
||||
|
||||
.dataflow-identity-fields,
|
||||
.dataflow-command-bar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.dataflow-name-input,
|
||||
.dataflow-description-input {
|
||||
max-width: none;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.dataflow-editor {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: auto minmax(0, 1fr) minmax(160px, 30%);
|
||||
}
|
||||
|
||||
.dataflow-palette {
|
||||
border-right: 0;
|
||||
border-bottom: var(--border-line);
|
||||
}
|
||||
|
||||
.dataflow-palette .dataflow-panel-heading {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.dataflow-palette-items {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.dataflow-palette-items button {
|
||||
min-width: 128px;
|
||||
}
|
||||
|
||||
.dataflow-inspector-fields {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.dataflow-results {
|
||||
flex-basis: 220px;
|
||||
}
|
||||
}
|
||||
1
webui/src/vite-env.d.ts
vendored
Normal file
1
webui/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference path="../../../govoplan-core/webui/src/vite-env.d.ts" />
|
||||
32
webui/tsconfig.json
Normal file
32
webui/tsconfig.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"preserveSymlinks": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@govoplan/core-webui": ["../../govoplan-core/webui/src/index.ts"],
|
||||
"@govoplan/core-webui/*": ["../../govoplan-core/webui/src/*"],
|
||||
"@xyflow/react": ["../../govoplan-core/webui/node_modules/@xyflow/react/dist/esm/index.d.ts"],
|
||||
"lucide-react": ["../../govoplan-core/webui/node_modules/lucide-react/dist/lucide-react.d.ts"],
|
||||
"react": ["../../govoplan-core/webui/node_modules/@types/react/index.d.ts"],
|
||||
"react/jsx-runtime": ["../../govoplan-core/webui/node_modules/@types/react/jsx-runtime.d.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user