@segmentstream/ontology 0.121.0 → 0.123.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/CHANGELOG.md +52 -0
- package/README.md +9 -1
- package/dist/action.d.ts +11 -6
- package/dist/analyze.d.ts +3 -2
- package/dist/analyze.js +21 -10
- package/dist/app-feedback.js +6 -5
- package/dist/chat.d.ts +2 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/migrate/apply.js +5 -17
- package/dist/replication/baseline.d.ts +1 -2
- package/dist/replication/baseline.js +3 -2
- package/dist/replication/legacy-baseline.d.ts +1 -2
- package/dist/replication/legacy-baseline.js +3 -6
- package/dist/replication/migrate.d.ts +1 -10
- package/dist/replication/migrate.js +0 -37
- package/dist/replication/model.d.ts +6 -9
- package/dist/replication/model.js +13 -47
- package/dist/replication/schema.js +3 -0
- package/dist/replication/shadow.d.ts +7 -3
- package/dist/replication/shadow.js +9 -9
- package/dist/replication/store.d.ts +6 -2
- package/dist/replication/store.js +21 -46
- package/dist/runtime/agents.js +58 -0
- package/dist/runtime/service-binding.d.ts +5 -1
- package/dist/runtime/service-binding.js +14 -5
- package/dist/service/agent/chat-archive.d.ts +2 -1
- package/dist/service/agent/chat-archive.js +12 -8
- package/dist/service/agent/web-tokens.js +9 -1
- package/dist/service/chat/reads.js +5 -1
- package/dist/service/mcp/server.js +5 -5
- package/dist/service/mcp/tools.js +7 -3
- package/dist/service/runtime-contract.d.ts +7 -0
- package/dist/storage/memory.d.ts +100 -0
- package/dist/storage/memory.js +281 -0
- package/dist/storage/sessions.d.ts +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.123.0
|
|
4
|
+
|
|
5
|
+
`memoryFileStorage()` keeps an ontology's files in memory, so tests that run actions in process can
|
|
6
|
+
use `uploads.for` inputs, `Files.stage`, `Files.open` and downloads. Build the backend on it with
|
|
7
|
+
`backendLayer(ontology, files.blobStorage)`, or pass `blobStorage: files.blobStorage` with a
|
|
8
|
+
`storageMaintenanceKey` to `createOntologyService`; the database keeps the upload lifecycle, with
|
|
9
|
+
the deployment's permission checks, file policies and quota. `files.upload({ principal, entity,
|
|
10
|
+
property, action, recordId?, filename, contentType, bytes })` returns the ticket and action options
|
|
11
|
+
for the action's `uploads.for` input, `files.read({ principal, entity, id, property })` returns a
|
|
12
|
+
stored file's metadata and bytes, and `files.fetch` answers the store's transfer grants for tests
|
|
13
|
+
that upload over HTTP. See "Testing actions with files" in `docs/ontology.md`.
|
|
14
|
+
|
|
15
|
+
Ontology replication covers every stored business entity, with all of its fields and its
|
|
16
|
+
relationships between stored business entities. The migrator no longer reads or carries
|
|
17
|
+
per-workspace replication exclusions across deployments, and delivery no longer filters events by
|
|
18
|
+
them. A workspace source that still records exclusions from an earlier release is cleared through
|
|
19
|
+
the ordinary policy change: the scopes they withheld are copied into a private candidate and
|
|
20
|
+
published by the usual cutover while existing analytical queries keep working. Nothing changes in
|
|
21
|
+
workspace code.
|
|
22
|
+
|
|
23
|
+
Warehouse SQL does not apply the ontology's permissions: anyone who can query the workspace
|
|
24
|
+
warehouse reads every replicated stored entity.
|
|
25
|
+
|
|
26
|
+
`check` warns `workflow_role_scoped` only when a workflow's role scopes a permission with `me`,
|
|
27
|
+
directly or through a path such as `me.staffMember.division`, and names only those permissions.
|
|
28
|
+
A scope that never names `me`, such as `{ purpose: { in: ["signing", "signed"] } }`, matches the
|
|
29
|
+
same records for the workflow's service user as for anyone else, and no longer warns.
|
|
30
|
+
|
|
31
|
+
`action({ writes })` type-checks an entity named by a string, as `check` and the runtime already
|
|
32
|
+
accepted it: `writes: [self, "note"]` beside handles and thunks such as `() => Note`. A name is
|
|
33
|
+
the entity's authored or snake_case name (`"staffMember"` or `"staff_member"`); since an action
|
|
34
|
+
is declared before its ontology, the type accepts any string and `check` refuses one that names
|
|
35
|
+
no stored entity of the ontology. The manifest and the runtime resolve it to the same entity as
|
|
36
|
+
its handle, so a handler may write it and nothing else it does not declare.
|
|
37
|
+
|
|
38
|
+
## 0.122.1
|
|
39
|
+
|
|
40
|
+
The agent no longer tells a member the builders' responses to app feedback when a chat starts.
|
|
41
|
+
It tells them when they ask about their feedback, reading only their own items: a builder who can
|
|
42
|
+
read everyone's feedback was told other members' responses as their own.
|
|
43
|
+
|
|
44
|
+
## 0.122.0
|
|
45
|
+
|
|
46
|
+
The website's visitors' chats in the inbox: `inbox.roles` may list `guest` where the ontology
|
|
47
|
+
declares `guest`, and each visitor's chat with the agent, `guest:<id>` on the `web` channel, then
|
|
48
|
+
becomes an `agent_chat` record of kind `private` when the service admits a turn of theirs, without
|
|
49
|
+
members and with `lastMessageAt` kept current. A workflow's runs and its agent tasks read registered
|
|
50
|
+
chats as staff do: their role's `agent_chat:read`, within its scope, finds the records and reads a
|
|
51
|
+
chat's messages with `chat_history` by the record id, as the workflow's own user and never as a
|
|
52
|
+
participant. A daily report of the website's chats is then a workflow that finds the day's chats,
|
|
53
|
+
has an agent task summarize them and posts the summary.
|
|
54
|
+
|
|
3
55
|
## 0.121.0
|
|
4
56
|
|
|
5
57
|
The platform builds in no role. An ontology without `defineOntology({ member })` names every role
|
package/README.md
CHANGED
|
@@ -243,6 +243,13 @@ when omitted. Streams stay within the step; carry tickets and references between
|
|
|
243
243
|
See `docs/ontology.md#file-transfers`
|
|
244
244
|
for the API and recovery rules.
|
|
245
245
|
|
|
246
|
+
Tests that run actions with files in process build the backend on `memoryFileStorage()`:
|
|
247
|
+
`backendLayer(ontology, files.blobStorage)`, or `blobStorage: files.blobStorage` in
|
|
248
|
+
`createOntologyService`. The store keeps the bytes in memory while the database keeps the
|
|
249
|
+
upload lifecycle; `files.upload(...)` returns the ticket and options for an `uploads.for`
|
|
250
|
+
input, and `files.read(...)` reads a stored file back with the reader's permissions. See
|
|
251
|
+
`docs/ontology.md#testing-actions-with-files`.
|
|
252
|
+
|
|
246
253
|
Buffered `get`/`post`/`request` calls receive the provider's response through a streamed
|
|
247
254
|
proxy call and collect up to 64 MiB (`MAXIMUM_CONNECTION_RESPONSE_BYTES`); a larger response
|
|
248
255
|
fails with `invalid_response`. To process a response incrementally, or one larger than that,
|
|
@@ -1327,7 +1334,8 @@ There is no automatic reporter authority in workflows, pipeline workers or admis
|
|
|
1327
1334
|
|
|
1328
1335
|
The MCP server preserves submit in compact listing and adds feedback guidance only when submit
|
|
1329
1336
|
is visible. Attachment guidance appears only when attach is visible. The caller offers once per
|
|
1330
|
-
problem
|
|
1337
|
+
problem and asks approval for the title and summary. It reports and acknowledges a builders'
|
|
1338
|
+
answer only when the member asks, reading only the member's own items.
|
|
1331
1339
|
Builders use `segmentstream ontology feedback list`, `show` and `respond` as their app member.
|
|
1332
1340
|
|
|
1333
1341
|
## Toolsets
|
package/dist/action.d.ts
CHANGED
|
@@ -134,10 +134,10 @@ interface ActionOptions<Input extends Schema.Top> {
|
|
|
134
134
|
readonly retryOnDeadlock?: boolean;
|
|
135
135
|
/**
|
|
136
136
|
* The entities the handler writes, such as `[self, Note]`; a thunk (`() => Note`) names an entity
|
|
137
|
-
* a circular import has not defined yet
|
|
138
|
-
*
|
|
139
|
-
* is declared. `[]` declares an action
|
|
140
|
-
* entity, as before.
|
|
137
|
+
* a circular import has not defined yet, and a name (`"note"`) one the module does not import.
|
|
138
|
+
* The runtime refuses any other write of the handler, the manifest lists them, and agents read
|
|
139
|
+
* them in the action's description, so "what changes what" is declared. `[]` declares an action
|
|
140
|
+
* that writes nothing. Absent, the handler may write any entity, as before.
|
|
141
141
|
*/
|
|
142
142
|
readonly writes?: ReadonlyArray<ActionWriteTarget>;
|
|
143
143
|
/**
|
|
@@ -149,8 +149,13 @@ interface ActionOptions<Input extends Schema.Top> {
|
|
|
149
149
|
*/
|
|
150
150
|
readonly confirm?: (context: ConfirmContext<Input["Type"]>) => Effect.Effect<ActionConfirmation, ActionError, OntologyReads>;
|
|
151
151
|
}
|
|
152
|
-
/**
|
|
153
|
-
|
|
152
|
+
/**
|
|
153
|
+
* An entity an action writes: its handle, a thunk returning it for a circular import, or its name
|
|
154
|
+
* as `entity(name, …)` declares it, in its authored or snake_case spelling (`"staffMember"` or
|
|
155
|
+
* `"staff_member"`). A name is any string here, since an action is declared before the ontology
|
|
156
|
+
* that lists its entities; `check` refuses one that names no stored entity of the ontology.
|
|
157
|
+
*/
|
|
158
|
+
export type ActionWriteTarget = AnyEntity | (() => AnyEntity) | string;
|
|
154
159
|
export interface ActionConfig<Input extends Schema.Top, Result> extends ActionOptions<Input> {
|
|
155
160
|
/**
|
|
156
161
|
* Runs inside the action's transaction. It reads and writes through entity handles (`Lead.get`,
|
package/dist/analyze.d.ts
CHANGED
|
@@ -116,8 +116,9 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
|
|
|
116
116
|
/**
|
|
117
117
|
* Whose private chats with the agent the workspace's staff work: `{ roles: [client] }`. The agent
|
|
118
118
|
* registers each private chat of a person holding one of these roles as an `agent_chat` record of
|
|
119
|
-
* kind `private`, which `agent_chat:read` within its scope reads with its messages.
|
|
120
|
-
*
|
|
119
|
+
* kind `private`, which `agent_chat:read` within its scope reads with its messages. With `guest`
|
|
120
|
+
* declared, `"guest"` takes the chats of the website's visitors too. Absent, no private chat is
|
|
121
|
+
* registered and `agent_chat` holds group chats only.
|
|
121
122
|
*/
|
|
122
123
|
readonly inbox?: InboxOptions<Role | string>;
|
|
123
124
|
/**
|
package/dist/analyze.js
CHANGED
|
@@ -102,7 +102,7 @@ export function analyze(config, options = {}) {
|
|
|
102
102
|
...(linkEmail === undefined ? {} : { linkEmail }),
|
|
103
103
|
...(codeEmail === undefined ? {} : { codeEmail }),
|
|
104
104
|
};
|
|
105
|
-
const inbox = inboxOptions(config.inbox, declaredRoles, report);
|
|
105
|
+
const inbox = inboxOptions(config.inbox, declaredRoles, guest !== undefined, report);
|
|
106
106
|
const discovery = config.discovery;
|
|
107
107
|
if (discovery !== undefined &&
|
|
108
108
|
(!isPlainObject(discovery) ||
|
|
@@ -351,7 +351,9 @@ export function analyze(config, options = {}) {
|
|
|
351
351
|
* `inbox`: the wire names of the roles whose private chats join the inbox, each a declared role or
|
|
352
352
|
* `member`; `undefined` when absent or malformed.
|
|
353
353
|
*/
|
|
354
|
-
function inboxOptions(value, declaredRoles,
|
|
354
|
+
function inboxOptions(value, declaredRoles,
|
|
355
|
+
/** Whether the ontology declares `guest`, whose visitors' chats the inbox may take. */
|
|
356
|
+
guests, report) {
|
|
355
357
|
if (value === undefined) {
|
|
356
358
|
return undefined;
|
|
357
359
|
}
|
|
@@ -363,6 +365,9 @@ function inboxOptions(value, declaredRoles, report) {
|
|
|
363
365
|
return undefined;
|
|
364
366
|
}
|
|
365
367
|
const declared = new Set(declaredRoles.map((candidate) => candidate.name));
|
|
368
|
+
if (guests) {
|
|
369
|
+
declared.add(GUEST_ROLE);
|
|
370
|
+
}
|
|
366
371
|
const roles = [];
|
|
367
372
|
let valid = true;
|
|
368
373
|
value.roles.forEach((candidate, index) => {
|
|
@@ -372,7 +377,7 @@ function inboxOptions(value, declaredRoles, report) {
|
|
|
372
377
|
? nameToWire(candidate)
|
|
373
378
|
: undefined;
|
|
374
379
|
if (name === undefined || !declared.has(name)) {
|
|
375
|
-
report("invalid-inbox", `inbox.roles[${index}]`, "Use a role the ontology declares, or
|
|
380
|
+
report("invalid-inbox", `inbox.roles[${index}]`, "Use a role the ontology declares, member, or guest when it declares guest.");
|
|
376
381
|
valid = false;
|
|
377
382
|
}
|
|
378
383
|
else if (!roles.includes(name)) {
|
|
@@ -530,13 +535,19 @@ function resolveWorkflows(input) {
|
|
|
530
535
|
"no action, so the workflow can at most read; add the actions it runs to the role's " +
|
|
531
536
|
"permissions.", "warning");
|
|
532
537
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
538
|
+
// Only `me` depends on who runs: a scope on the records' own values, such as
|
|
539
|
+
// `{ purpose: { in: ["signing", "signed"] } }`, matches the same records for the workflow.
|
|
540
|
+
const scopedByMe = input.checkGrants && declared !== undefined && declared !== implicit
|
|
541
|
+
? [
|
|
542
|
+
...new Set((declared.scopes ?? [])
|
|
543
|
+
.filter((scope) => usesMe(scope.where))
|
|
544
|
+
.map((scope) => scope.permission)),
|
|
545
|
+
]
|
|
546
|
+
: [];
|
|
547
|
+
if (declared !== undefined && scopedByMe.length > 0) {
|
|
548
|
+
report("workflow_role_scoped", `${path}.role`, `${declared.name} scopes ${scopedByMe.join(", ")} with me, and bare me is the workflow ` +
|
|
549
|
+
"service user's ID. Paths from me require relationships of that service user; verify " +
|
|
550
|
+
"the scope matches the intended records.", "warning");
|
|
540
551
|
}
|
|
541
552
|
const schema = workflowInputSchema(candidate.input);
|
|
542
553
|
if (typeof schema !== "string" && "fields" in schema) {
|
package/dist/app-feedback.js
CHANGED
|
@@ -24,7 +24,7 @@ export const AppFeedback = entity("app_feedback", {
|
|
|
24
24
|
title: "title",
|
|
25
25
|
description: "Feedback a member sent the app's builders through an agent: something the app cannot do, a " +
|
|
26
26
|
"failure, or a change they want. Each member sees their own; the builders answer with a " +
|
|
27
|
-
"response,
|
|
27
|
+
"response, which the member's agent tells them when they ask.",
|
|
28
28
|
properties: {
|
|
29
29
|
title: p.text({ managed: true, maxLength: 200, description: "What the feedback is about." }),
|
|
30
30
|
body: p.text({
|
|
@@ -94,7 +94,7 @@ export const AppFeedback = entity("app_feedback", {
|
|
|
94
94
|
}),
|
|
95
95
|
respond: action({
|
|
96
96
|
description: "Answer a member's feedback as the app's builders: done or declined, with a response in the " +
|
|
97
|
-
"member's language that says what changed, or why not. Their agent
|
|
97
|
+
"member's language that says what changed, or why not. Their agent tells them when they ask.",
|
|
98
98
|
hints: { destructive: false },
|
|
99
99
|
input: Schema.Struct({
|
|
100
100
|
feedback: self.ref,
|
|
@@ -116,9 +116,10 @@ export const AppFeedback = entity("app_feedback", {
|
|
|
116
116
|
}),
|
|
117
117
|
}),
|
|
118
118
|
acknowledge: action({
|
|
119
|
-
description: "Record that the member has been told the builders' response to their feedback, passing
|
|
120
|
-
"responded_at of the response you reported.
|
|
121
|
-
"
|
|
119
|
+
description: "Record that the member has been told the builders' response to their own feedback, passing " +
|
|
120
|
+
"the responded_at of the response you reported. When they ask about their feedback, find " +
|
|
121
|
+
"their own items (reporter is their user id from me), tell them what was done, then call " +
|
|
122
|
+
"this. " +
|
|
122
123
|
"acknowledged is false when there is no such response, as when the builders answered again " +
|
|
123
124
|
"meanwhile: read the item again and report the newer response.",
|
|
124
125
|
hints: { destructive: false, idempotent: true },
|
package/dist/chat.d.ts
CHANGED
|
@@ -5,7 +5,8 @@ export interface ChatAttributionSettings {
|
|
|
5
5
|
}
|
|
6
6
|
/**
|
|
7
7
|
* `inbox` of `defineOntology`: the roles of the people whose private chats with the agent the
|
|
8
|
-
* workspace's staff work, as `agent_chat` records of kind `private
|
|
8
|
+
* workspace's staff work, as `agent_chat` records of kind `private`: declared roles, `member`, or
|
|
9
|
+
* `guest`, the website's visitors, where the ontology declares `guest`.
|
|
9
10
|
*/
|
|
10
11
|
export interface InboxOptions<R = unknown> {
|
|
11
12
|
readonly roles: ReadonlyArray<R>;
|
package/dist/index.d.ts
CHANGED
|
@@ -78,6 +78,8 @@ export type { ActionRequest, AfterCommit, CommittedAction, FoundAction, } from "
|
|
|
78
78
|
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, implicitRoleNamesOf, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, workflowRoles, } from "./runtime/principals.js";
|
|
79
79
|
export type { ApiKeyCredential, ApiKeyParts, ApiKeySummary, CreatedApiKey, IdentityClaims, MemberKey, MemberRolesChange, MemberStatus, MemberSummary, PrincipalsManifest, StoredRolesListing, } from "./runtime/principals.js";
|
|
80
80
|
export { backendLayer, postgresLayer, sqlServiceRuntime } from "./runtime/service-binding.js";
|
|
81
|
+
export { memoryFileStorage } from "./storage/memory.js";
|
|
82
|
+
export type { MemoryFileStorage, MemoryFileStorageOptions, MemoryFileUpload, StoredFile, UploadedFile, } from "./storage/memory.js";
|
|
81
83
|
export { makeOntologyRuntime } from "./runtime/sql-runtime.js";
|
|
82
84
|
export type { SqlOntologyRuntime, WriteScope } from "./runtime/sql-runtime.js";
|
|
83
85
|
export { BASE_PATH, deriveApi } from "./service/api.js";
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,8 @@ export { Change, Edit, EditKind, HistoryEntry } from "./runtime/history.js";
|
|
|
48
48
|
export { ActionOutcome, ActionValidation, findAction, PREPARE_TIMEOUT, resolveAction, runAction, } from "./runtime/pipeline.js";
|
|
49
49
|
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, implicitRoleNamesOf, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, workflowRoles, } from "./runtime/principals.js";
|
|
50
50
|
export { backendLayer, postgresLayer, sqlServiceRuntime } from "./runtime/service-binding.js";
|
|
51
|
+
// File storage in memory, for tests that run actions with files in process.
|
|
52
|
+
export { memoryFileStorage } from "./storage/memory.js";
|
|
51
53
|
export { makeOntologyRuntime } from "./runtime/sql-runtime.js";
|
|
52
54
|
// The HTTP service derived from the ontology.
|
|
53
55
|
export { BASE_PATH, deriveApi } from "./service/api.js";
|
package/dist/migrate/apply.js
CHANGED
|
@@ -13,12 +13,12 @@ import { prepareReplicationBaseline } from "../replication/baseline.js";
|
|
|
13
13
|
import { randomUUID } from "node:crypto";
|
|
14
14
|
import { recordWorkflowCatalog } from "../runtime/workflow-admission.js";
|
|
15
15
|
import { prepareReplicationEvolution, dropsServingReplicationStorage, refreshReplicationProjection, retainReplicationHistory, renameReplicationHistory, } from "../replication/evolution.js";
|
|
16
|
-
import { migratedReplicationFills
|
|
16
|
+
import { migratedReplicationFills } from "../replication/migrate.js";
|
|
17
17
|
import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
|
|
18
18
|
import { principalsOntology, reconcileWorkflowUsers } from "../runtime/principals.js";
|
|
19
19
|
import { FEDERATION_TABLES } from "../runtime/federation-tables.js";
|
|
20
20
|
import { syncUserIdentities, USER_IDENTITY_ENTITY_ID } from "../runtime/user-identities.js";
|
|
21
|
-
import { resolveReplicationSelection
|
|
21
|
+
import { resolveReplicationSelection } from "../replication/model.js";
|
|
22
22
|
import { ACTION_ATTRIBUTION_TABLE, AGENT_TABLES, API_KEYS_TABLE, CATALOG_TABLE, CHANNEL_USERS_TABLE, OAUTH_GRANTS_GUEST_CHECK, OAUTH_TABLES, USER_ROLES_TABLE, quoteIdentifier, quoteLiteral, historyTableName, } from "./storage.js";
|
|
23
23
|
const CATALOG = quoteIdentifier(CATALOG_TABLE);
|
|
24
24
|
const IDENTITY_SYNC = "Copy members' sign-in identities the legacy identity stores hold.";
|
|
@@ -310,19 +310,13 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
310
310
|
const previousManifest = yield* readCatalog({ sql });
|
|
311
311
|
let refresh;
|
|
312
312
|
let active;
|
|
313
|
-
let exclusions;
|
|
314
313
|
if (replication?.present) {
|
|
315
314
|
const [state] = yield* sql.unsafe("SELECT * FROM _ontology_replication WHERE id FOR UPDATE");
|
|
316
|
-
if (state && previousManifest) {
|
|
317
|
-
exclusions = yield* Effect.try({
|
|
318
|
-
try: () => migrationReplicationExclusions(previousManifest, plan.target, state.exclusions ?? []),
|
|
319
|
-
catch: (cause) => new CatalogInvalid({ message: "The replication exclusions are invalid.", cause }),
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
315
|
if (state?.enabled) {
|
|
316
|
+
// Every stored business entity replicates; there is no per-workspace export policy.
|
|
323
317
|
refresh = yield* Effect.try({
|
|
324
|
-
try: () => resolveReplicationSelection(plan.target
|
|
325
|
-
catch: (cause) => new CatalogInvalid({ message: "The replication
|
|
318
|
+
try: () => resolveReplicationSelection(plan.target),
|
|
319
|
+
catch: (cause) => new CatalogInvalid({ message: "The replication projection is invalid.", cause }),
|
|
326
320
|
});
|
|
327
321
|
const [target] = presence.targets
|
|
328
322
|
? yield* sql.unsafe("SELECT * FROM _ontology_replication_targets WHERE generation = $1::uuid", [state.active_generation])
|
|
@@ -406,11 +400,6 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
406
400
|
yield* sql.unsafe("UPDATE _ontology_replication SET version = $1 WHERE id", [
|
|
407
401
|
REPLICATION_SCHEMA_VERSION,
|
|
408
402
|
]);
|
|
409
|
-
if (exclusions !== undefined) {
|
|
410
|
-
yield* sql.unsafe("UPDATE _ontology_replication SET exclusions = $1::jsonb WHERE id", [
|
|
411
|
-
JSON.stringify(exclusions),
|
|
412
|
-
]);
|
|
413
|
-
}
|
|
414
403
|
yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_protocol_floor");
|
|
415
404
|
yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_schema_floor_v5");
|
|
416
405
|
yield* sql.unsafe("ALTER TABLE _ontology_replication VALIDATE CONSTRAINT _ontology_replication_schema_floor_v6");
|
|
@@ -448,7 +437,6 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
448
437
|
generation: randomUUID(),
|
|
449
438
|
manifest: plan.target,
|
|
450
439
|
selection: refresh,
|
|
451
|
-
exclusions: exclusions ?? [],
|
|
452
440
|
newSource: true,
|
|
453
441
|
}).pipe(Effect.mapError((cause) => new CatalogInvalid({
|
|
454
442
|
message: "Replication initialization could not be prepared.",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
3
|
import type { OntologyManifest } from "../manifest.js";
|
|
4
|
-
import { type ReplicationFills, type ReplicationSelection
|
|
4
|
+
import { type ReplicationFills, type ReplicationSelection } from "./model.js";
|
|
5
5
|
import type { ReplicationLineage } from "./lineage.js";
|
|
6
6
|
export interface ReplicationTarget {
|
|
7
7
|
readonly generation: string;
|
|
@@ -34,7 +34,6 @@ export declare class ReplicationBaselineFailed extends ReplicationBaselineFailed
|
|
|
34
34
|
interface BaselineInput {
|
|
35
35
|
readonly generation: string;
|
|
36
36
|
readonly manifest: OntologyManifest;
|
|
37
|
-
readonly exclusions?: ReadonlyArray<ReplicationExclusion>;
|
|
38
37
|
readonly selection: ReadonlyArray<ReplicationSelection>;
|
|
39
38
|
readonly newSource?: boolean;
|
|
40
39
|
}
|
|
@@ -61,11 +61,12 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
|
|
|
61
61
|
yield* sql.unsafe(`INSERT INTO _ontology_replication_targets
|
|
62
62
|
(generation, source_id, from_revision, manifest, selection, protocol, baseline_complete)
|
|
63
63
|
VALUES ($1::uuid, $2::uuid, 0, $3::jsonb, $4::jsonb, 4, false)`, [input.generation, source, JSON.stringify(input.manifest), JSON.stringify(input.selection)]);
|
|
64
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
65
|
+
// An older backend release still reads the retired exclusions; a new baseline has none.
|
|
64
66
|
yield* sql.unsafe(`UPDATE _ontology_replication SET source_id = $1::uuid, selection = $2::jsonb,
|
|
65
|
-
enabled = true, exclusions =
|
|
67
|
+
enabled = true, exclusions = '[]'::jsonb, active_generation = $3::uuid WHERE id`, [
|
|
66
68
|
source,
|
|
67
69
|
JSON.stringify(Object.fromEntries(input.selection.map((s) => [s.entityId, s]))),
|
|
68
|
-
JSON.stringify(input.exclusions ?? []),
|
|
69
70
|
input.generation,
|
|
70
71
|
]);
|
|
71
72
|
if (state.version >= 5) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
3
|
import type { OntologyManifest } from "../manifest.js";
|
|
4
|
-
import { type ReplicationSelection
|
|
4
|
+
import { type ReplicationSelection } from "./model.js";
|
|
5
5
|
export interface ReplicationTarget {
|
|
6
6
|
readonly generation: string;
|
|
7
7
|
readonly source_id: string;
|
|
@@ -20,7 +20,6 @@ export declare class ReplicationBaselineFailed extends ReplicationBaselineFailed
|
|
|
20
20
|
export declare const createReplicationBaseline: (sql: SqlClient.SqlClient, input: {
|
|
21
21
|
readonly generation: string;
|
|
22
22
|
readonly manifest: OntologyManifest;
|
|
23
|
-
readonly exclusions?: ReadonlyArray<ReplicationExclusion>;
|
|
24
23
|
readonly selection: ReadonlyArray<ReplicationSelection>;
|
|
25
24
|
readonly newSource?: boolean;
|
|
26
25
|
}) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | import("./baseline.js").ReplicationBaselineFailed | ReplicationBaselineFailed, never>;
|
|
@@ -47,13 +47,10 @@ export const createReplicationBaseline = (sql, input) => sql.withTransaction(Eff
|
|
|
47
47
|
}
|
|
48
48
|
const source = input.newSource ? randomUUID() : state.source_id;
|
|
49
49
|
const selection = Object.fromEntries(input.selection.map((s) => [s.entityId, s]));
|
|
50
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
51
|
+
// An older backend release still reads the retired exclusions; a new baseline has none.
|
|
50
52
|
yield* sql.unsafe(`UPDATE _ontology_replication SET source_id = $1::uuid, selection = $2::jsonb, enabled = true,
|
|
51
|
-
exclusions =
|
|
52
|
-
source,
|
|
53
|
-
JSON.stringify(selection),
|
|
54
|
-
JSON.stringify(input.exclusions ?? []),
|
|
55
|
-
input.generation,
|
|
56
|
-
]);
|
|
53
|
+
exclusions = '[]'::jsonb, active_generation = $3::uuid WHERE id`, [source, JSON.stringify(selection), input.generation]);
|
|
57
54
|
const target = {
|
|
58
55
|
generation: input.generation,
|
|
59
56
|
source_id: source,
|
|
@@ -3,16 +3,7 @@ import type { SqlClient } from "effect/unstable/sql";
|
|
|
3
3
|
import type { OntologyManifest } from "../manifest.js";
|
|
4
4
|
import type { RetainedStorage } from "../migrate/model.js";
|
|
5
5
|
import type { ReplicationTarget } from "./baseline.js";
|
|
6
|
-
import { type
|
|
7
|
-
/** Persist exclusions across temporary removals, and follow a property's logical rename. */
|
|
8
|
-
export declare function migrationReplicationExclusions(current: OntologyManifest, target: OntologyManifest, exclusions: ReadonlyArray<ReplicationExclusion>): ReadonlyArray<ReplicationExclusion>;
|
|
9
|
-
/** Only current declarations participate; retained exclusions still protect a later restoration. */
|
|
10
|
-
export declare function effectiveReplicationExclusions(manifest: OntologyManifest, exclusions: readonly ReplicationExclusion[]): {
|
|
11
|
-
relationships?: ReadonlyArray<string>;
|
|
12
|
-
fields?: ReadonlyArray<string>;
|
|
13
|
-
entityId: string;
|
|
14
|
-
disabled?: boolean;
|
|
15
|
-
}[];
|
|
6
|
+
import { type ReplicationSelection } from "./model.js";
|
|
16
7
|
/**
|
|
17
8
|
* Fills of the migrated target, read inside the migration transaction after its steps. PostgreSQL gives
|
|
18
9
|
* a field added to an existing entity one value on every row, so any row shows it as capture would
|
|
@@ -3,43 +3,6 @@ import { quoteIdentifier as qi, tableName } from "../migrate/storage.js";
|
|
|
3
3
|
import { renamedReplicationField } from "./lineage.js";
|
|
4
4
|
import { queryFields } from "../query.js";
|
|
5
5
|
import { snapshotExpression } from "./schema.js";
|
|
6
|
-
/** Persist exclusions across temporary removals, and follow a property's logical rename. */
|
|
7
|
-
export function migrationReplicationExclusions(current, target, exclusions) {
|
|
8
|
-
return exclusions.map((item) => ({
|
|
9
|
-
...item,
|
|
10
|
-
...(item.fields === undefined
|
|
11
|
-
? {}
|
|
12
|
-
: {
|
|
13
|
-
fields: item.fields.map((field) => {
|
|
14
|
-
const entity = target.entities.find((entity) => entity.id === item.entityId);
|
|
15
|
-
const renamed = entity?.properties.find((property) => renamedReplicationField(current, target, item.entityId, property.name) === field);
|
|
16
|
-
return renamed?.name ?? field;
|
|
17
|
-
}),
|
|
18
|
-
}),
|
|
19
|
-
}));
|
|
20
|
-
}
|
|
21
|
-
/** Only current declarations participate; retained exclusions still protect a later restoration. */
|
|
22
|
-
export function effectiveReplicationExclusions(manifest, exclusions) {
|
|
23
|
-
return exclusions.flatMap((item) => {
|
|
24
|
-
const entity = manifest.entities.find((entity) => entity.id === item.entityId && !entity.builtIn && !entity.source);
|
|
25
|
-
if (!entity) {
|
|
26
|
-
return [];
|
|
27
|
-
}
|
|
28
|
-
const fields = new Set(queryFields(entity).map((field) => field.name));
|
|
29
|
-
const relationships = new Set(entity.relationships.map((relationship) => relationship.name));
|
|
30
|
-
return [
|
|
31
|
-
{
|
|
32
|
-
...item,
|
|
33
|
-
...(item.fields === undefined
|
|
34
|
-
? {}
|
|
35
|
-
: { fields: item.fields.filter((field) => fields.has(field)) }),
|
|
36
|
-
...(item.relationships === undefined
|
|
37
|
-
? {}
|
|
38
|
-
: { relationships: item.relationships.filter((name) => relationships.has(name)) }),
|
|
39
|
-
},
|
|
40
|
-
];
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
6
|
/**
|
|
44
7
|
* Fills of the migrated target, read inside the migration transaction after its steps. PostgreSQL gives
|
|
45
8
|
* a field added to an existing entity one value on every row, so any row shows it as capture would
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { OntologyManifest } from "../manifest.js";
|
|
2
2
|
/** The current projection of a continuous replication stream. `id` is always included. */
|
|
3
3
|
export interface ReplicationSelection {
|
|
4
4
|
readonly entityId: string;
|
|
@@ -10,14 +10,11 @@ export interface ReplicationSelection {
|
|
|
10
10
|
* captured before the field existed lack its key, while every record they describe holds this value.
|
|
11
11
|
*/
|
|
12
12
|
export type ReplicationFills = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
readonly relationships?: ReadonlyArray<string>;
|
|
19
|
-
}
|
|
20
|
-
export declare function resolveReplicationSelection(manifest: OntologyManifest, exclusions?: ReadonlyArray<ReplicationExclusion>): ReadonlyArray<ReplicationSelection>;
|
|
13
|
+
/**
|
|
14
|
+
* Every stored business entity replicates with all of its fields and its relationships between
|
|
15
|
+
* stored business entities. Built-in and warehouse-backed entities are never exported.
|
|
16
|
+
*/
|
|
17
|
+
export declare function resolveReplicationSelection(manifest: OntologyManifest): ReadonlyArray<ReplicationSelection>;
|
|
21
18
|
export interface ReplicationEvent {
|
|
22
19
|
readonly event_id: string;
|
|
23
20
|
readonly source_id: string;
|
|
@@ -1,53 +1,19 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { isValueMatched } from "../manifest.js";
|
|
3
2
|
import { queryFields } from "../query.js";
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Every stored business entity replicates with all of its fields and its relationships between
|
|
5
|
+
* stored business entities. Built-in and warehouse-backed entities are never exported.
|
|
6
|
+
*/
|
|
7
|
+
export function resolveReplicationSelection(manifest) {
|
|
5
8
|
const entities = manifest.entities.filter((entity) => !entity.builtIn && !entity.source);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const fields = new Set(queryFields(entity).map((field) => field.name));
|
|
15
|
-
const relationships = new Set(entity.relationships.map((relationship) => relationship.name));
|
|
16
|
-
if (item.fields?.some((field) => field === "id" || !fields.has(field))) {
|
|
17
|
-
throw new Error(`Unknown or required replication field on ${entity.name}.`);
|
|
18
|
-
}
|
|
19
|
-
if (item.relationships?.some((relationship) => !relationships.has(relationship))) {
|
|
20
|
-
throw new Error(`Unknown replication relationship on ${entity.name}.`);
|
|
21
|
-
}
|
|
22
|
-
// A value-matched relationship has no `<name>_id`: its reference is the property `on` names.
|
|
23
|
-
const matched = entity.relationships.find((relationship) => item.relationships?.includes(relationship.name) && isValueMatched(relationship));
|
|
24
|
-
if (matched !== undefined) {
|
|
25
|
-
throw new Error(`${entity.name}.${matched.name} is matched by value; exclude its property ` +
|
|
26
|
-
`${matched.on?.property ?? ""} instead.`);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
const included = entities.filter((entity) => !exclusions.some((item) => item.entityId === entity.id && item.disabled));
|
|
30
|
-
const selection = included.map((entity) => {
|
|
31
|
-
const excluded = exclusions.find((item) => item.entityId === entity.id);
|
|
32
|
-
const keyed = entity.relationships.filter((relationship) => relationship.cardinality === "one" && !isValueMatched(relationship));
|
|
33
|
-
const excludedFields = new Set([
|
|
34
|
-
...(excluded?.fields ?? []),
|
|
35
|
-
...keyed
|
|
36
|
-
.filter((relationship) => excluded?.relationships?.includes(relationship.name))
|
|
37
|
-
.map((relationship) => `${relationship.name}_id`),
|
|
38
|
-
]);
|
|
39
|
-
return {
|
|
40
|
-
entityId: entity.id,
|
|
41
|
-
fields: queryFields(entity)
|
|
42
|
-
.filter((field) => !excludedFields.has(field.name))
|
|
43
|
-
.map((field) => field.name),
|
|
44
|
-
relationships: entity.relationships
|
|
45
|
-
.filter((relationship) => relationship.cardinality === "many" &&
|
|
46
|
-
!excluded?.relationships?.includes(relationship.name) &&
|
|
47
|
-
included.some((target) => target.name === relationship.to))
|
|
48
|
-
.map((relationship) => relationship.name),
|
|
49
|
-
};
|
|
50
|
-
});
|
|
9
|
+
const selection = entities.map((entity) => ({
|
|
10
|
+
entityId: entity.id,
|
|
11
|
+
fields: queryFields(entity).map((field) => field.name),
|
|
12
|
+
relationships: entity.relationships
|
|
13
|
+
.filter((relationship) => relationship.cardinality === "many" &&
|
|
14
|
+
entities.some((target) => target.name === relationship.to))
|
|
15
|
+
.map((relationship) => relationship.name),
|
|
16
|
+
}));
|
|
51
17
|
validateReplicationSelection(manifest, selection);
|
|
52
18
|
return selection;
|
|
53
19
|
}
|
|
@@ -22,6 +22,9 @@ export const REPLICATION_DDL = [
|
|
|
22
22
|
selection jsonb NOT NULL DEFAULT '{}'::jsonb, enabled boolean NOT NULL DEFAULT false
|
|
23
23
|
)`,
|
|
24
24
|
`INSERT INTO _ontology_replication (id, version) VALUES (true, ${REPLICATION_SCHEMA_VERSION}) ON CONFLICT DO NOTHING`,
|
|
25
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
26
|
+
// Retired exclusions: no current reader applies them, but an older backend release still reads
|
|
27
|
+
// the column. The SDK only clears it.
|
|
25
28
|
`ALTER TABLE _ontology_replication ADD COLUMN IF NOT EXISTS exclusions jsonb NOT NULL DEFAULT '[]'::jsonb`,
|
|
26
29
|
`ALTER TABLE _ontology_replication ADD COLUMN IF NOT EXISTS active_generation uuid`,
|
|
27
30
|
`CREATE TABLE IF NOT EXISTS _ontology_replication_targets (
|
|
@@ -116,9 +116,13 @@ export declare const shadowPublicationReady: (sql: SqlClient.SqlClient, epoch: S
|
|
|
116
116
|
export type RetiredShadowSegment = Pick<ShadowSegment, "id" | "job_id">;
|
|
117
117
|
export declare const unfinishedRetiredSegments: (sql: SqlClient.SqlClient) => import("effect/unstable/sql/Statement").Statement<RetiredShadowSegment>;
|
|
118
118
|
export declare const settleRetiredSegment: (sql: SqlClient.SqlClient, segment: RetiredShadowSegment, committed: boolean) => import("effect/unstable/sql/Statement").Statement<object>;
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Policy-only refresh is independent of build leases and cannot confer publication eligibility.
|
|
121
|
+
* Every change of the active target's projection selects a new active generation, which fences
|
|
122
|
+
* a delayed install of an earlier projection.
|
|
123
|
+
*/
|
|
124
|
+
export declare const shadowPolicyViewOwnership: (sql: SqlClient.SqlClient, generation: string, source: string) => Effect.Effect<boolean, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
125
|
+
export declare const recordShadowPolicyViews: (sql: SqlClient.SqlClient, generation: string, source: string) => import("effect/unstable/sql/Statement").Statement<object>;
|
|
122
126
|
/** Used after reading a destination view's etag, before its conditional DDL update. */
|
|
123
127
|
export declare const shadowViewOwnership: (sql: SqlClient.SqlClient, id: string) => Effect.Effect<boolean, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
124
128
|
/** A finite background goal prevents continuous writes from moving initialization's finish line. */
|
|
@@ -511,10 +511,6 @@ export const refreshShadowCapturePolicy = (sql) => sql.unsafe(`UPDATE _ontology_
|
|
|
511
511
|
FROM _ontology_replication_targets t,jsonb_each(t.capture_bindings) binding,
|
|
512
512
|
jsonb_each_text(binding.value) field WHERE t.capturing
|
|
513
513
|
AND t.source_id=(SELECT source_id FROM _ontology_replication WHERE id)
|
|
514
|
-
AND NOT EXISTS (
|
|
515
|
-
SELECT 1 FROM _ontology_replication state,jsonb_array_elements(state.exclusions) exclusion
|
|
516
|
-
WHERE exclusion->>'entityId'=binding.key AND
|
|
517
|
-
(COALESCE((exclusion->>'disabled')::boolean,false) OR exclusion->'fields' ? field.value))
|
|
518
514
|
GROUP BY binding.key
|
|
519
515
|
) union_fields
|
|
520
516
|
) selections),'{}'::jsonb) WHERE id`);
|
|
@@ -581,15 +577,19 @@ export const settleRetiredSegment = (sql, segment, committed) => sql.unsafe(`UPD
|
|
|
581
577
|
committed_at=CASE WHEN $3='committed' THEN now() ELSE committed_at END
|
|
582
578
|
WHERE id=$1::uuid AND job_id=$2 AND state='pending' AND epoch IN (
|
|
583
579
|
SELECT id FROM _ontology_replication_epochs WHERE state IN ('retired','cancelled'))`, [segment.id, segment.job_id, committed ? "committed" : "failed"]);
|
|
584
|
-
/**
|
|
585
|
-
|
|
580
|
+
/**
|
|
581
|
+
* Policy-only refresh is independent of build leases and cannot confer publication eligibility.
|
|
582
|
+
* Every change of the active target's projection selects a new active generation, which fences
|
|
583
|
+
* a delayed install of an earlier projection.
|
|
584
|
+
*/
|
|
585
|
+
export const shadowPolicyViewOwnership = (sql, generation, source) => sql
|
|
586
586
|
.unsafe(`SELECT EXISTS(SELECT 1 FROM _ontology_replication
|
|
587
587
|
WHERE id AND enabled AND NOT destination_repair_pending AND active_generation=$1::uuid
|
|
588
|
-
AND source_id=$2::uuid
|
|
588
|
+
AND source_id=$2::uuid) AS valid`, [generation, source])
|
|
589
589
|
.pipe(Effect.map((rows) => rows[0].valid));
|
|
590
|
-
export const recordShadowPolicyViews = (sql, generation, source
|
|
590
|
+
export const recordShadowPolicyViews = (sql, generation, source) => sql.unsafe(`UPDATE _ontology_replication_epochs SET policy_installed=true WHERE id=$1::uuid
|
|
591
591
|
AND EXISTS(SELECT 1 FROM _ontology_replication WHERE id AND enabled AND NOT destination_repair_pending
|
|
592
|
-
AND active_generation=$1::uuid AND source_id=$2::uuid
|
|
592
|
+
AND active_generation=$1::uuid AND source_id=$2::uuid)`, [generation, source]);
|
|
593
593
|
/** Used after reading a destination view's etag, before its conditional DDL update. */
|
|
594
594
|
export const shadowViewOwnership = (sql, id) => sql
|
|
595
595
|
.unsafe(`SELECT EXISTS(SELECT 1 FROM _ontology_replication_epochs e
|