@segmentstream/ontology 0.122.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 +41 -0
- package/README.md +9 -1
- package/dist/action.d.ts +11 -6
- package/dist/analyze.js +13 -7
- package/dist/app-feedback.js +6 -5
- 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/service-binding.d.ts +5 -1
- package/dist/runtime/service-binding.js +14 -5
- package/dist/service/mcp/server.js +5 -5
- 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,46 @@
|
|
|
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
|
+
|
|
3
44
|
## 0.122.0
|
|
4
45
|
|
|
5
46
|
The website's visitors' chats in the inbox: `inbox.roles` may list `guest` where the ontology
|
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.js
CHANGED
|
@@ -535,13 +535,19 @@ function resolveWorkflows(input) {
|
|
|
535
535
|
"no action, so the workflow can at most read; add the actions it runs to the role's " +
|
|
536
536
|
"permissions.", "warning");
|
|
537
537
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
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");
|
|
545
551
|
}
|
|
546
552
|
const schema = workflowInputSchema(candidate.input);
|
|
547
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/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
|
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
|
-
import { type ReplicationEvent, type ReplicationSelection
|
|
3
|
+
import { type ReplicationEvent, type ReplicationSelection } from "./model.js";
|
|
4
4
|
import { advanceReplicationBaseline, ReplicationBaselineFailed, type ReplicationTarget } from "./baseline.js";
|
|
5
5
|
export type { ReplicationTarget } from "./baseline.js";
|
|
6
6
|
export declare const startReplication: (sql: SqlClient.SqlClient, input: {
|
|
7
7
|
readonly generation: string;
|
|
8
|
-
readonly exclusions?: ReadonlyArray<ReplicationExclusion>;
|
|
9
8
|
readonly selection?: ReadonlyArray<ReplicationSelection>;
|
|
10
9
|
readonly newSource?: boolean;
|
|
11
10
|
}) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed | import("../index.js").CatalogInvalid | import("./legacy-baseline.js").ReplicationBaselineFailed, never>;
|
|
12
11
|
export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
12
|
+
/**
|
|
13
|
+
* Disables source capture under the lifecycle fence: the state a preview branch's binding, or an
|
|
14
|
+
* earlier release's retired pause, leaves behind. Starting replication resumes such a source with a
|
|
15
|
+
* fresh incarnation; nothing in the platform offers capture as an opt-out.
|
|
16
|
+
*/
|
|
13
17
|
export declare const pauseReplication: (sql: SqlClient.SqlClient) => Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
14
18
|
export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
15
19
|
export { advanceReplicationBaseline };
|
|
@@ -9,18 +9,10 @@ import { readCatalog } from "../migrate/apply.js";
|
|
|
9
9
|
import { historyTableName, quoteIdentifier as qi } from "../migrate/storage.js";
|
|
10
10
|
import { REPLICATION_BATCH_BYTES, REPLICATION_BATCH_SIZE, publishMessage, replicationEventId, resolveReplicationSelection, } from "./model.js";
|
|
11
11
|
import { createReplicationBaseline, advanceReplicationBaseline, ReplicationBaselineFailed, } from "./baseline.js";
|
|
12
|
-
import {
|
|
12
|
+
import { migratedReplicationFills } from "./migrate.js";
|
|
13
13
|
import { refreshReplicationProjection } from "./evolution.js";
|
|
14
14
|
import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA } from "./schema.js";
|
|
15
15
|
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
16
|
-
const replicationPolicyKey = (policy) => JSON.stringify(policy
|
|
17
|
-
.map((item) => ({
|
|
18
|
-
entityId: item.entityId,
|
|
19
|
-
disabled: item.disabled ?? false,
|
|
20
|
-
fields: [...new Set(item.fields ?? [])].sort(),
|
|
21
|
-
relationships: [...new Set(item.relationships ?? [])].sort(),
|
|
22
|
-
}))
|
|
23
|
-
.sort((a, b) => a.entityId.localeCompare(b.entityId)));
|
|
24
16
|
export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
25
17
|
const manifest = yield* readCatalog({ sql });
|
|
26
18
|
if (!manifest) {
|
|
@@ -29,27 +21,31 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
|
29
21
|
});
|
|
30
22
|
}
|
|
31
23
|
const version = yield* protocol(sql);
|
|
32
|
-
|
|
24
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
25
|
+
// A source can still record the exclusions of retired per-workspace export policies. Clearing
|
|
26
|
+
// them is a policy change through the same scoped recovery and cutover as any other.
|
|
27
|
+
const [state] = yield* sql.unsafe(`SELECT enabled,
|
|
28
|
+
COALESCE(to_jsonb(_ontology_replication)->'exclusions','[]'::jsonb)<>'[]'::jsonb AS restricted
|
|
29
|
+
FROM _ontology_replication WHERE id`);
|
|
33
30
|
const requested = yield* replicationTarget(sql, input.generation);
|
|
34
31
|
const previous = version >= 6 && requested ? ((yield* activeReplicationTarget(sql)) ?? requested) : requested;
|
|
35
|
-
const
|
|
36
|
-
const persisted = replicationPolicyKey(policy) === replicationPolicyKey(state?.exclusions ?? []);
|
|
32
|
+
const restricted = state?.restricted === true;
|
|
37
33
|
const paused = version >= 6 && state?.enabled === false;
|
|
38
34
|
if (previous &&
|
|
39
35
|
!paused &&
|
|
40
|
-
|
|
36
|
+
!restricted &&
|
|
41
37
|
previous.manifest.hash === manifest.hash &&
|
|
42
38
|
input.selection === undefined) {
|
|
43
39
|
return previous;
|
|
44
40
|
}
|
|
45
41
|
const selection = input.selection ??
|
|
46
42
|
(yield* Effect.try({
|
|
47
|
-
try: () => resolveReplicationSelection(manifest
|
|
48
|
-
catch: (cause) => new ReplicationBaselineFailed({ message: "Invalid replication
|
|
43
|
+
try: () => resolveReplicationSelection(manifest),
|
|
44
|
+
catch: (cause) => new ReplicationBaselineFailed({ message: "Invalid replication projection.", cause }),
|
|
49
45
|
}));
|
|
50
46
|
if (previous &&
|
|
51
47
|
(paused ||
|
|
52
|
-
|
|
48
|
+
restricted ||
|
|
53
49
|
previous.manifest.hash !== manifest.hash ||
|
|
54
50
|
canonicalJson(previous.selection) !== canonicalJson(selection))) {
|
|
55
51
|
if (version >= 5) {
|
|
@@ -67,10 +63,9 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
|
67
63
|
}
|
|
68
64
|
const fills = yield* migratedReplicationFills(sql, current, manifest, selection);
|
|
69
65
|
yield* refreshReplicationProjection(sql, current, { ...current, manifest, selection, fills }, undefined, { resuming: version >= 6 && capture?.enabled === false });
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
]);
|
|
66
|
+
// @legacy ontology.replication-exclusion-remnants
|
|
67
|
+
// An older backend release still reads the retired exclusions; record that none remain.
|
|
68
|
+
yield* sql.unsafe("UPDATE _ontology_replication SET selection=$1::jsonb,exclusions='[]'::jsonb,enabled=true WHERE id", [JSON.stringify(Object.fromEntries(selection.map((item) => [item.entityId, item])))]);
|
|
74
69
|
if (version >= 6) {
|
|
75
70
|
yield* sql.unsafe(`UPDATE _ontology_replication_epochs SET policy_installed=false
|
|
76
71
|
WHERE id=(SELECT active_generation FROM _ontology_replication WHERE id)`);
|
|
@@ -121,6 +116,11 @@ export const activeReplicationTarget = (sql) => Effect.gen(function* () {
|
|
|
121
116
|
: yield* sql.unsafe(statement);
|
|
122
117
|
return rows[0];
|
|
123
118
|
});
|
|
119
|
+
/**
|
|
120
|
+
* Disables source capture under the lifecycle fence: the state a preview branch's binding, or an
|
|
121
|
+
* earlier release's retired pause, leaves behind. Starting replication resumes such a source with a
|
|
122
|
+
* fresh incarnation; nothing in the platform offers capture as an opt-out.
|
|
123
|
+
*/
|
|
124
124
|
export const pauseReplication = (sql) => sql.withTransaction(Effect.gen(function* () {
|
|
125
125
|
yield* lockReplicationLifecycle(sql);
|
|
126
126
|
yield* sql.unsafe("UPDATE _ontology_replication SET enabled = false WHERE id");
|
|
@@ -166,7 +166,7 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
166
166
|
ORDER BY revision,event_id LIMIT ${REPLICATION_BATCH_SIZE}`, shadow
|
|
167
167
|
? [target.generation, options.bulk ?? false, options.through ?? null]
|
|
168
168
|
: [target.generation]);
|
|
169
|
-
// An idle pass ends here: the bindings
|
|
169
|
+
// An idle pass ends here: the wire bindings below shape only queued events.
|
|
170
170
|
if (references.length === 0) {
|
|
171
171
|
return [];
|
|
172
172
|
}
|
|
@@ -196,10 +196,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
196
196
|
? yield* sql.unsafe("SELECT capture_bindings,capture_versions FROM _ontology_replication_targets WHERE generation=$1::uuid", [target.generation])
|
|
197
197
|
: [];
|
|
198
198
|
const batchBytes = options.bulk ? 32_000_000 : REPLICATION_BATCH_BYTES;
|
|
199
|
-
const [policy] = shadow
|
|
200
|
-
? yield* sql.unsafe("SELECT exclusions FROM _ontology_replication WHERE id")
|
|
201
|
-
: [];
|
|
202
|
-
const suppressed = [];
|
|
203
199
|
let size = 32;
|
|
204
200
|
const result = [];
|
|
205
201
|
for (const reference of references) {
|
|
@@ -216,23 +212,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
216
212
|
const bindings = wire.capture_versions?.find((version) => version.through === undefined || BigInt(event.revision) <= BigInt(version.through))?.bindings ?? wire.capture_bindings;
|
|
217
213
|
event = shadowWireEvent(event, bindings, target.selection);
|
|
218
214
|
}
|
|
219
|
-
const restriction = policy?.exclusions.find((item) => item.entityId === event.entity_id);
|
|
220
|
-
if (restriction?.disabled ||
|
|
221
|
-
(event.record_kind.startsWith("edge:") &&
|
|
222
|
-
restriction?.relationships?.includes(event.record_kind.slice(5)))) {
|
|
223
|
-
suppressed.push(reference.id);
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
if (restriction && event.record_kind === "entity" && !event.deleted) {
|
|
227
|
-
const fields = new Set([
|
|
228
|
-
...(restriction.fields ?? []),
|
|
229
|
-
...(restriction.relationships ?? []).map((name) => `${name}_id`),
|
|
230
|
-
]);
|
|
231
|
-
event = {
|
|
232
|
-
...event,
|
|
233
|
-
payload: JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(event.payload)).filter(([key]) => !fields.has(wire?.capture_bindings?.[event.entity_id]?.[key] ?? key)))),
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
215
|
const bytes = Buffer.byteLength(JSON.stringify(publishMessage(event))) + 1;
|
|
237
216
|
if (bytes + 32 > REPLICATION_BATCH_BYTES) {
|
|
238
217
|
return yield* Effect.die(new Error("A replication event exceeds the publish request limit."));
|
|
@@ -243,10 +222,6 @@ export const pendingReplicationEvents = (sql, target, options = {}) => Effect.ge
|
|
|
243
222
|
size += bytes;
|
|
244
223
|
result.push({ historyId: reference.id, event });
|
|
245
224
|
}
|
|
246
|
-
if (suppressed.length) {
|
|
247
|
-
yield* sql.unsafe(`UPDATE _ontology_replication_delivery SET suppressed_at=now()
|
|
248
|
-
WHERE generation=$1::uuid AND event_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))`, [target.generation, JSON.stringify(suppressed)]);
|
|
249
|
-
}
|
|
250
225
|
return result;
|
|
251
226
|
});
|
|
252
227
|
/** Lost publish responses deliberately leave the same immutable IDs pending. */
|
|
@@ -7,7 +7,11 @@ import type { Ontology } from "../ontology.js";
|
|
|
7
7
|
import { OntologyBackend, type OntologyServiceRuntime } from "../service/runtime-contract.js";
|
|
8
8
|
import { SignInLinks } from "./sign-in-links.js";
|
|
9
9
|
import { WorkflowStarter } from "./workflow-starts.js";
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* The service's backend on the runtime, over the SQL client in context. `blobStorage` is the
|
|
12
|
+
* deployment's file storage, or a test's `memoryFileStorage().blobStorage`; without it, actions
|
|
13
|
+
* that upload, stage or open files are refused.
|
|
14
|
+
*/
|
|
11
15
|
export declare function backendLayer(ontology: Ontology, blobStorage?: Redacted.Redacted<BlobStorageBinding>, workflowStarter?: WorkflowStarter["Service"], deployment?: DeploymentObservation, signInLinks?: SignInLinks["Service"]): Layer.Layer<OntologyBackend, never, SqlClient.SqlClient>;
|
|
12
16
|
/**
|
|
13
17
|
* `@effect/sql-pg` on the pooled `ontology_app` connection string, with the TLS server name a
|
|
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { Effect, Layer, Redacted } from "effect";
|
|
4
4
|
import { SqlClient } from "effect/unstable/sql";
|
|
5
5
|
import { isSqlError } from "effect/unstable/sql/SqlError";
|
|
6
|
+
import { memoryFileStore } from "../storage/memory.js";
|
|
6
7
|
import { neonBlobProvider } from "../storage/neon.js";
|
|
7
8
|
import { maintainBlobStorage } from "../storage/maintenance.js";
|
|
8
9
|
import { attachmentRuntime } from "../storage/attachments.js";
|
|
@@ -42,7 +43,11 @@ function rejectedAs(operation) {
|
|
|
42
43
|
...(rejection.diagnostic === undefined ? {} : { diagnostic: rejection.diagnostic }),
|
|
43
44
|
}), Effect.as(undefined));
|
|
44
45
|
}
|
|
45
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The service's backend on the runtime, over the SQL client in context. `blobStorage` is the
|
|
48
|
+
* deployment's file storage, or a test's `memoryFileStorage().blobStorage`; without it, actions
|
|
49
|
+
* that upload, stage or open files are refused.
|
|
50
|
+
*/
|
|
46
51
|
export function backendLayer(ontology, blobStorage, workflowStarter, deployment, signInLinks) {
|
|
47
52
|
return Layer.effect(OntologyBackend, Effect.gen(function* () {
|
|
48
53
|
const sql = yield* SqlClient.SqlClient;
|
|
@@ -134,10 +139,14 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
|
|
|
134
139
|
.pipe(Effect.orDie);
|
|
135
140
|
}
|
|
136
141
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
142
|
+
// A test's in-memory store answers its own transfer grants; a deployment's binding names
|
|
143
|
+
// the branch storage of its database.
|
|
144
|
+
const memory = memoryFileStore(blobStorage);
|
|
145
|
+
const provider = memory?.provider ??
|
|
146
|
+
(binding
|
|
147
|
+
? yield* Effect.acquireRelease(Effect.sync(() => neonBlobProvider(binding, deployment)), (provider) => Effect.sync(() => provider.close?.()))
|
|
148
|
+
: undefined);
|
|
149
|
+
const blobs = provider ? blobRuntime(ontology, sql, provider, memory?.fetch) : undefined;
|
|
141
150
|
const attachments = provider ? attachmentRuntime(ontology, sql, provider) : undefined;
|
|
142
151
|
return OntologyBackend.of({
|
|
143
152
|
workflowAdmissions: {
|
|
@@ -627,9 +627,9 @@ export const FEEDBACK_INSTRUCTIONS = "Feedback: this app accepts feedback for it
|
|
|
627
627
|
"something works badly or asks for something new. Do not offer what you can do yourself; offer " +
|
|
628
628
|
"once per problem. Before submitting, look for the user's open app_feedback with the same " +
|
|
629
629
|
"subject. Submit with app_feedback_submit only after the user agrees to the title and summary you " +
|
|
630
|
-
"show in their language.
|
|
631
|
-
"
|
|
632
|
-
"
|
|
630
|
+
"show in their language. When the user asks about their feedback, read only their own: filter " +
|
|
631
|
+
"app_feedback by reporter, their user id from me, since builders can read everyone's. Tell " +
|
|
632
|
+
"them the builders' response, then call app_feedback_acknowledge with its responded_at.";
|
|
633
633
|
export const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS = "Feedback: During requested work, this workspace preauthorizes minimal technical failure reports. " +
|
|
634
634
|
"Automatically record unexpected or persistent tool/connection failures through app_feedback_submit; " +
|
|
635
635
|
"first reuse the caller's open report with the same subject. Include only the operation, safe technical " +
|
|
@@ -637,8 +637,8 @@ export const AUTOMATIC_FAILURE_REPORT_INSTRUCTIONS = "Feedback: During requested
|
|
|
637
637
|
"reason and that the report was recorded in one or two sentences; do not merely offer to report it, " +
|
|
638
638
|
"and never claim it was recorded before a successful submission or existing-item read. " +
|
|
639
639
|
"Feature/change requests and sharing task contents or files still require the member's agreement " +
|
|
640
|
-
"to the title and summary.
|
|
641
|
-
"acknowledge only the response you
|
|
640
|
+
"to the title and summary. Asked about their feedback, read only the caller's own items " +
|
|
641
|
+
"(reporter is their user id from me) and acknowledge only the response you relayed.";
|
|
642
642
|
/**
|
|
643
643
|
* Fixed guidance keeps initialization independent of ontology size: the feedback paragraph depends
|
|
644
644
|
* only on whether the caller may run `app_feedback_submit`.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Effect, Redacted } from "effect";
|
|
2
|
+
import type { BlobUpload, BlobValue } from "../blob.js";
|
|
3
|
+
import { type ActionError } from "../errors.js";
|
|
4
|
+
import type { OpenFile } from "../files.js";
|
|
5
|
+
import type { Principal } from "../runtime.js";
|
|
6
|
+
import { OntologyBackend } from "../service/runtime-contract.js";
|
|
7
|
+
import { type BlobProvider, type BlobStorageBinding } from "./provider.js";
|
|
8
|
+
export interface MemoryFileStorageOptions {
|
|
9
|
+
/** The workspace's storage quota in bytes, which uploads count against. 1 GiB by default. */
|
|
10
|
+
readonly quotaBytes?: number;
|
|
11
|
+
}
|
|
12
|
+
/** A file to upload for an action's `uploads.for(entity, property)` input. */
|
|
13
|
+
export interface MemoryFileUpload {
|
|
14
|
+
/** Who uploads: the member or service user that then runs the action, with its roles stored. */
|
|
15
|
+
readonly principal: Principal;
|
|
16
|
+
/** The entity and file property of the action's `uploads.for` input. */
|
|
17
|
+
readonly entity: string;
|
|
18
|
+
readonly property: string;
|
|
19
|
+
/** The action that consumes the ticket, on `entity`. */
|
|
20
|
+
readonly action: string;
|
|
21
|
+
/** The record the action changes. Omit it for a record the action creates. */
|
|
22
|
+
readonly recordId?: string;
|
|
23
|
+
/** Names the record the action creates; the idempotency key by default, without `recordId`. */
|
|
24
|
+
readonly createIntent?: string;
|
|
25
|
+
/** The upload's and the action's idempotency key, a UUID; a new one by default. */
|
|
26
|
+
readonly idempotencyKey?: string;
|
|
27
|
+
readonly filename: string;
|
|
28
|
+
readonly contentType: string;
|
|
29
|
+
/** The file's bytes; a string is stored as UTF-8. */
|
|
30
|
+
readonly bytes: Uint8Array | string;
|
|
31
|
+
}
|
|
32
|
+
/** A completed upload, ready for the action it was made for. */
|
|
33
|
+
export interface UploadedFile {
|
|
34
|
+
/**
|
|
35
|
+
* The ticket an `uploads.for` input takes: `{ uploadId }` in an entity handle's action call,
|
|
36
|
+
* `{ upload_id: ticket.uploadId }` in an action's JSON input over HTTP or `runAction`.
|
|
37
|
+
*/
|
|
38
|
+
readonly ticket: BlobUpload;
|
|
39
|
+
/** The action options that consume the ticket: its idempotency key and, for a new record, create intent. */
|
|
40
|
+
readonly options: {
|
|
41
|
+
readonly idempotencyKey: string;
|
|
42
|
+
readonly createIntent?: string;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** A stored file revision read back, with its bytes. */
|
|
46
|
+
export interface StoredFile {
|
|
47
|
+
readonly file: BlobValue;
|
|
48
|
+
readonly bytes: Uint8Array;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* File storage held in memory, for tests that run the ontology in process. The backend built on
|
|
52
|
+
* it uploads, stages, opens and downloads files as on a deployment, with the same permission
|
|
53
|
+
* checks and upload lifecycle in the database; only the bytes stay in this process.
|
|
54
|
+
*/
|
|
55
|
+
export interface MemoryFileStorage {
|
|
56
|
+
/**
|
|
57
|
+
* The file storage to run the backend on: `backendLayer(ontology, files.blobStorage)`, or the
|
|
58
|
+
* `blobStorage` of `createOntologyService`'s configuration, which then also needs a
|
|
59
|
+
* `storageMaintenanceKey`.
|
|
60
|
+
*/
|
|
61
|
+
readonly blobStorage: Redacted.Redacted<BlobStorageBinding>;
|
|
62
|
+
/**
|
|
63
|
+
* Answers the transfer grants the store signs, as storage does: `PUT` stores an upload's bytes
|
|
64
|
+
* and `GET` returns a file's. A test that uploads over HTTP sends the bytes with it, such as
|
|
65
|
+
* `createBlobStorageClient(transport, files.fetch)` of the App SDK.
|
|
66
|
+
*/
|
|
67
|
+
readonly fetch: typeof fetch;
|
|
68
|
+
/**
|
|
69
|
+
* Uploads `bytes` as `principal` for `entity.action`'s `uploads.for(entity, property)` input
|
|
70
|
+
* and completes the upload: what an app's upload does, through the backend in context, which
|
|
71
|
+
* must run on this store. It checks the action's permission, the property's file policy and
|
|
72
|
+
* the quota as the service does.
|
|
73
|
+
*/
|
|
74
|
+
readonly upload: (input: MemoryFileUpload) => Effect.Effect<UploadedFile, ActionError, OntologyBackend>;
|
|
75
|
+
/**
|
|
76
|
+
* Reads a stored file revision back as `principal`, with the entity's read permission and
|
|
77
|
+
* scopes checked as `Files.open` checks them: the record's current file, or `revisionId`.
|
|
78
|
+
*/
|
|
79
|
+
readonly read: (input: OpenFile & {
|
|
80
|
+
readonly principal: Principal;
|
|
81
|
+
}) => Effect.Effect<StoredFile, ActionError, OntologyBackend>;
|
|
82
|
+
}
|
|
83
|
+
interface MemoryStore {
|
|
84
|
+
readonly provider: BlobProvider["Service"];
|
|
85
|
+
readonly fetch: typeof fetch;
|
|
86
|
+
}
|
|
87
|
+
/** The in-memory store `blobStorage` names, when `memoryFileStorage` made it. */
|
|
88
|
+
export declare function memoryFileStore(blobStorage: Redacted.Redacted<BlobStorageBinding> | undefined): MemoryStore | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* File storage held in memory, for tests that run an ontology's actions with files in process:
|
|
91
|
+
* `uploads.for` inputs, `Files.stage`, `Files.open`, downloads and the agent's attachments. Each
|
|
92
|
+
* call makes an empty store.
|
|
93
|
+
*
|
|
94
|
+
* ```ts
|
|
95
|
+
* const files = memoryFileStorage();
|
|
96
|
+
* const backend = backendLayer(ontology, files.blobStorage).pipe(Layer.provide(database));
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export declare function memoryFileStorage(options?: MemoryFileStorageOptions): MemoryFileStorage;
|
|
100
|
+
export {};
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { Effect, Redacted, Stream } from "effect";
|
|
3
|
+
import { isSqlError } from "effect/unstable/sql/SqlError";
|
|
4
|
+
import { nameToWire } from "../authoring-names.js";
|
|
5
|
+
import { ActionRejected, Conflict } from "../errors.js";
|
|
6
|
+
import { OntologyBackend } from "../service/runtime-contract.js";
|
|
7
|
+
import { BlobStorageError, } from "./provider.js";
|
|
8
|
+
/** A reserved domain: the grants a store signs, under its own host, never reach a network. */
|
|
9
|
+
const DOMAIN = "files.invalid";
|
|
10
|
+
/** How long storage honours a part upload grant and a download grant, as deployed storage does. */
|
|
11
|
+
const PART_GRANT_SECONDS = 300;
|
|
12
|
+
const DOWNLOAD_GRANT_SECONDS = 60;
|
|
13
|
+
/** The bytes `readPrefix` returns, which completion sniffs. */
|
|
14
|
+
const PREFIX_BYTES = 512;
|
|
15
|
+
const DEFAULT_QUOTA_BYTES = 1024 * 1024 * 1024;
|
|
16
|
+
/** The stores `memoryFileStorage` made, by the binding it handed out. */
|
|
17
|
+
const stores = new WeakMap();
|
|
18
|
+
/** The in-memory store `blobStorage` names, when `memoryFileStorage` made it. */
|
|
19
|
+
export function memoryFileStore(blobStorage) {
|
|
20
|
+
return blobStorage === undefined ? undefined : stores.get(blobStorage);
|
|
21
|
+
}
|
|
22
|
+
function failure(operation, message) {
|
|
23
|
+
return new BlobStorageError({ operation, cause: new Error(message) });
|
|
24
|
+
}
|
|
25
|
+
function sha256(bytes) {
|
|
26
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
27
|
+
}
|
|
28
|
+
function concat(chunks) {
|
|
29
|
+
const bytes = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
|
|
30
|
+
let offset = 0;
|
|
31
|
+
for (const chunk of chunks) {
|
|
32
|
+
bytes.set(chunk, offset);
|
|
33
|
+
offset += chunk.byteLength;
|
|
34
|
+
}
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
function text(status, body) {
|
|
38
|
+
return new Response(body, { status, headers: { "content-type": "text/plain" } });
|
|
39
|
+
}
|
|
40
|
+
/** The provider and the transfer endpoint of one store: the multipart lifecycle of object storage. */
|
|
41
|
+
function memoryStore(binding) {
|
|
42
|
+
const objects = new Map();
|
|
43
|
+
const uploads = new Map();
|
|
44
|
+
const grants = new Map();
|
|
45
|
+
const sign = (grant, method) => {
|
|
46
|
+
const token = randomUUID();
|
|
47
|
+
grants.set(token, grant);
|
|
48
|
+
return {
|
|
49
|
+
url: `${binding.endpoint}/${encodeURIComponent(grant.key)}?grant=${token}`,
|
|
50
|
+
method,
|
|
51
|
+
headers: {},
|
|
52
|
+
expiresAt: new Date(grant.expiresAt).toISOString(),
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
const upload = (operation, key, uploadId) => Effect.suspend(() => {
|
|
56
|
+
const pending = uploads.get(uploadId);
|
|
57
|
+
return pending?.key === key
|
|
58
|
+
? Effect.succeed(pending)
|
|
59
|
+
: Effect.fail(failure(operation, "No such multipart upload."));
|
|
60
|
+
});
|
|
61
|
+
const object = (operation, key) => Effect.suspend(() => {
|
|
62
|
+
const stored = objects.get(key);
|
|
63
|
+
return stored ? Effect.succeed(stored) : Effect.fail(failure(operation, "No such object."));
|
|
64
|
+
});
|
|
65
|
+
const provider = {
|
|
66
|
+
binding,
|
|
67
|
+
initiate: ({ key, contentType, sessionId }) => Effect.sync(() => {
|
|
68
|
+
const uploadId = randomUUID();
|
|
69
|
+
uploads.set(uploadId, { key, contentType, sessionId, parts: new Map() });
|
|
70
|
+
return uploadId;
|
|
71
|
+
}),
|
|
72
|
+
signPart: ({ key, uploadId, partNumber, size }) => upload("blob.sign_part", key, uploadId).pipe(Effect.map(() => sign({
|
|
73
|
+
kind: "part",
|
|
74
|
+
key,
|
|
75
|
+
uploadId,
|
|
76
|
+
partNumber,
|
|
77
|
+
size,
|
|
78
|
+
expiresAt: Date.now() + PART_GRANT_SECONDS * 1000,
|
|
79
|
+
}, "PUT"))),
|
|
80
|
+
parts: ({ key, uploadId }) => upload("blob.parts", key, uploadId).pipe(Effect.map((pending) => [...pending.parts]
|
|
81
|
+
.sort(([left], [right]) => left - right)
|
|
82
|
+
.map(([number, part]) => ({ number, size: part.size, etag: part.etag })))),
|
|
83
|
+
complete: ({ key, uploadId, parts }) => upload("blob.complete", key, uploadId).pipe(Effect.flatMap((pending) => {
|
|
84
|
+
const chunks = parts.map((part) => {
|
|
85
|
+
const stored = pending.parts.get(part.number);
|
|
86
|
+
return stored?.etag === part.etag ? stored.bytes : undefined;
|
|
87
|
+
});
|
|
88
|
+
if (parts.length === 0 || chunks.some((chunk) => chunk === undefined)) {
|
|
89
|
+
return Effect.fail(failure("blob.complete", "The parts do not match the upload."));
|
|
90
|
+
}
|
|
91
|
+
return Effect.sync(() => {
|
|
92
|
+
const bytes = concat(chunks);
|
|
93
|
+
objects.set(key, {
|
|
94
|
+
bytes,
|
|
95
|
+
size: bytes.byteLength,
|
|
96
|
+
contentType: pending.contentType,
|
|
97
|
+
sessionId: pending.sessionId,
|
|
98
|
+
});
|
|
99
|
+
uploads.delete(uploadId);
|
|
100
|
+
});
|
|
101
|
+
})),
|
|
102
|
+
inspect: (key) => Effect.sync(() => {
|
|
103
|
+
const stored = objects.get(key);
|
|
104
|
+
return stored
|
|
105
|
+
? { size: stored.size, contentType: stored.contentType, sessionId: stored.sessionId }
|
|
106
|
+
: undefined;
|
|
107
|
+
}),
|
|
108
|
+
sha256: (key, size) => object("blob.sha256", key).pipe(Effect.flatMap((stored) => stored.size === size
|
|
109
|
+
? Effect.succeed(sha256(stored.bytes))
|
|
110
|
+
: Effect.fail(failure("blob.sha256", "The object does not match its declared size.")))),
|
|
111
|
+
readPrefix: (key) => object("blob.read_prefix", key).pipe(Effect.map((stored) => stored.bytes.slice(0, PREFIX_BYTES))),
|
|
112
|
+
read: (key, maxBytes) => object("blob.read", key).pipe(Effect.flatMap((stored) => stored.size <= maxBytes
|
|
113
|
+
? Effect.succeed(stored.bytes.slice())
|
|
114
|
+
: Effect.fail(failure("blob.read", "The object exceeds the size it may have.")))),
|
|
115
|
+
download: ({ key, contentType }) => object("blob.download", key).pipe(Effect.map(() => sign({
|
|
116
|
+
kind: "download",
|
|
117
|
+
key,
|
|
118
|
+
contentType,
|
|
119
|
+
expiresAt: Date.now() + DOWNLOAD_GRANT_SECONDS * 1000,
|
|
120
|
+
}, "GET"))),
|
|
121
|
+
abort: ({ key, uploadId }) => Effect.sync(() => {
|
|
122
|
+
if (uploads.get(uploadId)?.key === key) {
|
|
123
|
+
uploads.delete(uploadId);
|
|
124
|
+
}
|
|
125
|
+
}),
|
|
126
|
+
remove: (key) => Effect.sync(() => {
|
|
127
|
+
objects.delete(key);
|
|
128
|
+
}),
|
|
129
|
+
pending: (key) => Effect.sync(() => [...uploads].flatMap(([uploadId, pending]) => (pending.key === key ? [uploadId] : []))),
|
|
130
|
+
};
|
|
131
|
+
const transfer = async (input, init) => {
|
|
132
|
+
const request = input instanceof Request ? input : undefined;
|
|
133
|
+
const url = new URL(request?.url ?? (input instanceof URL ? input.href : String(input)));
|
|
134
|
+
const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
|
|
135
|
+
(init?.signal ?? request?.signal)?.throwIfAborted();
|
|
136
|
+
const grant = url.origin === binding.endpoint ? grants.get(url.searchParams.get("grant") ?? "") : undefined;
|
|
137
|
+
if (grant === undefined ||
|
|
138
|
+
grant.key !== decodeURIComponent(url.pathname.slice(1)) ||
|
|
139
|
+
grant.expiresAt <= Date.now() ||
|
|
140
|
+
method !== (grant.kind === "part" ? "PUT" : "GET")) {
|
|
141
|
+
return text(403, "The transfer grant is not valid for this request.");
|
|
142
|
+
}
|
|
143
|
+
if (grant.kind === "download") {
|
|
144
|
+
const stored = objects.get(grant.key);
|
|
145
|
+
return stored
|
|
146
|
+
? new Response(stored.bytes.slice(), {
|
|
147
|
+
status: 200,
|
|
148
|
+
headers: {
|
|
149
|
+
"content-type": grant.contentType,
|
|
150
|
+
"content-length": String(stored.size),
|
|
151
|
+
},
|
|
152
|
+
})
|
|
153
|
+
: text(404, "No such object.");
|
|
154
|
+
}
|
|
155
|
+
const bytes = new Uint8Array(await new Response(init?.body ?? request?.body).arrayBuffer());
|
|
156
|
+
const pending = uploads.get(grant.uploadId);
|
|
157
|
+
if (pending === undefined) {
|
|
158
|
+
return text(404, "No such multipart upload.");
|
|
159
|
+
}
|
|
160
|
+
// The grant signs the part's length; storage refuses any other.
|
|
161
|
+
if (bytes.byteLength !== grant.size) {
|
|
162
|
+
return text(400, "The body does not match the signed content length.");
|
|
163
|
+
}
|
|
164
|
+
const etag = `"${sha256(bytes).slice(0, 32)}"`;
|
|
165
|
+
pending.parts.set(grant.partNumber, { size: bytes.byteLength, etag, bytes });
|
|
166
|
+
return new Response(null, { status: 200, headers: { etag } });
|
|
167
|
+
};
|
|
168
|
+
return { provider, fetch: transfer };
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* File storage held in memory, for tests that run an ontology's actions with files in process:
|
|
172
|
+
* `uploads.for` inputs, `Files.stage`, `Files.open`, downloads and the agent's attachments. Each
|
|
173
|
+
* call makes an empty store.
|
|
174
|
+
*
|
|
175
|
+
* ```ts
|
|
176
|
+
* const files = memoryFileStorage();
|
|
177
|
+
* const backend = backendLayer(ontology, files.blobStorage).pipe(Layer.provide(database));
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
export function memoryFileStorage(options = {}) {
|
|
181
|
+
const quotaBytes = options.quotaBytes ?? DEFAULT_QUOTA_BYTES;
|
|
182
|
+
if (!Number.isSafeInteger(quotaBytes) || quotaBytes <= 0) {
|
|
183
|
+
throw new Error("memoryFileStorage takes a positive integer quotaBytes.");
|
|
184
|
+
}
|
|
185
|
+
const secret = randomUUID();
|
|
186
|
+
// Each store is a branch of its own: files another store holds are not found in this one.
|
|
187
|
+
const branchId = `memory-${secret.slice(0, 8)}`;
|
|
188
|
+
const binding = {
|
|
189
|
+
projectId: "memory",
|
|
190
|
+
branchId,
|
|
191
|
+
endpoint: `https://${branchId}.${DOMAIN}`,
|
|
192
|
+
region: "memory",
|
|
193
|
+
bucket: "ontology-files",
|
|
194
|
+
accessKeyId: `memory-key-${secret}`,
|
|
195
|
+
secretAccessKey: `memory-secret-${secret}`,
|
|
196
|
+
quotaBytes,
|
|
197
|
+
};
|
|
198
|
+
const store = memoryStore(binding);
|
|
199
|
+
const blobStorage = Redacted.make(binding, { label: "memoryFileStorage" });
|
|
200
|
+
stores.set(blobStorage, store);
|
|
201
|
+
const blobsOf = Effect.gen(function* () {
|
|
202
|
+
const backend = yield* OntologyBackend;
|
|
203
|
+
if (backend.blobs === undefined) {
|
|
204
|
+
return yield* Effect.die(new Error("The ontology backend has no file storage. Build it on this store: " +
|
|
205
|
+
"backendLayer(ontology, files.blobStorage)."));
|
|
206
|
+
}
|
|
207
|
+
return backend.blobs;
|
|
208
|
+
});
|
|
209
|
+
// Storage and database failures are defects of the test's setup, not outcomes of the action.
|
|
210
|
+
const expected = (effect) => effect.pipe(Effect.catchIf((error) => isSqlError(error) || error instanceof BlobStorageError, (error) => Effect.die(error)));
|
|
211
|
+
return {
|
|
212
|
+
blobStorage,
|
|
213
|
+
fetch: store.fetch,
|
|
214
|
+
upload: (input) => expected(Effect.gen(function* () {
|
|
215
|
+
const blobs = yield* blobsOf;
|
|
216
|
+
const bytes = typeof input.bytes === "string" ? new TextEncoder().encode(input.bytes) : input.bytes;
|
|
217
|
+
const idempotencyKey = input.idempotencyKey ?? randomUUID();
|
|
218
|
+
const createIntent = input.recordId === undefined ? (input.createIntent ?? idempotencyKey) : undefined;
|
|
219
|
+
let session = yield* blobs.begin({
|
|
220
|
+
entity: nameToWire(input.entity),
|
|
221
|
+
property: nameToWire(input.property),
|
|
222
|
+
action: nameToWire(input.action),
|
|
223
|
+
...(input.recordId === undefined ? {} : { recordId: input.recordId }),
|
|
224
|
+
...(createIntent === undefined ? {} : { createIntent }),
|
|
225
|
+
idempotencyKey,
|
|
226
|
+
filename: input.filename,
|
|
227
|
+
contentType: input.contentType,
|
|
228
|
+
size: bytes.byteLength,
|
|
229
|
+
}, input.principal);
|
|
230
|
+
if (session.ticket === undefined) {
|
|
231
|
+
if (session.state !== "completing") {
|
|
232
|
+
const grant = yield* blobs.part(session.id, input.principal);
|
|
233
|
+
if (!grant.url.startsWith(`${binding.endpoint}/`)) {
|
|
234
|
+
return yield* Effect.die(new Error("The ontology backend stores files elsewhere. Build it on this store: " +
|
|
235
|
+
"backendLayer(ontology, files.blobStorage)."));
|
|
236
|
+
}
|
|
237
|
+
const response = yield* Effect.promise(() => store.fetch(grant.url, {
|
|
238
|
+
method: grant.method,
|
|
239
|
+
headers: grant.headers,
|
|
240
|
+
// A copy typed as an ArrayBuffer view: fetch's BodyInit refuses a view of any ArrayBufferLike.
|
|
241
|
+
body: new Uint8Array(bytes),
|
|
242
|
+
}));
|
|
243
|
+
if (!response.ok) {
|
|
244
|
+
return yield* new ActionRejected({
|
|
245
|
+
message: "file_transfer_failed",
|
|
246
|
+
cause: {
|
|
247
|
+
status: response.status,
|
|
248
|
+
detail: yield* Effect.promise(() => response.text()),
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
session = yield* blobs.complete(session.id, input.principal);
|
|
254
|
+
}
|
|
255
|
+
if (session.ticket === undefined) {
|
|
256
|
+
return yield* new Conflict({ entity: "upload", message: "The upload is not ready." });
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
ticket: session.ticket,
|
|
260
|
+
options: { idempotencyKey, ...(createIntent === undefined ? {} : { createIntent }) },
|
|
261
|
+
};
|
|
262
|
+
})),
|
|
263
|
+
read: (input) => expected(Effect.gen(function* () {
|
|
264
|
+
const blobs = yield* blobsOf;
|
|
265
|
+
if (blobs.files === undefined) {
|
|
266
|
+
return yield* Effect.die(new Error("The ontology backend's file storage does not open files."));
|
|
267
|
+
}
|
|
268
|
+
const files = blobs.files({ principal: input.principal });
|
|
269
|
+
return yield* Effect.scoped(Effect.gen(function* () {
|
|
270
|
+
const opened = yield* files.open({
|
|
271
|
+
entity: nameToWire(input.entity),
|
|
272
|
+
id: input.id,
|
|
273
|
+
property: nameToWire(input.property),
|
|
274
|
+
...(input.revisionId === undefined ? {} : { revisionId: input.revisionId }),
|
|
275
|
+
});
|
|
276
|
+
const chunks = yield* Stream.runCollect(opened.body);
|
|
277
|
+
return { file: opened.file, bytes: concat([...chunks]) };
|
|
278
|
+
}));
|
|
279
|
+
})),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
@@ -160,12 +160,12 @@ export declare function blobRuntime(ontology: Ontology, sql: SqlClient.SqlClient
|
|
|
160
160
|
expiresAt: string;
|
|
161
161
|
}, import("../errors.js").PermissionDenied | Conflict | NotFound | SqlError, never>;
|
|
162
162
|
download: (entityName: string, recordId: string, propertyName: string, input: {
|
|
163
|
-
readonly inline?: boolean | undefined;
|
|
164
163
|
readonly revisionId?: string | undefined;
|
|
164
|
+
readonly inline?: boolean | undefined;
|
|
165
165
|
}, principal: Principal) => Effect.Effect<import("./provider.js").TransferGrant, import("../errors.js").PermissionDenied | NotFound | SqlError | BlobStorageError, never>;
|
|
166
166
|
downloadFile: (entityName: string, recordId: string, propertyName: string, input: {
|
|
167
|
-
readonly inline?: boolean | undefined;
|
|
168
167
|
readonly revisionId?: string | undefined;
|
|
168
|
+
readonly inline?: boolean | undefined;
|
|
169
169
|
}, principal: Principal) => Effect.Effect<{
|
|
170
170
|
file: {
|
|
171
171
|
id: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.123.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",
|