@trytilde/ontology 4.0.0 → 6.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.
Files changed (3) hide show
  1. package/dist/mod.d.ts +245 -119
  2. package/dist/mod.js +285 -99
  3. 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**: dbt-style ducktail models (`source`, `model`, `cdcCurrent`, `sqlFile`), compiled
5
- * to `manifest.json`, which ducktail executes;
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, cdcCurrent, model, object, ontology, source, sql, t, transactionalView } from "@trytilde/ontology";
25
+ * import { action, defineSecrets, model, object, ontology, postgres, secret, source, sql, t, transactionalView } from "@trytilde/ontology";
25
26
  *
26
- * const customersRaw = source("app", "public_customers");
27
- * const customersNow = model({ name: "app_customers", schema: "current", ...cdcCurrent(customersRaw) });
28
- * const crmCustomers = model({ name: "crm_customers", schema: "cells", materialized: "cell", uniqueKey: "customer_id",
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";
@@ -142,42 +147,106 @@ export declare class SourceDef {
142
147
  constructor(pipeline: string, stream: string, loc: string | null);
143
148
  }
144
149
  /**
145
- * A source: `source(pipeline, stream)` names one raw stream of a pipeline declared elsewhere;
146
- * `source(name, { pipeline })` declares the pipeline that feeds the streams (`linear.poll`,
147
- * `github.webhook`, `postgres.cdc`, ...; see Pipelines) and answers its streams as sources
148
- * (`.stream("issues")`, typed by the pipeline's streams). List declared pipelines in
149
- * `ontology({ pipelines })`.
150
+ * Records your code sends through Tilde's Ingress (`IngressService.WriteRecords`, by API keys,
151
+ * people and agents with `write_streams` on the project, or the environment's own worker). Each
152
+ * stream declares a zod `schema` and the `key` property; a newer record of a key replaces the
153
+ * older. Its raw rows are `lake.raw.ingress__<stream>`.
150
154
  */
151
- export declare function source(pipeline: string, stream: string): SourceDef;
152
- export declare function source<const S extends string>(name: string, spec: {
153
- pipeline: Pipeline<S>;
154
- }): PipelineSource<S>;
155
+ export declare function ingress(): IngressFrom;
155
156
  /**
156
- * A custom stream: records that enter the environment through Tilde's Ingress
157
- * (`IngressService.WriteRecords`, by API keys, people and agents with `write_streams` on the
158
- * project, or the environment's own worker), each validated against `schema` and keyed by `key`
159
- * (a string or number property: a newer record of a key replaces the older). They land in
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 })`.
157
+ * Reference data the version ships (a solution's tenant configuration, say): each stream's
158
+ * `rows`, validated against its `schema` and loaded through Ingress by every rollout, so a
159
+ * redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
160
+ * list is not deleted).
162
161
  */
163
- export declare class StreamDef extends SourceDef {
164
- readonly schema: z.ZodType;
165
- readonly key: string;
166
- readonly reference: readonly unknown[];
167
- constructor(name: string, schema: z.ZodType, key: string, reference: readonly unknown[], loc: string | null);
162
+ export declare function rows(): IngressFrom;
163
+ export interface IngressFrom {
164
+ readonly kind: "ingress";
165
+ readonly rows: boolean;
168
166
  }
167
+ /** Where a source's records come from: a pipeline (`linear.sync`, `cloudwatch.poll`,
168
+ * `postgres.cdc`, `tilde.events`, ...), `ingress()` or `rows()`. */
169
+ export type From<S extends string = string> = Pipeline<S> | IngressFrom;
169
170
  /**
170
- * `reference`: static records the project ships with the stream (a solution's tenant
171
- * configuration, say). The build validates them against `schema` and compiles them into the
172
- * version; every rollout of the version loads them into the environment through Ingress, so a
173
- * redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
174
- * list is not deleted).
171
+ * How a source stream is read. By default it is its **current state**: one row per key, the
172
+ * newest, keys whose newest row removes them dropped (a generated incremental model,
173
+ * `lake.sources.<source>__<stream>`, columns `_key`, `_newest`, `_pos`, `payload`; a
174
+ * `postgres.cdc` stream gets ducktail's CDC current state instead, columns `_key`, `_pos`, `_seq`,
175
+ * `_source_ts`, `payload`). `ref()` it, map objects onto it, `changes()` it.
175
176
  */
176
- export declare function stream(name: string, options: {
177
+ export interface StreamOptions {
178
+ /** The key: a payload property, `_key` (the default: the record's identity as ducktail writes
179
+ * it), or a SQL expression over the raw row. */
180
+ key?: string | Sql;
181
+ /** SQL over the raw row ordering a key's rows (the largest wins, then the latest position):
182
+ * default `_source_ts`, the record's own version, for the sync kinds, CloudWatch, webhooks and
183
+ * ingress; `_pos` for other polled kinds (Plaid, Gmail, ...), whose removals carry no time. A
184
+ * removal that loses its key's order is not applied until a newer one wins; an incremental
185
+ * build compares only with rows still held, so a late older row can bring a removed key back
186
+ * until a full build (the sync kinds' reconcile repairs it). */
187
+ newest?: string | Sql;
188
+ /** SQL over the raw row, true for a row that removes its key: default `_op = 'd'`. */
189
+ deleted?: string | Sql;
190
+ /** Also give the raw rows as `.history` (every version, as ingested). */
191
+ history?: boolean;
192
+ /** `false`: no current state; the stream is its raw rows (an append-only log). */
193
+ current?: false;
194
+ }
195
+ /** A stream of `ingress()` or `rows()`: records validated against `schema`, keyed by `key`. */
196
+ export interface IngressStreamOptions {
177
197
  schema: z.ZodType;
198
+ /** A string or number property of the record. */
178
199
  key: string;
179
- reference?: readonly unknown[];
180
- }): StreamDef;
200
+ /** The records the version ships (required with `rows()`). */
201
+ rows?: readonly unknown[];
202
+ history?: boolean;
203
+ current?: false;
204
+ }
205
+ /** A source stream as the definitions use it: its current state (a model), with `.history`
206
+ * where declared; with `current: false`, its raw rows. */
207
+ export type StreamOf<O> = O extends {
208
+ current: false;
209
+ } ? SourceDef : O extends {
210
+ history: true;
211
+ } ? ModelDef & {
212
+ readonly history: SourceDef;
213
+ } : ModelDef;
214
+ /** What `source()` declares: its name, where its records come from, and its streams. */
215
+ export interface SourceDecl {
216
+ readonly name: string;
217
+ readonly from: From;
218
+ /** Each declared stream's raw rows. */
219
+ readonly raw: readonly SourceDef[];
220
+ readonly loc: string | null;
221
+ }
222
+ /** A declared source: each stream under its name, plus the declaration. */
223
+ export type Source<St = Record<string, unknown>> = {
224
+ readonly [K in keyof St]: StreamOf<St[K]>;
225
+ } & {
226
+ readonly $source: SourceDecl;
227
+ };
228
+ /**
229
+ * Every input of an ontology is a source: `source(name, { from, streams })`, where `from` is a
230
+ * pipeline (`linear.sync`, `github.sync`, `cloudwatch.poll`, `postgres.cdc`, `tilde.events`, your
231
+ * own `webhook()`, ...), `ingress()` or `rows()`, and `streams` names the streams it reads (typed
232
+ * by the pipeline) and how. `linear.issues` is then the current state of Linear's issues. List
233
+ * sources in `ontology({ sources })`. The name is the pipeline's state (cursors, backfills) and
234
+ * its raw tables' prefix (`lake.raw.<name>__<stream>`): renaming one starts it over.
235
+ */
236
+ export declare function source<const S extends string, const St extends {
237
+ readonly [K in S]?: StreamOptions;
238
+ }>(name: string, spec: {
239
+ from: Pipeline<S>;
240
+ streams: St & {
241
+ readonly [K in Exclude<keyof St, S>]: never;
242
+ };
243
+ }): Source<St>;
244
+ export declare function source<const St extends {
245
+ readonly [name: string]: IngressStreamOptions;
246
+ }>(name: string, spec: {
247
+ from: IngressFrom;
248
+ streams: St;
249
+ }): Source<St>;
181
250
  /** The SQL builder context of a model: evaluated twice, once per `isIncremental`. */
182
251
  export interface ModelSqlCtx {
183
252
  /** `lake.<schema>.<name>` of another model (a dependency), or an object type's table: the
@@ -251,10 +320,19 @@ export interface ModelIndex {
251
320
  unique?: boolean;
252
321
  method?: "btree" | "gin" | "gist" | "hash" | "brin";
253
322
  }
323
+ /**
324
+ * What a model is for, checked by the build. `staging`: cleanup of sources (casts, renames,
325
+ * dedup, unnesting), private: only other models `ref()` it. It backs no object, so it is not in
326
+ * the object schema, but lineage docs still show it. `model`: the domain; the only kind that backs an object. `projection`: a
327
+ * read-shaped table over objects or models (a grid, with indexes and search) for reads and
328
+ * realtime; never an object's source.
329
+ */
330
+ export type ModelType = "staging" | "model" | "projection";
254
331
  export interface ModelSpec<C extends Props> {
255
332
  name: string;
333
+ type: ModelType;
256
334
  schema?: string;
257
- materialized: "view" | "table" | "incremental" | "cell" | "microbatch";
335
+ materialization: "view" | "table" | "incremental" | "cell" | "microbatch";
258
336
  /** `microbatch` models (Postgres storage): built batch by batch of `eventTime` from `begin`
259
337
  * (a date, an RFC 3339 time or a duration before now; default: ducktail's `[backfill] start`),
260
338
  * each batch replaced as a whole; the SQL filters its inputs with `batchStart` / `batchEnd`. */
@@ -296,23 +374,38 @@ export declare class ModelDef<C extends Props = Props> {
296
374
  } | null;
297
375
  constructor(spec: ModelSpec<C>, loc: string | null);
298
376
  }
299
- export declare function model<C extends Props = Props>(spec: ModelSpec<C>): ModelDef<C>;
377
+ type Generated = "materialization" | "sql" | "uniqueKey" | "incrementalStrategy" | "columns" | "microbatch";
300
378
  /**
301
- * ducktail's `cdc_current`, verbatim from its README ("Current state from CDC"): the latest
302
- * row per `_key` of a CDC stream (`_key, _pos, _seq, _source_ts, payload, _deleted`), applying
303
- * deletes, honouring truncates and snapshot restarts (`t` rows: an incremental pre-hook clears
304
- * the target) and carrying unchanged TOAST columns forward. Spread it into a model:
305
- * `model({ name: "app_users", schema: "current", ...cdcCurrent(source("app", "users")) })`.
379
+ * `materialization: "diffed"`: a table recomputed from its upstreams' full state (`sql`) on every
380
+ * run that writes only the rows that differ from what it holds and deletes the keys that
381
+ * disappeared, so `changes()` over it (and realtime watches) stay as small as the real change.
382
+ * `gate` gives a row when the run must recompute (its upstreams' `changes`); without one, every
383
+ * run does. Stored as an incremental model.
306
384
  */
307
- export declare function cdcCurrent(of: SourceDef): {
308
- materialized: "incremental";
309
- uniqueKey: string;
310
- incrementalStrategy: "delete+insert";
311
- sql: ({ changes, isIncremental, self, dialect }: ModelSqlCtx) => Sql;
312
- preHooks: {
313
- incremental: (({ changes, self }: ModelSqlCtx) => Sql)[];
314
- };
315
- };
385
+ export interface DiffedModelSpec<C extends Props> extends Omit<ModelSpec<C>, Generated> {
386
+ materialization: "diffed";
387
+ key: string;
388
+ columns: C;
389
+ sql: (ctx: Pick<ModelSqlCtx, "ref" | "src" | "dialect">) => Sql;
390
+ gate?: (ctx: Pick<ModelSqlCtx, "ref" | "changes">) => Sql;
391
+ }
392
+ /**
393
+ * `materialization: "cell"` recomputed per touched key: `rows(filter)` selects the rows for the
394
+ * keys a SQL predicate admits (`filter` takes the caller's key expression), `touched` the keys
395
+ * (column `k`) any upstream change may affect. Rows of a touched key that no longer come out
396
+ * are deleted. `partition` is the column `touched` keys match, when it is not `key`.
397
+ */
398
+ export interface RecomputedCellModelSpec<C extends Props> extends Omit<ModelSpec<C>, Generated> {
399
+ materialization: "cell";
400
+ key: string;
401
+ partition?: string;
402
+ columns: C;
403
+ rows: (ctx: Pick<ModelSqlCtx, "ref" | "src" | "dialect"> & {
404
+ filter: (keyExpr: string) => Sql;
405
+ }) => Sql;
406
+ touched: (ctx: Pick<ModelSqlCtx, "ref" | "changes" | "self">) => Sql;
407
+ }
408
+ export declare function model<C extends Props = Props>(spec: ModelSpec<C> | DiffedModelSpec<C> | RecomputedCellModelSpec<C>): ModelDef<C>;
316
409
  /** A reference to one property of an object type (`Customer.notes`). */
317
410
  export interface PropRef<O extends string = string, F extends string = string, P = Prop<unknown, boolean, boolean>> {
318
411
  readonly kind: "prop";
@@ -332,6 +425,7 @@ type ObjectInternals<N extends string, P extends Props, K extends keyof P & stri
332
425
  history?: boolean;
333
426
  historyAt?: string;
334
427
  replicas?: string[];
428
+ signals?: readonly SignalChange[];
335
429
  };
336
430
  readonly $loc: string | null;
337
431
  /** Type-level only: the object row handlers see. */
@@ -351,6 +445,7 @@ export interface AnyObject {
351
445
  history?: boolean;
352
446
  historyAt?: string;
353
447
  replicas?: string[];
448
+ signals?: readonly SignalChange[];
354
449
  };
355
450
  readonly $loc: string | null;
356
451
  readonly $row: any;
@@ -370,6 +465,10 @@ export type ObjectDef<N extends string = string, P extends Props = Props, K exte
370
465
  * read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
371
466
  * history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
372
467
  * object's table in that destination, so SQL there can join it.
468
+ *
469
+ * `signals: ["created"]` (Postgres storage) makes those changes of the object signals of the
470
+ * environment's own Tilde connection (`tilde_ontology/<project>-<environment>`), which an
471
+ * agent's routine subscribes to like any connection's: see `signal`.
373
472
  */
374
473
  export declare function object<const N extends string, P extends Props, const K extends keyof P & string>(name: N, spec: {
375
474
  id: string;
@@ -380,7 +479,31 @@ export declare function object<const N extends string, P extends Props, const K
380
479
  history?: boolean;
381
480
  historyAt?: keyof P & string;
382
481
  replicas?: string[];
482
+ signals?: readonly SignalChange[];
383
483
  }): ObjectDef<N, P, K>;
484
+ /** A change of an object that can be a signal (`object({ signals })`). */
485
+ export type SignalChange = "created" | "updated" | "deleted";
486
+ /** A signal's data: the object's properties by API name, as JSON (keys, refs, decimals, dates and
487
+ * timestamps as text). For `deleted`, as they last were. */
488
+ export type SignalData<O extends AnyObject> = O["$row"];
489
+ /** One signal of an object, for the routine that takes it (`@trytilde/iac`'s
490
+ * `signal: { connection, type, filters }`): its `type` on the environment's connection. `$data`
491
+ * exists at the type level only. */
492
+ export interface SignalRef<O extends AnyObject = AnyObject> {
493
+ readonly kind: "signal";
494
+ readonly object: string;
495
+ readonly change: SignalChange;
496
+ /** `tilde_ontology.<object id>.<change>`. */
497
+ readonly type: string;
498
+ readonly $data: SignalData<O>;
499
+ }
500
+ /**
501
+ * A signal the object declares. Tilde delivers each one at least once and, per object, in
502
+ * order; changes that reach the storage together are one signal (an object created and deleted
503
+ * at once is none), and an object that existed before it declared signals emits `created` for
504
+ * none of its rows. A routine's filters and templates name the data's keys (`{{ stage }}`).
505
+ */
506
+ export declare function signal<O extends AnyObject>(object: O, change: SignalChange): SignalRef<O>;
384
507
  /** An object type's change history (`history: true`): the relation `lake.ontology.<id>__changes`,
385
508
  * which a view-less read declares in its `reads`, and Cedar's `Model::"<id>__changes"` (what
386
509
  * `query` is decided on). */
@@ -607,20 +730,8 @@ export declare class WebhookPipeline<S extends string = string, E extends string
607
730
  readonly [event: string]: NoInfer<S>;
608
731
  }): WebhookPipeline<S, E>;
609
732
  }
610
- /** A declared source: a pipeline under its name, whose streams are sources. */
611
- export declare class PipelineSource<S extends string = string> {
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[];
733
+ /** Polled options every polled kind takes. The streams it polls are the source's. */
734
+ interface PollOptions {
624
735
  interval?: Duration;
625
736
  /** Where the first sweep starts: a date, an RFC 3339 time or a duration before now. */
626
737
  backfill?: {
@@ -628,65 +739,83 @@ interface PollOptions<St extends string> {
628
739
  };
629
740
  requestTimeout?: Duration;
630
741
  }
631
- /** A provider webhook's routing: event name -> stream, the rest to `fallback`. */
742
+ /**
743
+ * A provider sync (ducktail's sync pipelines): one stream per entity, merging a backfill on the
744
+ * first run, the connection's webhooks (`webhook`, default on) and, where the provider takes
745
+ * it, a slow reconciling poll (`reconcile`; default 1h with webhooks, 60s without). Each row's
746
+ * `_key` is the entity and `_source_ts` its own version, so the source's streams are current
747
+ * state with no options.
748
+ */
749
+ interface SyncOptions {
750
+ webhook?: boolean;
751
+ reconcile?: Duration;
752
+ /** Where the backfill starts: a date, an RFC 3339 time or a duration before now. */
753
+ backfill?: {
754
+ start: string;
755
+ };
756
+ requestTimeout?: Duration;
757
+ }
758
+ /** A provider webhook's routing: event name -> stream, the rest to `fallback`. The streams are
759
+ * the routes' (and the fallback's). */
632
760
  interface WebhookOptions<P extends keyof WebhookEvents, S extends string> {
633
761
  connection: Connection<P>;
634
- /** The pipeline's streams. */
635
- streams: readonly S[];
636
762
  /** Event -> stream; events not listed go to `fallback` (without one, ducktail answers 422). */
637
763
  route: {
638
- readonly [E in WebhookEvents[P]]?: NoInfer<S>;
764
+ readonly [E in WebhookEvents[P]]?: S;
639
765
  };
640
- fallback?: NoInfer<S>;
766
+ fallback?: S;
641
767
  }
642
- /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
768
+ /** Linear: a sync (webhooks, backfill, reconcile), polled GraphQL alone, or the raw webhooks. */
643
769
  export declare const linear: {
644
- poll: <const St extends PolledStreams["linear"] = "teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">(o: PollOptions<St> & {
770
+ sync: (o: SyncOptions & {
771
+ connection: Connection<"linear">;
772
+ pageSize?: number;
773
+ fields?: { readonly [K in SyncStreams["linear"]]?: string; };
774
+ endpoint?: string;
775
+ }) => Pipeline<"teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">;
776
+ poll: (o: PollOptions & {
645
777
  connection: Connection<"linear">;
646
778
  pageSize?: number;
647
779
  /** A stream's GraphQL selection, replacing the built-in one. */
648
780
  fields?: { readonly [K in PolledStreams["linear"]]?: string; };
649
781
  endpoint?: string;
650
- }) => Pipeline<St>;
782
+ }) => Pipeline<"teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">;
651
783
  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
784
  };
653
- /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
785
+ interface SentryOptions {
786
+ connection: Connection<"sentry">;
787
+ organization: string;
788
+ /** Project slugs whose issues are read. */
789
+ projects?: readonly string[];
790
+ /** `https://sentry.io` (default), a regional host or self-hosted Sentry. */
791
+ baseUrl?: string;
792
+ query?: string;
793
+ }
794
+ /** Sentry: a sync (integration webhooks, backfill, reconcile), polled issues alone, or the raw webhooks. */
654
795
  export declare const sentry: {
655
- poll: <const St extends PolledStreams["sentry"] = "projects" | "issues">(o: PollOptions<St> & {
656
- connection: Connection<"sentry">;
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;
796
+ sync: (o: SyncOptions & SentryOptions) => Pipeline<"projects" | "issues">;
797
+ poll: (o: PollOptions & SentryOptions & {
663
798
  fullSweepInterval?: Duration;
664
- }) => Pipeline<St>;
799
+ }) => Pipeline<"projects" | "issues">;
665
800
  webhook: <const S extends string>(o: WebhookOptions<"sentry", S>) => WebhookPipeline<S, "installation" | "comment" | "error" | "event_alert" | "issue" | "metric_alert" | "seer">;
666
801
  };
667
- /** GitHub: the connection's webhooks (a GitHub App's). */
802
+ /** GitHub: a sync of the repositories, or the connection's raw webhooks. */
668
803
  export declare const github: {
669
804
  /**
670
- * One stream per entity (ducktail's `github` sync pipeline): the connection's webhooks for
671
- * the repositories, after a backfill of their recent pull requests, reviews, check runs and
672
- * releases on the first run (default 30 days). Each row's `_key` is the entity
673
- * (`{repository, number}` for pull requests, else `{id}`) and `_source_ts` its own time; the
674
- * payload is the webhook body. Never reconciles: GitHub's webhooks are complete.
805
+ * One stream per entity: the connection's webhooks for the repositories, after a backfill of
806
+ * their recent pull requests, reviews, check runs and releases on the first run (default 30
807
+ * days). Each row's `_key` is the entity (`{repository, number}` for pull requests, else
808
+ * `{id}`) and `_source_ts` its own time; the payload is the webhook body. Never reconciles:
809
+ * GitHub's webhooks are complete. Only the listed repositories are written: deliveries from
810
+ * any other repository the App is installed on are dropped.
675
811
  */
676
- sync: <const St extends SyncStreams["github"] = "pull_requests" | "pull_request_reviews" | "check_runs" | "releases">(o: {
812
+ sync: (o: Omit<SyncOptions, "reconcile" | "webhook"> & {
677
813
  connection: Connection<"github">;
678
- /** `owner/name`: backfilled, and the only repositories whose deliveries are written. */
814
+ /** `owner/name`: backfilled (each once, by its own job), and the only repositories written. */
679
815
  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
816
  baseUrl?: string;
687
817
  pageSize?: number;
688
- requestTimeout?: Duration;
689
- }) => Pipeline<St>;
818
+ }) => Pipeline<"pull_requests" | "pull_request_reviews" | "check_runs" | "releases">;
690
819
  /** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
691
820
  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
821
  };
@@ -702,7 +831,7 @@ export interface CloudwatchMetric {
702
831
  }
703
832
  /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
704
833
  export declare const cloudwatch: {
705
- poll: <const St extends PolledStreams["cloudwatch"] = "ecs_clusters" | "ecs_services" | "load_balancers" | "target_groups" | "target_health" | "metric_data" | "alarms" | "alarm_history">(o: PollOptions<St> & {
834
+ poll: (o: PollOptions & {
706
835
  connection: Connection<PolledProvider["cloudwatch"]>;
707
836
  region: string;
708
837
  discoveryInterval?: Duration;
@@ -721,16 +850,16 @@ export declare const cloudwatch: {
721
850
  discoverMetrics?: boolean;
722
851
  metrics?: readonly CloudwatchMetric[];
723
852
  endpoint?: string;
724
- }) => Pipeline<St>;
853
+ }) => Pipeline<"ecs_clusters" | "ecs_services" | "load_balancers" | "target_groups" | "target_health" | "metric_data" | "alarms" | "alarm_history">;
725
854
  };
726
855
  /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
727
856
  * `options` are ducktail's keys for it (README, "Polled sources"). */
728
- export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch">, const St extends PolledStreams[K] = PolledStreams[K]>(kind: K, o: PollOptions<St> & {
857
+ export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch">>(kind: K, o: PollOptions & {
729
858
  connection: Connection<PolledProvider[K]>;
730
859
  options?: {
731
860
  readonly [key: string]: PipelineValue | undefined;
732
861
  };
733
- }): Pipeline<St>;
862
+ }): Pipeline<PolledStreams[K]>;
734
863
  /** Postgres logical replication of tables (streams `<schema>_<table>`). */
