@datafn/server 0.0.2 → 0.0.3
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 -1
- package/dist/index.cjs +573 -231
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -146
- package/dist/index.d.ts +66 -146
- package/dist/index.js +573 -231
- package/dist/index.js.map +1 -1
- package/package.json +8 -6
package/dist/index.cjs
CHANGED
|
@@ -54,6 +54,65 @@ async function ensureInternalTable(adapter, tableName) {
|
|
|
54
54
|
await adapter.internal.ensureTable(tableName, columns);
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
// src/execution/sync/namespace-lock.ts
|
|
58
|
+
var AsyncMutex = class {
|
|
59
|
+
constructor() {
|
|
60
|
+
this.tail = Promise.resolve();
|
|
61
|
+
this.pendingCount = 0;
|
|
62
|
+
}
|
|
63
|
+
async runExclusive(task) {
|
|
64
|
+
this.pendingCount += 1;
|
|
65
|
+
const previous = this.tail;
|
|
66
|
+
let release;
|
|
67
|
+
this.tail = new Promise((resolve) => {
|
|
68
|
+
release = resolve;
|
|
69
|
+
});
|
|
70
|
+
await previous.catch(() => void 0);
|
|
71
|
+
try {
|
|
72
|
+
return await task();
|
|
73
|
+
} finally {
|
|
74
|
+
this.pendingCount -= 1;
|
|
75
|
+
release();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
isIdle() {
|
|
79
|
+
return this.pendingCount === 0;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var adapterNamespaceMutexes = /* @__PURE__ */ new WeakMap();
|
|
83
|
+
function getNamespaceMutexes(adapter) {
|
|
84
|
+
let namespaceMutexes = adapterNamespaceMutexes.get(adapter);
|
|
85
|
+
if (!namespaceMutexes) {
|
|
86
|
+
namespaceMutexes = /* @__PURE__ */ new Map();
|
|
87
|
+
adapterNamespaceMutexes.set(adapter, namespaceMutexes);
|
|
88
|
+
}
|
|
89
|
+
return namespaceMutexes;
|
|
90
|
+
}
|
|
91
|
+
function getMutex(namespaceMutexes, namespace) {
|
|
92
|
+
let mutex = namespaceMutexes.get(namespace);
|
|
93
|
+
if (!mutex) {
|
|
94
|
+
mutex = new AsyncMutex();
|
|
95
|
+
namespaceMutexes.set(namespace, mutex);
|
|
96
|
+
}
|
|
97
|
+
return mutex;
|
|
98
|
+
}
|
|
99
|
+
function withAdapterNamespaceLock(adapter, namespace, task) {
|
|
100
|
+
const namespaceMutexes = getNamespaceMutexes(adapter);
|
|
101
|
+
const mutex = getMutex(namespaceMutexes, namespace);
|
|
102
|
+
return mutex.runExclusive(task).finally(() => {
|
|
103
|
+
if (!mutex.isIdle()) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (namespaceMutexes.get(namespace) !== mutex) {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
namespaceMutexes.delete(namespace);
|
|
110
|
+
if (namespaceMutexes.size === 0) {
|
|
111
|
+
adapterNamespaceMutexes.delete(adapter);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
57
116
|
// src/execution/sync/sequence-store.ts
|
|
58
117
|
var RedisSequenceStore = class {
|
|
59
118
|
constructor(redis) {
|
|
@@ -129,51 +188,9 @@ var DatabaseSequenceStore = class {
|
|
|
129
188
|
await ensureInternalTable(this.db, "__datafn_meta");
|
|
130
189
|
this.ensured = true;
|
|
131
190
|
}
|
|
191
|
+
const needed = minSeq + 1;
|
|
132
192
|
try {
|
|
133
|
-
|
|
134
|
-
{ field: "namespace", op: "eq", value: namespace }
|
|
135
|
-
]);
|
|
136
|
-
const needed = minSeq + 1;
|
|
137
|
-
if (!meta) {
|
|
138
|
-
try {
|
|
139
|
-
await this.db.internal.create("__datafn_meta", {
|
|
140
|
-
id: `meta:${namespace}`,
|
|
141
|
-
namespace,
|
|
142
|
-
next_server_seq: needed
|
|
143
|
-
});
|
|
144
|
-
} catch {
|
|
145
|
-
}
|
|
146
|
-
} else {
|
|
147
|
-
const current = meta.next_server_seq || 1;
|
|
148
|
-
if (current < needed) {
|
|
149
|
-
await this.db.internal.update(
|
|
150
|
-
"__datafn_meta",
|
|
151
|
-
[{ field: "namespace", op: "eq", value: namespace }],
|
|
152
|
-
{ next_server_seq: needed }
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
} catch (error) {
|
|
157
|
-
this.logger?.warn("Failed to ensureMinSeq during failover", {
|
|
158
|
-
error: String(error),
|
|
159
|
-
operation: "ensureMinSeq"
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
async getNext(namespace) {
|
|
164
|
-
return (await this.getNextN(namespace, 1))[0];
|
|
165
|
-
}
|
|
166
|
-
async getNextN(namespace, count) {
|
|
167
|
-
if (!Number.isInteger(count) || count < 1 || count > 1e3) {
|
|
168
|
-
throw new Error("count must be a positive integer between 1 and 1000");
|
|
169
|
-
}
|
|
170
|
-
if (!this.ensured) {
|
|
171
|
-
await ensureInternalTable(this.db, "__datafn_meta");
|
|
172
|
-
this.ensured = true;
|
|
173
|
-
}
|
|
174
|
-
const MAX_RETRIES = 10;
|
|
175
|
-
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
176
|
-
try {
|
|
193
|
+
await withAdapterNamespaceLock(this.db, namespace, async () => {
|
|
177
194
|
const meta = await this.db.internal.findOne("__datafn_meta", [
|
|
178
195
|
{ field: "namespace", op: "eq", value: namespace }
|
|
179
196
|
]);
|
|
@@ -182,45 +199,116 @@ var DatabaseSequenceStore = class {
|
|
|
182
199
|
await this.db.internal.create("__datafn_meta", {
|
|
183
200
|
id: `meta:${namespace}`,
|
|
184
201
|
namespace,
|
|
185
|
-
next_server_seq:
|
|
202
|
+
next_server_seq: needed
|
|
186
203
|
});
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
204
|
+
} catch {
|
|
205
|
+
const currentMeta = await this.db.internal.findOne("__datafn_meta", [
|
|
206
|
+
{ field: "namespace", op: "eq", value: namespace }
|
|
207
|
+
]);
|
|
208
|
+
const current = currentMeta?.next_server_seq || 1;
|
|
209
|
+
if (current < needed) {
|
|
210
|
+
await this.db.internal.update(
|
|
211
|
+
"__datafn_meta",
|
|
212
|
+
[
|
|
213
|
+
{ field: "namespace", op: "eq", value: namespace },
|
|
214
|
+
{ field: "next_server_seq", op: "eq", value: current }
|
|
215
|
+
],
|
|
216
|
+
{ next_server_seq: needed }
|
|
217
|
+
);
|
|
218
|
+
}
|
|
191
219
|
}
|
|
192
220
|
} else {
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
221
|
+
const current = meta.next_server_seq || 1;
|
|
222
|
+
if (current < needed) {
|
|
223
|
+
await this.db.internal.update(
|
|
196
224
|
"__datafn_meta",
|
|
197
225
|
[
|
|
198
226
|
{ field: "namespace", op: "eq", value: namespace },
|
|
199
|
-
{ field: "next_server_seq", op: "eq", value:
|
|
227
|
+
{ field: "next_server_seq", op: "eq", value: current }
|
|
200
228
|
],
|
|
201
|
-
{ next_server_seq:
|
|
229
|
+
{ next_server_seq: needed }
|
|
202
230
|
);
|
|
203
|
-
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
} catch (error) {
|
|
235
|
+
this.logger?.warn("Failed to ensureMinSeq during failover", {
|
|
236
|
+
error: String(error),
|
|
237
|
+
operation: "ensureMinSeq"
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
async getNext(namespace) {
|
|
242
|
+
return (await this.getNextN(namespace, 1))[0];
|
|
243
|
+
}
|
|
244
|
+
async getNextN(namespace, count) {
|
|
245
|
+
if (!Number.isInteger(count) || count < 1 || count > 1e3) {
|
|
246
|
+
throw new Error("count must be a positive integer between 1 and 1000");
|
|
247
|
+
}
|
|
248
|
+
return await withAdapterNamespaceLock(this.db, namespace, async () => {
|
|
249
|
+
if (!this.ensured) {
|
|
250
|
+
await ensureInternalTable(this.db, "__datafn_meta");
|
|
251
|
+
this.ensured = true;
|
|
252
|
+
}
|
|
253
|
+
const MAX_RETRIES = 10;
|
|
254
|
+
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
255
|
+
try {
|
|
256
|
+
const meta = await this.db.internal.findOne("__datafn_meta", [
|
|
257
|
+
{ field: "namespace", op: "eq", value: namespace }
|
|
258
|
+
]);
|
|
259
|
+
if (!meta) {
|
|
260
|
+
try {
|
|
261
|
+
await this.db.internal.create("__datafn_meta", {
|
|
262
|
+
id: `meta:${namespace}`,
|
|
263
|
+
namespace,
|
|
264
|
+
next_server_seq: 1 + count
|
|
265
|
+
});
|
|
266
|
+
return Array.from({ length: count }, (_, i) => 1 + i);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
this.logger?.warn("Sequence allocation create retry", {
|
|
269
|
+
attempt,
|
|
270
|
+
error: String(error),
|
|
271
|
+
operation: "seq-create"
|
|
272
|
+
});
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
} else {
|
|
276
|
+
const currentSeq = meta.next_server_seq || 1;
|
|
277
|
+
try {
|
|
278
|
+
const affected = await this.db.internal.update(
|
|
279
|
+
"__datafn_meta",
|
|
280
|
+
[
|
|
281
|
+
{ field: "namespace", op: "eq", value: namespace },
|
|
282
|
+
{ field: "next_server_seq", op: "eq", value: currentSeq }
|
|
283
|
+
],
|
|
284
|
+
{ next_server_seq: currentSeq + count }
|
|
285
|
+
);
|
|
286
|
+
if (affected === 0) {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
return Array.from({ length: count }, (_, i) => currentSeq + i);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
this.logger?.warn("Sequence allocation CAS retry", {
|
|
292
|
+
attempt,
|
|
293
|
+
error: String(error),
|
|
294
|
+
operation: "seq-cas"
|
|
295
|
+
});
|
|
204
296
|
continue;
|
|
205
297
|
}
|
|
206
|
-
return Array.from({ length: count }, (_, i) => currentSeq + i);
|
|
207
|
-
} catch (error) {
|
|
208
|
-
this.logger?.warn("Sequence allocation CAS retry", { attempt, error: String(error), operation: "seq-cas" });
|
|
209
|
-
continue;
|
|
210
298
|
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (attempt === MAX_RETRIES - 1) {
|
|
301
|
+
this.logger?.error("Failed to get next serverSeq after max retries", {
|
|
302
|
+
error: String(error),
|
|
303
|
+
operation: "getNextN",
|
|
304
|
+
resource: "__datafn_meta"
|
|
305
|
+
});
|
|
306
|
+
throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
|
|
307
|
+
}
|
|
220
308
|
}
|
|
221
309
|
}
|
|
222
|
-
|
|
223
|
-
|
|
310
|
+
throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
|
|
311
|
+
});
|
|
224
312
|
}
|
|
225
313
|
async getCurrent(namespace) {
|
|
226
314
|
if (!this.ensured) {
|
|
@@ -415,8 +503,11 @@ function createStatusHandler(validatedSchema, limits, getServerTime = () => Date
|
|
|
415
503
|
"dfql.query",
|
|
416
504
|
"dfql.mutation",
|
|
417
505
|
"dfql.transact",
|
|
418
|
-
"
|
|
419
|
-
"
|
|
506
|
+
"sync.seed",
|
|
507
|
+
"sync.clone",
|
|
508
|
+
"sync.pull",
|
|
509
|
+
"sync.push",
|
|
510
|
+
"sync.reconcile"
|
|
420
511
|
],
|
|
421
512
|
limits,
|
|
422
513
|
// SRV-008: Round to nearest minute to avoid fingerprinting via exact timestamps
|
|
@@ -620,6 +711,9 @@ var VALID_OPERATIONS = /* @__PURE__ */ new Set([
|
|
|
620
711
|
var RECORD_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set(["insert", "merge", "replace"]);
|
|
621
712
|
var DFQL_SHARE_SCOPE_INVALID_CODE = "DFQL_SHARE_SCOPE_INVALID";
|
|
622
713
|
var DFQL_PRINCIPAL_INVALID_CODE = "DFQL_PRINCIPAL_INVALID";
|
|
714
|
+
function isShareableCapability(entry) {
|
|
715
|
+
return typeof entry === "object" && entry !== null && "shareable" in entry;
|
|
716
|
+
}
|
|
623
717
|
function normalizeNonEmptyString(value) {
|
|
624
718
|
if (typeof value !== "string") {
|
|
625
719
|
return null;
|
|
@@ -689,9 +783,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
|
|
|
689
783
|
const hasArchivableCapability3 = resolvedCapabilities.some(
|
|
690
784
|
(capability) => capability === "archivable"
|
|
691
785
|
);
|
|
692
|
-
const shareableCapability = resolvedCapabilities.find(
|
|
693
|
-
(capability) => typeof capability === "object" && capability !== null && "shareable" in capability
|
|
694
|
-
);
|
|
786
|
+
const shareableCapability = resolvedCapabilities.find(isShareableCapability);
|
|
695
787
|
const isShareOperation = m.operation === "share" || m.operation === "unshare";
|
|
696
788
|
if ((m.operation === "trash" || m.operation === "restore") && !hasTrashCapability3) {
|
|
697
789
|
return vErr(
|
|
@@ -818,7 +910,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
|
|
|
818
910
|
);
|
|
819
911
|
}
|
|
820
912
|
const allowedLevels = shareableCapability?.shareable.levels ?? [];
|
|
821
|
-
if (!allowedLevels.
|
|
913
|
+
if (!allowedLevels.some((candidate) => candidate === shareWith.level)) {
|
|
822
914
|
return vErr(
|
|
823
915
|
"DFQL_INVALID",
|
|
824
916
|
`Invalid DFQL: shareWith.level must be one of [${allowedLevels.join(", ")}]`,
|
|
@@ -885,7 +977,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
|
|
|
885
977
|
const resource2 = resourceResult.result;
|
|
886
978
|
const record2 = m.record;
|
|
887
979
|
for (const field of resource2.fields) {
|
|
888
|
-
if (field.required &&
|
|
980
|
+
if (field.required && field.default === void 0 && field.name !== "id" && !field.readonly) {
|
|
889
981
|
if (!(field.name in record2) || record2[field.name] === null || record2[field.name] === void 0) {
|
|
890
982
|
return vErr(
|
|
891
983
|
"DFQL_INVALID",
|
|
@@ -1028,7 +1120,7 @@ function validateRelationDepth(token, maxDepth) {
|
|
|
1028
1120
|
// src/validation/query.ts
|
|
1029
1121
|
function validateQuery(query, index, basePath = "$", limits) {
|
|
1030
1122
|
if (typeof query !== "object" || query === null || Array.isArray(query)) {
|
|
1031
|
-
return vErr("DFQL_INVALID", "Invalid DFQL: expected object
|
|
1123
|
+
return vErr("DFQL_INVALID", "Invalid DFQL: expected object", basePath);
|
|
1032
1124
|
}
|
|
1033
1125
|
const q = query;
|
|
1034
1126
|
const queryPollutionCheck = core.checkPrototypePollution(q);
|
|
@@ -1079,7 +1171,7 @@ function validateQuery(query, index, basePath = "$", limits) {
|
|
|
1079
1171
|
}
|
|
1080
1172
|
if (q.cursor && typeof q.cursor === "object") {
|
|
1081
1173
|
const cursor = q.cursor;
|
|
1082
|
-
const hasCursor = cursor.after || cursor.before;
|
|
1174
|
+
const hasCursor = cursor.after !== void 0 || cursor.before !== void 0;
|
|
1083
1175
|
if (hasCursor) {
|
|
1084
1176
|
if (!q.sort) {
|
|
1085
1177
|
q.sort = ["id:asc"];
|
|
@@ -1341,10 +1433,10 @@ function validateSelectTokens(select, resourceName, resource, index, fieldNames,
|
|
|
1341
1433
|
return vOk(void 0);
|
|
1342
1434
|
}
|
|
1343
1435
|
function validateCursor(cursor, sort) {
|
|
1344
|
-
if (cursor.after && (typeof cursor.after !== "object" || cursor.after === null)) {
|
|
1436
|
+
if (cursor.after !== void 0 && (typeof cursor.after !== "object" || cursor.after === null)) {
|
|
1345
1437
|
return vErr("DFQL_INVALID", "Invalid DFQL: cursor.after must be object", "cursor.after");
|
|
1346
1438
|
}
|
|
1347
|
-
if (cursor.before && (typeof cursor.before !== "object" || cursor.before === null)) {
|
|
1439
|
+
if (cursor.before !== void 0 && (typeof cursor.before !== "object" || cursor.before === null)) {
|
|
1348
1440
|
return vErr("DFQL_INVALID", "Invalid DFQL: cursor.before must be object", "cursor.before");
|
|
1349
1441
|
}
|
|
1350
1442
|
return vOk(void 0);
|
|
@@ -1375,6 +1467,9 @@ function validateGroupBy(q, fieldNames, relationNames) {
|
|
|
1375
1467
|
if (q.select && Array.isArray(q.select)) {
|
|
1376
1468
|
for (let i = 0; i < q.select.length; i++) {
|
|
1377
1469
|
const token = q.select[i];
|
|
1470
|
+
if (typeof token !== "string") {
|
|
1471
|
+
continue;
|
|
1472
|
+
}
|
|
1378
1473
|
if (token.includes(".*") || token.includes(".**") || token.endsWith(".#")) {
|
|
1379
1474
|
return vErr(
|
|
1380
1475
|
"DFQL_UNSUPPORTED",
|
|
@@ -2107,6 +2202,9 @@ function resolveDualReadAccessDecision(params) {
|
|
|
2107
2202
|
}
|
|
2108
2203
|
|
|
2109
2204
|
// src/validation/authz.ts
|
|
2205
|
+
function isShareableCapability2(entry) {
|
|
2206
|
+
return typeof entry === "object" && entry !== null && "shareable" in entry;
|
|
2207
|
+
}
|
|
2110
2208
|
function getCapabilityFieldSets(schema, resource) {
|
|
2111
2209
|
const resolvedCapabilities = core.resolveCapabilities(
|
|
2112
2210
|
schema.capabilities,
|
|
@@ -2420,9 +2518,7 @@ function canonicalizePrincipalFromUserId2(value) {
|
|
|
2420
2518
|
}
|
|
2421
2519
|
function getShareableCapability(resource, schema) {
|
|
2422
2520
|
const resolved = core.resolveCapabilities(schema.capabilities, resource.capabilities);
|
|
2423
|
-
return resolved.find(
|
|
2424
|
-
(entry) => typeof entry === "object" && entry !== null && "shareable" in entry
|
|
2425
|
-
);
|
|
2521
|
+
return resolved.find(isShareableCapability2);
|
|
2426
2522
|
}
|
|
2427
2523
|
function isPrivateShareableResource(schema, resourceName) {
|
|
2428
2524
|
const resource = schema.resources.find((r) => r.name === resourceName);
|
|
@@ -2510,6 +2606,76 @@ async function resolveAccessLevelFromV2(db, resource, recordId, actorId, namespa
|
|
|
2510
2606
|
}
|
|
2511
2607
|
return null;
|
|
2512
2608
|
}
|
|
2609
|
+
async function hasResourceScopeOwnerAccess(db, resource, actorId, namespace) {
|
|
2610
|
+
if (!actorId) {
|
|
2611
|
+
return false;
|
|
2612
|
+
}
|
|
2613
|
+
const principalResult = await resolveEffectivePrincipals({
|
|
2614
|
+
namespace,
|
|
2615
|
+
actorId,
|
|
2616
|
+
store: {
|
|
2617
|
+
getDirectMemberships: async ({ namespace: actorNamespace, actorId: actor }) => {
|
|
2618
|
+
const rows = await db.findMany({
|
|
2619
|
+
model: PRINCIPAL_MEMBERSHIPS_TABLE,
|
|
2620
|
+
where: [{ field: "actorId", operator: "eq", value: actor }],
|
|
2621
|
+
namespace: actorNamespace
|
|
2622
|
+
});
|
|
2623
|
+
return rows.map((row) => row).filter((row) => isGrantActive2(row)).map(
|
|
2624
|
+
(row) => typeof row.principalId === "string" ? row.principalId : ""
|
|
2625
|
+
).filter((principalId) => principalId.length > 0);
|
|
2626
|
+
},
|
|
2627
|
+
getHierarchyParents: async ({ namespace: actorNamespace, principalIds }) => {
|
|
2628
|
+
const edges = [];
|
|
2629
|
+
for (const principalId of principalIds) {
|
|
2630
|
+
const rows = await db.findMany({
|
|
2631
|
+
model: PRINCIPAL_HIERARCHY_TABLE,
|
|
2632
|
+
where: [{ field: "principalId", operator: "eq", value: principalId }],
|
|
2633
|
+
namespace: actorNamespace
|
|
2634
|
+
});
|
|
2635
|
+
for (const row of rows) {
|
|
2636
|
+
const edge = row;
|
|
2637
|
+
if (!isGrantActive2(edge)) {
|
|
2638
|
+
continue;
|
|
2639
|
+
}
|
|
2640
|
+
if (typeof edge.principalId === "string" && typeof edge.parentPrincipalId === "string") {
|
|
2641
|
+
edges.push({
|
|
2642
|
+
principalId: edge.principalId,
|
|
2643
|
+
parentPrincipalId: edge.parentPrincipalId
|
|
2644
|
+
});
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
return edges;
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
});
|
|
2652
|
+
if (principalResult.effectivePrincipals.includes(namespace)) {
|
|
2653
|
+
return true;
|
|
2654
|
+
}
|
|
2655
|
+
for (const principalId of principalResult.effectivePrincipals) {
|
|
2656
|
+
const rows = await db.findMany({
|
|
2657
|
+
model: GLOBAL_PERMISSIONS_TABLE,
|
|
2658
|
+
where: [
|
|
2659
|
+
{ field: "resourceType", operator: "eq", value: resource },
|
|
2660
|
+
{ field: "resourceNs", operator: "eq", value: namespace },
|
|
2661
|
+
{ field: "principalId", operator: "eq", value: principalId },
|
|
2662
|
+
{ field: "level", operator: "eq", value: "owner" }
|
|
2663
|
+
],
|
|
2664
|
+
namespace
|
|
2665
|
+
});
|
|
2666
|
+
const hasScopeOwnerGrant = rows.some((row) => {
|
|
2667
|
+
const grant = row;
|
|
2668
|
+
if (!isGrantActive2(grant)) {
|
|
2669
|
+
return false;
|
|
2670
|
+
}
|
|
2671
|
+
return grant.grantKind === "scope" || grant.resourceId === null;
|
|
2672
|
+
});
|
|
2673
|
+
if (hasScopeOwnerGrant) {
|
|
2674
|
+
return true;
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
return false;
|
|
2678
|
+
}
|
|
2513
2679
|
async function resolveAccessLevel(db, schema, resource, recordId, actorId, namespace) {
|
|
2514
2680
|
if (!actorId) {
|
|
2515
2681
|
return null;
|
|
@@ -2585,7 +2751,23 @@ async function validateShareableOperationAccess(input) {
|
|
|
2585
2751
|
path: "operation"
|
|
2586
2752
|
};
|
|
2587
2753
|
}
|
|
2588
|
-
if (input.operation === "insert"
|
|
2754
|
+
if (input.operation === "insert") {
|
|
2755
|
+
return { ok: true };
|
|
2756
|
+
}
|
|
2757
|
+
if ((input.operation === "share" || input.operation === "unshare") && (typeof input.id !== "string" || input.id.length === 0)) {
|
|
2758
|
+
if (!await hasResourceScopeOwnerAccess(
|
|
2759
|
+
input.db,
|
|
2760
|
+
input.resource,
|
|
2761
|
+
input.actorId,
|
|
2762
|
+
input.namespace
|
|
2763
|
+
)) {
|
|
2764
|
+
return {
|
|
2765
|
+
ok: false,
|
|
2766
|
+
code: "FORBIDDEN",
|
|
2767
|
+
message: "Authorization denied",
|
|
2768
|
+
path: "operation"
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2589
2771
|
return { ok: true };
|
|
2590
2772
|
}
|
|
2591
2773
|
if (typeof input.id !== "string" || input.id.length === 0) {
|
|
@@ -2622,6 +2804,7 @@ async function validateShareableOperationAccess(input) {
|
|
|
2622
2804
|
async function runBounded(tasks, concurrency) {
|
|
2623
2805
|
const results = new Array(tasks.length);
|
|
2624
2806
|
let nextIndex = 0;
|
|
2807
|
+
const effectiveConcurrency = tasks.length === 0 ? 0 : Math.max(1, concurrency);
|
|
2625
2808
|
async function worker() {
|
|
2626
2809
|
while (nextIndex < tasks.length) {
|
|
2627
2810
|
const idx = nextIndex++;
|
|
@@ -2629,7 +2812,7 @@ async function runBounded(tasks, concurrency) {
|
|
|
2629
2812
|
}
|
|
2630
2813
|
}
|
|
2631
2814
|
const workers = Array.from(
|
|
2632
|
-
{ length: Math.min(
|
|
2815
|
+
{ length: Math.min(effectiveConcurrency, tasks.length) },
|
|
2633
2816
|
() => worker()
|
|
2634
2817
|
);
|
|
2635
2818
|
await Promise.all(workers);
|
|
@@ -2774,7 +2957,7 @@ function validateSortForCursor(sortTerms) {
|
|
|
2774
2957
|
// src/execution/query/pagination.ts
|
|
2775
2958
|
function applyLimitOffset(records, limit, offset) {
|
|
2776
2959
|
const start = offset || 0;
|
|
2777
|
-
const end = limit ? start + limit
|
|
2960
|
+
const end = limit == null ? void 0 : start + limit;
|
|
2778
2961
|
return records.slice(start, end);
|
|
2779
2962
|
}
|
|
2780
2963
|
function computeNextCursor(results, sortTerms, limit) {
|
|
@@ -2863,7 +3046,7 @@ function isNestedSelectToken(token) {
|
|
|
2863
3046
|
}
|
|
2864
3047
|
if (parts.length === 2) {
|
|
2865
3048
|
const child = parts[1];
|
|
2866
|
-
return child !== "*" && child !== "#" && child !== "*#";
|
|
3049
|
+
return child !== "*" && child !== "**" && child !== "#" && child !== "*#";
|
|
2867
3050
|
}
|
|
2868
3051
|
return true;
|
|
2869
3052
|
}
|
|
@@ -3627,6 +3810,7 @@ function classifyQuery(query, schema) {
|
|
|
3627
3810
|
}
|
|
3628
3811
|
function hasInMemoryFilterPatterns(filters) {
|
|
3629
3812
|
for (const [key, value] of Object.entries(filters)) {
|
|
3813
|
+
if (key === "$or") return true;
|
|
3630
3814
|
if (key.includes(".")) return true;
|
|
3631
3815
|
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
3632
3816
|
const ops = value;
|
|
@@ -4369,6 +4553,9 @@ var REQUIRED_ACL_INDEXES = [
|
|
|
4369
4553
|
"idx_perm_principal",
|
|
4370
4554
|
"idx_perm_resource_ns_principal"
|
|
4371
4555
|
];
|
|
4556
|
+
function isShareableCapability3(entry) {
|
|
4557
|
+
return typeof entry === "object" && entry !== null && "shareable" in entry;
|
|
4558
|
+
}
|
|
4372
4559
|
function normalizeIndexNames(indexes) {
|
|
4373
4560
|
const normalized = /* @__PURE__ */ new Set();
|
|
4374
4561
|
for (const index of indexes) {
|
|
@@ -4441,15 +4628,15 @@ function injectCapabilityAutoFilters(query, schema) {
|
|
|
4441
4628
|
if (resolvedCapabilities.some((capability) => capability === "archivable") && metadata.includeArchived !== true) {
|
|
4442
4629
|
autoFilters.push({ isArchived: { $ne: true } });
|
|
4443
4630
|
}
|
|
4444
|
-
const shareableCapability = resolvedCapabilities.find(
|
|
4445
|
-
(capability) => typeof capability === "object" && capability !== null && "shareable" in capability
|
|
4446
|
-
);
|
|
4631
|
+
const shareableCapability = resolvedCapabilities.find(isShareableCapability3);
|
|
4447
4632
|
if (shareableCapability?.shareable.default === "private" && metadata.accessMode !== "sharedWithMe") {
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
4633
|
+
if (metadata.hasShareableScopeAccess === true) ; else {
|
|
4634
|
+
const accessIds = Array.isArray(metadata.shareableAccessIds) ? metadata.shareableAccessIds : [];
|
|
4635
|
+
if (accessIds.length === 0) {
|
|
4636
|
+
autoFilters.push({ id: { $in: ["__datafn_no_access__"] } });
|
|
4637
|
+
} else {
|
|
4638
|
+
autoFilters.push({ id: { $in: accessIds } });
|
|
4639
|
+
}
|
|
4453
4640
|
}
|
|
4454
4641
|
}
|
|
4455
4642
|
if (autoFilters.length === 0) {
|
|
@@ -4606,21 +4793,20 @@ function projectFieldsPushdown(record, resource, schema, select, omit) {
|
|
|
4606
4793
|
baseFields.add(capabilityField.name);
|
|
4607
4794
|
}
|
|
4608
4795
|
for (const f of resourceSchema.fields) baseFields.add(f.name);
|
|
4609
|
-
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
if (record[f.name] !== void 0) {
|
|
4614
|
-
result[f.name] = record[f.name];
|
|
4796
|
+
const assignBaseFields = (target) => {
|
|
4797
|
+
for (const field of baseFields) {
|
|
4798
|
+
if (record[field] !== void 0) {
|
|
4799
|
+
target[field] = record[field];
|
|
4615
4800
|
}
|
|
4616
4801
|
}
|
|
4802
|
+
};
|
|
4803
|
+
let result;
|
|
4804
|
+
if (!select || select.length === 0) {
|
|
4805
|
+
result = {};
|
|
4806
|
+
assignBaseFields(result);
|
|
4617
4807
|
} else if (select.includes("*")) {
|
|
4618
|
-
result = {
|
|
4619
|
-
|
|
4620
|
-
if (record[f.name] !== void 0) {
|
|
4621
|
-
result[f.name] = record[f.name];
|
|
4622
|
-
}
|
|
4623
|
-
}
|
|
4808
|
+
result = {};
|
|
4809
|
+
assignBaseFields(result);
|
|
4624
4810
|
for (const token of select) {
|
|
4625
4811
|
if (token !== "*" && baseFields.has(token) && !(token in result)) {
|
|
4626
4812
|
result[token] = record[token];
|
|
@@ -5017,6 +5203,12 @@ async function executeSearchQuery(query, schema, store, searchProvider, resolveC
|
|
|
5017
5203
|
const chunkQuery = {
|
|
5018
5204
|
...query,
|
|
5019
5205
|
filters: mergedFilters,
|
|
5206
|
+
select: ["id"],
|
|
5207
|
+
omit: void 0,
|
|
5208
|
+
groupBy: void 0,
|
|
5209
|
+
aggregations: void 0,
|
|
5210
|
+
having: void 0,
|
|
5211
|
+
count: void 0,
|
|
5020
5212
|
limit: void 0,
|
|
5021
5213
|
offset: void 0,
|
|
5022
5214
|
sort: void 0,
|
|
@@ -5201,7 +5393,7 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
|
|
|
5201
5393
|
return void 0;
|
|
5202
5394
|
}
|
|
5203
5395
|
if (!actorId) {
|
|
5204
|
-
return [];
|
|
5396
|
+
return { shareableAccessIds: [] };
|
|
5205
5397
|
}
|
|
5206
5398
|
const ids = /* @__PURE__ */ new Set();
|
|
5207
5399
|
const readMode = getSpv2MigrationRuntimeConfig().readMode;
|
|
@@ -5262,19 +5454,15 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
|
|
|
5262
5454
|
}
|
|
5263
5455
|
}
|
|
5264
5456
|
if (hasScopeGrant) {
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
});
|
|
5270
|
-
for (const row of scopedRows) {
|
|
5271
|
-
if (typeof row.id === "string") {
|
|
5272
|
-
ids.add(row.id);
|
|
5273
|
-
}
|
|
5274
|
-
}
|
|
5457
|
+
return {
|
|
5458
|
+
shareableAccessIds: [...ids].sort((a, b) => a.localeCompare(b)),
|
|
5459
|
+
hasShareableScopeAccess: true
|
|
5460
|
+
};
|
|
5275
5461
|
}
|
|
5276
5462
|
}
|
|
5277
|
-
return
|
|
5463
|
+
return {
|
|
5464
|
+
shareableAccessIds: [...ids].sort((a, b) => a.localeCompare(b))
|
|
5465
|
+
};
|
|
5278
5466
|
};
|
|
5279
5467
|
const mergeFilters = (existingFilters, nextFilter) => {
|
|
5280
5468
|
if (!existingFilters || Object.keys(existingFilters).length === 0) {
|
|
@@ -5672,12 +5860,12 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
|
|
|
5672
5860
|
String(query.resource),
|
|
5673
5861
|
namespace,
|
|
5674
5862
|
actorId
|
|
5675
|
-
).then((
|
|
5863
|
+
).then((shareableAccess) => {
|
|
5676
5864
|
const queryWithMetadata = {
|
|
5677
5865
|
...query,
|
|
5678
5866
|
metadata: {
|
|
5679
5867
|
...metadata ?? {},
|
|
5680
|
-
...
|
|
5868
|
+
...shareableAccess ?? {}
|
|
5681
5869
|
}
|
|
5682
5870
|
};
|
|
5683
5871
|
const queryWithAutoFilters = injectCapabilityAutoFilters(
|
|
@@ -5842,66 +6030,72 @@ var ChangeTrackingService = class _ChangeTrackingService {
|
|
|
5842
6030
|
return (await this.getNextServerSeqBatchFromDb(1))[0];
|
|
5843
6031
|
}
|
|
5844
6032
|
async getNextServerSeqBatchFromDb(count) {
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
const MAX_RETRIES = 10;
|
|
5850
|
-
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
5851
|
-
if (attempt > 0) {
|
|
5852
|
-
await sleep(10 * Math.pow(2, attempt - 1));
|
|
6033
|
+
return await withAdapterNamespaceLock(this.db, this.namespace, async () => {
|
|
6034
|
+
if (!this.metaEnsured) {
|
|
6035
|
+
await ensureInternalTable(this.db, "__datafn_meta");
|
|
6036
|
+
this.metaEnsured = true;
|
|
5853
6037
|
}
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
6038
|
+
const MAX_RETRIES = 10;
|
|
6039
|
+
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
6040
|
+
if (attempt > 0) {
|
|
6041
|
+
await sleep(10 * Math.pow(2, attempt - 1));
|
|
6042
|
+
}
|
|
6043
|
+
try {
|
|
6044
|
+
const meta = await this.db.internal.findOne("__datafn_meta", [
|
|
6045
|
+
{ field: "namespace", op: "eq", value: this.namespace }
|
|
6046
|
+
]);
|
|
6047
|
+
if (!meta) {
|
|
6048
|
+
try {
|
|
6049
|
+
await this.db.internal.create("__datafn_meta", {
|
|
6050
|
+
id: `meta:${this.namespace}`,
|
|
6051
|
+
namespace: this.namespace,
|
|
6052
|
+
next_server_seq: 1 + count
|
|
6053
|
+
});
|
|
6054
|
+
return Array.from({ length: count }, (_, i) => 1 + i);
|
|
6055
|
+
} catch (createError) {
|
|
6056
|
+
continue;
|
|
6057
|
+
}
|
|
6058
|
+
} else {
|
|
6059
|
+
const currentSeq = meta.next_server_seq || 1;
|
|
6060
|
+
try {
|
|
6061
|
+
const affected = await this.db.internal.update(
|
|
6062
|
+
"__datafn_meta",
|
|
6063
|
+
[
|
|
6064
|
+
{ field: "namespace", op: "eq", value: this.namespace },
|
|
6065
|
+
{ field: "next_server_seq", op: "eq", value: currentSeq }
|
|
6066
|
+
],
|
|
6067
|
+
{ next_server_seq: currentSeq + count }
|
|
6068
|
+
);
|
|
6069
|
+
if (affected === 0) {
|
|
6070
|
+
continue;
|
|
6071
|
+
}
|
|
6072
|
+
return Array.from({ length: count }, (_, i) => currentSeq + i);
|
|
6073
|
+
} catch (updateError) {
|
|
5881
6074
|
continue;
|
|
5882
6075
|
}
|
|
5883
|
-
return Array.from({ length: count }, (_, i) => currentSeq + i);
|
|
5884
|
-
} catch (updateError) {
|
|
5885
|
-
continue;
|
|
5886
6076
|
}
|
|
5887
|
-
}
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
6077
|
+
} catch (error) {
|
|
6078
|
+
if (attempt === MAX_RETRIES - 1) {
|
|
6079
|
+
this.logger?.error("Failed to get next serverSeq after max retries", {
|
|
6080
|
+
error: String(error),
|
|
6081
|
+
operation: "getNextServerSeqBatchFromDb",
|
|
6082
|
+
resource: "__datafn_meta"
|
|
6083
|
+
});
|
|
6084
|
+
throw new Error(
|
|
6085
|
+
"INTERNAL: Failed to allocate serverSeq after maximum retries"
|
|
6086
|
+
);
|
|
6087
|
+
}
|
|
6088
|
+
this.logger?.warn("Sequence batch CAS retry", {
|
|
6089
|
+
attempt,
|
|
5891
6090
|
error: String(error),
|
|
5892
|
-
operation: "
|
|
5893
|
-
resource: "__datafn_meta"
|
|
6091
|
+
operation: "seq-batch-cas"
|
|
5894
6092
|
});
|
|
5895
|
-
throw new Error(
|
|
5896
|
-
"INTERNAL: Failed to allocate serverSeq after maximum retries"
|
|
5897
|
-
);
|
|
5898
6093
|
}
|
|
5899
|
-
this.logger?.warn("Sequence batch CAS retry", { attempt, error: String(error), operation: "seq-batch-cas" });
|
|
5900
6094
|
}
|
|
5901
|
-
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
);
|
|
6095
|
+
throw new Error(
|
|
6096
|
+
"INTERNAL: Failed to allocate serverSeq after maximum retries"
|
|
6097
|
+
);
|
|
6098
|
+
});
|
|
5905
6099
|
}
|
|
5906
6100
|
/**
|
|
5907
6101
|
* Record a change entry for a mutation (delegates to recordChanges)
|
|
@@ -6083,12 +6277,15 @@ var ChangeTrackingService = class _ChangeTrackingService {
|
|
|
6083
6277
|
"__datafn_changes",
|
|
6084
6278
|
[
|
|
6085
6279
|
{ field: "namespace", op: "eq", value: this.namespace },
|
|
6086
|
-
{ field: "server_seq", op: "gt", value: params.sinceSeq }
|
|
6280
|
+
{ field: "server_seq", op: "gt", value: params.sinceSeq },
|
|
6281
|
+
{ field: "resource", op: "in", value: params.resources }
|
|
6087
6282
|
],
|
|
6088
|
-
{
|
|
6283
|
+
{
|
|
6284
|
+
orderBy: "server_seq",
|
|
6285
|
+
...typeof params.limit === "number" && params.limit > 0 ? { limit: params.limit } : {}
|
|
6286
|
+
}
|
|
6089
6287
|
);
|
|
6090
|
-
|
|
6091
|
-
const filtered = rows.filter((row) => resourceSet.has(String(row.resource ?? ""))).map((change) => ({
|
|
6288
|
+
return rows.map((change) => ({
|
|
6092
6289
|
namespace: this.namespace,
|
|
6093
6290
|
serverSeq: change.server_seq,
|
|
6094
6291
|
resource: change.resource,
|
|
@@ -6096,10 +6293,6 @@ var ChangeTrackingService = class _ChangeTrackingService {
|
|
|
6096
6293
|
op: change.op,
|
|
6097
6294
|
record: change.record ? JSON.parse(change.record) : null
|
|
6098
6295
|
}));
|
|
6099
|
-
if (typeof params.limit === "number" && params.limit > 0) {
|
|
6100
|
-
return filtered.slice(0, params.limit);
|
|
6101
|
-
}
|
|
6102
|
-
return filtered;
|
|
6103
6296
|
} catch (error) {
|
|
6104
6297
|
this.logger?.error("Failed to get resource-filtered changes", {
|
|
6105
6298
|
error: String(error),
|
|
@@ -6928,7 +7121,12 @@ async function executeShare(db, mutation, resolvedCapabilities, namespace, actor
|
|
|
6928
7121
|
if (!ownerCheck.ok) {
|
|
6929
7122
|
return ownerCheck;
|
|
6930
7123
|
}
|
|
6931
|
-
} else if (!
|
|
7124
|
+
} else if (!await hasResourceScopeOwnerAccess(
|
|
7125
|
+
db,
|
|
7126
|
+
mutation.resource,
|
|
7127
|
+
actorId,
|
|
7128
|
+
namespace
|
|
7129
|
+
)) {
|
|
6932
7130
|
return {
|
|
6933
7131
|
ok: false,
|
|
6934
7132
|
code: "FORBIDDEN",
|
|
@@ -7082,7 +7280,12 @@ async function executeUnshare(db, mutation, resolvedCapabilities, namespace, act
|
|
|
7082
7280
|
if (!ownerCheck.ok) {
|
|
7083
7281
|
return ownerCheck;
|
|
7084
7282
|
}
|
|
7085
|
-
} else if (!
|
|
7283
|
+
} else if (!await hasResourceScopeOwnerAccess(
|
|
7284
|
+
db,
|
|
7285
|
+
mutation.resource,
|
|
7286
|
+
actorId,
|
|
7287
|
+
namespace
|
|
7288
|
+
)) {
|
|
7086
7289
|
return {
|
|
7087
7290
|
ok: false,
|
|
7088
7291
|
code: "FORBIDDEN",
|
|
@@ -7179,6 +7382,9 @@ function includesResourceName(name, resource) {
|
|
|
7179
7382
|
function pickResourceName2(name) {
|
|
7180
7383
|
return Array.isArray(name) ? name[0] : name;
|
|
7181
7384
|
}
|
|
7385
|
+
function isShareableCapability4(entry) {
|
|
7386
|
+
return typeof entry === "object" && entry !== null && "shareable" in entry;
|
|
7387
|
+
}
|
|
7182
7388
|
function getResource2(schema, resourceName) {
|
|
7183
7389
|
return schema.resources.find((resource) => resource.name === resourceName);
|
|
7184
7390
|
}
|
|
@@ -7191,9 +7397,7 @@ function getInheritanceConfig(schema, resourceName) {
|
|
|
7191
7397
|
schema.capabilities,
|
|
7192
7398
|
resource.capabilities
|
|
7193
7399
|
);
|
|
7194
|
-
const shareable = resolvedCapabilities.find(
|
|
7195
|
-
(entry) => typeof entry === "object" && entry !== null && "shareable" in entry
|
|
7196
|
-
);
|
|
7400
|
+
const shareable = resolvedCapabilities.find(isShareableCapability4);
|
|
7197
7401
|
const relationInheritance = shareable?.shareable.relationInheritance;
|
|
7198
7402
|
if (!relationInheritance?.enabled) {
|
|
7199
7403
|
return null;
|
|
@@ -8849,9 +9053,10 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
|
|
|
8849
9053
|
resource: step.mutation?.resource ?? step.query?.resource ?? "?",
|
|
8850
9054
|
error: String(e?.message || e)
|
|
8851
9055
|
});
|
|
9056
|
+
const errorCode = typeof e?.code === "string" && e.code.length > 0 ? e.code : "INTERNAL";
|
|
8852
9057
|
results.push({
|
|
8853
9058
|
ok: false,
|
|
8854
|
-
error: { code:
|
|
9059
|
+
error: { code: errorCode, message: e?.message || String(e) }
|
|
8855
9060
|
});
|
|
8856
9061
|
if (isAtomic) return { ok: true, result: { ok: false, results } };
|
|
8857
9062
|
}
|
|
@@ -8938,17 +9143,28 @@ function createTransactHandler(validatedSchema, db, idempotencyStore, limits, ex
|
|
|
8938
9143
|
};
|
|
8939
9144
|
for (let i = 0; i < body.steps.length; i++) {
|
|
8940
9145
|
const step = body.steps[i];
|
|
8941
|
-
const isMutation = !!(step.mutation || typeof step.operation === "string");
|
|
8942
9146
|
let authzResult;
|
|
8943
|
-
if (
|
|
9147
|
+
if (step.mutation) {
|
|
9148
|
+
authzResult = validateMutationAuthz(
|
|
9149
|
+
step.mutation,
|
|
9150
|
+
validatedSchema,
|
|
9151
|
+
authzOpts
|
|
9152
|
+
);
|
|
9153
|
+
} else if (step.query) {
|
|
9154
|
+
authzResult = validateQueryAuthz(
|
|
9155
|
+
step.query,
|
|
9156
|
+
validatedSchema,
|
|
9157
|
+
authzOpts
|
|
9158
|
+
);
|
|
9159
|
+
} else if (typeof step.operation === "string") {
|
|
8944
9160
|
authzResult = validateMutationAuthz(
|
|
8945
|
-
step
|
|
9161
|
+
step,
|
|
8946
9162
|
validatedSchema,
|
|
8947
9163
|
authzOpts
|
|
8948
9164
|
);
|
|
8949
9165
|
} else {
|
|
8950
9166
|
authzResult = validateQueryAuthz(
|
|
8951
|
-
step
|
|
9167
|
+
step,
|
|
8952
9168
|
validatedSchema,
|
|
8953
9169
|
authzOpts
|
|
8954
9170
|
);
|
|
@@ -9162,7 +9378,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
|
|
|
9162
9378
|
try {
|
|
9163
9379
|
if (remaining <= 0) {
|
|
9164
9380
|
data[tableName] = [];
|
|
9165
|
-
next[tableName] = tableCounts[tableName] > 0 ?
|
|
9381
|
+
next[tableName] = tableCounts[tableName] > 0 ? "" : null;
|
|
9166
9382
|
} else {
|
|
9167
9383
|
const records = await db.findMany({
|
|
9168
9384
|
model: tableName,
|
|
@@ -9186,6 +9402,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
|
|
|
9186
9402
|
logger?.warn("Clone: auto-paginate fetch failed", { error: String(error), resource: tableName, operation: "clone-paginate" });
|
|
9187
9403
|
data[tableName] = [];
|
|
9188
9404
|
cursors[tableName] = "0";
|
|
9405
|
+
next[tableName] = null;
|
|
9189
9406
|
}
|
|
9190
9407
|
}
|
|
9191
9408
|
} else {
|
|
@@ -9962,6 +10179,9 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
|
|
|
9962
10179
|
}
|
|
9963
10180
|
continue;
|
|
9964
10181
|
}
|
|
10182
|
+
if (!isDataResourceKey(resource)) {
|
|
10183
|
+
continue;
|
|
10184
|
+
}
|
|
9965
10185
|
const isPrivate = isPrivateShareableResource(schema, resource);
|
|
9966
10186
|
if (isPrivate && !actorId) {
|
|
9967
10187
|
continue;
|
|
@@ -10299,15 +10519,34 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
|
|
|
10299
10519
|
case "replace": {
|
|
10300
10520
|
const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
|
|
10301
10521
|
const strippedRecord = stripReadonlyCapabilityFields(coercedData, resolvedCapabilities);
|
|
10302
|
-
const
|
|
10522
|
+
const createData = injectCapabilityFieldsOnInsert2(
|
|
10523
|
+
strippedRecord,
|
|
10524
|
+
resolvedCapabilities,
|
|
10525
|
+
actorId
|
|
10526
|
+
);
|
|
10527
|
+
const updateData = injectCapabilityFieldsOnUpdate2(
|
|
10303
10528
|
strippedRecord,
|
|
10304
10529
|
resolvedCapabilities,
|
|
10305
10530
|
actorId
|
|
10306
10531
|
);
|
|
10307
|
-
await targetDb.upsert({
|
|
10532
|
+
const persistedRecord = await targetDb.upsert({
|
|
10533
|
+
model: mut.resource,
|
|
10534
|
+
where: [{ field: "id", operator: "eq", value: mut.id }],
|
|
10535
|
+
create: { id: mut.id, ...createData },
|
|
10536
|
+
update: updateData,
|
|
10537
|
+
namespace,
|
|
10538
|
+
conflictTarget: "id"
|
|
10539
|
+
});
|
|
10308
10540
|
return {
|
|
10309
10541
|
ok: true,
|
|
10310
|
-
changes: [
|
|
10542
|
+
changes: [
|
|
10543
|
+
{
|
|
10544
|
+
resource: mut.resource,
|
|
10545
|
+
id: mut.id,
|
|
10546
|
+
op: "replace",
|
|
10547
|
+
record: { id: mut.id, ...persistedRecord }
|
|
10548
|
+
}
|
|
10549
|
+
]
|
|
10311
10550
|
};
|
|
10312
10551
|
}
|
|
10313
10552
|
case "delete":
|
|
@@ -10881,7 +11120,12 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
|
|
|
10881
11120
|
const toResource = toResources[0];
|
|
10882
11121
|
const joinStoreKey = core.getJoinStoreKey(fromResource, relation.relation, toResource);
|
|
10883
11122
|
const joinTableName = core.getJoinTableName(fromResource, relation.relation, relation.joinTable);
|
|
11123
|
+
const relationTouchesPrivateResource = isPrivateShareableResource(schema, fromResource) || isPrivateShareableResource(schema, toResource);
|
|
10884
11124
|
try {
|
|
11125
|
+
if (relationTouchesPrivateResource && !actorId) {
|
|
11126
|
+
joinCounts[joinStoreKey] = 0;
|
|
11127
|
+
continue;
|
|
11128
|
+
}
|
|
10885
11129
|
if (typeof db.count === "function") {
|
|
10886
11130
|
joinCounts[joinStoreKey] = await db.count({
|
|
10887
11131
|
model: joinTableName,
|
|
@@ -10982,7 +11226,7 @@ function createCloneHandler(validatedSchema, extractNamespace, extractActorId, d
|
|
|
10982
11226
|
code: "INTERNAL",
|
|
10983
11227
|
message: "Internal error",
|
|
10984
11228
|
details: { path: "$" }
|
|
10985
|
-
});
|
|
11229
|
+
}, 500);
|
|
10986
11230
|
} finally {
|
|
10987
11231
|
logRequest({
|
|
10988
11232
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -11061,7 +11305,7 @@ function createPullHandler(validatedSchema, extractNamespace, extractActorId, db
|
|
|
11061
11305
|
code: "INTERNAL",
|
|
11062
11306
|
message: "Internal error",
|
|
11063
11307
|
details: { path: "$" }
|
|
11064
|
-
});
|
|
11308
|
+
}, 500);
|
|
11065
11309
|
} finally {
|
|
11066
11310
|
logRequest({
|
|
11067
11311
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -11249,7 +11493,7 @@ function createPushHandler(validatedSchema, extractNamespace, extractActorId, db
|
|
|
11249
11493
|
code: "INTERNAL",
|
|
11250
11494
|
message: "Internal error",
|
|
11251
11495
|
details: { path: "$" }
|
|
11252
|
-
});
|
|
11496
|
+
}, 500);
|
|
11253
11497
|
} finally {
|
|
11254
11498
|
logRequest({
|
|
11255
11499
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -11332,7 +11576,7 @@ function createReconcileHandler(validatedSchema, extractNamespace, extractActorI
|
|
|
11332
11576
|
code: "INTERNAL",
|
|
11333
11577
|
message: "Internal error",
|
|
11334
11578
|
details: { path: "$" }
|
|
11335
|
-
});
|
|
11579
|
+
}, 500);
|
|
11336
11580
|
} finally {
|
|
11337
11581
|
logRequest({
|
|
11338
11582
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -11899,7 +12143,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
11899
12143
|
{
|
|
11900
12144
|
method: "GET",
|
|
11901
12145
|
path: "/datafn/resources/:resource",
|
|
11902
|
-
handler: async (req) => {
|
|
12146
|
+
handler: async (req, ctx) => {
|
|
11903
12147
|
const url = new URL(req.url);
|
|
11904
12148
|
const pathParts = url.pathname.split("/");
|
|
11905
12149
|
const rawResource = pathParts[3] ?? "";
|
|
@@ -11929,11 +12173,11 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
11929
12173
|
}
|
|
11930
12174
|
}
|
|
11931
12175
|
const dfql = {
|
|
12176
|
+
...queryBody,
|
|
11932
12177
|
resource,
|
|
11933
|
-
version: getResourceVersion(resource)
|
|
11934
|
-
...queryBody
|
|
12178
|
+
version: getResourceVersion(resource)
|
|
11935
12179
|
};
|
|
11936
|
-
const result = await executeQuery2(dfql);
|
|
12180
|
+
const result = await executeQuery2(dfql, ctx);
|
|
11937
12181
|
return jsonResponse({ ok: true, result });
|
|
11938
12182
|
} catch (err) {
|
|
11939
12183
|
if (err.code === "DFQL_UNKNOWN_RESOURCE") {
|
|
@@ -11996,7 +12240,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
11996
12240
|
id: body.id,
|
|
11997
12241
|
record: body.record
|
|
11998
12242
|
};
|
|
11999
|
-
const result = await executeMutation2(mutation);
|
|
12243
|
+
const result = await executeMutation2(mutation, ctx);
|
|
12000
12244
|
return jsonResponse({ ok: true, result });
|
|
12001
12245
|
} catch (err) {
|
|
12002
12246
|
if (err.code === "DFQL_UNKNOWN_RESOURCE") {
|
|
@@ -12061,7 +12305,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
12061
12305
|
id,
|
|
12062
12306
|
record: body.record
|
|
12063
12307
|
};
|
|
12064
|
-
const result = await executeMutation2(mutation);
|
|
12308
|
+
const result = await executeMutation2(mutation, ctx);
|
|
12065
12309
|
return jsonResponse({ ok: true, result });
|
|
12066
12310
|
} catch (err) {
|
|
12067
12311
|
if (err.code === "DFQL_UNKNOWN_RESOURCE") {
|
|
@@ -12076,7 +12320,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
12076
12320
|
{
|
|
12077
12321
|
method: "DELETE",
|
|
12078
12322
|
path: "/datafn/resources/:resource/:id",
|
|
12079
|
-
handler: async (req) => {
|
|
12323
|
+
handler: async (req, ctx) => {
|
|
12080
12324
|
const url = new URL(req.url);
|
|
12081
12325
|
const pathParts = url.pathname.split("/");
|
|
12082
12326
|
const rawResource = pathParts[3] ?? "";
|
|
@@ -12120,7 +12364,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
|
|
|
12120
12364
|
mutationId,
|
|
12121
12365
|
id
|
|
12122
12366
|
};
|
|
12123
|
-
const result = await executeMutation2(mutation);
|
|
12367
|
+
const result = await executeMutation2(mutation, ctx);
|
|
12124
12368
|
return jsonResponse({ ok: true, result });
|
|
12125
12369
|
} catch (err) {
|
|
12126
12370
|
if (err.code === "DFQL_UNKNOWN_RESOURCE") {
|
|
@@ -12233,6 +12477,19 @@ var WebSocketManager = class {
|
|
|
12233
12477
|
canonicalizeActorPrincipal(actorId) {
|
|
12234
12478
|
return actorId.includes(":") ? actorId : `user:${actorId}`;
|
|
12235
12479
|
}
|
|
12480
|
+
closeClientSafely(client, code, reason, operation) {
|
|
12481
|
+
if (typeof client.close !== "function") {
|
|
12482
|
+
return;
|
|
12483
|
+
}
|
|
12484
|
+
try {
|
|
12485
|
+
client.close(code, reason);
|
|
12486
|
+
} catch (error) {
|
|
12487
|
+
this.logger?.warn("WebSocket close error", {
|
|
12488
|
+
error: String(error),
|
|
12489
|
+
operation
|
|
12490
|
+
});
|
|
12491
|
+
}
|
|
12492
|
+
}
|
|
12236
12493
|
resolveClientPrincipals(authContext) {
|
|
12237
12494
|
const principals = /* @__PURE__ */ new Set();
|
|
12238
12495
|
if (Array.isArray(authContext.principalIds)) {
|
|
@@ -12313,13 +12570,13 @@ var WebSocketManager = class {
|
|
|
12313
12570
|
} catch (e) {
|
|
12314
12571
|
this.logger?.warn("Heartbeat ping failed", { error: String(e), operation: "ws-heartbeat" });
|
|
12315
12572
|
this.removeClient(client);
|
|
12316
|
-
|
|
12573
|
+
this.closeClientSafely(client, 1001, "Heartbeat ping failed", "ws-heartbeat-close");
|
|
12317
12574
|
continue;
|
|
12318
12575
|
}
|
|
12319
12576
|
setTimeout(() => {
|
|
12320
12577
|
if (this.pendingPong.has(client)) {
|
|
12321
12578
|
this.removeClient(client);
|
|
12322
|
-
|
|
12579
|
+
this.closeClientSafely(client, 1001, "Heartbeat timeout", "ws-heartbeat-timeout-close");
|
|
12323
12580
|
}
|
|
12324
12581
|
}, timeoutMs);
|
|
12325
12582
|
}
|
|
@@ -12338,11 +12595,16 @@ var WebSocketManager = class {
|
|
|
12338
12595
|
addClient(client, authContext) {
|
|
12339
12596
|
const { namespace } = authContext;
|
|
12340
12597
|
if (this.totalCount >= this.maxConnections) {
|
|
12341
|
-
|
|
12598
|
+
this.closeClientSafely(client, 4503, "Connection limit reached", "ws-limit-close");
|
|
12342
12599
|
return false;
|
|
12343
12600
|
}
|
|
12344
12601
|
if (this.getNamespaceCount(namespace) >= this.maxConnectionsPerNamespace) {
|
|
12345
|
-
|
|
12602
|
+
this.closeClientSafely(
|
|
12603
|
+
client,
|
|
12604
|
+
4503,
|
|
12605
|
+
"Namespace connection limit reached",
|
|
12606
|
+
"ws-namespace-limit-close"
|
|
12607
|
+
);
|
|
12346
12608
|
return false;
|
|
12347
12609
|
}
|
|
12348
12610
|
let nsSet = this.namespaceClients.get(namespace);
|
|
@@ -12459,6 +12721,7 @@ var WebSocketManager = class {
|
|
|
12459
12721
|
} catch (e) {
|
|
12460
12722
|
this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
|
|
12461
12723
|
this.removeClient(client);
|
|
12724
|
+
this.closeClientSafely(client, 1001, "Broadcast send failed", "ws-broadcast-close");
|
|
12462
12725
|
}
|
|
12463
12726
|
}
|
|
12464
12727
|
return {
|
|
@@ -12474,11 +12737,7 @@ var WebSocketManager = class {
|
|
|
12474
12737
|
close() {
|
|
12475
12738
|
this.destroy();
|
|
12476
12739
|
for (const [client] of this.clientNamespace) {
|
|
12477
|
-
|
|
12478
|
-
client.close?.(1001, "Going Away");
|
|
12479
|
-
} catch (e) {
|
|
12480
|
-
this.logger?.warn("WebSocket close error", { error: String(e), operation: "ws-close" });
|
|
12481
|
-
}
|
|
12740
|
+
this.closeClientSafely(client, 1001, "Going Away", "ws-close");
|
|
12482
12741
|
}
|
|
12483
12742
|
this.namespaceClients.clear();
|
|
12484
12743
|
this.namespacePrincipalClients.clear();
|
|
@@ -12616,9 +12875,9 @@ function createDefaultLogger(debug) {
|
|
|
12616
12875
|
};
|
|
12617
12876
|
}
|
|
12618
12877
|
return {
|
|
12619
|
-
info: (msg, ctx) => console.log(JSON.stringify({ level: "info", msg,
|
|
12620
|
-
warn: (msg, ctx) => console.warn(JSON.stringify({ level: "warn", msg,
|
|
12621
|
-
error: (msg, ctx) => console.error(JSON.stringify({ level: "error", msg,
|
|
12878
|
+
info: (msg, ctx) => console.log(JSON.stringify({ ...ctx ?? {}, level: "info", msg, ts: Date.now() })),
|
|
12879
|
+
warn: (msg, ctx) => console.warn(JSON.stringify({ ...ctx ?? {}, level: "warn", msg, ts: Date.now() })),
|
|
12880
|
+
error: (msg, ctx) => console.error(JSON.stringify({ ...ctx ?? {}, level: "error", msg, ts: Date.now() })),
|
|
12622
12881
|
debug: () => {
|
|
12623
12882
|
}
|
|
12624
12883
|
};
|
|
@@ -12915,9 +13174,75 @@ async function createDatafnServer(config) {
|
|
|
12915
13174
|
let inFlightCount = 0;
|
|
12916
13175
|
let shuttingDown = false;
|
|
12917
13176
|
let shutdownResolve = null;
|
|
13177
|
+
let shutdownTimer = null;
|
|
13178
|
+
const isPlainObjectContext = (value) => {
|
|
13179
|
+
if (!value || typeof value !== "object") {
|
|
13180
|
+
return false;
|
|
13181
|
+
}
|
|
13182
|
+
const prototype = Object.getPrototypeOf(value);
|
|
13183
|
+
return prototype === Object.prototype || prototype === null;
|
|
13184
|
+
};
|
|
13185
|
+
const createEnrichedContext = (ctx) => {
|
|
13186
|
+
if (isPlainObjectContext(ctx)) {
|
|
13187
|
+
return { ...ctx };
|
|
13188
|
+
}
|
|
13189
|
+
if (ctx && typeof ctx === "object") {
|
|
13190
|
+
let parsedBody;
|
|
13191
|
+
let hasParsedBody = false;
|
|
13192
|
+
const target = ctx;
|
|
13193
|
+
return new Proxy(target, {
|
|
13194
|
+
get(currentTarget, prop) {
|
|
13195
|
+
if (prop === "parsedBody") {
|
|
13196
|
+
if (hasParsedBody) {
|
|
13197
|
+
return parsedBody;
|
|
13198
|
+
}
|
|
13199
|
+
return Reflect.get(currentTarget, prop, currentTarget);
|
|
13200
|
+
}
|
|
13201
|
+
const value = Reflect.get(currentTarget, prop, currentTarget);
|
|
13202
|
+
return typeof value === "function" ? value.bind(currentTarget) : value;
|
|
13203
|
+
},
|
|
13204
|
+
set(currentTarget, prop, value) {
|
|
13205
|
+
if (prop === "parsedBody") {
|
|
13206
|
+
hasParsedBody = true;
|
|
13207
|
+
parsedBody = value;
|
|
13208
|
+
return true;
|
|
13209
|
+
}
|
|
13210
|
+
return Reflect.set(currentTarget, prop, value, currentTarget);
|
|
13211
|
+
},
|
|
13212
|
+
has(currentTarget, prop) {
|
|
13213
|
+
if (prop === "parsedBody") {
|
|
13214
|
+
return hasParsedBody || Reflect.has(currentTarget, prop);
|
|
13215
|
+
}
|
|
13216
|
+
return Reflect.has(currentTarget, prop);
|
|
13217
|
+
},
|
|
13218
|
+
ownKeys(currentTarget) {
|
|
13219
|
+
const keys = Reflect.ownKeys(currentTarget);
|
|
13220
|
+
if (hasParsedBody && !keys.includes("parsedBody")) {
|
|
13221
|
+
return [...keys, "parsedBody"];
|
|
13222
|
+
}
|
|
13223
|
+
return keys;
|
|
13224
|
+
},
|
|
13225
|
+
getOwnPropertyDescriptor(currentTarget, prop) {
|
|
13226
|
+
if (prop === "parsedBody") {
|
|
13227
|
+
if (!hasParsedBody) {
|
|
13228
|
+
return Reflect.getOwnPropertyDescriptor(currentTarget, prop);
|
|
13229
|
+
}
|
|
13230
|
+
return {
|
|
13231
|
+
configurable: true,
|
|
13232
|
+
enumerable: true,
|
|
13233
|
+
writable: true,
|
|
13234
|
+
value: parsedBody
|
|
13235
|
+
};
|
|
13236
|
+
}
|
|
13237
|
+
return Reflect.getOwnPropertyDescriptor(currentTarget, prop);
|
|
13238
|
+
}
|
|
13239
|
+
});
|
|
13240
|
+
}
|
|
13241
|
+
return { parsedBody: void 0 };
|
|
13242
|
+
};
|
|
12918
13243
|
const withAuth = (action, handler) => {
|
|
12919
13244
|
return async (req, ctx) => {
|
|
12920
|
-
const enrichedCtx = ctx;
|
|
13245
|
+
const enrichedCtx = createEnrichedContext(ctx);
|
|
12921
13246
|
if (shuttingDown) {
|
|
12922
13247
|
return new Response(
|
|
12923
13248
|
JSON.stringify({ ok: false, error: { code: "SERVICE_UNAVAILABLE", message: "Server is shutting down" } }),
|
|
@@ -12927,7 +13252,7 @@ async function createDatafnServer(config) {
|
|
|
12927
13252
|
inFlightCount++;
|
|
12928
13253
|
try {
|
|
12929
13254
|
if (rateLimitMiddleware) {
|
|
12930
|
-
const rateLimitResponse = await rateLimitMiddleware(action,
|
|
13255
|
+
const rateLimitResponse = await rateLimitMiddleware(action, enrichedCtx);
|
|
12931
13256
|
if (rateLimitResponse) return rateLimitResponse;
|
|
12932
13257
|
}
|
|
12933
13258
|
if (limits.maxPayloadBytes) {
|
|
@@ -12972,6 +13297,10 @@ async function createDatafnServer(config) {
|
|
|
12972
13297
|
if (shuttingDown && inFlightCount === 0 && shutdownResolve) {
|
|
12973
13298
|
const resolve = shutdownResolve;
|
|
12974
13299
|
shutdownResolve = null;
|
|
13300
|
+
if (shutdownTimer) {
|
|
13301
|
+
clearTimeout(shutdownTimer);
|
|
13302
|
+
shutdownTimer = null;
|
|
13303
|
+
}
|
|
12975
13304
|
resolve();
|
|
12976
13305
|
}
|
|
12977
13306
|
}
|
|
@@ -13030,14 +13359,20 @@ async function createDatafnServer(config) {
|
|
|
13030
13359
|
}
|
|
13031
13360
|
];
|
|
13032
13361
|
if (config.rest) {
|
|
13033
|
-
const internalMutate = async (m) => {
|
|
13034
|
-
const res = await mutationHandler(void 0, {
|
|
13362
|
+
const internalMutate = async (m, ctx) => {
|
|
13363
|
+
const res = await mutationHandler(void 0, {
|
|
13364
|
+
...ctx ?? {},
|
|
13365
|
+
parsedBody: m
|
|
13366
|
+
});
|
|
13035
13367
|
const env = await res.json();
|
|
13036
13368
|
if (!env.ok) throw env.error;
|
|
13037
13369
|
return env.result;
|
|
13038
13370
|
};
|
|
13039
|
-
const internalQuery = async (q) => {
|
|
13040
|
-
const res = await queryHandler(void 0, {
|
|
13371
|
+
const internalQuery = async (q, ctx) => {
|
|
13372
|
+
const res = await queryHandler(void 0, {
|
|
13373
|
+
...ctx ?? {},
|
|
13374
|
+
parsedBody: q
|
|
13375
|
+
});
|
|
13041
13376
|
const env = await res.json();
|
|
13042
13377
|
if (!env.ok) throw env.error;
|
|
13043
13378
|
return env.result;
|
|
@@ -13051,29 +13386,36 @@ async function createDatafnServer(config) {
|
|
|
13051
13386
|
for (const route of restRoutes) {
|
|
13052
13387
|
const action = route.method === "GET" ? "query" : "mutation";
|
|
13053
13388
|
routes.push({
|
|
13054
|
-
|
|
13389
|
+
method: route.method,
|
|
13390
|
+
path: route.path,
|
|
13391
|
+
meta: route.meta,
|
|
13055
13392
|
handler: withAuth(action, route.handler)
|
|
13056
13393
|
});
|
|
13057
13394
|
}
|
|
13058
13395
|
}
|
|
13059
13396
|
const router = http.createRouter({
|
|
13060
13397
|
routes,
|
|
13061
|
-
basePath: "/"
|
|
13398
|
+
basePath: "/",
|
|
13399
|
+
context: config.context
|
|
13062
13400
|
});
|
|
13063
13401
|
const serverClose = async () => {
|
|
13064
13402
|
if (shuttingDown) return;
|
|
13065
13403
|
shuttingDown = true;
|
|
13404
|
+
process.off("SIGTERM", sigHandler);
|
|
13405
|
+
process.off("SIGINT", sigHandler);
|
|
13066
13406
|
wsManager.close();
|
|
13067
13407
|
if (inFlightCount > 0) {
|
|
13068
13408
|
const timeoutMs = config.shutdownTimeoutMs ?? 1e4;
|
|
13069
13409
|
await new Promise((resolve) => {
|
|
13070
13410
|
shutdownResolve = resolve;
|
|
13071
|
-
setTimeout(() => {
|
|
13411
|
+
shutdownTimer = setTimeout(() => {
|
|
13072
13412
|
if (shutdownResolve === resolve) {
|
|
13073
13413
|
shutdownResolve = null;
|
|
13414
|
+
shutdownTimer = null;
|
|
13074
13415
|
resolve();
|
|
13075
13416
|
}
|
|
13076
13417
|
}, timeoutMs);
|
|
13418
|
+
shutdownTimer.unref?.();
|
|
13077
13419
|
});
|
|
13078
13420
|
}
|
|
13079
13421
|
if (config.searchProvider?.dispose) {
|
|
@@ -13093,8 +13435,8 @@ async function createDatafnServer(config) {
|
|
|
13093
13435
|
}
|
|
13094
13436
|
};
|
|
13095
13437
|
const sigHandler = () => serverClose().catch((e) => logger.error("Graceful shutdown error", { error: String(e), operation: "shutdown" }));
|
|
13096
|
-
process.
|
|
13097
|
-
process.
|
|
13438
|
+
process.on("SIGTERM", sigHandler);
|
|
13439
|
+
process.on("SIGINT", sigHandler);
|
|
13098
13440
|
const serverSearch = async (params, _ctx) => {
|
|
13099
13441
|
if (!db$1) {
|
|
13100
13442
|
throw new Error("Database is not configured");
|