@surfaces-ui/pipelines 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Surfaces UI
2
+ Copyright 2026 Josh Schoen
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-readmes.mjs from package.json. Edit the script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @surfaces-ui/pipelines
4
+
5
+ Reference pipeline runner for Surfaces UI: builds datasets from one another on an Engine, with data quality rules.
6
+
7
+ The reference pipeline runner: builds datasets from one another on an engine, in dependency order, with row rules and checks over what was built. Runs only definitions a person approved.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @surfaces-ui/pipelines
13
+ ```
14
+
15
+ ## Part of Surfaces UI
16
+
17
+ Surfaces UI is a UI library for data and analytics: exploring schemas, querying, charting, tables at scale, chat, and pages an agent can build.
18
+
19
+ - [Getting started](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/getting-started.md)
20
+ - [Building with an agent](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/agent-integration.md)
21
+ - [Styling](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/styling.md)
22
+ - [Source for this package](https://github.com/teradata-labs/surfaces-ui/tree/main/packages/pipelines)
23
+
24
+ Licensed under Apache-2.0. See LICENSE and NOTICE.
@@ -0,0 +1,157 @@
1
+ import { type Pipelines } from "@surfaces-ui/data";
2
+ import type { Engine } from "@surfaces-ui/engine";
3
+ import { type Dataset, type PipelineDraft, type Run } from "@surfaces-ui/proto";
4
+ export interface ExpectationDefinition {
5
+ name: string;
6
+ /** A condition every record should meet, e.g. `amount >= 0`. */
7
+ constraint: string;
8
+ /** What happens to a record that breaks it. Defaults to "warn". */
9
+ action?: "warn" | "drop" | "fail";
10
+ }
11
+ /** A test over the whole built dataset: what a row-level expectation cannot say. */
12
+ export interface CheckDefinition {
13
+ kind: "unique" | "not_null" | "relationships" | "accepted_values" | "row_count";
14
+ /** The column, or for "unique" the columns that together must not repeat. */
15
+ columns?: string[];
16
+ /** "relationships": the dataset or table, and column, every value must be found in. */
17
+ to?: {
18
+ table: string;
19
+ column: string;
20
+ };
21
+ /** "accepted_values": the values allowed, compared as text. */
22
+ values?: string[];
23
+ /** "row_count" bounds. */
24
+ min?: number;
25
+ max?: number;
26
+ /** "fail" (default) counts the dataset as failed, so what reads it is not built; "warn" reports it. */
27
+ severity?: "warn" | "fail";
28
+ name?: string;
29
+ }
30
+ export interface ColumnDefinition {
31
+ name: string;
32
+ type?: string;
33
+ description?: string;
34
+ }
35
+ export interface DatasetDefinition {
36
+ /** The table's name. Other datasets read it by this name. */
37
+ name: string;
38
+ /** "table" (default) is rebuilt on each run; "view" runs its query when read. */
39
+ kind?: "table" | "view";
40
+ layer?: "bronze" | "silver" | "gold";
41
+ description?: string;
42
+ /** A single SELECT. It may read the source's tables and other datasets of the pipeline. */
43
+ sql: string;
44
+ /**
45
+ * The datasets and source tables it reads. Left out, they are worked out
46
+ * from the query's text, which can mistake a name that only appears in it
47
+ * (a column or an alias) for one it reads.
48
+ */
49
+ depends?: string[];
50
+ /** What one row is, in a sentence: "one row per order line". */
51
+ grain?: string;
52
+ /** The columns that pick out one row. They are checked unique and not empty after every build. */
53
+ primaryKey?: string[];
54
+ columns?: ColumnDefinition[];
55
+ expectations?: ExpectationDefinition[];
56
+ checks?: CheckDefinition[];
57
+ tags?: string[];
58
+ owner?: string;
59
+ }
60
+ export interface PipelineDefinition {
61
+ id: string;
62
+ name?: string;
63
+ description?: string;
64
+ /** The source whose engine builds the datasets. They can then be queried through it. */
65
+ sourceId: string;
66
+ datasets: DatasetDefinition[];
67
+ }
68
+ /** A pipeline someone saved, with every version kept. */
69
+ export interface SavedPipeline {
70
+ definition: PipelineDefinition;
71
+ version: number;
72
+ versions: {
73
+ version: number;
74
+ savedAt: string;
75
+ approvedBy: string;
76
+ note: string;
77
+ definition: PipelineDefinition;
78
+ }[];
79
+ }
80
+ /** Where saved pipelines live. The dev server keeps one JSON file per pipeline. */
81
+ export interface PipelineStore {
82
+ list(): Promise<SavedPipeline[]>;
83
+ put(saved: SavedPipeline): Promise<void>;
84
+ }
85
+ /** Where runs are kept, so history outlives the process. */
86
+ export interface RunStore {
87
+ /** Every pipeline's runs, newest first. */
88
+ load(): Promise<Run[]>;
89
+ /** Called as a run progresses and when it ends; the same ID replaces what was kept. */
90
+ save(run: Run): Promise<void>;
91
+ }
92
+ export interface PipelinesOptions {
93
+ /** Pipelines defined in the server's config. They cannot be changed by a save. */
94
+ pipelines: PipelineDefinition[];
95
+ /** The engine behind a source. It must support `materialize`. */
96
+ engineOf(sourceId: string): Engine | undefined;
97
+ /** Called when a run that built something ends, so caches over the source can be dropped. */
98
+ onFinished?(run: Run, sourceId: string): void;
99
+ /** Runs kept per pipeline. Defaults to 50. */
100
+ historyLimit?: number;
101
+ /** Where runs are kept. Left out, they are kept in memory and lost on restart. */
102
+ runs?: RunStore;
103
+ /**
104
+ * Allows `savePipeline`: pipelines a person approved are checked and kept
105
+ * here, and can be run like the configured ones. Left out, pipelines are
106
+ * fixed.
107
+ */
108
+ saved?: PipelineStore;
109
+ now?: () => Date;
110
+ }
111
+ /**
112
+ * The names a query reads, out of a list of candidates. String literals and
113
+ * comments are ignored, so a name that only appears in text does not count.
114
+ */
115
+ export declare function referencedNames(sql: string, candidates: string[]): string[];
116
+ /**
117
+ * The order to build datasets in: each after everything it reads. Throws a
118
+ * readable error when datasets depend on each other in a circle.
119
+ */
120
+ export declare function buildOrder(inputs: Map<string, string[]>): string[];
121
+ /**
122
+ * The datasets a selection names, given what each reads. "orders" is that
123
+ * dataset alone, "orders+" adds everything that reads it (directly or not),
124
+ * "+orders" adds everything it reads, and "+orders+" both. Names are
125
+ * matched without regard to case; an unknown name is reported.
126
+ */
127
+ export declare function selectDatasets(select: string[], inputs: Map<string, string[]>): {
128
+ selected: Set<string>;
129
+ unknown: string[];
130
+ };
131
+ /** The checks a dataset gets: its own, and for a primary key one that it is unique and one per column that it is never empty. */
132
+ export declare function datasetChecks(dataset: DatasetDefinition): (CheckDefinition & {
133
+ implied?: boolean;
134
+ })[];
135
+ /** A pipeline definition from a draft a person approved. */
136
+ export declare function definitionFromDraft(draft: PipelineDraft): PipelineDefinition;
137
+ /**
138
+ * A reference pipeline backend on any Engine that can `materialize`. Each
139
+ * dataset is a SELECT; a run builds them in dependency order as tables (or
140
+ * views) of the source, applying row-level rules before a build and checks
141
+ * over the whole dataset after it. Every run recomputes whole datasets:
142
+ * there is no incremental or streaming processing, checkpoints or
143
+ * schedules.
144
+ *
145
+ * It runs only definitions it holds: those passed in, and with a `saved`
146
+ * store, ones a person approved through `savePipeline`, which are checked
147
+ * before they are kept. A run request names a pipeline and datasets, never
148
+ * SQL.
149
+ */
150
+ export declare function createPipelines(options: PipelinesOptions): Promise<Pipelines>;
151
+ /** Saved pipelines kept in memory: for tests, and a server with nowhere to write. */
152
+ export declare function memoryPipelineStore(initial?: SavedPipeline[]): PipelineStore;
153
+ /** Runs kept in memory, as a `RunStore`. */
154
+ export declare function memoryRunStore(): RunStore & {
155
+ runs: Run[];
156
+ };
157
+ export type { Dataset };
package/dist/index.js ADDED
@@ -0,0 +1,599 @@
1
+ import { create } from "@bufbuild/protobuf";
2
+ import { checkName, pipelineDigest } from "@surfaces-ui/data";
3
+ import { CancelRunRequestSchema, CancelRunResponseSchema, CheckKind, CheckSeverity, DatasetKind, DatasetRunSchema, ExpectationAction, GetPipelineRequestSchema, GetPipelineResponseSchema, GetRunRequestSchema, GetRunResponseSchema, InspectFilesRequestSchema, InspectFilesResponseSchema, ListPipelineVersionsRequestSchema, ListPipelineVersionsResponseSchema, ListPipelinesResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, PipelineDraftSchema, PipelineSchema, PipelineVersionSchema, RefreshKind, RunSchema, RunState, SavePipelineRequestSchema, SavePipelineResponseSchema, StartRunRequestSchema, StartRunResponseSchema, } from "@surfaces-ui/proto";
4
+ import { SqlError, assertReadOnly, blankLiterals, checkQuery, initSql } from "@surfaces-ui/sql";
5
+ const ACTION = {
6
+ warn: ExpectationAction.WARN,
7
+ drop: ExpectationAction.DROP,
8
+ fail: ExpectationAction.FAIL,
9
+ };
10
+ const ACTION_NAME = new Map([
11
+ [ExpectationAction.WARN, "warn"],
12
+ [ExpectationAction.DROP, "drop"],
13
+ [ExpectationAction.FAIL, "fail"],
14
+ ]);
15
+ const KIND = {
16
+ unique: CheckKind.UNIQUE,
17
+ not_null: CheckKind.NOT_NULL,
18
+ relationships: CheckKind.RELATIONSHIPS,
19
+ accepted_values: CheckKind.ACCEPTED_VALUES,
20
+ row_count: CheckKind.ROW_COUNT,
21
+ };
22
+ const KIND_NAME = new Map(Object.entries(KIND).map(([name, kind]) => [kind, name]));
23
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
+ /** A pipeline ID: also a file name where saved pipelines are kept. */
25
+ const PIPELINE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,80}$/;
26
+ const lower = (name) => name.toLowerCase();
27
+ const plural = (n, one, many) => `${n.toLocaleString("en")} ${n === 1 || n === 1n ? one : many}`;
28
+ /**
29
+ * The names a query reads, out of a list of candidates. String literals and
30
+ * comments are ignored, so a name that only appears in text does not count.
31
+ */
32
+ export function referencedNames(sql, candidates) {
33
+ const bare = blankLiterals(sql).toLowerCase();
34
+ return candidates.filter((name) => new RegExp(`(^|[^\\w$])${lower(name).replace(/[$]/g, "\\$")}($|[^\\w$])`).test(bare));
35
+ }
36
+ /**
37
+ * The order to build datasets in: each after everything it reads. Throws a
38
+ * readable error when datasets depend on each other in a circle.
39
+ */
40
+ export function buildOrder(inputs) {
41
+ const order = [];
42
+ const state = new Map();
43
+ const visit = (name, trail) => {
44
+ if (state.get(name) === "done")
45
+ return;
46
+ if (state.get(name) === "visiting")
47
+ throw new Error(`These datasets depend on each other in a circle: ${[...trail.slice(trail.indexOf(name)), name].join(" → ")}`);
48
+ state.set(name, "visiting");
49
+ for (const input of inputs.get(name) ?? [])
50
+ if (inputs.has(input))
51
+ visit(input, [...trail, name]);
52
+ state.set(name, "done");
53
+ order.push(name);
54
+ };
55
+ for (const name of inputs.keys())
56
+ visit(name, []);
57
+ return order;
58
+ }
59
+ /**
60
+ * The datasets a selection names, given what each reads. "orders" is that
61
+ * dataset alone, "orders+" adds everything that reads it (directly or not),
62
+ * "+orders" adds everything it reads, and "+orders+" both. Names are
63
+ * matched without regard to case; an unknown name is reported.
64
+ */
65
+ export function selectDatasets(select, inputs) {
66
+ const selected = new Set();
67
+ const unknown = [];
68
+ const grow = (start, next) => {
69
+ const seen = new Set([start]);
70
+ for (const queue = [start]; queue.length > 0;) {
71
+ for (const n of next(queue.shift()))
72
+ if (!seen.has(n))
73
+ (seen.add(n), queue.push(n));
74
+ }
75
+ return seen;
76
+ };
77
+ const readers = (name) => [...inputs].filter(([, reads]) => reads.map(lower).includes(name)).map(([n]) => n);
78
+ const reads = (name) => (inputs.get(name) ?? []).map(lower).filter((n) => inputs.has(n));
79
+ for (const item of select) {
80
+ const up = item.startsWith("+");
81
+ const down = item.endsWith("+");
82
+ const name = lower(item.replace(/^\+|\+$/g, "").trim());
83
+ if (!inputs.has(name)) {
84
+ unknown.push(item.replace(/^\+|\+$/g, "").trim());
85
+ continue;
86
+ }
87
+ selected.add(name);
88
+ if (down)
89
+ for (const n of grow(name, readers))
90
+ selected.add(n);
91
+ if (up)
92
+ for (const n of grow(name, reads))
93
+ selected.add(n);
94
+ }
95
+ return { selected, unknown };
96
+ }
97
+ /** The checks a dataset gets: its own, and for a primary key one that it is unique and one per column that it is never empty. */
98
+ export function datasetChecks(dataset) {
99
+ const key = dataset.primaryKey ?? [];
100
+ const implied = key.length === 0 ? [] : [{ kind: "unique", columns: key, implied: true }, ...key.map((column) => ({ kind: "not_null", columns: [column], implied: true }))];
101
+ const own = dataset.checks ?? [];
102
+ const same = (a, b) => a.kind === b.kind && (a.columns ?? []).map(lower).join() === (b.columns ?? []).map(lower).join();
103
+ return [...implied.filter((i) => !own.some((o) => same(o, i))), ...own];
104
+ }
105
+ /** A pipeline definition from a draft a person approved. */
106
+ export function definitionFromDraft(draft) {
107
+ return {
108
+ id: draft.id,
109
+ ...(draft.name && draft.name !== draft.id ? { name: draft.name } : {}),
110
+ ...(draft.description ? { description: draft.description } : {}),
111
+ sourceId: draft.sourceId,
112
+ datasets: draft.datasets.map((d) => ({
113
+ name: d.name,
114
+ ...(d.kind === DatasetKind.VIEW ? { kind: "view" } : {}),
115
+ ...(d.layer === "bronze" || d.layer === "silver" || d.layer === "gold" ? { layer: d.layer } : {}),
116
+ ...(d.description ? { description: d.description } : {}),
117
+ sql: d.sql,
118
+ ...(d.inputs.length > 0 ? { depends: d.inputs } : {}),
119
+ ...(d.grain ? { grain: d.grain } : {}),
120
+ ...(d.primaryKey.length > 0 ? { primaryKey: d.primaryKey } : {}),
121
+ ...(d.columns.length > 0 ? { columns: d.columns.map((c) => ({ name: c.name, ...(c.type ? { type: c.type } : {}), ...(c.description ? { description: c.description } : {}) })) } : {}),
122
+ ...(d.expectations.length > 0 ? { expectations: d.expectations.map((e) => ({ name: e.name, constraint: e.constraint, action: ACTION_NAME.get(e.action) ?? "warn" })) } : {}),
123
+ ...(d.checks.filter((c) => !c.implied).length > 0
124
+ ? {
125
+ checks: d.checks
126
+ .filter((c) => !c.implied)
127
+ .map((c) => ({
128
+ kind: KIND_NAME.get(c.kind) ?? "unique",
129
+ ...(c.columns.length > 0 ? { columns: c.columns } : {}),
130
+ ...(c.toTable ? { to: { table: c.toTable, column: c.toColumn } } : {}),
131
+ ...(c.values.length > 0 ? { values: c.values } : {}),
132
+ ...(c.minRows !== undefined ? { min: Number(c.minRows) } : {}),
133
+ ...(c.maxRows !== undefined ? { max: Number(c.maxRows) } : {}),
134
+ ...(c.severity === CheckSeverity.WARN ? { severity: "warn" } : {}),
135
+ // A name that is only the one made up from the kind and columns is left out.
136
+ ...(c.name && c.name !== checkName({ kind: c.kind, columns: c.columns }) ? { name: c.name } : {}),
137
+ })),
138
+ }
139
+ : {}),
140
+ ...(d.tags.length > 0 ? { tags: d.tags } : {}),
141
+ ...(d.owner ? { owner: d.owner } : {}),
142
+ })),
143
+ };
144
+ }
145
+ /** A check as the `Check` message. */
146
+ function checkMessage(check) {
147
+ return {
148
+ name: checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns }),
149
+ kind: KIND[check.kind],
150
+ columns: check.columns ?? [],
151
+ toTable: check.to?.table ?? "",
152
+ toColumn: check.to?.column ?? "",
153
+ values: check.values ?? [],
154
+ ...(check.min !== undefined ? { minRows: BigInt(check.min) } : {}),
155
+ ...(check.max !== undefined ? { maxRows: BigInt(check.max) } : {}),
156
+ severity: check.severity === "warn" ? CheckSeverity.WARN : CheckSeverity.FAIL,
157
+ implied: check.implied ?? false,
158
+ };
159
+ }
160
+ /** A dataset definition as the `Dataset` message, without run state. */
161
+ function datasetMessage(dataset, inputs) {
162
+ return {
163
+ name: dataset.name,
164
+ kind: dataset.kind === "view" ? DatasetKind.VIEW : DatasetKind.TABLE,
165
+ layer: dataset.layer ?? "",
166
+ description: dataset.description ?? "",
167
+ sql: dataset.sql,
168
+ inputs,
169
+ inputsDeclared: dataset.depends !== undefined,
170
+ expectations: (dataset.expectations ?? []).map((rule) => ({ name: rule.name, constraint: rule.constraint, action: ACTION[rule.action ?? "warn"] })),
171
+ grain: dataset.grain ?? "",
172
+ primaryKey: dataset.primaryKey ?? [],
173
+ columns: (dataset.columns ?? []).map((c) => ({ name: c.name, type: c.type ?? "", description: c.description ?? "" })),
174
+ checks: datasetChecks(dataset).map(checkMessage),
175
+ tags: dataset.tags ?? [],
176
+ owner: dataset.owner ?? "",
177
+ };
178
+ }
179
+ /**
180
+ * A reference pipeline backend on any Engine that can `materialize`. Each
181
+ * dataset is a SELECT; a run builds them in dependency order as tables (or
182
+ * views) of the source, applying row-level rules before a build and checks
183
+ * over the whole dataset after it. Every run recomputes whole datasets:
184
+ * there is no incremental or streaming processing, checkpoints or
185
+ * schedules.
186
+ *
187
+ * It runs only definitions it holds: those passed in, and with a `saved`
188
+ * store, ones a person approved through `savePipeline`, which are checked
189
+ * before they are kept. A run request names a pipeline and datasets, never
190
+ * SQL.
191
+ */
192
+ export async function createPipelines(options) {
193
+ await initSql();
194
+ const now = options.now ?? (() => new Date());
195
+ const historyLimit = options.historyLimit ?? 50;
196
+ const runs = new Map();
197
+ const latest = new Map();
198
+ const cancelling = new Set();
199
+ let counter = 0;
200
+ const configured = new Map();
201
+ for (const definition of options.pipelines) {
202
+ if (configured.has(definition.id))
203
+ throw new Error(`Two pipelines have the ID ${definition.id}.`);
204
+ configured.set(definition.id, definition);
205
+ }
206
+ const saved = new Map();
207
+ for (const pipeline of (await options.saved?.list()) ?? [])
208
+ if (!configured.has(pipeline.definition.id))
209
+ saved.set(pipeline.definition.id, pipeline);
210
+ const find = (id) => {
211
+ const definition = configured.get(id) ?? saved.get(id)?.definition;
212
+ if (!definition)
213
+ throw new Error(`Pipeline not found: ${id}`);
214
+ return definition;
215
+ };
216
+ const versionOf = (id) => saved.get(id)?.version ?? 0;
217
+ /** Remembers each dataset's last finished state from a run. */
218
+ const remember = (run) => {
219
+ for (const result of run.datasetRuns) {
220
+ if (result.state === RunState.RUNNING || result.state === RunState.QUEUED)
221
+ continue;
222
+ const seen = latest.get(run.pipelineId) ?? new Map();
223
+ seen.set(lower(result.name), { ...result, ...(result.state === RunState.COMPLETED ? { builtAt: run.endTime || run.startTime, runId: run.id } : {}) });
224
+ latest.set(run.pipelineId, seen);
225
+ }
226
+ };
227
+ for (const run of [...((await options.runs?.load()) ?? [])].reverse()) {
228
+ // A run the process stopped during is not still going.
229
+ const kept = run.state === RunState.RUNNING ? create(RunSchema, { ...run, state: RunState.CANCELLED, errorMessage: run.errorMessage || "The server stopped during this run." }) : run;
230
+ runs.set(kept.pipelineId, [kept, ...(runs.get(kept.pipelineId) ?? [])].slice(0, historyLimit));
231
+ if (!kept.dryRun)
232
+ remember(kept);
233
+ const n = Number(/^run-(\d+)$/.exec(kept.id)?.[1] ?? 0);
234
+ if (n > counter)
235
+ counter = n;
236
+ }
237
+ /** Checks a pipeline and works out its graph. Every problem found is reported, not just the first. */
238
+ const prepare = async (definition) => {
239
+ const problems = [];
240
+ const engine = options.engineOf(definition.sourceId);
241
+ if (!engine)
242
+ return { problems: [`The source "${definition.sourceId}" is not available.`] };
243
+ if (!engine.materialize)
244
+ return { problems: [`The source "${definition.sourceId}" cannot build tables, so it cannot run pipelines.`] };
245
+ const names = definition.datasets.map((d) => d.name);
246
+ for (const name of names)
247
+ if (!NAME.test(name))
248
+ problems.push(`Dataset names use letters, digits and underscores: ${name}`);
249
+ if (new Set(names.map(lower)).size !== names.length)
250
+ problems.push("Two datasets have the same name.");
251
+ const sources = (await engine.listTables({ catalog: "", schema: "", search: "" })).map((t) => t.ref?.table ?? "").filter((t) => t && !names.some((n) => lower(n) === lower(t)));
252
+ const known = new Set([...names, ...sources].map(lower));
253
+ const inputs = new Map();
254
+ for (const dataset of definition.datasets) {
255
+ try {
256
+ // A dataset is always a single read-only query; the engine wraps it to build the table.
257
+ assertReadOnly(dataset.sql, engine.dialect);
258
+ for (const rule of dataset.expectations ?? [])
259
+ assertReadOnly(`SELECT * FROM (${dataset.sql}) AS "_d" WHERE (${rule.constraint})`, engine.dialect);
260
+ for (const check of datasetChecks(dataset)) {
261
+ if (check.kind === "relationships" && check.to && !known.has(lower(check.to.table)))
262
+ problems.push(`${dataset.name}: the check ${checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns })} looks in ${check.to.table}, which is neither a dataset nor a table of the source.`);
263
+ checkQuery({ kind: KIND[check.kind], columns: check.columns ?? [], toTable: check.to?.table, toColumn: check.to?.column, values: check.values }, dataset.name, engine.dialect);
264
+ }
265
+ }
266
+ catch (error) {
267
+ problems.push(`${dataset.name}: ${error instanceof SqlError ? error.message : error instanceof Error ? error.message : String(error)}`);
268
+ }
269
+ if (dataset.depends) {
270
+ for (const name of dataset.depends)
271
+ if (!known.has(lower(name)))
272
+ problems.push(`${dataset.name} says it reads ${name}, which is neither a dataset nor a table of the source.`);
273
+ inputs.set(lower(dataset.name), dataset.depends.filter((n) => lower(n) !== lower(dataset.name)));
274
+ }
275
+ else {
276
+ inputs.set(lower(dataset.name), referencedNames(dataset.sql, [...names.filter((n) => n !== dataset.name), ...sources]));
277
+ }
278
+ }
279
+ let order = [];
280
+ try {
281
+ order = buildOrder(new Map([...inputs].map(([name, reads]) => [name, reads.map(lower)])));
282
+ }
283
+ catch (error) {
284
+ problems.push(error instanceof Error ? error.message : String(error));
285
+ }
286
+ return problems.length > 0 ? { problems } : { prepared: { definition, engine, inputs, sources, order }, problems };
287
+ };
288
+ const single = async (engine, sql, params = []) => {
289
+ const result = await engine.execute(sql, params);
290
+ let row = {};
291
+ for await (const batch of result.batches)
292
+ if (batch.numRows > 0)
293
+ row = (batch.get(0)?.toJSON() ?? {});
294
+ return row;
295
+ };
296
+ const save = (run) => {
297
+ const list = runs.get(run.pipelineId) ?? [];
298
+ const index = list.findIndex((r) => r.id === run.id);
299
+ if (index >= 0)
300
+ list[index] = run;
301
+ else
302
+ list.unshift(run);
303
+ runs.set(run.pipelineId, list.slice(0, historyLimit));
304
+ void options.runs?.save(run).catch(() => undefined);
305
+ };
306
+ /** Runs a dataset's checks over what was just built. Counts only; no value is read back. */
307
+ const runChecks = async (engine, dataset) => {
308
+ const results = [];
309
+ for (const check of datasetChecks(dataset)) {
310
+ const name = checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns });
311
+ const severity = check.severity === "warn" ? CheckSeverity.WARN : CheckSeverity.FAIL;
312
+ const query = checkQuery({ kind: KIND[check.kind], columns: check.columns ?? [], toTable: check.to?.table, toColumn: check.to?.column, values: check.values }, dataset.name, engine.dialect);
313
+ const row = await single(engine, query.sql, query.params);
314
+ let failed = 0n;
315
+ let summary = "";
316
+ const columns = (check.columns ?? []).join(", ");
317
+ if (check.kind === "row_count") {
318
+ const rows = BigInt(String(row.rows ?? 0));
319
+ const low = check.min !== undefined && rows < BigInt(check.min);
320
+ const high = check.max !== undefined && rows > BigInt(check.max);
321
+ failed = low || high ? 1n : 0n;
322
+ summary = `${plural(rows, "row", "rows")}${low ? `, fewer than ${check.min}` : high ? `, more than ${check.max}` : ""}.`;
323
+ }
324
+ else {
325
+ failed = BigInt(String(row.failed ?? 0));
326
+ summary =
327
+ failed === 0n
328
+ ? "Passed."
329
+ : check.kind === "unique"
330
+ ? `${plural(failed, "row shares", "rows share")} ${columns} with another row.`
331
+ : check.kind === "not_null"
332
+ ? `${plural(failed, "row has", "rows have")} no ${columns}.`
333
+ : check.kind === "relationships"
334
+ ? `${plural(failed, "row has a", "rows have a")} ${columns} not found in ${check.to?.table}.${check.to?.column}.`
335
+ : `${plural(failed, "row has", "rows have")} a ${columns} that is not one of the values allowed.`;
336
+ }
337
+ results.push({ name, kind: KIND[check.kind], severity, failedRecords: failed, summary, failingRowsSql: query.failingRowsSql });
338
+ }
339
+ return results;
340
+ };
341
+ const execute = async (prepared, run, selected, fullRefresh) => {
342
+ const { definition, engine } = prepared;
343
+ const byName = new Map(definition.datasets.map((d) => [lower(d.name), d]));
344
+ const results = new Map();
345
+ const publish = (state, errorMessage = "") => {
346
+ const next = create(RunSchema, { ...run, state, errorMessage, endTime: state === RunState.RUNNING ? "" : now().toISOString(), datasetRuns: [...results.values()].map((result) => create(DatasetRunSchema, result)) });
347
+ save(next);
348
+ return next;
349
+ };
350
+ const record = (result) => {
351
+ results.set(lower(result.name ?? ""), result);
352
+ publish(RunState.RUNNING);
353
+ };
354
+ const todo = prepared.order.filter((name) => selected.has(name));
355
+ for (const name of todo)
356
+ results.set(name, { name: byName.get(name).name, state: RunState.QUEUED });
357
+ publish(RunState.RUNNING);
358
+ let failed = "";
359
+ for (const name of todo) {
360
+ const dataset = byName.get(name);
361
+ if (cancelling.has(run.id)) {
362
+ record({ name: dataset.name, state: RunState.CANCELLED });
363
+ continue;
364
+ }
365
+ const blocked = (prepared.inputs.get(name) ?? []).map(lower).find((input) => {
366
+ const state = results.get(input)?.state;
367
+ return state === RunState.FAILED || state === RunState.SKIPPED || state === RunState.CANCELLED;
368
+ });
369
+ if (blocked) {
370
+ record({ name: dataset.name, state: RunState.SKIPPED, errorMessage: `Not built because ${byName.get(blocked)?.name ?? blocked} was not.` });
371
+ continue;
372
+ }
373
+ record({ name: dataset.name, state: RunState.RUNNING });
374
+ const started = Date.now();
375
+ const rules = dataset.expectations ?? [];
376
+ try {
377
+ if (fullRefresh)
378
+ await engine.dropMaterialized?.(dataset.name);
379
+ let expectations = [];
380
+ if (rules.length > 0) {
381
+ // A record whose rule cannot be decided (a null) counts as failing it.
382
+ const counts = await single(engine, `SELECT COUNT(*) AS "total", ${rules.map((rule, i) => `SUM(CASE WHEN (${rule.constraint}) THEN 0 ELSE 1 END) AS "f${i}"`).join(", ")} FROM (${dataset.sql}) AS "_d"`);
383
+ const total = Number(counts.total ?? 0);
384
+ expectations = rules.map((rule, i) => {
385
+ const bad = Number(counts[`f${i}`] ?? 0);
386
+ return { name: rule.name, constraint: rule.constraint, action: ACTION[rule.action ?? "warn"], passedRecords: BigInt(total - bad), failedRecords: BigInt(bad) };
387
+ });
388
+ const fatal = expectations.find((e) => e.action === ExpectationAction.FAIL && (e.failedRecords ?? 0n) > 0n);
389
+ if (fatal) {
390
+ const message = `${fatal.failedRecords} records broke the rule ${fatal.name}, which stops the run.`;
391
+ record({ name: dataset.name, state: RunState.FAILED, durationMs: BigInt(Date.now() - started), errorMessage: message, expectations });
392
+ failed ||= `${dataset.name}: ${message}`;
393
+ continue;
394
+ }
395
+ }
396
+ const dropping = rules.filter((rule) => rule.action === "drop");
397
+ const sql = dropping.length === 0 ? dataset.sql : `SELECT * FROM (${dataset.sql}) AS "_d" WHERE ${dropping.map((rule) => `(${rule.constraint})`).join(" AND ")}`;
398
+ const { rowCount } = await engine.materialize(dataset.name, sql, { view: dataset.kind === "view" });
399
+ const checks = await runChecks(engine, dataset);
400
+ const broken = checks.filter((c) => c.severity === CheckSeverity.FAIL && (c.failedRecords ?? 0n) > 0n);
401
+ if (broken.length > 0) {
402
+ // Built, as dbt's build leaves a model that fails its tests; what reads it is not.
403
+ const message = `Built, but ${broken.length === 1 ? "the check" : "the checks"} ${broken.map((c) => c.name).join(", ")} failed: ${broken.map((c) => c.summary).join(" ")}`;
404
+ record({ name: dataset.name, state: RunState.FAILED, rowsWritten: BigInt(rowCount), durationMs: BigInt(Date.now() - started), errorMessage: message, expectations, checks });
405
+ failed ||= `${dataset.name}: ${message}`;
406
+ continue;
407
+ }
408
+ record({ name: dataset.name, state: RunState.COMPLETED, rowsWritten: BigInt(rowCount), durationMs: BigInt(Date.now() - started), expectations, checks });
409
+ }
410
+ catch (error) {
411
+ const message = error instanceof Error ? error.message : String(error);
412
+ record({ name: dataset.name, state: RunState.FAILED, durationMs: BigInt(Date.now() - started), errorMessage: message });
413
+ failed ||= `${dataset.name}: ${message}`;
414
+ }
415
+ }
416
+ const cancelled = cancelling.delete(run.id);
417
+ const ended = publish(failed ? RunState.FAILED : cancelled ? RunState.CANCELLED : RunState.COMPLETED, failed);
418
+ remember(ended);
419
+ options.onFinished?.(ended, definition.sourceId);
420
+ };
421
+ const summary = (definition) => ({
422
+ id: definition.id,
423
+ name: definition.name ?? definition.id,
424
+ description: definition.description ?? "",
425
+ sourceId: definition.sourceId,
426
+ datasetCount: definition.datasets.length,
427
+ latestRun: runs.get(definition.id)?.[0],
428
+ });
429
+ const describe = async (definition) => {
430
+ const { prepared, problems } = await prepare(definition);
431
+ if (!prepared)
432
+ throw new Error(problems.join(" "));
433
+ const seen = latest.get(definition.id);
434
+ const read = new Set([...prepared.inputs.values()].flat().map(lower));
435
+ return create(PipelineSchema, {
436
+ summary: summary(definition),
437
+ recomputeOnly: true,
438
+ canBuild: true,
439
+ canSave: !!options.saved && !configured.has(definition.id),
440
+ version: versionOf(definition.id),
441
+ datasets: [
442
+ ...prepared.sources.filter((name) => read.has(lower(name))).map((name) => ({ name, kind: DatasetKind.SOURCE })),
443
+ ...prepared.order.map((key) => {
444
+ const dataset = definition.datasets.find((d) => lower(d.name) === key);
445
+ const last = seen?.get(key);
446
+ return {
447
+ ...datasetMessage(dataset, prepared.inputs.get(key) ?? []),
448
+ state: last?.state ?? RunState.UNSPECIFIED,
449
+ rowsWritten: last?.state === RunState.COMPLETED ? last.rowsWritten : undefined,
450
+ builtAt: last?.builtAt ?? "",
451
+ lastRunId: last?.runId ?? "",
452
+ };
453
+ }),
454
+ ],
455
+ });
456
+ };
457
+ return {
458
+ async listPipelines() {
459
+ return create(ListPipelinesResponseSchema, { pipelines: [...configured.values(), ...[...saved.values()].map((s) => s.definition)].map(summary) });
460
+ },
461
+ async getPipeline(init) {
462
+ const definition = find(create(GetPipelineRequestSchema, init).id);
463
+ return create(GetPipelineResponseSchema, { pipeline: await describe(definition) });
464
+ },
465
+ async listRuns(init) {
466
+ const request = create(ListRunsRequestSchema, init);
467
+ find(request.pipelineId);
468
+ return create(ListRunsResponseSchema, { runs: (runs.get(request.pipelineId) ?? []).slice(0, request.pageSize || historyLimit) });
469
+ },
470
+ async getRun(init) {
471
+ const request = create(GetRunRequestSchema, init);
472
+ const run = runs.get(request.pipelineId)?.find((r) => r.id === request.runId);
473
+ if (!run)
474
+ throw new Error(`Run not found: ${request.runId}`);
475
+ return create(GetRunResponseSchema, { run });
476
+ },
477
+ async startRun(init) {
478
+ const request = create(StartRunRequestSchema, init);
479
+ const definition = find(request.pipelineId);
480
+ if (runs.get(definition.id)?.some((r) => r.state === RunState.RUNNING))
481
+ throw new Error("This pipeline is already running.");
482
+ const fullRefresh = request.refreshKind === RefreshKind.FULL_REFRESH;
483
+ if (fullRefresh && !request.dryRun && !request.confirmFullRefresh)
484
+ throw new Error("A full refresh clears the chosen tables first. Confirm it to go ahead.");
485
+ const { prepared, problems } = await prepare(definition);
486
+ const base = create(RunSchema, {
487
+ id: `run-${String(++counter).padStart(4, "0")}`,
488
+ pipelineId: definition.id,
489
+ state: RunState.RUNNING,
490
+ startTime: now().toISOString(),
491
+ trigger: request.trigger || "manual",
492
+ startedBy: request.startedBy,
493
+ refreshKind: request.refreshKind,
494
+ datasets: request.select.length > 0 ? request.select : request.datasets,
495
+ dryRun: request.dryRun,
496
+ version: versionOf(definition.id),
497
+ });
498
+ // `datasets` is the older form: each with what reads it.
499
+ const select = request.select.length > 0 ? request.select : request.datasets.map((name) => `${name}+`);
500
+ const inputs = prepared?.inputs ?? new Map(definition.datasets.map((d) => [lower(d.name), []]));
501
+ const { selected, unknown } = select.length === 0 ? { selected: new Set(prepared?.order ?? []), unknown: [] } : selectDatasets(select, inputs);
502
+ const all = [...problems, ...unknown.map((name) => `There is no dataset called ${name}.`)];
503
+ if (!prepared || all.length > 0 || request.dryRun) {
504
+ const done = create(RunSchema, { ...base, state: all.length > 0 ? RunState.FAILED : RunState.COMPLETED, endTime: now().toISOString(), errorMessage: all.join(" ") });
505
+ save(done);
506
+ return create(StartRunResponseSchema, { run: done });
507
+ }
508
+ save(base);
509
+ void execute(prepared, base, selected, fullRefresh).catch((error) => {
510
+ save(create(RunSchema, { ...base, state: RunState.FAILED, endTime: now().toISOString(), errorMessage: error instanceof Error ? error.message : String(error) }));
511
+ });
512
+ return create(StartRunResponseSchema, { run: base });
513
+ },
514
+ async cancelRun(init) {
515
+ const request = create(CancelRunRequestSchema, init);
516
+ const run = runs.get(request.pipelineId)?.find((r) => r.id === request.runId);
517
+ const running = run?.state === RunState.RUNNING;
518
+ // The dataset being built finishes; the rest are not started.
519
+ if (running)
520
+ cancelling.add(request.runId);
521
+ return create(CancelRunResponseSchema, { cancelled: running });
522
+ },
523
+ async inspectFiles(init) {
524
+ const request = create(InspectFilesRequestSchema, init);
525
+ const engine = options.engineOf(request.sourceId);
526
+ if (!engine?.inspect)
527
+ throw new Error(`The source "${request.sourceId}" cannot inspect files.`);
528
+ const found = await engine.inspect(request.format, request.location.trim());
529
+ return create(InspectFilesResponseSchema, found);
530
+ },
531
+ ...(options.saved
532
+ ? {
533
+ async savePipeline(init) {
534
+ const request = create(SavePipelineRequestSchema, init);
535
+ const draft = create(PipelineDraftSchema, request.pipeline ?? {});
536
+ if (!PIPELINE_ID.test(draft.id))
537
+ throw new Error("A pipeline ID uses letters, digits, hyphens and underscores.");
538
+ if (configured.has(draft.id))
539
+ throw new Error(`${draft.id} is defined in the server's config, so it cannot be changed by a save.`);
540
+ const current = versionOf(draft.id);
541
+ if (request.expectedVersion !== current)
542
+ throw new Error(`This pipeline has changed since (it is at version ${current}; the change was made against ${request.expectedVersion}).`);
543
+ if (!request.approvedBy.trim())
544
+ throw new Error("Say who approved this pipeline.");
545
+ if (request.approvalDigest !== (await pipelineDigest(draft)))
546
+ throw new Error("This is not the pipeline that was approved: it changed after it was approved.");
547
+ const definition = definitionFromDraft(draft);
548
+ if (definition.datasets.length === 0)
549
+ throw new Error("A pipeline needs at least one dataset.");
550
+ const { problems } = await prepare(definition);
551
+ if (problems.length > 0)
552
+ throw new Error(problems.join(" "));
553
+ const at = now().toISOString();
554
+ const before = saved.get(draft.id);
555
+ const next = { definition, version: current + 1, versions: [{ version: current + 1, savedAt: at, approvedBy: request.approvedBy.trim(), note: request.note, definition }, ...(before?.versions ?? [])] };
556
+ await options.saved.put(next);
557
+ saved.set(draft.id, next);
558
+ return create(SavePipelineResponseSchema, { pipeline: await describe(definition) });
559
+ },
560
+ async listPipelineVersions(init) {
561
+ const request = create(ListPipelineVersionsRequestSchema, init);
562
+ find(request.pipelineId);
563
+ const versions = (saved.get(request.pipelineId)?.versions ?? []).map((v) => create(PipelineVersionSchema, { version: v.version, savedAt: v.savedAt, approvedBy: v.approvedBy, note: v.note }));
564
+ return create(ListPipelineVersionsResponseSchema, { versions });
565
+ },
566
+ }
567
+ : {}),
568
+ };
569
+ }
570
+ /** Saved pipelines kept in memory: for tests, and a server with nowhere to write. */
571
+ export function memoryPipelineStore(initial = []) {
572
+ const held = new Map(initial.map((s) => [s.definition.id, s]));
573
+ return {
574
+ async list() {
575
+ return [...held.values()];
576
+ },
577
+ async put(saved) {
578
+ held.set(saved.definition.id, saved);
579
+ },
580
+ };
581
+ }
582
+ /** Runs kept in memory, as a `RunStore`. */
583
+ export function memoryRunStore() {
584
+ const runs = [];
585
+ return {
586
+ runs,
587
+ async load() {
588
+ return [...runs];
589
+ },
590
+ async save(run) {
591
+ const index = runs.findIndex((r) => r.id === run.id && r.pipelineId === run.pipelineId);
592
+ if (index >= 0)
593
+ runs[index] = run;
594
+ else
595
+ runs.unshift(run);
596
+ },
597
+ };
598
+ }
599
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAkB,SAAS,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAE9E,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EAEvB,SAAS,EACT,aAAa,EAEb,WAAW,EAEX,gBAAgB,EAChB,iBAAiB,EACjB,wBAAwB,EACxB,yBAAyB,EACzB,mBAAmB,EACnB,oBAAoB,EACpB,yBAAyB,EACzB,0BAA0B,EAC1B,iCAAiC,EACjC,kCAAkC,EAClC,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,EAEtB,mBAAmB,EACnB,cAAc,EAEd,qBAAqB,EACrB,WAAW,EAEX,SAAS,EACT,QAAQ,EACR,yBAAyB,EACzB,0BAA0B,EAC1B,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE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uf\";\nimport { type Pipelines, checkName, pipelineDigest } from \"@surfaces-ui/data\";\nimport type { Engine, Param } from \"@surfaces-ui/engine\";\nimport {\n CancelRunRequestSchema,\n CancelRunResponseSchema,\n type CheckResultSchema,\n CheckKind,\n CheckSeverity,\n type Dataset,\n DatasetKind,\n type DatasetSchema,\n DatasetRunSchema,\n ExpectationAction,\n GetPipelineRequestSchema,\n GetPipelineResponseSchema,\n GetRunRequestSchema,\n GetRunResponseSchema,\n InspectFilesRequestSchema,\n InspectFilesResponseSchema,\n ListPipelineVersionsRequestSchema,\n ListPipelineVersionsResponseSchema,\n ListPipelinesResponseSchema,\n ListRunsRequestSchema,\n ListRunsResponseSchema,\n type PipelineDraft,\n PipelineDraftSchema,\n PipelineSchema,\n type PipelineVersion,\n PipelineVersionSchema,\n RefreshKind,\n type Run,\n RunSchema,\n RunState,\n SavePipelineRequestSchema,\n SavePipelineResponseSchema,\n StartRunRequestSchema,\n StartRunResponseSchema,\n} from \"@surfaces-ui/proto\";\nimport { SqlError, assertReadOnly, blankLiterals, checkQuery, initSql } from \"@surfaces-ui/sql\";\n\nexport interface ExpectationDefinition {\n name: string;\n /** A condition every record should meet, e.g. `amount >= 0`. */\n constraint: string;\n /** What happens to a record that breaks it. Defaults to \"warn\". */\n action?: \"warn\" | \"drop\" | \"fail\";\n}\n\n/** A test over the whole built dataset: what a row-level expectation cannot say. */\nexport interface CheckDefinition {\n kind: \"unique\" | \"not_null\" | \"relationships\" | \"accepted_values\" | \"row_count\";\n /** The column, or for \"unique\" the columns that together must not repeat. */\n columns?: string[];\n /** \"relationships\": the dataset or table, and column, every value must be found in. */\n to?: { table: string; column: string };\n /** \"accepted_values\": the values allowed, compared as text. */\n values?: string[];\n /** \"row_count\" bounds. */\n min?: number;\n max?: number;\n /** \"fail\" (default) counts the dataset as failed, so what reads it is not built; \"warn\" reports it. */\n severity?: \"warn\" | \"fail\";\n name?: string;\n}\n\nexport interface ColumnDefinition {\n name: string;\n type?: string;\n description?: string;\n}\n\nexport interface DatasetDefinition {\n /** The table's name. Other datasets read it by this name. */\n name: string;\n /** \"table\" (default) is rebuilt on each run; \"view\" runs its query when read. */\n kind?: \"table\" | \"view\";\n layer?: \"bronze\" | \"silver\" | \"gold\";\n description?: string;\n /** A single SELECT. It may read the source's tables and other datasets of the pipeline. */\n sql: string;\n /**\n * The datasets and source tables it reads. Left out, they are worked out\n * from the query's text, which can mistake a name that only appears in it\n * (a column or an alias) for one it reads.\n */\n depends?: string[];\n /** What one row is, in a sentence: \"one row per order line\". */\n grain?: string;\n /** The columns that pick out one row. They are checked unique and not empty after every build. */\n primaryKey?: string[];\n columns?: ColumnDefinition[];\n expectations?: ExpectationDefinition[];\n checks?: CheckDefinition[];\n tags?: string[];\n owner?: string;\n}\n\nexport interface PipelineDefinition {\n id: string;\n name?: string;\n description?: string;\n /** The source whose engine builds the datasets. They can then be queried through it. */\n sourceId: string;\n datasets: DatasetDefinition[];\n}\n\n/** A pipeline someone saved, with every version kept. */\nexport interface SavedPipeline {\n definition: PipelineDefinition;\n version: number;\n versions: { version: number; savedAt: string; approvedBy: string; note: string; definition: PipelineDefinition }[];\n}\n\n/** Where saved pipelines live. The dev server keeps one JSON file per pipeline. */\nexport interface PipelineStore {\n list(): Promise<SavedPipeline[]>;\n put(saved: SavedPipeline): Promise<void>;\n}\n\n/** Where runs are kept, so history outlives the process. */\nexport interface RunStore {\n /** Every pipeline's runs, newest first. */\n load(): Promise<Run[]>;\n /** Called as a run progresses and when it ends; the same ID replaces what was kept. */\n save(run: Run): Promise<void>;\n}\n\nexport interface PipelinesOptions {\n /** Pipelines defined in the server's config. They cannot be changed by a save. */\n pipelines: PipelineDefinition[];\n /** The engine behind a source. It must support `materialize`. */\n engineOf(sourceId: string): Engine | undefined;\n /** Called when a run that built something ends, so caches over the source can be dropped. */\n onFinished?(run: Run, sourceId: string): void;\n /** Runs kept per pipeline. Defaults to 50. */\n historyLimit?: number;\n /** Where runs are kept. Left out, they are kept in memory and lost on restart. */\n runs?: RunStore;\n /**\n * Allows `savePipeline`: pipelines a person approved are checked and kept\n * here, and can be run like the configured ones. Left out, pipelines are\n * fixed.\n */\n saved?: PipelineStore;\n now?: () => Date;\n}\n\ntype DatasetRunInit = MessageInitShape<typeof DatasetRunSchema>;\ntype CheckResultInit = MessageInitShape<typeof CheckResultSchema>;\n\nconst ACTION: Record<NonNullable<ExpectationDefinition[\"action\"]>, ExpectationAction> = {\n warn: ExpectationAction.WARN,\n drop: ExpectationAction.DROP,\n fail: ExpectationAction.FAIL,\n};\nconst ACTION_NAME = new Map<ExpectationAction, ExpectationDefinition[\"action\"]>([\n [ExpectationAction.WARN, \"warn\"],\n [ExpectationAction.DROP, \"drop\"],\n [ExpectationAction.FAIL, \"fail\"],\n]);\nconst KIND: Record<CheckDefinition[\"kind\"], CheckKind> = {\n unique: CheckKind.UNIQUE,\n not_null: CheckKind.NOT_NULL,\n relationships: CheckKind.RELATIONSHIPS,\n accepted_values: CheckKind.ACCEPTED_VALUES,\n row_count: CheckKind.ROW_COUNT,\n};\nconst KIND_NAME = new Map<CheckKind, CheckDefinition[\"kind\"]>(Object.entries(KIND).map(([name, kind]) => [kind, name as CheckDefinition[\"kind\"]]));\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n/** A pipeline ID: also a file name where saved pipelines are kept. */\nconst PIPELINE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,80}$/;\nconst lower = (name: string) => name.toLowerCase();\nconst plural = (n: bigint | number, one: string, many: string) => `${n.toLocaleString(\"en\")} ${n === 1 || n === 1n ? one : many}`;\n\n/**\n * The names a query reads, out of a list of candidates. String literals and\n * comments are ignored, so a name that only appears in text does not count.\n */\nexport function referencedNames(sql: string, candidates: string[]): string[] {\n const bare = blankLiterals(sql).toLowerCase();\n return candidates.filter((name) => new RegExp(`(^|[^\\\\w$])${lower(name).replace(/[$]/g, \"\\\\$\")}($|[^\\\\w$])`).test(bare));\n}\n\n/**\n * The order to build datasets in: each after everything it reads. Throws a\n * readable error when datasets depend on each other in a circle.\n */\nexport function buildOrder(inputs: Map<string, string[]>): string[] {\n const order: string[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (name: string, trail: string[]) => {\n if (state.get(name) === \"done\") return;\n if (state.get(name) === \"visiting\") throw new Error(`These datasets depend on each other in a circle: ${[...trail.slice(trail.indexOf(name)), name].join(\" → \")}`);\n state.set(name, \"visiting\");\n for (const input of inputs.get(name) ?? []) if (inputs.has(input)) visit(input, [...trail, name]);\n state.set(name, \"done\");\n order.push(name);\n };\n for (const name of inputs.keys()) visit(name, []);\n return order;\n}\n\n/**\n * The datasets a selection names, given what each reads. \"orders\" is that\n * dataset alone, \"orders+\" adds everything that reads it (directly or not),\n * \"+orders\" adds everything it reads, and \"+orders+\" both. Names are\n * matched without regard to case; an unknown name is reported.\n */\nexport function selectDatasets(select: string[], inputs: Map<string, string[]>): { selected: Set<string>; unknown: string[] } {\n const selected = new Set<string>();\n const unknown: string[] = [];\n const grow = (start: string, next: (name: string) => string[]) => {\n const seen = new Set([start]);\n for (const queue = [start]; queue.length > 0; ) {\n for (const n of next(queue.shift()!)) if (!seen.has(n)) (seen.add(n), queue.push(n));\n }\n return seen;\n };\n const readers = (name: string) => [...inputs].filter(([, reads]) => reads.map(lower).includes(name)).map(([n]) => n);\n const reads = (name: string) => (inputs.get(name) ?? []).map(lower).filter((n) => inputs.has(n));\n for (const item of select) {\n const up = item.startsWith(\"+\");\n const down = item.endsWith(\"+\");\n const name = lower(item.replace(/^\\+|\\+$/g, \"\").trim());\n if (!inputs.has(name)) {\n unknown.push(item.replace(/^\\+|\\+$/g, \"\").trim());\n continue;\n }\n selected.add(name);\n if (down) for (const n of grow(name, readers)) selected.add(n);\n if (up) for (const n of grow(name, reads)) selected.add(n);\n }\n return { selected, unknown };\n}\n\n/** The checks a dataset gets: its own, and for a primary key one that it is unique and one per column that it is never empty. */\nexport function datasetChecks(dataset: DatasetDefinition): (CheckDefinition & { implied?: boolean })[] {\n const key = dataset.primaryKey ?? [];\n const implied: (CheckDefinition & { implied: boolean })[] =\n key.length === 0 ? [] : [{ kind: \"unique\", columns: key, implied: true }, ...key.map((column) => ({ kind: \"not_null\" as const, columns: [column], implied: true }))];\n const own = dataset.checks ?? [];\n const same = (a: CheckDefinition, b: CheckDefinition) => a.kind === b.kind && (a.columns ?? []).map(lower).join() === (b.columns ?? []).map(lower).join();\n return [...implied.filter((i) => !own.some((o) => same(o, i))), ...own];\n}\n\n/** A pipeline definition from a draft a person approved. */\nexport function definitionFromDraft(draft: PipelineDraft): PipelineDefinition {\n return {\n id: draft.id,\n ...(draft.name && draft.name !== draft.id ? { name: draft.name } : {}),\n ...(draft.description ? { description: draft.description } : {}),\n sourceId: draft.sourceId,\n datasets: draft.datasets.map((d) => ({\n name: d.name,\n ...(d.kind === DatasetKind.VIEW ? { kind: \"view\" as const } : {}),\n ...(d.layer === \"bronze\" || d.layer === \"silver\" || d.layer === \"gold\" ? { layer: d.layer } : {}),\n ...(d.description ? { description: d.description } : {}),\n sql: d.sql,\n ...(d.inputs.length > 0 ? { depends: d.inputs } : {}),\n ...(d.grain ? { grain: d.grain } : {}),\n ...(d.primaryKey.length > 0 ? { primaryKey: d.primaryKey } : {}),\n ...(d.columns.length > 0 ? { columns: d.columns.map((c) => ({ name: c.name, ...(c.type ? { type: c.type } : {}), ...(c.description ? { description: c.description } : {}) })) } : {}),\n ...(d.expectations.length > 0 ? { expectations: d.expectations.map((e) => ({ name: e.name, constraint: e.constraint, action: ACTION_NAME.get(e.action) ?? \"warn\" })) } : {}),\n ...(d.checks.filter((c) => !c.implied).length > 0\n ? {\n checks: d.checks\n .filter((c) => !c.implied)\n .map((c) => ({\n kind: KIND_NAME.get(c.kind) ?? \"unique\",\n ...(c.columns.length > 0 ? { columns: c.columns } : {}),\n ...(c.toTable ? { to: { table: c.toTable, column: c.toColumn } } : {}),\n ...(c.values.length > 0 ? { values: c.values } : {}),\n ...(c.minRows !== undefined ? { min: Number(c.minRows) } : {}),\n ...(c.maxRows !== undefined ? { max: Number(c.maxRows) } : {}),\n ...(c.severity === CheckSeverity.WARN ? { severity: \"warn\" as const } : {}),\n // A name that is only the one made up from the kind and columns is left out.\n ...(c.name && c.name !== checkName({ kind: c.kind, columns: c.columns }) ? { name: c.name } : {}),\n })),\n }\n : {}),\n ...(d.tags.length > 0 ? { tags: d.tags } : {}),\n ...(d.owner ? { owner: d.owner } : {}),\n })),\n };\n}\n\n/** A check as the `Check` message. */\nfunction checkMessage(check: CheckDefinition & { implied?: boolean }) {\n return {\n name: checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns }),\n kind: KIND[check.kind],\n columns: check.columns ?? [],\n toTable: check.to?.table ?? \"\",\n toColumn: check.to?.column ?? \"\",\n values: check.values ?? [],\n ...(check.min !== undefined ? { minRows: BigInt(check.min) } : {}),\n ...(check.max !== undefined ? { maxRows: BigInt(check.max) } : {}),\n severity: check.severity === \"warn\" ? CheckSeverity.WARN : CheckSeverity.FAIL,\n implied: check.implied ?? false,\n };\n}\n\n/** A dataset definition as the `Dataset` message, without run state. */\nfunction datasetMessage(dataset: DatasetDefinition, inputs: string[]): MessageInitShape<typeof DatasetSchema> {\n return {\n name: dataset.name,\n kind: dataset.kind === \"view\" ? DatasetKind.VIEW : DatasetKind.TABLE,\n layer: dataset.layer ?? \"\",\n description: dataset.description ?? \"\",\n sql: dataset.sql,\n inputs,\n inputsDeclared: dataset.depends !== undefined,\n expectations: (dataset.expectations ?? []).map((rule) => ({ name: rule.name, constraint: rule.constraint, action: ACTION[rule.action ?? \"warn\"] })),\n grain: dataset.grain ?? \"\",\n primaryKey: dataset.primaryKey ?? [],\n columns: (dataset.columns ?? []).map((c) => ({ name: c.name, type: c.type ?? \"\", description: c.description ?? \"\" })),\n checks: datasetChecks(dataset).map(checkMessage),\n tags: dataset.tags ?? [],\n owner: dataset.owner ?? \"\",\n };\n}\n\ninterface Prepared {\n definition: PipelineDefinition;\n engine: Engine;\n /** Dataset name (lower case) to the dataset and source table names it reads. */\n inputs: Map<string, string[]>;\n sources: string[];\n order: string[];\n}\n\n/**\n * A reference pipeline backend on any Engine that can `materialize`. Each\n * dataset is a SELECT; a run builds them in dependency order as tables (or\n * views) of the source, applying row-level rules before a build and checks\n * over the whole dataset after it. Every run recomputes whole datasets:\n * there is no incremental or streaming processing, checkpoints or\n * schedules.\n *\n * It runs only definitions it holds: those passed in, and with a `saved`\n * store, ones a person approved through `savePipeline`, which are checked\n * before they are kept. A run request names a pipeline and datasets, never\n * SQL.\n */\nexport async function createPipelines(options: PipelinesOptions): Promise<Pipelines> {\n await initSql();\n const now = options.now ?? (() => new Date());\n const historyLimit = options.historyLimit ?? 50;\n const runs = new Map<string, Run[]>();\n const latest = new Map<string, Map<string, DatasetRunInit & { builtAt?: string; runId?: string }>>();\n const cancelling = new Set<string>();\n let counter = 0;\n\n const configured = new Map<string, PipelineDefinition>();\n for (const definition of options.pipelines) {\n if (configured.has(definition.id)) throw new Error(`Two pipelines have the ID ${definition.id}.`);\n configured.set(definition.id, definition);\n }\n const saved = new Map<string, SavedPipeline>();\n for (const pipeline of (await options.saved?.list()) ?? []) if (!configured.has(pipeline.definition.id)) saved.set(pipeline.definition.id, pipeline);\n const find = (id: string) => {\n const definition = configured.get(id) ?? saved.get(id)?.definition;\n if (!definition) throw new Error(`Pipeline not found: ${id}`);\n return definition;\n };\n const versionOf = (id: string) => saved.get(id)?.version ?? 0;\n\n /** Remembers each dataset's last finished state from a run. */\n const remember = (run: Run) => {\n for (const result of run.datasetRuns) {\n if (result.state === RunState.RUNNING || result.state === RunState.QUEUED) continue;\n const seen = latest.get(run.pipelineId) ?? new Map();\n seen.set(lower(result.name), { ...result, ...(result.state === RunState.COMPLETED ? { builtAt: run.endTime || run.startTime, runId: run.id } : {}) });\n latest.set(run.pipelineId, seen);\n }\n };\n for (const run of [...((await options.runs?.load()) ?? [])].reverse()) {\n // A run the process stopped during is not still going.\n const kept = run.state === RunState.RUNNING ? create(RunSchema, { ...run, state: RunState.CANCELLED, errorMessage: run.errorMessage || \"The server stopped during this run.\" }) : run;\n runs.set(kept.pipelineId, [kept, ...(runs.get(kept.pipelineId) ?? [])].slice(0, historyLimit));\n if (!kept.dryRun) remember(kept);\n const n = Number(/^run-(\\d+)$/.exec(kept.id)?.[1] ?? 0);\n if (n > counter) counter = n;\n }\n\n /** Checks a pipeline and works out its graph. Every problem found is reported, not just the first. */\n const prepare = async (definition: PipelineDefinition): Promise<{ prepared?: Prepared; problems: string[] }> => {\n const problems: string[] = [];\n const engine = options.engineOf(definition.sourceId);\n if (!engine) return { problems: [`The source \"${definition.sourceId}\" is not available.`] };\n if (!engine.materialize) return { problems: [`The source \"${definition.sourceId}\" cannot build tables, so it cannot run pipelines.`] };\n const names = definition.datasets.map((d) => d.name);\n for (const name of names) if (!NAME.test(name)) problems.push(`Dataset names use letters, digits and underscores: ${name}`);\n if (new Set(names.map(lower)).size !== names.length) problems.push(\"Two datasets have the same name.\");\n const sources = (await engine.listTables({ catalog: \"\", schema: \"\", search: \"\" })).map((t) => t.ref?.table ?? \"\").filter((t) => t && !names.some((n) => lower(n) === lower(t)));\n const known = new Set([...names, ...sources].map(lower));\n const inputs = new Map<string, string[]>();\n for (const dataset of definition.datasets) {\n try {\n // A dataset is always a single read-only query; the engine wraps it to build the table.\n assertReadOnly(dataset.sql, engine.dialect);\n for (const rule of dataset.expectations ?? []) assertReadOnly(`SELECT * FROM (${dataset.sql}) AS \"_d\" WHERE (${rule.constraint})`, engine.dialect);\n for (const check of datasetChecks(dataset)) {\n if (check.kind === \"relationships\" && check.to && !known.has(lower(check.to.table))) problems.push(`${dataset.name}: the check ${checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns })} looks in ${check.to.table}, which is neither a dataset nor a table of the source.`);\n checkQuery({ kind: KIND[check.kind], columns: check.columns ?? [], toTable: check.to?.table, toColumn: check.to?.column, values: check.values }, dataset.name, engine.dialect);\n }\n } catch (error) {\n problems.push(`${dataset.name}: ${error instanceof SqlError ? error.message : error instanceof Error ? error.message : String(error)}`);\n }\n if (dataset.depends) {\n for (const name of dataset.depends) if (!known.has(lower(name))) problems.push(`${dataset.name} says it reads ${name}, which is neither a dataset nor a table of the source.`);\n inputs.set(lower(dataset.name), dataset.depends.filter((n) => lower(n) !== lower(dataset.name)));\n } else {\n inputs.set(lower(dataset.name), referencedNames(dataset.sql, [...names.filter((n) => n !== dataset.name), ...sources]));\n }\n }\n let order: string[] = [];\n try {\n order = buildOrder(new Map([...inputs].map(([name, reads]) => [name, reads.map(lower)])));\n } catch (error) {\n problems.push(error instanceof Error ? error.message : String(error));\n }\n return problems.length > 0 ? { problems } : { prepared: { definition, engine, inputs, sources, order }, problems };\n };\n\n const single = async (engine: Engine, sql: string, params: Param[] = []): Promise<Record<string, unknown>> => {\n const result = await engine.execute(sql, params);\n let row: Record<string, unknown> = {};\n for await (const batch of result.batches) if (batch.numRows > 0) row = (batch.get(0)?.toJSON() ?? {}) as Record<string, unknown>;\n return row;\n };\n\n const save = (run: Run) => {\n const list = runs.get(run.pipelineId) ?? [];\n const index = list.findIndex((r) => r.id === run.id);\n if (index >= 0) list[index] = run;\n else list.unshift(run);\n runs.set(run.pipelineId, list.slice(0, historyLimit));\n void options.runs?.save(run).catch(() => undefined);\n };\n\n /** Runs a dataset's checks over what was just built. Counts only; no value is read back. */\n const runChecks = async (engine: Engine, dataset: DatasetDefinition): Promise<CheckResultInit[]> => {\n const results: CheckResultInit[] = [];\n for (const check of datasetChecks(dataset)) {\n const name = checkName({ name: check.name, kind: KIND[check.kind], columns: check.columns });\n const severity = check.severity === \"warn\" ? CheckSeverity.WARN : CheckSeverity.FAIL;\n const query = checkQuery({ kind: KIND[check.kind], columns: check.columns ?? [], toTable: check.to?.table, toColumn: check.to?.column, values: check.values }, dataset.name, engine.dialect);\n const row = await single(engine, query.sql, query.params);\n let failed = 0n;\n let summary = \"\";\n const columns = (check.columns ?? []).join(\", \");\n if (check.kind === \"row_count\") {\n const rows = BigInt(String(row.rows ?? 0));\n const low = check.min !== undefined && rows < BigInt(check.min);\n const high = check.max !== undefined && rows > BigInt(check.max);\n failed = low || high ? 1n : 0n;\n summary = `${plural(rows, \"row\", \"rows\")}${low ? `, fewer than ${check.min}` : high ? `, more than ${check.max}` : \"\"}.`;\n } else {\n failed = BigInt(String(row.failed ?? 0));\n summary =\n failed === 0n\n ? \"Passed.\"\n : check.kind === \"unique\"\n ? `${plural(failed, \"row shares\", \"rows share\")} ${columns} with another row.`\n : check.kind === \"not_null\"\n ? `${plural(failed, \"row has\", \"rows have\")} no ${columns}.`\n : check.kind === \"relationships\"\n ? `${plural(failed, \"row has a\", \"rows have a\")} ${columns} not found in ${check.to?.table}.${check.to?.column}.`\n : `${plural(failed, \"row has\", \"rows have\")} a ${columns} that is not one of the values allowed.`;\n }\n results.push({ name, kind: KIND[check.kind], severity, failedRecords: failed, summary, failingRowsSql: query.failingRowsSql });\n }\n return results;\n };\n\n const execute = async (prepared: Prepared, run: Run, selected: Set<string>, fullRefresh: boolean) => {\n const { definition, engine } = prepared;\n const byName = new Map(definition.datasets.map((d) => [lower(d.name), d]));\n const results = new Map<string, DatasetRunInit>();\n const publish = (state: RunState, errorMessage = \"\") => {\n const next = create(RunSchema, { ...run, state, errorMessage, endTime: state === RunState.RUNNING ? \"\" : now().toISOString(), datasetRuns: [...results.values()].map((result) => create(DatasetRunSchema, result)) });\n save(next);\n return next;\n };\n const record = (result: DatasetRunInit) => {\n results.set(lower(result.name ?? \"\"), result);\n publish(RunState.RUNNING);\n };\n const todo = prepared.order.filter((name) => selected.has(name));\n for (const name of todo) results.set(name, { name: byName.get(name)!.name, state: RunState.QUEUED });\n publish(RunState.RUNNING);\n\n let failed = \"\";\n for (const name of todo) {\n const dataset = byName.get(name)!;\n if (cancelling.has(run.id)) {\n record({ name: dataset.name, state: RunState.CANCELLED });\n continue;\n }\n const blocked = (prepared.inputs.get(name) ?? []).map(lower).find((input) => {\n const state = results.get(input)?.state;\n return state === RunState.FAILED || state === RunState.SKIPPED || state === RunState.CANCELLED;\n });\n if (blocked) {\n record({ name: dataset.name, state: RunState.SKIPPED, errorMessage: `Not built because ${byName.get(blocked)?.name ?? blocked} was not.` });\n continue;\n }\n record({ name: dataset.name, state: RunState.RUNNING });\n const started = Date.now();\n const rules = dataset.expectations ?? [];\n try {\n if (fullRefresh) await engine.dropMaterialized?.(dataset.name);\n let expectations: DatasetRunInit[\"expectations\"] = [];\n if (rules.length > 0) {\n // A record whose rule cannot be decided (a null) counts as failing it.\n const counts = await single(engine, `SELECT COUNT(*) AS \"total\", ${rules.map((rule, i) => `SUM(CASE WHEN (${rule.constraint}) THEN 0 ELSE 1 END) AS \"f${i}\"`).join(\", \")} FROM (${dataset.sql}) AS \"_d\"`);\n const total = Number(counts.total ?? 0);\n expectations = rules.map((rule, i) => {\n const bad = Number(counts[`f${i}`] ?? 0);\n return { name: rule.name, constraint: rule.constraint, action: ACTION[rule.action ?? \"warn\"], passedRecords: BigInt(total - bad), failedRecords: BigInt(bad) };\n });\n const fatal = expectations.find((e) => e.action === ExpectationAction.FAIL && (e.failedRecords ?? 0n) > 0n);\n if (fatal) {\n const message = `${fatal.failedRecords} records broke the rule ${fatal.name}, which stops the run.`;\n record({ name: dataset.name, state: RunState.FAILED, durationMs: BigInt(Date.now() - started), errorMessage: message, expectations });\n failed ||= `${dataset.name}: ${message}`;\n continue;\n }\n }\n const dropping = rules.filter((rule) => rule.action === \"drop\");\n const sql = dropping.length === 0 ? dataset.sql : `SELECT * FROM (${dataset.sql}) AS \"_d\" WHERE ${dropping.map((rule) => `(${rule.constraint})`).join(\" AND \")}`;\n const { rowCount } = await engine.materialize!(dataset.name, sql, { view: dataset.kind === \"view\" });\n const checks = await runChecks(engine, dataset);\n const broken = checks.filter((c) => c.severity === CheckSeverity.FAIL && (c.failedRecords ?? 0n) > 0n);\n if (broken.length > 0) {\n // Built, as dbt's build leaves a model that fails its tests; what reads it is not.\n const message = `Built, but ${broken.length === 1 ? \"the check\" : \"the checks\"} ${broken.map((c) => c.name).join(\", \")} failed: ${broken.map((c) => c.summary).join(\" \")}`;\n record({ name: dataset.name, state: RunState.FAILED, rowsWritten: BigInt(rowCount), durationMs: BigInt(Date.now() - started), errorMessage: message, expectations, checks });\n failed ||= `${dataset.name}: ${message}`;\n continue;\n }\n record({ name: dataset.name, state: RunState.COMPLETED, rowsWritten: BigInt(rowCount), durationMs: BigInt(Date.now() - started), expectations, checks });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n record({ name: dataset.name, state: RunState.FAILED, durationMs: BigInt(Date.now() - started), errorMessage: message });\n failed ||= `${dataset.name}: ${message}`;\n }\n }\n const cancelled = cancelling.delete(run.id);\n const ended = publish(failed ? RunState.FAILED : cancelled ? RunState.CANCELLED : RunState.COMPLETED, failed);\n remember(ended);\n options.onFinished?.(ended, definition.sourceId);\n };\n\n const summary = (definition: PipelineDefinition) => ({\n id: definition.id,\n name: definition.name ?? definition.id,\n description: definition.description ?? \"\",\n sourceId: definition.sourceId,\n datasetCount: definition.datasets.length,\n latestRun: runs.get(definition.id)?.[0],\n });\n\n const describe = async (definition: PipelineDefinition) => {\n const { prepared, problems } = await prepare(definition);\n if (!prepared) throw new Error(problems.join(\" \"));\n const seen = latest.get(definition.id);\n const read = new Set([...prepared.inputs.values()].flat().map(lower));\n return create(PipelineSchema, {\n summary: summary(definition),\n recomputeOnly: true,\n canBuild: true,\n canSave: !!options.saved && !configured.has(definition.id),\n version: versionOf(definition.id),\n datasets: [\n ...prepared.sources.filter((name) => read.has(lower(name))).map((name) => ({ name, kind: DatasetKind.SOURCE })),\n ...prepared.order.map((key) => {\n const dataset = definition.datasets.find((d) => lower(d.name) === key)!;\n const last = seen?.get(key);\n return {\n ...datasetMessage(dataset, prepared.inputs.get(key) ?? []),\n state: last?.state ?? RunState.UNSPECIFIED,\n rowsWritten: last?.state === RunState.COMPLETED ? last.rowsWritten : undefined,\n builtAt: last?.builtAt ?? \"\",\n lastRunId: last?.runId ?? \"\",\n };\n }),\n ],\n });\n };\n\n return {\n async listPipelines() {\n return create(ListPipelinesResponseSchema, { pipelines: [...configured.values(), ...[...saved.values()].map((s) => s.definition)].map(summary) });\n },\n\n async getPipeline(init) {\n const definition = find(create(GetPipelineRequestSchema, init).id);\n return create(GetPipelineResponseSchema, { pipeline: await describe(definition) });\n },\n\n async listRuns(init) {\n const request = create(ListRunsRequestSchema, init);\n find(request.pipelineId);\n return create(ListRunsResponseSchema, { runs: (runs.get(request.pipelineId) ?? []).slice(0, request.pageSize || historyLimit) });\n },\n\n async getRun(init) {\n const request = create(GetRunRequestSchema, init);\n const run = runs.get(request.pipelineId)?.find((r) => r.id === request.runId);\n if (!run) throw new Error(`Run not found: ${request.runId}`);\n return create(GetRunResponseSchema, { run });\n },\n\n async startRun(init) {\n const request = create(StartRunRequestSchema, init);\n const definition = find(request.pipelineId);\n if (runs.get(definition.id)?.some((r) => r.state === RunState.RUNNING)) throw new Error(\"This pipeline is already running.\");\n const fullRefresh = request.refreshKind === RefreshKind.FULL_REFRESH;\n if (fullRefresh && !request.dryRun && !request.confirmFullRefresh) throw new Error(\"A full refresh clears the chosen tables first. Confirm it to go ahead.\");\n const { prepared, problems } = await prepare(definition);\n const base = create(RunSchema, {\n id: `run-${String(++counter).padStart(4, \"0\")}`,\n pipelineId: definition.id,\n state: RunState.RUNNING,\n startTime: now().toISOString(),\n trigger: request.trigger || \"manual\",\n startedBy: request.startedBy,\n refreshKind: request.refreshKind,\n datasets: request.select.length > 0 ? request.select : request.datasets,\n dryRun: request.dryRun,\n version: versionOf(definition.id),\n });\n // `datasets` is the older form: each with what reads it.\n const select = request.select.length > 0 ? request.select : request.datasets.map((name) => `${name}+`);\n const inputs = prepared?.inputs ?? new Map(definition.datasets.map((d) => [lower(d.name), [] as string[]]));\n const { selected, unknown } = select.length === 0 ? { selected: new Set(prepared?.order ?? []), unknown: [] } : selectDatasets(select, inputs);\n const all = [...problems, ...unknown.map((name) => `There is no dataset called ${name}.`)];\n if (!prepared || all.length > 0 || request.dryRun) {\n const done = create(RunSchema, { ...base, state: all.length > 0 ? RunState.FAILED : RunState.COMPLETED, endTime: now().toISOString(), errorMessage: all.join(\" \") });\n save(done);\n return create(StartRunResponseSchema, { run: done });\n }\n save(base);\n void execute(prepared, base, selected, fullRefresh).catch((error: unknown) => {\n save(create(RunSchema, { ...base, state: RunState.FAILED, endTime: now().toISOString(), errorMessage: error instanceof Error ? error.message : String(error) }));\n });\n return create(StartRunResponseSchema, { run: base });\n },\n\n async cancelRun(init) {\n const request = create(CancelRunRequestSchema, init);\n const run = runs.get(request.pipelineId)?.find((r) => r.id === request.runId);\n const running = run?.state === RunState.RUNNING;\n // The dataset being built finishes; the rest are not started.\n if (running) cancelling.add(request.runId);\n return create(CancelRunResponseSchema, { cancelled: running });\n },\n\n async inspectFiles(init) {\n const request = create(InspectFilesRequestSchema, init);\n const engine = options.engineOf(request.sourceId);\n if (!engine?.inspect) throw new Error(`The source \"${request.sourceId}\" cannot inspect files.`);\n const found = await engine.inspect(request.format, request.location.trim());\n return create(InspectFilesResponseSchema, found);\n },\n\n ...(options.saved\n ? {\n async savePipeline(init: MessageInitShape<typeof SavePipelineRequestSchema>) {\n const request = create(SavePipelineRequestSchema, init);\n const draft = create(PipelineDraftSchema, request.pipeline ?? {});\n if (!PIPELINE_ID.test(draft.id)) throw new Error(\"A pipeline ID uses letters, digits, hyphens and underscores.\");\n if (configured.has(draft.id)) throw new Error(`${draft.id} is defined in the server's config, so it cannot be changed by a save.`);\n const current = versionOf(draft.id);\n if (request.expectedVersion !== current) throw new Error(`This pipeline has changed since (it is at version ${current}; the change was made against ${request.expectedVersion}).`);\n if (!request.approvedBy.trim()) throw new Error(\"Say who approved this pipeline.\");\n if (request.approvalDigest !== (await pipelineDigest(draft))) throw new Error(\"This is not the pipeline that was approved: it changed after it was approved.\");\n const definition = definitionFromDraft(draft);\n if (definition.datasets.length === 0) throw new Error(\"A pipeline needs at least one dataset.\");\n const { problems } = await prepare(definition);\n if (problems.length > 0) throw new Error(problems.join(\" \"));\n const at = now().toISOString();\n const before = saved.get(draft.id);\n const next: SavedPipeline = { definition, version: current + 1, versions: [{ version: current + 1, savedAt: at, approvedBy: request.approvedBy.trim(), note: request.note, definition }, ...(before?.versions ?? [])] };\n await options.saved!.put(next);\n saved.set(draft.id, next);\n return create(SavePipelineResponseSchema, { pipeline: await describe(definition) });\n },\n async listPipelineVersions(init: MessageInitShape<typeof ListPipelineVersionsRequestSchema>) {\n const request = create(ListPipelineVersionsRequestSchema, init);\n find(request.pipelineId);\n const versions: PipelineVersion[] = (saved.get(request.pipelineId)?.versions ?? []).map((v) => create(PipelineVersionSchema, { version: v.version, savedAt: v.savedAt, approvedBy: v.approvedBy, note: v.note }));\n return create(ListPipelineVersionsResponseSchema, { versions });\n },\n }\n : {}),\n };\n}\n\n/** Saved pipelines kept in memory: for tests, and a server with nowhere to write. */\nexport function memoryPipelineStore(initial: SavedPipeline[] = []): PipelineStore {\n const held = new Map(initial.map((s) => [s.definition.id, s]));\n return {\n async list() {\n return [...held.values()];\n },\n async put(saved) {\n held.set(saved.definition.id, saved);\n },\n };\n}\n\n/** Runs kept in memory, as a `RunStore`. */\nexport function memoryRunStore(): RunStore & { runs: Run[] } {\n const runs: Run[] = [];\n return {\n runs,\n async load() {\n return [...runs];\n },\n async save(run) {\n const index = runs.findIndex((r) => r.id === run.id && r.pipelineId === run.pipelineId);\n if (index >= 0) runs[index] = run;\n else runs.unshift(run);\n },\n };\n}\n\nexport type { Dataset };\n"]}
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@surfaces-ui/pipelines",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Reference pipeline runner for Surfaces UI: builds datasets from one another on an Engine, with data quality rules",
5
+ "keywords": [
6
+ "surfaces-ui",
7
+ "analytics",
8
+ "data",
9
+ "pipelines",
10
+ "data-quality"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/teradata-labs/surfaces-ui.git",
16
+ "directory": "packages/pipelines"
17
+ },
18
+ "homepage": "https://github.com/teradata-labs/surfaces-ui#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/teradata-labs/surfaces-ui/issues"
21
+ },
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "NOTICE"
34
+ ],
35
+ "dependencies": {
36
+ "@bufbuild/protobuf": "^2.17.0",
37
+ "@surfaces-ui/data": "0.2.0",
38
+ "@surfaces-ui/engine": "0.2.0",
39
+ "@surfaces-ui/proto": "0.2.0",
40
+ "@surfaces-ui/sql": "0.2.0"
41
+ },
42
+ "devDependencies": {
43
+ "@surfaces-ui/engine-duckdb": "0.2.0"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "typecheck": "tsc -p tsconfig.json --noEmit",
52
+ "test": "vitest run --passWithNoTests"
53
+ }
6
54
  }