@segmentstream/ontology 0.197.0 → 0.198.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 (60) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/dist/analyze.d.ts +2 -0
  3. package/dist/analyze.js +17 -0
  4. package/dist/bin/check.js +12 -0
  5. package/dist/bin/migrate.js +1 -1
  6. package/dist/connection.d.ts +109 -6
  7. package/dist/connection.js +132 -17
  8. package/dist/diagnostics.d.ts +3 -3
  9. package/dist/diagnostics.js +2 -0
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/manifest.d.ts +28 -0
  13. package/dist/manifest.js +6 -0
  14. package/dist/migrate/apply.d.ts +7 -1
  15. package/dist/migrate/apply.js +12 -3
  16. package/dist/migrate/model.d.ts +8 -0
  17. package/dist/migrate/plan.js +14 -1
  18. package/dist/owned-workflows.d.ts +10 -0
  19. package/dist/owned-workflows.js +16 -0
  20. package/dist/runtime/owner-departures.d.ts +35 -0
  21. package/dist/runtime/owner-departures.js +64 -0
  22. package/dist/runtime/pipeline.d.ts +15 -1
  23. package/dist/runtime/pipeline.js +67 -1
  24. package/dist/runtime/principals.d.ts +17 -2
  25. package/dist/runtime/principals.js +33 -2
  26. package/dist/runtime/service-binding.js +17 -3
  27. package/dist/runtime/workflow-starts.d.ts +108 -8
  28. package/dist/runtime/workflow-starts.js +276 -49
  29. package/dist/service/agent/attachments.js +27 -6
  30. package/dist/service/agent/authentication.d.ts +5 -0
  31. package/dist/service/agent/authentication.js +1 -1
  32. package/dist/service/agent/task-caller.d.ts +4 -2
  33. package/dist/service/agent/task-caller.js +4 -2
  34. package/dist/service/authentication.d.ts +7 -0
  35. package/dist/service/authentication.js +12 -0
  36. package/dist/service/chat/envelope.d.ts +7 -0
  37. package/dist/service/chat/envelope.js +15 -0
  38. package/dist/service/config.d.ts +6 -0
  39. package/dist/service/connections.d.ts +17 -2
  40. package/dist/service/connections.js +21 -1
  41. package/dist/service/errors.js +27 -1
  42. package/dist/service/member-files.js +6 -0
  43. package/dist/service/operations.d.ts +8 -0
  44. package/dist/service/operations.js +11 -4
  45. package/dist/service/owned-connections.d.ts +80 -0
  46. package/dist/service/owned-connections.js +488 -0
  47. package/dist/service/runtime-contract.d.ts +22 -0
  48. package/dist/service/schemas.d.ts +2 -0
  49. package/dist/service/service.js +23 -2
  50. package/dist/service/workflow-errors.d.ts +18 -1
  51. package/dist/service/workflow-errors.js +51 -2
  52. package/dist/service/workflows.d.ts +24 -0
  53. package/dist/service/workflows.js +360 -50
  54. package/dist/start-recovery-contract.d.ts +17 -1
  55. package/dist/start-recovery-contract.js +11 -1
  56. package/dist/start-recovery.js +4 -1
  57. package/dist/storage/tables.d.ts +15 -0
  58. package/dist/storage/tables.js +21 -0
  59. package/dist/workflow.d.ts +20 -2
  60. package/package.json +1 -1
@@ -152,6 +152,11 @@ export declare function resolveApiKeyCredential(ontology: Ontology, key: string)
152
152
  * an unknown user, a service and an inactive member.
153
153
  */
154
154
  export declare function resolveMemberById(ontology: Ontology, userId: string): Effect.Effect<Principal | undefined, never, SqlClient.SqlClient>;
