@segmentstream/ontology 0.208.0 → 0.210.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.
@@ -18,7 +18,7 @@ import { Files } from "../files.js";
18
18
  import { canonicalJson } from "../manifest.js";
19
19
  import { unavailableFiles } from "../storage/file-access.js";
20
20
  import { ActionRejected, PermissionDenied, } from "../errors.js";
21
- import { isActionTrigger, isCronTrigger, isWebhookTrigger, } from "../manifest.js";
21
+ import { isActionTrigger, isCronTrigger, isPlatformTrigger, isWebhookTrigger, } from "../manifest.js";
22
22
  import { webhookTokenMatches } from "../webhook-token.js";
23
23
  import { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_VERIFICATION_CHARS, presentedWebhookSignature, WEBHOOK_BASE_PATH, webhookPath, } from "../webhooks.js";
24
24
  import { generatedSignatureMatches, readWebhookBody, signatureCheck, signatureRefusals, utf8Text, } from "./webhooks.js";
@@ -29,7 +29,8 @@ import { writesOnlyThroughActions } from "../runtime/generated-actions.js";
29
29
  import { validate } from "../runtime/validation.js";
30
30
  import { connectionOwnerOf, recordedOwner, runAttributes, triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
31
31
  import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, RECOVERY_SWEEP_BUDGET_MS, } from "../start-recovery-contract.js";
32
- import { nextCronTime, } from "../workflow.js";
32
+ import { isWorkflowTrigger, nextCronTime, } from "../workflow.js";
33
+ import { decodePlatformEvent, evaluatePlatformTrigger, maySend, } from "../runtime/platform-triggers.js";
33
34
  import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
34
35
  import { callbackIdentityToken, StepIdentityToken } from "./workflow-callback.js";
35
36
  import { OwnerInactive } from "./workflow-errors.js";
@@ -578,15 +579,20 @@ function runStartedBy(attributes) {
578
579
  if (kind === "trigger" && trigger !== undefined) {
579
580
  const actionId = attributes?.["startedBy.actionId"];
580
581
  const recordId = attributes?.["startedBy.recordId"];
582
+ const event = attributes?.["startedBy.event"];
581
583
  const triggerKind = attributes?.["startedBy.triggerKind"];
582
584
  return {
583
585
  kind,
584
- ...(triggerKind === "cron" || triggerKind === "action" || triggerKind === "webhook"
586
+ ...(triggerKind === "cron" ||
587
+ triggerKind === "action" ||
588
+ triggerKind === "webhook" ||
589
+ triggerKind === "platform"
585
590
  ? { triggerKind }
586
591
  : {}),
587
592
  trigger,
588
593
  ...(actionId === undefined ? {} : { actionId }),
589
594
  ...(recordId === undefined ? {} : { recordId }),
595
+ ...(event === undefined ? {} : { event }),
590
596
  };
591
597
  }
592
598
  return undefined;
@@ -636,6 +642,8 @@ export function triggerPath(workflow, trigger) {
636
642
  }
637
643
  /** The route Vercel calls every five minutes when the manifest declares an action trigger. */
638
644
  export const SWEEP_PATH = `${WORKFLOW_BASE_PATH}/workflows/sweep`;
645
+ /** The route the platform delivers a platform event about this workspace to. */
646
+ export const PLATFORM_EVENTS_PATH = `${WORKFLOW_BASE_PATH}/workflows/events`;
639
647
  function workflowView(workflow, now) {
640
648
  return {
641
649
  ...workflow,
@@ -674,7 +682,16 @@ function workflowView(workflow, now) {
674
682
  connection: trigger.connection ?? null,
675
683
  },
676
684
  ]
677
- : []),
685
+ : isPlatformTrigger(trigger)
686
+ ? [
687
+ {
688
+ kind: trigger.kind,
689
+ name: trigger.name,
690
+ description: trigger.description,
691
+ events: trigger.events,
692
+ },
693
+ ]
694
+ : []),
678
695
  };
679
696
  }
