@trytilde/ontology 4.0.0 → 5.0.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/dist/mod.d.ts +251 -123
- package/dist/mod.js +300 -101
- package/package.json +1 -1
package/dist/mod.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@trytilde/ontology`: an ontology project in TypeScript, the single source for
|
|
3
3
|
*
|
|
4
|
-
* - **models**:
|
|
5
|
-
*
|
|
4
|
+
* - **sources and models**: every input is a `source` (a pipeline, `ingress()` or `rows()`) whose
|
|
5
|
+
* streams are current-state models; dbt-style ducktail models (`model`, `sqlFile`) over them,
|
|
6
|
+
* compiled to `manifest.json`, which ducktail executes;
|
|
6
7
|
* - **nouns**: object types with typed properties over models, links, entity resolution;
|
|
7
8
|
* - **transactional views**: a portion of the graph materialised per key in a celld SQLite
|
|
8
9
|
* cell for hot transactional work (`transactionalView`);
|
|
@@ -21,11 +22,15 @@
|
|
|
21
22
|
*
|
|
22
23
|
* ```ts
|
|
23
24
|
* import { z } from "zod";
|
|
24
|
-
* import { action,
|
|
25
|
+
* import { action, defineSecrets, model, object, ontology, postgres, secret, source, sql, t, transactionalView } from "@trytilde/ontology";
|
|
25
26
|
*
|
|
26
|
-
* const
|
|
27
|
-
* const
|
|
28
|
-
*
|
|
27
|
+
* const secrets = defineSecrets({ APP_DB_PASSWORD: secret() });
|
|
28
|
+
* const app = source("app", {
|
|
29
|
+
* from: postgres.cdc({ host: "db.internal", user: "replicator", password: secrets.APP_DB_PASSWORD, database: "app", tables: ["public.customers"] }),
|
|
30
|
+
* streams: { public_customers: {} },
|
|
31
|
+
* });
|
|
32
|
+
* const customersNow = app.public_customers;
|
|
33
|
+
* const crmCustomers = model({ name: "crm_customers", type: "model", schema: "cells", materialization: "cell", uniqueKey: "customer_id",
|
|
29
34
|
* columns: { customer_id: t.string(), name: t.string() },
|
|
30
35
|
* sql: ({ ref }) => sql`SELECT payload->>'id' AS customer_id, payload->>'name' AS name FROM ${ref(customersNow)}` });
|
|
31
36
|
* export const Customer = object("Customer", { id: "customer", key: "customerId", source: crmCustomers,
|
|
@@ -37,7 +42,7 @@
|
|
|
37
42
|
* edits: [Customer.notes], reads: [Customer],
|
|
38
43
|
* handler: ({ input, view, ctx }) => { ctx.update(Customer, view.key, { notes: input.notes }); return null; },
|
|
39
44
|
* });
|
|
40
|
-
* export default ontology({ objects: [Customer], views: [CustomerView], actions: [setNotes] });
|
|
45
|
+
* export default ontology({ sources: [app], secrets, objects: [Customer], views: [CustomerView], actions: [setNotes] });
|
|
41
46
|
* ```
|
|
42
47
|
*/
|
|
43
48
|
import { z } from "zod";
|
|
@@ -49,11 +54,13 @@ export type Json = null | boolean | number | string | Json[] | {
|
|
|
49
54
|
export type SqlParam = string | number | boolean | null;
|
|
50
55
|
export type Key = string | number;
|
|
51
56
|
/** Where an ontology's data lives: `cell` (the default: SQLite cells for views, DuckLake for the
|
|
52
|
-
* lake)
|
|
53
|
-
|
|
57
|
+
* lake), `postgres` (one Postgres schema for everything; see CONTEXT.md, "Postgres storage") or
|
|
58
|
+
* `sqlite` (one SQLite database for everything, in the environment's Durable Object: the small,
|
|
59
|
+
* scale-to-zero tier; see CONTEXT.md, "SQLite storage"). */
|
|
60
|
+
export type Storage = "cell" | "postgres" | "sqlite";
|
|
54
61
|
/** The SQL dialect models and handler SQL are written in: DuckDB for `cell` storage, Postgres
|
|
55
|
-
* for `postgres`; ClickHouse for the models of a ClickHouse destination. */
|
|
56
|
-
export type Dialect = "duckdb" | "postgres" | "clickhouse";
|
|
62
|
+
* for `postgres`, SQLite for `sqlite`; ClickHouse for the models of a ClickHouse destination. */
|
|
63
|
+
export type Dialect = "duckdb" | "postgres" | "sqlite" | "clickhouse";
|
|
57
64
|
/** The kind of a named destination models can materialize to besides the storage. */
|
|
58
65
|
export type DestinationKind = "clickhouse";
|
|
59
66
|
/** A SQL text fragment (in the storage's dialect). */
|
|
@@ -142,42 +149,106 @@ export declare class SourceDef {
|
|
|
142
149
|
constructor(pipeline: string, stream: string, loc: string | null);
|
|
143
150
|
}
|
|
144
151
|
/**
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
* `
|
|
148
|
-
*
|
|
149
|
-
* `ontology({ pipelines })`.
|
|
152
|
+
* Records your code sends through Tilde's Ingress (`IngressService.WriteRecords`, by API keys,
|
|
153
|
+
* people and agents with `write_streams` on the project, or the environment's own worker). Each
|
|
154
|
+
* stream declares a zod `schema` and the `key` property; a newer record of a key replaces the
|
|
155
|
+
* older. Its raw rows are `lake.raw.ingress__<stream>`.
|
|
150
156
|
*/
|
|
151
|
-
export declare function
|
|
152
|
-
export declare function source<const S extends string>(name: string, spec: {
|
|
153
|
-
pipeline: Pipeline<S>;
|
|
154
|
-
}): PipelineSource<S>;
|
|
157
|
+
export declare function ingress(): IngressFrom;
|
|
155
158
|
/**
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* `lake.raw.ingress__<name>`: read it with `src()` and `changes()` like any source (the payload
|
|
161
|
-
* is the record). List streams in `ontology({ streams })`.
|
|
159
|
+
* Reference data the version ships (a solution's tenant configuration, say): each stream's
|
|
160
|
+
* `rows`, validated against its `schema` and loaded through Ingress by every rollout, so a
|
|
161
|
+
* redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
|
|
162
|
+
* list is not deleted).
|
|
162
163
|
*/
|
|
163
|
-
export declare
|
|
164
|
-
|
|
165
|
-
readonly
|
|
166
|
-
readonly
|
|
167
|
-
constructor(name: string, schema: z.ZodType, key: string, reference: readonly unknown[], loc: string | null);
|
|
164
|
+
export declare function rows(): IngressFrom;
|
|
165
|
+
export interface IngressFrom {
|
|
166
|
+
readonly kind: "ingress";
|
|
167
|
+
readonly rows: boolean;
|
|
168
168
|
}
|
|
169
|
+
/** Where a source's records come from: a pipeline (`linear.sync`, `cloudwatch.poll`,
|
|
170
|
+
* `postgres.cdc`, `tilde.events`, ...), `ingress()` or `rows()`. */
|
|
171
|
+
export type From<S extends string = string> = Pipeline<S> | IngressFrom;
|
|
169
172
|
/**
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
173
|
+
* How a source stream is read. By default it is its **current state**: one row per key, the
|
|
174
|
+
* newest, keys whose newest row removes them dropped (a generated incremental model,
|
|
175
|
+
* `lake.sources.<source>__<stream>`, columns `_key`, `_newest`, `_pos`, `payload`; a
|
|
176
|
+
* `postgres.cdc` stream gets ducktail's CDC current state instead, columns `_key`, `_pos`, `_seq`,
|
|
177
|
+
* `_source_ts`, `payload`). `ref()` it, map objects onto it, `changes()` it.
|
|
175
178
|
*/
|
|
176
|
-
export
|
|
179
|
+
export interface StreamOptions {
|
|
180
|
+
/** The key: a payload property, `_key` (the default: the record's identity as ducktail writes
|
|
181
|
+
* it), or a SQL expression over the raw row. */
|
|
182
|
+
key?: string | Sql;
|
|
183
|
+
/** SQL over the raw row ordering a key's rows (the largest wins, then the latest position):
|
|
184
|
+
* default `_source_ts`, the record's own version, for the sync kinds, CloudWatch, webhooks and
|
|
185
|
+
* ingress; `_pos` for other polled kinds (Plaid, Gmail, ...), whose removals carry no time. A
|
|
186
|
+
* removal that loses its key's order is not applied until a newer one wins; an incremental
|
|
187
|
+
* build compares only with rows still held, so a late older row can bring a removed key back
|
|
188
|
+
* until a full build (the sync kinds' reconcile repairs it). */
|
|
189
|
+
newest?: string | Sql;
|
|
190
|
+
/** SQL over the raw row, true for a row that removes its key: default `_op = 'd'`. */
|
|
191
|
+
deleted?: string | Sql;
|
|
192
|
+
/** Also give the raw rows as `.history` (every version, as ingested). */
|
|
193
|
+
history?: boolean;
|
|
194
|
+
/** `false`: no current state; the stream is its raw rows (an append-only log). */
|
|
195
|
+
current?: false;
|
|
196
|
+
}
|
|
197
|
+
/** A stream of `ingress()` or `rows()`: records validated against `schema`, keyed by `key`. */
|
|
198
|
+
export interface IngressStreamOptions {
|
|
177
199
|
schema: z.ZodType;
|
|
200
|
+
/** A string or number property of the record. */
|
|
178
201
|
key: string;
|
|
179
|
-
|
|
180
|
-
|
|
202
|
+
/** The records the version ships (required with `rows()`). */
|
|
203
|
+
rows?: readonly unknown[];
|
|
204
|
+
history?: boolean;
|
|
205
|
+
current?: false;
|
|
206
|
+
}
|
|
207
|
+
/** A source stream as the definitions use it: its current state (a model), with `.history`
|
|
208
|
+
* where declared; with `current: false`, its raw rows. */
|
|
209
|
+
export type StreamOf<O> = O extends {
|
|
210
|
+
current: false;
|
|
211
|
+
} ? SourceDef : O extends {
|
|
212
|
+
history: true;
|
|
213
|
+
} ? ModelDef & {
|
|
214
|
+
readonly history: SourceDef;
|
|
215
|
+
} : ModelDef;
|
|
216
|
+
/** What `source()` declares: its name, where its records come from, and its streams. */
|
|
217
|
+
export interface SourceDecl {
|
|
218
|
+
readonly name: string;
|
|
219
|
+
readonly from: From;
|
|
220
|
+
/** Each declared stream's raw rows. */
|
|
221
|
+
readonly raw: readonly SourceDef[];
|
|
222
|
+
readonly loc: string | null;
|
|
223
|
+
}
|
|
224
|
+
/** A declared source: each stream under its name, plus the declaration. */
|
|
225
|
+
export type Source<St = Record<string, unknown>> = {
|
|
226
|
+
readonly [K in keyof St]: StreamOf<St[K]>;
|
|
227
|
+
} & {
|
|
228
|
+
readonly $source: SourceDecl;
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* Every input of an ontology is a source: `source(name, { from, streams })`, where `from` is a
|
|
232
|
+
* pipeline (`linear.sync`, `github.sync`, `cloudwatch.poll`, `postgres.cdc`, `tilde.events`, your
|
|
233
|
+
* own `webhook()`, ...), `ingress()` or `rows()`, and `streams` names the streams it reads (typed
|
|
234
|
+
* by the pipeline) and how. `linear.issues` is then the current state of Linear's issues. List
|
|
235
|
+
* sources in `ontology({ sources })`. The name is the pipeline's state (cursors, backfills) and
|
|
236
|
+
* its raw tables' prefix (`lake.raw.<name>__<stream>`): renaming one starts it over.
|
|
237
|
+
*/
|
|
238
|
+
export declare function source<const S extends string, const St extends {
|
|
239
|
+
readonly [K in S]?: StreamOptions;
|
|
240
|
+
}>(name: string, spec: {
|
|
241
|
+
from: Pipeline<S>;
|
|
242
|
+
streams: St & {
|
|
243
|
+
readonly [K in Exclude<keyof St, S>]: never;
|
|
244
|
+
};
|
|
245
|
+
}): Source<St>;
|
|
246
|
+
export declare function source<const St extends {
|
|
247
|
+
readonly [name: string]: IngressStreamOptions;
|
|
248
|
+
}>(name: string, spec: {
|
|
249
|
+
from: IngressFrom;
|
|
250
|
+
streams: St;
|
|
251
|
+
}): Source<St>;
|
|
181
252
|
/** The SQL builder context of a model: evaluated twice, once per `isIncremental`. */
|
|
182
253
|
export interface ModelSqlCtx {
|
|
183
254
|
/** `lake.<schema>.<name>` of another model (a dependency), or an object type's table: the
|
|
@@ -251,10 +322,19 @@ export interface ModelIndex {
|
|
|
251
322
|
unique?: boolean;
|
|
252
323
|
method?: "btree" | "gin" | "gist" | "hash" | "brin";
|
|
253
324
|
}
|
|
325
|
+
/**
|
|
326
|
+
* What a model is for, checked by the build. `staging`: cleanup of sources (casts, renames,
|
|
327
|
+
* dedup, unnesting), private: only other models `ref()` it. It backs no object, so it is not in
|
|
328
|
+
* the object schema, but lineage docs still show it. `model`: the domain; the only kind that backs an object. `projection`: a
|
|
329
|
+
* read-shaped table over objects or models (a grid, with indexes and search) for reads and
|
|
330
|
+
* realtime; never an object's source.
|
|
331
|
+
*/
|
|
332
|
+
export type ModelType = "staging" | "model" | "projection";
|
|
254
333
|
export interface ModelSpec<C extends Props> {
|
|
255
334
|
name: string;
|
|
335
|
+
type: ModelType;
|
|
256
336
|
schema?: string;
|
|
257
|
-
|
|
337
|
+
materialization: "view" | "table" | "incremental" | "cell" | "microbatch";
|
|
258
338
|
/** `microbatch` models (Postgres storage): built batch by batch of `eventTime` from `begin`
|
|
259
339
|
* (a date, an RFC 3339 time or a duration before now; default: ducktail's `[backfill] start`),
|
|
260
340
|
* each batch replaced as a whole; the SQL filters its inputs with `batchStart` / `batchEnd`. */
|
|
@@ -296,23 +376,38 @@ export declare class ModelDef<C extends Props = Props> {
|
|
|
296
376
|
} | null;
|
|
297
377
|
constructor(spec: ModelSpec<C>, loc: string | null);
|
|
298
378
|
}
|
|
299
|
-
|
|
379
|
+
type Generated = "materialization" | "sql" | "uniqueKey" | "incrementalStrategy" | "columns" | "microbatch";
|
|
300
380
|
/**
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
381
|
+
* `materialization: "diffed"`: a table recomputed from its upstreams' full state (`sql`) on every
|
|
382
|
+
* run that writes only the rows that differ from what it holds and deletes the keys that
|
|
383
|
+
* disappeared, so `changes()` over it (and realtime watches) stay as small as the real change.
|
|
384
|
+
* `gate` gives a row when the run must recompute (its upstreams' `changes`); without one, every
|
|
385
|
+
* run does. Stored as an incremental model.
|
|
306
386
|
*/
|
|
307
|
-
export
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
sql: (
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
387
|
+
export interface DiffedModelSpec<C extends Props> extends Omit<ModelSpec<C>, Generated> {
|
|
388
|
+
materialization: "diffed";
|
|
389
|
+
key: string;
|
|
390
|
+
columns: C;
|
|
391
|
+
sql: (ctx: Pick<ModelSqlCtx, "ref" | "src" | "dialect">) => Sql;
|
|
392
|
+
gate?: (ctx: Pick<ModelSqlCtx, "ref" | "changes">) => Sql;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* `materialization: "cell"` recomputed per touched key: `rows(filter)` selects the rows for the
|
|
396
|
+
* keys a SQL predicate admits (`filter` takes the caller's key expression), `touched` the keys
|
|
397
|
+
* (column `k`) any upstream change may affect. Rows of a touched key that no longer come out
|
|
398
|
+
* are deleted. `partition` is the column `touched` keys match, when it is not `key`.
|
|
399
|
+
*/
|
|
400
|
+
export interface RecomputedCellModelSpec<C extends Props> extends Omit<ModelSpec<C>, Generated> {
|
|
401
|
+
materialization: "cell";
|
|
402
|
+
key: string;
|
|
403
|
+
partition?: string;
|
|
404
|
+
columns: C;
|
|
405
|
+
rows: (ctx: Pick<ModelSqlCtx, "ref" | "src" | "dialect"> & {
|
|
406
|
+
filter: (keyExpr: string) => Sql;
|
|
407
|
+
}) => Sql;
|
|
408
|
+
touched: (ctx: Pick<ModelSqlCtx, "ref" | "changes" | "self">) => Sql;
|
|
409
|
+
}
|
|
410
|
+
export declare function model<C extends Props = Props>(spec: ModelSpec<C> | DiffedModelSpec<C> | RecomputedCellModelSpec<C>): ModelDef<C>;
|
|
316
411
|
/** A reference to one property of an object type (`Customer.notes`). */
|
|
317
412
|
export interface PropRef<O extends string = string, F extends string = string, P = Prop<unknown, boolean, boolean>> {
|
|
318
413
|
readonly kind: "prop";
|
|
@@ -332,6 +427,7 @@ type ObjectInternals<N extends string, P extends Props, K extends keyof P & stri
|
|
|
332
427
|
history?: boolean;
|
|
333
428
|
historyAt?: string;
|
|
334
429
|
replicas?: string[];
|
|
430
|
+
signals?: readonly SignalChange[];
|
|
335
431
|
};
|
|
336
432
|
readonly $loc: string | null;
|
|
337
433
|
/** Type-level only: the object row handlers see. */
|
|
@@ -351,6 +447,7 @@ export interface AnyObject {
|
|
|
351
447
|
history?: boolean;
|
|
352
448
|
historyAt?: string;
|
|
353
449
|
replicas?: string[];
|
|
450
|
+
signals?: readonly SignalChange[];
|
|
354
451
|
};
|
|
355
452
|
readonly $loc: string | null;
|
|
356
453
|
readonly $row: any;
|
|
@@ -370,6 +467,10 @@ export type ObjectDef<N extends string = string, P extends Props = Props, K exte
|
|
|
370
467
|
* read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
|
|
371
468
|
* history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
|
|
372
469
|
* object's table in that destination, so SQL there can join it.
|
|
470
|
+
*
|
|
471
|
+
* `signals: ["created"]` (Postgres storage) makes those changes of the object signals of the
|
|
472
|
+
* environment's own Tilde connection (`tilde_ontology/<project>-<environment>`), which an
|
|
473
|
+
* agent's routine subscribes to like any connection's: see `signal`.
|
|
373
474
|
*/
|
|
374
475
|
export declare function object<const N extends string, P extends Props, const K extends keyof P & string>(name: N, spec: {
|
|
375
476
|
id: string;
|
|
@@ -380,7 +481,31 @@ export declare function object<const N extends string, P extends Props, const K
|
|
|
380
481
|
history?: boolean;
|
|
381
482
|
historyAt?: keyof P & string;
|
|
382
483
|
replicas?: string[];
|
|
484
|
+
signals?: readonly SignalChange[];
|
|
383
485
|
}): ObjectDef<N, P, K>;
|
|
486
|
+
/** A change of an object that can be a signal (`object({ signals })`). */
|
|
487
|
+
export type SignalChange = "created" | "updated" | "deleted";
|
|
488
|
+
/** A signal's data: the object's properties by API name, as JSON (keys, refs, decimals, dates and
|
|
489
|
+
* timestamps as text). For `deleted`, as they last were. */
|
|
490
|
+
export type SignalData<O extends AnyObject> = O["$row"];
|
|
491
|
+
/** One signal of an object, for the routine that takes it (`@trytilde/iac`'s
|
|
492
|
+
* `signal: { connection, type, filters }`): its `type` on the environment's connection. `$data`
|
|
493
|
+
* exists at the type level only. */
|
|
494
|
+
export interface SignalRef<O extends AnyObject = AnyObject> {
|
|
495
|
+
readonly kind: "signal";
|
|
496
|
+
readonly object: string;
|
|
497
|
+
readonly change: SignalChange;
|
|
498
|
+
/** `tilde_ontology.<object id>.<change>`. */
|
|
499
|
+
readonly type: string;
|
|
500
|
+
readonly $data: SignalData<O>;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* A signal the object declares. Tilde delivers each one at least once and, per object, in
|
|
504
|
+
* order; changes that reach the storage together are one signal (an object created and deleted
|
|
505
|
+
* at once is none), and an object that existed before it declared signals emits `created` for
|
|
506
|
+
* none of its rows. A routine's filters and templates name the data's keys (`{{ stage }}`).
|
|
507
|
+
*/
|
|
508
|
+
export declare function signal<O extends AnyObject>(object: O, change: SignalChange): SignalRef<O>;
|
|
384
509
|
/** An object type's change history (`history: true`): the relation `lake.ontology.<id>__changes`,
|
|
385
510
|
* which a view-less read declares in its `reads`, and Cedar's `Model::"<id>__changes"` (what
|
|
386
511
|
* `query` is decided on). */
|
|
@@ -607,20 +732,8 @@ export declare class WebhookPipeline<S extends string = string, E extends string
|
|
|
607
732
|
readonly [event: string]: NoInfer<S>;
|
|
608
733
|
}): WebhookPipeline<S, E>;
|
|
609
734
|
}
|
|
610
|
-
/**
|
|
611
|
-
|
|
612
|
-
readonly name: string;
|
|
613
|
-
readonly pipeline: Pipeline<S>;
|
|
614
|
-
readonly loc: string | null;
|
|
615
|
-
readonly kind = "pipelineSource";
|
|
616
|
-
constructor(name: string, pipeline: Pipeline<S>, loc: string | null);
|
|
617
|
-
/** One of the pipeline's streams: `lake.raw.<name>__<stream>`. */
|
|
618
|
-
stream(stream: S): SourceDef;
|
|
619
|
-
}
|
|
620
|
-
/** Polled options every polled kind takes. */
|
|
621
|
-
interface PollOptions<St extends string> {
|
|
622
|
-
/** The streams to poll (default: all of the kind's). */
|
|
623
|
-
streams?: readonly St[];
|
|
735
|
+
/** Polled options every polled kind takes. The streams it polls are the source's. */
|
|
736
|
+
interface PollOptions {
|
|
624
737
|
interval?: Duration;
|
|
625
738
|
/** Where the first sweep starts: a date, an RFC 3339 time or a duration before now. */
|
|
626
739
|
backfill?: {
|
|
@@ -628,65 +741,83 @@ interface PollOptions<St extends string> {
|
|
|
628
741
|
};
|
|
629
742
|
requestTimeout?: Duration;
|
|
630
743
|
}
|
|
631
|
-
/**
|
|
744
|
+
/**
|
|
745
|
+
* A provider sync (ducktail's sync pipelines): one stream per entity, merging a backfill on the
|
|
746
|
+
* first run, the connection's webhooks (`webhook`, default on) and, where the provider takes
|
|
747
|
+
* it, a slow reconciling poll (`reconcile`; default 1h with webhooks, 60s without). Each row's
|
|
748
|
+
* `_key` is the entity and `_source_ts` its own version, so the source's streams are current
|
|
749
|
+
* state with no options.
|
|
750
|
+
*/
|
|
751
|
+
interface SyncOptions {
|
|
752
|
+
webhook?: boolean;
|
|
753
|
+
reconcile?: Duration;
|
|
754
|
+
/** Where the backfill starts: a date, an RFC 3339 time or a duration before now. */
|
|
755
|
+
backfill?: {
|
|
756
|
+
start: string;
|
|
757
|
+
};
|
|
758
|
+
requestTimeout?: Duration;
|
|
759
|
+
}
|
|
760
|
+
/** A provider webhook's routing: event name -> stream, the rest to `fallback`. The streams are
|
|
761
|
+
* the routes' (and the fallback's). */
|
|
632
762
|
interface WebhookOptions<P extends keyof WebhookEvents, S extends string> {
|
|
633
763
|
connection: Connection<P>;
|
|
634
|
-
/** The pipeline's streams. */
|
|
635
|
-
streams: readonly S[];
|
|
636
764
|
/** Event -> stream; events not listed go to `fallback` (without one, ducktail answers 422). */
|
|
637
765
|
route: {
|
|
638
|
-
readonly [E in WebhookEvents[P]]?:
|
|
766
|
+
readonly [E in WebhookEvents[P]]?: S;
|
|
639
767
|
};
|
|
640
|
-
fallback?:
|
|
768
|
+
fallback?: S;
|
|
641
769
|
}
|
|
642
|
-
/** Linear:
|
|
770
|
+
/** Linear: a sync (webhooks, backfill, reconcile), polled GraphQL alone, or the raw webhooks. */
|
|
643
771
|
export declare const linear: {
|
|
644
|
-
|
|
772
|
+
sync: (o: SyncOptions & {
|
|
773
|
+
connection: Connection<"linear">;
|
|
774
|
+
pageSize?: number;
|
|
775
|
+
fields?: { readonly [K in SyncStreams["linear"]]?: string; };
|
|
776
|
+
endpoint?: string;
|
|
777
|
+
}) => Pipeline<"teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">;
|
|
778
|
+
poll: (o: PollOptions & {
|
|
645
779
|
connection: Connection<"linear">;
|
|
646
780
|
pageSize?: number;
|
|
647
781
|
/** A stream's GraphQL selection, replacing the built-in one. */
|
|
648
782
|
fields?: { readonly [K in PolledStreams["linear"]]?: string; };
|
|
649
783
|
endpoint?: string;
|
|
650
|
-
}) => Pipeline<
|
|
784
|
+
}) => Pipeline<"teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">;
|
|
651
785
|
webhook: <const S extends string>(o: WebhookOptions<"linear", S>) => WebhookPipeline<S, "Attachment" | "AuditEntry" | "Comment" | "Customer" | "CustomerNeed" | "Cycle" | "Document" | "Initiative" | "InitiativeUpdate" | "Issue" | "IssueLabel" | "IssueSLA" | "OAuthApp" | "Project" | "ProjectUpdate" | "Reaction" | "User">;
|
|
652
786
|
};
|
|
653
|
-
|
|
787
|
+
interface SentryOptions {
|
|
788
|
+
connection: Connection<"sentry">;
|
|
789
|
+
organization: string;
|
|
790
|
+
/** Project slugs whose issues are read. */
|
|
791
|
+
projects?: readonly string[];
|
|
792
|
+
/** `https://sentry.io` (default), a regional host or self-hosted Sentry. */
|
|
793
|
+
baseUrl?: string;
|
|
794
|
+
query?: string;
|
|
795
|
+
}
|
|
796
|
+
/** Sentry: a sync (integration webhooks, backfill, reconcile), polled issues alone, or the raw webhooks. */
|
|
654
797
|
export declare const sentry: {
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
organization: string;
|
|
658
|
-
/** Project slugs whose issues are polled. */
|
|
659
|
-
projects?: readonly string[];
|
|
660
|
-
/** `https://sentry.io` (default), a regional host or self-hosted Sentry. */
|
|
661
|
-
baseUrl?: string;
|
|
662
|
-
query?: string;
|
|
798
|
+
sync: (o: SyncOptions & SentryOptions) => Pipeline<"projects" | "issues">;
|
|
799
|
+
poll: (o: PollOptions & SentryOptions & {
|
|
663
800
|
fullSweepInterval?: Duration;
|
|
664
|
-
}) => Pipeline<
|
|
801
|
+
}) => Pipeline<"projects" | "issues">;
|
|
665
802
|
webhook: <const S extends string>(o: WebhookOptions<"sentry", S>) => WebhookPipeline<S, "installation" | "comment" | "error" | "event_alert" | "issue" | "metric_alert" | "seer">;
|
|
666
803
|
};
|
|
667
|
-
/** GitHub: the connection's webhooks
|
|
804
|
+
/** GitHub: a sync of the repositories, or the connection's raw webhooks. */
|
|
668
805
|
export declare const github: {
|
|
669
806
|
/**
|
|
670
|
-
* One stream per entity
|
|
671
|
-
*
|
|
672
|
-
*
|
|
673
|
-
*
|
|
674
|
-
*
|
|
807
|
+
* One stream per entity: the connection's webhooks for the repositories, after a backfill of
|
|
808
|
+
* their recent pull requests, reviews, check runs and releases on the first run (default 30
|
|
809
|
+
* days). Each row's `_key` is the entity (`{repository, number}` for pull requests, else
|
|
810
|
+
* `{id}`) and `_source_ts` its own time; the payload is the webhook body. Never reconciles:
|
|
811
|
+
* GitHub's webhooks are complete. Only the listed repositories are written: deliveries from
|
|
812
|
+
* any other repository the App is installed on are dropped.
|
|
675
813
|
*/
|
|
676
|
-
sync: <
|
|
814
|
+
sync: (o: Omit<SyncOptions, "reconcile" | "webhook"> & {
|
|
677
815
|
connection: Connection<"github">;
|
|
678
|
-
/** `owner/name`: backfilled, and the only repositories
|
|
816
|
+
/** `owner/name`: backfilled (each once, by its own job), and the only repositories written. */
|
|
679
817
|
repositories: readonly string[];
|
|
680
|
-
/** The streams to write (default: all). */
|
|
681
|
-
streams?: readonly St[];
|
|
682
|
-
/** Where the backfill starts: a date, an RFC 3339 time or a duration before now. */
|
|
683
|
-
backfill?: {
|
|
684
|
-
start: string;
|
|
685
|
-
};
|
|
686
818
|
baseUrl?: string;
|
|
687
819
|
pageSize?: number;
|
|
688
|
-
|
|
689
|
-
}) => Pipeline<St>;
|
|
820
|
+
}) => Pipeline<"pull_requests" | "pull_request_reviews" | "check_runs" | "releases">;
|
|
690
821
|
/** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
|
|
691
822
|
webhook: <const S extends string>(o: WebhookOptions<"github", S>) => WebhookPipeline<S, "issues" | "check_run" | "check_suite" | "code_scanning_alert" | "create" | "delete" | "dependabot_alert" | "deployment" | "deployment_status" | "discussion" | "discussion_comment" | "fork" | "installation" | "installation_repositories" | "issue_comment" | "label" | "member" | "merge_group" | "milestone" | "ping" | "pull_request" | "pull_request_review" | "pull_request_review_comment" | "pull_request_review_thread" | "push" | "release" | "repository" | "secret_scanning_alert" | "status" | "workflow_job" | "workflow_run">;
|
|
692
823
|
};
|
|
@@ -702,7 +833,7 @@ export interface CloudwatchMetric {
|
|
|
702
833
|
}
|
|
703
834
|
/** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
|
|
704
835
|
export declare const cloudwatch: {
|
|
705
|
-
poll:
|
|
836
|
+
poll: (o: PollOptions & {
|
|
706
837
|
connection: Connection<PolledProvider["cloudwatch"]>;
|
|
707
838
|
region: string;
|
|
708
839
|
discoveryInterval?: Duration;
|
|
@@ -721,16 +852,16 @@ export declare const cloudwatch: {
|
|
|
721
852
|
discoverMetrics?: boolean;
|
|
722
853
|
metrics?: readonly CloudwatchMetric[];
|
|
723
854
|
endpoint?: string;
|
|
724
|
-
}) => Pipeline<
|
|
855
|
+
}) => Pipeline<"ecs_clusters" | "ecs_services" | "load_balancers" | "target_groups" | "target_health" | "metric_data" | "alarms" | "alarm_history">;
|
|
725
856
|
};
|
|
726
857
|
/** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
|
|
727
858
|
* `options` are ducktail's keys for it (README, "Polled sources"). */
|
|
728
|
-
export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch"
|
|
859
|
+
export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch">>(kind: K, o: PollOptions & {
|
|
729
860
|
connection: Connection<PolledProvider[K]>;
|
|
730
861
|
options?: {
|
|
731
862
|
readonly [key: string]: PipelineValue | undefined;
|
|
732
863
|
};
|
|
733
|
-
}): Pipeline<
|
|
864
|
+
}): Pipeline<PolledStreams[K]>;
|
|
734
865
|
/** Postgres logical replication of tables (streams `<schema>_<table>`). */
|
|
735
866
|
export declare const postgres: {
|
|
736
867
|
cdc: <const T extends string>(o: {
|
|
@@ -768,19 +899,18 @@ export declare const kafka: {
|
|
|
768
899
|
};
|
|
769
900
|
/**
|
|
770
901
|
* A webhook pipeline of the solution's own, which Tilde delivers to (records written through
|
|
771
|
-
* Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream
|
|
772
|
-
* a header.
|
|
902
|
+
* Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>` for each stream the
|
|
903
|
+
* source declares, or one URL routed by a header (its streams are then the routes').
|
|
773
904
|
*/
|
|
774
|
-
export declare function webhook<const S extends string>(o
|
|
775
|
-
streams: readonly S[];
|
|
905
|
+
export declare function webhook<const S extends string = string>(o?: {
|
|
776
906
|
/** The header whose value keys deliveries (`_key = {"id": ...}`). */
|
|
777
907
|
keyHeader?: string;
|
|
778
908
|
route?: {
|
|
779
909
|
header: string;
|
|
780
910
|
streams: {
|
|
781
|
-
readonly [value: string]:
|
|
911
|
+
readonly [value: string]: S;
|
|
782
912
|
};
|
|
783
|
-
fallback?:
|
|
913
|
+
fallback?: S;
|
|
784
914
|
};
|
|
785
915
|
}): Pipeline<S>;
|
|
786
916
|
/** The tables Tilde's registry events deliver (`tilde.events`). */
|
|
@@ -789,12 +919,10 @@ export type RegistryStream = "public_chat_threads" | "public_chat_runs" | "publi
|
|
|
789
919
|
export declare const tilde: {
|
|
790
920
|
/**
|
|
791
921
|
* The organization's registry events (threads, runs, tasks, invocations, inference usage,
|
|
792
|
-
* messages...), pushed by Tilde to environments that turn them on: only the streams
|
|
793
|
-
* are delivered. The source must be named `tilde`.
|
|
922
|
+
* messages...), pushed by Tilde to environments that turn them on: only the streams the
|
|
923
|
+
* source declares are delivered. The source must be named `tilde`.
|
|
794
924
|
*/
|
|
795
|
-
events:
|
|
796
|
-
streams: readonly S[];
|
|
797
|
-
}) => Pipeline<S>;
|
|
925
|
+
events: () => Pipeline<RegistryStream>;
|
|
798
926
|
};
|
|
799
927
|
/** Options of `ctx.deferredFetch`. */
|
|
800
928
|
export interface DeferredOptions {
|
|
@@ -1201,15 +1329,15 @@ export interface OntologySpec {
|
|
|
1201
1329
|
/** Third-party accounts each environment binds, by name (`satisfies Connections`), for
|
|
1202
1330
|
* deferred (and live) requests and pipelines. */
|
|
1203
1331
|
connections?: Connections;
|
|
1204
|
-
/**
|
|
1205
|
-
|
|
1332
|
+
/** Every input: `source(name, { from, streams })`. Once a source reads a pipeline, every raw
|
|
1333
|
+
* stream read must be a declared source's, and every declared stream must be read. */
|
|
1334
|
+
sources?: {
|
|
1335
|
+
readonly $source: SourceDecl;
|
|
1336
|
+
}[];
|
|
1206
1337
|
/** Raw secrets the pipelines take (`defineSecrets`), supplied by each environment. */
|
|
1207
1338
|
secrets?: {
|
|
1208
1339
|
readonly [name: string]: SecretRef;
|
|
1209
1340
|
};
|
|
1210
|
-
/** The pipelines that feed the sources (`source(name, { pipeline })`). Once there is one,
|
|
1211
|
-
* every source read must have one, and the rollout builds ducktail's config from them. */
|
|
1212
|
-
pipelines?: PipelineSource[];
|
|
1213
1341
|
/** Where the data lives (default `cell`); it also decides the dialect of every SQL text. */
|
|
1214
1342
|
storage?: Storage;
|
|
1215
1343
|
/** Named places models can materialize to besides the storage (`model({ destination })`),
|
package/dist/mod.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `@trytilde/ontology`: an ontology project in TypeScript, the single source for
|
|
3
3
|
*
|
|
4
|
-
* - **models**:
|
|
5
|
-
*
|
|
4
|
+
* - **sources and models**: every input is a `source` (a pipeline, `ingress()` or `rows()`) whose
|
|
5
|
+
* streams are current-state models; dbt-style ducktail models (`model`, `sqlFile`) over them,
|
|
6
|
+
* compiled to `manifest.json`, which ducktail executes;
|
|
6
7
|
* - **nouns**: object types with typed properties over models, links, entity resolution;
|
|
7
8
|
* - **transactional views**: a portion of the graph materialised per key in a celld SQLite
|
|
8
9
|
* cell for hot transactional work (`transactionalView`);
|
|
@@ -21,11 +22,15 @@
|
|
|
21
22
|
*
|
|
22
23
|
* ```ts
|
|
23
24
|
* import { z } from "zod";
|
|
24
|
-
* import { action,
|
|
25
|
+
* import { action, defineSecrets, model, object, ontology, postgres, secret, source, sql, t, transactionalView } from "@trytilde/ontology";
|
|
25
26
|
*
|
|
26
|
-
* const
|
|
27
|
-
* const
|
|
28
|
-
*
|
|
27
|
+
* const secrets = defineSecrets({ APP_DB_PASSWORD: secret() });
|
|
28
|
+
* const app = source("app", {
|
|
29
|
+
* from: postgres.cdc({ host: "db.internal", user: "replicator", password: secrets.APP_DB_PASSWORD, database: "app", tables: ["public.customers"] }),
|
|
30
|
+
* streams: { public_customers: {} },
|
|
31
|
+
* });
|
|
32
|
+
* const customersNow = app.public_customers;
|
|
33
|
+
* const crmCustomers = model({ name: "crm_customers", type: "model", schema: "cells", materialization: "cell", uniqueKey: "customer_id",
|
|
29
34
|
* columns: { customer_id: t.string(), name: t.string() },
|
|
30
35
|
* sql: ({ ref }) => sql`SELECT payload->>'id' AS customer_id, payload->>'name' AS name FROM ${ref(customersNow)}` });
|
|
31
36
|
* export const Customer = object("Customer", { id: "customer", key: "customerId", source: crmCustomers,
|
|
@@ -37,7 +42,7 @@
|
|
|
37
42
|
* edits: [Customer.notes], reads: [Customer],
|
|
38
43
|
* handler: ({ input, view, ctx }) => { ctx.update(Customer, view.key, { notes: input.notes }); return null; },
|
|
39
44
|
* });
|
|
40
|
-
* export default ontology({ objects: [Customer], views: [CustomerView], actions: [setNotes] });
|
|
45
|
+
* export default ontology({ sources: [app], secrets, objects: [Customer], views: [CustomerView], actions: [setNotes] });
|
|
41
46
|
* ```
|
|
42
47
|
*/
|
|
43
48
|
import { z } from "zod";
|
|
@@ -161,23 +166,127 @@ export class SourceDef {
|
|
|
161
166
|
this.table = `lake.raw.${pipeline}__${stream}`;
|
|
162
167
|
}
|
|
163
168
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
169
|
+
/**
|
|
170
|
+
* Records your code sends through Tilde's Ingress (`IngressService.WriteRecords`, by API keys,
|
|
171
|
+
* people and agents with `write_streams` on the project, or the environment's own worker). Each
|
|
172
|
+
* stream declares a zod `schema` and the `key` property; a newer record of a key replaces the
|
|
173
|
+
* older. Its raw rows are `lake.raw.ingress__<stream>`.
|
|
174
|
+
*/
|
|
175
|
+
export function ingress() {
|
|
176
|
+
return { kind: "ingress", rows: false };
|
|
171
177
|
}
|
|
172
178
|
/**
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
* `lake.raw.ingress__<name>`: read it with `src()` and `changes()` like any source (the payload
|
|
178
|
-
* is the record). List streams in `ontology({ streams })`.
|
|
179
|
+
* Reference data the version ships (a solution's tenant configuration, say): each stream's
|
|
180
|
+
* `rows`, validated against its `schema` and loaded through Ingress by every rollout, so a
|
|
181
|
+
* redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
|
|
182
|
+
* list is not deleted).
|
|
179
183
|
*/
|
|
180
|
-
export
|
|
184
|
+
export function rows() {
|
|
185
|
+
return { kind: "ingress", rows: true };
|
|
186
|
+
}
|
|
187
|
+
export function source(name, spec) {
|
|
188
|
+
const loc = callSite();
|
|
189
|
+
const from = spec.from;
|
|
190
|
+
if (from.kind === "pipeline" && from.name !== null && from.name !== name) {
|
|
191
|
+
throw new Error(`${loc ?? ""} this pipeline is named \`${from.name}\`: source("${from.name}", { from })`);
|
|
192
|
+
}
|
|
193
|
+
const entries = Object.entries(spec.streams);
|
|
194
|
+
if (!entries.length)
|
|
195
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: declare the streams it reads`);
|
|
196
|
+
const out = {};
|
|
197
|
+
const raw = [];
|
|
198
|
+
for (const [stream, o] of entries) {
|
|
199
|
+
let def;
|
|
200
|
+
if (from.kind === "ingress") {
|
|
201
|
+
const io = o;
|
|
202
|
+
if (from.rows && !io.rows)
|
|
203
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: stream \`${stream}\` of rows() needs its \`rows\``);
|
|
204
|
+
def = new StreamDef(stream, io.schema, io.key, io.rows ?? [], loc);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
if (from.streams.length && !from.streams.includes(stream)) {
|
|
208
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: \`${stream}\` is not one of its pipeline's streams (${from.streams.join(", ")})`);
|
|
209
|
+
}
|
|
210
|
+
def = new SourceDef(name, stream, loc);
|
|
211
|
+
}
|
|
212
|
+
raw.push(def);
|
|
213
|
+
if (o.current === false) {
|
|
214
|
+
out[stream] = def;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (from.kind === "pipeline" && from.type === "postgres") {
|
|
218
|
+
const so = o;
|
|
219
|
+
if (so.key !== undefined || so.newest !== undefined || so.deleted !== undefined) {
|
|
220
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: a postgres.cdc stream's current state is ducktail's (by the table's key): no \`key\`, \`newest\` or \`deleted\``);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// A provider's webhook keys each delivery by its delivery id: one row per delivery is no
|
|
224
|
+
// current state, so its streams name their key.
|
|
225
|
+
if (from.kind === "pipeline" && from.type === "webhook" && from.connection !== null && [undefined, "_key"].includes(o.key)) {
|
|
226
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: stream \`${stream}\` of a provider webhook is keyed by delivery: give it a \`key\` (and \`newest\`), or \`current: false\` for its raw rows`);
|
|
227
|
+
}
|
|
228
|
+
// A webhook without a key header delivers no key: its rows have no current state to take.
|
|
229
|
+
if (from.kind === "pipeline" && from.type === "webhook" && from.name === null && !from.options.key_header && [undefined, "_key"].includes(o.key)) {
|
|
230
|
+
throw new Error(`${loc ?? ""} source \`${name}\`: stream \`${stream}\` has no key (webhook() without keyHeader): give it a \`key\`, or \`current: false\` for its raw rows`);
|
|
231
|
+
}
|
|
232
|
+
// Versioned by the record's own time where ducktail writes one that orders versions (the sync
|
|
233
|
+
// kinds, CloudWatch, Kafka's record timestamp: its `_pos` is an offset within one partition);
|
|
234
|
+
// other polled kinds by position, as ducktail takes them (their removals carry no source time).
|
|
235
|
+
const versioned = from.kind === "ingress" || ["linear", "sentry", "github", "cloudwatch", "webhook", "kafka"].includes(from.type);
|
|
236
|
+
const current = from.kind === "pipeline" && from.type === "postgres"
|
|
237
|
+
? new ModelDef({ type: "model", name: `${name}__${stream}`, schema: "sources", description: `The current state of ${name}.${stream}.`, ...cdcCurrent(def) }, loc)
|
|
238
|
+
: currentState(name, stream, def, from.kind === "ingress" ? { key: o.key } : o, versioned ? "_source_ts" : "_pos", loc);
|
|
239
|
+
if (o.history)
|
|
240
|
+
Object.defineProperty(current, "history", { value: def, enumerable: true });
|
|
241
|
+
out[stream] = current;
|
|
242
|
+
}
|
|
243
|
+
out.$source = { name, from, raw, loc };
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
/** The current state of a keyed raw stream: the newest row per key, removals deleted. */
|
|
247
|
+
function currentState(source, stream, of, o, newestByDefault, loc) {
|
|
248
|
+
const text = (v, fallback) => (v === undefined ? fallback : typeof v === "string" ? v : v.sql);
|
|
249
|
+
// A key property of the payload, or the envelope's `_key`; an expression as written.
|
|
250
|
+
const key = o.key === undefined || o.key === "_key"
|
|
251
|
+
? "CAST(_key AS VARCHAR)"
|
|
252
|
+
: typeof o.key === "string"
|
|
253
|
+
? `(payload->>'${o.key.replace(/'/g, "''")}')`
|
|
254
|
+
: o.key.sql;
|
|
255
|
+
const newest = text(o.newest, newestByDefault);
|
|
256
|
+
// NULL is not a removal, in the full build and the incremental one alike.
|
|
257
|
+
const deleted = `coalesce((${text(o.deleted, "_op = 'd'")}), false)`;
|
|
258
|
+
const pick = (from) => raw(`SELECT ${key} AS _key, ${newest} AS _newest, _pos, payload, (${deleted}) AS _gone FROM ${from.sql} AS r WHERE ${key} IS NOT NULL`);
|
|
259
|
+
const order = raw("ORDER BY _key, _newest DESC NULLS LAST, _pos DESC");
|
|
260
|
+
return new ModelDef({
|
|
261
|
+
type: "model",
|
|
262
|
+
name: `${source}__${stream}`,
|
|
263
|
+
schema: "sources",
|
|
264
|
+
description: `The current state of ${source}.${stream}.`,
|
|
265
|
+
materialization: "incremental",
|
|
266
|
+
uniqueKey: "_key",
|
|
267
|
+
incrementalStrategy: "delete+insert",
|
|
268
|
+
sql: ({ src, changes, isIncremental, self, dialect }) =>
|
|
269
|
+
// SQLite has no DISTINCT ON, and runs every model in full.
|
|
270
|
+
dialect === "sqlite"
|
|
271
|
+
? sql `SELECT _key, _newest, _pos, payload FROM (
|
|
272
|
+
SELECT *, row_number() OVER (PARTITION BY _key ${raw("ORDER BY _newest DESC NULLS LAST, _pos DESC")}) AS __n FROM (${pick(src(of))}) every_row
|
|
273
|
+
) newest WHERE __n = 1 AND NOT _gone`
|
|
274
|
+
: isIncremental
|
|
275
|
+
? sql `WITH fresh AS (${pick(changes(of))})
|
|
276
|
+
SELECT _key, _newest, _pos, payload, _gone AS _deleted FROM (
|
|
277
|
+
SELECT DISTINCT ON (_key) * FROM (
|
|
278
|
+
SELECT * FROM fresh
|
|
279
|
+
UNION ALL
|
|
280
|
+
SELECT _key, _newest, _pos, payload, false AS _gone FROM ${self} WHERE _key IN (SELECT _key FROM fresh)
|
|
281
|
+
) both_ages ${order}
|
|
282
|
+
) newest`
|
|
283
|
+
: sql `SELECT _key, _newest, _pos, payload FROM (
|
|
284
|
+
SELECT DISTINCT ON (_key) * FROM (${pick(src(of))}) every_row ${order}
|
|
285
|
+
) newest WHERE NOT _gone`,
|
|
286
|
+
}, loc);
|
|
287
|
+
}
|
|
288
|
+
/** An Ingress stream's raw rows (`lake.raw.ingress__<name>`), with its schema, key and shipped rows. */
|
|
289
|
+
class StreamDef extends SourceDef {
|
|
181
290
|
schema;
|
|
182
291
|
key;
|
|
183
292
|
reference;
|
|
@@ -188,16 +297,6 @@ export class StreamDef extends SourceDef {
|
|
|
188
297
|
this.reference = reference;
|
|
189
298
|
}
|
|
190
299
|
}
|
|
191
|
-
/**
|
|
192
|
-
* `reference`: static records the project ships with the stream (a solution's tenant
|
|
193
|
-
* configuration, say). The build validates them against `schema` and compiles them into the
|
|
194
|
-
* version; every rollout of the version loads them into the environment through Ingress, so a
|
|
195
|
-
* redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
|
|
196
|
-
* list is not deleted).
|
|
197
|
-
*/
|
|
198
|
-
export function stream(name, options) {
|
|
199
|
-
return new StreamDef(name, options.schema, options.key, options.reference ?? [], callSite());
|
|
200
|
-
}
|
|
201
300
|
export function sqlFile(path) {
|
|
202
301
|
return { kind: "sqlFile", path, loc: callSite() };
|
|
203
302
|
}
|
|
@@ -220,17 +319,90 @@ export class ModelDef {
|
|
|
220
319
|
this.id = `model:${spec.name}`;
|
|
221
320
|
}
|
|
222
321
|
}
|
|
322
|
+
const raw = (text) => ({ sql: text });
|
|
223
323
|
export function model(spec) {
|
|
224
|
-
|
|
324
|
+
const loc = callSite();
|
|
325
|
+
if ("key" in spec) {
|
|
326
|
+
// Their SQL is the storage's (IS DISTINCT FROM, the self join): no destination.
|
|
327
|
+
if (spec.destination !== undefined) {
|
|
328
|
+
throw new Error(`model ${spec.name}${loc ? ` (${loc})` : ""}: a ${spec.materialization} model materializes in the storage; it takes no \`destination\``);
|
|
329
|
+
}
|
|
330
|
+
// The generated SQL selects, compares and deletes by these columns: a typo would only fail at
|
|
331
|
+
// ducktail's run, far from here.
|
|
332
|
+
const cols = Object.keys(spec.columns);
|
|
333
|
+
for (const [field, column] of [["key", spec.key], ["partition", "partition" in spec ? spec.partition : undefined]]) {
|
|
334
|
+
if (column !== undefined && !cols.includes(column)) {
|
|
335
|
+
throw new Error(`model ${spec.name}${loc ? ` (${loc})` : ""}: \`${field}: "${column}"\` is not one of its columns (${cols.join(", ")})`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (spec.materialization === "diffed")
|
|
340
|
+
return new ModelDef(diffed(spec), loc);
|
|
341
|
+
if ("rows" in spec)
|
|
342
|
+
return new ModelDef(recomputedCell(spec), loc);
|
|
343
|
+
return new ModelDef(spec, loc);
|
|
344
|
+
}
|
|
345
|
+
/** The key is the model's identity: a duplicate fails its build, not a later run. (A NULL one
|
|
346
|
+
* is dropped by the generated SQL.) */
|
|
347
|
+
const keyTests = (given, key) => given?.some((t) => t.kind === "unique" && t.column === key) ? given : [...(given ?? []), tests.unique(key)];
|
|
348
|
+
function diffed({ gate, sql: body, key, ...spec }) {
|
|
349
|
+
const cols = Object.keys(spec.columns);
|
|
350
|
+
const k = raw(key);
|
|
351
|
+
const changed = cols.filter((c) => c !== key).map((c) => `n.${c} IS DISTINCT FROM o.${c}`).join(" OR ") || "false";
|
|
352
|
+
const list = (alias) => raw(cols.map((c) => `${alias}.${c}`).join(", "));
|
|
353
|
+
return {
|
|
354
|
+
...spec,
|
|
355
|
+
materialization: "incremental",
|
|
356
|
+
uniqueKey: key,
|
|
357
|
+
incrementalStrategy: "delete+insert",
|
|
358
|
+
tests: keyTests(spec.tests, key),
|
|
359
|
+
sql: (ctx) => {
|
|
360
|
+
// A NULL key never matches a stored row: it would be re-emitted every run.
|
|
361
|
+
const keyed = sql `SELECT * FROM (${body(ctx)}) AS __b WHERE ${k} IS NOT NULL`;
|
|
362
|
+
if (!ctx.isIncremental)
|
|
363
|
+
return keyed;
|
|
364
|
+
// A one-time filter: when the gate gives no row, `fresh` is never computed.
|
|
365
|
+
const go = gate ? sql ` AND EXISTS (${gate(ctx)})` : sql ``;
|
|
366
|
+
return sql `WITH fresh AS (${keyed})
|
|
367
|
+
SELECT ${list("n")}, false AS _deleted FROM fresh n LEFT JOIN ${ctx.self} o ON o.${k} = n.${k}
|
|
368
|
+
WHERE (o.${k} IS NULL OR ${raw(changed)})${go}
|
|
369
|
+
UNION ALL
|
|
370
|
+
SELECT ${list("o")}, true AS _deleted FROM ${ctx.self} o
|
|
371
|
+
WHERE NOT EXISTS (SELECT 1 FROM fresh f WHERE f.${k} = o.${k})${go}`;
|
|
372
|
+
},
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
function recomputedCell({ rows, touched, partition, key, ...spec }) {
|
|
376
|
+
const cols = raw(Object.keys(spec.columns).join(", "));
|
|
377
|
+
const k = raw(key);
|
|
378
|
+
return {
|
|
379
|
+
...spec,
|
|
380
|
+
materialization: "cell",
|
|
381
|
+
uniqueKey: key,
|
|
382
|
+
tests: keyTests(spec.tests, key),
|
|
383
|
+
sql: (ctx) => {
|
|
384
|
+
// A NULL key never matches a stored row: it would be re-emitted every run.
|
|
385
|
+
const keyed = (filter) => sql `SELECT * FROM (${rows({ ...ctx, filter })}) AS __r WHERE ${k} IS NOT NULL`;
|
|
386
|
+
if (!ctx.isIncremental)
|
|
387
|
+
return keyed(() => sql `true`);
|
|
388
|
+
const fresh = keyed((keyExpr) => sql `${raw(keyExpr)} IN (SELECT k FROM touched)`);
|
|
389
|
+
return sql `WITH touched AS (${touched(ctx)}),
|
|
390
|
+
fresh AS (${fresh})
|
|
391
|
+
SELECT ${cols}, false AS _deleted FROM fresh
|
|
392
|
+
UNION ALL
|
|
393
|
+
SELECT ${cols}, true AS _deleted FROM ${ctx.self} o
|
|
394
|
+
WHERE o.${raw(partition ?? key)} IN (SELECT k FROM touched) AND NOT EXISTS (SELECT 1 FROM fresh f WHERE f.${k} = o.${k})`;
|
|
395
|
+
},
|
|
396
|
+
};
|
|
225
397
|
}
|
|
226
398
|
/**
|
|
227
399
|
* ducktail's `cdc_current`, verbatim from its README ("Current state from CDC"): the latest
|
|
228
400
|
* row per `_key` of a CDC stream (`_key, _pos, _seq, _source_ts, payload, _deleted`), applying
|
|
229
401
|
* deletes, honouring truncates and snapshot restarts (`t` rows: an incremental pre-hook clears
|
|
230
|
-
* the target) and carrying unchanged TOAST columns forward.
|
|
231
|
-
*
|
|
402
|
+
* the target) and carrying unchanged TOAST columns forward. Every `postgres.cdc` stream's
|
|
403
|
+
* current state.
|
|
232
404
|
*/
|
|
233
|
-
|
|
405
|
+
function cdcCurrent(of) {
|
|
234
406
|
const body = (changes, base) => sql `WITH __changes AS (
|
|
235
407
|
SELECT _key, _op, _pos, _seq, _source_ts, _headers, payload
|
|
236
408
|
FROM ${changes} __c
|
|
@@ -307,10 +479,12 @@ SELECT v._key,
|
|
|
307
479
|
FROM __versions AS v${current}
|
|
308
480
|
WHERE v._n = 1`;
|
|
309
481
|
return {
|
|
310
|
-
|
|
482
|
+
materialization: "incremental",
|
|
311
483
|
uniqueKey: "_key",
|
|
312
484
|
incrementalStrategy: "delete+insert",
|
|
313
485
|
sql: ({ changes, isIncremental, self, dialect }) => {
|
|
486
|
+
if (dialect === "sqlite")
|
|
487
|
+
throw new Error(`${of.loc ?? ""} ${of.pipeline}.${of.stream}: a postgres.cdc stream's current state needs postgres or duckdb storage (sqlite storage ingests on demand, no CDC)`);
|
|
314
488
|
if (dialect === "postgres") {
|
|
315
489
|
return isIncremental
|
|
316
490
|
? pgBody(changes(of), sql `__current.payload`, sql `\nLEFT JOIN ${self} AS __current ON __current._key = v._key`)
|
|
@@ -338,6 +512,10 @@ LEFT JOIN ${self} __current ON __current._key = __versions._key`
|
|
|
338
512
|
* read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
|
|
339
513
|
* history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
|
|
340
514
|
* object's table in that destination, so SQL there can join it.
|
|
515
|
+
*
|
|
516
|
+
* `signals: ["created"]` (Postgres storage) makes those changes of the object signals of the
|
|
517
|
+
* environment's own Tilde connection (`tilde_ontology/<project>-<environment>`), which an
|
|
518
|
+
* agent's routine subscribes to like any connection's: see `signal`.
|
|
341
519
|
*/
|
|
342
520
|
export function object(name, spec) {
|
|
343
521
|
const def = { $kind: "object", $name: name, $spec: spec, $loc: callSite() };
|
|
@@ -345,6 +523,18 @@ export function object(name, spec) {
|
|
|
345
523
|
def[property] = { kind: "prop", object: name, property, prop };
|
|
346
524
|
return def;
|
|
347
525
|
}
|
|
526
|
+
/**
|
|
527
|
+
* A signal the object declares. Tilde delivers each one at least once and, per object, in
|
|
528
|
+
* order; changes that reach the storage together are one signal (an object created and deleted
|
|
529
|
+
* at once is none), and an object that existed before it declared signals emits `created` for
|
|
530
|
+
* none of its rows. A routine's filters and templates name the data's keys (`{{ stage }}`).
|
|
531
|
+
*/
|
|
532
|
+
export function signal(object, change) {
|
|
533
|
+
if (!object.$spec.signals?.includes(change)) {
|
|
534
|
+
throw new Error(`${object.$name} declares no \`${change}\` signal: add it to its signals`);
|
|
535
|
+
}
|
|
536
|
+
return { kind: "signal", object: object.$name, change, type: `tilde_ontology.${object.$spec.id}.${change}` };
|
|
537
|
+
}
|
|
348
538
|
export function history(object) {
|
|
349
539
|
return { kind: "history", object: object.$name, model: `${object.$spec.id}__changes` };
|
|
350
540
|
}
|
|
@@ -447,7 +637,8 @@ export class Pipeline {
|
|
|
447
637
|
}
|
|
448
638
|
/** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
|
|
449
639
|
untypedStreams(...names) {
|
|
450
|
-
|
|
640
|
+
// A catalog kind has no fixed list (the source names its streams); a routed one does.
|
|
641
|
+
return new Pipeline(this.type, this.connection, this.streams.length ? [...this.streams, ...names] : [], this.options, this.loc, this.name);
|
|
451
642
|
}
|
|
452
643
|
}
|
|
453
644
|
/** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
|
|
@@ -459,70 +650,52 @@ export class WebhookPipeline extends Pipeline {
|
|
|
459
650
|
return new WebhookPipeline(this.type, this.connection, this.streams, options, this.loc, this.name);
|
|
460
651
|
}
|
|
461
652
|
}
|
|
462
|
-
|
|
463
|
-
export class PipelineSource {
|
|
464
|
-
name;
|
|
465
|
-
pipeline;
|
|
466
|
-
loc;
|
|
467
|
-
kind = "pipelineSource";
|
|
468
|
-
constructor(name, pipeline, loc) {
|
|
469
|
-
this.name = name;
|
|
470
|
-
this.pipeline = pipeline;
|
|
471
|
-
this.loc = loc;
|
|
472
|
-
}
|
|
473
|
-
/** One of the pipeline's streams: `lake.raw.<name>__<stream>`. */
|
|
474
|
-
stream(stream) {
|
|
475
|
-
return new SourceDef(this.name, stream, callSite());
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
const poll = (kind, connection, o, extra) => new Pipeline(kind, connection, o.streams ?? [], {
|
|
653
|
+
const poll = (kind, connection, o, extra) => new Pipeline(kind, connection, [], {
|
|
479
654
|
interval: o.interval,
|
|
480
655
|
backfill: o.backfill,
|
|
481
656
|
request_timeout: o.requestTimeout,
|
|
482
657
|
...extra,
|
|
483
658
|
}, callSite());
|
|
484
|
-
|
|
659
|
+
const sync = (kind, connection, o, extra) => new Pipeline(kind, connection, [], {
|
|
660
|
+
webhook: o.webhook === false ? undefined : {},
|
|
661
|
+
interval: o.reconcile,
|
|
662
|
+
backfill: o.backfill,
|
|
663
|
+
request_timeout: o.requestTimeout,
|
|
664
|
+
...extra,
|
|
665
|
+
}, callSite());
|
|
666
|
+
function providerWebhook(provider, o) {
|
|
485
667
|
const headers = webhookHeaders[provider];
|
|
486
668
|
const routes = Object.fromEntries(Object.entries(o.route).filter(([, v]) => v !== undefined));
|
|
487
|
-
|
|
669
|
+
const streams = [...new Set([...Object.values(routes), ...(o.fallback ? [o.fallback] : [])])];
|
|
670
|
+
return new WebhookPipeline("webhook", o.connection, streams, {
|
|
488
671
|
key_header: headers.key,
|
|
489
672
|
route: { header: headers.event, streams: routes, fallback: o.fallback },
|
|
490
|
-
...extra,
|
|
491
673
|
}, callSite());
|
|
492
674
|
}
|
|
493
|
-
/** Linear:
|
|
675
|
+
/** Linear: a sync (webhooks, backfill, reconcile), polled GraphQL alone, or the raw webhooks. */
|
|
494
676
|
export const linear = {
|
|
677
|
+
sync: (o) => sync("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
|
|
495
678
|
poll: (o) => poll("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
|
|
496
679
|
webhook: (o) => providerWebhook("linear", o),
|
|
497
680
|
};
|
|
498
|
-
|
|
681
|
+
const sentryOptions = (o) => ({ organization: o.organization, projects: o.projects, base_url: o.baseUrl, query: o.query });
|
|
682
|
+
/** Sentry: a sync (integration webhooks, backfill, reconcile), polled issues alone, or the raw webhooks. */
|
|
499
683
|
export const sentry = {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
projects: o.projects,
|
|
503
|
-
base_url: o.baseUrl,
|
|
504
|
-
query: o.query,
|
|
505
|
-
full_sweep_interval: o.fullSweepInterval,
|
|
506
|
-
}),
|
|
684
|
+
sync: (o) => sync("sentry", o.connection, o, sentryOptions(o)),
|
|
685
|
+
poll: (o) => poll("sentry", o.connection, o, { ...sentryOptions(o), full_sweep_interval: o.fullSweepInterval }),
|
|
507
686
|
webhook: (o) => providerWebhook("sentry", o),
|
|
508
687
|
};
|
|
509
|
-
/** GitHub: the connection's webhooks
|
|
688
|
+
/** GitHub: a sync of the repositories, or the connection's raw webhooks. */
|
|
510
689
|
export const github = {
|
|
511
690
|
/**
|
|
512
|
-
* One stream per entity
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
691
|
+
* One stream per entity: the connection's webhooks for the repositories, after a backfill of
|
|
692
|
+
* their recent pull requests, reviews, check runs and releases on the first run (default 30
|
|
693
|
+
* days). Each row's `_key` is the entity (`{repository, number}` for pull requests, else
|
|
694
|
+
* `{id}`) and `_source_ts` its own time; the payload is the webhook body. Never reconciles:
|
|
695
|
+
* GitHub's webhooks are complete. Only the listed repositories are written: deliveries from
|
|
696
|
+
* any other repository the App is installed on are dropped.
|
|
517
697
|
*/
|
|
518
|
-
sync: (o) =>
|
|
519
|
-
repositories: o.repositories,
|
|
520
|
-
webhook: {},
|
|
521
|
-
backfill: o.backfill,
|
|
522
|
-
base_url: o.baseUrl,
|
|
523
|
-
page_size: o.pageSize,
|
|
524
|
-
request_timeout: o.requestTimeout,
|
|
525
|
-
}, callSite()),
|
|
698
|
+
sync: (o) => sync("github", o.connection, o, { repositories: o.repositories, base_url: o.baseUrl, page_size: o.pageSize }),
|
|
526
699
|
/** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
|
|
527
700
|
webhook: (o) => providerWebhook("github", o),
|
|
528
701
|
};
|
|
@@ -580,20 +753,21 @@ export const kafka = {
|
|
|
580
753
|
};
|
|
581
754
|
/**
|
|
582
755
|
* A webhook pipeline of the solution's own, which Tilde delivers to (records written through
|
|
583
|
-
* Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream
|
|
584
|
-
* a header.
|
|
756
|
+
* Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>` for each stream the
|
|
757
|
+
* source declares, or one URL routed by a header (its streams are then the routes').
|
|
585
758
|
*/
|
|
586
|
-
export function webhook(o) {
|
|
587
|
-
|
|
759
|
+
export function webhook(o = {}) {
|
|
760
|
+
const streams = o.route ? [...new Set([...Object.values(o.route.streams), ...(o.route.fallback ? [o.route.fallback] : [])])] : [];
|
|
761
|
+
return new Pipeline("webhook", null, streams, { key_header: o.keyHeader, route: o.route }, callSite());
|
|
588
762
|
}
|
|
589
763
|
/** Tilde itself. */
|
|
590
764
|
export const tilde = {
|
|
591
765
|
/**
|
|
592
766
|
* The organization's registry events (threads, runs, tasks, invocations, inference usage,
|
|
593
|
-
* messages...), pushed by Tilde to environments that turn them on: only the streams
|
|
594
|
-
* are delivered. The source must be named `tilde`.
|
|
767
|
+
* messages...), pushed by Tilde to environments that turn them on: only the streams the
|
|
768
|
+
* source declares are delivered. The source must be named `tilde`.
|
|
595
769
|
*/
|
|
596
|
-
events: (
|
|
770
|
+
events: () => new Pipeline("webhook", null, [], { key_header: "x-tilde-key" }, callSite(), "tilde"),
|
|
597
771
|
};
|
|
598
772
|
export function auth(name, resolve) {
|
|
599
773
|
return { kind: "auth", name, resolve, loc: callSite() };
|
|
@@ -850,9 +1024,8 @@ export function ontology(spec) {
|
|
|
850
1024
|
policies: [],
|
|
851
1025
|
auths: [],
|
|
852
1026
|
connections: {},
|
|
853
|
-
|
|
1027
|
+
sources: [],
|
|
854
1028
|
secrets: {},
|
|
855
|
-
pipelines: [],
|
|
856
1029
|
storage: "cell",
|
|
857
1030
|
destinations: {},
|
|
858
1031
|
...spec,
|
|
@@ -946,7 +1119,7 @@ function evaluateModel(m, incremental, dialect, readFile, byName, sources) {
|
|
|
946
1119
|
return { sql: body, pre: hooks(m.spec.preHooks), post: hooks(m.spec.postHooks), deps: [...deps], found };
|
|
947
1120
|
}
|
|
948
1121
|
/** A declared pipeline in the IR: ducktail's keys for it, secrets as `${NAME}` (listed). */
|
|
949
|
-
function pipelineIR(p) {
|
|
1122
|
+
function pipelineIR(p, pipeline) {
|
|
950
1123
|
const secrets = new Set();
|
|
951
1124
|
const ref = (s) => {
|
|
952
1125
|
secrets.add(s.name);
|
|
@@ -966,12 +1139,15 @@ function pipelineIR(p) {
|
|
|
966
1139
|
return table(v);
|
|
967
1140
|
};
|
|
968
1141
|
const table = (o) => Object.fromEntries(Object.entries(o).filter(([, x]) => x !== undefined).map(([k, x]) => [k, value(x)]));
|
|
969
|
-
const options = table(
|
|
1142
|
+
const options = table(pipeline.options);
|
|
970
1143
|
return {
|
|
971
1144
|
name: p.name,
|
|
972
|
-
kind:
|
|
973
|
-
connection:
|
|
974
|
-
|
|
1145
|
+
kind: pipeline.type,
|
|
1146
|
+
connection: pipeline.connection ? authName(pipeline.connection) : null,
|
|
1147
|
+
// A routed webhook, CDC or Kafka pipeline writes its own list (routes, tables, topics); a
|
|
1148
|
+
// polled or sync kind polls only the streams the source declares, and Tilde delivers only
|
|
1149
|
+
// those registry events.
|
|
1150
|
+
streams: pipeline.streams.length ? [...pipeline.streams] : p.raw.map((r) => r.stream),
|
|
975
1151
|
secrets: [...secrets].sort(),
|
|
976
1152
|
options,
|
|
977
1153
|
loc: p.loc,
|
|
@@ -985,7 +1161,19 @@ export function toIR(o, root, readFile) {
|
|
|
985
1161
|
: v && typeof v === "object"
|
|
986
1162
|
? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === "loc" ? rel(x) : relDeep(x)]))
|
|
987
1163
|
: v;
|
|
988
|
-
const dialect = o.storage === "postgres" ? "postgres" : "duckdb";
|
|
1164
|
+
const dialect = o.storage === "postgres" ? "postgres" : o.storage === "sqlite" ? "sqlite" : "duckdb";
|
|
1165
|
+
const decls = o.sources.map((x) => x.$source);
|
|
1166
|
+
const seen = new Set();
|
|
1167
|
+
for (const d of decls) {
|
|
1168
|
+
// Ingress streams share one namespace (`ingress__<stream>`), pipelines theirs (`<source>__`).
|
|
1169
|
+
for (const id of d.from.kind === "ingress" ? d.raw.map((r) => `ingress stream \`${r.stream}\``) : [`source \`${d.name}\``]) {
|
|
1170
|
+
if (seen.has(id))
|
|
1171
|
+
throw new Error(`${d.loc ?? ""} ${id} is declared twice`);
|
|
1172
|
+
seen.add(id);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
const pipelines = decls.flatMap((d) => (d.from.kind === "pipeline" ? [[d, d.from]] : []));
|
|
1176
|
+
const streams = decls.flatMap((d) => (d.from.kind === "ingress" ? d.raw : []));
|
|
989
1177
|
// Every model and source reachable from the definitions (and from model SQL).
|
|
990
1178
|
const models = new Map();
|
|
991
1179
|
const sources = new Map();
|
|
@@ -1004,13 +1192,22 @@ export function toIR(o, root, readFile) {
|
|
|
1004
1192
|
const evaluated = new Map();
|
|
1005
1193
|
while (queue.length) {
|
|
1006
1194
|
const m = queue.shift();
|
|
1007
|
-
|
|
1195
|
+
const prior = models.get(m.id);
|
|
1196
|
+
if (prior === m)
|
|
1008
1197
|
continue;
|
|
1198
|
+
// Two definitions of one name (two sources generating `<name>__<stream>`, or a model named so).
|
|
1199
|
+
if (prior)
|
|
1200
|
+
throw new Error(`${m.loc ?? ""} model \`${m.spec.name}\` is defined twice (also at ${prior.loc ?? "?"})`);
|
|
1009
1201
|
models.set(m.id, m);
|
|
1010
|
-
const isIncremental = m.spec.
|
|
1202
|
+
const isIncremental = m.spec.materialization === "incremental" || m.spec.materialization === "cell";
|
|
1011
1203
|
const own = m.spec.destination ? "clickhouse" : dialect;
|
|
1012
1204
|
const full = evaluateModel(m, false, own, readFile, byName, sources);
|
|
1013
|
-
|
|
1205
|
+
// SQLite storage recomputes every table from its full SQL (CONTEXT.md, "SQLite storage").
|
|
1206
|
+
const incremental = isIncremental && dialect !== "sqlite" ? evaluateModel(m, true, own, readFile, byName, sources) : null;
|
|
1207
|
+
// SQLite storage runs a model's full SQL only: hooks for incremental runs would never run.
|
|
1208
|
+
if (dialect === "sqlite" && ((m.spec.preHooks?.incremental?.length ?? 0) > 0 || (m.spec.postHooks?.incremental?.length ?? 0) > 0)) {
|
|
1209
|
+
throw new Error(`model ${m.spec.name}${m.loc ? ` (${m.loc})` : ""}: sqlite storage runs no hooks (it recomputes a model and writes the difference)`);
|
|
1210
|
+
}
|
|
1014
1211
|
evaluated.set(m.id, { full, incremental });
|
|
1015
1212
|
for (const r of [...full.found, ...(incremental?.found ?? [])]) {
|
|
1016
1213
|
if (r.kind === "model")
|
|
@@ -1031,7 +1228,8 @@ export function toIR(o, root, readFile) {
|
|
|
1031
1228
|
name: s.name,
|
|
1032
1229
|
schema: s.schema ?? "main",
|
|
1033
1230
|
description: s.description ?? null,
|
|
1034
|
-
|
|
1231
|
+
type: s.type,
|
|
1232
|
+
materialized: s.materialization,
|
|
1035
1233
|
unique_key: s.uniqueKey === undefined ? [] : Array.isArray(s.uniqueKey) ? s.uniqueKey : [s.uniqueKey],
|
|
1036
1234
|
incremental_strategy: s.incrementalStrategy ?? null,
|
|
1037
1235
|
cluster_by: s.clusterBy ?? null,
|
|
@@ -1067,6 +1265,7 @@ export function toIR(o, root, readFile) {
|
|
|
1067
1265
|
history: !!obj.$spec.history,
|
|
1068
1266
|
history_at: obj.$spec.historyAt ?? null,
|
|
1069
1267
|
...(obj.$spec.replicas?.length ? { replicas: obj.$spec.replicas } : {}),
|
|
1268
|
+
...(obj.$spec.signals?.length ? { signals: [...obj.$spec.signals] } : {}),
|
|
1070
1269
|
properties: Object.entries(obj.$spec.properties).map(([name, p]) => ({
|
|
1071
1270
|
name,
|
|
1072
1271
|
id: p.spec.id ?? null,
|
|
@@ -1102,8 +1301,8 @@ export function toIR(o, root, readFile) {
|
|
|
1102
1301
|
connections: Object.entries(o.connections).map(([name, c]) => ({ name, provider: c.provider, type: c.type ?? null, ...(c.optional ? { optional: true } : {}), loc: null })),
|
|
1103
1302
|
// Only when declared, so the IR of a project without them is unchanged.
|
|
1104
1303
|
...(Object.keys(o.secrets).length ? { secrets: Object.values(o.secrets).map((x) => ({ name: x.name, loc: x.loc })) } : {}),
|
|
1105
|
-
...(
|
|
1106
|
-
streams:
|
|
1304
|
+
...(pipelines.length ? { pipelines: pipelines.map(([d, p]) => pipelineIR(d, p)) } : {}),
|
|
1305
|
+
streams: streams.map((st) => ({
|
|
1107
1306
|
name: st.stream,
|
|
1108
1307
|
key: st.key,
|
|
1109
1308
|
schema: z.toJSONSchema(st.schema, { unrepresentable: "any", io: "input" }),
|
package/package.json
CHANGED