simetra 0.1.0 → 0.2.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/README.md +1 -0
- package/dist/compiler/index.d.ts +843 -207
- package/dist/compiler/index.js +27880 -13611
- package/dist/model/index.d.ts +1580 -258
- package/dist/model/index.js +1031 -164
- package/dist/schema/index.d.ts +473 -272
- package/dist/schema/index.js +2002 -498
- package/dist/server/index.d.ts +103 -0
- package/dist/server/index.js +1503 -0
- package/package.json +15 -9
- package/schemas/catalogs.schema.json +6 -2
- package/schemas/custom-tables.schema.json +53 -2
- package/schemas/project.schema.json +255 -3
|
@@ -0,0 +1,1503 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { APPLIED_SNAPSHOT_HASH_FUNCTION_NAME, COMMAND_CORE_ERRORS, COMMAND_SETTING, CURRENT_USER_FUNCTION_NAME, INTEGER_TEXT, LOGIN_ROLE_REQUEST_PURPOSES, OBJECT_MODULE_KEYS, OPERATION_EVENTS, PLATFORM_ROLES, PLATFORM_SCHEMA, PROVIDER_API_ROLES, SESSION_CLAIMS_SETTING, UUID_TEXT, batchSchema, encodeAttributes, encodeItemValue, encodePair, isPlainObject, isTextEncodedType, operationSchema, readQuerySchema, runtimeCatalogSchema, sessionClaimsSchema } from "simetra/model";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
// src/server/errors.ts
|
|
5
|
+
/**
|
|
6
|
+
* The rejection of `run` and `read`: `message` is the error code, no
|
|
7
|
+
* `cause` — текст Postgres не має виходити назовні навіть через ланцюжок
|
|
8
|
+
* причин (Р-A3-8).
|
|
9
|
+
*/
|
|
10
|
+
var CommandFailure = class extends Error {
|
|
11
|
+
error;
|
|
12
|
+
constructor(error) {
|
|
13
|
+
super(error.code);
|
|
14
|
+
this.name = "CommandFailure";
|
|
15
|
+
this.error = error;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** Значення причин запису T0: усе, крім `errcode` і `message`. */
|
|
19
|
+
const valuesOf = (entry) => Object.entries(entry).filter(([key]) => key !== "errcode" && key !== "message").map(([, value]) => value);
|
|
20
|
+
const E = COMMAND_CORE_ERRORS;
|
|
21
|
+
const FORBIDDEN_REASONS = valuesOf(E.forbidden);
|
|
22
|
+
const CONFLICT_REASONS = valuesOf(E.conflict);
|
|
23
|
+
const CONTEXT_DETAILS = valuesOf(E.context);
|
|
24
|
+
const INVALID_REASONS = valuesOf(E.invalid);
|
|
25
|
+
const INTERNAL$2 = { code: "command.internal" };
|
|
26
|
+
function tablesOf(object) {
|
|
27
|
+
return [{
|
|
28
|
+
object,
|
|
29
|
+
name: object.table.name,
|
|
30
|
+
key: object.key,
|
|
31
|
+
keyName: object.keyName,
|
|
32
|
+
attributes: object.attributes,
|
|
33
|
+
constraints: object.constraints,
|
|
34
|
+
prefix: ""
|
|
35
|
+
}, ...object.tabularSections.map((s) => ({
|
|
36
|
+
object,
|
|
37
|
+
name: s.table.name,
|
|
38
|
+
key: s.key,
|
|
39
|
+
keyName: s.keyName,
|
|
40
|
+
attributes: s.attributes,
|
|
41
|
+
constraints: s.constraints,
|
|
42
|
+
prefix: `${s.name}.`
|
|
43
|
+
}))];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Таблиця за `TABLE` помилки (Postgres дає ім'я без схеми): спершу серед
|
|
47
|
+
* таблиць об'єкта фази, інакше — однозначний збіг у каталозі (Р-A3-19).
|
|
48
|
+
*/
|
|
49
|
+
function tableOf(catalog, phase, name) {
|
|
50
|
+
if (name === void 0) return void 0;
|
|
51
|
+
const found = (phase === void 0 ? [] : tablesOf(phase.object)).find((t) => t.name === name);
|
|
52
|
+
if (found !== void 0) return found;
|
|
53
|
+
const all = catalog.objects.flatMap(tablesOf).filter((t) => t.name === name);
|
|
54
|
+
return all.length === 1 ? all[0] : void 0;
|
|
55
|
+
}
|
|
56
|
+
/** Логічний шлях фізичної колонки таблиці; пара — за обома колонками. */
|
|
57
|
+
function pathOf(table, column) {
|
|
58
|
+
if (column === table.key) return `${table.prefix}${table.keyName}`;
|
|
59
|
+
const attribute = table.attributes.find((a) => a.column === column || a.pair?.typeColumn === column);
|
|
60
|
+
return attribute === void 0 ? void 0 : `${table.prefix}${attribute.name}`;
|
|
61
|
+
}
|
|
62
|
+
const MEMBER$2 = E.invalid.creatorMember;
|
|
63
|
+
/** Основна таблиця довідника членства під шляхом `creatorMember.` (спека П4 §6.13). */
|
|
64
|
+
const memberTable = (membership) => ({
|
|
65
|
+
...tablesOf(membership)[0],
|
|
66
|
+
prefix: `${MEMBER$2}.`
|
|
67
|
+
});
|
|
68
|
+
/** Шлях за `DETAIL` `22023` ядра (таблиця брифу Задачі 7). */
|
|
69
|
+
function invalidOf(object, detail, membership) {
|
|
70
|
+
if (detail === MEMBER$2 || detail.startsWith(`${MEMBER$2}.`)) {
|
|
71
|
+
const column = detail.slice(MEMBER$2.length + 1);
|
|
72
|
+
return {
|
|
73
|
+
code: "command.invalid",
|
|
74
|
+
path: (membership === void 0 || column === "" ? void 0 : pathOf(memberTable(membership), column)) ?? MEMBER$2
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const [main, ...sections] = tablesOf(object);
|
|
78
|
+
const column = pathOf(main, detail);
|
|
79
|
+
if (column !== void 0) return {
|
|
80
|
+
code: "command.invalid",
|
|
81
|
+
path: column
|
|
82
|
+
};
|
|
83
|
+
for (const section of sections) {
|
|
84
|
+
const head = `${E.invalid.tabular}.${section.name}`;
|
|
85
|
+
if (detail === head) return {
|
|
86
|
+
code: "command.invalid",
|
|
87
|
+
path: section.prefix.slice(0, -1)
|
|
88
|
+
};
|
|
89
|
+
if (detail.startsWith(`${head}.`)) {
|
|
90
|
+
const path = pathOf(section, detail.slice(head.length + 1));
|
|
91
|
+
return path === void 0 ? {
|
|
92
|
+
code: "command.invalid",
|
|
93
|
+
reason: "unknown"
|
|
94
|
+
} : {
|
|
95
|
+
code: "command.invalid",
|
|
96
|
+
path
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
code: "command.invalid",
|
|
102
|
+
reason: INVALID_REASONS.includes(detail) ? detail : "unknown"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Логічні реквізити колонок без дублів (пара — дві колонки, один реквізит). */
|
|
106
|
+
function attributesOf(table, columns) {
|
|
107
|
+
const names = columns.flatMap((c) => {
|
|
108
|
+
const path = c === table.key ? void 0 : pathOf(table, c);
|
|
109
|
+
return path === void 0 ? [] : [path];
|
|
110
|
+
});
|
|
111
|
+
return [...new Set(names)];
|
|
112
|
+
}
|
|
113
|
+
const VERSION_TEXT = /^[1-9]\d*$/;
|
|
114
|
+
const isVersion = (text) => VERSION_TEXT.test(text) && Number.isSafeInteger(Number(text));
|
|
115
|
+
/**
|
|
116
|
+
* Maps a database error to the error the outside sees (P4 spec §6.10).
|
|
117
|
+
* `DETAIL` і `HINT` ідуть назовні лише як значення з переліку T0, колонка
|
|
118
|
+
* каталогу чи безпечне ціле: SQL-обробник застосунку може кинути той самий
|
|
119
|
+
* `MESSAGE` з даними рядка (Р-A3-8). Решта — `command.internal` без тексту;
|
|
120
|
+
* повну помилку логує викликач.
|
|
121
|
+
*/
|
|
122
|
+
function mapDatabaseError(error, catalog, phase) {
|
|
123
|
+
if (error.connectionLost) return { code: "command.unavailable" };
|
|
124
|
+
const { code, message, detail } = error;
|
|
125
|
+
if (code === E.context.errcode && message === E.context.message) return detail !== void 0 && CONTEXT_DETAILS.includes(detail) ? {
|
|
126
|
+
code: "command.context",
|
|
127
|
+
detail
|
|
128
|
+
} : INTERNAL$2;
|
|
129
|
+
switch (code) {
|
|
130
|
+
case E.forbidden.errcode:
|
|
131
|
+
if (message === E.forbidden.message) return detail !== void 0 && FORBIDDEN_REASONS.includes(detail) ? {
|
|
132
|
+
code: "command.forbidden",
|
|
133
|
+
reason: detail
|
|
134
|
+
} : INTERNAL$2;
|
|
135
|
+
return rlsOf(catalog, phase, error.table);
|
|
136
|
+
case E.conflict.errcode:
|
|
137
|
+
if (message !== E.conflict.message) return INTERNAL$2;
|
|
138
|
+
if (detail === void 0 || !CONFLICT_REASONS.includes(detail)) return INTERNAL$2;
|
|
139
|
+
if (error.hint === void 0) return {
|
|
140
|
+
code: "command.conflict",
|
|
141
|
+
reason: detail
|
|
142
|
+
};
|
|
143
|
+
return isVersion(error.hint) ? {
|
|
144
|
+
code: "command.conflict",
|
|
145
|
+
reason: detail,
|
|
146
|
+
currentVersion: Number(error.hint)
|
|
147
|
+
} : INTERNAL$2;
|
|
148
|
+
case E.invalid.errcode: return message === E.invalid.message && detail !== void 0 && phase !== void 0 ? invalidOf(phase.object, detail, phase.kind === "write" ? phase.membership : void 0) : INTERNAL$2;
|
|
149
|
+
case "22P02": return phase?.kind === "read" ? { code: "command.invalid" } : INTERNAL$2;
|
|
150
|
+
case "23503": {
|
|
151
|
+
const table = tableOf(catalog, phase, error.table);
|
|
152
|
+
const fk = table?.constraints.find((c) => c.name === error.constraint && c.kind === "foreignKey");
|
|
153
|
+
const [path] = table === void 0 || fk === void 0 ? [] : attributesOf(table, fk.columns);
|
|
154
|
+
return path === void 0 ? INTERNAL$2 : {
|
|
155
|
+
code: "command.invalid",
|
|
156
|
+
path
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
case "23502": {
|
|
160
|
+
const membership = phase?.kind === "write" ? phase.membership : void 0;
|
|
161
|
+
if (membership !== void 0 && error.table === membership.table.name && error.column !== void 0) {
|
|
162
|
+
const path = pathOf(memberTable(membership), error.column);
|
|
163
|
+
return path === void 0 ? INTERNAL$2 : {
|
|
164
|
+
code: "command.invalid",
|
|
165
|
+
path
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const table = tableOf(catalog, phase, error.table);
|
|
169
|
+
const path = table === void 0 || error.column === void 0 ? void 0 : pathOf(table, error.column);
|
|
170
|
+
return path === void 0 ? INTERNAL$2 : {
|
|
171
|
+
code: "command.constraint",
|
|
172
|
+
kind: "notNull",
|
|
173
|
+
attributes: [path]
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
case "23505":
|
|
177
|
+
case "23514": {
|
|
178
|
+
const kind = code === "23505" ? "unique" : "check";
|
|
179
|
+
const table = tableOf(catalog, phase, error.table);
|
|
180
|
+
const constraint = table?.constraints.find((c) => c.name === error.constraint && c.kind === kind);
|
|
181
|
+
const attributes = table === void 0 || constraint === void 0 ? [] : attributesOf(table, constraint.columns);
|
|
182
|
+
return attributes.length === 0 ? INTERNAL$2 : {
|
|
183
|
+
code: "command.constraint",
|
|
184
|
+
kind,
|
|
185
|
+
attributes
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
default: return INTERNAL$2;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Whether the full database error goes to the log: every `command.internal`
|
|
193
|
+
* and every error without SQLSTATE. Без SQLSTATE назовні — недоступність, але
|
|
194
|
+
* під нею може бути власна вада T3 чи драйвера (`TypeError`), не лише обрив:
|
|
195
|
+
* без журналу вона зникла б.
|
|
196
|
+
*/
|
|
197
|
+
function logsDatabaseError(error, mapped) {
|
|
198
|
+
return mapped.code === "command.internal" || error.code === void 0;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Відмова RLS на записі (Р-A3-19): таблицю Postgres називає лише в тексті,
|
|
202
|
+
* тож об'єкт — з фази, а на `COMMIT` — з однозначного `TABLE`.
|
|
203
|
+
*/
|
|
204
|
+
function rlsOf(catalog, phase, tableName) {
|
|
205
|
+
const object = phase?.object ?? tableOf(catalog, void 0, tableName)?.object;
|
|
206
|
+
return {
|
|
207
|
+
code: "command.forbidden",
|
|
208
|
+
reason: "rls",
|
|
209
|
+
...object === void 0 ? {} : { object: {
|
|
210
|
+
kind: object.kind,
|
|
211
|
+
name: object.name
|
|
212
|
+
} },
|
|
213
|
+
...phase?.kind === "write" ? { operation: phase.operation } : {}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// src/server/decode.ts
|
|
217
|
+
const internal = () => new CommandFailure({ code: "command.internal" });
|
|
218
|
+
/**
|
|
219
|
+
* Decodes a result row of the core (`to_jsonb(row) || <numeric/bigint as
|
|
220
|
+
* text>`) into logical names and entity types. Розбіжність з каталогом
|
|
221
|
+
* (невідома мітка, версія поза безпечним цілим) — `command.internal`: база
|
|
222
|
+
* не тієї моделі чи дані, яких клієнт не прочитає без втрат.
|
|
223
|
+
*/
|
|
224
|
+
function decodeRow(object, json) {
|
|
225
|
+
let row;
|
|
226
|
+
try {
|
|
227
|
+
row = JSON.parse(json);
|
|
228
|
+
} catch {
|
|
229
|
+
throw internal();
|
|
230
|
+
}
|
|
231
|
+
return decodeRecord(object, row);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Decodes a parsed core row; the root core returns two rows in one JSON
|
|
235
|
+
* (spec P4 §6.13).
|
|
236
|
+
*/
|
|
237
|
+
function decodeRecord(object, row) {
|
|
238
|
+
if (!isPlainObject(row)) throw internal();
|
|
239
|
+
const out = decodeAttributes(object.attributes, object.key, object.keyName, row);
|
|
240
|
+
if (Object.hasOwn(row, object.versionColumn)) out[object.versionName] = decodeSafeInteger(row[object.versionColumn]);
|
|
241
|
+
const tabular = row.tabular;
|
|
242
|
+
if (isPlainObject(tabular)) for (const section of object.tabularSections) {
|
|
243
|
+
const rows = tabular[section.table.name];
|
|
244
|
+
if (rows === void 0) continue;
|
|
245
|
+
if (!Array.isArray(rows)) throw internal();
|
|
246
|
+
out[section.name] = rows.map((r) => {
|
|
247
|
+
if (!isPlainObject(r)) throw internal();
|
|
248
|
+
const line = decodeAttributes(section.attributes, section.key, section.keyName, r);
|
|
249
|
+
if (Object.hasOwn(r, section.parent)) line[section.parentName] = r[section.parent];
|
|
250
|
+
if (Object.hasOwn(r, section.lineNumber)) line[section.lineNumberName] = decodeSafeInteger(r[section.lineNumber]);
|
|
251
|
+
return line;
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
function decodeAttributes(attributes, key, keyName, row) {
|
|
257
|
+
const out = {};
|
|
258
|
+
if (Object.hasOwn(row, key)) out[keyName] = row[key];
|
|
259
|
+
for (const attribute of attributes) {
|
|
260
|
+
if (!Object.hasOwn(row, attribute.column)) continue;
|
|
261
|
+
out[attribute.name] = decodeValue(attribute, row);
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
function decodeValue(attribute, row) {
|
|
266
|
+
const value = row[attribute.column];
|
|
267
|
+
if (attribute.pair !== void 0) {
|
|
268
|
+
const label = row[attribute.pair.typeColumn];
|
|
269
|
+
if (value === null && label === null) return null;
|
|
270
|
+
const target = attribute.pair.targets.find((t) => t.label === label);
|
|
271
|
+
if (target === void 0) throw internal();
|
|
272
|
+
return {
|
|
273
|
+
type: `${target.object.kind}.${target.object.name}`,
|
|
274
|
+
id: value
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
if (value === null) return null;
|
|
278
|
+
if (attribute.array === true) {
|
|
279
|
+
if (!Array.isArray(value)) throw internal();
|
|
280
|
+
return value.map((v) => v === null ? null : decodeScalar(attribute, v));
|
|
281
|
+
}
|
|
282
|
+
return decodeScalar(attribute, value);
|
|
283
|
+
}
|
|
284
|
+
function decodeScalar(attribute, value) {
|
|
285
|
+
if (attribute.type === "BigInt") {
|
|
286
|
+
if (typeof value !== "string" || !INTEGER_TEXT.test(value)) throw internal();
|
|
287
|
+
return BigInt(value);
|
|
288
|
+
}
|
|
289
|
+
if (attribute.type === "Ref" && attribute.enumValues !== void 0) {
|
|
290
|
+
const found = attribute.enumValues.find((v) => v.label === value);
|
|
291
|
+
if (found === void 0) throw internal();
|
|
292
|
+
return found.name;
|
|
293
|
+
}
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Версія й номер рядка — `number` типу сутності; поза безпечним цілим клієнт
|
|
298
|
+
* їх спотворив би.
|
|
299
|
+
*/
|
|
300
|
+
function decodeSafeInteger(value) {
|
|
301
|
+
const version = typeof value === "string" && INTEGER_TEXT.test(value) ? Number(value) : value;
|
|
302
|
+
if (typeof version !== "number" || !Number.isSafeInteger(version)) throw internal();
|
|
303
|
+
return version;
|
|
304
|
+
}
|
|
305
|
+
// src/server/values.ts
|
|
306
|
+
/**
|
|
307
|
+
* Значення команд (Р-A3-7): вхід за логічними іменами перевіряється за
|
|
308
|
+
* каталогом до бази; кодування одного значення — у T0 (`simetra/model`),
|
|
309
|
+
* тут — збирання `p_item` команди й параметр `where`. Рядок результату ядра
|
|
310
|
+
* декодується назад у логічні імена й типи сутності кодогену.
|
|
311
|
+
*/
|
|
312
|
+
const invalid$1 = (path) => ({ error: {
|
|
313
|
+
code: "command.invalid",
|
|
314
|
+
path
|
|
315
|
+
} });
|
|
316
|
+
/**
|
|
317
|
+
* A logical value as the text of a bound `where` parameter. Json and arrays
|
|
318
|
+
* are not comparable by equality there.
|
|
319
|
+
*/
|
|
320
|
+
function encodeParam(attribute, value, path) {
|
|
321
|
+
if (attribute.pair !== void 0) throw new Error(`internal: pair ${attribute.name} goes through encodePair`);
|
|
322
|
+
if (attribute.array === true || attribute.type === "Json") return invalid$1(path);
|
|
323
|
+
const encoded = encodeItemValue(attribute, value, path);
|
|
324
|
+
if ("error" in encoded) return encoded;
|
|
325
|
+
return { value: encoded.value === null ? null : String(encoded.value) };
|
|
326
|
+
}
|
|
327
|
+
/** Відмова входу на шляху; ловить її лише `encodeItem`. */
|
|
328
|
+
var InvalidInput = class {
|
|
329
|
+
path;
|
|
330
|
+
constructor(path) {
|
|
331
|
+
this.path = path;
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
/**
|
|
335
|
+
* Читання чернетки: геттер, що кидає, чи відкликаний `Proxy` — помилка
|
|
336
|
+
* входу на цьому шляху, а не сирий виняток (чернетку міг повернути хук).
|
|
337
|
+
*/
|
|
338
|
+
function at(path, read) {
|
|
339
|
+
try {
|
|
340
|
+
return read();
|
|
341
|
+
} catch {
|
|
342
|
+
throw new InvalidInput(path);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
/** Власні ключі простого об'єкта; інакше — відмова на `path`. */
|
|
346
|
+
function keysOf(path, value) {
|
|
347
|
+
const keys = at(path, () => isPlainObject(value) ? Object.keys(value) : void 0);
|
|
348
|
+
if (keys === void 0) throw new InvalidInput(path);
|
|
349
|
+
return keys;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* The `p_item` of a save: the table key from `op.id`, physical columns,
|
|
353
|
+
* `tabular` by section table. Перша помилка (Р-A3-8): реквізити — за
|
|
354
|
+
* порядком каталогу, і поза грантом, і з невірним значенням; невідомі
|
|
355
|
+
* ключі — після них, за порядком входу.
|
|
356
|
+
*/
|
|
357
|
+
function encodeItem(object, op, draft) {
|
|
358
|
+
try {
|
|
359
|
+
return { item: itemOf(object, op, draft) };
|
|
360
|
+
} catch (error) {
|
|
361
|
+
if (error instanceof InvalidInput) return invalid$1(error.path);
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function itemOf(object, op, draft) {
|
|
366
|
+
const item = { [object.key]: op.id };
|
|
367
|
+
const allowed = (a) => op.action === "create" ? a.insert : a.update;
|
|
368
|
+
const values = at("values", () => draft.values);
|
|
369
|
+
if (values !== void 0) Object.assign(item, columnsOf(encodeAttributes(object.attributes, values, {
|
|
370
|
+
allowed,
|
|
371
|
+
path: "values",
|
|
372
|
+
prefix: ""
|
|
373
|
+
})));
|
|
374
|
+
const sections = at("tabularSections", () => draft.tabularSections);
|
|
375
|
+
if (sections === void 0) return item;
|
|
376
|
+
const names = keysOf("tabularSections", sections);
|
|
377
|
+
const unknownSection = names.find((name) => !object.tabularSections.some((s) => s.name === name));
|
|
378
|
+
if (unknownSection !== void 0) throw new InvalidInput(unknownSection);
|
|
379
|
+
const tabular = {};
|
|
380
|
+
for (const section of object.tabularSections) {
|
|
381
|
+
if (!names.includes(section.name)) continue;
|
|
382
|
+
const rows = at(section.name, () => sections[section.name]);
|
|
383
|
+
tabular[section.table.name] = encodeRows(section, rows);
|
|
384
|
+
}
|
|
385
|
+
item.tabular = tabular;
|
|
386
|
+
return item;
|
|
387
|
+
}
|
|
388
|
+
function encodeRows(section, rows) {
|
|
389
|
+
const length = at(section.name, () => Array.isArray(rows) ? rows.length : void 0);
|
|
390
|
+
if (length === void 0) throw new InvalidInput(section.name);
|
|
391
|
+
const encoded = [];
|
|
392
|
+
for (let i = 0; i < length; i++) {
|
|
393
|
+
const path = `${section.name}.${i}`;
|
|
394
|
+
const row = at(path, () => rows[i]);
|
|
395
|
+
keysOf(path, row);
|
|
396
|
+
const keyPath = `${path}.${section.keyName}`;
|
|
397
|
+
const key = at(keyPath, () => row[section.keyName]);
|
|
398
|
+
if (typeof key !== "string" || !UUID_TEXT.test(key)) throw new InvalidInput(keyPath);
|
|
399
|
+
const columns = columnsOf(encodeAttributes(section.attributes, row, {
|
|
400
|
+
allowed: (a) => a.insert,
|
|
401
|
+
path,
|
|
402
|
+
prefix: `${path}.`,
|
|
403
|
+
rowKey: section.keyName
|
|
404
|
+
}));
|
|
405
|
+
encoded.push({
|
|
406
|
+
[section.key]: key,
|
|
407
|
+
...columns
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
return encoded;
|
|
411
|
+
}
|
|
412
|
+
/** Колонки обходу T0; його відмова — `InvalidInput` на її шляху. */
|
|
413
|
+
function columnsOf(encoded) {
|
|
414
|
+
if ("error" in encoded) throw new InvalidInput(encoded.error.path ?? "");
|
|
415
|
+
return encoded.columns;
|
|
416
|
+
}
|
|
417
|
+
// src/server/read.ts
|
|
418
|
+
const LABEL_CAST = "text";
|
|
419
|
+
const KEY_CAST = "uuid";
|
|
420
|
+
/** An identifier quoted for SQL text. */
|
|
421
|
+
const ident = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
422
|
+
/** A string literal quoted for SQL text. */
|
|
423
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
424
|
+
/**
|
|
425
|
+
* Рядок читання — та сама форма, що й результат ядра (`to_jsonb` і
|
|
426
|
+
* `numeric`/`bigint` текстом, Рт1), тож декодує його той самий `decodeRow`.
|
|
427
|
+
*/
|
|
428
|
+
function projection(object) {
|
|
429
|
+
const text = object.attributes.filter((a) => isTextEncodedType(a.pgType)).map((a) => `${literal(a.column)}, t.${ident(a.column)}::${a.array === true ? "text[]" : "text"}`);
|
|
430
|
+
return text.length === 0 ? "to_jsonb(t)::text" : `(to_jsonb(t) || jsonb_build_object(${text.join(", ")}))::text`;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Builds the server read statement (P4 spec §6.11): one row by id or a
|
|
434
|
+
* keyset page by equality, with bound parameters only. Тип приведення —
|
|
435
|
+
* з каталогу без модифікатора: `$n::character varying(10)` обрізав би
|
|
436
|
+
* значення фільтра й знайшов би рядок з іншим значенням.
|
|
437
|
+
*/
|
|
438
|
+
function buildReadStatement(object, query) {
|
|
439
|
+
const params = [];
|
|
440
|
+
const bind = (value, cast) => {
|
|
441
|
+
params.push(value);
|
|
442
|
+
return `$${params.length}::${cast}`;
|
|
443
|
+
};
|
|
444
|
+
const equals = (column, value, cast) => value === null ? `${ident(column)} IS NULL` : `${ident(column)} = ${bind(value, cast)}`;
|
|
445
|
+
const key = ident(object.key);
|
|
446
|
+
const conditions = [];
|
|
447
|
+
let limit;
|
|
448
|
+
if ("id" in query) {
|
|
449
|
+
conditions.push(`${key} = ${bind(query.id, KEY_CAST)}`);
|
|
450
|
+
limit = 1;
|
|
451
|
+
} else {
|
|
452
|
+
for (const [name, value] of Object.entries(query.where)) {
|
|
453
|
+
const attribute = object.attributes.find((a) => a.name === name);
|
|
454
|
+
if (attribute === void 0) return { error: {
|
|
455
|
+
code: "command.invalid",
|
|
456
|
+
path: name
|
|
457
|
+
} };
|
|
458
|
+
if (attribute.pair !== void 0) {
|
|
459
|
+
const pair = encodePair(attribute, value, name);
|
|
460
|
+
if ("error" in pair) return pair;
|
|
461
|
+
conditions.push(equals(attribute.pair.typeColumn, pair.value.label, LABEL_CAST), equals(attribute.column, pair.value.id, attribute.castType));
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const encoded = encodeParam(attribute, value, name);
|
|
465
|
+
if ("error" in encoded) return encoded;
|
|
466
|
+
conditions.push(equals(attribute.column, encoded.value, attribute.castType));
|
|
467
|
+
}
|
|
468
|
+
if (query.after !== void 0) conditions.push(`${key} > ${bind(query.after, KEY_CAST)}`);
|
|
469
|
+
limit = query.limit;
|
|
470
|
+
}
|
|
471
|
+
const where = conditions.length === 0 ? "" : ` WHERE ${conditions.join(" AND ")}`;
|
|
472
|
+
const table = `${ident(object.table.schema)}.${ident(object.table.name)}`;
|
|
473
|
+
params.push(String(limit));
|
|
474
|
+
return {
|
|
475
|
+
text: `SELECT ${projection(object)} AS row FROM ${table} t${where} ORDER BY ${key} LIMIT $${params.length}`,
|
|
476
|
+
params
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
/** The input path of the first Zod issue; `undefined` — the input root. */
|
|
480
|
+
function issuePath(error) {
|
|
481
|
+
const [issue] = error.issues;
|
|
482
|
+
return issue === void 0 || issue.path.length === 0 ? void 0 : issue.path.join(".");
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Checks a read query against the catalog and builds its statement; every
|
|
486
|
+
* failure is `command.invalid` before the database.
|
|
487
|
+
*/
|
|
488
|
+
function prepareRead(catalog, query) {
|
|
489
|
+
let parsed;
|
|
490
|
+
try {
|
|
491
|
+
parsed = readQuerySchema.safeParse(query);
|
|
492
|
+
} catch {
|
|
493
|
+
return { error: { code: "command.invalid" } };
|
|
494
|
+
}
|
|
495
|
+
if (!parsed.success) {
|
|
496
|
+
const path = issuePath(parsed.error);
|
|
497
|
+
return { error: {
|
|
498
|
+
code: "command.invalid",
|
|
499
|
+
...path === void 0 ? {} : { path }
|
|
500
|
+
} };
|
|
501
|
+
}
|
|
502
|
+
const { object: ref } = parsed.data;
|
|
503
|
+
const object = catalog.objects.find((o) => o.kind === ref.kind && o.name === ref.name);
|
|
504
|
+
if (object === void 0) return { error: {
|
|
505
|
+
code: "command.invalid",
|
|
506
|
+
path: "object"
|
|
507
|
+
} };
|
|
508
|
+
const statement = buildReadStatement(object, parsed.data);
|
|
509
|
+
return "error" in statement ? statement : {
|
|
510
|
+
object,
|
|
511
|
+
statement
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
// src/server/hook-context.ts
|
|
515
|
+
const frames = new AsyncLocalStorage();
|
|
516
|
+
const INTERNAL$1 = { code: "command.internal" };
|
|
517
|
+
/** Runs `work` as the async context of a command attempt. */
|
|
518
|
+
function inCommand(frame, work) {
|
|
519
|
+
return frames.run(frame, work);
|
|
520
|
+
}
|
|
521
|
+
/** Runs `work` outside any command (`afterCommit` actions). */
|
|
522
|
+
function outsideCommand(work) {
|
|
523
|
+
return frames.exit(work);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* `run` чи `read` будь-якого рантайму в асинхронному контексті активної
|
|
527
|
+
* команди — `command.nested` (спека П4 §6.5). Відмова закриває чергу тієї
|
|
528
|
+
* команди: перехопивши її, хук не продовжить команду (Р-A3-15).
|
|
529
|
+
*/
|
|
530
|
+
function rejectNested() {
|
|
531
|
+
const frame = frames.getStore();
|
|
532
|
+
if (frame?.command.active === true) frame.tx.abort({ code: "command.nested" });
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Calls one hook with its `ctx`, then waits for every `ctx` call the hook
|
|
536
|
+
* started. The first failure of the attempt wins even when the hook caught
|
|
537
|
+
* it; a hook's own exception is `command.internal`, logged.
|
|
538
|
+
*/
|
|
539
|
+
async function callHook(tx, phase, hook) {
|
|
540
|
+
const scope = {
|
|
541
|
+
live: true,
|
|
542
|
+
pending: /* @__PURE__ */ new Set()
|
|
543
|
+
};
|
|
544
|
+
let outcome;
|
|
545
|
+
try {
|
|
546
|
+
outcome = { value: await hook(contextOf(tx, phase, scope)) };
|
|
547
|
+
} catch (error) {
|
|
548
|
+
if (tx.terminal === void 0) {
|
|
549
|
+
tx.state.log({
|
|
550
|
+
kind: "hook",
|
|
551
|
+
error
|
|
552
|
+
});
|
|
553
|
+
tx.close({
|
|
554
|
+
failure: new CommandFailure(INTERNAL$1),
|
|
555
|
+
retry: false,
|
|
556
|
+
destroy: false
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
scope.live = false;
|
|
561
|
+
await Promise.allSettled(scope.pending);
|
|
562
|
+
if (tx.terminal !== void 0) throw tx.terminal.failure;
|
|
563
|
+
return outcome.value;
|
|
564
|
+
}
|
|
565
|
+
function contextOf(tx, phase, scope) {
|
|
566
|
+
const { object, op } = phase;
|
|
567
|
+
const valid = () => scope.live && frames.getStore()?.tx === tx;
|
|
568
|
+
const misuse = () => {
|
|
569
|
+
tx.state.log({
|
|
570
|
+
kind: "hook",
|
|
571
|
+
error: /* @__PURE__ */ new Error("hook context used outside its hook")
|
|
572
|
+
});
|
|
573
|
+
const failure = new CommandFailure(INTERNAL$1);
|
|
574
|
+
const frame = frames.getStore();
|
|
575
|
+
if (frame?.command.active === true) frame.tx.close({
|
|
576
|
+
failure,
|
|
577
|
+
retry: false,
|
|
578
|
+
destroy: false
|
|
579
|
+
});
|
|
580
|
+
return failure;
|
|
581
|
+
};
|
|
582
|
+
const track = (work) => {
|
|
583
|
+
let promise;
|
|
584
|
+
if (!valid()) promise = Promise.reject(misuse());
|
|
585
|
+
else if (tx.terminal !== void 0) promise = Promise.reject(tx.terminal.failure);
|
|
586
|
+
else {
|
|
587
|
+
promise = work().catch((error) => {
|
|
588
|
+
if (tx.terminal === void 0) {
|
|
589
|
+
tx.state.log({
|
|
590
|
+
kind: "hook",
|
|
591
|
+
error
|
|
592
|
+
});
|
|
593
|
+
tx.close({
|
|
594
|
+
failure: new CommandFailure(INTERNAL$1),
|
|
595
|
+
retry: false,
|
|
596
|
+
destroy: false
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
throw error;
|
|
600
|
+
});
|
|
601
|
+
scope.pending.add(promise);
|
|
602
|
+
}
|
|
603
|
+
promise.catch(() => void 0);
|
|
604
|
+
return promise;
|
|
605
|
+
};
|
|
606
|
+
const ctx = {
|
|
607
|
+
object: {
|
|
608
|
+
kind: object.kind,
|
|
609
|
+
name: object.name
|
|
610
|
+
},
|
|
611
|
+
id: op.id,
|
|
612
|
+
action: op.action,
|
|
613
|
+
isNew: op.action === "create",
|
|
614
|
+
...op.action === "markDeletion" ? { mark: op.mark } : {},
|
|
615
|
+
additionalProperties: phase.additionalProperties,
|
|
616
|
+
user: tx.user,
|
|
617
|
+
...tx.act === void 0 ? {} : { act: { sub: tx.act.sub } },
|
|
618
|
+
run: (operation) => track(async () => {
|
|
619
|
+
const frame = frames.getStore();
|
|
620
|
+
const depth = frame.depth + 1;
|
|
621
|
+
if (depth > tx.state.maxDepth) tx.abort({ code: "command.depth" });
|
|
622
|
+
return frames.run({
|
|
623
|
+
...frame,
|
|
624
|
+
depth
|
|
625
|
+
}, () => phase.runNested(operation));
|
|
626
|
+
}),
|
|
627
|
+
read: (query) => track(async () => {
|
|
628
|
+
const prepared = prepareRead(tx.state.catalog, query);
|
|
629
|
+
if ("error" in prepared) tx.abort(prepared.error);
|
|
630
|
+
const { object: target, statement } = prepared;
|
|
631
|
+
const { rows } = await tx.enqueue([statement], {
|
|
632
|
+
kind: "read",
|
|
633
|
+
object: target
|
|
634
|
+
});
|
|
635
|
+
try {
|
|
636
|
+
return rows.map((r) => {
|
|
637
|
+
if (typeof r.row !== "string") throw new Error("read row is not text");
|
|
638
|
+
return decodeRow(target, r.row);
|
|
639
|
+
});
|
|
640
|
+
} catch (error) {
|
|
641
|
+
tx.anomaly(error);
|
|
642
|
+
}
|
|
643
|
+
}),
|
|
644
|
+
reject(code, path) {
|
|
645
|
+
if (!valid()) throw misuse();
|
|
646
|
+
tx.abort({
|
|
647
|
+
code: "command.rejected",
|
|
648
|
+
reason: code,
|
|
649
|
+
...path === void 0 ? {} : { path }
|
|
650
|
+
});
|
|
651
|
+
},
|
|
652
|
+
afterCommit(fn) {
|
|
653
|
+
if (!valid()) throw misuse();
|
|
654
|
+
tx.afterCommit.push(fn);
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
return Object.freeze(ctx);
|
|
658
|
+
}
|
|
659
|
+
// src/server/port.ts
|
|
660
|
+
/**
|
|
661
|
+
* Парсери типів на рівні запиту: текст Postgres без перетворень. Інакше
|
|
662
|
+
* парсери, які host поставив на пул (`types` у `pg.Pool`), змінили б рядок
|
|
663
|
+
* ядра ще до `decodeRow` — і значення залежали б від налаштувань host-а.
|
|
664
|
+
*/
|
|
665
|
+
const RAW_TYPES = { getTypeParser: () => (value) => value };
|
|
666
|
+
/** Adapts a `pg` pool to the runtime port. */
|
|
667
|
+
function fromPgPool(pool) {
|
|
668
|
+
return { async connect() {
|
|
669
|
+
const client = await pool.connect();
|
|
670
|
+
return {
|
|
671
|
+
async query(text, params) {
|
|
672
|
+
const { rows, command } = await client.query({
|
|
673
|
+
text,
|
|
674
|
+
values: params ?? [],
|
|
675
|
+
types: RAW_TYPES
|
|
676
|
+
});
|
|
677
|
+
return {
|
|
678
|
+
rows,
|
|
679
|
+
command
|
|
680
|
+
};
|
|
681
|
+
},
|
|
682
|
+
release(destroy) {
|
|
683
|
+
client.release(destroy);
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
} };
|
|
687
|
+
}
|
|
688
|
+
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
689
|
+
const ADMIN_SHUTDOWN = /* @__PURE__ */ new Set([
|
|
690
|
+
"57P01",
|
|
691
|
+
"57P02",
|
|
692
|
+
"57P03"
|
|
693
|
+
]);
|
|
694
|
+
/**
|
|
695
|
+
* Normalizes whatever the driver threw. Помилка без SQLSTATE — обрив чи
|
|
696
|
+
* збій драйвера до відповіді бази: з'єднанню вже не можна вірити.
|
|
697
|
+
*/
|
|
698
|
+
function normalizeError(error) {
|
|
699
|
+
const text = (key) => {
|
|
700
|
+
try {
|
|
701
|
+
const value = typeof error === "object" && error !== null ? error[key] : void 0;
|
|
702
|
+
return typeof value === "string" ? value : void 0;
|
|
703
|
+
} catch {
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
const raw = text("code");
|
|
708
|
+
const code = raw !== void 0 && SQLSTATE.test(raw) ? raw : void 0;
|
|
709
|
+
const fields = {
|
|
710
|
+
detail: text("detail"),
|
|
711
|
+
hint: text("hint"),
|
|
712
|
+
constraint: text("constraint"),
|
|
713
|
+
table: text("table"),
|
|
714
|
+
column: text("column")
|
|
715
|
+
};
|
|
716
|
+
return {
|
|
717
|
+
...code === void 0 ? {} : { code },
|
|
718
|
+
message: text("message") ?? describe(error),
|
|
719
|
+
...Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0)),
|
|
720
|
+
connectionLost: code === void 0 || code.startsWith("08") || ADMIN_SHUTDOWN.has(code)
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
/** `String()` кидає на об'єкті без прототипу й на відкликаному `Proxy`. */
|
|
724
|
+
function describe(error) {
|
|
725
|
+
try {
|
|
726
|
+
return String(error);
|
|
727
|
+
} catch {
|
|
728
|
+
return "unknown error";
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
// src/server/phase.ts
|
|
732
|
+
const invalid = (path) => ({
|
|
733
|
+
code: "command.invalid",
|
|
734
|
+
...path === void 0 ? {} : { path }
|
|
735
|
+
});
|
|
736
|
+
function targetOf(catalog, op) {
|
|
737
|
+
const object = catalog.objects.find((o) => o.kind === op.object.kind && o.name === op.object.name);
|
|
738
|
+
if (object === void 0) return { error: invalid("object") };
|
|
739
|
+
const target = object.operations[op.action];
|
|
740
|
+
if (target === void 0) return { error: invalid("action") };
|
|
741
|
+
return {
|
|
742
|
+
object,
|
|
743
|
+
target
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
/** `create` кореня скоупу; `undefined` — звичайна операція. */
|
|
747
|
+
function rootCreateOf(catalog, object, op) {
|
|
748
|
+
const root = op.action === "create" ? object.operations.create?.root : void 0;
|
|
749
|
+
if (root === void 0) return void 0;
|
|
750
|
+
return { membership: root.membership === void 0 ? void 0 : catalog.objects.find((o) => o.id === root.membership) };
|
|
751
|
+
}
|
|
752
|
+
const MEMBER$1 = "creatorMember";
|
|
753
|
+
/**
|
|
754
|
+
* `creatorMember` тим самим обходом T0, що й `values` (Р-A6-13): дозволені —
|
|
755
|
+
* ключі вставки довідника членства, крім примушених скоупу й користувача
|
|
756
|
+
* (ключ таблиці поза реквізитами й так невідомий обходу).
|
|
757
|
+
*/
|
|
758
|
+
function encodeMember(membership, values) {
|
|
759
|
+
const forced = membership.attributes.filter((a) => a.column === membership.scopeColumn || a.column === membership.membership?.userColumn).map((a) => a.name);
|
|
760
|
+
return encodeAttributes(membership.attributes, values, {
|
|
761
|
+
allowed: (a) => a.insert,
|
|
762
|
+
forced,
|
|
763
|
+
path: MEMBER$1,
|
|
764
|
+
prefix: `${MEMBER$1}.`
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Вхід операції з урахуванням кореня скоупу: `id` — лише поза коренем,
|
|
769
|
+
* `tabularSections` кореня на створенні не пишуться, `creatorMember` — лише
|
|
770
|
+
* в кореня з довідником членства. Повертає id, які генерує T3.
|
|
771
|
+
*/
|
|
772
|
+
function rootInput(catalog, object, op) {
|
|
773
|
+
const creation = rootCreateOf(catalog, object, op);
|
|
774
|
+
if (op.action !== "create") return { id: op.id };
|
|
775
|
+
if (creation === void 0) {
|
|
776
|
+
if (op.id === void 0) return { error: invalid("id") };
|
|
777
|
+
if (op.creatorMember !== void 0) return { error: invalid(MEMBER$1) };
|
|
778
|
+
return { id: op.id };
|
|
779
|
+
}
|
|
780
|
+
if (op.id !== void 0) return { error: invalid("id") };
|
|
781
|
+
if (op.tabularSections !== void 0) return { error: invalid("tabularSections") };
|
|
782
|
+
const { membership } = creation;
|
|
783
|
+
if (membership === void 0) return op.creatorMember === void 0 ? { id: globalThis.crypto.randomUUID() } : { error: invalid(MEMBER$1) };
|
|
784
|
+
const member = encodeMember(membership, op.creatorMember ?? {});
|
|
785
|
+
if ("error" in member) return member;
|
|
786
|
+
return {
|
|
787
|
+
id: globalThis.crypto.randomUUID(),
|
|
788
|
+
memberId: globalThis.crypto.randomUUID()
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
const draftOf = (op) => op.action === "create" || op.action === "update" ? {
|
|
792
|
+
...op.values === void 0 ? {} : { values: op.values },
|
|
793
|
+
...op.tabularSections === void 0 ? {} : { tabularSections: op.tabularSections }
|
|
794
|
+
} : {};
|
|
795
|
+
/**
|
|
796
|
+
* Перевірка до транзакції (спека П4 §6.5): схема операції, об'єкт і операція
|
|
797
|
+
* каталогу, значення за каталогом — без звернення до бази.
|
|
798
|
+
*/
|
|
799
|
+
function prepareInput(catalog, input) {
|
|
800
|
+
let parsed;
|
|
801
|
+
try {
|
|
802
|
+
parsed = Array.isArray(input) ? batchSchema.safeParse(input) : operationSchema.transform((op) => [op]).safeParse(input);
|
|
803
|
+
} catch {
|
|
804
|
+
throw new CommandFailure(invalid());
|
|
805
|
+
}
|
|
806
|
+
if (!parsed.success) throw new CommandFailure(invalid(issuePath(parsed.error)));
|
|
807
|
+
return parsed.data.map((op) => {
|
|
808
|
+
const found = targetOf(catalog, op);
|
|
809
|
+
if ("error" in found) throw new CommandFailure(found.error);
|
|
810
|
+
const ids = rootInput(catalog, found.object, op);
|
|
811
|
+
if ("error" in ids) throw new CommandFailure(ids.error);
|
|
812
|
+
const prepared = {
|
|
813
|
+
...op,
|
|
814
|
+
...ids
|
|
815
|
+
};
|
|
816
|
+
if (prepared.action === "create" || prepared.action === "update") {
|
|
817
|
+
const encoded = encodeItem(found.object, prepared, draftOf(prepared));
|
|
818
|
+
if ("error" in encoded) throw new CommandFailure(encoded.error);
|
|
819
|
+
}
|
|
820
|
+
return prepared;
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
const fn = (target) => `${ident(target.function.schema)}.${ident(target.function.name)}`;
|
|
824
|
+
/** Виклик функції ядра фази зі зв'язаними параметрами. */
|
|
825
|
+
function callOf({ object, target }, op, draft) {
|
|
826
|
+
switch (op.action) {
|
|
827
|
+
case "create":
|
|
828
|
+
case "update": {
|
|
829
|
+
const encoded = encodeItem(object, op, draft);
|
|
830
|
+
if ("error" in encoded) return encoded;
|
|
831
|
+
return {
|
|
832
|
+
text: `SELECT ${fn(target)}($1::jsonb, $2::bigint) AS r`,
|
|
833
|
+
params: [JSON.stringify(encoded.item), op.action === "create" ? null : String(op.expectedVersion)]
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
case "markDeletion": return {
|
|
837
|
+
text: `SELECT ${fn(target)}($1::uuid, $2::bigint, $3::boolean) AS r`,
|
|
838
|
+
params: [
|
|
839
|
+
op.id,
|
|
840
|
+
String(op.expectedVersion),
|
|
841
|
+
String(op.mark)
|
|
842
|
+
]
|
|
843
|
+
};
|
|
844
|
+
case "delete": return {
|
|
845
|
+
text: `SELECT ${fn(target)}($1::uuid, $2::bigint) AS r`,
|
|
846
|
+
params: [op.id, String(op.expectedVersion)]
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const CONTEXT_TEXT = `SELECT set_config(${literal(COMMAND_SETTING)}, $1, true)`;
|
|
851
|
+
/**
|
|
852
|
+
* Чернетка хука «до» — та сама перевірка, що й вхід (спека П4 §6.5): ключі
|
|
853
|
+
* поза чернеткою — `command.invalid`; значення перевіряє `encodeItem`.
|
|
854
|
+
* Чернетка `markDeletion` порожня: позначку хук бачить у `ctx.mark` (Р-A3-18).
|
|
855
|
+
*/
|
|
856
|
+
function checkDraft(tx, op, draft, path = (key) => key) {
|
|
857
|
+
const keys = op.action === "markDeletion" ? [] : ["values", "tabularSections"];
|
|
858
|
+
let bad;
|
|
859
|
+
try {
|
|
860
|
+
if (!isPlainObject(draft)) throw new Error("beforeWrite returned no draft object");
|
|
861
|
+
bad = Object.keys(draft).find((key) => !keys.includes(key) || draft[key] === void 0);
|
|
862
|
+
} catch (error) {
|
|
863
|
+
tx.state.log({
|
|
864
|
+
kind: "hook",
|
|
865
|
+
error
|
|
866
|
+
});
|
|
867
|
+
tx.abort({ code: "command.internal" });
|
|
868
|
+
}
|
|
869
|
+
if (bad !== void 0) tx.abort(invalid(path(bad)));
|
|
870
|
+
return draft;
|
|
871
|
+
}
|
|
872
|
+
/** Фаза `ctx.run`: той самий вхід, що й у команди, — копія й перевірка. */
|
|
873
|
+
async function runNested(tx, operation) {
|
|
874
|
+
let op;
|
|
875
|
+
try {
|
|
876
|
+
if (Array.isArray(operation)) throw new CommandFailure(invalid());
|
|
877
|
+
[op] = prepareInput(tx.state.catalog, structuredClone(operation));
|
|
878
|
+
} catch (error) {
|
|
879
|
+
tx.abort(error instanceof CommandFailure ? error.error : invalid());
|
|
880
|
+
}
|
|
881
|
+
return runPhase(tx, op);
|
|
882
|
+
}
|
|
883
|
+
/** Модуль об'єкта, коли операція піднімає подію запису (Р-A3-2). */
|
|
884
|
+
function moduleOf(tx, object, op) {
|
|
885
|
+
return OPERATION_EVENTS[op.action] === "write" ? tx.state.objectModules[`${object.kind}.${object.name}`] : void 0;
|
|
886
|
+
}
|
|
887
|
+
const phaseOf = (tx, object, op) => ({
|
|
888
|
+
object,
|
|
889
|
+
op,
|
|
890
|
+
additionalProperties: /* @__PURE__ */ new Map(),
|
|
891
|
+
runNested: (operation) => runNested(tx, operation)
|
|
892
|
+
});
|
|
893
|
+
/** `beforeWrite` фази й перевірка повернутої чернетки. */
|
|
894
|
+
async function beforeWrite(tx, phase, module, draft, path) {
|
|
895
|
+
if (module?.beforeWrite === void 0) return draft;
|
|
896
|
+
const hook = module.beforeWrite.bind(module);
|
|
897
|
+
const returned = await callHook(tx, phase, (ctx) => hook({
|
|
898
|
+
ctx,
|
|
899
|
+
draft
|
|
900
|
+
}));
|
|
901
|
+
return checkDraft(tx, phase.op, returned, path);
|
|
902
|
+
}
|
|
903
|
+
/** `onWrite` фази над копією рядка: зміна копії не змінює результату (Р-A3-15). */
|
|
904
|
+
async function onWrite(tx, phase, module, row) {
|
|
905
|
+
if (module?.onWrite === void 0) return;
|
|
906
|
+
const hook = module.onWrite.bind(module);
|
|
907
|
+
await callHook(tx, phase, (ctx) => hook({
|
|
908
|
+
ctx,
|
|
909
|
+
row: structuredClone(row)
|
|
910
|
+
}));
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* One phase: `beforeWrite`, the command context and the core call as one
|
|
914
|
+
* queue unit, the row decoded before `COMMIT`, then `onWrite`. Повертає
|
|
915
|
+
* рядок фази за логічними іменами.
|
|
916
|
+
*/
|
|
917
|
+
async function runPhase(tx, op) {
|
|
918
|
+
const found = targetOf(tx.state.catalog, op);
|
|
919
|
+
if ("error" in found) tx.abort(found.error);
|
|
920
|
+
const creation = rootCreateOf(tx.state.catalog, found.object, op);
|
|
921
|
+
if (creation !== void 0) return runRootPhase(tx, found, op, creation);
|
|
922
|
+
const { object } = found;
|
|
923
|
+
const module = moduleOf(tx, object, op);
|
|
924
|
+
const phase = phaseOf(tx, object, op);
|
|
925
|
+
const call = callOf(found, op, await beforeWrite(tx, phase, module, draftOf(op)));
|
|
926
|
+
if ("error" in call) tx.abort(call.error);
|
|
927
|
+
const text = await callCore(tx, found, op, call);
|
|
928
|
+
const row = decodeCoreRow(tx, object, () => JSON.parse(text));
|
|
929
|
+
recordChange(tx, object, op, row);
|
|
930
|
+
await onWrite(tx, phase, module, row.row);
|
|
931
|
+
return row.row;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Створення тенанта (спека П4 §6.13, Р-A6-14): `beforeWrite` кореня →
|
|
935
|
+
* `beforeWrite` довідника членства над `{ values: creatorMember }` → повторна
|
|
936
|
+
* перевірка обох чернеток → контекст кореня й ядро `<корінь>_create_root`
|
|
937
|
+
* однією одиницею черги → `onWrite` кореня → `onWrite` членства. Набір змін —
|
|
938
|
+
* один запис фази кореня, результат — рядок кореня.
|
|
939
|
+
*/
|
|
940
|
+
async function runRootPhase(tx, found, op, { membership }) {
|
|
941
|
+
const { object, target } = found;
|
|
942
|
+
if (op.action !== "create") throw new Error("internal: root phase");
|
|
943
|
+
const module = moduleOf(tx, object, op);
|
|
944
|
+
const phase = phaseOf(tx, object, op);
|
|
945
|
+
const draft = await beforeWrite(tx, phase, module, draftOf(op));
|
|
946
|
+
let member;
|
|
947
|
+
if (membership !== void 0) {
|
|
948
|
+
if (op.memberId === void 0) throw new Error("internal: member id");
|
|
949
|
+
const memberOp = {
|
|
950
|
+
action: "create",
|
|
951
|
+
object: {
|
|
952
|
+
kind: membership.kind,
|
|
953
|
+
name: membership.name
|
|
954
|
+
},
|
|
955
|
+
id: op.memberId,
|
|
956
|
+
values: op.creatorMember ?? {}
|
|
957
|
+
};
|
|
958
|
+
const memberModule = moduleOf(tx, membership, memberOp);
|
|
959
|
+
const memberPhase = phaseOf(tx, membership, memberOp);
|
|
960
|
+
member = {
|
|
961
|
+
object: membership,
|
|
962
|
+
module: memberModule,
|
|
963
|
+
phase: memberPhase,
|
|
964
|
+
draft: await beforeWrite(tx, memberPhase, memberModule, draftOf(memberOp), () => MEMBER$1)
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
if (draft.tabularSections !== void 0) tx.abort(invalid("tabularSections"));
|
|
968
|
+
let memberColumns;
|
|
969
|
+
if (member !== void 0) {
|
|
970
|
+
if (member.draft.tabularSections !== void 0) tx.abort(invalid(MEMBER$1));
|
|
971
|
+
const encoded = encodeMember(member.object, member.draft.values ?? {});
|
|
972
|
+
if ("error" in encoded) tx.abort(encoded.error);
|
|
973
|
+
memberColumns = encoded.columns;
|
|
974
|
+
}
|
|
975
|
+
const encoded = encodeItem(object, op, draft);
|
|
976
|
+
if ("error" in encoded) tx.abort(encoded.error);
|
|
977
|
+
const text = await callCore(tx, found, op, {
|
|
978
|
+
text: `SELECT ${fn(target)}($1::jsonb, $2::jsonb, $3::uuid) AS r`,
|
|
979
|
+
params: [
|
|
980
|
+
JSON.stringify(encoded.item),
|
|
981
|
+
memberColumns === void 0 ? null : JSON.stringify(memberColumns),
|
|
982
|
+
op.memberId ?? null
|
|
983
|
+
]
|
|
984
|
+
}, membership);
|
|
985
|
+
let result;
|
|
986
|
+
const rootRow = decodeCoreRow(tx, object, () => {
|
|
987
|
+
result = JSON.parse(text);
|
|
988
|
+
if (!isPlainObject(result)) throw new Error("root core result");
|
|
989
|
+
return result.root;
|
|
990
|
+
});
|
|
991
|
+
recordChange(tx, object, op, rootRow);
|
|
992
|
+
let memberRow;
|
|
993
|
+
if (member !== void 0) {
|
|
994
|
+
const { object: memberObject } = member;
|
|
995
|
+
memberRow = decodeCoreRow(tx, memberObject, () => result.member, false).row;
|
|
996
|
+
} else if (result.member !== null) coreAnomaly(tx, object);
|
|
997
|
+
await onWrite(tx, phase, module, rootRow.row);
|
|
998
|
+
if (member !== void 0) await onWrite(tx, member.phase, member.module, memberRow);
|
|
999
|
+
return rootRow.row;
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Контекст і виклик ядра — неподільна одиниця черги (Рт5, Р-A3-15): між
|
|
1003
|
+
* ними не стане оператор іншої фази. Повертає текст рядка ядра.
|
|
1004
|
+
*/
|
|
1005
|
+
async function callCore(tx, { object, target }, op, call, membership) {
|
|
1006
|
+
const context = {
|
|
1007
|
+
action: target.context,
|
|
1008
|
+
object: object.kindLabel,
|
|
1009
|
+
root: op.id
|
|
1010
|
+
};
|
|
1011
|
+
const { rows } = await tx.enqueue([{
|
|
1012
|
+
text: CONTEXT_TEXT,
|
|
1013
|
+
params: [JSON.stringify(context)]
|
|
1014
|
+
}, call], {
|
|
1015
|
+
kind: "write",
|
|
1016
|
+
object,
|
|
1017
|
+
operation: op.action,
|
|
1018
|
+
...membership === void 0 ? {} : { membership }
|
|
1019
|
+
});
|
|
1020
|
+
const text = rows[0]?.r;
|
|
1021
|
+
if (typeof text !== "string") coreAnomaly(tx, object);
|
|
1022
|
+
return text;
|
|
1023
|
+
}
|
|
1024
|
+
/** Відповідь бази не тієї форми — аномалія: назовні код, у журнал — подробиці. */
|
|
1025
|
+
function coreAnomaly(tx, object, cause) {
|
|
1026
|
+
tx.anomaly(new Error(`core row of ${object.kind}.${object.name} does not match the catalog`, { cause }));
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Рядок ядра за каталогом: ключ, версія й скоуп мусять бути. Без скоупу —
|
|
1030
|
+
* лише рядок членства з результату ядра кореня (`requireScope = false`).
|
|
1031
|
+
*/
|
|
1032
|
+
function decodeCoreRow(tx, object, parse, requireScope = true) {
|
|
1033
|
+
let row;
|
|
1034
|
+
let scope;
|
|
1035
|
+
try {
|
|
1036
|
+
const raw = parse();
|
|
1037
|
+
row = decodeRecord(object, raw);
|
|
1038
|
+
scope = object.scopeColumn === void 0 ? void 0 : raw[object.scopeColumn];
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
coreAnomaly(tx, object, error);
|
|
1041
|
+
}
|
|
1042
|
+
if (typeof row[object.keyName] !== "string" || typeof row[object.versionName] !== "number" || requireScope && object.scopeColumn !== void 0 && typeof scope !== "string") coreAnomaly(tx, object);
|
|
1043
|
+
return {
|
|
1044
|
+
row,
|
|
1045
|
+
scope
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
function recordChange(tx, object, op, { row, scope }) {
|
|
1049
|
+
tx.changes.push({
|
|
1050
|
+
object: {
|
|
1051
|
+
kind: object.kind,
|
|
1052
|
+
name: object.name
|
|
1053
|
+
},
|
|
1054
|
+
...object.scopeKindId === void 0 ? {} : { scopeKind: object.scopeKindId },
|
|
1055
|
+
...typeof scope === "string" ? { scope } : {},
|
|
1056
|
+
id: row[object.keyName],
|
|
1057
|
+
version: row[object.versionName],
|
|
1058
|
+
operation: op.action
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
// src/server/transaction.ts
|
|
1062
|
+
const RETRY_CODES = /* @__PURE__ */ new Set(["40001", "40P01"]);
|
|
1063
|
+
const INTERNAL = { code: "command.internal" };
|
|
1064
|
+
const statement = (text, ...params) => ({
|
|
1065
|
+
text,
|
|
1066
|
+
params
|
|
1067
|
+
});
|
|
1068
|
+
const BEGIN = statement("BEGIN ISOLATION LEVEL READ COMMITTED");
|
|
1069
|
+
const COMMIT = statement("COMMIT");
|
|
1070
|
+
const ROLLBACK = statement("ROLLBACK");
|
|
1071
|
+
/** `SET LOCAL ROLE` на роль команд — і в транзакції створення рантайму. */
|
|
1072
|
+
const COMMAND_ROLE = statement(`SET LOCAL ROLE ${ident(PLATFORM_ROLES.command)}`);
|
|
1073
|
+
const CLAIMS_TEXT = `SELECT set_config(${literal(SESSION_CLAIMS_SETTING)}, $1, true), set_config('TimeZone', 'UTC', true), set_config('bytea_output', 'hex', true)`;
|
|
1074
|
+
/** Claims, `TimeZone` і `bytea_output` транзакції — і команди, і читання. */
|
|
1075
|
+
const claimsStatement = (claims) => statement(CLAIMS_TEXT, claims);
|
|
1076
|
+
const CURRENT_USER = statement(`SELECT ${ident(PLATFORM_SCHEMA)}.${ident(CURRENT_USER_FUNCTION_NAME)}() AS user_id`);
|
|
1077
|
+
/**
|
|
1078
|
+
* Помилка порту як відмова спроби. Кожен `command.internal` мапінгу йде в
|
|
1079
|
+
* журнал з повною помилкою: назовні — лише код.
|
|
1080
|
+
*/
|
|
1081
|
+
function terminalOf(raw, state, phase) {
|
|
1082
|
+
const error = normalizeError(raw);
|
|
1083
|
+
if (!error.connectionLost && RETRY_CODES.has(error.code ?? "")) return {
|
|
1084
|
+
failure: new CommandFailure({ code: "command.retry-exhausted" }),
|
|
1085
|
+
retry: true,
|
|
1086
|
+
destroy: false
|
|
1087
|
+
};
|
|
1088
|
+
const mapped = mapDatabaseError(error, state.catalog, phase);
|
|
1089
|
+
if (logsDatabaseError(error, mapped)) state.log({
|
|
1090
|
+
kind: "database",
|
|
1091
|
+
error: raw
|
|
1092
|
+
});
|
|
1093
|
+
return {
|
|
1094
|
+
failure: new CommandFailure(mapped),
|
|
1095
|
+
retry: false,
|
|
1096
|
+
destroy: error.connectionLost
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* One attempt of a command on one connection: the statement queue
|
|
1101
|
+
* (Р-A3-15). Одиниця черги — оператор чи неподільна пара; перша відмова
|
|
1102
|
+
* закриває чергу, і далі порт отримує лише `ROLLBACK`.
|
|
1103
|
+
*/
|
|
1104
|
+
var Transaction = class {
|
|
1105
|
+
client;
|
|
1106
|
+
state;
|
|
1107
|
+
terminal;
|
|
1108
|
+
changes = [];
|
|
1109
|
+
afterCommit = [];
|
|
1110
|
+
/** The current user of the attempt (step 4 of §6.5). */
|
|
1111
|
+
user = "";
|
|
1112
|
+
act;
|
|
1113
|
+
tail = Promise.resolve();
|
|
1114
|
+
constructor(client, state) {
|
|
1115
|
+
this.client = client;
|
|
1116
|
+
this.state = state;
|
|
1117
|
+
}
|
|
1118
|
+
/** Runs a unit after the previous ones; resolves to its last result. */
|
|
1119
|
+
enqueue(unit, phase) {
|
|
1120
|
+
const result = this.tail.then(async () => {
|
|
1121
|
+
let last = {
|
|
1122
|
+
rows: [],
|
|
1123
|
+
command: ""
|
|
1124
|
+
};
|
|
1125
|
+
for (const { text, params } of unit) {
|
|
1126
|
+
if (this.terminal !== void 0) throw this.terminal.failure;
|
|
1127
|
+
try {
|
|
1128
|
+
last = await this.client.query(text, params);
|
|
1129
|
+
} catch (raw) {
|
|
1130
|
+
throw this.close(terminalOf(raw, this.state, phase));
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return last;
|
|
1134
|
+
});
|
|
1135
|
+
this.tail = result.catch(() => void 0);
|
|
1136
|
+
return result;
|
|
1137
|
+
}
|
|
1138
|
+
/** Closes the queue; the first failure decides the attempt. */
|
|
1139
|
+
close(terminal) {
|
|
1140
|
+
this.terminal ??= terminal;
|
|
1141
|
+
return terminal.failure;
|
|
1142
|
+
}
|
|
1143
|
+
/** Fails the attempt with a non-database error. */
|
|
1144
|
+
abort(error) {
|
|
1145
|
+
throw this.close({
|
|
1146
|
+
failure: new CommandFailure(error),
|
|
1147
|
+
retry: false,
|
|
1148
|
+
destroy: false
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Fails the attempt with `command.internal` for an anomaly — a database
|
|
1153
|
+
* answer of the wrong shape or an unexpected exception — and logs it.
|
|
1154
|
+
*/
|
|
1155
|
+
anomaly(error) {
|
|
1156
|
+
this.state.log({
|
|
1157
|
+
kind: "database",
|
|
1158
|
+
error
|
|
1159
|
+
});
|
|
1160
|
+
this.abort(INTERNAL);
|
|
1161
|
+
}
|
|
1162
|
+
/** Resolves once no unit is running. */
|
|
1163
|
+
settled() {
|
|
1164
|
+
return this.tail;
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
/**
|
|
1168
|
+
* Завершує невдалу спробу: обірване з'єднання знищується без `ROLLBACK`;
|
|
1169
|
+
* `ROLLBACK`, що сам упав, — теж (стан з'єднання невідомий).
|
|
1170
|
+
*/
|
|
1171
|
+
async function endFailed(client, destroy) {
|
|
1172
|
+
if (!destroy) try {
|
|
1173
|
+
await client.query(ROLLBACK.text, ROLLBACK.params);
|
|
1174
|
+
client.release();
|
|
1175
|
+
return;
|
|
1176
|
+
} catch {}
|
|
1177
|
+
client.release(true);
|
|
1178
|
+
}
|
|
1179
|
+
/** Кроки 1–7 транзакції команди (спека П4 §6.5). */
|
|
1180
|
+
async function attempt(state, command, claims, act, ops) {
|
|
1181
|
+
let client;
|
|
1182
|
+
try {
|
|
1183
|
+
client = await state.database.connect();
|
|
1184
|
+
} catch (raw) {
|
|
1185
|
+
return { terminal: terminalOf(raw, state, void 0) };
|
|
1186
|
+
}
|
|
1187
|
+
const tx = new Transaction(client, state);
|
|
1188
|
+
tx.act = act;
|
|
1189
|
+
const rows = [];
|
|
1190
|
+
let tag;
|
|
1191
|
+
try {
|
|
1192
|
+
tag = await inCommand({
|
|
1193
|
+
command,
|
|
1194
|
+
tx,
|
|
1195
|
+
depth: 0
|
|
1196
|
+
}, async () => {
|
|
1197
|
+
await tx.enqueue([BEGIN]);
|
|
1198
|
+
await tx.enqueue([claimsStatement(claims)]);
|
|
1199
|
+
await tx.enqueue([COMMAND_ROLE]);
|
|
1200
|
+
const { rows: users } = await tx.enqueue([CURRENT_USER]);
|
|
1201
|
+
const user = users[0]?.user_id;
|
|
1202
|
+
if (user == null) tx.abort({ code: "command.unauthenticated" });
|
|
1203
|
+
if (typeof user !== "string") tx.anomaly(/* @__PURE__ */ new Error("user id is not text"));
|
|
1204
|
+
tx.user = user;
|
|
1205
|
+
for (const op of ops) rows.push(await runPhase(tx, op));
|
|
1206
|
+
return (await tx.enqueue([COMMIT])).command;
|
|
1207
|
+
});
|
|
1208
|
+
} catch (error) {
|
|
1209
|
+
if (tx.terminal === void 0) {
|
|
1210
|
+
if (error instanceof CommandFailure) tx.close({
|
|
1211
|
+
failure: error,
|
|
1212
|
+
retry: false,
|
|
1213
|
+
destroy: false
|
|
1214
|
+
});
|
|
1215
|
+
else try {
|
|
1216
|
+
tx.anomaly(error);
|
|
1217
|
+
} catch {}
|
|
1218
|
+
}
|
|
1219
|
+
await tx.settled();
|
|
1220
|
+
const terminal = tx.terminal;
|
|
1221
|
+
await endFailed(client, terminal.destroy);
|
|
1222
|
+
return { terminal };
|
|
1223
|
+
}
|
|
1224
|
+
client.release();
|
|
1225
|
+
if (tag !== "COMMIT") {
|
|
1226
|
+
state.log({
|
|
1227
|
+
kind: "database",
|
|
1228
|
+
error: /* @__PURE__ */ new Error(`COMMIT answered ${tag}`)
|
|
1229
|
+
});
|
|
1230
|
+
return { terminal: {
|
|
1231
|
+
failure: new CommandFailure(INTERNAL),
|
|
1232
|
+
retry: false,
|
|
1233
|
+
destroy: false
|
|
1234
|
+
} };
|
|
1235
|
+
}
|
|
1236
|
+
return {
|
|
1237
|
+
result: {
|
|
1238
|
+
rows,
|
|
1239
|
+
changes: tx.changes
|
|
1240
|
+
},
|
|
1241
|
+
afterCommit: tx.afterCommit
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Runs `afterCommit` actions in order; a failing action is logged and the
|
|
1246
|
+
* next one still runs.
|
|
1247
|
+
*/
|
|
1248
|
+
async function runAfterCommit(actions, log) {
|
|
1249
|
+
for (const action of actions) try {
|
|
1250
|
+
await action();
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
log({
|
|
1253
|
+
kind: "afterCommit",
|
|
1254
|
+
error
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
/** A command: validation, attempts with retry, then `afterCommit` (§6.5). */
|
|
1259
|
+
async function runCommand(state, session, input) {
|
|
1260
|
+
rejectNested();
|
|
1261
|
+
const ops = prepareInput(state.catalog, input);
|
|
1262
|
+
let claims;
|
|
1263
|
+
try {
|
|
1264
|
+
claims = JSON.stringify(session);
|
|
1265
|
+
} catch {
|
|
1266
|
+
throw new CommandFailure(INTERNAL);
|
|
1267
|
+
}
|
|
1268
|
+
const snapshot = structuredClone(ops);
|
|
1269
|
+
const act = typeof session.act?.sub === "string" ? { sub: session.act.sub } : void 0;
|
|
1270
|
+
const command = { active: true };
|
|
1271
|
+
let outcome;
|
|
1272
|
+
try {
|
|
1273
|
+
for (let n = 0; n < state.maxAttempts; n++) {
|
|
1274
|
+
outcome = await attempt(state, command, claims, act, structuredClone(snapshot));
|
|
1275
|
+
if (!("terminal" in outcome) || !outcome.terminal.retry) break;
|
|
1276
|
+
}
|
|
1277
|
+
} finally {
|
|
1278
|
+
command.active = false;
|
|
1279
|
+
}
|
|
1280
|
+
if ("terminal" in outcome) throw outcome.terminal.failure;
|
|
1281
|
+
const { result, afterCommit } = outcome;
|
|
1282
|
+
if (afterCommit.length > 0) {
|
|
1283
|
+
const chain = outsideCommand(() => runAfterCommit(afterCommit, state.log));
|
|
1284
|
+
if (state.defer === void 0) await chain;
|
|
1285
|
+
else try {
|
|
1286
|
+
state.defer(chain);
|
|
1287
|
+
} catch (error) {
|
|
1288
|
+
state.log({
|
|
1289
|
+
kind: "defer",
|
|
1290
|
+
error
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
return result;
|
|
1295
|
+
}
|
|
1296
|
+
// src/server/runtime.ts
|
|
1297
|
+
/**
|
|
1298
|
+
* The request role the server reads under for a provider profile;
|
|
1299
|
+
* `undefined` — the profile names none (P4 spec Рт18). Таблиці — параметри,
|
|
1300
|
+
* щоб правило перевірялося на підставлених профілях.
|
|
1301
|
+
*/
|
|
1302
|
+
function readRoleOf(provider, purposes = LOGIN_ROLE_REQUEST_PURPOSES, roles = PROVIDER_API_ROLES) {
|
|
1303
|
+
return purposes[provider].includes("user") ? roles[provider].user : void 0;
|
|
1304
|
+
}
|
|
1305
|
+
/** Ключ модуля — `"<kind>.<name>"` об'єкта каталогу (Р-A3-17). */
|
|
1306
|
+
function checkModules(catalog, modules) {
|
|
1307
|
+
for (const [name, module] of Object.entries(modules)) {
|
|
1308
|
+
if (!catalog.objects.some((o) => `${o.kind}.${o.name}` === name)) throw new Error(`objectModules: unknown object "${name}"`);
|
|
1309
|
+
for (const [key, hook] of Object.entries(module)) if (!OBJECT_MODULE_KEYS.includes(key) || typeof hook !== "function") throw new Error(`objectModules: unknown hook "${name}.${key}"`);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
const BEGIN_READ_ONLY = "BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY";
|
|
1313
|
+
const MEMBER = "SELECT pg_has_role(session_user, $1, 'SET') AS member";
|
|
1314
|
+
const APPLIED_HASH = `SELECT ${ident(PLATFORM_SCHEMA)}.${ident(APPLIED_SNAPSHOT_HASH_FUNCTION_NAME)}() AS hash`;
|
|
1315
|
+
const NO_APPLIED_STATE = /* @__PURE__ */ new Set(["42883", "3F000"]);
|
|
1316
|
+
const UNDEFINED_OBJECT = "42704";
|
|
1317
|
+
const limitSchema = z.int().min(1).optional();
|
|
1318
|
+
/**
|
|
1319
|
+
* Створення рантайму — одна транзакція `READ ONLY` (Р-A3-12): членство в
|
|
1320
|
+
* ролі запиту, роль команд, хеш застосованого знімка.
|
|
1321
|
+
*/
|
|
1322
|
+
async function inspect(database, catalog, role, log) {
|
|
1323
|
+
const fail = (raw, error = normalizeError(raw)) => {
|
|
1324
|
+
const mapped = { code: error.connectionLost ? "command.unavailable" : "command.internal" };
|
|
1325
|
+
if (logsDatabaseError(error, mapped)) log({
|
|
1326
|
+
kind: "database",
|
|
1327
|
+
error: raw
|
|
1328
|
+
});
|
|
1329
|
+
return new CommandFailure(mapped);
|
|
1330
|
+
};
|
|
1331
|
+
let client;
|
|
1332
|
+
try {
|
|
1333
|
+
client = await database.connect();
|
|
1334
|
+
} catch (raw) {
|
|
1335
|
+
throw fail(raw);
|
|
1336
|
+
}
|
|
1337
|
+
let step = BEGIN_READ_ONLY;
|
|
1338
|
+
try {
|
|
1339
|
+
await client.query(BEGIN_READ_ONLY, []);
|
|
1340
|
+
let member = true;
|
|
1341
|
+
if (role !== void 0) {
|
|
1342
|
+
step = MEMBER;
|
|
1343
|
+
member = (await client.query(MEMBER, [role])).rows[0]?.member === "t";
|
|
1344
|
+
}
|
|
1345
|
+
step = COMMAND_ROLE.text;
|
|
1346
|
+
await client.query(COMMAND_ROLE.text, COMMAND_ROLE.params);
|
|
1347
|
+
step = APPLIED_HASH;
|
|
1348
|
+
const hash = (await client.query(APPLIED_HASH, [])).rows[0]?.hash;
|
|
1349
|
+
step = COMMIT.text;
|
|
1350
|
+
const { command } = await client.query(COMMIT.text, COMMIT.params);
|
|
1351
|
+
client.release();
|
|
1352
|
+
if (command !== "COMMIT" || typeof hash !== "string" && hash !== null) {
|
|
1353
|
+
log({
|
|
1354
|
+
kind: "database",
|
|
1355
|
+
error: /* @__PURE__ */ new Error(`runtime check answered ${command}`)
|
|
1356
|
+
});
|
|
1357
|
+
throw new CommandFailure({ code: "command.internal" });
|
|
1358
|
+
}
|
|
1359
|
+
return {
|
|
1360
|
+
member,
|
|
1361
|
+
applied: hash
|
|
1362
|
+
};
|
|
1363
|
+
} catch (raw) {
|
|
1364
|
+
if (raw instanceof CommandFailure) throw raw;
|
|
1365
|
+
const error = normalizeError(raw);
|
|
1366
|
+
await endFailed(client, error.connectionLost);
|
|
1367
|
+
if (step === APPLIED_HASH && NO_APPLIED_STATE.has(error.code ?? "")) return mismatch(catalog, null);
|
|
1368
|
+
if (step === MEMBER && error.code === UNDEFINED_OBJECT) {
|
|
1369
|
+
const { applied } = await inspect(database, catalog, void 0, log);
|
|
1370
|
+
return {
|
|
1371
|
+
member: false,
|
|
1372
|
+
applied
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
throw fail(raw, error);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
function mismatch(catalog, applied) {
|
|
1379
|
+
throw new CommandFailure({
|
|
1380
|
+
code: "command.model-mismatch",
|
|
1381
|
+
hashes: {
|
|
1382
|
+
catalog: catalog.snapshotHash,
|
|
1383
|
+
applied
|
|
1384
|
+
}
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Creates the command runtime (P4 spec §6.5): validates the catalog and the
|
|
1389
|
+
* object modules, checks the applied snapshot hash and the request-role
|
|
1390
|
+
* membership in one read-only transaction. Rejects with `CommandFailure`
|
|
1391
|
+
* (`command.model-mismatch`, `command.read-role-missing`, …); an invalid
|
|
1392
|
+
* catalog or module map throws before any database call.
|
|
1393
|
+
*/
|
|
1394
|
+
async function createCommandRuntime(options) {
|
|
1395
|
+
const catalog = runtimeCatalogSchema.parse(options.catalog);
|
|
1396
|
+
const objectModules = options.objectModules ?? {};
|
|
1397
|
+
checkModules(catalog, objectModules);
|
|
1398
|
+
const maxAttempts = limitSchema.parse(options.maxAttempts) ?? 3;
|
|
1399
|
+
const maxDepth = limitSchema.parse(options.maxDepth) ?? 8;
|
|
1400
|
+
const sink = options.log ?? ((entry) => console.error(entry));
|
|
1401
|
+
const log = (entry) => {
|
|
1402
|
+
try {
|
|
1403
|
+
sink(entry);
|
|
1404
|
+
} catch {}
|
|
1405
|
+
};
|
|
1406
|
+
const role = readRoleOf(catalog.provider);
|
|
1407
|
+
const { member, applied } = await inspect(options.database, catalog, role, log);
|
|
1408
|
+
if (applied !== catalog.snapshotHash) mismatch(catalog, applied);
|
|
1409
|
+
if (role !== void 0 && !member && options.readFallback !== true) throw new CommandFailure({
|
|
1410
|
+
code: "command.read-role-missing",
|
|
1411
|
+
role
|
|
1412
|
+
});
|
|
1413
|
+
const state = {
|
|
1414
|
+
database: options.database,
|
|
1415
|
+
catalog,
|
|
1416
|
+
objectModules,
|
|
1417
|
+
defer: options.defer,
|
|
1418
|
+
log,
|
|
1419
|
+
maxAttempts,
|
|
1420
|
+
maxDepth,
|
|
1421
|
+
readRole: member ? role : void 0
|
|
1422
|
+
};
|
|
1423
|
+
return {
|
|
1424
|
+
run: (session, input) => runCommand(state, session, input),
|
|
1425
|
+
read: (session, query) => readRows(state, session, query)
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Серверне читання (спека П4 §6.11): одна транзакція `READ ONLY` під роллю
|
|
1430
|
+
* запиту — політики бачать рівно те, що PostgREST з тими самими claims
|
|
1431
|
+
* (інваріант 10). Без повтору: §6.11 його не передбачає, `40001` тут — `command.internal`.
|
|
1432
|
+
*/
|
|
1433
|
+
async function readRows(state, session, query) {
|
|
1434
|
+
rejectNested();
|
|
1435
|
+
let claims;
|
|
1436
|
+
try {
|
|
1437
|
+
if (!sessionClaimsSchema.safeParse(session).success) throw new CommandFailure({ code: "command.unauthenticated" });
|
|
1438
|
+
claims = JSON.stringify(session);
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
if (error instanceof CommandFailure) throw error;
|
|
1441
|
+
throw new CommandFailure({ code: "command.internal" });
|
|
1442
|
+
}
|
|
1443
|
+
const prepared = prepareRead(state.catalog, query);
|
|
1444
|
+
if ("error" in prepared) throw new CommandFailure(prepared.error);
|
|
1445
|
+
const { object, statement } = prepared;
|
|
1446
|
+
const fail = (raw, phase) => {
|
|
1447
|
+
const error = normalizeError(raw);
|
|
1448
|
+
const mapped = mapDatabaseError(error, state.catalog, phase);
|
|
1449
|
+
if (logsDatabaseError(error, mapped)) state.log({
|
|
1450
|
+
kind: "database",
|
|
1451
|
+
error: raw
|
|
1452
|
+
});
|
|
1453
|
+
return {
|
|
1454
|
+
failure: new CommandFailure(mapped),
|
|
1455
|
+
destroy: error.connectionLost
|
|
1456
|
+
};
|
|
1457
|
+
};
|
|
1458
|
+
let client;
|
|
1459
|
+
try {
|
|
1460
|
+
client = await state.database.connect();
|
|
1461
|
+
} catch (raw) {
|
|
1462
|
+
throw fail(raw, void 0).failure;
|
|
1463
|
+
}
|
|
1464
|
+
const role = state.readRole === void 0 ? COMMAND_ROLE : {
|
|
1465
|
+
text: `SET LOCAL ROLE ${ident(state.readRole)}`,
|
|
1466
|
+
params: []
|
|
1467
|
+
};
|
|
1468
|
+
let rows;
|
|
1469
|
+
let tag;
|
|
1470
|
+
let phase;
|
|
1471
|
+
try {
|
|
1472
|
+
await client.query(BEGIN_READ_ONLY, []);
|
|
1473
|
+
const claimsSet = claimsStatement(claims);
|
|
1474
|
+
await client.query(claimsSet.text, claimsSet.params);
|
|
1475
|
+
await client.query(role.text, role.params);
|
|
1476
|
+
phase = {
|
|
1477
|
+
kind: "read",
|
|
1478
|
+
object
|
|
1479
|
+
};
|
|
1480
|
+
({rows} = await client.query(statement.text, statement.params));
|
|
1481
|
+
phase = void 0;
|
|
1482
|
+
({command: tag} = await client.query(COMMIT.text, COMMIT.params));
|
|
1483
|
+
} catch (raw) {
|
|
1484
|
+
const { failure, destroy } = fail(raw, phase);
|
|
1485
|
+
await endFailed(client, destroy);
|
|
1486
|
+
throw failure;
|
|
1487
|
+
}
|
|
1488
|
+
client.release();
|
|
1489
|
+
try {
|
|
1490
|
+
if (tag !== "COMMIT") throw new Error(`COMMIT answered ${tag}`);
|
|
1491
|
+
return rows.map((r) => {
|
|
1492
|
+
if (typeof r.row !== "string") throw new Error("read row is not text");
|
|
1493
|
+
return decodeRow(object, r.row);
|
|
1494
|
+
});
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
state.log({
|
|
1497
|
+
kind: "database",
|
|
1498
|
+
error
|
|
1499
|
+
});
|
|
1500
|
+
throw new CommandFailure({ code: "command.internal" });
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
export { CommandFailure, createCommandRuntime, fromPgPool, readRoleOf };
|