735
864
  export declare const postgres: {
736
865
  cdc: <const T extends string>(o: {
@@ -768,19 +897,18 @@ export declare const kafka: {
768
897
  };
769
898
  /**
770
899
  * 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>`, or one URL routed by
772
- * a header.
900
+ * Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>` for each stream the
901
+ * source declares, or one URL routed by a header (its streams are then the routes').
773
902
  */
774
- export declare function webhook<const S extends string>(o: {
775
- streams: readonly S[];
903
+ export declare function webhook<const S extends string = string>(o?: {
776
904
  /** The header whose value keys deliveries (`_key = {"id": ...}`). */
777
905
  keyHeader?: string;
778
906
  route?: {
779
907
  header: string;
780
908
  streams: {
781
- readonly [value: string]: NoInfer<S>;
909
+ readonly [value: string]: S;
782
910
  };
783
- fallback?: NoInfer<S>;
911
+ fallback?: S;
784
912
  };
785
913
  }): Pipeline<S>;
786
914
  /** The tables Tilde's registry events deliver (`tilde.events`). */
@@ -789,12 +917,10 @@ export type RegistryStream = "public_chat_threads" | "public_chat_runs" | "publi
789
917
  export declare const tilde: {
790
918
  /**
791
919
  * 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 listed
793
- * are delivered. The source must be named `tilde`.
920
+ * messages...), pushed by Tilde to environments that turn them on: only the streams the
921
+ * source declares are delivered. The source must be named `tilde`.
794
922
  */
795
- events: <const S extends RegistryStream>(o: {
796
- streams: readonly S[];
797
- }) => Pipeline<S>;
923
+ events: () => Pipeline<RegistryStream>;
798
924
  };
799
925
  /** Options of `ctx.deferredFetch`. */
800
926
  export interface DeferredOptions {
@@ -1201,15 +1327,15 @@ export interface OntologySpec {
1201
1327
  /** Third-party accounts each environment binds, by name (`satisfies Connections`), for
1202
1328
  * deferred (and live) requests and pipelines. */
1203
1329
  connections?: Connections;
1204
- /** Custom streams records are written to through Tilde's Ingress (`stream`). */
1205
- streams?: StreamDef[];
1330
+ /** Every input: `source(name, { from, streams })`. Once a source reads a pipeline, every raw
1331
+ * stream read must be a declared source's, and every declared stream must be read. */
1332
+ sources?: {
1333
+ readonly $source: SourceDecl;
1334
+ }[];
1206
1335
  /** Raw secrets the pipelines take (`defineSecrets`), supplied by each environment. */
1207
1336
  secrets?: {
1208
1337
  readonly [name: string]: SecretRef;
1209
1338
  };
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
1339
  /** Where the data lives (default `cell`); it also decides the dialect of every SQL text. */
1214
1340
  storage?: Storage;
1215
1341
  /** 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**: dbt-style ducktail models (`source`, `model`, `cdcCurrent`, `sqlFile`), compiled
5
- * to `manifest.json`, which ducktail executes;
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, cdcCurrent, model, object, ontology, source, sql, t, transactionalView } from "@trytilde/ontology";
25
+ * import { action, defineSecrets, model, object, ontology, postgres, secret, source, sql, t, transactionalView } from "@trytilde/ontology";
25
26
  *
26
- * const customersRaw = source("app", "public_customers");
27
- * const customersNow = model({ name: "app_customers", schema: "current", ...cdcCurrent(customersRaw) });
28
- * const crmCustomers = model({ name: "crm_customers", schema: "cells", materialized: "cell", uniqueKey: "customer_id",
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,121 @@ export class SourceDef {
161
166
  this.table = `lake.raw.${pipeline}__${stream}`;
162
167
  }
163
168
  }
164
- export function source(name, spec) {
165
- if (typeof spec === "string")
166
- return new SourceDef(name, spec, callSite());
167
- if (spec.pipeline.name !== null && spec.pipeline.name !== name) {
168
- throw new Error(`${callSite() ?? ""} this pipeline is named \`${spec.pipeline.name}\`: source("${spec.pipeline.name}", { pipeline })`);
169
- }
170
- return new PipelineSource(name, spec.pipeline, callSite());
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
- * A custom stream: records that enter the environment through Tilde's Ingress
174
- * (`IngressService.WriteRecords`, by API keys, people and agents with `write_streams` on the
175
- * project, or the environment's own worker), each validated against `schema` and keyed by `key`
176
- * (a string or number property: a newer record of a key replaces the older). They land in
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 class StreamDef extends SourceDef {
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 }) => isIncremental
269
+ ? sql `WITH fresh AS (${pick(changes(of))})
270
+ SELECT _key, _newest, _pos, payload, _gone AS _deleted FROM (
271
+ SELECT DISTINCT ON (_key) * FROM (
272
+ SELECT * FROM fresh
273
+ UNION ALL
274
+ SELECT _key, _newest, _pos, payload, false AS _gone FROM ${self} WHERE _key IN (SELECT _key FROM fresh)
275
+ ) both_ages ${order}
276
+ ) newest`
277
+ : sql `SELECT _key, _newest, _pos, payload FROM (
278
+ SELECT DISTINCT ON (_key) * FROM (${pick(src(of))}) every_row ${order}
279
+ ) newest WHERE NOT _gone`,
280
+ }, loc);
281
+ }
282
+ /** An Ingress stream's raw rows (`lake.raw.ingress__<name>`), with its schema, key and shipped rows. */
283
+ class StreamDef extends SourceDef {
181
284
  schema;
182
285
  key;
183
286
  reference;
@@ -188,16 +291,6 @@ export class StreamDef extends SourceDef {
188
291
  this.reference = reference;
189
292
  }
190
293
  }
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
294
  export function sqlFile(path) {
202
295
  return { kind: "sqlFile", path, loc: callSite() };
203
296
  }
@@ -220,17 +313,90 @@ export class ModelDef {
220
313
  this.id = `model:${spec.name}`;
221
314
  }
222
315
  }
316
+ const raw = (text) => ({ sql: text });
223
317
  export function model(spec) {
224
- return new ModelDef(spec, callSite());
318
+ const loc = callSite();
319
+ if ("key" in spec) {
320
+ // Their SQL is the storage's (IS DISTINCT FROM, the self join): no destination.
321
+ if (spec.destination !== undefined) {
322
+ throw new Error(`model ${spec.name}${loc ? ` (${loc})` : ""}: a ${spec.materialization} model materializes in the storage; it takes no \`destination\``);
323
+ }
324
+ // The generated SQL selects, compares and deletes by these columns: a typo would only fail at
325
+ // ducktail's run, far from here.
326
+ const cols = Object.keys(spec.columns);
327
+ for (const [field, column] of [["key", spec.key], ["partition", "partition" in spec ? spec.partition : undefined]]) {
328
+ if (column !== undefined && !cols.includes(column)) {
329
+ throw new Error(`model ${spec.name}${loc ? ` (${loc})` : ""}: \`${field}: "${column}"\` is not one of its columns (${cols.join(", ")})`);
330
+ }
331
+ }
332
+ }
333
+ if (spec.materialization === "diffed")
334
+ return new ModelDef(diffed(spec), loc);
335
+ if ("rows" in spec)
336
+ return new ModelDef(recomputedCell(spec), loc);
337
+ return new ModelDef(spec, loc);
338
+ }
339
+ /** The key is the model's identity: a duplicate fails its build, not a later run. (A NULL one
340
+ * is dropped by the generated SQL.) */
341
+ const keyTests = (given, key) => given?.some((t) => t.kind === "unique" && t.column === key) ? given : [...(given ?? []), tests.unique(key)];
342
+ function diffed({ gate, sql: body, key, ...spec }) {
343
+ const cols = Object.keys(spec.columns);
344
+ const k = raw(key);
345
+ const changed = cols.filter((c) => c !== key).map((c) => `n.${c} IS DISTINCT FROM o.${c}`).join(" OR ") || "false";
346
+ const list = (alias) => raw(cols.map((c) => `${alias}.${c}`).join(", "));
347
+ return {
348
+ ...spec,
349
+ materialization: "incremental",
350
+ uniqueKey: key,
351
+ incrementalStrategy: "delete+insert",
352
+ tests: keyTests(spec.tests, key),
353
+ sql: (ctx) => {
354
+ // A NULL key never matches a stored row: it would be re-emitted every run.
355
+ const keyed = sql `SELECT * FROM (${body(ctx)}) AS __b WHERE ${k} IS NOT NULL`;
356
+ if (!ctx.isIncremental)
357
+ return keyed;
358
+ // A one-time filter: when the gate gives no row, `fresh` is never computed.
359
+ const go = gate ? sql ` AND EXISTS (${gate(ctx)})` : sql ``;
360
+ return sql `WITH fresh AS (${keyed})
361
+ SELECT ${list("n")}, false AS _deleted FROM fresh n LEFT JOIN ${ctx.self} o ON o.${k} = n.${k}
362
+ WHERE (o.${k} IS NULL OR ${raw(changed)})${go}
363
+ UNION ALL
364
+ SELECT ${list("o")}, true AS _deleted FROM ${ctx.self} o
365
+ WHERE NOT EXISTS (SELECT 1 FROM fresh f WHERE f.${k} = o.${k})${go}`;
366
+ },
367
+ };
368
+ }
369
+ function recomputedCell({ rows, touched, partition, key, ...spec }) {
370
+ const cols = raw(Object.keys(spec.columns).join(", "));
371
+ const k = raw(key);
372
+ return {
373
+ ...spec,
374
+ materialization: "cell",
375
+ uniqueKey: key,
376
+ tests: keyTests(spec.tests, key),
377
+ sql: (ctx) => {
378
+ // A NULL key never matches a stored row: it would be re-emitted every run.
379
+ const keyed = (filter) => sql `SELECT * FROM (${rows({ ...ctx, filter })}) AS __r WHERE ${k} IS NOT NULL`;
380
+ if (!ctx.isIncremental)
381
+ return keyed(() => sql `true`);
382
+ const fresh = keyed((keyExpr) => sql `${raw(keyExpr)} IN (SELECT k FROM touched)`);
383
+ return sql `WITH touched AS (${touched(ctx)}),
384
+ fresh AS (${fresh})
385
+ SELECT ${cols}, false AS _deleted FROM fresh
386
+ UNION ALL
387
+ SELECT ${cols}, true AS _deleted FROM ${ctx.self} o
388
+ WHERE o.${raw(partition ?? key)} IN (SELECT k FROM touched) AND NOT EXISTS (SELECT 1 FROM fresh f WHERE f.${k} = o.${k})`;
389
+ },
390
+ };
225
391
  }
226
392
  /**
227
393
  * ducktail's `cdc_current`, verbatim from its README ("Current state from CDC"): the latest
228
394
  * row per `_key` of a CDC stream (`_key, _pos, _seq, _source_ts, payload, _deleted`), applying
229
395
  * deletes, honouring truncates and snapshot restarts (`t` rows: an incremental pre-hook clears
230
- * the target) and carrying unchanged TOAST columns forward. Spread it into a model:
231
- * `model({ name: "app_users", schema: "current", ...cdcCurrent(source("app", "users")) })`.
396
+ * the target) and carrying unchanged TOAST columns forward. Every `postgres.cdc` stream's
397
+ * current state.
232
398
  */
233
- export function cdcCurrent(of) {
399
+ function cdcCurrent(of) {
234
400
  const body = (changes, base) => sql `WITH __changes AS (
235
401
  SELECT _key, _op, _pos, _seq, _source_ts, _headers, payload
236
402
  FROM ${changes} __c
@@ -307,7 +473,7 @@ SELECT v._key,
307
473
  FROM __versions AS v${current}
308
474
  WHERE v._n = 1`;
309
475
  return {
310
- materialized: "incremental",
476
+ materialization: "incremental",
311
477
  uniqueKey: "_key",
312
478
  incrementalStrategy: "delete+insert",
313
479
  sql: ({ changes, isIncremental, self, dialect }) => {
@@ -338,6 +504,10 @@ LEFT JOIN ${self} __current ON __current._key = __versions._key`
338
504
  * read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
339
505
  * history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
340
506
  * object's table in that destination, so SQL there can join it.
507
+ *
508
+ * `signals: ["created"]` (Postgres storage) makes those changes of the object signals of the
509
+ * environment's own Tilde connection (`tilde_ontology/<project>-<environment>`), which an
510
+ * agent's routine subscribes to like any connection's: see `signal`.
341
511
  */
342
512
  export function object(name, spec) {
343
513
  const def = { $kind: "object", $name: name, $spec: spec, $loc: callSite() };
@@ -345,6 +515,18 @@ export function object(name, spec) {
345
515
  def[property] = { kind: "prop", object: name, property, prop };
346
516
  return def;
347
517
  }
518
+ /**
519
+ * A signal the object declares. Tilde delivers each one at least once and, per object, in
520
+ * order; changes that reach the storage together are one signal (an object created and deleted
521
+ * at once is none), and an object that existed before it declared signals emits `created` for
522
+ * none of its rows. A routine's filters and templates name the data's keys (`{{ stage }}`).
523
+ */
524
+ export function signal(object, change) {
525
+ if (!object.$spec.signals?.includes(change)) {
526
+ throw new Error(`${object.$name} declares no \`${change}\` signal: add it to its signals`);
527
+ }
528
+ return { kind: "signal", object: object.$name, change, type: `tilde_ontology.${object.$spec.id}.${change}` };
529
+ }
348
530
  export function history(object) {
349
531
  return { kind: "history", object: object.$name, model: `${object.$spec.id}__changes` };
350
532
  }
@@ -447,7 +629,8 @@ export class Pipeline {
447
629
  }
448
630
  /** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
449
631
  untypedStreams(...names) {
450
- return new Pipeline(this.type, this.connection, [...this.streams, ...names], this.options, this.loc, this.name);
632
+ // A catalog kind has no fixed list (the source names its streams); a routed one does.
633
+ return new Pipeline(this.type, this.connection, this.streams.length ? [...this.streams, ...names] : [], this.options, this.loc, this.name);
451
634
  }
452
635
  }
453
636
  /** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
@@ -459,70 +642,52 @@ export class WebhookPipeline extends Pipeline {
459
642
  return new WebhookPipeline(this.type, this.connection, this.streams, options, this.loc, this.name);
460
643
  }
461
644
  }
462
- /** A declared source: a pipeline under its name, whose streams are sources. */
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 ?? [], {
645
+ const poll = (kind, connection, o, extra) => new Pipeline(kind, connection, [], {
479
646
  interval: o.interval,
480
647
  backfill: o.backfill,
481
648
  request_timeout: o.requestTimeout,
482
649
  ...extra,
483
650
  }, callSite());
484
- function providerWebhook(provider, o, extra = {}) {
651
+ const sync = (kind, connection, o, extra) => new Pipeline(kind, connection, [], {
652
+ webhook: o.webhook === false ? undefined : {},
653
+ interval: o.reconcile,
654
+ backfill: o.backfill,
655
+ request_timeout: o.requestTimeout,
656
+ ...extra,
657
+ }, callSite());
658
+ function providerWebhook(provider, o) {
485
659
  const headers = webhookHeaders[provider];
486
660
  const routes = Object.fromEntries(Object.entries(o.route).filter(([, v]) => v !== undefined));
487
- return new WebhookPipeline("webhook", o.connection, o.streams, {
661
+ const streams = [...new Set([...Object.values(routes), ...(o.fallback ? [o.fallback] : [])])];
662
+ return new WebhookPipeline("webhook", o.connection, streams, {
488
663
  key_header: headers.key,
489
664
  route: { header: headers.event, streams: routes, fallback: o.fallback },
490
- ...extra,
491
665
  }, callSite());
492
666
  }
493
- /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
667
+ /** Linear: a sync (webhooks, backfill, reconcile), polled GraphQL alone, or the raw webhooks. */
494
668
  export const linear = {
669
+ sync: (o) => sync("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
495
670
  poll: (o) => poll("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
496
671
  webhook: (o) => providerWebhook("linear", o),
497
672
  };
498
- /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
673
+ const sentryOptions = (o) => ({ organization: o.organization, projects: o.projects, base_url: o.baseUrl, query: o.query });
674
+ /** Sentry: a sync (integration webhooks, backfill, reconcile), polled issues alone, or the raw webhooks. */
499
675
  export const sentry = {
500
- poll: (o) => poll("sentry", o.connection, o, {
501
- organization: o.organization,
502
- projects: o.projects,
503
- base_url: o.baseUrl,
504
- query: o.query,
505
- full_sweep_interval: o.fullSweepInterval,
506
- }),
676
+ sync: (o) => sync("sentry", o.connection, o, sentryOptions(o)),
677
+ poll: (o) => poll("sentry", o.connection, o, { ...sentryOptions(o), full_sweep_interval: o.fullSweepInterval }),
507
678
  webhook: (o) => providerWebhook("sentry", o),
508
679
  };
509
- /** GitHub: the connection's webhooks (a GitHub App's). */
680
+ /** GitHub: a sync of the repositories, or the connection's raw webhooks. */
510
681
  export const github = {
511
682
  /**
512
- * One stream per entity (ducktail's `github` sync pipeline): the connection's webhooks for
513
- * the repositories, after a backfill of their recent pull requests, reviews, check runs and
514
- * releases on the first run (default 30 days). Each row's `_key` is the entity
515
- * (`{repository, number}` for pull requests, else `{id}`) and `_source_ts` its own time; the
516
- * payload is the webhook body. Never reconciles: GitHub's webhooks are complete.
683
+ * One stream per entity: the connection's webhooks for the repositories, after a backfill of
684
+ * their recent pull requests, reviews, check runs and releases on the first run (default 30
685
+ * days). Each row's `_key` is the entity (`{repository, number}` for pull requests, else
686
+ * `{id}`) and `_source_ts` its own time; the payload is the webhook body. Never reconciles:
687
+ * GitHub's webhooks are complete. Only the listed repositories are written: deliveries from
688
+ * any other repository the App is installed on are dropped.
517
689
  */
518
- sync: (o) => new Pipeline("github", o.connection, o.streams ?? [], {
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()),
690
+ sync: (o) => sync("github", o.connection, o, { repositories: o.repositories, base_url: o.baseUrl, page_size: o.pageSize }),
526
691
  /** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
527
692
  webhook: (o) => providerWebhook("github", o),
528
693
  };
@@ -580,20 +745,21 @@ export const kafka = {
580
745
  };
581
746
  /**
582
747
  * 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>`, or one URL routed by
584
- * a header.
748
+ * Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>` for each stream the
749
+ * source declares, or one URL routed by a header (its streams are then the routes').
585
750
  */
586
- export function webhook(o) {
587
- return new Pipeline("webhook", null, o.streams, { key_header: o.keyHeader, route: o.route }, callSite());
751
+ export function webhook(o = {}) {
752
+ const streams = o.route ? [...new Set([...Object.values(o.route.streams), ...(o.route.fallback ? [o.route.fallback] : [])])] : [];
753
+ return new Pipeline("webhook", null, streams, { key_header: o.keyHeader, route: o.route }, callSite());
588
754
  }
589
755
  /** Tilde itself. */
590
756
  export const tilde = {
591
757
  /**
592
758
  * 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 listed
594
- * are delivered. The source must be named `tilde`.
759
+ * messages...), pushed by Tilde to environments that turn them on: only the streams the
760
+ * source declares are delivered. The source must be named `tilde`.
595
761
  */
596
- events: (o) => new Pipeline("webhook", null, o.streams, { key_header: "x-tilde-key" }, callSite(), "tilde"),
762
+ events: () => new Pipeline("webhook", null, [], { key_header: "x-tilde-key" }, callSite(), "tilde"),
597
763
  };
598
764
  export function auth(name, resolve) {
599
765
  return { kind: "auth", name, resolve, loc: callSite() };
@@ -850,9 +1016,8 @@ export function ontology(spec) {
850
1016
  policies: [],
851
1017
  auths: [],
852
1018
  connections: {},
853
- streams: [],
1019
+ sources: [],
854
1020
  secrets: {},
855
- pipelines: [],
856
1021
  storage: "cell",
857
1022
  destinations: {},
858
1023
  ...spec,
@@ -946,7 +1111,7 @@ function evaluateModel(m, incremental, dialect, readFile, byName, sources) {
946
1111
  return { sql: body, pre: hooks(m.spec.preHooks), post: hooks(m.spec.postHooks), deps: [...deps], found };
947
1112
  }
948
1113
  /** A declared pipeline in the IR: ducktail's keys for it, secrets as `${NAME}` (listed). */
949
- function pipelineIR(p) {
1114
+ function pipelineIR(p, pipeline) {
950
1115
  const secrets = new Set();
951
1116
  const ref = (s) => {
952
1117
  secrets.add(s.name);
@@ -966,12 +1131,15 @@ function pipelineIR(p) {
966
1131
  return table(v);
967
1132
  };
968
1133
  const table = (o) => Object.fromEntries(Object.entries(o).filter(([, x]) => x !== undefined).map(([k, x]) => [k, value(x)]));
969
- const options = table(p.pipeline.options);
1134
+ const options = table(pipeline.options);
970
1135
  return {
971
1136
  name: p.name,
972
- kind: p.pipeline.type,
973
- connection: p.pipeline.connection ? authName(p.pipeline.connection) : null,
974
- streams: [...p.pipeline.streams],
1137
+ kind: pipeline.type,
1138
+ connection: pipeline.connection ? authName(pipeline.connection) : null,
1139
+ // A routed webhook, CDC or Kafka pipeline writes its own list (routes, tables, topics); a
1140
+ // polled or sync kind polls only the streams the source declares, and Tilde delivers only
1141
+ // those registry events.
1142
+ streams: pipeline.streams.length ? [...pipeline.streams] : p.raw.map((r) => r.stream),
975
1143
  secrets: [...secrets].sort(),
976
1144
  options,
977
1145
  loc: p.loc,
@@ -986,6 +1154,18 @@ export function toIR(o, root, readFile) {
986
1154
  ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === "loc" ? rel(x) : relDeep(x)]))
987
1155
  : v;
988
1156
  const dialect = o.storage === "postgres" ? "postgres" : "duckdb";
1157
+ const decls = o.sources.map((x) => x.$source);
1158
+ const seen = new Set();
1159
+ for (const d of decls) {
1160
+ // Ingress streams share one namespace (`ingress__<stream>`), pipelines theirs (`<source>__`).
1161
+ for (const id of d.from.kind === "ingress" ? d.raw.map((r) => `ingress stream \`${r.stream}\``) : [`source \`${d.name}\``]) {
1162
+ if (seen.has(id))
1163
+ throw new Error(`${d.loc ?? ""} ${id} is declared twice`);
1164
+ seen.add(id);
1165
+ }
1166
+ }
1167
+ const pipelines = decls.flatMap((d) => (d.from.kind === "pipeline" ? [[d, d.from]] : []));
1168
+ const streams = decls.flatMap((d) => (d.from.kind === "ingress" ? d.raw : []));
989
1169
  // Every model and source reachable from the definitions (and from model SQL).
990
1170
  const models = new Map();
991
1171
  const sources = new Map();
@@ -1004,10 +1184,14 @@ export function toIR(o, root, readFile) {
1004
1184
  const evaluated = new Map();
1005
1185
  while (queue.length) {
1006
1186
  const m = queue.shift();
1007
- if (models.has(m.id))
1187
+ const prior = models.get(m.id);
1188
+ if (prior === m)
1008
1189
  continue;
1190
+ // Two definitions of one name (two sources generating `<name>__<stream>`, or a model named so).
1191
+ if (prior)
1192
+ throw new Error(`${m.loc ?? ""} model \`${m.spec.name}\` is defined twice (also at ${prior.loc ?? "?"})`);
1009
1193
  models.set(m.id, m);
1010
- const isIncremental = m.spec.materialized === "incremental" || m.spec.materialized === "cell";
1194
+ const isIncremental = m.spec.materialization === "incremental" || m.spec.materialization === "cell";
1011
1195
  const own = m.spec.destination ? "clickhouse" : dialect;
1012
1196
  const full = evaluateModel(m, false, own, readFile, byName, sources);
1013
1197
  const incremental = isIncremental ? evaluateModel(m, true, own, readFile, byName, sources) : null;
@@ -1031,7 +1215,8 @@ export function toIR(o, root, readFile) {
1031
1215
  name: s.name,
1032
1216
  schema: s.schema ?? "main",
1033
1217
  description: s.description ?? null,
1034
- materialized: s.materialized,
1218
+ type: s.type,
1219
+ materialized: s.materialization,
1035
1220
  unique_key: s.uniqueKey === undefined ? [] : Array.isArray(s.uniqueKey) ? s.uniqueKey : [s.uniqueKey],
1036
1221
  incremental_strategy: s.incrementalStrategy ?? null,
1037
1222
  cluster_by: s.clusterBy ?? null,
@@ -1067,6 +1252,7 @@ export function toIR(o, root, readFile) {
1067
1252
  history: !!obj.$spec.history,
1068
1253
  history_at: obj.$spec.historyAt ?? null,
1069
1254
  ...(obj.$spec.replicas?.length ? { replicas: obj.$spec.replicas } : {}),
1255
+ ...(obj.$spec.signals?.length ? { signals: [...obj.$spec.signals] } : {}),
1070
1256
  properties: Object.entries(obj.$spec.properties).map(([name, p]) => ({
1071
1257
  name,
1072
1258
  id: p.spec.id ?? null,
@@ -1102,8 +1288,8 @@ export function toIR(o, root, readFile) {
1102
1288
  connections: Object.entries(o.connections).map(([name, c]) => ({ name, provider: c.provider, type: c.type ?? null, ...(c.optional ? { optional: true } : {}), loc: null })),
1103
1289
  // Only when declared, so the IR of a project without them is unchanged.
1104
1290
  ...(Object.keys(o.secrets).length ? { secrets: Object.values(o.secrets).map((x) => ({ name: x.name, loc: x.loc })) } : {}),
1105
- ...(o.pipelines.length ? { pipelines: o.pipelines.map(pipelineIR) } : {}),
1106
- streams: o.streams.map((st) => ({
1291
+ ...(pipelines.length ? { pipelines: pipelines.map(([d, p]) => pipelineIR(d, p)) } : {}),
1292
+ streams: streams.map((st) => ({
1107
1293
  name: st.stream,
1108
1294
  key: st.key,
1109
1295
  schema: z.toJSONSchema(st.schema, { unrepresentable: "any", io: "input" }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trytilde/ontology",
3
- "version": "4.0.0",
3
+ "version": "6.0.0",
4
4
  "description": "Tilde Cloud ontologies in TypeScript: the definitions and the client build tilde deploy runs",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",