680
697
  function isWorkloadToken(token) {
@@ -1268,9 +1285,15 @@ export function workflowsLayer(options) {
1268
1285
  if (allocated._tag === "Failure") {
1269
1286
  return refused(toServerResponse(unavailable(requestId)));
1270
1287
  }
1288
+ // A cron start is admitted once per minute and a platform start once per event, so a
1289
+ // repeated delivery reserves the same row and run.
1271
1290
  const identity = context.startedBy.kind === "trigger" && context.startedBy.triggerKind === "cron"
1272
1291
  ? `${workflow.manifest.name}:${context.startedBy.trigger}:${Math.floor(Date.now() / 60_000)}`
1273
- : `${requestId}:${canonicalJson(context.startedBy)}`;
1292
+ : context.startedBy.kind === "trigger" &&
1293
+ context.startedBy.triggerKind === "platform" &&
1294
+ context.startedBy.event !== undefined
1295
+ ? `${context.startedBy.trigger}:${context.startedBy.event}`
1296
+ : `${requestId}:${canonicalJson(context.startedBy)}`;
1274
1297
  const hash = createHash("sha256").update(identity).digest("hex");
1275
1298
  const actionId = [
1276
1299
  hash.slice(0, 8),
@@ -1803,6 +1826,97 @@ export function workflowsLayer(options) {
1803
1826
  });
1804
1827
  yield* router.add("*", `${WEBHOOK_BASE_PATH}/:name`, webhook);
1805
1828
  yield* router.add("*", `${WEBHOOK_BASE_PATH}/:name/:token`, webhook);
1829
+ // Platform triggers, with their workflows' functions: an event starts each trigger listing
1830
+ // its type once (docs/ontology-platform-triggers-spec.md).
1831
+ const platformTargets = workflows.flatMap((workflow) => workflow.manifest.triggers.filter(isPlatformTrigger).flatMap((trigger) => {
1832
+ const authored = workflow.declaration.triggers.find((candidate) => isWorkflowTrigger(candidate) &&
1833
+ candidate.kind === "platform" &&
1834
+ nameToWire(candidate.name) === trigger.name);
1835
+ return authored === undefined || authored.kind !== "platform"
1836
+ ? []
1837
+ : [
1838
+ {
1839
+ declared: workflow,
1840
+ target: {
1841
+ workflow: workflow.manifest.name,
1842
+ trigger: `${workflow.manifest.name}.${trigger.name}`,
1843
+ events: trigger.events,
1844
+ when: authored.when,
1845
+ input: authored.input,
1846
+ codec: workflow.input,
1847
+ },
1848
+ },
1849
+ ];
1850
+ }));
1851
+ // The platform delivers an event about this workspace: the platform token names this
1852
+ // workspace, which the verifier checks. Each trigger listing the event's type starts its
1853
+ // workflow once per event; a trigger whose own code fails is skipped and logged, and the
1854
+ // others still start. Nothing here opens the database until a trigger starts.
1855
+ yield* router.add("POST", PLATFORM_EVENTS_PATH, authorized((caller, request) => Effect.gen(function* () {
1856
+ const requestId = yield* RequestId;
1857
+ if (caller.kind !== "platform") {
1858
+ return toServerResponse(forbidden(requestId, "Only the platform delivers platform events."));
1859
+ }
1860
+ const text = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
1861
+ let body;
1862
+ try {
1863
+ body = JSON.parse(text);
1864
+ }
1865
+ catch {
1866
+ body = undefined;
1867
+ }
1868
+ const event = decodePlatformEvent(typeof body === "object" && body !== null && !Array.isArray(body)
1869
+ ? body.event
1870
+ : undefined);
1871
+ if (event === undefined) {
1872
+ return json({ error: "platform_event_invalid" }, 422);
1873
+ }
1874
+ if (!maySend("platform", event)) {
1875
+ return toServerResponse(forbidden(requestId, `This sender may not deliver ${event.type} events.`));
1876
+ }
1877
+ const runs = [];
1878
+ const skipped = [];
1879
+ for (const { declared, target } of platformTargets) {
1880
+ if (!target.events.includes(event.type)) {
1881
+ continue;
1882
+ }
1883
+ const outcome = yield* evaluatePlatformTrigger(target, event);
1884
+ if (!outcome.start) {
1885
+ if ("failed" in outcome) {
1886
+ skipped.push({ trigger: target.trigger, code: outcome.failed });
1887
+ yield* Effect.logError("ontology.workflow.platform_trigger_failed", outcome.cause).pipe(Effect.annotateLogs({
1888
+ requestId,
1889
+ trigger: target.trigger,
1890
+ event: event.id,
1891
+ type: event.type,
1892
+ code: outcome.failed,
1893
+ }));
1894
+ }
1895
+ continue;
1896
+ }
1897
+ const begun = yield* beginRun(declared, outcome.input, {
1898
+ startedBy: {
1899
+ kind: "trigger",
1900
+ triggerKind: "platform",
1901
+ trigger: target.trigger,
1902
+ event: event.id,
1903
+ },
1904
+ });
1905
+ // The sender retries a failed delivery; starts already admitted are not repeated.
1906
+ if (!begun.ok) {
1907
+ return begun.response;
1908
+ }
1909
+ runs.push({ trigger: target.trigger, runId: begun.runId });
1910
+ }
1911
+ yield* Effect.logInfo("ontology.workflow.platform_event").pipe(Effect.annotateLogs({
1912
+ requestId,
1913
+ event: event.id,
1914
+ type: event.type,
1915
+ started: runs.length,
1916
+ skipped: skipped.length,
1917
+ }));
1918
+ return json({ runs, skipped }, 202);
1919
+ })));
1806
1920
  // The sweep: Vercel's cron calls it with GET; an operator may POST, with
1807
1921
  // `?retryAbandoned=true` to retry the starts the automatic sweep gave up on.
1808
1922
  const sweep = (request) => Effect.gen(function* () {
@@ -2,6 +2,7 @@ import type { Schema } from "effect";
2
2
  import type { ActionInput, ActionResult, AnyAction } from "./action.js";
3
3
  import type { AnyConnectionHandle } from "./connection.js";
4
4
  import type { ActionHandle, AnyStoredEntity } from "./entity.js";
5
+ import type { PlatformEvent, PlatformEventOf, PlatformEventType } from "./platform-events.js";
5
6
  import type { Edit } from "./runtime/history.js";
6
7
  import type { Principal } from "./runtime.js";
7
8
  import type { WebhookDelivery, WebhookHmacFormat, WebhookSignatureScheme } from "./webhooks.js";
@@ -19,6 +20,11 @@ export declare const MAX_WORKFLOWS = 50;
19
20
  * record. A workflow may carry several, so it exceeds the workflows an ontology may declare.
20
21
  */
21
22
  export declare const MAX_ACTION_TRIGGERS = 100;
23
+ /**
24
+ * The most platform triggers, `platform(…)`, one ontology may declare across its workflows, as for
25
+ * webhooks: it bounds the runs one platform event can start.
26
+ */
27
+ export declare const MAX_PLATFORM_TRIGGERS = 20;
22
28
  /**
23
29
  * What a trigger listed in `defineOntology({ triggers })` runs instead of a workflow: one action,
24
30
  * in a durable run retried like a step, as the trigger's own workflow user holding `role`. The
@@ -235,10 +241,50 @@ export interface WebhookOptions extends TriggerRuns {
235
241
  */
236
242
  export declare function webhook<const Name extends string>(name: Name, options: WebhookOptions): WebhookTrigger<Name>;
237
243
  /**
238
- * What starts a workflow on its own. A discriminated union on `kind`: `cron`, `action` and
239
- * `webhook`; other kinds are additions.
244
+ * A platform trigger, `platform(name, { description, events, when, input })`: starts the workflow
245
+ * for each event of the listed catalog types that the platform records for this workspace, such
246
+ * as a production deployment that failed. `when` and `input` are code: the manifest records the
247
+ * kind, the name, the description and the event types, never the functions.
248
+ */
249
+ export interface PlatformTrigger<Name extends string = string, Input = unknown> {
250
+ readonly [WorkflowTriggerTypeId]: typeof WorkflowTriggerTypeId;
251
+ readonly kind: "platform";
252
+ /** A camelCase name, unique within its workflow: `deployFailed`. */
253
+ readonly name: Name;
254
+ /** Which events start the workflow and why, for people, agents and the catalog. */
255
+ readonly description: string;
256
+ /** The catalog types that start it, such as `"deployment.failed"`. */
257
+ readonly events: ReadonlyArray<string>;
258
+ /** Whether the run starts; omitted means always. */
259
+ readonly when: ((event: PlatformEvent) => boolean) | undefined;
260
+ /** The workflow's input, in TypeScript names; omitted means `{}`. */
261
+ readonly input: ((event: PlatformEvent) => Input) | undefined;
262
+ }
263
+ export interface PlatformOptions<T extends PlatformEventType, Input> {
264
+ /** Required, like every declaration: which events start the workflow and why. */
265
+ readonly description: string;
266
+ /** One or more catalog types. The functions receive the event of any of them. */
267
+ readonly events: readonly [T, ...ReadonlyArray<T>];
268
+ /** Whether the run starts, from the event; synchronous. Omitted means always. */
269
+ readonly when?: (event: PlatformEventOf<T>) => boolean;
270
+ /**
271
+ * The workflow's input, from the event; synchronous. Omitted means `{}`, which the workflow's
272
+ * input must accept.
273
+ */
274
+ readonly input?: (event: PlatformEventOf<T>) => Input;
275
+ }
276
+ /**
277
+ * Declares a platform trigger; list it in `workflow(name, { triggers })`. The workflow starts for
278
+ * each listed event the platform records for this workspace, and its runs act as the workflow's
279
+ * own user. A workflow that follows a deployment declares one; work that follows another workflow
280
+ * stays in that workflow, since workflow runs are not events.
281
+ */
282
+ export declare function platform<const Name extends string, const T extends PlatformEventType, Input = unknown>(name: Name, options: PlatformOptions<T, Input>): PlatformTrigger<Name, Input>;
283
+ /**
284
+ * What starts a workflow on its own. A discriminated union on `kind`: `cron`, `action`, `webhook`
285
+ * and `platform`; other kinds are additions.
240
286
  */
241
- export type WorkflowTrigger<Input = unknown> = CronTrigger<string, Input> | ActionTrigger<string, Input> | WebhookTrigger;
287
+ export type WorkflowTrigger<Input = unknown> = CronTrigger<string, Input> | ActionTrigger<string, Input> | WebhookTrigger | PlatformTrigger<string, Input>;
242
288
  export interface AfterOptions<Event, T, Input> extends TriggerRuns {
243
289
  /** Required, like every declaration: which actions start the workflow and why. */
244
290
  readonly description: string;
@@ -287,13 +333,15 @@ export interface WorkflowRunContext {
287
333
  readonly startedBy: {
288
334
  readonly kind: "trigger";
289
335
  /** The trigger's kind; runs started before it was recorded omit it. */
290
- readonly triggerKind?: "cron" | "action" | "webhook";
336
+ readonly triggerKind?: "cron" | "action" | "webhook" | "platform";
291
337
  /** `<workflow>.<trigger>`, in wire names. */
292
338
  readonly trigger: string;
293
339
  /** For an action trigger: the action whose commit started the run. */
294
340
  readonly actionId?: string;
295
341
  /** For an action trigger evaluated per edited record: that record. */
296
342
  readonly recordId?: string;
343
+ /** For a platform trigger: the id of the event that started the run. */
344
+ readonly event?: string;
297
345
  } | {
298
346
  readonly kind: "member";
299
347
  readonly userId: string;
@@ -332,8 +380,8 @@ export interface WorkflowOptions<S extends AnyInputSchema | undefined = undefine
332
380
  /** The `"use workflow"` function. It receives the decoded input. */
333
381
  readonly run: WorkflowFunction<InputOf<S>>;
334
382
  /**
335
- * What starts the workflow on its own: `cron(…)`, `after(…)` or `webhook(…)`. None means the
336
- * app, the CLI or another workflow.
383
+ * What starts the workflow on its own: `cron(…)`, `after(…)`, `webhook(…)` or `platform(…)`.
384
+ * None means the app, the CLI or another workflow.
337
385
  */
338
386
  readonly triggers?: ReadonlyArray<WorkflowTrigger>;
339
387
  /**
package/dist/workflow.js CHANGED
@@ -13,6 +13,11 @@ export const MAX_WORKFLOWS = 50;
13
13
  * record. A workflow may carry several, so it exceeds the workflows an ontology may declare.
14
14
  */
15
15
  export const MAX_ACTION_TRIGGERS = 100;
16
+ /**
17
+ * The most platform triggers, `platform(…)`, one ontology may declare across its workflows, as for
18
+ * webhooks: it bounds the runs one platform event can start.
19
+ */
20
+ export const MAX_PLATFORM_TRIGGERS = 20;
16
21
  /** Declares a cron trigger; list it in `workflow(name, { triggers })`. UTC, five fields. */
17
22
  export function cron(name, expression, options) {
18
23
  return {
@@ -50,6 +55,23 @@ export function webhook(name, options) {
50
55
  ...(options.input === undefined ? {} : { input: options.input }),
51
56
  };
52
57
  }
58
+ /**
59
+ * Declares a platform trigger; list it in `workflow(name, { triggers })`. The workflow starts for
60
+ * each listed event the platform records for this workspace, and its runs act as the workflow's
61
+ * own user. A workflow that follows a deployment declares one; work that follows another workflow
62
+ * stays in that workflow, since workflow runs are not events.
63
+ */
64
+ export function platform(name, options) {
65
+ return {
66
+ [WorkflowTriggerTypeId]: WorkflowTriggerTypeId,
67
+ kind: "platform",
68
+ name,
69
+ description: options?.description,
70
+ events: options?.events ?? [],
71
+ when: options?.when,
72
+ input: options?.input,
73
+ };
74
+ }
53
75
  export function after(name, target, options) {
54
76
  const names = triggerTarget(target);
55
77
  return {
@@ -12,10 +12,12 @@
12
12
  */
13
13
  export { p } from "./property.js";
14
14
  export type { AnyProperty, NumberOptions, Property, PropertyOptions, TextOptions, } from "./property.js";
15
- export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_WORKFLOWS, nextCronTime, webhook, workflow, } from "./workflow.js";
15
+ export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_PLATFORM_TRIGGERS, MAX_WORKFLOWS, nextCronTime, platform, webhook, workflow, } from "./workflow.js";
16
+ export { PLATFORM_EVENT_TYPES } from "./platform-events.js";
17
+ export type { PlatformEvent, PlatformEventOf, PlatformEventType } from "./platform-events.js";
16
18
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
17
19
  export type { WebhookDelivery, WebhookHmacFormat, WebhookSignatureScheme, WebhookSignedPart, } from "./webhooks.js";
18
- export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
20
+ export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, PlatformOptions, PlatformTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
19
21
  export { run, WORKFLOW_BASE_PATH, WorkflowStepRequired } from "./workflow-runtime.js";
20
22
  export { recoverWorkflowStarts, StartRecoveryWorkflowRequired } from "./start-recovery.js";
21
23
  export { runTriggerAction, TriggerRunUnsupported, TriggerRunWorkflowRequired, } from "./trigger-run.js";
package/dist/workflows.js CHANGED
@@ -11,7 +11,8 @@
11
11
  * with the workflow's.
12
12
  */
13
13
  export { p } from "./property.js";
14
- export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_WORKFLOWS, nextCronTime, webhook, workflow, } from "./workflow.js";
14
+ export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_PLATFORM_TRIGGERS, MAX_WORKFLOWS, nextCronTime, platform, webhook, workflow, } from "./workflow.js";
15
+ export { PLATFORM_EVENT_TYPES } from "./platform-events.js";
15
16
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
16
17
  export { run, WORKFLOW_BASE_PATH, WorkflowStepRequired } from "./workflow-runtime.js";
17
18
  export { recoverWorkflowStarts, StartRecoveryWorkflowRequired } from "./start-recovery.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.208.0",
3
+ "version": "0.210.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",