155
+ /**
156
+ * Of the user ids given, those of active members whom no channel blocked: the users a run a cron
157
+ * starts may belong to. One query, whatever the number of ids.
158
+ */
159
+ export declare function activeMemberIds(sql: SqlClient.SqlClient, userIds: ReadonlyArray<string>): Effect.Effect<ReadonlySet<string>, SqlError>;
155
160
  export interface CreatedApiKey {
156
161
  readonly id: string;
157
162
  /** The key itself. It is not stored and cannot be shown again. */
@@ -268,8 +273,14 @@ export interface MemberSummary {
268
273
  /** Members created at sign-in without a usable email have none. */
269
274
  readonly email: string | undefined;
270
275
  readonly name: string;
276
+ /** Active and not blocked: whether the member may act now. */
271
277
  readonly active: boolean;
272
278
  readonly blocked?: true;
279
+ /**
280
+ * Present once the member is deactivated, whether or not they are also blocked. Blocking, which
281
+ * can be undone, folds into `active` too; this tells a deactivation apart from a block.
282
+ */
283
+ readonly deactivated?: true;
273
284
  readonly identities?: ReadonlyArray<{
274
285
  readonly provider: string;
275
286
  readonly subject: string;
@@ -288,8 +299,12 @@ export type MemberKey = {
288
299
  } | {
289
300
  readonly email: string;
290
301
  };
291
- /** Every member, signed in or not, by email. */
292
- export declare function listMembers(listing?: StoredRolesListing): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
302
+ /** Which members a listing reads: every one, or only those with the ids given. */
303
+ export interface MemberListing extends StoredRolesListing {
304
+ readonly ids?: ReadonlyArray<string>;
305
+ }
306
+ /** Every member, signed in or not, by email; or only the members with the ids given. */
307
+ export declare function listMembers(listing?: MemberListing): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
293
308
  /**
294
309
  * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
295
310
  * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
@@ -849,6 +849,26 @@ export function resolveMemberById(ontology, userId) {
849
849
  return yield* rolesOf(ontology, sql, decodeUser(row));
850
850
  }).pipe(Effect.orDie);
851
851
  }
852
+ /**
853
+ * Of the user ids given, those of active members whom no channel blocked: the users a run a cron
854
+ * starts may belong to. One query, whatever the number of ids.
855
+ */
856
+ export function activeMemberIds(sql, userIds) {
857
+ return Effect.gen(function* () {
858
+ if (userIds.length === 0) {
859
+ return new Set();
860
+ }
861
+ const blocks = yield* channelUsersAvailable(sql);
862
+ const rows = yield* sql.unsafe(`SELECT u."id"::text AS "id" FROM "${USER_TABLE}" AS u ` +
863
+ `WHERE u."id" IN (SELECT value::uuid FROM jsonb_array_elements_text($1::jsonb)) ` +
864
+ `AND u."kind" = 'member' AND u."active"` +
865
+ (blocks
866
+ ? ` AND NOT EXISTS (SELECT 1 FROM "${CHANNEL_USERS_TABLE}" AS c ` +
867
+ `WHERE c."user_id" = u."id" AND c."blocked_at" IS NOT NULL)`
868
+ : ""), [JSON.stringify(userIds)]);
869
+ return new Set(rows.map((row) => row.id));
870
+ });
871
+ }
852
872
  /**
853
873
  * Issues an API key for a user. With `delegation` the key acts only for the member each request
854
874
  * names; the column is written only then, so that keys without it can still be issued on a
@@ -1120,6 +1140,7 @@ function memberSummary(raw, hidden) {
1120
1140
  name: row.name,
1121
1141
  active: row.active && !row.blocked,
1122
1142
  ...(row.blocked ? { blocked: true } : {}),
1143
+ ...(row.active ? {} : { deactivated: true }),
1123
1144
  ...(row.identities?.length
1124
1145
  ? {
1125
1146
  identities: row.identities.map(({ provider, subject, username }) => ({
@@ -1192,12 +1213,22 @@ function memberColumns(sql) {
1192
1213
  });
1193
1214
  }
1194
1215
  const MEMBER_FROM = `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member'`;
1195
- /** Every member, signed in or not, by email. */
1216
+ /** Every member, signed in or not, by email; or only the members with the ids given. */
1196
1217
  export function listMembers(listing) {
1197
1218
  return Effect.gen(function* () {
1198
1219
  const sql = yield* SqlClient.SqlClient;
1220
+ // Only a UUID can be a user's id; anything else names no member.
1221
+ const ids = listing?.ids === undefined ? undefined : [...new Set(listing.ids)].filter(isRecordId);
1222
+ if (ids !== undefined && ids.length === 0) {
1223
+ return [];
1224
+ }
1199
1225
  const columns = yield* memberColumns(sql);
1200
- const rows = yield* sql.unsafe(`SELECT ${columns} ${MEMBER_FROM} ORDER BY "u"."email" NULLS LAST, "u"."id"`);
1226
+ const rows = ids === undefined
1227
+ ? yield* sql.unsafe(`SELECT ${columns} ${MEMBER_FROM} ORDER BY "u"."email" NULLS LAST, "u"."id"`)
1228
+ : // The ids are compared as UUIDs, so the primary key finds them.
1229
+ yield* sql.unsafe(`SELECT ${columns} ${MEMBER_FROM} ` +
1230
+ `AND "u"."id" IN (SELECT "value"::uuid FROM jsonb_array_elements_text($1::jsonb)) ` +
1231
+ `ORDER BY "u"."email" NULLS LAST, "u"."id"`, [JSON.stringify(ids)]);
1201
1232
  return rows.map((row) => memberSummary(row, hiddenOf(listing)));
1202
1233
  }).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
1203
1234
  }
@@ -22,14 +22,17 @@ import { sqlOAuthStore } from "./oauth.js";
22
22
  import { sqlFederationStore } from "./federation.js";
23
23
  import { runNewUserHook, withSignUpOnboarding } from "./new-user-hook.js";
24
24
  import { runAction } from "./pipeline.js";
25
- import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolveSignInState, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
25
+ import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolveSignInState, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, activeMemberIds, resolveMemberById, } from "./principals.js";
26
26
  import { postgresTls } from "./postgres-tls.js";
27
27
  import { makeOntologyRuntime } from "./sql-runtime.js";
28
28
  import { NEON_AUTH_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, } from "./user-identity-sql.js";
29
29
  import { ActionTransactions, makeActionTransactions } from "./action-transactions.js";
30
30
  import { SignInLinks } from "./sign-in-links.js";
31
- import { listStarts, sweepStarts, WorkflowStarter, WorkflowStartFailed, } from "./workflow-starts.js";
31
+ import { insertOwnedCronStarts, listStarts, startFiredStarts, sweepStarts, WorkflowStarter, WorkflowStartFailed, } from "./workflow-starts.js";
32
+ import { declaresOwnedWorkflow } from "../owned-workflows.js";
32
33
  import { reserveWorkflowStart, recordWorkflowSubmission } from "./workflow-admission.js";
34
+ /** A user id as the ontology stores it; any other value names no run owner. */
35
+ const RUN_OWNER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33
36
  /** Connections one service instance holds to the database's pooler. */
34
37
  const MAX_CONNECTIONS = 5;
35
38
  /**
@@ -188,9 +191,20 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
188
191
  forInvocation: (invocation) => blobs?.files(invocation) ?? unavailableFiles,
189
192
  }), Effect.catchTag("UnknownAction", (error) => Effect.die(error))),
190
193
  workflowStarts: {
191
- sweep: (input) => sweepStarts(sql, boundStarter, input).pipe(Effect.orDie),
194
+ sweep: (input) => sweepStarts(sql, boundStarter, {
195
+ ...input,
196
+ owners: declaresOwnedWorkflow(ontology.manifest),
197
+ }).pipe(Effect.orDie),
192
198
  list: (input) => listStarts(sql, input).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error))),
199
+ writeOwned: (starts) => insertOwnedCronStarts(sql, starts).pipe(Effect.orDie),
200
+ startFired: (input) => boundStarter === undefined
201
+ ? Effect.die(new Error("Starting a cron's runs needs the ontology service's starter."))
202
+ : startFiredStarts(sql, boundStarter, input).pipe(Effect.orDie),
193
203
  },
204
+ resolveRunOwner: (userId) => RUN_OWNER_ID.test(userId)
205
+ ? withSql(resolveMemberById(ontology, userId))
206
+ : Effect.succeed(undefined),
207
+ activeMembers: (userIds) => activeMemberIds(sql, userIds.filter((id) => RUN_OWNER_ID.test(id))).pipe(Effect.orDie),
194
208
  agentTasks: sqlAgentTaskStore(sql),
195
209
  get: (input) => runtime.get(input),
196
210
  find: (input) => runtime.query(input),
@@ -2,6 +2,7 @@ import { Context, Effect, Schema } from "effect";
2
2
  import type { SqlClient } from "effect/unstable/sql";
3
3
  import type { SqlError } from "effect/unstable/sql/SqlError";
4
4
  import type { AnyAction } from "../action.js";
5
+ import type { ConnectionCallKind, ConnectionOwner } from "../connection.js";
5
6
  import type { Ontology } from "../ontology.js";
6
7
  import type { Principal, StoredRecord } from "../runtime.js";
7
8
  import { type ActionEvent, type TriggerFunction, type WorkflowRunContext } from "../workflow.js";
@@ -16,6 +17,31 @@ export declare const SWEEP_DELAY_SECONDS = 30;
16
17
  export declare const SWEEP_BATCH = 100;
17
18
  /** How long started rows are kept, for the starts listing, before the sweep deletes them. */
18
19
  export declare const STARTED_RETENTION_DAYS = 30;
20
+ /**
21
+ * The record a run belongs to and its call kind, fixed when the run starts
22
+ * (docs/private-connections-spec.md, "The run owner"). In this release the record is a user.
23
+ */
24
+ export interface StartOwner {
25
+ readonly entity: "user";
26
+ readonly id: string;
27
+ readonly call: ConnectionCallKind;
28
+ }
29
+ /** The run attributes that record a run's owner, next to `startedBy.*`. */
30
+ export declare const OWNER_ATTRIBUTES: {
31
+ readonly entity: "owner.entity";
32
+ readonly id: "owner.id";
33
+ readonly call: "owner.call";
34
+ };
35
+ /** The attributes that record `owner` on a run; none without one. */
36
+ export declare function ownerAttributes(owner: StartOwner | undefined): Record<string, string>;
37
+ /**
38
+ * The owner a run's attributes record: `undefined` for a run without one, such as every run
39
+ * started before owners were recorded, and `"invalid"` for attributes that name an owner this SDK
40
+ * cannot read, which no step may run as anyone else for.
41
+ */
42
+ export declare function recordedOwner(attributes: Readonly<Record<string, string>> | undefined): StartOwner | "invalid" | undefined;
43
+ /** The owner whose credential a run's calls use, as the connection runtime takes it. */
44
+ export declare function connectionOwnerOf(owner: StartOwner): ConnectionOwner;
19
45
  /** A start an action trigger decided: one row of `_workflow_starts`. */
20
46
  export interface PendingStart {
21
47
  readonly reservation?: import("./workflow-admission.js").WorkflowReservation;
@@ -32,6 +58,8 @@ export interface PendingStart {
32
58
  readonly recordId: string | null;
33
59
  /** The workflow's input in its wire form, as the cron route receives it. */
34
60
  readonly input: unknown;
61
+ /** The run's owner, for a start of an owned workflow that has one. */
62
+ readonly owner?: StartOwner;
35
63
  }
36
64
  declare const WorkflowStartFailed_base: Schema.Class<WorkflowStartFailed, Schema.TaggedStruct<"WorkflowStartFailed", {
37
65
  readonly reason: Schema.Literals<readonly ["unknown_workflow", "not_compiled", "no_recovery_workflow", "invalid_input", "engine", "timeout"]>;
@@ -73,8 +101,13 @@ declare const WorkflowStarter_base: Context.ServiceClass<WorkflowStarter, "@segm
73
101
  */
74
102
  export declare class WorkflowStarter extends WorkflowStarter_base {
75
103
  }
76
- /** The `startedBy` of a run an action trigger started. */
104
+ /** The `startedBy` of a run an action trigger started, and its owner. */
77
105
  export declare function triggerContext(start: PendingStart): WorkflowRunContext;
106
+ /**
107
+ * A run's plaintext attributes: who started it, `startedBy.*`, and its owner, `owner.*`. Workflow
108
+ * SDK 5 attributes are flat strings; `$` keys belong to the SDK.
109
+ */
110
+ export declare function runAttributes(startedBy: WorkflowRunContext["startedBy"], owner?: StartOwner): Record<string, string>;
78
111
  /** An action trigger as the runtime evaluates it: the manifest's names and the authored functions. */
79
112
  export interface ResolvedActionTrigger {
80
113
  /** The workflow's wire name. */
@@ -89,14 +122,14 @@ export interface ResolvedActionTrigger {
89
122
  readonly input: TriggerFunction<ActionEvent, unknown, unknown> | undefined;
90
123
  /** The workflow's input codec, TypeScript names on the type side and wire names encoded. */
91
124
  readonly codec: Schema.Top;
125
+ /** Whether the workflow lists an owned connection, so that its runs have owners. */
126
+ readonly owned: boolean;
92
127
  }
93
128
  /**
94
129
  * The action triggers of the workflows that passed `check`, paired with their declarations. Built
95
130
  * once per ontology.
96
131
  */
97
132
  export declare function actionTriggers(ontology: Ontology): ReadonlyArray<ResolvedActionTrigger>;
98
- /** Whether the ontology declares any action trigger, so that `_workflow_starts` exists. */
99
- export declare function hasActionTriggers(ontology: Ontology): boolean;
100
133
  /**
101
134
  * The triggers that fire for an action of `entity` run by `principal`: on that action or on the
102
135
  * entity, except the triggers of the workflow whose user runs it, so that a workflow never starts
@@ -122,6 +155,12 @@ export interface TriggerEvaluation {
122
155
  /** When the action ran: the transaction's time, as history records it. */
123
156
  readonly at: string;
124
157
  readonly principal: Principal;
158
+ /**
159
+ * Who a run the action starts belongs to, when its workflow is owned: the owner of the workflow
160
+ * run the action ran in, or the member who called it (`actingConnectionOwner`). Undefined for
161
+ * anyone else, whose starts have no owner.
162
+ */
163
+ readonly owner?: ConnectionOwner | undefined;
125
164
  /** The decoded input. */
126
165
  readonly input: unknown;
127
166
  readonly result: unknown;
@@ -158,18 +197,79 @@ export type SweepResult = StartRecoveryOutcome;
158
197
  /**
159
198
  * The sweep: starts up to {@link SWEEP_BATCH} rows pending for more than
160
199
  * {@link SWEEP_DELAY_SECONDS}, oldest first, locked with `SKIP LOCKED` so that concurrent sweeps
161
- * take different rows, and records each outcome before the locks are released. Rows that failed
162
- * {@link MAX_START_ATTEMPTS} times are taken only with `retryAbandoned`. Started rows older than
163
- * {@link STARTED_RETENTION_DAYS} days are deleted. `waiting` counts the pending rows an automatic
164
- * sweep still takes, young ones included, created before `before` when it is given: the recovery
165
- * run's horizon.
200
+ * take different rows, and records each outcome before the locks are released. With a `deadline`
201
+ * it takes batch after batch until none is left or the deadline passes, and launches no start after
202
+ * it: the recovery run of an ontology with an owned workflow drains a cron's rows this way. Rows
203
+ * that failed {@link MAX_START_ATTEMPTS} times are taken only with `retryAbandoned`. Started rows
204
+ * older than {@link STARTED_RETENTION_DAYS} days are deleted. `waiting` counts the pending rows an
205
+ * automatic sweep still takes, young ones included, created before `before` when it is given: the
206
+ * recovery run's horizon.
166
207
  */
167
208
  export declare function sweepStarts(sql: SqlClient.SqlClient, starter: WorkflowStarter["Service"] | undefined, options: {
168
209
  readonly retryAbandoned: boolean;
169
210
  readonly requestId: string;
170
211
  /** ISO 8601; counts as waiting only the rows created before it. */
171
212
  readonly before?: string | undefined;
213
+ /** Epoch ms: sweep batches until this instant instead of one. */
214
+ readonly deadline?: number | undefined;
215
+ /**
216
+ * The ontology declares an owned workflow, so that the table has the owner columns and a row's
217
+ * owner is read. Every sweep passes on the arguments and attributes a row recorded, owner
218
+ * included, unchanged.
219
+ */
220
+ readonly owners?: boolean | undefined;
221
+ readonly clock?: () => number;
172
222
  }): Effect.Effect<SweepResult, SqlError>;
223
+ /**
224
+ * One run a cron decided for an owner of an owned workflow, ready to start: the scheduled minute it
225
+ * belongs to, its owner, and the workflow function's id, arguments and attributes as the run takes
226
+ * them (docs/private-connections-spec.md, "Starting the runs").
227
+ */
228
+ export interface OwnedCronStart {
229
+ /** `<workflow>.<trigger>`, in wire names. */
230
+ readonly trigger: string;
231
+ readonly workflow: string;
232
+ /** The cron's scheduled minute, ISO 8601. */
233
+ readonly fireKey: string;
234
+ readonly owner: StartOwner;
235
+ /** The trigger's input in its wire form. */
236
+ readonly input: unknown;
237
+ readonly workflowId: string;
238
+ readonly arguments: ReadonlyArray<unknown>;
239
+ readonly attributes: Readonly<Record<string, string>>;
240
+ }
241
+ /**
242
+ * The action id of an owner's cron start: derived from its trigger, minute and owner, so that a
243
+ * repeated delivery of the cron names the same row.
244
+ */
245
+ export declare function cronStartId(trigger: string, fireKey: string, ownerId: string): string;
246
+ /**
247
+ * Writes one pending row per owner, each in a statement of its own page, and answers how many were
248
+ * new. A row a repeated delivery of the cron already wrote is left as it is: the unique index on
249
+ * the trigger, the minute and the owner, and the derived action id, both name it.
250
+ */
251
+ export declare function insertOwnedCronStarts(sql: SqlClient.SqlClient, starts: ReadonlyArray<OwnedCronStart>): Effect.Effect<number, SqlError>;
252
+ /** What starting one cron fire's rows did, and how many of them are still pending. */
253
+ export interface FiredStarts {
254
+ readonly started: number;
255
+ readonly failed: number;
256
+ readonly pending: number;
257
+ }
258
+ /**
259
+ * Starts the pending rows one cron fire wrote, {@link SWEEP_BATCH} at a time, until none is left
260
+ * or `deadline` (epoch ms) passes: the cron's request starts what it can, and the recovery run it
261
+ * armed starts the rest. Rows are leased as the sweep leases them, so a sweep or a repeated
262
+ * delivery never starts the same row at the same time, and the starter's reservation keeps a
263
+ * retried start to one run. One owner's failed start is recorded on its row and stops no other; a
264
+ * row whose start failed once is left to the recovery run's growing delays.
265
+ */
266
+ export declare function startFiredStarts(sql: SqlClient.SqlClient, starter: WorkflowStarter["Service"], input: {
267
+ readonly trigger: string;
268
+ readonly fireKey: string;
269
+ readonly requestId: string;
270
+ readonly deadline: number;
271
+ readonly clock?: () => number;
272
+ }): Effect.Effect<FiredStarts, SqlError>;
173
273
  /** A row of the starts listing; the input stays in the database. */
174
274
  export interface WorkflowStartView {
175
275
  readonly trigger: string;