@trytilde/ontology 3.1.1 → 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.js CHANGED
@@ -1,15 +1,16 @@
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`);
9
10
  * - **verbs**: `action` (txWrite) and `read` (txRead in a view, or `read` against the lake),
10
11
  * with zod input and output and declared `edits` and `reads` (enforced). Handlers call
11
12
  * third parties with plain `fetch` or SDKs; `ctx.deferredFetch` sends a request durably after
12
- * the action commits, with credentials from a `connection` slot (a third-party account the
13
+ * the action commits, with credentials from a declared connection (a third-party account the
13
14
  * environment binds, never visible to handlers) or an `auth` resolver over declared `secrets`;
14
15
  * - **realtime views**: `realtime` reads whose results are pushed to subscribers when they
15
16
  * change (per view instance in its cell, or across cells from the lake);
@@ -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,127 @@ 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, 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
- return new ModelDef(spec, callSite());
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. Spread it into a model:
231
- * `model({ name: "app_users", schema: "current", ...cdcCurrent(source("app", "users")) })`.
402
+ * the target) and carrying unchanged TOAST columns forward. Every `postgres.cdc` stream's
403
+ * current state.
232
404
  */
233
- export function cdcCurrent(of) {
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
- materialized: "incremental",
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
  }
@@ -395,23 +585,16 @@ export function transactionalView(name, spec) {
395
585
  }
396
586
  export const secret = () => ({ kind: "secret", default: null });
397
587
  export const setting = (defaultValue) => ({ kind: "setting", default: defaultValue ?? null });
398
- /** A connection slot; `provider` defaults to the slot's name. */
399
- export function connection(name, options = {}) {
400
- return { kind: "connection", name, provider: options.provider ?? name, type: options.type ?? null, loc: callSite() };
401
- }
402
- /** A connection slot of a Tilde connection provider (and optionally one of its types), named by
403
- * its key in `defineSlots`. */
404
- export function slot(provider, options = {}) {
405
- return { kind: "slot", provider, type: options.type ?? null, loc: callSite() };
406
- }
407
- /**
408
- * The connection slots the ontology needs, by name: `defineSlots({ linear: slot("linear"),
409
- * github: slot("github") })`. Pipelines and requests name them as `slots.linear` (a pipeline
410
- * helper takes only a slot of its provider), each environment binds them to its organization's
411
- * connections, and `ontology({ slots })` declares them.
412
- */
413
- export function defineSlots(slots) {
414
- return Object.fromEntries(Object.entries(slots).map(([name, s]) => [name, { kind: "connection", name, provider: s.provider, type: s.type, loc: s.loc }]));
588
+ /** Each declared connection's name: `ontology()` records them, at build time and in the Worker. */
589
+ const connectionNames = new WeakMap();
590
+ /** The name of a connection `ontology({ connections })` declares, or of an `auth` resolver. */
591
+ export function authName(auth) {
592
+ if ("kind" in auth && auth.kind === "auth")
593
+ return auth.name;
594
+ const name = connectionNames.get(auth);
595
+ if (!name)
596
+ throw new ActionError(`a connection (${auth.provider}) not declared in ontology({ connections }): declare it`);
597
+ return name;
415
598
  }
416
599
  /**
417
600
  * The raw secrets the ontology's pipelines need, by name: `defineSecrets({ PG_PASSWORD:
@@ -430,23 +613,23 @@ export function defineSecrets(secrets) {
430
613
  }
431
614
  /**
432
615
  * What feeds a source's raw streams (`lake.raw.<source>__<stream>`): one ducktail pipeline of
433
- * `type`, optionally through a connection slot, with its streams and ducktail's own config keys
616
+ * `type`, optionally through a connection, with its streams and ducktail's own config keys
434
617
  * (`options`, snake_case as ducktail's README writes them). Made by the helpers below; the build
435
618
  * compiles it into the version and the environment's rollout gives it to ducktail.
436
619
  */
437
620
  export class Pipeline {
438
621
  type;
439
- slot;
622
+ connection;
440
623
  streams;
441
624
  options;
442
625
  loc;
443
626
  name;
444
627
  kind = "pipeline";
445
- constructor(type, slot, streams, options, loc,
628
+ constructor(type, connection, streams, options, loc,
446
629
  /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
447
630
  name = null) {
448
631
  this.type = type;
449
- this.slot = slot;
632
+ this.connection = connection;
450
633
  this.streams = streams;
451
634
  this.options = options;
452
635
  this.loc = loc;
@@ -454,7 +637,8 @@ export class Pipeline {
454
637
  }
455
638
  /** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
456
639
  untypedStreams(...names) {
457
- return new Pipeline(this.type, this.slot, [...this.streams, ...names], this.options, this.loc, this.name);
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);
458
642
  }
459
643
  }
460
644
  /** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
@@ -463,71 +647,61 @@ export class WebhookPipeline extends Pipeline {
463
647
  untypedEvents(routes) {
464
648
  const route = this.options.route;
465
649
  const options = { ...this.options, route: { ...route, streams: { ...route.streams, ...routes } } };
466
- return new WebhookPipeline(this.type, this.slot, this.streams, options, this.loc, this.name);
467
- }
468
- }
469
- /** A declared source: a pipeline under its name, whose streams are sources. */
470
- export class PipelineSource {
471
- name;
472
- pipeline;
473
- loc;
474
- kind = "pipelineSource";
475
- constructor(name, pipeline, loc) {
476
- this.name = name;
477
- this.pipeline = pipeline;
478
- this.loc = loc;
479
- }
480
- /** One of the pipeline's streams: `lake.raw.<name>__<stream>`. */
481
- stream(stream) {
482
- return new SourceDef(this.name, stream, callSite());
650
+ return new WebhookPipeline(this.type, this.connection, this.streams, options, this.loc, this.name);
483
651
  }
484
652
  }
485
- const poll = (kind, slot, o, extra) => new Pipeline(kind, slot, o.streams ?? [], {
653
+ const poll = (kind, connection, o, extra) => new Pipeline(kind, connection, [], {
486
654
  interval: o.interval,
487
655
  backfill: o.backfill,
488
656
  request_timeout: o.requestTimeout,
489
657
  ...extra,
490
658
  }, callSite());
491
- function providerWebhook(provider, o, extra = {}) {
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) {
492
667
  const headers = webhookHeaders[provider];
493
668
  const routes = Object.fromEntries(Object.entries(o.route).filter(([, v]) => v !== undefined));
494
- return new WebhookPipeline("webhook", o.slot, o.streams, {
669
+ const streams = [...new Set([...Object.values(routes), ...(o.fallback ? [o.fallback] : [])])];
670
+ return new WebhookPipeline("webhook", o.connection, streams, {
495
671
  key_header: headers.key,
496
672
  route: { header: headers.event, streams: routes, fallback: o.fallback },
497
- ...extra,
498
673
  }, callSite());
499
674
  }
500
- /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
675
+ /** Linear: a sync (webhooks, backfill, reconcile), polled GraphQL alone, or the raw webhooks. */
501
676
  export const linear = {
502
- poll: (o) => poll("linear", o.slot, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
677
+ sync: (o) => sync("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
678
+ poll: (o) => poll("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
503
679
  webhook: (o) => providerWebhook("linear", o),
504
680
  };
505
- /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
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. */
506
683
  export const sentry = {
507
- poll: (o) => poll("sentry", o.slot, o, {
508
- organization: o.organization,
509
- projects: o.projects,
510
- base_url: o.baseUrl,
511
- query: o.query,
512
- full_sweep_interval: o.fullSweepInterval,
513
- }),
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 }),
514
686
  webhook: (o) => providerWebhook("sentry", o),
515
687
  };
516
- /** GitHub: the connection's webhooks (a GitHub App's), with an optional backfill of history. */
688
+ /** GitHub: a sync of the repositories, or the connection's raw webhooks. */
517
689
  export const github = {
518
- webhook: (o) => providerWebhook("github", o, {
519
- backfill: o.backfill && {
520
- provider: "github",
521
- repositories: o.backfill.repositories,
522
- start: o.backfill.start,
523
- base_url: o.backfill.baseUrl,
524
- page_size: o.backfill.pageSize,
525
- },
526
- }),
690
+ /**
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.
697
+ */
698
+ sync: (o) => sync("github", o.connection, o, { repositories: o.repositories, base_url: o.baseUrl, page_size: o.pageSize }),
699
+ /** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
700
+ webhook: (o) => providerWebhook("github", o),
527
701
  };
528
702
  /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
529
703
  export const cloudwatch = {
530
- poll: (o) => poll("cloudwatch", o.slot, o, {
704
+ poll: (o) => poll("cloudwatch", o.connection, o, {
531
705
  region: o.region,
532
706
  discovery_interval: o.discoveryInterval,
533
707
  period: o.period,
@@ -542,7 +716,7 @@ export const cloudwatch = {
542
716
  /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
543
717
  * `options` are ducktail's keys for it (README, "Polled sources"). */
544
718
  export function polled(kind, o) {
545
- return poll(kind, o.slot, o, o.options ?? {});
719
+ return poll(kind, o.connection, o, o.options ?? {});
546
720
  }
547
721
  /** ducktail's raw stream of a Postgres table or a Kafka topic. */
548
722
  const streamName = (name) => name.replace(/[^A-Za-z0-9]/g, "_").toLowerCase();
@@ -579,20 +753,21 @@ export const kafka = {
579
753
  };
580
754
  /**
581
755
  * A webhook pipeline of the solution's own, which Tilde delivers to (records written through
582
- * Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>`, or one URL routed by
583
- * 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').
584
758
  */
585
- export function webhook(o) {
586
- return new Pipeline("webhook", null, o.streams, { key_header: o.keyHeader, route: o.route }, callSite());
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());
587
762
  }
588
763
  /** Tilde itself. */
589
764
  export const tilde = {
590
765
  /**
591
766
  * The organization's registry events (threads, runs, tasks, invocations, inference usage,
592
- * messages...), pushed by Tilde to environments that turn them on: only the streams listed
593
- * 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`.
594
769
  */
595
- events: (o) => new Pipeline("webhook", null, o.streams, { key_header: "x-tilde-key" }, callSite(), "tilde"),
770
+ events: () => new Pipeline("webhook", null, [], { key_header: "x-tilde-key" }, callSite(), "tilde"),
596
771
  };
597
772
  export function auth(name, resolve) {
598
773
  return { kind: "auth", name, resolve, loc: callSite() };
@@ -627,6 +802,26 @@ export function prop(ref) {
627
802
  }
628
803
  /** Every `prop()` schema, to find tags the output's JSON Schema loses (transforms, ...). */
629
804
  const propSchemas = new WeakMap();
805
+ /** The most rows a list view's window holds. */
806
+ export const LIST_MAX = 1000;
807
+ /** What a list view's subscriber sends: its query, how many rows from the top it shows, and
808
+ * `resume` (the last update's), when widening a window it already has or reconnecting. */
809
+ export const listInput = (query) => z.object({ query, limit: z.number().int().min(1).max(LIST_MAX), resume: z.string().max(256).default("") });
810
+ const listUpdateShape = (row) => ({
811
+ /** Drop the rows held: this update holds the whole window (the first, unless resumed). */
812
+ reset: z.boolean(),
813
+ /** Rows that entered or changed, each at its index in the new window. */
814
+ upserts: z.array(z.object({ key: z.string(), index: z.number().int(), row })),
815
+ /** Keys of rows that left the window. */
816
+ removes: z.array(z.string()),
817
+ /** Rows exist past the window. */
818
+ more: z.boolean(),
819
+ /** Pass back as `resume` to widen this window without starting over. */
820
+ resume: z.string(),
821
+ });
822
+ /** A list view's update: what changed in the window since the last one (see `realtime`).
823
+ * `summary` is present on a reset and when it changed. */
824
+ export const listUpdate = (row, summary) => z.object({ ...listUpdateShape(row), ...(summary ? { summary: summary.optional() } : {}) });
630
825
  function refIr(r) {
631
826
  if ("kind" in r && r.kind === "prop")
632
827
  return { object: r.object, property: r.property };
@@ -731,6 +926,13 @@ spec) {
731
926
  export function realtime(name,
732
927
  // deno-lint-ignore no-explicit-any
733
928
  spec) {
929
+ if (spec.rows) {
930
+ const input = listInput(spec.input);
931
+ const output = listUpdate(spec.row, spec.summary?.output);
932
+ const ir = handlerIr(name, "read", null, { ...spec, input, output, watch: spec.watch ?? [] });
933
+ const list = { key: spec.key, row: spec.row, order: spec.order, rows: spec.rows, summary: spec.summary };
934
+ return { kind: "realtime", name, ir, input, output, list, handler: () => { throw new Error(`${name} is a list view`); } };
935
+ }
734
936
  const ir = handlerIr(name, spec.view ? "txRead" : "read", spec.view ?? null, { ...spec, watch: spec.watch ?? [] });
735
937
  return { kind: "realtime", name, ir, input: spec.input, output: spec.output, handler: spec.handler };
736
938
  }
@@ -789,6 +991,13 @@ export const openSpace = { kind: "cedar", text: 'Action::"OpenSpace"' };
789
991
  export function space(id) {
790
992
  return { kind: "cedar", text: `Space::${JSON.stringify(id)}` };
791
993
  }
994
+ /** Who may chat with a registry agent from a space (`<AgentChat>` in `@trytilde/spaces`), in which
995
+ * registry thread (`context.thread`): `permit(principal, action == ${chatWithAgent}, resource == ${agent(id)}) when { ... };`. */
996
+ export const chatWithAgent = { kind: "cedar", text: 'Action::"ChatWithAgent"' };
997
+ /** A Tilde registry agent by its id, a Cedar resource. */
998
+ export function agent(id) {
999
+ return { kind: "cedar", text: `Agent::${JSON.stringify(id)}` };
1000
+ }
792
1001
  /** A group: the token's subject is in each group its `groups` attribute lists (comma-separated). */
793
1002
  export function group(name) {
794
1003
  return { kind: "cedar", text: `Group::${JSON.stringify(name)}` };
@@ -799,6 +1008,8 @@ export function policy(id, text) {
799
1008
  }
800
1009
  /** The default export of `<root>/ontology.ts`. */
801
1010
  export function ontology(spec) {
1011
+ for (const [name, connection] of Object.entries(spec.connections ?? {}))
1012
+ connectionNames.set(connection, name);
802
1013
  return {
803
1014
  kind: "ontology",
804
1015
  models: [],
@@ -812,11 +1023,9 @@ export function ontology(spec) {
812
1023
  env: {},
813
1024
  policies: [],
814
1025
  auths: [],
815
- connections: [],
816
- streams: [],
817
- slots: {},
1026
+ connections: {},
1027
+ sources: [],
818
1028
  secrets: {},
819
- pipelines: [],
820
1029
  storage: "cell",
821
1030
  destinations: {},
822
1031
  ...spec,
@@ -910,7 +1119,7 @@ function evaluateModel(m, incremental, dialect, readFile, byName, sources) {
910
1119
  return { sql: body, pre: hooks(m.spec.preHooks), post: hooks(m.spec.postHooks), deps: [...deps], found };
911
1120
  }
912
1121
  /** A declared pipeline in the IR: ducktail's keys for it, secrets as `${NAME}` (listed). */
913
- function pipelineIR(p) {
1122
+ function pipelineIR(p, pipeline) {
914
1123
  const secrets = new Set();
915
1124
  const ref = (s) => {
916
1125
  secrets.add(s.name);
@@ -930,12 +1139,15 @@ function pipelineIR(p) {
930
1139
  return table(v);
931
1140
  };
932
1141
  const table = (o) => Object.fromEntries(Object.entries(o).filter(([, x]) => x !== undefined).map(([k, x]) => [k, value(x)]));
933
- const options = table(p.pipeline.options);
1142
+ const options = table(pipeline.options);
934
1143
  return {
935
1144
  name: p.name,
936
- kind: p.pipeline.type,
937
- slot: p.pipeline.slot?.name ?? null,
938
- streams: [...p.pipeline.streams],
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),
939
1151
  secrets: [...secrets].sort(),
940
1152
  options,
941
1153
  loc: p.loc,
@@ -949,7 +1161,19 @@ export function toIR(o, root, readFile) {
949
1161
  : v && typeof v === "object"
950
1162
  ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === "loc" ? rel(x) : relDeep(x)]))
951
1163
  : v;
952
- 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 : []));
953
1177
  // Every model and source reachable from the definitions (and from model SQL).
954
1178
  const models = new Map();
955
1179
  const sources = new Map();
@@ -968,13 +1192,22 @@ export function toIR(o, root, readFile) {
968
1192
  const evaluated = new Map();
969
1193
  while (queue.length) {
970
1194
  const m = queue.shift();
971
- if (models.has(m.id))
1195
+ const prior = models.get(m.id);
1196
+ if (prior === m)
972
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 ?? "?"})`);
973
1201
  models.set(m.id, m);
974
- const isIncremental = m.spec.materialized === "incremental" || m.spec.materialized === "cell";
1202
+ const isIncremental = m.spec.materialization === "incremental" || m.spec.materialization === "cell";
975
1203
  const own = m.spec.destination ? "clickhouse" : dialect;
976
1204
  const full = evaluateModel(m, false, own, readFile, byName, sources);
977
- const incremental = isIncremental ? evaluateModel(m, true, own, readFile, byName, sources) : null;
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
+ }
978
1211
  evaluated.set(m.id, { full, incremental });
979
1212
  for (const r of [...full.found, ...(incremental?.found ?? [])]) {
980
1213
  if (r.kind === "model")
@@ -995,7 +1228,8 @@ export function toIR(o, root, readFile) {
995
1228
  name: s.name,
996
1229
  schema: s.schema ?? "main",
997
1230
  description: s.description ?? null,
998
- materialized: s.materialized,
1231
+ type: s.type,
1232
+ materialized: s.materialization,
999
1233
  unique_key: s.uniqueKey === undefined ? [] : Array.isArray(s.uniqueKey) ? s.uniqueKey : [s.uniqueKey],
1000
1234
  incremental_strategy: s.incrementalStrategy ?? null,
1001
1235
  cluster_by: s.clusterBy ?? null,
@@ -1031,6 +1265,7 @@ export function toIR(o, root, readFile) {
1031
1265
  history: !!obj.$spec.history,
1032
1266
  history_at: obj.$spec.historyAt ?? null,
1033
1267
  ...(obj.$spec.replicas?.length ? { replicas: obj.$spec.replicas } : {}),
1268
+ ...(obj.$spec.signals?.length ? { signals: [...obj.$spec.signals] } : {}),
1034
1269
  properties: Object.entries(obj.$spec.properties).map(([name, p]) => ({
1035
1270
  name,
1036
1271
  id: p.spec.id ?? null,
@@ -1063,11 +1298,11 @@ export function toIR(o, root, readFile) {
1063
1298
  env: Object.entries(o.env).map(([name, e]) => ({ name, kind: e.kind, default: e.default })),
1064
1299
  policies: o.policies.map((p) => ({ id: p.id, text: p.text, loc: p.loc })),
1065
1300
  auths: o.auths.map((a) => ({ name: a.name, loc: a.loc })),
1066
- connections: [...o.connections, ...Object.values(o.slots)].map((c) => ({ name: c.name, provider: c.provider, type: c.type, loc: c.loc })),
1301
+ connections: Object.entries(o.connections).map(([name, c]) => ({ name, provider: c.provider, type: c.type ?? null, ...(c.optional ? { optional: true } : {}), loc: null })),
1067
1302
  // Only when declared, so the IR of a project without them is unchanged.
1068
1303
  ...(Object.keys(o.secrets).length ? { secrets: Object.values(o.secrets).map((x) => ({ name: x.name, loc: x.loc })) } : {}),
1069
- ...(o.pipelines.length ? { pipelines: o.pipelines.map(pipelineIR) } : {}),
1070
- streams: o.streams.map((st) => ({
1304
+ ...(pipelines.length ? { pipelines: pipelines.map(([d, p]) => pipelineIR(d, p)) } : {}),
1305
+ streams: streams.map((st) => ({
1071
1306
  name: st.stream,
1072
1307
  key: st.key,
1073
1308
  schema: z.toJSONSchema(st.schema, { unrepresentable: "any", io: "input" }),