@segmentstream/ontology 0.99.0 → 0.99.2
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 +1255 -0
- package/dist/analyze.js +40 -5
- package/dist/feedback-config.js +17 -8
- package/dist/replication/baseline.d.ts +9 -3
- package/dist/replication/baseline.js +9 -6
- package/dist/replication/scans.js +3 -1
- package/dist/replication/shadow.js +29 -6
- package/dist/replication/store.d.ts +2 -2
- package/dist/replication/store.js +12 -5
- package/dist/replication/stored-manifests.d.ts +25 -0
- package/dist/replication/stored-manifests.js +93 -0
- package/package.json +2 -1
package/dist/analyze.js
CHANGED
|
@@ -8,7 +8,7 @@ import { CONNECTION_KEY, isConnection } from "./connection.js";
|
|
|
8
8
|
import { isEntity } from "./entity.js";
|
|
9
9
|
import { QUERY_METRICS_ROUTE, LEGACY_MEMBER_NAME, ENTITY_ID, GENERATED_ACTIONS, GENERATED_UPSERT_PREFIX, HISTORY_SUFFIX, MCP_METRIC_TOOLS, MCP_READ_TOOLS, MCP_TOOL_NAME_MAX_LENGTH, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, mcpToolName, RESERVED_ENTITY_NAMES, RESERVED_MEMBER_NAMES, RESERVED_RELATIONSHIP_NAMES, SNAKE_CASE_NAME, SYSTEM_PROPERTIES, humanize, isSystemProperty, toCamelCase, } from "./names.js";
|
|
10
10
|
import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownPropertyOptions, referenceTarget, } from "./property.js";
|
|
11
|
-
import { generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
|
|
11
|
+
import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
|
|
12
12
|
import { ON_DELETE, isRelationship } from "./relationship.js";
|
|
13
13
|
import { isRole, member, role } from "./role.js";
|
|
14
14
|
import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
|
|
@@ -2298,6 +2298,44 @@ function unknownPermission(value, { entity, verb }, verbs) {
|
|
|
2298
2298
|
}
|
|
2299
2299
|
return `${value} is not a permission of this ontology; ${entity} has ${[...own].join(", ")}.`;
|
|
2300
2300
|
}
|
|
2301
|
+
/**
|
|
2302
|
+
* What `*:*` grants, naming only what it leaves out that the role does not grant by name: the
|
|
2303
|
+
* entities in {@link EXPLICIT_GRANT_ENTITIES} without an `<entity>:*`, administering users without
|
|
2304
|
+
* `user:*`, and workflows without `workflow:*:*`.
|
|
2305
|
+
*/
|
|
2306
|
+
function wildcardWarning(permissions) {
|
|
2307
|
+
const whole = new Set(permissions.flatMap((value) => {
|
|
2308
|
+
const parsed = parsePermission(value);
|
|
2309
|
+
return parsed !== undefined && parsed.verb === WILDCARD ? [parsed.entity] : [];
|
|
2310
|
+
}));
|
|
2311
|
+
const workflows = permissions.some((value) => {
|
|
2312
|
+
const workflow = parseWorkflowPermission(value);
|
|
2313
|
+
return workflow?.workflow === WILDCARD && workflow.verb === WILDCARD;
|
|
2314
|
+
});
|
|
2315
|
+
const entities = [...EXPLICIT_GRANT_ENTITIES].filter((entity) => !whole.has(entity));
|
|
2316
|
+
const left = [
|
|
2317
|
+
...(entities.length === 0
|
|
2318
|
+
? []
|
|
2319
|
+
: [
|
|
2320
|
+
`${listed(entities)}, which only a permission naming ${entities.length === 1 ? "it" : "them"} grants`,
|
|
2321
|
+
]),
|
|
2322
|
+
...(whole.has("user")
|
|
2323
|
+
? []
|
|
2324
|
+
: [
|
|
2325
|
+
`administering users (${USER_MEMBER_VERBS.map((verb) => `user:${verb}`).join(", ")} ` +
|
|
2326
|
+
"and user's authored actions), which only user:<verb> or user:* grants",
|
|
2327
|
+
]),
|
|
2328
|
+
...(workflows ? [] : ["workflows, which only workflow:<workflow>:<verb> grants"]),
|
|
2329
|
+
];
|
|
2330
|
+
const except = left.length === 0
|
|
2331
|
+
? ""
|
|
2332
|
+
: `, except ${left.length === 1 ? left[0] : `${left.slice(0, -1).join("; ")}; and ${left.at(-1)}`}`;
|
|
2333
|
+
return `*:* grants every entity and action, including those added later${except}.`;
|
|
2334
|
+
}
|
|
2335
|
+
/** `a`, `a and b`, `a, b and c`. */
|
|
2336
|
+
function listed(names) {
|
|
2337
|
+
return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
|
|
2338
|
+
}
|
|
2301
2339
|
function checkRolePermissions(candidate, verbs, workflows, report) {
|
|
2302
2340
|
const builtIn = candidate.name === MEMBER_ROLE;
|
|
2303
2341
|
const path = builtIn ? "member.permissions" : `roles.${candidate.name}.permissions`;
|
|
@@ -2327,10 +2365,7 @@ function checkRolePermissions(candidate, verbs, workflows, report) {
|
|
|
2327
2365
|
return;
|
|
2328
2366
|
}
|
|
2329
2367
|
if (parsed.entity === WILDCARD && parsed.verb === WILDCARD) {
|
|
2330
|
-
report("wildcard-permission", at,
|
|
2331
|
-
"agent_review, app_feedback, app_feedback_file, user_identity and " +
|
|
2332
|
-
`administering users (${USER_MEMBER_VERBS.map((verb) => `user:${verb}`).join(", ")} ` +
|
|
2333
|
-
"and user's authored actions), which only user:<verb> or user:* grants.", "warning");
|
|
2368
|
+
report("wildcard-permission", at, wildcardWarning(permissions), "warning");
|
|
2334
2369
|
return;
|
|
2335
2370
|
}
|
|
2336
2371
|
const problem = unknownPermission(`${parsed.entity}:${parsed.verb}`, parsed, verbs);
|
package/dist/feedback-config.js
CHANGED
|
@@ -73,17 +73,26 @@ export function feedbackRoles(options, files, roles, report) {
|
|
|
73
73
|
}
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
|
-
const resolved = roles.map((candidate) =>
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
const resolved = roles.map((candidate) => {
|
|
77
|
+
if (!builders.has(candidate.name)) {
|
|
78
|
+
return candidate;
|
|
79
|
+
}
|
|
80
|
+
const entries = roleEntries(Array.isArray(candidate.permissions) ? candidate.permissions : [], candidate.scopes ?? []);
|
|
81
|
+
// A builder reads and answers every item: add what the role does not already hold unscoped.
|
|
82
|
+
// A scoped grant of the same permission is widened, since the unscoped one covers it.
|
|
83
|
+
const unscoped = new Set(entries.flatMap((entry) => (typeof entry === "string" ? [normalizePermission(entry)] : [])));
|
|
84
|
+
return role(candidate.name, {
|
|
79
85
|
description: candidate.description,
|
|
80
86
|
permissions: [
|
|
81
|
-
...
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
87
|
+
...entries,
|
|
88
|
+
...[
|
|
89
|
+
"app_feedback:read",
|
|
90
|
+
"app_feedback:respond",
|
|
91
|
+
...(files ? ["app_feedback_file:read"] : []),
|
|
92
|
+
].filter((permission) => !unscoped.has(permission)),
|
|
85
93
|
],
|
|
86
|
-
})
|
|
94
|
+
});
|
|
95
|
+
});
|
|
87
96
|
const own = { reporter: { $me: [] } };
|
|
88
97
|
resolved.push(role(FEEDBACK_REPORTER_ROLE, {
|
|
89
98
|
description: "Implicit feedback authority of authenticated human members; never assigned.",
|
|
@@ -39,13 +39,19 @@ interface BaselineInput {
|
|
|
39
39
|
readonly newSource?: boolean;
|
|
40
40
|
}
|
|
41
41
|
/** Enable capture in a short fenced transaction before scanning any business records. */
|
|
42
|
-
export declare const prepareReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<ReplicationTarget,
|
|
42
|
+
export declare const prepareReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
|
|
43
|
+
readonly manifest: OntologyManifest;
|
|
44
|
+
}, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
|
|
43
45
|
/**
|
|
44
46
|
* Commit one keyset page and its cursor together. Schema 5 locks source rows before allocating
|
|
45
47
|
* snapshot revisions; older schemas retain their revision-zero baseline protocol. A failed page
|
|
46
48
|
* retries without changing earlier pages, and capture covers inserts/deletes across pages.
|
|
47
49
|
*/
|
|
48
|
-
export declare const advanceReplicationBaseline: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget,
|
|
50
|
+
export declare const advanceReplicationBaseline: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
|
|
51
|
+
readonly manifest: OntologyManifest;
|
|
52
|
+
}, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
|
|
49
53
|
/** Prepare once, then advance a bounded page; subsequent calls resume the same durable target. */
|
|
50
|
-
export declare const createReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<ReplicationTarget,
|
|
54
|
+
export declare const createReplicationBaseline: (sql: SqlClient.SqlClient, input: BaselineInput) => Effect.Effect<Omit<ReplicationTarget, "manifest" | "manifest_hash"> & {
|
|
55
|
+
readonly manifest: OntologyManifest;
|
|
56
|
+
}, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed, never>;
|
|
51
57
|
export {};
|
|
@@ -5,12 +5,13 @@ import { joinColumnNames, joinTableName, quoteIdentifier as qi, quoteLiteral as
|
|
|
5
5
|
import { REPLICATION_RECORD_BYTES, validateReplicationSelection, } from "./model.js";
|
|
6
6
|
import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA, snapshotExpression, } from "./schema.js";
|
|
7
7
|
import { lockReplicationLifecycle, shareReplicationLifecycle } from "./transaction.js";
|
|
8
|
+
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
8
9
|
import { initialReplicationLineage } from "./lineage.js";
|
|
9
10
|
import { scheduleReplicationScans, replicationScanScopes, advanceReplicationScan, } from "./scans.js";
|
|
10
11
|
/** An initial scan cannot be created with the requested state or record projection. */
|
|
11
12
|
export class ReplicationBaselineFailed extends Schema.TaggedError()("ReplicationBaselineFailed", { message: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
|
|
12
13
|
}
|
|
13
|
-
const targetSql = `SELECT generation::text, source_id::text, from_revision::text,
|
|
14
|
+
const targetSql = `SELECT generation::text, source_id::text, from_revision::text, ${TARGET_MANIFEST_HASH},
|
|
14
15
|
selection, protocol, baseline_complete, backfill_complete, initial_revision::text,
|
|
15
16
|
${REPLICATION_TARGET_FILLS}, ${REPLICATION_TARGET_METADATA}, replay_complete, baseline_cursor
|
|
16
17
|
FROM _ontology_replication_targets WHERE generation = $1::uuid`;
|
|
@@ -25,7 +26,9 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
|
|
|
25
26
|
message: "Run the ontology SDK migration before enabling replication.",
|
|
26
27
|
});
|
|
27
28
|
}
|
|
28
|
-
const [existing] = yield* sql
|
|
29
|
+
const [existing] = yield* storedTargets(sql, targetSql, [
|
|
30
|
+
input.generation,
|
|
31
|
+
]);
|
|
29
32
|
if (existing) {
|
|
30
33
|
return existing;
|
|
31
34
|
}
|
|
@@ -72,7 +75,7 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
|
|
|
72
75
|
initial: true,
|
|
73
76
|
});
|
|
74
77
|
}
|
|
75
|
-
const [target] = yield* sql
|
|
78
|
+
const [target] = yield* storedTargets(sql, targetSql, [input.generation]);
|
|
76
79
|
if (state.version >= 6) {
|
|
77
80
|
yield* enableShadowCapture(sql, target, replicationScanScopes(target));
|
|
78
81
|
}
|
|
@@ -129,14 +132,14 @@ export const advanceReplicationBaseline = (sql, generation) => Effect.gen(functi
|
|
|
129
132
|
const [version] = yield* sql.unsafe("SELECT version FROM _ontology_replication WHERE id");
|
|
130
133
|
if ((version?.version ?? 4) >= 5) {
|
|
131
134
|
yield* advanceReplicationScan(sql, generation);
|
|
132
|
-
const [target] = yield* sql
|
|
135
|
+
const [target] = yield* storedTargets(sql, targetSql, [generation]);
|
|
133
136
|
return target;
|
|
134
137
|
}
|
|
135
138
|
const progress = yield* sql.withTransaction(Effect.gen(function* () {
|
|
136
139
|
yield* sql.unsafe("SET LOCAL statement_timeout = '30s'");
|
|
137
140
|
yield* sql.unsafe("SET LOCAL lock_timeout = '5s'");
|
|
138
141
|
yield* shareReplicationLifecycle(sql);
|
|
139
|
-
const [target] = yield* sql
|
|
142
|
+
const [target] = yield* storedTargets(sql, `${targetSql} FOR NO KEY UPDATE`, [generation]);
|
|
140
143
|
if (!target) {
|
|
141
144
|
return yield* new ReplicationBaselineFailed({
|
|
142
145
|
message: "The replication target is missing.",
|
|
@@ -205,7 +208,7 @@ export const advanceReplicationBaseline = (sql, generation) => Effect.gen(functi
|
|
|
205
208
|
yield* sql.unsafe(`UPDATE _ontology_replication_targets SET baseline_complete = true,
|
|
206
209
|
initial_revision = (SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM _ontology_replication_revision)
|
|
207
210
|
WHERE generation = $1::uuid AND NOT baseline_complete`, [generation]);
|
|
208
|
-
const [target] = yield* sql
|
|
211
|
+
const [target] = yield* storedTargets(sql, targetSql, [generation]);
|
|
209
212
|
return target;
|
|
210
213
|
}));
|
|
211
214
|
});
|
|
@@ -4,6 +4,7 @@ import { joinColumnNames, joinTableName, quoteIdentifier as qi, quoteLiteral as
|
|
|
4
4
|
import { REPLICATION_RECORD_BYTES } from "./model.js";
|
|
5
5
|
import { snapshotExpression } from "./schema.js";
|
|
6
6
|
import { lockReplicationLifecycle, shareReplicationLifecycle } from "./transaction.js";
|
|
7
|
+
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
7
8
|
export function replicationScanScopes(target) {
|
|
8
9
|
return target.selection.flatMap((item) => [
|
|
9
10
|
{ entityId: item.entityId, kind: "entity" },
|
|
@@ -58,7 +59,8 @@ export const advanceReplicationScan = (sql, generation) => Effect.gen(function*
|
|
|
58
59
|
yield* sql.unsafe("SET LOCAL statement_timeout = '30s'");
|
|
59
60
|
yield* sql.unsafe("SET LOCAL lock_timeout = '5s'");
|
|
60
61
|
yield* shareReplicationLifecycle(sql);
|
|
61
|
-
const [target] = yield* sql
|
|
62
|
+
const [target] = yield* storedTargets(sql, `SELECT generation::text, source_id::text, selection, ${TARGET_MANIFEST_HASH}
|
|
63
|
+
FROM _ontology_replication_targets WHERE generation = $1::uuid FOR NO KEY UPDATE`, [generation]);
|
|
62
64
|
const [state] = yield* sql.unsafe("SELECT enabled, active_generation::text, version FROM _ontology_replication WHERE id");
|
|
63
65
|
if (!target || !state?.enabled || state.active_generation !== generation) {
|
|
64
66
|
return { finish: false, progressed: false };
|
|
@@ -7,11 +7,13 @@ import { ReplicationBaselineFailed } from "./baseline.js";
|
|
|
7
7
|
import { initialReplicationLineage, renamedReplicationField } from "./lineage.js";
|
|
8
8
|
import { replicationScanScopes, scheduleReplicationScans, } from "./scans.js";
|
|
9
9
|
import { lockReplicationLifecycle } from "./transaction.js";
|
|
10
|
+
import { rememberJson, rememberedJson } from "./stored-manifests.js";
|
|
10
11
|
export const SHADOW_HANDOFF_MS = 30_000;
|
|
11
12
|
export const SHADOW_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
12
13
|
export const SHADOW_QUERY_LIFETIME_MS = 60 * 60 * 1000;
|
|
13
14
|
const shadowJson = (value) => JSON.stringify(value, (_key, item) => (typeof item === "bigint" ? item.toString() : item));
|
|
14
|
-
|
|
15
|
+
/** An epoch's state; its target and routes, which never change after insert, are read apart. */
|
|
16
|
+
const epochFields = `id::text, source_id::text, desired_hash, state,
|
|
15
17
|
predecessor::text, boundary::text, catchup_boundary::text, token::text, fence::text,
|
|
16
18
|
handoff_until::text, operation_id::text, installed, cancel_requested`;
|
|
17
19
|
const segmentFields = `id::text, epoch::text, generation::text, source_id::text,
|
|
@@ -82,17 +84,38 @@ export function expandShadowRoutes(routes, target) {
|
|
|
82
84
|
return { ...route, target: expanded };
|
|
83
85
|
});
|
|
84
86
|
}
|
|
85
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Completes an epoch's state with its target and expanded routes. They hold whole manifests and
|
|
89
|
+
* never change after insert, so a process reads them once per epoch (see `stored-manifests.ts`).
|
|
90
|
+
* An epoch removed between the two reads is read as absent.
|
|
91
|
+
*/
|
|
92
|
+
const expandEpoch = (sql, row) => Effect.gen(function* () {
|
|
93
|
+
if (!row) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
const key = `epoch:${row.id}:${row.desired_hash}`;
|
|
97
|
+
let body = rememberedJson(key);
|
|
98
|
+
if (!body) {
|
|
99
|
+
const [stored] = yield* sql.unsafe("SELECT target, routes FROM _ontology_replication_epochs WHERE id=$1::uuid", [row.id]);
|
|
100
|
+
if (!stored) {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
body = stored;
|
|
104
|
+
rememberJson(key, body);
|
|
105
|
+
}
|
|
106
|
+
const target = { ...body.target };
|
|
107
|
+
return { ...row, target, routes: expandShadowRoutes(body.routes, target) };
|
|
108
|
+
});
|
|
86
109
|
export const shadowEpoch = (sql, id) => sql
|
|
87
110
|
.unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs WHERE id=$1::uuid`, [id])
|
|
88
|
-
.pipe(Effect.
|
|
111
|
+
.pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
|
|
89
112
|
export const servingShadowEpoch = (sql) => sql
|
|
90
113
|
.unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs
|
|
91
114
|
WHERE id=(SELECT serving_epoch FROM _ontology_replication WHERE id)`)
|
|
92
|
-
.pipe(Effect.
|
|
115
|
+
.pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
|
|
93
116
|
export const candidateShadowEpoch = (sql) => sql
|
|
94
117
|
.unsafe(`SELECT ${epochFields} FROM _ontology_replication_epochs WHERE state='candidate'`)
|
|
95
|
-
.pipe(Effect.
|
|
118
|
+
.pipe(Effect.flatMap((rows) => expandEpoch(sql, rows[0])));
|
|
96
119
|
export const shadowProjectionHash = (target) => createHash("sha256")
|
|
97
120
|
.update(canonicalJson({
|
|
98
121
|
manifest: target.manifest.hash,
|
|
@@ -341,7 +364,7 @@ export const beginShadowHandoff = (sql, id, owner, minimumFence = "0") => sql.wi
|
|
|
341
364
|
AND id=(SELECT active_generation FROM _ontology_replication WHERE id AND enabled)
|
|
342
365
|
AND NOT EXISTS(SELECT 1 FROM _ontology_replication_scans WHERE generation=$1::uuid AND NOT complete)
|
|
343
366
|
RETURNING ${epochFields}`, [id, owner]);
|
|
344
|
-
return expandEpoch(epoch);
|
|
367
|
+
return yield* expandEpoch(sql, epoch);
|
|
345
368
|
}));
|
|
346
369
|
/** Destination invalidation must have succeeded (or switched) before this transaction runs. */
|
|
347
370
|
export const abandonShadowHandoff = (sql, epoch) => sql.withTransaction(Effect.gen(function* () {
|
|
@@ -9,9 +9,9 @@ export declare const startReplication: (sql: SqlClient.SqlClient, input: {
|
|
|
9
9
|
readonly selection?: ReadonlyArray<ReplicationSelection>;
|
|
10
10
|
readonly newSource?: boolean;
|
|
11
11
|
}) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError | ReplicationBaselineFailed | import("../index.js").CatalogInvalid | import("./legacy-baseline.js").ReplicationBaselineFailed, never>;
|
|
12
|
-
export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
12
|
+
export declare const activeReplicationTarget: (sql: SqlClient.SqlClient) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
13
13
|
export declare const pauseReplication: (sql: SqlClient.SqlClient) => Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
14
|
-
export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
14
|
+
export declare const replicationTarget: (sql: SqlClient.SqlClient, generation: string) => Effect.Effect<ReplicationTarget | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
15
15
|
export { advanceReplicationBaseline };
|
|
16
16
|
export { replicationInitiallyReady as legacyReplicationInitiallyReady } from "./legacy-store.js";
|
|
17
17
|
/** Retained history is recovery storage; frequent delivery reads only indexed unaccepted references. */
|
|
@@ -12,6 +12,7 @@ import { createReplicationBaseline, advanceReplicationBaseline, ReplicationBasel
|
|
|
12
12
|
import { effectiveReplicationExclusions, migratedReplicationFills } from "./migrate.js";
|
|
13
13
|
import { refreshReplicationProjection } from "./evolution.js";
|
|
14
14
|
import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA } from "./schema.js";
|
|
15
|
+
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
15
16
|
const replicationPolicyKey = (policy) => JSON.stringify(policy
|
|
16
17
|
.map((item) => ({
|
|
17
18
|
entityId: item.entityId,
|
|
@@ -102,7 +103,7 @@ export const startReplication = (sql, input) => Effect.gen(function* () {
|
|
|
102
103
|
? createReplicationBaseline(sql, { ...input, manifest, selection })
|
|
103
104
|
: createLegacyBaseline(sql, { ...input, manifest, selection }).pipe(Effect.map((target) => target));
|
|
104
105
|
}).pipe(Effect.map((target) => target));
|
|
105
|
-
const targetFields = `generation::text, source_id::text, from_revision::text,
|
|
106
|
+
const targetFields = `generation::text, source_id::text, from_revision::text, ${TARGET_MANIFEST_HASH}, selection,
|
|
106
107
|
protocol, baseline_complete, backfill_complete, initial_revision::text, replay_complete,
|
|
107
108
|
${REPLICATION_TARGET_FILLS}, ${REPLICATION_TARGET_METADATA}, 4 AS delivery_version`;
|
|
108
109
|
const protocol = (sql) => sql
|
|
@@ -113,8 +114,11 @@ export const activeReplicationTarget = (sql) => Effect.gen(function* () {
|
|
|
113
114
|
const fields = version >= 4
|
|
114
115
|
? targetFields
|
|
115
116
|
: "generation::text, source_id::text, from_revision::text, manifest, selection";
|
|
116
|
-
const
|
|
117
|
-
WHERE generation = (SELECT active_generation FROM _ontology_replication WHERE id)
|
|
117
|
+
const statement = `SELECT ${fields} FROM _ontology_replication_targets
|
|
118
|
+
WHERE generation = (SELECT active_generation FROM _ontology_replication WHERE id)`;
|
|
119
|
+
const rows = version >= 4
|
|
120
|
+
? yield* storedTargets(sql, statement)
|
|
121
|
+
: yield* sql.unsafe(statement);
|
|
118
122
|
return rows[0];
|
|
119
123
|
});
|
|
120
124
|
export const pauseReplication = (sql) => sql.withTransaction(Effect.gen(function* () {
|
|
@@ -126,7 +130,10 @@ export const replicationTarget = (sql, generation) => Effect.gen(function* () {
|
|
|
126
130
|
const fields = version >= 4
|
|
127
131
|
? targetFields
|
|
128
132
|
: "generation::text, source_id::text, from_revision::text, manifest, selection";
|
|
129
|
-
const
|
|
133
|
+
const statement = `SELECT ${fields} FROM _ontology_replication_targets WHERE generation = $1::uuid`;
|
|
134
|
+
const rows = version >= 4
|
|
135
|
+
? yield* storedTargets(sql, statement, [generation])
|
|
136
|
+
: yield* sql.unsafe(statement, [generation]);
|
|
130
137
|
return rows[0];
|
|
131
138
|
});
|
|
132
139
|
export { advanceReplicationBaseline };
|
|
@@ -309,7 +316,7 @@ export const advanceReplicationReplay = (sql, generation) => sql.withTransaction
|
|
|
309
316
|
/** Static pre-upgrade histories have no new inserts: v4 writers atomically enqueue new history. */
|
|
310
317
|
export const advanceReplicationBackfill = (sql, generation) => sql.withTransaction(Effect.gen(function* () {
|
|
311
318
|
yield* shareReplicationLifecycle(sql);
|
|
312
|
-
const [target] = yield* sql
|
|
319
|
+
const [target] = yield* storedTargets(sql, `SELECT ${targetFields}, backfill_cursor, backfill_revision::text
|
|
313
320
|
FROM _ontology_replication_targets WHERE generation = $1::uuid FOR NO KEY UPDATE`, [generation]);
|
|
314
321
|
if (!target || target.backfill_complete) {
|
|
315
322
|
return true;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { SqlClient } from "effect/unstable/sql";
|
|
3
|
+
import type { OntologyManifest } from "../manifest.js";
|
|
4
|
+
/** The value stored under a key, marked as most recently used; undefined when not remembered. */
|
|
5
|
+
export declare function rememberedJson<A>(key: string): A | undefined;
|
|
6
|
+
/** Keep a value under a key, evicting the least recently used entries past the length bound. */
|
|
7
|
+
export declare function rememberJson(key: string, value: unknown): void;
|
|
8
|
+
/** Forget every remembered value; for tests that reuse ids across databases. */
|
|
9
|
+
export declare function forgetStoredManifests(): void;
|
|
10
|
+
/** Selects a target's manifest hash in place of its manifest; `storedTargets` restores it. */
|
|
11
|
+
export declare const TARGET_MANIFEST_HASH = "manifest->>'hash' AS manifest_hash";
|
|
12
|
+
type WithManifest<T> = Omit<T, "manifest_hash" | "manifest"> & {
|
|
13
|
+
readonly manifest: OntologyManifest;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Run a target read that selects `TARGET_MANIFEST_HASH` (and `generation`) instead of the manifest,
|
|
17
|
+
* and return its rows with the manifest restored: from memory for a generation and hash already
|
|
18
|
+
* read, otherwise from the target row itself. A migration can change a target between the read and
|
|
19
|
+
* its manifest's read; the whole read is then repeated, so a target never pairs one version's
|
|
20
|
+
* fields with another version's manifest.
|
|
21
|
+
*/
|
|
22
|
+
export declare const storedTargets: <T extends {
|
|
23
|
+
readonly generation: string;
|
|
24
|
+
}>(sql: SqlClient.SqlClient, statement: string, parameters?: ReadonlyArray<unknown>) => Effect.Effect<WithManifest<T>[], import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
/**
|
|
3
|
+
* A replication target carries the workspace's whole manifest, megabytes for a large ontology, and
|
|
4
|
+
* replication reads its targets and epochs on every pass, page and bound query. A stored target's
|
|
5
|
+
* manifest changes only together with its hash, and an epoch's target and routes never change after
|
|
6
|
+
* the epoch is inserted. Readers therefore select the hash or the epoch's identity instead, and take
|
|
7
|
+
* the large JSON from this process's memory, reading it from the database once per process for each
|
|
8
|
+
* one it has not seen. Keys hold the generation or epoch id, so no two workspaces share an entry.
|
|
9
|
+
*/
|
|
10
|
+
/** The JSON length a process keeps; a large ontology's target and epoch fit many times over. */
|
|
11
|
+
const REMEMBERED_LENGTH = 64 * 1024 * 1024;
|
|
12
|
+
const remembered = new Map();
|
|
13
|
+
let rememberedLength = 0;
|
|
14
|
+
/** The value stored under a key, marked as most recently used; undefined when not remembered. */
|
|
15
|
+
export function rememberedJson(key) {
|
|
16
|
+
const entry = remembered.get(key);
|
|
17
|
+
if (entry === undefined) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
remembered.delete(key);
|
|
21
|
+
remembered.set(key, entry);
|
|
22
|
+
return entry.value;
|
|
23
|
+
}
|
|
24
|
+
/** Keep a value under a key, evicting the least recently used entries past the length bound. */
|
|
25
|
+
export function rememberJson(key, value) {
|
|
26
|
+
const length = JSON.stringify(value)?.length ?? 0;
|
|
27
|
+
const previous = remembered.get(key);
|
|
28
|
+
if (previous) {
|
|
29
|
+
remembered.delete(key);
|
|
30
|
+
rememberedLength -= previous.length;
|
|
31
|
+
}
|
|
32
|
+
if (length > REMEMBERED_LENGTH) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
remembered.set(key, { value, length });
|
|
36
|
+
rememberedLength += length;
|
|
37
|
+
for (const [oldest, entry] of remembered) {
|
|
38
|
+
if (rememberedLength <= REMEMBERED_LENGTH) {
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
remembered.delete(oldest);
|
|
42
|
+
rememberedLength -= entry.length;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Forget every remembered value; for tests that reuse ids across databases. */
|
|
46
|
+
export function forgetStoredManifests() {
|
|
47
|
+
remembered.clear();
|
|
48
|
+
rememberedLength = 0;
|
|
49
|
+
}
|
|
50
|
+
/** Selects a target's manifest hash in place of its manifest; `storedTargets` restores it. */
|
|
51
|
+
export const TARGET_MANIFEST_HASH = "manifest->>'hash' AS manifest_hash";
|
|
52
|
+
/** Reads of a target that a concurrent migration may change between its two statements. */
|
|
53
|
+
const CONSISTENT_READ_ATTEMPTS = 5;
|
|
54
|
+
/**
|
|
55
|
+
* Run a target read that selects `TARGET_MANIFEST_HASH` (and `generation`) instead of the manifest,
|
|
56
|
+
* and return its rows with the manifest restored: from memory for a generation and hash already
|
|
57
|
+
* read, otherwise from the target row itself. A migration can change a target between the read and
|
|
58
|
+
* its manifest's read; the whole read is then repeated, so a target never pairs one version's
|
|
59
|
+
* fields with another version's manifest.
|
|
60
|
+
*/
|
|
61
|
+
export const storedTargets = (sql, statement, parameters = []) => Effect.gen(function* () {
|
|
62
|
+
for (let attempt = 1; attempt <= CONSISTENT_READ_ATTEMPTS; attempt += 1) {
|
|
63
|
+
const targets = yield* readStoredTargets(sql, statement, parameters);
|
|
64
|
+
if (targets) {
|
|
65
|
+
return targets;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return yield* Effect.die(new Error("A replication target kept changing while it was read; the next pass retries."));
|
|
69
|
+
});
|
|
70
|
+
/** One attempt: the rows with their manifests, or undefined when a row changed between reads. */
|
|
71
|
+
const readStoredTargets = (sql, statement, parameters) => Effect.gen(function* () {
|
|
72
|
+
const rows = yield* sql.unsafe(statement, parameters);
|
|
73
|
+
const targets = [];
|
|
74
|
+
for (const row of rows) {
|
|
75
|
+
const { manifest_hash: hash, ...rest } = row;
|
|
76
|
+
const key = `target:${row.generation}:${hash}`;
|
|
77
|
+
let manifest = hash ? rememberedJson(key) : undefined;
|
|
78
|
+
if (!manifest) {
|
|
79
|
+
const [stored] = yield* sql.unsafe(`SELECT manifest, ${TARGET_MANIFEST_HASH} FROM _ontology_replication_targets
|
|
80
|
+
WHERE generation = $1::uuid`, [row.generation]);
|
|
81
|
+
// Removed or migrated since the first read: read the whole target again.
|
|
82
|
+
if (!stored || (stored.manifest_hash ?? null) !== (hash ?? null)) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
manifest = stored.manifest;
|
|
86
|
+
if (hash) {
|
|
87
|
+
rememberJson(key, manifest);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
targets.push({ ...rest, manifest });
|
|
91
|
+
}
|
|
92
|
+
return targets;
|
|
93
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.99.
|
|
3
|
+
"version": "0.99.2",
|
|
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",
|
|
@@ -69,6 +69,7 @@
|
|
|
69
69
|
"files": [
|
|
70
70
|
"dist",
|
|
71
71
|
"README.md",
|
|
72
|
+
"CHANGELOG.md",
|
|
72
73
|
"LICENSE",
|
|
73
74
|
"NOTICE"
|
|
74
75
|
],
|