@surfaces-ui/dev-server 0.0.0-stage → 0.3.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 +202 -0
- package/NOTICE +4 -0
- package/README.md +33 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +44 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +217 -0
- package/dist/config.js +203 -0
- package/dist/config.js.map +1 -0
- package/dist/env.d.ts +13 -0
- package/dist/env.js +27 -0
- package/dist/env.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/pipelines-cli.d.ts +2 -0
- package/dist/pipelines-cli.js +126 -0
- package/dist/pipelines-cli.js.map +1 -0
- package/dist/server.d.ts +106 -0
- package/dist/server.js +272 -0
- package/dist/server.js.map +1 -0
- package/dist/store.d.ts +7 -0
- package/dist/store.js +88 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.d.ts +34 -0
- package/dist/stores.js +170 -0
- package/dist/stores.js.map +1 -0
- package/package.json +73 -3
package/dist/config.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { createDuckDbEngine, isRemotePath } from "@surfaces-ui/engine-duckdb";
|
|
5
|
+
import { createDataFusionEngine } from "@surfaces-ui/engine-datafusion";
|
|
6
|
+
import { createTeradataEngine, driverClient } from "@surfaces-ui/engine-teradata";
|
|
7
|
+
import { dbtPipelines as dbtPipelinesOf, defaultRelation, readArtifacts, semanticModelsFromDbt } from "@surfaces-ui/pipelines-dbt";
|
|
8
|
+
import { dbtCommand, targetDir } from "@surfaces-ui/pipelines-dbt/node";
|
|
9
|
+
import { SemanticModelSchema, SourceKind } from "@surfaces-ui/proto";
|
|
10
|
+
import { create } from "@bufbuild/protobuf";
|
|
11
|
+
import { semanticModelFromJson } from "@surfaces-ui/data";
|
|
12
|
+
import { fileDiscoveryStore } from "./store.js";
|
|
13
|
+
import { fileForms, filePipelineStore, fileRunStore, fileSemantics, fileSurfaceLibrary } from "./stores.js";
|
|
14
|
+
/**
|
|
15
|
+
* Reads a named secret from environment variables, so credentials stay out
|
|
16
|
+
* of config files and the repository. For the name `LAKE` it reads
|
|
17
|
+
* `LAKE_KEY_ID`, `LAKE_SECRET`, `LAKE_SESSION_TOKEN`, `LAKE_CONNECTION_STRING`
|
|
18
|
+
* `LAKE_TOKEN` and `LAKE_PASSWORD`, whichever are set.
|
|
19
|
+
*/
|
|
20
|
+
export function envSecrets(env = process.env) {
|
|
21
|
+
return (name) => {
|
|
22
|
+
const values = {
|
|
23
|
+
keyId: env[`${name}_KEY_ID`],
|
|
24
|
+
secret: env[`${name}_SECRET`],
|
|
25
|
+
sessionToken: env[`${name}_SESSION_TOKEN`],
|
|
26
|
+
connectionString: env[`${name}_CONNECTION_STRING`],
|
|
27
|
+
token: env[`${name}_TOKEN`],
|
|
28
|
+
password: env[`${name}_PASSWORD`],
|
|
29
|
+
};
|
|
30
|
+
return Object.values(values).some((v) => v) ? values : undefined;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Identity helper that gives `surfaces.config.ts` type checking. */
|
|
34
|
+
export function defineConfig(config) {
|
|
35
|
+
return config;
|
|
36
|
+
}
|
|
37
|
+
export const CONFIG_FILES = ["surfaces.config.ts", "surfaces.config.mjs", "surfaces.config.js"];
|
|
38
|
+
/** Loads a config file and resolves its relative paths. */
|
|
39
|
+
export async function loadConfig(file) {
|
|
40
|
+
const absolute = path.resolve(file);
|
|
41
|
+
const module = (await import(pathToFileURL(absolute).href));
|
|
42
|
+
const config = module.default;
|
|
43
|
+
if (!config || (!Array.isArray(config.sources) && !config.seeds)) {
|
|
44
|
+
throw new Error(`${file} must default-export defineConfig({ sources: [...] }) or defineConfig({ seeds: true })`);
|
|
45
|
+
}
|
|
46
|
+
return { config, dir: path.dirname(absolute) };
|
|
47
|
+
}
|
|
48
|
+
/** Opens the engines a config describes. */
|
|
49
|
+
export async function openSources(config, dir, resolveSecret = envSecrets()) {
|
|
50
|
+
const ids = new Set();
|
|
51
|
+
const sources = [];
|
|
52
|
+
const all = [...(config.sources ?? []), ...(config.seeds ? (await loadSeeds()).sources : [])];
|
|
53
|
+
for (const source of all) {
|
|
54
|
+
if (ids.has(source.id))
|
|
55
|
+
throw new Error(`Duplicate source id: ${source.id}`);
|
|
56
|
+
ids.add(source.id);
|
|
57
|
+
if (source.engine === "datafusion") {
|
|
58
|
+
sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.FILES, engine: await createDataFusionEngine({ baseUrl: source.baseUrl }) });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (source.engine === "teradata" && source.transport === "driver") {
|
|
62
|
+
const engine = await createTeradataEngine({ client: driverClient(source.connect, { database: source.database }), database: source.database, databases: source.databases, address: source.address });
|
|
63
|
+
sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (source.engine === "teradata") {
|
|
67
|
+
const engine = await createTeradataEngine({
|
|
68
|
+
baseUrl: source.baseUrl,
|
|
69
|
+
system: source.system,
|
|
70
|
+
user: source.user,
|
|
71
|
+
secret: source.secret,
|
|
72
|
+
database: source.database,
|
|
73
|
+
databases: source.databases,
|
|
74
|
+
session: source.session,
|
|
75
|
+
resolveSecret,
|
|
76
|
+
});
|
|
77
|
+
sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const engine = await createDuckDbEngine({
|
|
81
|
+
tables: source.tables.map((t) => ({ ...t, path: isRemotePath(t.path) ? t.path : path.resolve(dir, t.path) })),
|
|
82
|
+
connections: source.connections,
|
|
83
|
+
catalogs: source.catalogs?.map((c) => (c.kind === "duckdb" ? { ...c, uri: path.resolve(dir, c.uri) } : c)),
|
|
84
|
+
resolveSecret,
|
|
85
|
+
});
|
|
86
|
+
sources.push({ id: source.id, displayName: source.displayName, engine });
|
|
87
|
+
}
|
|
88
|
+
return sources;
|
|
89
|
+
}
|
|
90
|
+
/** The seeds package and the sources, pipelines and forms it adds. */
|
|
91
|
+
export async function loadSeeds() {
|
|
92
|
+
const module = await import("@surfaces-ui/seeds");
|
|
93
|
+
const dataDir = path.join(path.dirname(createRequire(import.meta.url).resolve("@surfaces-ui/seeds/package.json")), "data");
|
|
94
|
+
const sources = module.seedSources(dataDir);
|
|
95
|
+
const pipelines = module.seeds.flatMap((seed) => seed.pipelines.map((p) => ({ ...p, sourceId: seed.id })));
|
|
96
|
+
const forms = module.seeds.flatMap((seed) => seed.forms.map((f) => ({ id: f.id, title: f.title, description: f.description, target: `${seed.id}.${f.table}`, fields: f.fields })));
|
|
97
|
+
const semanticModels = module.seeds.flatMap((seed) => module.seedSemanticModels(seed));
|
|
98
|
+
return { sources, pipelines, forms, semanticModels, ids: module.seeds.map((s) => s.id) };
|
|
99
|
+
}
|
|
100
|
+
/** Each dbt project's backend options and its starter semantic models. A project whose artifacts cannot be read is reported and left out. */
|
|
101
|
+
async function dbtProjects(projects, dir) {
|
|
102
|
+
if (projects.length === 0)
|
|
103
|
+
return [];
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const project of projects) {
|
|
106
|
+
const read = targetDir(path.resolve(dir, project.targetDir));
|
|
107
|
+
try {
|
|
108
|
+
const artifacts = await readArtifacts(read);
|
|
109
|
+
const options = {
|
|
110
|
+
...(project.id ? { id: project.id } : {}),
|
|
111
|
+
...(project.name ? { name: project.name } : {}),
|
|
112
|
+
sourceId: project.sourceId,
|
|
113
|
+
read,
|
|
114
|
+
...(project.relationPrefix ? { relationOf: (node) => `${project.relationPrefix}.${defaultRelation(node)}` } : {}),
|
|
115
|
+
...(project.build ? { invoke: dbtCommand({ ...project.build, projectDir: path.resolve(dir, project.build.projectDir), ...(project.build.profilesDir ? { profilesDir: path.resolve(dir, project.build.profilesDir) } : {}) }) } : {}),
|
|
116
|
+
};
|
|
117
|
+
const semantic = project.semanticModels === false ? { models: [], skipped: [] } : semanticModelsFromDbt(artifacts, options);
|
|
118
|
+
if (semantic.skipped.length > 0)
|
|
119
|
+
console.warn(`[surfaces] dbt ${artifacts.manifest.metadata?.project_name}: ${semantic.skipped.length} semantic fields left out. ${semantic.skipped.join(" ")}`);
|
|
120
|
+
out.push({ options, models: semantic.models.map((m) => create(SemanticModelSchema, m)) });
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
console.warn(`[surfaces] The dbt project at ${project.targetDir} was left out: ${error instanceof Error ? error.message : String(error)}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
export async function serverOptions(config, sources, dir = process.cwd()) {
|
|
129
|
+
let embedder;
|
|
130
|
+
if (config.discovery?.embedder === "local") {
|
|
131
|
+
try {
|
|
132
|
+
const name = "@surfaces-ui/embedder-local";
|
|
133
|
+
embedder = (await import(name)).localEmbedder();
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
console.warn("[surfaces] @surfaces-ui/embedder-local is not installed; search will be keyword only.");
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const seeded = config.seeds ? await loadSeeds() : undefined;
|
|
140
|
+
const storeDir = path.resolve(dir, config.discovery?.storeDir ?? ".surfaces");
|
|
141
|
+
const forms = [...(config.forms ?? []), ...(seeded?.forms ?? [])];
|
|
142
|
+
const dbt = await dbtProjects(config.dbt ?? [], dir);
|
|
143
|
+
return {
|
|
144
|
+
sources,
|
|
145
|
+
maxResultRows: config.maxResultRows,
|
|
146
|
+
storedResults: config.storedResults,
|
|
147
|
+
...(config.agent ? { agent: config.agent } : {}),
|
|
148
|
+
...(config.models ? { models: config.models } : {}),
|
|
149
|
+
pipelines: [...(config.pipelines ?? []), ...(seeded?.pipelines ?? [])],
|
|
150
|
+
...(dbt.length > 0 ? { externalPipelines: ({ onFinished }) => dbt.map((project) => dbtPipelinesOf({ ...project.options, onFinished })) } : {}),
|
|
151
|
+
// Run history outlives a restart.
|
|
152
|
+
pipelineRuns: fileRunStore(path.join(storeDir, "pipeline-runs")),
|
|
153
|
+
...(config.savedPipelines
|
|
154
|
+
? { savedPipelines: filePipelineStore(path.resolve(dir, (typeof config.savedPipelines === "object" && config.savedPipelines.dir) || path.join(storeDir, "pipelines"))) }
|
|
155
|
+
: {}),
|
|
156
|
+
forms: forms.length > 0 ? fileForms(path.join(storeDir, "forms"), forms) : undefined,
|
|
157
|
+
library: fileSurfaceLibrary(path.join(storeDir, "surfaces")),
|
|
158
|
+
semantics: fileSemantics(path.resolve(dir, config.semantic?.dir ?? path.join(storeDir, "semantic")), {
|
|
159
|
+
models: withDbtModels(starterModels([...(config.semantic?.models ?? []), ...(seeded?.semanticModels ?? [])]), dbt.flatMap((p) => p.models)),
|
|
160
|
+
}),
|
|
161
|
+
discovery: {
|
|
162
|
+
embedder,
|
|
163
|
+
allowSampleValues: [...(config.discovery?.allowSampleValues ?? []), ...(seeded?.ids ?? [])],
|
|
164
|
+
store: fileDiscoveryStore(storeDir),
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* dbt's semantic models beside the others. Names are shared by every source,
|
|
170
|
+
* so one whose name is taken is renamed after its project (orders becomes
|
|
171
|
+
* shop_orders) and the rename is reported.
|
|
172
|
+
*/
|
|
173
|
+
function withDbtModels(starters, fromDbt) {
|
|
174
|
+
const taken = new Set(starters.map((m) => m.name));
|
|
175
|
+
const out = [...starters];
|
|
176
|
+
for (const model of fromDbt) {
|
|
177
|
+
let name = model.name;
|
|
178
|
+
if (taken.has(name)) {
|
|
179
|
+
name = `${model.dataset?.pipelineId ?? "dbt"}_${model.name}`.toLowerCase().replace(/[^a-z0-9_]+/g, "_").slice(0, 64);
|
|
180
|
+
if (taken.has(name)) {
|
|
181
|
+
console.warn(`[surfaces] dbt's semantic model ${model.name} was left out: the names ${model.name} and ${name} are taken.`);
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
console.warn(`[surfaces] dbt's semantic model ${model.name} is named ${name} here, since another model is named ${model.name}.`);
|
|
185
|
+
}
|
|
186
|
+
taken.add(name);
|
|
187
|
+
out.push(name === model.name ? model : { ...model, name });
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
/** Starter models from config, in the contract's JSON form; one that does not parse is reported and left out. */
|
|
192
|
+
function starterModels(json) {
|
|
193
|
+
return json.flatMap((item) => {
|
|
194
|
+
try {
|
|
195
|
+
return [semanticModelFromJson(item)];
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
console.warn(`[surfaces] A semantic model in the config was left out: ${error instanceof Error ? error.message : String(error)}`);
|
|
199
|
+
return [];
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAwF,kBAAkB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACpK,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAyB,oBAAoB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAEzG,OAAO,EAA0C,YAAY,IAAI,cAAc,EAAE,eAAe,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAC3K,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAA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AAC,mCAAmC,KAAK,CAAC,IAAI,aAAa,IAAI,uCAAuC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC;QACnI,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAChB,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,iHAAiH;AACjH,SAAS,aAAa,CAAC,IAAiB;IACtC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC3B,IAAI,CAAC;YACH,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,2DAA2D,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClI,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { DataSource, ModelSettings } from \"@surfaces-ui/data\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Embedder } from \"@surfaces-ui/discovery\";\nimport { type DuckDbCatalog, type DuckDbConnection, type DuckDbSecretValues, type DuckDbTable, createDuckDbEngine, isRemotePath } from \"@surfaces-ui/engine-duckdb\";\nimport { createDataFusionEngine } from \"@surfaces-ui/engine-datafusion\";\nimport { type DriverConnection, createTeradataEngine, driverClient } from \"@surfaces-ui/engine-teradata\";\nimport type { PipelineDefinition } from \"@surfaces-ui/pipelines\";\nimport { type DbtNode, type DbtPipelinesOptions, dbtPipelines as dbtPipelinesOf, defaultRelation, readArtifacts, semanticModelsFromDbt } from \"@surfaces-ui/pipelines-dbt\";\nimport { dbtCommand, targetDir } from \"@surfaces-ui/pipelines-dbt/node\";\nimport { type SemanticModel, SemanticModelSchema, SourceKind } from \"@surfaces-ui/proto\";\nimport { type JsonValue, create } from \"@bufbuild/protobuf\";\nimport { semanticModelFromJson } from \"@surfaces-ui/data\";\nimport type { StoredResultsOptions } from \"@surfaces-ui/engine-service\";\nimport type { AgentServices, ServerSource, SurfacesServerOptions } from \"./server.js\";\nimport { fileDiscoveryStore } from \"./store.js\";\nimport { type FormConfig, fileForms, filePipelineStore, fileRunStore, fileSemantics, fileSurfaceLibrary } from \"./stores.js\";\n\n/** A DuckDB-backed source: files and lake tables exposed as named tables. */\nexport interface DuckDbSourceConfig {\n id: string;\n displayName?: string;\n engine: \"duckdb\";\n /** Local paths are relative to the config file; remote ones (`s3://`, `gs://`, `az://`, `https://`) need a connection that covers them. */\n tables: DuckDbTable[];\n /**\n * Object stores and web locations the tables read from. Each names a\n * secret; the values come from the server's environment (see `envSecrets`),\n * never from this file.\n */\n connections?: DuckDbConnection[];\n /** Catalogs to attach read-only: an Iceberg REST catalog, or a DuckDB database file. */\n catalogs?: DuckDbCatalog[];\n}\n\n/** A DataFusion server reached over its HTTP SQL endpoint. Read-only: no kept results and no pipelines. */\nexport interface DataFusionSourceConfig {\n id: string;\n displayName?: string;\n engine: \"datafusion\";\n /** Address of the server, e.g. http://localhost:8080. */\n baseUrl: string;\n}\n\n/**\n * A Teradata system reached through Teradata Query Service (its REST API).\n * Read-only: no kept results, no pipelines and no time travel. The password\n * or JWT is never written here: `secret` names it, and the server reads\n * `<NAME>_PASSWORD` or `<NAME>_TOKEN` from its environment (see `envSecrets`).\n */\nexport interface TeradataSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n /** Address of Query Service up to `/systems`, e.g. https://vantage.example.com:1443. */\n baseUrl: string;\n /** The system name configured in Query Service. */\n system: string;\n /** Database user. Needed with a password; not with a JWT. The user should hold SELECT rights only. */\n user?: string;\n /** Name of the secret holding the password or JWT. */\n secret: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n transport?: \"query-service\";\n /** `explicit` (default) keeps one session set to UTC; `implicit` lets requests run side by side. See `QueryServiceOptions.session`. */\n session?: \"explicit\" | \"implicit\";\n}\n\n/**\n * A Teradata system reached through a driver connection the config opens\n * itself, for example with the `teradatasql` package installed outside this\n * repo. The server never imports a driver: `connect` is the config's own\n * code, and it reads the password from the environment, never from here.\n */\nexport interface TeradataDriverSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n transport: \"driver\";\n /** Opens the connection, on first use. Its errors are not passed on, since a driver's message can repeat its settings. */\n connect(): DriverConnection | Promise<DriverConnection>;\n /** Shown as where this source connects, such as the host name. Never a credential. */\n address?: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n}\n\nexport type SourceConfig = DuckDbSourceConfig | DataFusionSourceConfig | TeradataSourceConfig | TeradataDriverSourceConfig;\n\nexport interface DiscoveryConfig {\n /**\n * \"local\" runs a small embedding model on this machine for semantic search\n * (needs `@surfaces-ui/embedder-local`; the model downloads once to a cache\n * outside the repo). Omit for keyword search only.\n */\n embedder?: \"local\";\n /** Source IDs whose data values may be profiled, shown and put in agent context. Default: none. */\n allowSampleValues?: string[];\n /** Folder for context packs and accepted descriptions, relative to the config file. Defaults to `.surfaces`. */\n storeDir?: string;\n}\n\nexport interface SurfacesConfig {\n /** May be left out when `seeds` is on. */\n sources?: SourceConfig[];\n /**\n * Serve the six synthetic industry models from `@surfaces-ui/seeds` as the\n * sources `retail`, `healthcare`, `fraud`, `telco`, `transportation` and\n * `manufacturing`, with their pipelines and forms. Their data is invented,\n * so their values may be shown (they are added to `allowSampleValues`).\n */\n seeds?: boolean;\n /**\n * Semantic models: the dimensions, measures and metrics of a project's\n * queries, which explorers and reports take their fields from. They are\n * kept as one JSON file each in `dir` (default `<storeDir>/semantic`), so\n * point it at a folder in your repo to review and commit them. `models`\n * (in the contract's JSON form) are added when the folder has none of\n * that name; with `seeds` on, each seed's starter models are too.\n */\n semantic?: { dir?: string; models?: JsonValue[] };\n /**\n * Forms people can submit. Fields and checks are set here; a client sends\n * only a form id and values. Submissions are appended to\n * `<storeDir>/forms/<form id>.jsonl`.\n */\n forms?: FormConfig[];\n discovery?: DiscoveryConfig;\n /** Port for `surfaces-dev`. Defaults to 5220. */\n port?: number;\n maxResultRows?: number;\n /**\n * Pipelines the server can run: datasets built from one another by SQL,\n * with data quality rules. The SQL lives here, never in the browser.\n */\n pipelines?: PipelineDefinition[];\n /**\n * Lets people save pipelines they approved (`SavePipeline`), typically ones\n * an agent proposed. Each is checked by the server before it is kept, as\n * one JSON file with its versions in `<storeDir>/pipelines/` (or `dir`).\n * Pipelines in `pipelines` stay as written here. Off by default.\n */\n savedPipelines?: boolean | { dir?: string };\n /**\n * dbt projects, served as pipelines read from their artifacts: models,\n * seeds, snapshots and sources as datasets, dbt's tests as checks, and its\n * runs and source freshness. dbt stays what builds them.\n */\n dbt?: DbtProjectConfig[];\n /** Keeping query results so views do not re-run the query. `false` turns it off. */\n storedResults?: StoredResultsOptions | false;\n /**\n * An agent to serve as `AgentService`, such as\n * `anthropicAgent({ client: new Anthropic(), system: catalogPrompt(analyticsCatalog) })`.\n * Its model key is read from this server's environment, never from config.\n * A function gets the server's data source, for tools that list tables or\n * run queries.\n */\n agent?: AgentBackend | ((dataSource: DataSource, services: AgentServices) => AgentBackend);\n /**\n * Which model each agent backend uses, shown and changed from a page\n * (`ModelService`). Build it with `modelSettings` from `@surfaces-ui/data`.\n * Keys stay in the environment; nothing here carries one.\n */\n models?: ModelSettings;\n}\n\n/**\n * Reads a named secret from environment variables, so credentials stay out\n * of config files and the repository. For the name `LAKE` it reads\n * `LAKE_KEY_ID`, `LAKE_SECRET`, `LAKE_SESSION_TOKEN`, `LAKE_CONNECTION_STRING`\n * `LAKE_TOKEN` and `LAKE_PASSWORD`, whichever are set.\n */\nexport function envSecrets(env: Record<string, string | undefined> = process.env): (name: string) => DuckDbSecretValues | undefined {\n return (name) => {\n const values: DuckDbSecretValues = {\n keyId: env[`${name}_KEY_ID`],\n secret: env[`${name}_SECRET`],\n sessionToken: env[`${name}_SESSION_TOKEN`],\n connectionString: env[`${name}_CONNECTION_STRING`],\n token: env[`${name}_TOKEN`],\n password: env[`${name}_PASSWORD`],\n };\n return Object.values(values).some((v) => v) ? values : undefined;\n };\n}\n\n/** Identity helper that gives `surfaces.config.ts` type checking. */\nexport function defineConfig(config: SurfacesConfig): SurfacesConfig {\n return config;\n}\n\nexport const CONFIG_FILES = [\"surfaces.config.ts\", \"surfaces.config.mjs\", \"surfaces.config.js\"];\n\n/** Loads a config file and resolves its relative paths. */\nexport async function loadConfig(file: string): Promise<{ config: SurfacesConfig; dir: string }> {\n const absolute = path.resolve(file);\n const module = (await import(pathToFileURL(absolute).href)) as { default?: SurfacesConfig };\n const config = module.default;\n if (!config || (!Array.isArray(config.sources) && !config.seeds)) {\n throw new Error(`${file} must default-export defineConfig({ sources: [...] }) or defineConfig({ seeds: true })`);\n }\n return { config, dir: path.dirname(absolute) };\n}\n\n/** Opens the engines a config describes. */\nexport async function openSources(\n config: SurfacesConfig,\n dir: string,\n resolveSecret: (name: string) => DuckDbSecretValues | undefined | Promise<DuckDbSecretValues | undefined> = envSecrets(),\n): Promise<ServerSource[]> {\n const ids = new Set<string>();\n const sources: ServerSource[] = [];\n const all = [...(config.sources ?? []), ...(config.seeds ? (await loadSeeds()).sources : [])];\n for (const source of all) {\n if (ids.has(source.id)) throw new Error(`Duplicate source id: ${source.id}`);\n ids.add(source.id);\n if (source.engine === \"datafusion\") {\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.FILES, engine: await createDataFusionEngine({ baseUrl: source.baseUrl }) });\n continue;\n }\n if (source.engine === \"teradata\" && source.transport === \"driver\") {\n const engine = await createTeradataEngine({ client: driverClient(source.connect, { database: source.database }), database: source.database, databases: source.databases, address: source.address });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n if (source.engine === \"teradata\") {\n const engine = await createTeradataEngine({\n baseUrl: source.baseUrl,\n system: source.system,\n user: source.user,\n secret: source.secret,\n database: source.database,\n databases: source.databases,\n session: source.session,\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n const engine = await createDuckDbEngine({\n tables: source.tables.map((t) => ({ ...t, path: isRemotePath(t.path) ? t.path : path.resolve(dir, t.path) })),\n connections: source.connections,\n catalogs: source.catalogs?.map((c) => (c.kind === \"duckdb\" ? { ...c, uri: path.resolve(dir, c.uri) } : c)),\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, engine });\n }\n return sources;\n}\n\ntype SeedsModule = typeof import(\"@surfaces-ui/seeds\");\n\n/** The seeds package and the sources, pipelines and forms it adds. */\nexport async function loadSeeds() {\n const module: SeedsModule = await import(\"@surfaces-ui/seeds\");\n const dataDir = path.join(path.dirname(createRequire(import.meta.url).resolve(\"@surfaces-ui/seeds/package.json\")), \"data\");\n const sources: DuckDbSourceConfig[] = module.seedSources(dataDir);\n const pipelines: PipelineDefinition[] = module.seeds.flatMap((seed) => seed.pipelines.map((p) => ({ ...p, sourceId: seed.id })));\n const forms: FormConfig[] = module.seeds.flatMap((seed) =>\n seed.forms.map((f) => ({ id: f.id, title: f.title, description: f.description, target: `${seed.id}.${f.table}`, fields: f.fields })),\n );\n const semanticModels: JsonValue[] = module.seeds.flatMap((seed) => module.seedSemanticModels(seed) as unknown as JsonValue[]);\n return { sources, pipelines, forms, semanticModels, ids: module.seeds.map((s) => s.id) };\n}\n\n/** A dbt project the server reads. Paths are relative to the config file. */\nexport interface DbtProjectConfig {\n /** The pipeline's id. Defaults to the project's name. */\n id?: string;\n name?: string;\n /** The source whose engine reads the warehouse dbt builds into. */\n sourceId: string;\n /** Where dbt writes its artifacts: the project's `target` directory. */\n targetDir: string;\n /**\n * Lets a person, or an agent they approve, start `dbt build` (or\n * `dbt compile` to check) from here. Needs `projectDir`. Credentials stay\n * in dbt's profile and this server's environment. Off by default: runs\n * made by dbt itself are reported either way.\n */\n build?: { projectDir: string; profilesDir?: string; target?: string; command?: string };\n /** Starter semantic models from dbt's semantic layer (semantic_manifest.json). On by default. */\n semanticModels?: boolean;\n /**\n * Put before each table's `schema.alias` when the source reads dbt's\n * database under a name of its own: the name a DuckDB source attaches the\n * database file as, for one.\n */\n relationPrefix?: string;\n}\n\n/** Each dbt project's backend options and its starter semantic models. A project whose artifacts cannot be read is reported and left out. */\nasync function dbtProjects(projects: DbtProjectConfig[], dir: string) {\n if (projects.length === 0) return [];\n const out: { options: Omit<DbtPipelinesOptions, \"onFinished\">; models: SemanticModel[] }[] = [];\n for (const project of projects) {\n const read = targetDir(path.resolve(dir, project.targetDir));\n try {\n const artifacts = await readArtifacts(read);\n const options = {\n ...(project.id ? { id: project.id } : {}),\n ...(project.name ? { name: project.name } : {}),\n sourceId: project.sourceId,\n read,\n ...(project.relationPrefix ? { relationOf: (node: DbtNode) => `${project.relationPrefix}.${defaultRelation(node)}` } : {}),\n ...(project.build ? { invoke: dbtCommand({ ...project.build, projectDir: path.resolve(dir, project.build.projectDir), ...(project.build.profilesDir ? { profilesDir: path.resolve(dir, project.build.profilesDir) } : {}) }) } : {}),\n };\n const semantic = project.semanticModels === false ? { models: [], skipped: [] } : semanticModelsFromDbt(artifacts, options);\n if (semantic.skipped.length > 0) console.warn(`[surfaces] dbt ${artifacts.manifest.metadata?.project_name}: ${semantic.skipped.length} semantic fields left out. ${semantic.skipped.join(\" \")}`);\n out.push({ options, models: semantic.models.map((m) => create(SemanticModelSchema, m)) });\n } catch (error) {\n console.warn(`[surfaces] The dbt project at ${project.targetDir} was left out: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return out;\n}\n\nexport async function serverOptions(config: SurfacesConfig, sources: ServerSource[], dir = process.cwd()): Promise<SurfacesServerOptions> {\n let embedder: Embedder | undefined;\n if (config.discovery?.embedder === \"local\") {\n try {\n const name = \"@surfaces-ui/embedder-local\";\n embedder = ((await import(name)) as { localEmbedder(): Embedder }).localEmbedder();\n } catch {\n console.warn(\"[surfaces] @surfaces-ui/embedder-local is not installed; search will be keyword only.\");\n }\n }\n const seeded = config.seeds ? await loadSeeds() : undefined;\n const storeDir = path.resolve(dir, config.discovery?.storeDir ?? \".surfaces\");\n const forms = [...(config.forms ?? []), ...(seeded?.forms ?? [])];\n const dbt = await dbtProjects(config.dbt ?? [], dir);\n return {\n sources,\n maxResultRows: config.maxResultRows,\n storedResults: config.storedResults,\n ...(config.agent ? { agent: config.agent } : {}),\n ...(config.models ? { models: config.models } : {}),\n pipelines: [...(config.pipelines ?? []), ...(seeded?.pipelines ?? [])],\n ...(dbt.length > 0 ? { externalPipelines: ({ onFinished }) => dbt.map((project) => dbtPipelinesOf({ ...project.options, onFinished })) } : {}),\n // Run history outlives a restart.\n pipelineRuns: fileRunStore(path.join(storeDir, \"pipeline-runs\")),\n ...(config.savedPipelines\n ? { savedPipelines: filePipelineStore(path.resolve(dir, (typeof config.savedPipelines === \"object\" && config.savedPipelines.dir) || path.join(storeDir, \"pipelines\"))) }\n : {}),\n forms: forms.length > 0 ? fileForms(path.join(storeDir, \"forms\"), forms) : undefined,\n library: fileSurfaceLibrary(path.join(storeDir, \"surfaces\")),\n semantics: fileSemantics(path.resolve(dir, config.semantic?.dir ?? path.join(storeDir, \"semantic\")), {\n models: withDbtModels(starterModels([...(config.semantic?.models ?? []), ...(seeded?.semanticModels ?? [])]), dbt.flatMap((p) => p.models)),\n }),\n discovery: {\n embedder,\n allowSampleValues: [...(config.discovery?.allowSampleValues ?? []), ...(seeded?.ids ?? [])],\n store: fileDiscoveryStore(storeDir),\n },\n };\n}\n\n/**\n * dbt's semantic models beside the others. Names are shared by every source,\n * so one whose name is taken is renamed after its project (orders becomes\n * shop_orders) and the rename is reported.\n */\nfunction withDbtModels(starters: SemanticModel[], fromDbt: SemanticModel[]): SemanticModel[] {\n const taken = new Set(starters.map((m) => m.name));\n const out = [...starters];\n for (const model of fromDbt) {\n let name = model.name;\n if (taken.has(name)) {\n name = `${model.dataset?.pipelineId ?? \"dbt\"}_${model.name}`.toLowerCase().replace(/[^a-z0-9_]+/g, \"_\").slice(0, 64);\n if (taken.has(name)) {\n console.warn(`[surfaces] dbt's semantic model ${model.name} was left out: the names ${model.name} and ${name} are taken.`);\n continue;\n }\n console.warn(`[surfaces] dbt's semantic model ${model.name} is named ${name} here, since another model is named ${model.name}.`);\n }\n taken.add(name);\n out.push(name === model.name ? model : { ...model, name });\n }\n return out;\n}\n\n/** Starter models from config, in the contract's JSON form; one that does not parse is reported and left out. */\nfunction starterModels(json: JsonValue[]): SemanticModel[] {\n return json.flatMap((item) => {\n try {\n return [semanticModelFromJson(item)];\n } catch (error) {\n console.warn(`[surfaces] A semantic model in the config was left out: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n });\n}\n"]}
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The file the dev server reads secrets from, next to `surfaces.config.ts`. It must be git-ignored. */
|
|
2
|
+
export declare const ENV_FILE = ".env.local";
|
|
3
|
+
/**
|
|
4
|
+
* Reads `.env.local` in `dir` into `env`, so a key such as
|
|
5
|
+
* `ANTHROPIC_API_KEY` can live in a git-ignored file instead of the shell.
|
|
6
|
+
* A variable already set in the environment wins over the file. Returns the
|
|
7
|
+
* names it set and never the values, so a caller can say what it read
|
|
8
|
+
* without printing a secret.
|
|
9
|
+
*/
|
|
10
|
+
export declare function loadEnvFile(dir: string, env?: NodeJS.ProcessEnv): {
|
|
11
|
+
file?: string;
|
|
12
|
+
names: string[];
|
|
13
|
+
};
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseEnv } from "node:util";
|
|
4
|
+
/** The file the dev server reads secrets from, next to `surfaces.config.ts`. It must be git-ignored. */
|
|
5
|
+
export const ENV_FILE = ".env.local";
|
|
6
|
+
/**
|
|
7
|
+
* Reads `.env.local` in `dir` into `env`, so a key such as
|
|
8
|
+
* `ANTHROPIC_API_KEY` can live in a git-ignored file instead of the shell.
|
|
9
|
+
* A variable already set in the environment wins over the file. Returns the
|
|
10
|
+
* names it set and never the values, so a caller can say what it read
|
|
11
|
+
* without printing a secret.
|
|
12
|
+
*/
|
|
13
|
+
export function loadEnvFile(dir, env = process.env) {
|
|
14
|
+
const file = path.join(dir, ENV_FILE);
|
|
15
|
+
if (!fs.existsSync(file))
|
|
16
|
+
return { names: [] };
|
|
17
|
+
const values = parseEnv(fs.readFileSync(file, "utf8"));
|
|
18
|
+
const names = [];
|
|
19
|
+
for (const [name, value] of Object.entries(values)) {
|
|
20
|
+
if (env[name] !== undefined || value === undefined || value === "")
|
|
21
|
+
continue;
|
|
22
|
+
env[name] = value;
|
|
23
|
+
names.push(name);
|
|
24
|
+
}
|
|
25
|
+
return { file, names };
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=env.js.map
|
package/dist/env.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,wGAAwG;AACxG,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW,EAAE,GAAG,GAAsB,OAAO,CAAC,GAAG;IAC3E,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACtC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;IAC/C,MAAM,MAAM,GAAG,QAAQ,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;IACvD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnD,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE;YAAE,SAAS;QAC7E,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;QAClB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseEnv } from \"node:util\";\n\n/** The file the dev server reads secrets from, next to `surfaces.config.ts`. It must be git-ignored. */\nexport const ENV_FILE = \".env.local\";\n\n/**\n * Reads `.env.local` in `dir` into `env`, so a key such as\n * `ANTHROPIC_API_KEY` can live in a git-ignored file instead of the shell.\n * A variable already set in the environment wins over the file. Returns the\n * names it set and never the values, so a caller can say what it read\n * without printing a secret.\n */\nexport function loadEnvFile(dir: string, env: NodeJS.ProcessEnv = process.env): { file?: string; names: string[] } {\n const file = path.join(dir, ENV_FILE);\n if (!fs.existsSync(file)) return { names: [] };\n const values = parseEnv(fs.readFileSync(file, \"utf8\"));\n const names: string[] = [];\n for (const [name, value] of Object.entries(values)) {\n if (env[name] !== undefined || value === undefined || value === \"\") continue;\n env[name] = value;\n names.push(name);\n }\n return { file, names };\n}\n"]}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC","sourcesContent":["export * from \"./config.js\";\nexport * from \"./server.js\";\nexport * from \"./store.js\";\nexport * from \"./env.js\";\nexport * from \"./stores.js\";\n"]}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { toJson } from "@bufbuild/protobuf";
|
|
5
|
+
import { CheckSeverity, DatasetKind, PipelineSchema, RefreshKind, RunSchema, RunState } from "@surfaces-ui/proto";
|
|
6
|
+
import { CONFIG_FILES, loadConfig, openSources, serverOptions } from "./config.js";
|
|
7
|
+
import { loadEnvFile } from "./env.js";
|
|
8
|
+
import { createSurfacesServer } from "./server.js";
|
|
9
|
+
const USAGE = `Usage: surfaces-pipelines <command> [options]
|
|
10
|
+
|
|
11
|
+
list The pipelines the config defines or a person saved
|
|
12
|
+
describe <id> Datasets, what each reads, grain, key, columns and checks
|
|
13
|
+
check <id> Checks the pipeline without building anything
|
|
14
|
+
run <id> Builds the pipeline, then runs its checks
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
--select <name> Only this dataset; name+ adds what reads it, +name what it reads (repeatable)
|
|
18
|
+
--full-refresh --yes Clear the chosen tables first; needs --yes, since it destroys data
|
|
19
|
+
--json Print the result as JSON
|
|
20
|
+
--config <file> The config to read (default: ${CONFIG_FILES[0]})
|
|
21
|
+
|
|
22
|
+
Exits 1 when a dataset fails to build or a check that fails the run does, so cron and CI can use it.`;
|
|
23
|
+
const args = process.argv.slice(2);
|
|
24
|
+
const has = (name) => args.includes(name);
|
|
25
|
+
const values = (name) => args.flatMap((arg, i) => (arg === name && args[i + 1] ? [args[i + 1]] : []));
|
|
26
|
+
const positional = args.filter((arg, i) => !arg.startsWith("--") && !["--select", "--config"].includes(args[i - 1] ?? ""));
|
|
27
|
+
const [command, id] = positional;
|
|
28
|
+
const json = has("--json");
|
|
29
|
+
const bigints = (_, value) => (typeof value === "bigint" ? Number(value) : value);
|
|
30
|
+
const print = (value) => console.log(JSON.stringify(value, bigints, 2));
|
|
31
|
+
const STATE = { [RunState.COMPLETED]: "built", [RunState.FAILED]: "failed", [RunState.SKIPPED]: "skipped", [RunState.CANCELLED]: "cancelled", [RunState.RUNNING]: "running", [RunState.QUEUED]: "queued" };
|
|
32
|
+
async function open() {
|
|
33
|
+
const file = values("--config")[0] ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(f)));
|
|
34
|
+
// Secrets come from the environment or a git-ignored .env.local beside the config, as for the dev server.
|
|
35
|
+
loadEnvFile(path.dirname(path.resolve(file ?? CONFIG_FILES[0])));
|
|
36
|
+
const { config, dir } = file ? await loadConfig(file) : { config: { seeds: true }, dir: process.cwd() };
|
|
37
|
+
const sources = await openSources(config, dir);
|
|
38
|
+
const server = await createSurfacesServer({ ...(await serverOptions(config, sources, dir)), discovery: false });
|
|
39
|
+
if (!server.pipelines)
|
|
40
|
+
throw new Error("This config defines no pipelines.");
|
|
41
|
+
return { pipelines: server.pipelines, close: () => server.close() };
|
|
42
|
+
}
|
|
43
|
+
function describe(pipeline) {
|
|
44
|
+
const lines = [`${pipeline.summary?.name} (${pipeline.summary?.id}) on ${pipeline.summary?.sourceId}${pipeline.version ? `, version ${pipeline.version}` : ""}`];
|
|
45
|
+
if (pipeline.summary?.description)
|
|
46
|
+
lines.push(pipeline.summary.description);
|
|
47
|
+
for (const dataset of pipeline.datasets.filter((d) => d.sql)) {
|
|
48
|
+
lines.push("", `${dataset.name}${dataset.layer ? ` [${dataset.layer}]` : ""}${dataset.grain ? `: ${dataset.grain}` : ""}`);
|
|
49
|
+
if (dataset.inputs.length > 0)
|
|
50
|
+
lines.push(` reads ${dataset.inputs.join(", ")}${dataset.inputsDeclared ? "" : " (worked out from the query)"}`);
|
|
51
|
+
if (dataset.primaryKey.length > 0)
|
|
52
|
+
lines.push(` key ${dataset.primaryKey.join(", ")}`);
|
|
53
|
+
for (const column of dataset.columns)
|
|
54
|
+
lines.push(` ${column.name}${column.type ? ` ${column.type}` : ""}${column.description ? ` — ${column.description}` : ""}`);
|
|
55
|
+
for (const check of dataset.checks)
|
|
56
|
+
lines.push(` check ${check.name}${check.severity === CheckSeverity.WARN ? " (warns)" : ""}`);
|
|
57
|
+
if (dataset.builtAt)
|
|
58
|
+
lines.push(` built ${dataset.builtAt} by ${dataset.lastRunId}`);
|
|
59
|
+
}
|
|
60
|
+
return lines.join("\n");
|
|
61
|
+
}
|
|
62
|
+
function report(run, views) {
|
|
63
|
+
const lines = [`${run.id}: ${STATE[run.state] === "built" ? "completed" : (STATE[run.state] ?? "unknown")}${run.dryRun ? " (checked, nothing built)" : ""}`];
|
|
64
|
+
for (const dataset of run.datasetRuns) {
|
|
65
|
+
const built = dataset.state === RunState.COMPLETED || dataset.rowsWritten > 0n;
|
|
66
|
+
lines.push(` ${dataset.name}: ${STATE[dataset.state] ?? "?"}${built ? (views.has(dataset.name) ? " as a view" : `, ${Number(dataset.rowsWritten).toLocaleString("en")} rows`) : ""}`);
|
|
67
|
+
for (const check of dataset.checks)
|
|
68
|
+
lines.push(` ${check.failedRecords > 0n ? (check.severity === CheckSeverity.WARN ? "warn" : "FAIL") : "pass"} ${check.name}: ${check.summary}`);
|
|
69
|
+
if (dataset.errorMessage && dataset.checks.length === 0)
|
|
70
|
+
lines.push(` ${dataset.errorMessage}`);
|
|
71
|
+
}
|
|
72
|
+
if (run.errorMessage)
|
|
73
|
+
lines.push(run.errorMessage);
|
|
74
|
+
return lines.join("\n");
|
|
75
|
+
}
|
|
76
|
+
async function main() {
|
|
77
|
+
if (!command || has("--help") || !["list", "describe", "check", "run"].includes(command) || (command !== "list" && !id)) {
|
|
78
|
+
console.error(USAGE);
|
|
79
|
+
return 2;
|
|
80
|
+
}
|
|
81
|
+
const fullRefresh = has("--full-refresh");
|
|
82
|
+
if (fullRefresh && !has("--yes")) {
|
|
83
|
+
console.error("A full refresh clears the chosen tables before building them. Add --yes to go ahead.");
|
|
84
|
+
return 2;
|
|
85
|
+
}
|
|
86
|
+
const { pipelines, close } = await open();
|
|
87
|
+
try {
|
|
88
|
+
if (command === "list") {
|
|
89
|
+
const { pipelines: list } = await pipelines.listPipelines({});
|
|
90
|
+
if (json)
|
|
91
|
+
print(list.map((p) => ({ id: p.id, name: p.name, sourceId: p.sourceId, datasets: p.datasetCount, latestRun: p.latestRun && { id: p.latestRun.id, state: STATE[p.latestRun.state] } })));
|
|
92
|
+
else
|
|
93
|
+
for (const p of list)
|
|
94
|
+
console.log(`${p.id}\t${p.datasetCount} datasets\t${p.latestRun ? `last run ${STATE[p.latestRun.state] ?? "?"}` : "never run"}\t${p.name}`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
if (command === "describe") {
|
|
98
|
+
const { pipeline } = await pipelines.getPipeline({ id });
|
|
99
|
+
if (json)
|
|
100
|
+
print(toJson(PipelineSchema, pipeline));
|
|
101
|
+
else
|
|
102
|
+
console.log(describe(pipeline));
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
let run = (await pipelines.startRun({ pipelineId: id, select: values("--select"), dryRun: command === "check", refreshKind: fullRefresh ? RefreshKind.FULL_REFRESH : RefreshKind.REFRESH, confirmFullRefresh: fullRefresh, trigger: "cli", startedBy: process.env.USER ? `${process.env.USER} (cli)` : "cli" })).run;
|
|
106
|
+
while (run.state === RunState.RUNNING) {
|
|
107
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
108
|
+
run = (await pipelines.getRun({ pipelineId: id, runId: run.id })).run;
|
|
109
|
+
}
|
|
110
|
+
if (json)
|
|
111
|
+
print(toJson(RunSchema, run));
|
|
112
|
+
else {
|
|
113
|
+
const { pipeline } = await pipelines.getPipeline({ id });
|
|
114
|
+
console.log(report(run, new Set(pipeline?.datasets.filter((d) => d.kind === DatasetKind.VIEW).map((d) => d.name))));
|
|
115
|
+
}
|
|
116
|
+
return run.state === RunState.COMPLETED ? 0 : 1;
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await close();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
main().then((code) => process.exit(code), (error) => {
|
|
123
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
124
|
+
process.exit(1);
|
|
125
|
+
});
|
|
126
|
+
//# sourceMappingURL=pipelines-cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipelines-cli.js","sourceRoot":"","sources":["../src/pipelines-cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,aAAa,EAAE,WAAW,EAAiB,cAAc,EAAE,WAAW,EAAY,SAAS,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC3I,OAAO,EAAE,YAAY,EAAuB,UAAU,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,KAAK,GAAG;;;;;;;;;;;4DAW8C,YAAY,CAAC,CAAC,CAAC;;qGAE0B,CAAC;AAEtG,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,GAAG,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAClD,MAAM,MAAM,GAAG,CAAC,IAAY,EA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AQ,EAAE,GAAG,MAAM,SAAS,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YACzD,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACtH,CAAC;QACD,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,MAAM,KAAK,EAAE,CAAC;IAChB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,IAAI,CACT,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAC5B,CAAC,KAAc,EAAE,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CACF,CAAC","sourcesContent":["#!/usr/bin/env node\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { toJson } from \"@bufbuild/protobuf\";\nimport type { Pipelines } from \"@surfaces-ui/data\";\nimport { CheckSeverity, DatasetKind, type Pipeline, PipelineSchema, RefreshKind, type Run, RunSchema, RunState } from \"@surfaces-ui/proto\";\nimport { CONFIG_FILES, type SurfacesConfig, loadConfig, openSources, serverOptions } from \"./config.js\";\nimport { loadEnvFile } from \"./env.js\";\nimport { createSurfacesServer } from \"./server.js\";\n\nconst USAGE = `Usage: surfaces-pipelines <command> [options]\n\n list The pipelines the config defines or a person saved\n describe <id> Datasets, what each reads, grain, key, columns and checks\n check <id> Checks the pipeline without building anything\n run <id> Builds the pipeline, then runs its checks\n\nOptions:\n --select <name> Only this dataset; name+ adds what reads it, +name what it reads (repeatable)\n --full-refresh --yes Clear the chosen tables first; needs --yes, since it destroys data\n --json Print the result as JSON\n --config <file> The config to read (default: ${CONFIG_FILES[0]})\n\nExits 1 when a dataset fails to build or a check that fails the run does, so cron and CI can use it.`;\n\nconst args = process.argv.slice(2);\nconst has = (name: string) => args.includes(name);\nconst values = (name: string) => args.flatMap((arg, i) => (arg === name && args[i + 1] ? [args[i + 1]!] : []));\nconst positional = args.filter((arg, i) => !arg.startsWith(\"--\") && ![\"--select\", \"--config\"].includes(args[i - 1] ?? \"\"));\nconst [command, id] = positional;\nconst json = has(\"--json\");\nconst bigints = (_: string, value: unknown) => (typeof value === \"bigint\" ? Number(value) : value);\nconst print = (value: unknown) => console.log(JSON.stringify(value, bigints, 2));\nconst STATE: Record<number, string> = { [RunState.COMPLETED]: \"built\", [RunState.FAILED]: \"failed\", [RunState.SKIPPED]: \"skipped\", [RunState.CANCELLED]: \"cancelled\", [RunState.RUNNING]: \"running\", [RunState.QUEUED]: \"queued\" };\n\nasync function open(): Promise<{ pipelines: Pipelines; close(): Promise<void> }> {\n const file = values(\"--config\")[0] ?? CONFIG_FILES.find((f) => fs.existsSync(path.resolve(f)));\n // Secrets come from the environment or a git-ignored .env.local beside the config, as for the dev server.\n loadEnvFile(path.dirname(path.resolve(file ?? CONFIG_FILES[0]!)));\n const { config, dir }: { config: SurfacesConfig; dir: string } = file ? await loadConfig(file) : { config: { seeds: true }, dir: process.cwd() };\n const sources = await openSources(config, dir);\n const server = await createSurfacesServer({ ...(await serverOptions(config, sources, dir)), discovery: false });\n if (!server.pipelines) throw new Error(\"This config defines no pipelines.\");\n return { pipelines: server.pipelines, close: () => server.close() };\n}\n\nfunction describe(pipeline: Pipeline) {\n const lines = [`${pipeline.summary?.name} (${pipeline.summary?.id}) on ${pipeline.summary?.sourceId}${pipeline.version ? `, version ${pipeline.version}` : \"\"}`];\n if (pipeline.summary?.description) lines.push(pipeline.summary.description);\n for (const dataset of pipeline.datasets.filter((d) => d.sql)) {\n lines.push(\"\", `${dataset.name}${dataset.layer ? ` [${dataset.layer}]` : \"\"}${dataset.grain ? `: ${dataset.grain}` : \"\"}`);\n if (dataset.inputs.length > 0) lines.push(` reads ${dataset.inputs.join(\", \")}${dataset.inputsDeclared ? \"\" : \" (worked out from the query)\"}`);\n if (dataset.primaryKey.length > 0) lines.push(` key ${dataset.primaryKey.join(\", \")}`);\n for (const column of dataset.columns) lines.push(` ${column.name}${column.type ? ` ${column.type}` : \"\"}${column.description ? ` — ${column.description}` : \"\"}`);\n for (const check of dataset.checks) lines.push(` check ${check.name}${check.severity === CheckSeverity.WARN ? \" (warns)\" : \"\"}`);\n if (dataset.builtAt) lines.push(` built ${dataset.builtAt} by ${dataset.lastRunId}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction report(run: Run, views: Set<string>) {\n const lines = [`${run.id}: ${STATE[run.state] === \"built\" ? \"completed\" : (STATE[run.state] ?? \"unknown\")}${run.dryRun ? \" (checked, nothing built)\" : \"\"}`];\n for (const dataset of run.datasetRuns) {\n const built = dataset.state === RunState.COMPLETED || dataset.rowsWritten > 0n;\n lines.push(` ${dataset.name}: ${STATE[dataset.state] ?? \"?\"}${built ? (views.has(dataset.name) ? \" as a view\" : `, ${Number(dataset.rowsWritten).toLocaleString(\"en\")} rows`) : \"\"}`);\n for (const check of dataset.checks) lines.push(` ${check.failedRecords > 0n ? (check.severity === CheckSeverity.WARN ? \"warn\" : \"FAIL\") : \"pass\"} ${check.name}: ${check.summary}`);\n if (dataset.errorMessage && dataset.checks.length === 0) lines.push(` ${dataset.errorMessage}`);\n }\n if (run.errorMessage) lines.push(run.errorMessage);\n return lines.join(\"\\n\");\n}\n\nasync function main(): Promise<number> {\n if (!command || has(\"--help\") || ![\"list\", \"describe\", \"check\", \"run\"].includes(command) || (command !== \"list\" && !id)) {\n console.error(USAGE);\n return 2;\n }\n const fullRefresh = has(\"--full-refresh\");\n if (fullRefresh && !has(\"--yes\")) {\n console.error(\"A full refresh clears the chosen tables before building them. Add --yes to go ahead.\");\n return 2;\n }\n const { pipelines, close } = await open();\n try {\n if (command === \"list\") {\n const { pipelines: list } = await pipelines.listPipelines({});\n if (json) print(list.map((p) => ({ id: p.id, name: p.name, sourceId: p.sourceId, datasets: p.datasetCount, latestRun: p.latestRun && { id: p.latestRun.id, state: STATE[p.latestRun.state] } })));\n else for (const p of list) console.log(`${p.id}\\t${p.datasetCount} datasets\\t${p.latestRun ? `last run ${STATE[p.latestRun.state] ?? \"?\"}` : \"never run\"}\\t${p.name}`);\n return 0;\n }\n if (command === \"describe\") {\n const { pipeline } = await pipelines.getPipeline({ id });\n if (json) print(toJson(PipelineSchema, pipeline!));\n else console.log(describe(pipeline!));\n return 0;\n }\n let run = (await pipelines.startRun({ pipelineId: id, select: values(\"--select\"), dryRun: command === \"check\", refreshKind: fullRefresh ? RefreshKind.FULL_REFRESH : RefreshKind.REFRESH, confirmFullRefresh: fullRefresh, trigger: \"cli\", startedBy: process.env.USER ? `${process.env.USER} (cli)` : \"cli\" })).run!;\n while (run.state === RunState.RUNNING) {\n await new Promise((resolve) => setTimeout(resolve, 200));\n run = (await pipelines.getRun({ pipelineId: id, runId: run.id })).run!;\n }\n if (json) print(toJson(RunSchema, run));\n else {\n const { pipeline } = await pipelines.getPipeline({ id });\n console.log(report(run, new Set(pipeline?.datasets.filter((d) => d.kind === DatasetKind.VIEW).map((d) => d.name))));\n }\n return run.state === RunState.COMPLETED ? 0 : 1;\n } finally {\n await close();\n }\n}\n\nmain().then(\n (code) => process.exit(code),\n (error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n },\n);\n"]}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type ConnectRouter } from "@connectrpc/connect";
|
|
2
|
+
import { type DataSource, type Discovery, type Forms, type ModelSettings, type Pipelines, type Semantics, type SurfaceLibrary } from "@surfaces-ui/data";
|
|
3
|
+
import { type DiscoveryOptions } from "@surfaces-ui/discovery";
|
|
4
|
+
import { type EngineServicesOptions } from "@surfaces-ui/engine-service";
|
|
5
|
+
import { type PipelineDefinition, type PipelineStore, type RunStore } from "@surfaces-ui/pipelines";
|
|
6
|
+
import { type AgentBackend } from "@surfaces-ui/agent";
|
|
7
|
+
export type { ServerSource, StoredResultsOptions } from "@surfaces-ui/engine-service";
|
|
8
|
+
export interface SurfacesServerOptions extends EngineServicesOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Discovery settings: sources whose data values may be shown or shared, an
|
|
11
|
+
* embedder for semantic search, a language model, and where packs are kept.
|
|
12
|
+
* Pass `false` to leave the discovery services out.
|
|
13
|
+
*/
|
|
14
|
+
discovery?: Omit<DiscoveryOptions, "dataSource"> | false;
|
|
15
|
+
/**
|
|
16
|
+
* Pipelines this server can run. Their SQL is set here, on the server; a
|
|
17
|
+
* client can only choose which to run. Omit to leave the pipeline services out.
|
|
18
|
+
*/
|
|
19
|
+
pipelines?: PipelineDefinition[];
|
|
20
|
+
/**
|
|
21
|
+
* Pipeline backends built by another tool, served beside the pipelines
|
|
22
|
+
* above: `dbtPipelines` from `@surfaces-ui/pipelines-dbt` for a dbt project.
|
|
23
|
+
* `onFinished` is for a run they start, which changes tables.
|
|
24
|
+
*/
|
|
25
|
+
externalPipelines?(hooks: {
|
|
26
|
+
onFinished(): void;
|
|
27
|
+
}): Pipelines[];
|
|
28
|
+
/** Where pipeline runs are kept, so history outlives a restart. Omit to keep them in memory. */
|
|
29
|
+
pipelineRuns?: RunStore;
|
|
30
|
+
/**
|
|
31
|
+
* Allows `SavePipeline`: a pipeline a person approved is checked (its
|
|
32
|
+
* version, the digest of what they approved, read-only queries and a dry
|
|
33
|
+
* run) and kept here. Pipelines in `pipelines` cannot be changed this way.
|
|
34
|
+
* Omit to keep pipelines fixed.
|
|
35
|
+
*/
|
|
36
|
+
savedPipelines?: PipelineStore;
|
|
37
|
+
/**
|
|
38
|
+
* Forms people can submit. The backend defines each form's fields; a client
|
|
39
|
+
* sends a form id and values, which are checked before anything is kept.
|
|
40
|
+
* Omit to leave the form service out.
|
|
41
|
+
*/
|
|
42
|
+
forms?: Forms;
|
|
43
|
+
/** Where saved surfaces (pages, charts, forms, explorers) are kept. Omit to leave the surface calls out. */
|
|
44
|
+
library?: SurfaceLibrary;
|
|
45
|
+
/**
|
|
46
|
+
* Where semantic models are kept, served as `SemanticService`. Every save
|
|
47
|
+
* is checked against the data first: the model's query must run through
|
|
48
|
+
* this server's read-only sources and return the columns its fields name.
|
|
49
|
+
* Omit to leave it out.
|
|
50
|
+
*/
|
|
51
|
+
semantics?: Semantics;
|
|
52
|
+
/**
|
|
53
|
+
* Which model each agent backend uses, served as `ModelService` so a page
|
|
54
|
+
* can show and change it. It carries no key. Omit to leave it out.
|
|
55
|
+
*/
|
|
56
|
+
models?: ModelSettings;
|
|
57
|
+
/**
|
|
58
|
+
* An agent to serve as `AgentService`, so a browser chat reaches it with
|
|
59
|
+
* `connectAgent` from `@surfaces-ui/client-connect`. The agent runs here, with
|
|
60
|
+
* its model key in this server's environment. Omit to leave it out.
|
|
61
|
+
* Pass a function to build the agent from this server's own data source,
|
|
62
|
+
* for tools that list tables or run queries.
|
|
63
|
+
*/
|
|
64
|
+
agent?: AgentBackend | ((dataSource: DataSource, services: AgentServices) => AgentBackend);
|
|
65
|
+
/** Origins allowed to call from a browser. Defaults to any localhost origin. */
|
|
66
|
+
allowedOrigins?: (string | RegExp)[];
|
|
67
|
+
}
|
|
68
|
+
/** What a server gives an agent it builds, besides its data: give them to `dataTools`. */
|
|
69
|
+
export interface AgentServices {
|
|
70
|
+
/** The server's semantic models, for `list_semantic_models` and `describe_semantic_model`. */
|
|
71
|
+
semantics?: Semantics;
|
|
72
|
+
/** The server's pipelines, for `pipelineTools` from `@surfaces-ui/agent`. */
|
|
73
|
+
pipelines?: Pipelines;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Serves any AgentBackend as `AgentService` on a Connect router: one `Send`
|
|
77
|
+
* streams one turn. Mount it in your own Connect server, or pass `agent` to
|
|
78
|
+
* `createSurfacesServer`. Who the person is comes from the request
|
|
79
|
+
* (`decided_by`, `actor`); check it against your own session before acting.
|
|
80
|
+
*/
|
|
81
|
+
export declare function agentRoutes(agent: AgentBackend): (router: ConnectRouter) => void;
|
|
82
|
+
export interface SurfacesServer {
|
|
83
|
+
/** The server's sources as an in-process DataSource (no HTTP), for embedding in other servers. */
|
|
84
|
+
dataSource: DataSource;
|
|
85
|
+
/** The discovery backend, when enabled. */
|
|
86
|
+
discovery: (Discovery & {
|
|
87
|
+
warm(): Promise<{
|
|
88
|
+
objects: number;
|
|
89
|
+
}>;
|
|
90
|
+
}) | undefined;
|
|
91
|
+
/** The pipeline backend, when pipelines are configured. */
|
|
92
|
+
pipelines: Pipelines | undefined;
|
|
93
|
+
forms: Forms | undefined;
|
|
94
|
+
library: SurfaceLibrary | undefined;
|
|
95
|
+
semantics: Semantics | undefined;
|
|
96
|
+
models: ModelSettings | undefined;
|
|
97
|
+
/** Registers the services on a Connect router, to mount in an existing server. */
|
|
98
|
+
routes(router: ConnectRouter): void;
|
|
99
|
+
/** Starts an HTTP server. Port 0 picks a free port. */
|
|
100
|
+
listen(port?: number, host?: string): Promise<{
|
|
101
|
+
url: string;
|
|
102
|
+
port: number;
|
|
103
|
+
}>;
|
|
104
|
+
close(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
export declare function createSurfacesServer(options: SurfacesServerOptions): Promise<SurfacesServer>;
|