@party-stack/ontology-backend 0.0.0-stage → 0.2.1
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/LICENSE +21 -0
- package/README.md +148 -2
- package/lib/actions.d.ts +47 -0
- package/lib/actions.d.ts.map +1 -0
- package/lib/actions.js +306 -0
- package/lib/actions.js.map +1 -0
- package/lib/clients.d.ts +236 -0
- package/lib/clients.d.ts.map +1 -0
- package/lib/clients.js +211 -0
- package/lib/clients.js.map +1 -0
- package/lib/delivery.d.ts +746 -0
- package/lib/delivery.d.ts.map +1 -0
- package/lib/delivery.js +863 -0
- package/lib/delivery.js.map +1 -0
- package/lib/description.d.ts +29 -0
- package/lib/description.d.ts.map +1 -0
- package/lib/description.js +28 -0
- package/lib/description.js.map +1 -0
- package/lib/encrypted.d.ts +41 -0
- package/lib/encrypted.d.ts.map +1 -0
- package/lib/encrypted.js +111 -0
- package/lib/encrypted.js.map +1 -0
- package/lib/errors.d.ts +106 -0
- package/lib/errors.d.ts.map +1 -0
- package/lib/errors.js +275 -0
- package/lib/errors.js.map +1 -0
- package/lib/fulfillment.d.ts +25 -0
- package/lib/fulfillment.d.ts.map +1 -0
- package/lib/fulfillment.js +99 -0
- package/lib/fulfillment.js.map +1 -0
- package/lib/index.d.ts +297 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +91 -0
- package/lib/index.js.map +1 -0
- package/lib/maintenance.d.ts +11 -0
- package/lib/maintenance.d.ts.map +1 -0
- package/lib/maintenance.js +24 -0
- package/lib/maintenance.js.map +1 -0
- package/lib/meta.d.ts +26 -0
- package/lib/meta.d.ts.map +1 -0
- package/lib/meta.js +213 -0
- package/lib/meta.js.map +1 -0
- package/lib/owned.d.ts +74 -0
- package/lib/owned.d.ts.map +1 -0
- package/lib/owned.js +593 -0
- package/lib/owned.js.map +1 -0
- package/lib/policy/indexes.d.ts +12 -0
- package/lib/policy/indexes.d.ts.map +1 -0
- package/lib/policy/indexes.js +113 -0
- package/lib/policy/indexes.js.map +1 -0
- package/lib/policy/planner.d.ts +10 -0
- package/lib/policy/planner.d.ts.map +1 -0
- package/lib/policy/planner.js +118 -0
- package/lib/policy/planner.js.map +1 -0
- package/lib/policy/view.d.ts +31 -0
- package/lib/policy/view.d.ts.map +1 -0
- package/lib/policy/view.js +173 -0
- package/lib/policy/view.js.map +1 -0
- package/lib/policy.d.ts +47 -0
- package/lib/policy.d.ts.map +1 -0
- package/lib/policy.js +100 -0
- package/lib/policy.js.map +1 -0
- package/lib/protocol.d.ts +570 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +144 -0
- package/lib/protocol.js.map +1 -0
- package/lib/query.d.ts +33 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +51 -0
- package/lib/query.js.map +1 -0
- package/lib/references.d.ts +8 -0
- package/lib/references.d.ts.map +1 -0
- package/lib/references.js +41 -0
- package/lib/references.js.map +1 -0
- package/lib/storage.d.ts +55 -0
- package/lib/storage.d.ts.map +1 -0
- package/lib/storage.js +168 -0
- package/lib/storage.js.map +1 -0
- package/lib/subset.d.ts +19 -0
- package/lib/subset.d.ts.map +1 -0
- package/lib/subset.js +150 -0
- package/lib/subset.js.map +1 -0
- package/lib/subsetSchema.d.ts +10 -0
- package/lib/subsetSchema.d.ts.map +1 -0
- package/lib/subsetSchema.js +20 -0
- package/lib/subsetSchema.js.map +1 -0
- package/package.json +72 -3
package/lib/owned.js
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { BackendError, classifyBackendFailure, schemaValidationIssues } from "./errors.js";
|
|
2
|
+
import { ActionReceiptSchema, BackendCommitSchema } from "./index.js";
|
|
3
|
+
import { compileObjectSubset } from "./subset.js";
|
|
4
|
+
import { executeQuery } from "./query.js";
|
|
5
|
+
import { makeDeliveryManager, scanSelectedRows } from "./delivery.js";
|
|
6
|
+
import { maintenanceInterval, scheduleMaintenance } from "./maintenance.js";
|
|
7
|
+
import { actionReferenceIssues } from "./references.js";
|
|
8
|
+
import { CurrentActionAuthorization, CurrentExecutionContext, CurrentQueryAuthorization } from "./policy.js";
|
|
9
|
+
import { setAtPath } from "@party-stack/ontology-spec/utils";
|
|
10
|
+
import { OntologyStorageError, field, indexesForQuery, lte, makeOntologyStorage, makeStorageModel, ontologyDefinitionContractSignature, or } from "@party-stack/ontology-storage";
|
|
11
|
+
import { Clock, Effect, PubSub, Redacted, Schema, Semaphore, Stream } from "effect";
|
|
12
|
+
import { byteSource, digestBytes } from "@party-stack/ontology-storage/blobs";
|
|
13
|
+
import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
|
|
14
|
+
import { Table } from "@party-stack/ontology-storage/tables";
|
|
15
|
+
//#region src/owned.ts
|
|
16
|
+
const fault = (operation, kind, message, cause) => new BackendError({
|
|
17
|
+
operation,
|
|
18
|
+
kind,
|
|
19
|
+
message,
|
|
20
|
+
retryable: false,
|
|
21
|
+
cause: cause === void 0 ? void 0 : Redacted.make(cause)
|
|
22
|
+
});
|
|
23
|
+
const boundary = (effect) => effect.pipe(Effect.mapError((error) => classifyBackendFailure("storage", error)));
|
|
24
|
+
const CursorSchema = Schema.Struct({
|
|
25
|
+
source: Schema.String,
|
|
26
|
+
revision: Schema.Int
|
|
27
|
+
});
|
|
28
|
+
const ReceiptSchema = Schema.Struct({
|
|
29
|
+
fingerprint: Schema.String,
|
|
30
|
+
receipt: ActionReceiptSchema,
|
|
31
|
+
completedAt: Schema.Finite
|
|
32
|
+
});
|
|
33
|
+
const JournalSchema = Schema.Struct({
|
|
34
|
+
revision: Schema.Int,
|
|
35
|
+
commit: BackendCommitSchema,
|
|
36
|
+
committedAt: Schema.Finite
|
|
37
|
+
});
|
|
38
|
+
const stableValue = (value) => {
|
|
39
|
+
if (Array.isArray(value)) return value.map(stableValue);
|
|
40
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => [key, stableValue(entry)]));
|
|
41
|
+
return value;
|
|
42
|
+
};
|
|
43
|
+
/** Authoritative local backend with atomic mutation batches, durable receipts, and a pull journal. */
|
|
44
|
+
const makeOwnedBackend = Effect.fnUntraced(function* (options) {
|
|
45
|
+
const schemas = yield* Effect.try({
|
|
46
|
+
try: () => compileEffectSchemas(options.ir),
|
|
47
|
+
catch: (cause) => fault("definition", "InvalidConfiguration", "Invalid ontology definition.", cause)
|
|
48
|
+
});
|
|
49
|
+
const objectSchemas = Object.fromEntries(Object.entries(schemas.objectSchemas).map(([name, schema]) => [name, Schema.toEncoded(schema)]));
|
|
50
|
+
const model = yield* boundary(makeStorageModel({
|
|
51
|
+
namespace: options.namespace,
|
|
52
|
+
ir: options.ir,
|
|
53
|
+
schemas: objectSchemas
|
|
54
|
+
}));
|
|
55
|
+
const storage = makeOntologyStorage(model, options.tables, { blobs: options.blobs });
|
|
56
|
+
const tables = options.tables;
|
|
57
|
+
const deliveries = yield* makeDeliveryManager({
|
|
58
|
+
tables,
|
|
59
|
+
namespace: options.namespace
|
|
60
|
+
});
|
|
61
|
+
const definitionSignature = yield* Effect.try({
|
|
62
|
+
try: () => ontologyDefinitionContractSignature(options.ir),
|
|
63
|
+
catch: (cause) => fault("definition", "InvalidConfiguration", "Invalid ontology definition.", cause)
|
|
64
|
+
});
|
|
65
|
+
const schemaHash = yield* boundary(digestBytes({
|
|
66
|
+
type: "application/json",
|
|
67
|
+
stream: Stream.make(new TextEncoder().encode(definitionSignature))
|
|
68
|
+
}));
|
|
69
|
+
const maxCommits = options.history?.maxCommits ?? 1e4;
|
|
70
|
+
if (maxCommits !== Infinity && !Number.isSafeInteger(maxCommits) || maxCommits < 1) return yield* fault("history", "InvalidConfiguration", "Journal retention requires a positive commit bound.");
|
|
71
|
+
const resultRetentionMs = options.resultRetentionMs ?? 6048e5;
|
|
72
|
+
const maintenanceIntervalMs = yield* maintenanceInterval(options.maintenance);
|
|
73
|
+
if (resultRetentionMs <= 0 || Number.isNaN(resultRetentionMs)) return yield* fault("retention", "InvalidConfiguration", "Result retention must be positive.");
|
|
74
|
+
if (options.history?.maxAgeMs !== void 0 && (options.history.maxAgeMs < 0 || Number.isNaN(options.history.maxAgeMs))) return yield* fault("retention", "InvalidConfiguration", "Journal retention age must be nonnegative.");
|
|
75
|
+
const receiptKey = (id, scope, legacy = false) => JSON.stringify([
|
|
76
|
+
options.actionScope ?? (legacy ? "system" : scope ?? "system"),
|
|
77
|
+
...scope === void 0 ? [] : [scope],
|
|
78
|
+
id
|
|
79
|
+
]);
|
|
80
|
+
const metadata = Table.make({ name: JSON.stringify([
|
|
81
|
+
"backend",
|
|
82
|
+
options.namespace,
|
|
83
|
+
"metadata"
|
|
84
|
+
]) });
|
|
85
|
+
const receipts = Table.make({
|
|
86
|
+
name: JSON.stringify([
|
|
87
|
+
"backend",
|
|
88
|
+
options.namespace,
|
|
89
|
+
"receipts"
|
|
90
|
+
]),
|
|
91
|
+
codec: {
|
|
92
|
+
encode: (value) => Schema.encodeSync(ReceiptSchema)(value),
|
|
93
|
+
decode: (value) => Schema.decodeUnknownSync(ReceiptSchema)(value)
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
const journal = Table.make({
|
|
97
|
+
name: JSON.stringify([
|
|
98
|
+
"backend",
|
|
99
|
+
options.namespace,
|
|
100
|
+
"journal"
|
|
101
|
+
]),
|
|
102
|
+
codec: {
|
|
103
|
+
encode: (value) => Schema.encodeSync(JournalSchema)(value),
|
|
104
|
+
decode: (value) => Schema.decodeUnknownSync(JournalSchema)(value)
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
let source = "";
|
|
108
|
+
const cursor = (revision) => JSON.stringify({
|
|
109
|
+
source,
|
|
110
|
+
revision
|
|
111
|
+
});
|
|
112
|
+
const parseCursor = Effect.fnUntraced(function* (encoded, current) {
|
|
113
|
+
if (encoded === void 0) return 0;
|
|
114
|
+
const parsed = yield* Effect.try({
|
|
115
|
+
try: () => Schema.decodeUnknownSync(Schema.fromJsonString(CursorSchema))(encoded),
|
|
116
|
+
catch: () => fault("changes", "HistoryExpired", "Invalid backend change cursor.")
|
|
117
|
+
});
|
|
118
|
+
if (parsed.source !== source) return yield* fault("changes", "SourceMismatch", "Change cursor belongs to a different source.");
|
|
119
|
+
if (!Number.isSafeInteger(parsed.revision) || parsed.revision < 0 || parsed.revision > current) return yield* fault("changes", "HistoryExpired", "Invalid backend change position.");
|
|
120
|
+
return parsed.revision;
|
|
121
|
+
});
|
|
122
|
+
const current = Effect.gen(function* () {
|
|
123
|
+
const last = yield* tables.query(journal, {
|
|
124
|
+
orderBy: [{
|
|
125
|
+
field: field("revision"),
|
|
126
|
+
direction: "desc"
|
|
127
|
+
}],
|
|
128
|
+
limit: 1
|
|
129
|
+
});
|
|
130
|
+
return Math.max(last[0]?.value.revision ?? 0, (yield* tables.get(metadata, "head"))?.revision ?? 0);
|
|
131
|
+
});
|
|
132
|
+
let initialRevision = 0;
|
|
133
|
+
const wakes = yield* PubSub.sliding(1);
|
|
134
|
+
yield* Effect.addFinalizer(() => PubSub.shutdown(wakes));
|
|
135
|
+
yield* boundary(storage.transaction((native) => Effect.gen(function* () {
|
|
136
|
+
yield* tables.ensureIndex(journal, {
|
|
137
|
+
name: "revision",
|
|
138
|
+
field: {
|
|
139
|
+
_tag: "Field",
|
|
140
|
+
path: ["revision"]
|
|
141
|
+
},
|
|
142
|
+
unique: true
|
|
143
|
+
});
|
|
144
|
+
for (const object of Object.values(model.objects)) yield* native.ensureIndex(object, {
|
|
145
|
+
name: "primaryKey",
|
|
146
|
+
field: {
|
|
147
|
+
_tag: "Field",
|
|
148
|
+
path: [object.definition.primaryKey]
|
|
149
|
+
},
|
|
150
|
+
unique: true
|
|
151
|
+
});
|
|
152
|
+
const head = yield* tables.get(metadata, "head");
|
|
153
|
+
source = head?.source ?? `${options.namespace}:${crypto.randomUUID()}`;
|
|
154
|
+
if (!head) yield* tables.put(metadata, "head", {
|
|
155
|
+
source,
|
|
156
|
+
revision: 0
|
|
157
|
+
});
|
|
158
|
+
initialRevision = yield* current;
|
|
159
|
+
})));
|
|
160
|
+
const object = (name) => {
|
|
161
|
+
const store = model.objects[name];
|
|
162
|
+
return store ? Effect.succeed(store) : Effect.fail(fault("object", "InvalidRequest", `Unknown object type ${JSON.stringify(name)}.`));
|
|
163
|
+
};
|
|
164
|
+
const read = (native) => ({
|
|
165
|
+
get: (name, key) => boundary(Effect.flatMap(object(name), (store) => native.get(store, key))),
|
|
166
|
+
loadSubset: (name, query) => boundary(Effect.flatMap(object(name), (store) => native.query(store, query))),
|
|
167
|
+
...native.queryGrouped ? { loadGroupedSubset: (name, partition, query) => boundary(Effect.flatMap(object(name), (store) => native.queryGrouped(store, partition, query))) } : {}
|
|
168
|
+
});
|
|
169
|
+
const mutation = (native) => {
|
|
170
|
+
const changes = /* @__PURE__ */ new Map();
|
|
171
|
+
const gate = Semaphore.makeUnsafe(1);
|
|
172
|
+
const put = (name, value) => boundary(Effect.gen(function* () {
|
|
173
|
+
const store = yield* object(name);
|
|
174
|
+
const key = value[store.definition.primaryKey];
|
|
175
|
+
changes.set(JSON.stringify([name, key]), {
|
|
176
|
+
kind: "put",
|
|
177
|
+
objectType: name,
|
|
178
|
+
key
|
|
179
|
+
});
|
|
180
|
+
yield* native.put(store, value);
|
|
181
|
+
}));
|
|
182
|
+
return {
|
|
183
|
+
tx: {
|
|
184
|
+
ensureIndex: (name, index) => boundary(Effect.flatMap(object(name), (store) => native.ensureIndex(store, index))),
|
|
185
|
+
...read(native),
|
|
186
|
+
patch: (name, key, patches) => boundary(Effect.gen(function* () {
|
|
187
|
+
const store = yield* object(name);
|
|
188
|
+
let value = yield* native.get(store, key);
|
|
189
|
+
if (!value) return yield* fault("patch", "NotFound", "Object not found.");
|
|
190
|
+
for (const patch of patches) {
|
|
191
|
+
if (!patch.path.length) return yield* fault("patch", "InvalidRequest", "Patch paths cannot be empty.");
|
|
192
|
+
value = yield* Effect.try({
|
|
193
|
+
try: () => setAtPath(value, patch.path, patch.value),
|
|
194
|
+
catch: (cause) => fault("patch", "InvalidRequest", "Invalid patch path.", cause)
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
if (value[store.definition.primaryKey] !== key) return yield* fault("patch", "InvalidRequest", "Patches cannot change an object's identity.");
|
|
198
|
+
yield* put(name, value);
|
|
199
|
+
})).pipe(gate.withPermits(1)),
|
|
200
|
+
put: (name, value) => gate.withPermits(1)(put(name, value)),
|
|
201
|
+
delete: (name, key) => boundary(Effect.gen(function* () {
|
|
202
|
+
const store = yield* object(name);
|
|
203
|
+
changes.set(JSON.stringify([name, key]), {
|
|
204
|
+
kind: "delete",
|
|
205
|
+
objectType: name,
|
|
206
|
+
key
|
|
207
|
+
});
|
|
208
|
+
yield* native.delete(store, key);
|
|
209
|
+
})).pipe(gate.withPermits(1))
|
|
210
|
+
},
|
|
211
|
+
changes
|
|
212
|
+
};
|
|
213
|
+
};
|
|
214
|
+
const append = Effect.fnUntraced(function* (native, changes, operationId) {
|
|
215
|
+
const published = yield* Effect.forEach(changes.values(), (change) => Effect.gen(function* () {
|
|
216
|
+
if (change.kind === "delete") return {
|
|
217
|
+
...change,
|
|
218
|
+
kind: "delete"
|
|
219
|
+
};
|
|
220
|
+
const value = yield* read(native).get(change.objectType, change.key);
|
|
221
|
+
if (value === void 0) return yield* fault("commit", "Internal", "A written object is unavailable during publication.");
|
|
222
|
+
return {
|
|
223
|
+
...change,
|
|
224
|
+
kind: "put",
|
|
225
|
+
value
|
|
226
|
+
};
|
|
227
|
+
}));
|
|
228
|
+
const revision = yield* tables.allocateRevision(journal.name, initialRevision);
|
|
229
|
+
if (!Number.isSafeInteger(revision)) return yield* fault("commit", "Unavailable", "Backend journal revision exhausted.");
|
|
230
|
+
const encodedCursor = cursor(revision);
|
|
231
|
+
const commit = {
|
|
232
|
+
cursor: encodedCursor,
|
|
233
|
+
operationId,
|
|
234
|
+
changes: published
|
|
235
|
+
};
|
|
236
|
+
if (!(yield* tables.insert(journal, revision, {
|
|
237
|
+
revision,
|
|
238
|
+
commit,
|
|
239
|
+
committedAt: yield* Clock.currentTimeMillis
|
|
240
|
+
}))) return yield* fault("commit", "Internal", "Publication revision was already committed.");
|
|
241
|
+
const journalFloor = Math.max(0, Number.isFinite(maxCommits) ? revision - maxCommits : 0);
|
|
242
|
+
if (journalFloor > 0) for (const row of yield* tables.query(journal, {
|
|
243
|
+
where: lte(field("revision"), journalFloor),
|
|
244
|
+
orderBy: [{ field: field("revision") }],
|
|
245
|
+
limit: 100
|
|
246
|
+
})) yield* tables.delete(journal, row.key);
|
|
247
|
+
return encodedCursor;
|
|
248
|
+
});
|
|
249
|
+
const trustedStorage = {
|
|
250
|
+
ir: options.ir,
|
|
251
|
+
read: (body) => storage.read((native) => body(read(native))).pipe(Effect.mapError((error) => error instanceof OntologyStorageError ? classifyBackendFailure("storage", error) : error)),
|
|
252
|
+
transaction: (body) => Effect.gen(function* () {
|
|
253
|
+
const result = yield* storage.transaction((native) => Effect.gen(function* () {
|
|
254
|
+
const { tx, changes } = mutation(native);
|
|
255
|
+
const value = yield* body(tx);
|
|
256
|
+
if (changes.size) yield* append(native, changes);
|
|
257
|
+
return {
|
|
258
|
+
value,
|
|
259
|
+
changed: changes.size > 0
|
|
260
|
+
};
|
|
261
|
+
})).pipe(Effect.mapError((error) => error instanceof OntologyStorageError ? classifyBackendFailure("storage", error) : error));
|
|
262
|
+
if (result.changed) yield* PubSub.publish(wakes, void 0);
|
|
263
|
+
return result.value;
|
|
264
|
+
})
|
|
265
|
+
};
|
|
266
|
+
const prepare = Effect.fn("OwnedBackend.prepare")(function* (invocation) {
|
|
267
|
+
const authorization = yield* CurrentActionAuthorization;
|
|
268
|
+
const parameterSchema = authorization ? authorization.parameterSchemas[invocation.name] : schemas.actionParameterSchemas[invocation.name];
|
|
269
|
+
if (!parameterSchema) return yield* fault("applyAction", "InvalidRequest", "Unknown action type.");
|
|
270
|
+
if (!options.mutators[invocation.name]) return yield* fault("applyAction", "NotImplemented", `No action implementation for ${JSON.stringify(invocation.name)}.`);
|
|
271
|
+
if (!invocation.id) return yield* fault("applyAction", "InvalidRequest", "Actions require a stable invocation ID.");
|
|
272
|
+
const encodedParameters = yield* Schema.encodeEffect(Schema.toCodecJson(Schema.toEncoded(parameterSchema)))(invocation.parameters).pipe(Effect.mapError((error) => new BackendError({
|
|
273
|
+
operation: "applyAction",
|
|
274
|
+
kind: "ValidationFailed",
|
|
275
|
+
message: "Action parameters do not match their definition.",
|
|
276
|
+
retryable: false,
|
|
277
|
+
actionOutcome: "not-committed",
|
|
278
|
+
issues: schemaValidationIssues(error)
|
|
279
|
+
})));
|
|
280
|
+
const attachmentIdentity = yield* Effect.forEach(invocation.attachmentUploads ?? [], (upload) => digestBytes(upload.blob).pipe(Effect.map((digest) => ({
|
|
281
|
+
id: upload.attachment.id,
|
|
282
|
+
target: upload.target,
|
|
283
|
+
type: byteSource(upload.blob).type,
|
|
284
|
+
size: byteSource(upload.blob).size,
|
|
285
|
+
digest
|
|
286
|
+
})), Effect.mapError((cause) => fault("upload", "InvalidRequest", "Cannot identify attachment bytes.", cause))));
|
|
287
|
+
const identity = JSON.stringify(stableValue([
|
|
288
|
+
invocation.name,
|
|
289
|
+
encodedParameters,
|
|
290
|
+
attachmentIdentity,
|
|
291
|
+
invocation.replay
|
|
292
|
+
]));
|
|
293
|
+
const key = receiptKey(invocation.id, authorization?.scope);
|
|
294
|
+
const legacyKey = receiptKey(invocation.id, authorization?.scope, true);
|
|
295
|
+
return {
|
|
296
|
+
invocation,
|
|
297
|
+
identity,
|
|
298
|
+
receiptKey: key,
|
|
299
|
+
legacyReceiptKey: key === legacyKey ? void 0 : legacyKey
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
const invokeIn = Effect.fnUntraced(function* (native, prepared, commitUploads) {
|
|
303
|
+
const { invocation } = prepared;
|
|
304
|
+
const action = options.ir.actionTypes.find((candidate) => candidate.name === invocation.name);
|
|
305
|
+
const mutator = options.mutators[invocation.name];
|
|
306
|
+
if (!action || !mutator) return yield* fault("applyAction", "NotImplemented", `No action implementation for ${JSON.stringify(invocation.name)}.`);
|
|
307
|
+
if (!invocation.id) return yield* fault("applyAction", "InvalidRequest", "Actions require a stable invocation ID.");
|
|
308
|
+
const fingerprint = prepared.identity;
|
|
309
|
+
const previous = (yield* tables.get(receipts, prepared.receiptKey, { forUpdate: true })) ?? (prepared.legacyReceiptKey ? yield* tables.get(receipts, prepared.legacyReceiptKey, { forUpdate: true }) : void 0);
|
|
310
|
+
if (previous && previous.completedAt > (yield* Clock.currentTimeMillis) - resultRetentionMs) {
|
|
311
|
+
if (previous.fingerprint !== fingerprint) return yield* fault("applyAction", "Conflict", "An invocation ID was reused with different parameters.");
|
|
312
|
+
return {
|
|
313
|
+
receipt: previous.receipt,
|
|
314
|
+
changed: false
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const authorize = yield* CurrentActionAuthorization;
|
|
318
|
+
const authorization = authorize ? yield* authorize.apply(read(native), invocation) : void 0;
|
|
319
|
+
const permittedRead = authorization?.read ?? read(native);
|
|
320
|
+
const parameters = yield* Schema.decodeUnknownEffect(Schema.toEncoded(schemas.actionParameterSchemas[invocation.name]))(authorization?.parameters ?? invocation.parameters).pipe(Effect.mapError((error) => new BackendError({
|
|
321
|
+
operation: "applyAction",
|
|
322
|
+
kind: "ValidationFailed",
|
|
323
|
+
message: "Action parameters do not match their definition.",
|
|
324
|
+
retryable: false,
|
|
325
|
+
actionOutcome: "not-committed",
|
|
326
|
+
issues: schemaValidationIssues(error)
|
|
327
|
+
})));
|
|
328
|
+
const issues = yield* actionReferenceIssues(options.ir, action.parameters, parameters, permittedRead);
|
|
329
|
+
if (issues.length) return yield* new BackendError({
|
|
330
|
+
operation: "applyAction",
|
|
331
|
+
kind: "ValidationFailed",
|
|
332
|
+
message: "Submission failed validation.",
|
|
333
|
+
retryable: false,
|
|
334
|
+
actionOutcome: "not-committed",
|
|
335
|
+
issues
|
|
336
|
+
});
|
|
337
|
+
const { tx, changes } = mutation(native);
|
|
338
|
+
const returned = yield* mutator({
|
|
339
|
+
...tx,
|
|
340
|
+
...permittedRead
|
|
341
|
+
}, {
|
|
342
|
+
...invocation,
|
|
343
|
+
parameters
|
|
344
|
+
});
|
|
345
|
+
const resultSchema = schemas.actionReturnSchemas[invocation.name];
|
|
346
|
+
const result = resultSchema ? yield* Schema.encodeEffect(Schema.toCodecJson(resultSchema))(returned).pipe(Effect.mapError((cause) => new BackendError({
|
|
347
|
+
operation: "applyAction.result",
|
|
348
|
+
kind: "InvalidResponse",
|
|
349
|
+
retryable: false,
|
|
350
|
+
actionOutcome: "not-committed",
|
|
351
|
+
message: "Action result does not match its definition.",
|
|
352
|
+
cause: Redacted.make(cause)
|
|
353
|
+
}))) : void 0;
|
|
354
|
+
yield* commitUploads;
|
|
355
|
+
const affected = /* @__PURE__ */ new Map();
|
|
356
|
+
for (const change of changes.values()) {
|
|
357
|
+
const keys = affected.get(change.objectType) ?? /* @__PURE__ */ new Set();
|
|
358
|
+
keys.add(change.key);
|
|
359
|
+
affected.set(change.objectType, keys);
|
|
360
|
+
}
|
|
361
|
+
const receipt = {
|
|
362
|
+
affected: [...affected].map(([objectType, keys]) => ({
|
|
363
|
+
objectType,
|
|
364
|
+
keys: [...keys]
|
|
365
|
+
})),
|
|
366
|
+
affectedComplete: true,
|
|
367
|
+
operationId: invocation.id,
|
|
368
|
+
outcome: "committed",
|
|
369
|
+
...resultSchema ? { result } : {},
|
|
370
|
+
cursor: yield* append(native, changes, invocation.id)
|
|
371
|
+
};
|
|
372
|
+
yield* tables.put(receipts, prepared.receiptKey, {
|
|
373
|
+
fingerprint,
|
|
374
|
+
receipt,
|
|
375
|
+
completedAt: yield* Clock.currentTimeMillis
|
|
376
|
+
});
|
|
377
|
+
return {
|
|
378
|
+
receipt,
|
|
379
|
+
changed: true
|
|
380
|
+
};
|
|
381
|
+
});
|
|
382
|
+
yield* boundary(tables.transaction((tx) => Effect.gen(function* () {
|
|
383
|
+
yield* tx.ensureIndex(receipts, {
|
|
384
|
+
name: "completedAt",
|
|
385
|
+
field: field("completedAt")
|
|
386
|
+
});
|
|
387
|
+
yield* tx.ensureIndex(journal, {
|
|
388
|
+
name: "committedAt",
|
|
389
|
+
field: field("committedAt")
|
|
390
|
+
});
|
|
391
|
+
})));
|
|
392
|
+
const hasGarbage = tables.read((tx) => Effect.gen(function* () {
|
|
393
|
+
const now = yield* Clock.currentTimeMillis;
|
|
394
|
+
if (Number.isFinite(resultRetentionMs)) {
|
|
395
|
+
if ((yield* tx.query(receipts, {
|
|
396
|
+
where: lte(field("completedAt"), now - resultRetentionMs),
|
|
397
|
+
limit: 1
|
|
398
|
+
})).length) return true;
|
|
399
|
+
}
|
|
400
|
+
const floor = Number.isFinite(maxCommits) ? (yield* current) - maxCommits : 0;
|
|
401
|
+
const expired = [lte(field("revision"), floor)];
|
|
402
|
+
if (options.history?.maxAgeMs !== void 0 && Number.isFinite(options.history.maxAgeMs)) expired.push(lte(field("committedAt"), now - options.history.maxAgeMs));
|
|
403
|
+
return (yield* tx.query(journal, {
|
|
404
|
+
where: or(...expired),
|
|
405
|
+
limit: 1
|
|
406
|
+
})).length > 0;
|
|
407
|
+
}));
|
|
408
|
+
const collectGarbage = boundary(Effect.flatMap(hasGarbage, (needed) => needed ? tables.transaction((tx) => Effect.gen(function* () {
|
|
409
|
+
const now = yield* Clock.currentTimeMillis;
|
|
410
|
+
if (Number.isFinite(resultRetentionMs)) for (const row of yield* tx.query(receipts, {
|
|
411
|
+
where: lte(field("completedAt"), now - resultRetentionMs),
|
|
412
|
+
limit: 100
|
|
413
|
+
})) yield* tx.delete(receipts, row.key);
|
|
414
|
+
const revision = yield* current;
|
|
415
|
+
const floor = Number.isFinite(maxCommits) ? revision - maxCommits : 0;
|
|
416
|
+
const conditions = [lte(field("revision"), floor)];
|
|
417
|
+
if (options.history?.maxAgeMs !== void 0 && Number.isFinite(options.history.maxAgeMs)) conditions.push(lte(field("committedAt"), now - options.history.maxAgeMs));
|
|
418
|
+
const expired = yield* tx.query(journal, {
|
|
419
|
+
where: or(...conditions),
|
|
420
|
+
orderBy: [{ field: field("revision") }],
|
|
421
|
+
limit: 100
|
|
422
|
+
});
|
|
423
|
+
const head = yield* tx.get(metadata, "head");
|
|
424
|
+
if (head && expired.length) yield* tx.put(metadata, "head", {
|
|
425
|
+
...head,
|
|
426
|
+
revision,
|
|
427
|
+
journalFloor: Math.max(head.journalFloor ?? 0, ...expired.map((row) => row.value.revision))
|
|
428
|
+
});
|
|
429
|
+
for (const row of expired) yield* tx.delete(journal, row.key);
|
|
430
|
+
})) : Effect.void));
|
|
431
|
+
const subscribeSelection = Effect.fnUntraced(function* (selection, policy, resume) {
|
|
432
|
+
const context = yield* CurrentExecutionContext;
|
|
433
|
+
const subsets = yield* Effect.forEach(selection.subsets, (subset) => compileObjectSubset(options.ir, subset, context));
|
|
434
|
+
return yield* deliveries.open({
|
|
435
|
+
policy: {
|
|
436
|
+
...options.delivery,
|
|
437
|
+
...policy
|
|
438
|
+
},
|
|
439
|
+
resume,
|
|
440
|
+
binding: JSON.stringify([source, schemaHash]),
|
|
441
|
+
identity: JSON.stringify(selection),
|
|
442
|
+
changes: PubSub.subscribe(wakes).pipe(Effect.map(Stream.fromSubscription)),
|
|
443
|
+
capture: (_tx, emit) => boundary(Effect.gen(function* () {
|
|
444
|
+
for (const subset of subsets) {
|
|
445
|
+
const store = yield* object(subset.objectType);
|
|
446
|
+
yield* scanSelectedRows((query) => boundary(storage.query(store, query)), subset.query, (row) => emit({
|
|
447
|
+
kind: "base",
|
|
448
|
+
objectType: subset.objectType,
|
|
449
|
+
...row
|
|
450
|
+
}));
|
|
451
|
+
}
|
|
452
|
+
const revision = yield* current;
|
|
453
|
+
return {
|
|
454
|
+
sourceId: source,
|
|
455
|
+
schemaHash,
|
|
456
|
+
generation: 1,
|
|
457
|
+
revision: revision + 1,
|
|
458
|
+
cursor: cursor(revision),
|
|
459
|
+
coverage: subsets.map((subset) => ({
|
|
460
|
+
subset,
|
|
461
|
+
complete: true
|
|
462
|
+
}))
|
|
463
|
+
};
|
|
464
|
+
}))
|
|
465
|
+
});
|
|
466
|
+
});
|
|
467
|
+
const maintenance = collectGarbage.pipe(Effect.andThen(deliveries.collectGarbage), Effect.asVoid);
|
|
468
|
+
yield* scheduleMaintenance(maintenance, maintenanceIntervalMs);
|
|
469
|
+
return {
|
|
470
|
+
name: "owned",
|
|
471
|
+
storage: trustedStorage,
|
|
472
|
+
sourceId: source,
|
|
473
|
+
maintenance,
|
|
474
|
+
supportsIdempotency: true,
|
|
475
|
+
subscribeSelection,
|
|
476
|
+
acknowledgeDelivery: deliveries.acknowledge,
|
|
477
|
+
query: (document, settings) => boundary(storage.read((native) => Effect.gen(function* () {
|
|
478
|
+
const tx = read(native);
|
|
479
|
+
return (yield* executeQuery(document, {
|
|
480
|
+
reader: {
|
|
481
|
+
ir: options.ir,
|
|
482
|
+
loadSubset: (type, scan) => tx.loadSubset(type, scan),
|
|
483
|
+
loadGroupedSubset: tx.loadGroupedSubset
|
|
484
|
+
},
|
|
485
|
+
context: yield* CurrentExecutionContext,
|
|
486
|
+
inputs: settings?.inputs
|
|
487
|
+
})).value;
|
|
488
|
+
}))),
|
|
489
|
+
loadSubset: (request) => boundary(Effect.gen(function* () {
|
|
490
|
+
const subset = yield* compileObjectSubset(options.ir, request, yield* CurrentExecutionContext);
|
|
491
|
+
const object = model.objects[subset.objectType];
|
|
492
|
+
if (object) for (const index of indexesForQuery(subset.query ?? {}, new Set(object.definition.properties.map((property) => property.name)))) yield* storage.ensureIndex(object, index);
|
|
493
|
+
return yield* storage.read((native) => Effect.gen(function* () {
|
|
494
|
+
return {
|
|
495
|
+
rows: yield* read(native).loadSubset(subset.objectType, subset.query),
|
|
496
|
+
complete: true,
|
|
497
|
+
cursor: cursor(yield* current)
|
|
498
|
+
};
|
|
499
|
+
}));
|
|
500
|
+
})),
|
|
501
|
+
applyAction: Effect.fn("OwnedBackend.applyAction")(function* (invocation) {
|
|
502
|
+
const prepared = yield* prepare(invocation);
|
|
503
|
+
const prior = yield* boundary(Effect.gen(function* () {
|
|
504
|
+
return (yield* tables.get(receipts, prepared.receiptKey)) ?? (prepared.legacyReceiptKey ? yield* tables.get(receipts, prepared.legacyReceiptKey) : void 0);
|
|
505
|
+
}));
|
|
506
|
+
if (prior && prior.completedAt > (yield* Clock.currentTimeMillis) - resultRetentionMs) {
|
|
507
|
+
if (prior.fingerprint !== prepared.identity) return yield* fault("applyAction", "Conflict", "An invocation ID was reused with different parameters.");
|
|
508
|
+
return prior.receipt;
|
|
509
|
+
}
|
|
510
|
+
const commitUploads = invocation.attachmentUploads?.length ? options.prepareUploads ? yield* options.prepareUploads(invocation) : yield* fault("applyAction", "NotImplemented", "This owned backend has no attachment upload coordinator.") : Effect.void;
|
|
511
|
+
const result = yield* boundary(storage.transaction((native) => invokeIn(native, prepared, commitUploads)));
|
|
512
|
+
if (result.changed) yield* PubSub.publish(wakes, void 0);
|
|
513
|
+
yield* collectGarbage.pipe(Effect.catch((error) => Effect.logWarning("Ontology maintenance failed", { kind: error.kind })));
|
|
514
|
+
return result.receipt;
|
|
515
|
+
}),
|
|
516
|
+
validateAction: (name, parameters, settings) => Effect.gen(function* () {
|
|
517
|
+
const action = options.ir.actionTypes.find((action) => action.name === name);
|
|
518
|
+
if (!action) return yield* fault("validateAction", "InvalidRequest", "Unknown action type.");
|
|
519
|
+
const known = settings?.knownParameters;
|
|
520
|
+
const definition = known ? {
|
|
521
|
+
...action,
|
|
522
|
+
parameters: action.parameters.filter((parameter) => known.includes(parameter.name) || parameters[parameter.name] !== void 0)
|
|
523
|
+
} : action;
|
|
524
|
+
const schema = definition === action ? schemas.actionParameterSchemas[name] : compileEffectSchemas({
|
|
525
|
+
...options.ir,
|
|
526
|
+
actionTypes: [definition]
|
|
527
|
+
}).actionParameterSchemas[name];
|
|
528
|
+
const result = yield* Effect.result(Schema.decodeUnknownEffect(Schema.toEncoded(schema))(parameters));
|
|
529
|
+
if (result._tag === "Failure") return {
|
|
530
|
+
certain: true,
|
|
531
|
+
value: {
|
|
532
|
+
kind: "err",
|
|
533
|
+
value: schemaValidationIssues(result.failure)
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
const referenceIssues = yield* boundary(storage.read((native) => actionReferenceIssues(options.ir, definition.parameters, result.success, read(native))));
|
|
537
|
+
if (referenceIssues.length) return {
|
|
538
|
+
certain: true,
|
|
539
|
+
value: {
|
|
540
|
+
kind: "err",
|
|
541
|
+
value: referenceIssues
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
return { certain: false };
|
|
545
|
+
}),
|
|
546
|
+
queryFunction: (name, parameters) => boundary(storage.read((native) => Effect.gen(function* () {
|
|
547
|
+
const handler = options.queryFunctions?.[name];
|
|
548
|
+
if (!options.ir.queryFunctionTypes.find((candidate) => candidate.name === name)) return yield* fault("query", "InvalidRequest", "Unknown query function.");
|
|
549
|
+
if (!handler) return yield* fault("query", "NotImplemented", `No query implementation for ${JSON.stringify(name)}.`);
|
|
550
|
+
const parsed = yield* Schema.decodeUnknownEffect(Schema.toEncoded(schemas.queryParameterSchemas[name]))(parameters).pipe(Effect.mapError(() => fault("query", "ValidationFailed", "Query parameters do not match their definition.")));
|
|
551
|
+
const authorize = yield* CurrentQueryAuthorization;
|
|
552
|
+
const result = yield* handler(authorize ? yield* authorize(read(native), name, parsed) : read(native), parsed);
|
|
553
|
+
return yield* Schema.decodeUnknownEffect(Schema.toEncoded(schemas.queryReturnSchemas[name]))(result).pipe(Effect.mapError(() => fault("query", "Internal", "Query result does not match its definition.")));
|
|
554
|
+
}))),
|
|
555
|
+
changes: {
|
|
556
|
+
pull: (request) => boundary(storage.read(() => Effect.gen(function* () {
|
|
557
|
+
const head = yield* current;
|
|
558
|
+
const after = yield* parseCursor(request.cursor, head);
|
|
559
|
+
if (after < Math.max((yield* tables.get(metadata, "head"))?.journalFloor ?? 0, Number.isFinite(maxCommits) ? head - maxCommits : 0)) return yield* fault("changes", "HistoryExpired", "Requested changes were compacted; acquire a fresh coordinated snapshot before resuming.");
|
|
560
|
+
const limit = request.limit ?? 100;
|
|
561
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* fault("changes", "InvalidRequest", "Change page limit must be between 1 and 1000.");
|
|
562
|
+
const rows = yield* tables.query(journal, {
|
|
563
|
+
where: {
|
|
564
|
+
op: "gt",
|
|
565
|
+
left: {
|
|
566
|
+
_tag: "Field",
|
|
567
|
+
path: ["revision"]
|
|
568
|
+
},
|
|
569
|
+
right: after
|
|
570
|
+
},
|
|
571
|
+
orderBy: [{ field: {
|
|
572
|
+
_tag: "Field",
|
|
573
|
+
path: ["revision"]
|
|
574
|
+
} }],
|
|
575
|
+
limit: limit + 1
|
|
576
|
+
});
|
|
577
|
+
const page = rows.slice(0, limit);
|
|
578
|
+
return {
|
|
579
|
+
commits: page.map((row) => row.value.commit),
|
|
580
|
+
cursor: cursor(page.at(-1)?.value.revision ?? head),
|
|
581
|
+
hasMore: rows.length > limit
|
|
582
|
+
};
|
|
583
|
+
}))),
|
|
584
|
+
watch: PubSub.subscribe(wakes).pipe(Effect.map(Stream.fromSubscription))
|
|
585
|
+
},
|
|
586
|
+
attachments: options.attachments,
|
|
587
|
+
encrypted: options.encrypted
|
|
588
|
+
};
|
|
589
|
+
});
|
|
590
|
+
//#endregion
|
|
591
|
+
export { makeOwnedBackend };
|
|
592
|
+
|
|
593
|
+
//# sourceMappingURL=owned.js.map
|