@_linked/server 3.6.1 → 3.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/lib/esm/backend.d.ts +9 -0
- package/lib/esm/backend.js +28 -1
- package/lib/esm/backend.js.map +1 -1
- package/lib/esm/data/server.ttl +75 -0
- package/lib/esm/ontologies/server.d.ts +4 -22
- package/lib/esm/ontologies/server.js +5 -11
- package/lib/esm/ontologies/server.js.map +1 -1
- package/lib/esm/ontologies/server.register.js +3 -3
- package/lib/esm/ontologies/server.register.js.map +1 -1
- package/lib/esm/package.d.ts +1 -1
- package/lib/esm/shapes/LinkedServer.d.ts +23 -3
- package/lib/esm/shapes/LinkedServer.js +60 -13
- package/lib/esm/shapes/LinkedServer.js.map +1 -1
- package/lib/esm/shapes/quadstores/RemoteDataset.d.ts +41 -1
- package/lib/esm/shapes/quadstores/RemoteDataset.js +152 -4
- package/lib/esm/shapes/quadstores/RemoteDataset.js.map +1 -1
- package/lib/esm/utils/adminChannel.d.ts +35 -0
- package/lib/esm/utils/adminChannel.js +47 -3
- package/lib/esm/utils/adminChannel.js.map +1 -1
- package/lib/esm/utils/linkedDependencies.d.ts +7 -0
- package/lib/esm/utils/linkedDependencies.js +29 -0
- package/lib/esm/utils/linkedDependencies.js.map +1 -1
- package/lib/esm/utils/ontologySync.d.ts +144 -0
- package/lib/esm/utils/ontologySync.js +145 -0
- package/lib/esm/utils/ontologySync.js.map +1 -0
- package/lib/esm/utils/queryPlane.d.ts +21 -0
- package/lib/esm/utils/queryPlane.js +54 -0
- package/lib/esm/utils/queryPlane.js.map +1 -1
- package/package.json +4 -4
- package/readme.md +13 -3
- package/lib/esm/data/server.json +0 -47
|
@@ -5,7 +5,8 @@ import type { AskQuery } from '@_linked/core/queries/AskQuery';
|
|
|
5
5
|
import type { UpdateQuery } from '@_linked/core/queries/UpdateQuery';
|
|
6
6
|
import type { CreateQuery } from '@_linked/core/queries/CreateQuery';
|
|
7
7
|
import type { DeleteQuery, DeleteResponse } from '@_linked/core/queries/DeleteQuery';
|
|
8
|
-
import type { SelectResult, UpdateResult, CreateResult } from '@_linked/core/queries/IntermediateRepresentation';
|
|
8
|
+
import type { SelectResult, UpdateResult, CreateResult, GraphQuery, GraphResult } from '@_linked/core/queries/IntermediateRepresentation';
|
|
9
|
+
import { type GraphRegistryRow } from '@_linked/core/utils/graphRegistryCache';
|
|
9
10
|
/**
|
|
10
11
|
* Constructor argument for `new RemoteDataset(config)`: the `config` object of a
|
|
11
12
|
* `linked.{frontend,backend}.datasets.json` entry, passed verbatim.
|
|
@@ -104,6 +105,8 @@ export declare class RemoteDataset implements IDataset {
|
|
|
104
105
|
readonly forwardEndUser: boolean;
|
|
105
106
|
private initialized?;
|
|
106
107
|
private pingInfo?;
|
|
108
|
+
private readonly instanceRegistryKey;
|
|
109
|
+
private warnedRegistryRead;
|
|
107
110
|
constructor(config?: RemoteDatasetConfig | string);
|
|
108
111
|
/**
|
|
109
112
|
* The body of the last successful `ping` (see {@link init}); undefined before one, and
|
|
@@ -120,6 +123,43 @@ export declare class RemoteDataset implements IDataset {
|
|
|
120
123
|
updateQuery(query: UpdateQuery): Promise<UpdateResult>;
|
|
121
124
|
createQuery(query: CreateQuery): Promise<CreateResult>;
|
|
122
125
|
deleteQuery(query: DeleteQuery): Promise<DeleteResponse>;
|
|
126
|
+
/**
|
|
127
|
+
* A whole-graph operation (`graph_create`, `graph_replace`, `graph_patch`, `graph_drop`): the
|
|
128
|
+
* query is plain data, so it is sent as is, the same way and with the same headers as every
|
|
129
|
+
* other query. On success this store's registry cache notes it in the same step (a create adds
|
|
130
|
+
* the graph, a drop removes it), so its next `.from(graphs.allOntologies)` read sees the change.
|
|
131
|
+
* A refusal rejects with a `GraphQueryError` (see `graphQueryFailure`): a server or gateway
|
|
132
|
+
* without the method answers `unsupported-query-kind`.
|
|
133
|
+
*/
|
|
134
|
+
graphQuery(query: GraphQuery): Promise<GraphResult>;
|
|
135
|
+
/**
|
|
136
|
+
* The key this store's graph-registry cache is kept under: the data server's url and the
|
|
137
|
+
* dataset it named in its `ping` answer (CN's gateway answers `{dataset}`), so stores of the
|
|
138
|
+
* same dataset share one entry; else one key per instance. (`POST /admin/graph-registry-changed`
|
|
139
|
+
* drops every entry of the process, whatever its key.)
|
|
140
|
+
*/
|
|
141
|
+
protected graphRegistryKey(): string;
|
|
142
|
+
/**
|
|
143
|
+
* Drop the cached graph registry of `dataset` (default: this store's, see `graphRegistryKey`):
|
|
144
|
+
* the next read that expands `graphs.allOntologies` re-reads it.
|
|
145
|
+
*/
|
|
146
|
+
invalidateGraphRegistry(dataset?: string): void;
|
|
147
|
+
/**
|
|
148
|
+
* Read the data server's graph registry: the records of the ontology and shapes graphs, by
|
|
149
|
+
* class, through the same query wire (the record shapes read the registry graph themselves).
|
|
150
|
+
*/
|
|
151
|
+
protected loadGraphRegistry(): Promise<GraphRegistryRow[]>;
|
|
152
|
+
/**
|
|
153
|
+
* In the url form, expand `graphs.allOntologies` and `graphs.allShapes` in a read's `graphs`
|
|
154
|
+
* from this store's registry cache (per dataset, updated by its own graph queries, dropped by a
|
|
155
|
+
* pushed invalidation, re-read after 30 seconds), so the data server reads exactly the graphs
|
|
156
|
+
* this process knows of. Other names (graph IRIs, `graphs.default`, `graphs.union`) go as they
|
|
157
|
+
* are, for the data server's store to resolve. A name that expands to no graph is sent as is,
|
|
158
|
+
* so the data server answers from its own registry; so is every name when the registry cannot
|
|
159
|
+
* be read (the data server refused or failed the record selects), with one warning per store.
|
|
160
|
+
* The no-url form sends `graphs` unchanged: the backend's store expands them.
|
|
161
|
+
*/
|
|
162
|
+
private withReadGraphs;
|
|
123
163
|
private call;
|
|
124
164
|
/**
|
|
125
165
|
* Opts in to `rejectOnError`, so a failed call (HTTP error status, or no
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { packageName } from '../../package.js';
|
|
2
2
|
import { brandLinkedError } from '@_linked/core/utils/linkedError';
|
|
3
3
|
import { Server } from '@_linked/server-utils/utils/Server';
|
|
4
|
+
import { GraphQueryError, isGraphQueryError, unsupportedGraphQuery, } from '@_linked/core/queries/graphQuery';
|
|
5
|
+
import { invalidateGraphRegistry, noteGraphQuery, readGraphRegistry, } from '@_linked/core/utils/graphRegistryCache';
|
|
6
|
+
import { graphs } from '@_linked/core/ontologies/graphs';
|
|
7
|
+
import { OntologyGraph, ShapesGraph } from '@_linked/core/shapes/NamedGraph';
|
|
4
8
|
/**
|
|
5
9
|
* The header the url form sends with a query made while a signed-in user's HTTP request is
|
|
6
10
|
* being answered: that user's WebID. The data server decides what to do with it; the bearer
|
|
@@ -58,6 +62,44 @@ export class RemoteDatasetUnauthorizedError extends RemoteDatasetError {
|
|
|
58
62
|
brandLinkedError(RemoteDatasetError, '@_linked/server', 'RemoteDatasetError');
|
|
59
63
|
brandLinkedError(RemoteDatasetUnreachableError, '@_linked/server', 'RemoteDatasetUnreachableError');
|
|
60
64
|
brandLinkedError(RemoteDatasetUnauthorizedError, '@_linked/server', 'RemoteDatasetUnauthorizedError');
|
|
65
|
+
/** The refusal codes a data server sends back for a graph query (`{error, code}`). */
|
|
66
|
+
const GRAPH_REFUSAL_CODES = new Set([
|
|
67
|
+
'unsupported-query-kind',
|
|
68
|
+
'graph-not-registered',
|
|
69
|
+
'graph-name-read-only',
|
|
70
|
+
'graph-exists',
|
|
71
|
+
]);
|
|
72
|
+
/**
|
|
73
|
+
* A failed graph query as the caller expects it: a {@link GraphQueryError} when the data server
|
|
74
|
+
* refused it with one of the graph refusal codes, or when it has no graph method at all (404 or
|
|
75
|
+
* 501 without any code: an older server or gateway), which reads as `unsupported-query-kind`
|
|
76
|
+
* so the ontology sync falls back to the default graph. Anything else is passed on as is.
|
|
77
|
+
*/
|
|
78
|
+
function graphQueryFailure(err, query) {
|
|
79
|
+
if (isGraphQueryError(err))
|
|
80
|
+
return err;
|
|
81
|
+
const code = err === null || err === void 0 ? void 0 : err.code;
|
|
82
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
83
|
+
let refusal;
|
|
84
|
+
if (typeof code === 'string' && GRAPH_REFUSAL_CODES.has(code)) {
|
|
85
|
+
refusal = new GraphQueryError(code, message, query.graph);
|
|
86
|
+
}
|
|
87
|
+
else if (code === undefined) {
|
|
88
|
+
const status = err === null || err === void 0 ? void 0 : err.status;
|
|
89
|
+
if (status === 404 || status === 501)
|
|
90
|
+
refusal = unsupportedGraphQuery(query, message);
|
|
91
|
+
}
|
|
92
|
+
if (!refusal)
|
|
93
|
+
return err;
|
|
94
|
+
refusal.cause = err;
|
|
95
|
+
return refusal;
|
|
96
|
+
}
|
|
97
|
+
/** The portable names a remote store expands from its own registry cache, with their record class. */
|
|
98
|
+
const REGISTRY_EXPANDED = new Map([
|
|
99
|
+
[graphs.allOntologies, OntologyGraph.targetClass.id],
|
|
100
|
+
[graphs.allShapes, ShapesGraph.targetClass.id],
|
|
101
|
+
]);
|
|
102
|
+
let nextRegistryKey = 0;
|
|
61
103
|
/** On `ping`, these statuses mean nothing at that url serves the query wire. */
|
|
62
104
|
const PING_UNREACHABLE_STATUSES = new Set([404, 501, 502, 503, 504]);
|
|
63
105
|
/**
|
|
@@ -85,6 +127,8 @@ export class RemoteDataset {
|
|
|
85
127
|
constructor(config) {
|
|
86
128
|
/** Whether the url form sends {@link END_USER_HEADER}; see `RemoteDatasetConfig.forwardEndUser`. */
|
|
87
129
|
this.forwardEndUser = true;
|
|
130
|
+
this.instanceRegistryKey = `remote-dataset:${nextRegistryKey++}`;
|
|
131
|
+
this.warnedRegistryRead = false;
|
|
88
132
|
if (!config)
|
|
89
133
|
return;
|
|
90
134
|
if (typeof config === 'string') {
|
|
@@ -141,11 +185,11 @@ export class RemoteDataset {
|
|
|
141
185
|
// Queries serialize to DSL-JSON for the wire: the live (closed) query can't cross a call
|
|
142
186
|
// as-is, so we ship `toJSON()` and the server's generic provider rehydrates it with
|
|
143
187
|
// `fromJSON()`.
|
|
144
|
-
selectQuery(query) {
|
|
145
|
-
return this.call('selectQuery', query.toJSON());
|
|
188
|
+
async selectQuery(query) {
|
|
189
|
+
return this.call('selectQuery', await this.withReadGraphs(query.toJSON()));
|
|
146
190
|
}
|
|
147
|
-
askQuery(query) {
|
|
148
|
-
return this.call('askQuery', query.toJSON());
|
|
191
|
+
async askQuery(query) {
|
|
192
|
+
return this.call('askQuery', await this.withReadGraphs(query.toJSON()));
|
|
149
193
|
}
|
|
150
194
|
updateQuery(query) {
|
|
151
195
|
return this.call('updateQuery', query.toJSON());
|
|
@@ -156,6 +200,110 @@ export class RemoteDataset {
|
|
|
156
200
|
deleteQuery(query) {
|
|
157
201
|
return this.call('deleteQuery', query.toJSON());
|
|
158
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* A whole-graph operation (`graph_create`, `graph_replace`, `graph_patch`, `graph_drop`): the
|
|
205
|
+
* query is plain data, so it is sent as is, the same way and with the same headers as every
|
|
206
|
+
* other query. On success this store's registry cache notes it in the same step (a create adds
|
|
207
|
+
* the graph, a drop removes it), so its next `.from(graphs.allOntologies)` read sees the change.
|
|
208
|
+
* A refusal rejects with a `GraphQueryError` (see `graphQueryFailure`): a server or gateway
|
|
209
|
+
* without the method answers `unsupported-query-kind`.
|
|
210
|
+
*/
|
|
211
|
+
async graphQuery(query) {
|
|
212
|
+
let result;
|
|
213
|
+
try {
|
|
214
|
+
result = await this.call('graphQuery', query);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
throw graphQueryFailure(err, query);
|
|
218
|
+
}
|
|
219
|
+
if (this.url !== undefined)
|
|
220
|
+
noteGraphQuery(this.graphRegistryKey(), query);
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The key this store's graph-registry cache is kept under: the data server's url and the
|
|
225
|
+
* dataset it named in its `ping` answer (CN's gateway answers `{dataset}`), so stores of the
|
|
226
|
+
* same dataset share one entry; else one key per instance. (`POST /admin/graph-registry-changed`
|
|
227
|
+
* drops every entry of the process, whatever its key.)
|
|
228
|
+
*/
|
|
229
|
+
graphRegistryKey() {
|
|
230
|
+
var _a;
|
|
231
|
+
const dataset = (_a = this.pingInfo) === null || _a === void 0 ? void 0 : _a.dataset;
|
|
232
|
+
return typeof dataset === 'string' && dataset && this.url
|
|
233
|
+
? `${this.url}#${dataset}`
|
|
234
|
+
: this.instanceRegistryKey;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Drop the cached graph registry of `dataset` (default: this store's, see `graphRegistryKey`):
|
|
238
|
+
* the next read that expands `graphs.allOntologies` re-reads it.
|
|
239
|
+
*/
|
|
240
|
+
invalidateGraphRegistry(dataset) {
|
|
241
|
+
invalidateGraphRegistry(dataset !== null && dataset !== void 0 ? dataset : this.graphRegistryKey());
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Read the data server's graph registry: the records of the ontology and shapes graphs, by
|
|
245
|
+
* class, through the same query wire (the record shapes read the registry graph themselves).
|
|
246
|
+
*/
|
|
247
|
+
async loadGraphRegistry() {
|
|
248
|
+
const rows = [];
|
|
249
|
+
const kinds = [OntologyGraph, ShapesGraph];
|
|
250
|
+
const results = await Promise.all(kinds.map((kind) => kind.select().exec(this)));
|
|
251
|
+
results.forEach((records, i) => {
|
|
252
|
+
var _a;
|
|
253
|
+
const recordClass = kinds[i].targetClass.id;
|
|
254
|
+
for (const record of (_a = records) !== null && _a !== void 0 ? _a : []) {
|
|
255
|
+
if (typeof (record === null || record === void 0 ? void 0 : record.id) === 'string' && record.id)
|
|
256
|
+
rows.push({ graph: record.id, recordClass });
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
return rows;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* In the url form, expand `graphs.allOntologies` and `graphs.allShapes` in a read's `graphs`
|
|
263
|
+
* from this store's registry cache (per dataset, updated by its own graph queries, dropped by a
|
|
264
|
+
* pushed invalidation, re-read after 30 seconds), so the data server reads exactly the graphs
|
|
265
|
+
* this process knows of. Other names (graph IRIs, `graphs.default`, `graphs.union`) go as they
|
|
266
|
+
* are, for the data server's store to resolve. A name that expands to no graph is sent as is,
|
|
267
|
+
* so the data server answers from its own registry; so is every name when the registry cannot
|
|
268
|
+
* be read (the data server refused or failed the record selects), with one warning per store.
|
|
269
|
+
* The no-url form sends `graphs` unchanged: the backend's store expands them.
|
|
270
|
+
*/
|
|
271
|
+
async withReadGraphs(json) {
|
|
272
|
+
if (this.url === undefined || !json || typeof json !== 'object')
|
|
273
|
+
return json;
|
|
274
|
+
const names = json.graphs;
|
|
275
|
+
if (!Array.isArray(names) || !names.some((name) => REGISTRY_EXPANDED.has(name)))
|
|
276
|
+
return json;
|
|
277
|
+
let registry;
|
|
278
|
+
try {
|
|
279
|
+
registry = await readGraphRegistry(this.graphRegistryKey(), () => this.loadGraphRegistry());
|
|
280
|
+
}
|
|
281
|
+
catch (err) {
|
|
282
|
+
if (!this.warnedRegistryRead) {
|
|
283
|
+
this.warnedRegistryRead = true;
|
|
284
|
+
console.warn(`RemoteDataset: could not read the graph registry at ${this.url}; reads send graph names unexpanded:`, err instanceof Error ? err.message : err);
|
|
285
|
+
}
|
|
286
|
+
return json;
|
|
287
|
+
}
|
|
288
|
+
const out = [];
|
|
289
|
+
const add = (iri) => {
|
|
290
|
+
if (!out.includes(iri))
|
|
291
|
+
out.push(iri);
|
|
292
|
+
};
|
|
293
|
+
for (const name of names) {
|
|
294
|
+
const recordClass = REGISTRY_EXPANDED.get(name);
|
|
295
|
+
if (!recordClass) {
|
|
296
|
+
add(name);
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const listed = [...registry].filter(([, classes]) => classes.has(recordClass)).map(([graph]) => graph);
|
|
300
|
+
if (listed.length)
|
|
301
|
+
listed.sort().forEach(add);
|
|
302
|
+
else
|
|
303
|
+
add(name);
|
|
304
|
+
}
|
|
305
|
+
return { ...json, graphs: out };
|
|
306
|
+
}
|
|
159
307
|
call(method, json) {
|
|
160
308
|
if (this.url === undefined)
|
|
161
309
|
return this.callBackend(method, json);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RemoteDataset.js","sourceRoot":"","sources":["../../../../src/shapes/quadstores/RemoteDataset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AA2C5D;;;;GAIG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,mBAAmB,CAAC;AAEnD,2FAA2F;AAC3F,sFAAsF;AACtF,+FAA+F;AAC/F,iFAAiF;AACjF,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;AAEzE,SAAS,kBAAkB;IACzB,MAAM,KAAK,GAAI,UAAuE,CAAC,gBAAgB,CAAC,CAAC;IACzG,OAAO,OAAO,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,QAAQ,CAAA,KAAK,UAAU,CAAC,CAAC,CAAE,KAAK,CAAC,QAAQ,EAA8B,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3G,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB;;IACjC,MAAM,GAAG,GAAG,kBAAkB,EAAE,CAAC;IACjC,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,SAAS,CAAC;IAClD,MAAM,KAAK,GAAG,MAAA,MAAA,MAAA,MAAA,GAAG,CAAC,OAAO,0CAAE,UAAU,0CAAE,WAAW,0CAAE,SAAS,0CAAE,EAAE,CAAC;IAClE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAChE,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAQ3C,YAAY,OAAe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E,IAAI,CAAA,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;QACxE,MAAM,MAAM,GACV,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAA,KAAK,QAAQ;YAC/B,CAAC,CAAC,MAAM,CAAC,KAAK;YACd,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI;gBAChC,CAAC,CAAC,IAAI;gBACN,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC5B,MAAM,OAAO,GAAG,qCAAqC,IAAI,aAAa,MAAM,SAAS,QAAQ,CAAC,MAAM,GAClG,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC,EACxB,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QAEjC,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvD,MAAM,IAAI,8BAA8B,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACjF,CAAC;QACD,IAAI,MAAM,KAAK,MAAM,IAAI,CAAC,yBAAyB,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YACrF,MAAM,IAAI,6BAA6B,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { packageName } from '../../package.js';\nimport { brandLinkedError } from '@_linked/core/utils/linkedError';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport type { CallContext } from '@_linked/server-utils/utils/CallContext';\nimport type { IDataset } from '@_linked/core/interfaces/IDataset';\nimport type { SelectQuery } from '@_linked/core/queries/SelectQuery';\nimport type { CountQuery } from '@_linked/core/queries/CountQuery';\nimport type { AskQuery } from '@_linked/core/queries/AskQuery';\nimport type { UpdateQuery } from '@_linked/core/queries/UpdateQuery';\nimport type { CreateQuery } from '@_linked/core/queries/CreateQuery';\nimport type {\n DeleteQuery,\n DeleteResponse,\n} from '@_linked/core/queries/DeleteQuery';\nimport type {\n SelectResult,\n UpdateResult,\n CreateResult,\n} from '@_linked/core/queries/IntermediateRepresentation';\n\n/**\n * Constructor argument for `new RemoteDataset(config)`: the `config` object of a\n * `linked.{frontend,backend}.datasets.json` entry, passed verbatim.\n */\nexport interface RemoteDatasetConfig {\n /**\n * Base URL of the data server, e.g. `http://localhost:4040/gateway`; routes are appended\n * to it. Without it, queries go to this process's own backend through `Server.call`.\n * Present but empty is an error, never the no-url form.\n */\n url?: string;\n /** Sent as `Authorization: Bearer <token>` when set and `url` is set. */\n token?: string;\n /** Stable name; becomes the suffix of the store URI: ${DATA_ROOT}/backend-api-store/<name>. */\n name?: string;\n /** Or pass a fully-qualified URI directly. */\n id?: string;\n /**\n * In the url form, send the signed-in user's WebID of the current call as\n * `x-linked-end-user` (see {@link END_USER_HEADER}). Default true; `false` (or the\n * string `'false'`, as an interpolated config gives it) turns it off.\n */\n forwardEndUser?: boolean | string;\n}\n\n/**\n * The header the url form sends with a query made while a signed-in user's HTTP request is\n * being answered: that user's WebID. The data server decides what to do with it; the bearer\n * token still decides which data the store reaches.\n */\nexport const END_USER_HEADER = 'x-linked-end-user';\n\n// The store `@_linked/server-utils/utils/CallContext` keeps the call context in, shared on\n// `globalThis` under this key. Read here instead of importing that module: it imports\n// `node:async_hooks`, and this store also runs in the browser (the no-url form). In a browser,\n// and in a server before any call ran, the key is unset and there is no context.\nconst CALL_CONTEXT_KEY = Symbol.for('@_linked/server-utils:callContext');\n\nfunction currentCallContext(): CallContext | undefined {\n const store = (globalThis as Record<symbol, { getStore?: () => unknown } | undefined>)[CALL_CONTEXT_KEY];\n return typeof store?.getStore === 'function' ? (store.getStore() as CallContext | undefined) : undefined;\n}\n\n/**\n * The WebID of the signed-in user behind the current call: the http context's\n * `request.linkedAuth.userAccount.accountOf.id`. Undefined in a system context\n * (`runAsSystem`), outside any call, and for a request without a session.\n */\nexport function currentEndUserWebId(): string | undefined {\n const ctx = currentCallContext();\n if (!ctx || ctx.kind !== 'http') return undefined;\n const webId = ctx.request?.linkedAuth?.userAccount?.accountOf?.id;\n return typeof webId === 'string' && webId ? webId : undefined;\n}\n\n/**\n * A failed call to the data server at `url`. `status` is the HTTP status (0 when no HTTP\n * answer came back); `code` is the error body's `code` when the server sent one.\n */\nexport class RemoteDatasetError extends Error {\n /** The data server base url ('' when the configured url is empty). */\n readonly url: string;\n /** The HTTP status; 0 = no HTTP answer. */\n readonly status: number;\n /** The error body's `code`, when the server sent one. */\n readonly code?: string;\n\n constructor(message: string, url: string, status: number, code?: string) {\n super(message);\n this.name = new.target.name;\n this.url = url;\n this.status = status;\n if (code !== undefined) this.code = code;\n }\n}\n\n/**\n * Nothing at `url` speaks the query wire: no HTTP answer, an empty url, or (on `ping`) an\n * answer that is not the server's. A boot that gets this should stop.\n */\nexport class RemoteDatasetUnreachableError extends RemoteDatasetError {}\n\n/** The data server answered 401 or 403: it refused this dataset's token. */\nexport class RemoteDatasetUnauthorizedError extends RemoteDatasetError {}\n\n// Branded, so `isLinkedError(err, RemoteDatasetUnreachableError)` from `@_linked/core` matches an\n// error thrown by another copy of this module, where `instanceof` does not. See\n// https://github.com/linked-fw/cli/blob/main/docs/architecture/shared-state-and-error-brands.md.\nbrandLinkedError(RemoteDatasetError, '@_linked/server', 'RemoteDatasetError');\nbrandLinkedError(RemoteDatasetUnreachableError, '@_linked/server', 'RemoteDatasetUnreachableError');\nbrandLinkedError(RemoteDatasetUnauthorizedError, '@_linked/server', 'RemoteDatasetUnauthorizedError');\n\n/**\n * What the data server's `ping` answered, as is. The generic `@_linked/server` ping answers\n * `{ok: true}`; a gateway may add fields that say which dataset it serves, such as\n * `{ok, projectId, branchName, dataset, forked}`. A body that is not a JSON object reads as `{}`.\n */\nexport type RemoteDatasetPingInfo = Readonly<Record<string, unknown>>;\n\ntype Method =\n | 'ping'\n | 'selectQuery'\n | 'askQuery'\n | 'updateQuery'\n | 'createQuery'\n | 'deleteQuery';\n\n/** On `ping`, these statuses mean nothing at that url serves the query wire. */\nconst PING_UNREACHABLE_STATUSES = new Set([404, 501, 502, 503, 504]);\n\n/**\n * An {@link IDataset} whose queries are answered by a linked server.\n *\n * - **Without `url`** the server is this app's own backend: every query goes through\n * `Server.call`'s package form (`/call/@_linked/server/<method>` with a body of `{args}`),\n * and on a backend `Server`'s local shortcut answers it in process. This is the store a\n * browser uses to talk to its backend.\n * - **With `url`** the server is a remote data server: every query posts\n * `{\"args\": [query.toJSON()]}` to `{url}/call/@_linked/server/<method>` with the bearer\n * `token`, through `fetch`, never through `Server` (whose local shortcut would answer the\n * app's own provider) and never retried (a retried write could apply twice). `init()` asks\n * the server's `ping` and throws {@link RemoteDatasetUnreachableError} or\n * {@link RemoteDatasetUnauthorizedError} when it cannot be used.\n *\n * A store is not a Shape: it addresses the backend by package name, so nothing about the\n * store instance crosses the wire. Query routing is decided by the query's shape.\n *\n * `LinkedStorage.setDefaultDataset` calls `init()` without awaiting it, so a boot that must\n * fail loudly awaits `init()` itself first; a successful `init()` is memoized, and resolves\n * the ping body (also readable as `info`), so a boot can log which dataset the server serves.\n */\nexport class RemoteDataset implements IDataset {\n /**\n * Kept so the config form is still accepted and a store can be named; it is not an\n * addressing mechanism, nothing transmits or resolves it.\n */\n readonly id?: string;\n /** The data server base url, trailing slashes trimmed; undefined in the no-url form. */\n readonly url?: string;\n private readonly token?: string;\n /** Whether the url form sends {@link END_USER_HEADER}; see `RemoteDatasetConfig.forwardEndUser`. */\n readonly forwardEndUser: boolean = true;\n private initialized?: Promise<RemoteDatasetPingInfo | undefined>;\n private pingInfo?: RemoteDatasetPingInfo;\n\n constructor(config?: RemoteDatasetConfig | string) {\n if (!config) return;\n if (typeof config === 'string') {\n this.id = `${process.env.DATA_ROOT}/backend-api-store/${config}`;\n return;\n }\n if (typeof config.url === 'string') {\n this.url = config.url.trim().replace(/\\/+$/, '');\n const token = typeof config.token === 'string' ? config.token.trim() : '';\n if (token) this.token = token;\n }\n if (config.forwardEndUser === false || config.forwardEndUser === 'false') {\n this.forwardEndUser = false;\n }\n if (config.id) {\n this.id = config.id;\n return;\n }\n if (config.name) {\n this.id = `${process.env.DATA_ROOT}/backend-api-store/${config.name}`;\n }\n }\n\n /**\n * The body of the last successful `ping` (see {@link init}); undefined before one, and\n * always in the no-url form.\n */\n get info(): RemoteDatasetPingInfo | undefined {\n return this.pingInfo;\n }\n\n /**\n * In the url form, asks the server's `ping` and resolves its body (also kept as\n * {@link info}); resolves undefined in the no-url form.\n */\n init(): Promise<RemoteDatasetPingInfo | undefined> {\n // No initialization needed when queries are routed to the app's own backend.\n if (this.url === undefined) return Promise.resolve(undefined);\n if (!this.initialized) {\n this.initialized = this.post('ping', []).then(\n (body) => {\n const info: RemoteDatasetPingInfo = Object.freeze(\n body && typeof body === 'object' && !Array.isArray(body)\n ? { ...(body as Record<string, unknown>) }\n : {},\n );\n this.pingInfo = info;\n return info;\n },\n (err) => {\n // Not memoized: the next init() asks again.\n this.initialized = undefined;\n throw err;\n },\n );\n }\n return this.initialized;\n }\n\n // Queries serialize to DSL-JSON for the wire: the live (closed) query can't cross a call\n // as-is, so we ship `toJSON()` and the server's generic provider rehydrates it with\n // `fromJSON()`.\n selectQuery(query: SelectQuery | CountQuery): Promise<SelectResult | number> {\n return this.call('selectQuery', query.toJSON());\n }\n\n askQuery(query: AskQuery): Promise<boolean> {\n return this.call('askQuery', query.toJSON());\n }\n\n updateQuery(query: UpdateQuery): Promise<UpdateResult> {\n return this.call('updateQuery', query.toJSON());\n }\n\n createQuery(query: CreateQuery): Promise<CreateResult> {\n return this.call('createQuery', query.toJSON());\n }\n\n deleteQuery(query: DeleteQuery): Promise<DeleteResponse> {\n return this.call('deleteQuery', query.toJSON());\n }\n\n private call<T>(method: Method, json: unknown): Promise<T> {\n if (this.url === undefined) return this.callBackend(method, json);\n return this.post(method, [json]) as Promise<T>;\n }\n\n /**\n * Opts in to `rejectOnError`, so a failed call (HTTP error status, or no\n * provider on the backend) rejects with a `ServerCallError` carrying the\n * status and the server's message instead of reading as an empty result.\n * Whatever a successful call returns, `undefined` included, resolves as is.\n */\n private callBackend<T>(method: string, json: unknown): Promise<T> {\n // The PACKAGE form, not the shape form. It posts to\n // `/call/<packageName>/<method>` with a body of `{args}` only — no `shapeURI`,\n // no `instanceNode` — and the backend answers from this package's generic\n // provider without resolving or instantiating any Shape.\n return Server.call(packageName, { method, rejectOnError: true }, json);\n }\n\n /**\n * The url form: one POST to `{url}/call/@_linked/server/<method>`. Resolves the parsed\n * body (`null` is a valid result: a method that returned `undefined`). Messages name the\n * url and the method, never the token.\n */\n private async post(method: Method, args: unknown[]): Promise<unknown> {\n const base = this.url ?? '';\n if (!base) {\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: no data server url is set (the configured url is empty); cannot ${method}`,\n '',\n 0,\n );\n }\n const target = `${base}/call/${packageName}/${method}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n if (this.token) headers.Authorization = `Bearer ${this.token}`;\n if (this.forwardEndUser) {\n const endUser = currentEndUserWebId();\n if (endUser) headers[END_USER_HEADER] = endUser;\n }\n\n let response: Response;\n try {\n response = await globalThis.fetch(target, {\n method: 'POST',\n headers,\n body: JSON.stringify({ args }),\n });\n } catch (err) {\n const cause = err instanceof Error ? err.message : String(err);\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: cannot reach the data server at ${base} (${method}): ${cause}`,\n base,\n 0,\n );\n }\n\n const text = await response.text();\n let body: unknown = undefined;\n let isJson = false;\n if (text) {\n try {\n body = JSON.parse(text);\n isJson = true;\n } catch {\n body = text;\n }\n }\n\n if (response.ok) {\n if (isJson) return body;\n if (method === 'ping') {\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: the data server at ${base} answered ping with a body that is not JSON`,\n base,\n response.status,\n );\n }\n if (!text) return undefined;\n throw new RemoteDatasetError(\n `RemoteDataset: the data server at ${base} answered ${method} with a body that is not JSON`,\n base,\n response.status,\n );\n }\n\n const record = body && typeof body === 'object' ? (body as Record<string, unknown>) : undefined;\n const code = typeof record?.code === 'string' ? record.code : undefined;\n const detail =\n typeof record?.error === 'string'\n ? record.error\n : typeof body === 'string' && body\n ? body\n : response.statusText;\n const message = `RemoteDataset: the data server at ${base} answered ${method} with ${response.status}${\n code ? ` (${code})` : ''\n }${detail ? `: ${detail}` : ''}`;\n\n if (response.status === 401 || response.status === 403) {\n throw new RemoteDatasetUnauthorizedError(message, base, response.status, code);\n }\n if (method === 'ping' && (PING_UNREACHABLE_STATUSES.has(response.status) || !isJson)) {\n throw new RemoteDatasetUnreachableError(message, base, response.status, code);\n }\n throw new RemoteDatasetError(message, base, response.status, code);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RemoteDataset.js","sourceRoot":"","sources":["../../../../src/shapes/quadstores/RemoteDataset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AAmB5D,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,qBAAqB,GAEtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,iBAAiB,GAElB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM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C,CAAC,MAAM,CAAC,KAAK;YACd,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI;gBAChC,CAAC,CAAC,IAAI;gBACN,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC5B,MAAM,OAAO,GAAG,qCAAqC,IAAI,aAAa,MAAM,SAAS,QAAQ,CAAC,MAAM,GAClG,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC,EACxB,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QAEjC,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvD,MAAM,IAAI,8BAA8B,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACjF,CAAC;QACD,IAAI,MAAM,KAAK,MAAM,IAAI,CAAC,yBAAyB,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YACrF,MAAM,IAAI,6BAA6B,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAChF,CAAC;QACD,MAAM,IAAI,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { packageName } from '../../package.js';\nimport { brandLinkedError } from '@_linked/core/utils/linkedError';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport type { CallContext } from '@_linked/server-utils/utils/CallContext';\nimport type { IDataset } from '@_linked/core/interfaces/IDataset';\nimport type { SelectQuery } from '@_linked/core/queries/SelectQuery';\nimport type { CountQuery } from '@_linked/core/queries/CountQuery';\nimport type { AskQuery } from '@_linked/core/queries/AskQuery';\nimport type { UpdateQuery } from '@_linked/core/queries/UpdateQuery';\nimport type { CreateQuery } from '@_linked/core/queries/CreateQuery';\nimport type {\n DeleteQuery,\n DeleteResponse,\n} from '@_linked/core/queries/DeleteQuery';\nimport type {\n SelectResult,\n UpdateResult,\n CreateResult,\n GraphQuery,\n GraphResult,\n} from '@_linked/core/queries/IntermediateRepresentation';\nimport {\n GraphQueryError,\n isGraphQueryError,\n unsupportedGraphQuery,\n type GraphQueryErrorCode,\n} from '@_linked/core/queries/graphQuery';\nimport {\n invalidateGraphRegistry,\n noteGraphQuery,\n readGraphRegistry,\n type GraphRegistryRow,\n} from '@_linked/core/utils/graphRegistryCache';\nimport { graphs } from '@_linked/core/ontologies/graphs';\nimport { OntologyGraph, ShapesGraph } from '@_linked/core/shapes/NamedGraph';\n\n/**\n * Constructor argument for `new RemoteDataset(config)`: the `config` object of a\n * `linked.{frontend,backend}.datasets.json` entry, passed verbatim.\n */\nexport interface RemoteDatasetConfig {\n /**\n * Base URL of the data server, e.g. `http://localhost:4040/gateway`; routes are appended\n * to it. Without it, queries go to this process's own backend through `Server.call`.\n * Present but empty is an error, never the no-url form.\n */\n url?: string;\n /** Sent as `Authorization: Bearer <token>` when set and `url` is set. */\n token?: string;\n /** Stable name; becomes the suffix of the store URI: ${DATA_ROOT}/backend-api-store/<name>. */\n name?: string;\n /** Or pass a fully-qualified URI directly. */\n id?: string;\n /**\n * In the url form, send the signed-in user's WebID of the current call as\n * `x-linked-end-user` (see {@link END_USER_HEADER}). Default true; `false` (or the\n * string `'false'`, as an interpolated config gives it) turns it off.\n */\n forwardEndUser?: boolean | string;\n}\n\n/**\n * The header the url form sends with a query made while a signed-in user's HTTP request is\n * being answered: that user's WebID. The data server decides what to do with it; the bearer\n * token still decides which data the store reaches.\n */\nexport const END_USER_HEADER = 'x-linked-end-user';\n\n// The store `@_linked/server-utils/utils/CallContext` keeps the call context in, shared on\n// `globalThis` under this key. Read here instead of importing that module: it imports\n// `node:async_hooks`, and this store also runs in the browser (the no-url form). In a browser,\n// and in a server before any call ran, the key is unset and there is no context.\nconst CALL_CONTEXT_KEY = Symbol.for('@_linked/server-utils:callContext');\n\nfunction currentCallContext(): CallContext | undefined {\n const store = (globalThis as Record<symbol, { getStore?: () => unknown } | undefined>)[CALL_CONTEXT_KEY];\n return typeof store?.getStore === 'function' ? (store.getStore() as CallContext | undefined) : undefined;\n}\n\n/**\n * The WebID of the signed-in user behind the current call: the http context's\n * `request.linkedAuth.userAccount.accountOf.id`. Undefined in a system context\n * (`runAsSystem`), outside any call, and for a request without a session.\n */\nexport function currentEndUserWebId(): string | undefined {\n const ctx = currentCallContext();\n if (!ctx || ctx.kind !== 'http') return undefined;\n const webId = ctx.request?.linkedAuth?.userAccount?.accountOf?.id;\n return typeof webId === 'string' && webId ? webId : undefined;\n}\n\n/**\n * A failed call to the data server at `url`. `status` is the HTTP status (0 when no HTTP\n * answer came back); `code` is the error body's `code` when the server sent one.\n */\nexport class RemoteDatasetError extends Error {\n /** The data server base url ('' when the configured url is empty). */\n readonly url: string;\n /** The HTTP status; 0 = no HTTP answer. */\n readonly status: number;\n /** The error body's `code`, when the server sent one. */\n readonly code?: string;\n\n constructor(message: string, url: string, status: number, code?: string) {\n super(message);\n this.name = new.target.name;\n this.url = url;\n this.status = status;\n if (code !== undefined) this.code = code;\n }\n}\n\n/**\n * Nothing at `url` speaks the query wire: no HTTP answer, an empty url, or (on `ping`) an\n * answer that is not the server's. A boot that gets this should stop.\n */\nexport class RemoteDatasetUnreachableError extends RemoteDatasetError {}\n\n/** The data server answered 401 or 403: it refused this dataset's token. */\nexport class RemoteDatasetUnauthorizedError extends RemoteDatasetError {}\n\n// Branded, so `isLinkedError(err, RemoteDatasetUnreachableError)` from `@_linked/core` matches an\n// error thrown by another copy of this module, where `instanceof` does not. See\n// https://github.com/linked-fw/cli/blob/main/docs/architecture/shared-state-and-error-brands.md.\nbrandLinkedError(RemoteDatasetError, '@_linked/server', 'RemoteDatasetError');\nbrandLinkedError(RemoteDatasetUnreachableError, '@_linked/server', 'RemoteDatasetUnreachableError');\nbrandLinkedError(RemoteDatasetUnauthorizedError, '@_linked/server', 'RemoteDatasetUnauthorizedError');\n\n/**\n * What the data server's `ping` answered, as is. The generic `@_linked/server` ping answers\n * `{ok: true}`; a gateway may add fields that say which dataset it serves, such as\n * `{ok, projectId, branchName, dataset, forked}`. A body that is not a JSON object reads as `{}`.\n */\nexport type RemoteDatasetPingInfo = Readonly<Record<string, unknown>>;\n\ntype Method =\n | 'ping'\n | 'selectQuery'\n | 'askQuery'\n | 'updateQuery'\n | 'createQuery'\n | 'deleteQuery'\n | 'graphQuery';\n\n/** The refusal codes a data server sends back for a graph query (`{error, code}`). */\nconst GRAPH_REFUSAL_CODES: ReadonlySet<string> = new Set<GraphQueryErrorCode>([\n 'unsupported-query-kind',\n 'graph-not-registered',\n 'graph-name-read-only',\n 'graph-exists',\n]);\n\n/**\n * A failed graph query as the caller expects it: a {@link GraphQueryError} when the data server\n * refused it with one of the graph refusal codes, or when it has no graph method at all (404 or\n * 501 without any code: an older server or gateway), which reads as `unsupported-query-kind`\n * so the ontology sync falls back to the default graph. Anything else is passed on as is.\n */\nfunction graphQueryFailure(err: unknown, query: GraphQuery): unknown {\n if (isGraphQueryError(err)) return err;\n const code = (err as { code?: unknown } | null)?.code;\n const message = err instanceof Error ? err.message : String(err);\n let refusal: GraphQueryError | undefined;\n if (typeof code === 'string' && GRAPH_REFUSAL_CODES.has(code)) {\n refusal = new GraphQueryError(code as GraphQueryErrorCode, message, query.graph);\n } else if (code === undefined) {\n const status = (err as { status?: unknown } | null)?.status;\n if (status === 404 || status === 501) refusal = unsupportedGraphQuery(query, message);\n }\n if (!refusal) return err;\n (refusal as { cause?: unknown }).cause = err;\n return refusal;\n}\n\n/** The portable names a remote store expands from its own registry cache, with their record class. */\nconst REGISTRY_EXPANDED: ReadonlyMap<string, string> = new Map([\n [graphs.allOntologies, OntologyGraph.targetClass.id],\n [graphs.allShapes, ShapesGraph.targetClass.id],\n]);\n\nlet nextRegistryKey = 0;\n\n/** On `ping`, these statuses mean nothing at that url serves the query wire. */\nconst PING_UNREACHABLE_STATUSES = new Set([404, 501, 502, 503, 504]);\n\n/**\n * An {@link IDataset} whose queries are answered by a linked server.\n *\n * - **Without `url`** the server is this app's own backend: every query goes through\n * `Server.call`'s package form (`/call/@_linked/server/<method>` with a body of `{args}`),\n * and on a backend `Server`'s local shortcut answers it in process. This is the store a\n * browser uses to talk to its backend.\n * - **With `url`** the server is a remote data server: every query posts\n * `{\"args\": [query.toJSON()]}` to `{url}/call/@_linked/server/<method>` with the bearer\n * `token`, through `fetch`, never through `Server` (whose local shortcut would answer the\n * app's own provider) and never retried (a retried write could apply twice). `init()` asks\n * the server's `ping` and throws {@link RemoteDatasetUnreachableError} or\n * {@link RemoteDatasetUnauthorizedError} when it cannot be used.\n *\n * A store is not a Shape: it addresses the backend by package name, so nothing about the\n * store instance crosses the wire. Query routing is decided by the query's shape.\n *\n * `LinkedStorage.setDefaultDataset` calls `init()` without awaiting it, so a boot that must\n * fail loudly awaits `init()` itself first; a successful `init()` is memoized, and resolves\n * the ping body (also readable as `info`), so a boot can log which dataset the server serves.\n */\nexport class RemoteDataset implements IDataset {\n /**\n * Kept so the config form is still accepted and a store can be named; it is not an\n * addressing mechanism, nothing transmits or resolves it.\n */\n readonly id?: string;\n /** The data server base url, trailing slashes trimmed; undefined in the no-url form. */\n readonly url?: string;\n private readonly token?: string;\n /** Whether the url form sends {@link END_USER_HEADER}; see `RemoteDatasetConfig.forwardEndUser`. */\n readonly forwardEndUser: boolean = true;\n private initialized?: Promise<RemoteDatasetPingInfo | undefined>;\n private pingInfo?: RemoteDatasetPingInfo;\n private readonly instanceRegistryKey = `remote-dataset:${nextRegistryKey++}`;\n private warnedRegistryRead = false;\n\n constructor(config?: RemoteDatasetConfig | string) {\n if (!config) return;\n if (typeof config === 'string') {\n this.id = `${process.env.DATA_ROOT}/backend-api-store/${config}`;\n return;\n }\n if (typeof config.url === 'string') {\n this.url = config.url.trim().replace(/\\/+$/, '');\n const token = typeof config.token === 'string' ? config.token.trim() : '';\n if (token) this.token = token;\n }\n if (config.forwardEndUser === false || config.forwardEndUser === 'false') {\n this.forwardEndUser = false;\n }\n if (config.id) {\n this.id = config.id;\n return;\n }\n if (config.name) {\n this.id = `${process.env.DATA_ROOT}/backend-api-store/${config.name}`;\n }\n }\n\n /**\n * The body of the last successful `ping` (see {@link init}); undefined before one, and\n * always in the no-url form.\n */\n get info(): RemoteDatasetPingInfo | undefined {\n return this.pingInfo;\n }\n\n /**\n * In the url form, asks the server's `ping` and resolves its body (also kept as\n * {@link info}); resolves undefined in the no-url form.\n */\n init(): Promise<RemoteDatasetPingInfo | undefined> {\n // No initialization needed when queries are routed to the app's own backend.\n if (this.url === undefined) return Promise.resolve(undefined);\n if (!this.initialized) {\n this.initialized = this.post('ping', []).then(\n (body) => {\n const info: RemoteDatasetPingInfo = Object.freeze(\n body && typeof body === 'object' && !Array.isArray(body)\n ? { ...(body as Record<string, unknown>) }\n : {},\n );\n this.pingInfo = info;\n return info;\n },\n (err) => {\n // Not memoized: the next init() asks again.\n this.initialized = undefined;\n throw err;\n },\n );\n }\n return this.initialized;\n }\n\n // Queries serialize to DSL-JSON for the wire: the live (closed) query can't cross a call\n // as-is, so we ship `toJSON()` and the server's generic provider rehydrates it with\n // `fromJSON()`.\n async selectQuery(query: SelectQuery | CountQuery): Promise<SelectResult | number> {\n return this.call('selectQuery', await this.withReadGraphs(query.toJSON()));\n }\n\n async askQuery(query: AskQuery): Promise<boolean> {\n return this.call('askQuery', await this.withReadGraphs(query.toJSON()));\n }\n\n updateQuery(query: UpdateQuery): Promise<UpdateResult> {\n return this.call('updateQuery', query.toJSON());\n }\n\n createQuery(query: CreateQuery): Promise<CreateResult> {\n return this.call('createQuery', query.toJSON());\n }\n\n deleteQuery(query: DeleteQuery): Promise<DeleteResponse> {\n return this.call('deleteQuery', query.toJSON());\n }\n\n /**\n * A whole-graph operation (`graph_create`, `graph_replace`, `graph_patch`, `graph_drop`): the\n * query is plain data, so it is sent as is, the same way and with the same headers as every\n * other query. On success this store's registry cache notes it in the same step (a create adds\n * the graph, a drop removes it), so its next `.from(graphs.allOntologies)` read sees the change.\n * A refusal rejects with a `GraphQueryError` (see `graphQueryFailure`): a server or gateway\n * without the method answers `unsupported-query-kind`.\n */\n async graphQuery(query: GraphQuery): Promise<GraphResult> {\n let result: GraphResult;\n try {\n result = await this.call<GraphResult>('graphQuery', query);\n } catch (err) {\n throw graphQueryFailure(err, query);\n }\n if (this.url !== undefined) noteGraphQuery(this.graphRegistryKey(), query);\n return result;\n }\n\n /**\n * The key this store's graph-registry cache is kept under: the data server's url and the\n * dataset it named in its `ping` answer (CN's gateway answers `{dataset}`), so stores of the\n * same dataset share one entry; else one key per instance. (`POST /admin/graph-registry-changed`\n * drops every entry of the process, whatever its key.)\n */\n protected graphRegistryKey(): string {\n const dataset = this.pingInfo?.dataset;\n return typeof dataset === 'string' && dataset && this.url\n ? `${this.url}#${dataset}`\n : this.instanceRegistryKey;\n }\n\n /**\n * Drop the cached graph registry of `dataset` (default: this store's, see `graphRegistryKey`):\n * the next read that expands `graphs.allOntologies` re-reads it.\n */\n invalidateGraphRegistry(dataset?: string): void {\n invalidateGraphRegistry(dataset ?? this.graphRegistryKey());\n }\n\n /**\n * Read the data server's graph registry: the records of the ontology and shapes graphs, by\n * class, through the same query wire (the record shapes read the registry graph themselves).\n */\n protected async loadGraphRegistry(): Promise<GraphRegistryRow[]> {\n const rows: GraphRegistryRow[] = [];\n const kinds = [OntologyGraph, ShapesGraph] as const;\n const results = await Promise.all(kinds.map((kind) => kind.select().exec(this)));\n results.forEach((records, i) => {\n const recordClass = kinds[i].targetClass.id;\n for (const record of (records as Array<{ id?: unknown }> | null) ?? []) {\n if (typeof record?.id === 'string' && record.id) rows.push({ graph: record.id, recordClass });\n }\n });\n return rows;\n }\n\n /**\n * In the url form, expand `graphs.allOntologies` and `graphs.allShapes` in a read's `graphs`\n * from this store's registry cache (per dataset, updated by its own graph queries, dropped by a\n * pushed invalidation, re-read after 30 seconds), so the data server reads exactly the graphs\n * this process knows of. Other names (graph IRIs, `graphs.default`, `graphs.union`) go as they\n * are, for the data server's store to resolve. A name that expands to no graph is sent as is,\n * so the data server answers from its own registry; so is every name when the registry cannot\n * be read (the data server refused or failed the record selects), with one warning per store.\n * The no-url form sends `graphs` unchanged: the backend's store expands them.\n */\n private async withReadGraphs(json: unknown): Promise<unknown> {\n if (this.url === undefined || !json || typeof json !== 'object') return json;\n const names = (json as { graphs?: unknown }).graphs;\n if (!Array.isArray(names) || !names.some((name) => REGISTRY_EXPANDED.has(name))) return json;\n let registry: Awaited<ReturnType<typeof readGraphRegistry>>;\n try {\n registry = await readGraphRegistry(this.graphRegistryKey(), () => this.loadGraphRegistry());\n } catch (err) {\n if (!this.warnedRegistryRead) {\n this.warnedRegistryRead = true;\n console.warn(\n `RemoteDataset: could not read the graph registry at ${this.url}; reads send graph names unexpanded:`,\n err instanceof Error ? err.message : err,\n );\n }\n return json;\n }\n const out: string[] = [];\n const add = (iri: string) => {\n if (!out.includes(iri)) out.push(iri);\n };\n for (const name of names as string[]) {\n const recordClass = REGISTRY_EXPANDED.get(name);\n if (!recordClass) {\n add(name);\n continue;\n }\n const listed = [...registry].filter(([, classes]) => classes.has(recordClass)).map(([graph]) => graph);\n if (listed.length) listed.sort().forEach(add);\n else add(name);\n }\n return { ...(json as Record<string, unknown>), graphs: out };\n }\n\n private call<T>(method: Method, json: unknown): Promise<T> {\n if (this.url === undefined) return this.callBackend(method, json);\n return this.post(method, [json]) as Promise<T>;\n }\n\n /**\n * Opts in to `rejectOnError`, so a failed call (HTTP error status, or no\n * provider on the backend) rejects with a `ServerCallError` carrying the\n * status and the server's message instead of reading as an empty result.\n * Whatever a successful call returns, `undefined` included, resolves as is.\n */\n private callBackend<T>(method: string, json: unknown): Promise<T> {\n // The PACKAGE form, not the shape form. It posts to\n // `/call/<packageName>/<method>` with a body of `{args}` only — no `shapeURI`,\n // no `instanceNode` — and the backend answers from this package's generic\n // provider without resolving or instantiating any Shape.\n return Server.call(packageName, { method, rejectOnError: true }, json);\n }\n\n /**\n * The url form: one POST to `{url}/call/@_linked/server/<method>`. Resolves the parsed\n * body (`null` is a valid result: a method that returned `undefined`). Messages name the\n * url and the method, never the token.\n */\n private async post(method: Method, args: unknown[]): Promise<unknown> {\n const base = this.url ?? '';\n if (!base) {\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: no data server url is set (the configured url is empty); cannot ${method}`,\n '',\n 0,\n );\n }\n const target = `${base}/call/${packageName}/${method}`;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n if (this.token) headers.Authorization = `Bearer ${this.token}`;\n if (this.forwardEndUser) {\n const endUser = currentEndUserWebId();\n if (endUser) headers[END_USER_HEADER] = endUser;\n }\n\n let response: Response;\n try {\n response = await globalThis.fetch(target, {\n method: 'POST',\n headers,\n body: JSON.stringify({ args }),\n });\n } catch (err) {\n const cause = err instanceof Error ? err.message : String(err);\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: cannot reach the data server at ${base} (${method}): ${cause}`,\n base,\n 0,\n );\n }\n\n const text = await response.text();\n let body: unknown = undefined;\n let isJson = false;\n if (text) {\n try {\n body = JSON.parse(text);\n isJson = true;\n } catch {\n body = text;\n }\n }\n\n if (response.ok) {\n if (isJson) return body;\n if (method === 'ping') {\n throw new RemoteDatasetUnreachableError(\n `RemoteDataset: the data server at ${base} answered ping with a body that is not JSON`,\n base,\n response.status,\n );\n }\n if (!text) return undefined;\n throw new RemoteDatasetError(\n `RemoteDataset: the data server at ${base} answered ${method} with a body that is not JSON`,\n base,\n response.status,\n );\n }\n\n const record = body && typeof body === 'object' ? (body as Record<string, unknown>) : undefined;\n const code = typeof record?.code === 'string' ? record.code : undefined;\n const detail =\n typeof record?.error === 'string'\n ? record.error\n : typeof body === 'string' && body\n ? body\n : response.statusText;\n const message = `RemoteDataset: the data server at ${base} answered ${method} with ${response.status}${\n code ? ` (${code})` : ''\n }${detail ? `: ${detail}` : ''}`;\n\n if (response.status === 401 || response.status === 403) {\n throw new RemoteDatasetUnauthorizedError(message, base, response.status, code);\n }\n if (method === 'ping' && (PING_UNREACHABLE_STATUSES.has(response.status) || !isJson)) {\n throw new RemoteDatasetUnreachableError(message, base, response.status, code);\n }\n throw new RemoteDatasetError(message, base, response.status, code);\n }\n}\n"]}
|
|
@@ -14,6 +14,22 @@ export interface ShapeSyncResult {
|
|
|
14
14
|
reloaded?: string[];
|
|
15
15
|
/** The node shape IRIs registered in the process after the reload. Set by `POST /admin/sync-shapes`. */
|
|
16
16
|
shapes?: string[];
|
|
17
|
+
/**
|
|
18
|
+
* The ontology sync: packages whose ontology graph (or, on a store without graph queries,
|
|
19
|
+
* class hierarchy) was written, packages left as they were (unchanged, or their data could not
|
|
20
|
+
* be read), and the graphs written and dropped. Set by `POST /admin/sync-shapes`.
|
|
21
|
+
*/
|
|
22
|
+
ontologies?: {
|
|
23
|
+
written: string[];
|
|
24
|
+
skipped: string[];
|
|
25
|
+
graphs?: string[];
|
|
26
|
+
droppedGraphs?: string[];
|
|
27
|
+
};
|
|
28
|
+
/** The shape check's findings, counted by severity (each is logged). Set by `POST /admin/sync-shapes`. */
|
|
29
|
+
shapeCheck?: {
|
|
30
|
+
errors: number;
|
|
31
|
+
warnings: number;
|
|
32
|
+
};
|
|
17
33
|
}
|
|
18
34
|
/** Whether `name` is a valid npm package name (and so can never be a path like `..`). */
|
|
19
35
|
export declare function isValidPackageName(name: string): boolean;
|
|
@@ -33,7 +49,26 @@ export interface AdminChannelHandlers {
|
|
|
33
49
|
syncShapes: (request: {
|
|
34
50
|
packages: string[];
|
|
35
51
|
}) => Promise<ShapeSyncResult>;
|
|
52
|
+
/**
|
|
53
|
+
* Drop the cached graph registry for `dataset` (see `POST /admin/graph-registry-changed`).
|
|
54
|
+
* Default: {@link dropGraphRegistryCache}.
|
|
55
|
+
*/
|
|
56
|
+
graphRegistryChanged?: (dataset: string) => void;
|
|
36
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Drop the process's cached graph registry after the host changed the graphs of `dataset`.
|
|
60
|
+
*
|
|
61
|
+
* Every entry is dropped, not only that dataset's: an entry's key is each store's own
|
|
62
|
+
* (`graphRegistryKey()`: a `FusekiStore` keys by its dataset URL, a `RemoteDataset` by the
|
|
63
|
+
* dataset its server names), no store tells which key it uses, and the stores are built by the
|
|
64
|
+
* app's storage config, whose aliases the server does not see. The registry is small, so the cost
|
|
65
|
+
* is one registry read per dataset on its next expanding read.
|
|
66
|
+
*/
|
|
67
|
+
export declare function dropGraphRegistryCache(_dataset: string): void;
|
|
68
|
+
/** The `dataset` of a graph-registry-changed body: a non-empty name. */
|
|
69
|
+
export declare function parseGraphRegistryChangedBody(body: unknown): {
|
|
70
|
+
dataset: string;
|
|
71
|
+
};
|
|
37
72
|
/** Compare the provided secret with the configured one in constant time. */
|
|
38
73
|
export declare function adminSecretMatches(secret: string | undefined, provided: string | undefined): boolean;
|
|
39
74
|
/** The `packages` of a sync-shapes body: a list of package names, or none. */
|
|
@@ -8,15 +8,24 @@
|
|
|
8
8
|
* - `GET /admin/health` → 200 `{status: 'ok'}` once the server listens (the boot
|
|
9
9
|
* shape sync has finished by then).
|
|
10
10
|
* - `POST /admin/restart` → 202, then the process exits; the host starts it again.
|
|
11
|
-
* - `POST /admin/sync-shapes` → re-syncs the app's
|
|
12
|
-
*
|
|
11
|
+
* - `POST /admin/sync-shapes` → re-syncs the app's ontologies (each registered package's
|
|
12
|
+
* ontology graph, skipped when unchanged), runs the shape check and
|
|
13
|
+
* re-syncs its shapes into its app data, as the boot does, and answers 200 with
|
|
14
|
+
* {@link ShapeSyncResult}. Body (optional):
|
|
13
15
|
* `{packages: string[]}`, packages whose source changed on disk: in dev they are
|
|
14
16
|
* reloaded first, so the sync sees shapes added or changed since the boot. Each
|
|
15
17
|
* name must be a valid npm package name and the app itself or one of its direct
|
|
16
18
|
* dependencies, never an `@_linked/*` framework package; anything else answers
|
|
17
|
-
* 400 `{error}`. A failed or timed-out sync
|
|
19
|
+
* 400 `{error}`. The list never filters the syncs. A failed or timed-out sync
|
|
20
|
+
* answers 500 `{error}` (a failed ontology sync too, after the shape sync ran).
|
|
21
|
+
* - `POST /admin/graph-registry-changed` `{dataset}` → the host changed the named graphs of that
|
|
22
|
+
* dataset (a graph query through its gateway): the process drops its cached graph registry, so
|
|
23
|
+
* its next `.from(graphs.allOntologies)` read re-reads it, and answers 200
|
|
24
|
+
* `{invalidated: dataset}`. A body without a dataset name answers 400. Without the push the
|
|
25
|
+
* cache's 30-second expiry applies.
|
|
18
26
|
*/
|
|
19
27
|
import { timingSafeEqual } from 'crypto';
|
|
28
|
+
import { invalidateGraphRegistry } from '@_linked/core/utils/graphRegistryCache';
|
|
20
29
|
/** npm's package-name rule: optional `@scope/`, lower case, URL-safe, no leading `.` or `_` (a scope may start with `_`, as `@_linked` does). */
|
|
21
30
|
const NPM_NAME = /^(?:@[a-z0-9-~_][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
|
|
22
31
|
/** Whether `name` is a valid npm package name (and so can never be a path like `..`). */
|
|
@@ -42,6 +51,26 @@ export function assertReloadablePackages(packages, allowed) {
|
|
|
42
51
|
/** Thrown by a handler for a request the channel refuses with 400. */
|
|
43
52
|
export class AdminRequestError extends Error {
|
|
44
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Drop the process's cached graph registry after the host changed the graphs of `dataset`.
|
|
56
|
+
*
|
|
57
|
+
* Every entry is dropped, not only that dataset's: an entry's key is each store's own
|
|
58
|
+
* (`graphRegistryKey()`: a `FusekiStore` keys by its dataset URL, a `RemoteDataset` by the
|
|
59
|
+
* dataset its server names), no store tells which key it uses, and the stores are built by the
|
|
60
|
+
* app's storage config, whose aliases the server does not see. The registry is small, so the cost
|
|
61
|
+
* is one registry read per dataset on its next expanding read.
|
|
62
|
+
*/
|
|
63
|
+
export function dropGraphRegistryCache(_dataset) {
|
|
64
|
+
invalidateGraphRegistry();
|
|
65
|
+
}
|
|
66
|
+
/** The `dataset` of a graph-registry-changed body: a non-empty name. */
|
|
67
|
+
export function parseGraphRegistryChangedBody(body) {
|
|
68
|
+
const dataset = body && typeof body === 'object' ? body.dataset : undefined;
|
|
69
|
+
if (typeof dataset !== 'string' || !dataset.trim() || dataset.length > 1024) {
|
|
70
|
+
throw new AdminRequestError('dataset must be the name of the dataset whose graphs changed');
|
|
71
|
+
}
|
|
72
|
+
return { dataset: dataset.trim() };
|
|
73
|
+
}
|
|
45
74
|
/** Compare the provided secret with the configured one in constant time. */
|
|
46
75
|
export function adminSecretMatches(secret, provided) {
|
|
47
76
|
if (!secret || !provided)
|
|
@@ -93,6 +122,21 @@ export function registerAdminRoutes(app, secret, handlers) {
|
|
|
93
122
|
res.sendStatus(202);
|
|
94
123
|
setTimeout(handlers.exit, 50);
|
|
95
124
|
});
|
|
125
|
+
app.post('/admin/graph-registry-changed', (req, res) => {
|
|
126
|
+
var _a;
|
|
127
|
+
if (!requireAdmin(req, res))
|
|
128
|
+
return;
|
|
129
|
+
let dataset;
|
|
130
|
+
try {
|
|
131
|
+
({ dataset } = parseGraphRegistryChangedBody(req.body));
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
res.status(400).json({ error: err.message });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
((_a = handlers.graphRegistryChanged) !== null && _a !== void 0 ? _a : dropGraphRegistryCache)(dataset);
|
|
138
|
+
res.status(200).json({ invalidated: dataset });
|
|
139
|
+
});
|
|
96
140
|
app.post('/admin/sync-shapes', async (req, res) => {
|
|
97
141
|
if (!requireAdmin(req, res))
|
|
98
142
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adminChannel.js","sourceRoot":"","sources":["../../../src/utils/adminChannel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,C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,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAG,GAAa,CAAC,OAAO,EAAE,CAAC,CAAC;YACxD,OAAO;QACT,CAAC;QACD,IAAI,CAAC;YACH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,MAAM,GAAG,GAAG,YAAY,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YAC5D,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * The host→app control channel: `/admin/*` routes a host (Create Now) uses on an\n * app process it started. Present only when the process was started with a\n * shared secret in `CN_APP_ADMIN_SECRET`; without it every route answers 404, so\n * a standalone app has no control channel. Every request carries the secret in\n * the `x-cn-admin-secret` header.\n *\n * - `GET /admin/health` → 200 `{status: 'ok'}` once the server listens (the boot\n * shape sync has finished by then).\n * - `POST /admin/restart` → 202, then the process exits; the host starts it again.\n * - `POST /admin/sync-shapes` → re-syncs the app's shapes into its app data, as\n * the boot does, and answers 200 with {@link ShapeSyncResult}. Body (optional):\n * `{packages: string[]}`, packages whose source changed on disk: in dev they are\n * reloaded first, so the sync sees shapes added or changed since the boot. Each\n * name must be a valid npm package name and the app itself or one of its direct\n * dependencies, never an `@_linked/*` framework package; anything else answers\n * 400 `{error}`. A failed or timed-out sync answers 500 `{error}`.\n */\nimport { timingSafeEqual } from 'crypto';\nimport type express from 'express';\n\n/** What one shape sync did. */\nexport interface ShapeSyncResult {\n /** Shapes written: those whose stored hash differed from the registered shape. */\n written: number;\n /** The orphan policy the sync ran with (see utils/syncShapes). */\n orphanScope?: 'all' | 'none';\n /** Set when no sync ran: shape sync is turned off, or there is no default dataset. */\n skipped?: 'disabled' | 'no-default-dataset';\n /**\n * The requested packages whose source was reloaded before the sync (dev only: a built\n * app reloads nothing). Set by `POST /admin/sync-shapes`.\n */\n reloaded?: string[];\n /** The node shape IRIs registered in the process after the reload. Set by `POST /admin/sync-shapes`. */\n shapes?: string[];\n}\n\n/** npm's package-name rule: optional `@scope/`, lower case, URL-safe, no leading `.` or `_` (a scope may start with `_`, as `@_linked` does). */\nconst NPM_NAME = /^(?:@[a-z0-9-~_][a-z0-9-._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/;\n\n/** Whether `name` is a valid npm package name (and so can never be a path like `..`). */\nexport function isValidPackageName(name: string): boolean {\n return name.length <= 214 && NPM_NAME.test(name) && !name.split('/').some((part) => part === '.' || part === '..');\n}\n\n/**\n * Refuse a package a host may not ask to reload: not a valid npm name, a framework\n * (`@_linked/*`) package, or not in `allowed` (the app's own name and its direct\n * dependencies). Throws {@link AdminRequestError}.\n */\nexport function assertReloadablePackages(packages: string[], allowed: ReadonlySet<string>): void {\n for (const pkg of packages) {\n if (!isValidPackageName(pkg)) throw new AdminRequestError(`not a package name: ${JSON.stringify(pkg)}`);\n if (pkg.startsWith('@_linked/')) throw new AdminRequestError(`framework packages are not reloaded: ${pkg}`);\n if (!allowed.has(pkg)) {\n throw new AdminRequestError(`unknown package: ${pkg} is neither the app nor one of its direct dependencies`);\n }\n }\n}\n\n/** Thrown by a handler for a request the channel refuses with 400. */\nexport class AdminRequestError extends Error {}\n\nexport interface AdminChannelHandlers {\n /** Exit the process (the host restarts it). Called after the 202 is sent. */\n exit: () => void;\n /** Reload `packages` (when given) and sync the registered shapes into app data. */\n syncShapes: (request: { packages: string[] }) => Promise<ShapeSyncResult>;\n}\n\n/** Compare the provided secret with the configured one in constant time. */\nexport function adminSecretMatches(\n secret: string | undefined,\n provided: string | undefined\n): boolean {\n if (!secret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(secret);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\n/** The `packages` of a sync-shapes body: a list of package names, or none. */\nexport function parseSyncShapesBody(body: unknown): { packages: string[] } {\n if (body === undefined || body === null || body === '') return { packages: [] };\n if (typeof body !== 'object') {\n throw new AdminRequestError('the body must be a JSON object');\n }\n const packages = (body as { packages?: unknown }).packages;\n if (packages === undefined) return { packages: [] };\n if (!Array.isArray(packages) || packages.some((p) => typeof p !== 'string' || !p)) {\n throw new AdminRequestError('packages must be a list of package names');\n }\n for (const p of packages as string[]) {\n if (!isValidPackageName(p)) throw new AdminRequestError(`not a package name: ${JSON.stringify(p)}`);\n }\n return { packages: [...new Set(packages as string[])] };\n}\n\n/** Mount the control channel's routes on `app`. */\nexport function registerAdminRoutes(\n app: express.Express,\n secret: string | undefined,\n handlers: AdminChannelHandlers\n): void {\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!secret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!adminSecretMatches(secret, req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n\n app.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n\n app.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n setTimeout(handlers.exit, 50);\n });\n\n app.post('/admin/sync-shapes', async (req, res) => {\n if (!requireAdmin(req, res)) return;\n let request: { packages: string[] };\n try {\n request = parseSyncShapesBody(req.body);\n } catch (err) {\n res.status(400).json({ error: (err as Error).message });\n return;\n }\n try {\n res.status(200).json(await handlers.syncShapes(request));\n } catch (err) {\n const status = err instanceof AdminRequestError ? 400 : 500;\n res.status(status).json({ error: err instanceof Error ? err.message : String(err) });\n }\n });\n}\n"]}
|
|
1
|
+
{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EAAE,GAAG,CAAC;YAAE,OAAO;QACpC,IAAI,OAA+B,CAAC;QACpC,IAAI,CAAC;YACH,OAAO,GAAG,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAG,GAAa,CAAC,OAAO,EAAE,CAAC,CAAC;YACxD,OAAO;QACT,CAAC;QACD,IAAI,CAAC;YACH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,MAAM,GAAG,GAAG,YAAY,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YAC5D,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * The host→app control channel: `/admin/*` routes a host (Create Now) uses on an\n * app process it started. Present only when the process was started with a\n * shared secret in `CN_APP_ADMIN_SECRET`; without it every route answers 404, so\n * a standalone app has no control channel. Every request carries the secret in\n * the `x-cn-admin-secret` header.\n *\n * - `GET /admin/health` → 200 `{status: 'ok'}` once the server listens (the boot\n * shape sync has finished by then).\n * - `POST /admin/restart` → 202, then the process exits; the host starts it again.\n * - `POST /admin/sync-shapes` → re-syncs the app's ontologies (each registered package's\n * ontology graph, skipped when unchanged), runs the shape check and\n * re-syncs its shapes into its app data, as the boot does, and answers 200 with\n * {@link ShapeSyncResult}. Body (optional):\n * `{packages: string[]}`, packages whose source changed on disk: in dev they are\n * reloaded first, so the sync sees shapes added or changed since the boot. Each\n * name must be a valid npm package name and the app itself or one of its direct\n * dependencies, never an `@_linked/*` framework package; anything else answers\n * 400 `{error}`. The list never filters the syncs. A failed or timed-out sync\n * answers 500 `{error}` (a failed ontology sync too, after the shape sync ran).\n * - `POST /admin/graph-registry-changed` `{dataset}` → the host changed the named graphs of that\n * dataset (a graph query through its gateway): the process drops its cached graph registry, so\n * its next `.from(graphs.allOntologies)` read re-reads it, and answers 200\n * `{invalidated: dataset}`. A body without a dataset name answers 400. Without the push the\n * cache's 30-second expiry applies.\n */\nimport { timingSafeEqual } from 'crypto';\nimport type express from 'express';\nimport { invalidateGraphRegistry } from '@_linked/core/utils/graphRegistryCache';\n\n/** What one shape sync did. */\nexport interface ShapeSyncResult {\n /** Shapes written: those whose stored hash differed from the registered shape. */\n written: number;\n /** The orphan policy the sync ran with (see utils/syncShapes). */\n orphanScope?: 'all' | 'none';\n /** Set when no sync ran: shape sync is turned off, or there is no default dataset. */\n skipped?: 'disabled' | 'no-default-dataset';\n /**\n * The requested packages whose source was reloaded before the sync (dev only: a built\n * app reloads nothing). Set by `POST /admin/sync-shapes`.\n */\n reloaded?: string[];\n /** The node shape IRIs registered in the process after the reload. Set by `POST /admin/sync-shapes`. */\n shapes?: string[];\n /**\n * The ontology sync: packages whose ontology graph (or, on a store without graph queries,\n * class hierarchy) was written, packages left as they were (unchanged, or their data could not\n * be read), and the graphs written and dropped. Set by `POST /admin/sync-shapes`.\n */\n ontologies?: { written: string[]; skipped: string[]; graphs?: string[]; droppedGraphs?: string[] };\n /** The shape check's findings, counted by severity (each is logged). Set by `POST /admin/sync-shapes`. */\n shapeCheck?: { errors: number; warnings: number };\n}\n\n/** npm's package-name rule: optional `@scope/`, lower case, URL-safe, no leading `.` or `_` (a scope may start with `_`, as `@_linked` does). */\nconst NPM_NAME = /^(?:@[a-z0-9-~_][a-z0-9-._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/;\n\n/** Whether `name` is a valid npm package name (and so can never be a path like `..`). */\nexport function isValidPackageName(name: string): boolean {\n return name.length <= 214 && NPM_NAME.test(name) && !name.split('/').some((part) => part === '.' || part === '..');\n}\n\n/**\n * Refuse a package a host may not ask to reload: not a valid npm name, a framework\n * (`@_linked/*`) package, or not in `allowed` (the app's own name and its direct\n * dependencies). Throws {@link AdminRequestError}.\n */\nexport function assertReloadablePackages(packages: string[], allowed: ReadonlySet<string>): void {\n for (const pkg of packages) {\n if (!isValidPackageName(pkg)) throw new AdminRequestError(`not a package name: ${JSON.stringify(pkg)}`);\n if (pkg.startsWith('@_linked/')) throw new AdminRequestError(`framework packages are not reloaded: ${pkg}`);\n if (!allowed.has(pkg)) {\n throw new AdminRequestError(`unknown package: ${pkg} is neither the app nor one of its direct dependencies`);\n }\n }\n}\n\n/** Thrown by a handler for a request the channel refuses with 400. */\nexport class AdminRequestError extends Error {}\n\nexport interface AdminChannelHandlers {\n /** Exit the process (the host restarts it). Called after the 202 is sent. */\n exit: () => void;\n /** Reload `packages` (when given) and sync the registered shapes into app data. */\n syncShapes: (request: { packages: string[] }) => Promise<ShapeSyncResult>;\n /**\n * Drop the cached graph registry for `dataset` (see `POST /admin/graph-registry-changed`).\n * Default: {@link dropGraphRegistryCache}.\n */\n graphRegistryChanged?: (dataset: string) => void;\n}\n\n/**\n * Drop the process's cached graph registry after the host changed the graphs of `dataset`.\n *\n * Every entry is dropped, not only that dataset's: an entry's key is each store's own\n * (`graphRegistryKey()`: a `FusekiStore` keys by its dataset URL, a `RemoteDataset` by the\n * dataset its server names), no store tells which key it uses, and the stores are built by the\n * app's storage config, whose aliases the server does not see. The registry is small, so the cost\n * is one registry read per dataset on its next expanding read.\n */\nexport function dropGraphRegistryCache(_dataset: string): void {\n invalidateGraphRegistry();\n}\n\n/** The `dataset` of a graph-registry-changed body: a non-empty name. */\nexport function parseGraphRegistryChangedBody(body: unknown): { dataset: string } {\n const dataset = body && typeof body === 'object' ? (body as { dataset?: unknown }).dataset : undefined;\n if (typeof dataset !== 'string' || !dataset.trim() || dataset.length > 1024) {\n throw new AdminRequestError('dataset must be the name of the dataset whose graphs changed');\n }\n return { dataset: dataset.trim() };\n}\n\n/** Compare the provided secret with the configured one in constant time. */\nexport function adminSecretMatches(\n secret: string | undefined,\n provided: string | undefined\n): boolean {\n if (!secret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(secret);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\n/** The `packages` of a sync-shapes body: a list of package names, or none. */\nexport function parseSyncShapesBody(body: unknown): { packages: string[] } {\n if (body === undefined || body === null || body === '') return { packages: [] };\n if (typeof body !== 'object') {\n throw new AdminRequestError('the body must be a JSON object');\n }\n const packages = (body as { packages?: unknown }).packages;\n if (packages === undefined) return { packages: [] };\n if (!Array.isArray(packages) || packages.some((p) => typeof p !== 'string' || !p)) {\n throw new AdminRequestError('packages must be a list of package names');\n }\n for (const p of packages as string[]) {\n if (!isValidPackageName(p)) throw new AdminRequestError(`not a package name: ${JSON.stringify(p)}`);\n }\n return { packages: [...new Set(packages as string[])] };\n}\n\n/** Mount the control channel's routes on `app`. */\nexport function registerAdminRoutes(\n app: express.Express,\n secret: string | undefined,\n handlers: AdminChannelHandlers\n): void {\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!secret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!adminSecretMatches(secret, req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n\n app.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n\n app.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n setTimeout(handlers.exit, 50);\n });\n\n app.post('/admin/graph-registry-changed', (req, res) => {\n if (!requireAdmin(req, res)) return;\n let dataset: string;\n try {\n ({ dataset } = parseGraphRegistryChangedBody(req.body));\n } catch (err) {\n res.status(400).json({ error: (err as Error).message });\n return;\n }\n (handlers.graphRegistryChanged ?? dropGraphRegistryCache)(dataset);\n res.status(200).json({ invalidated: dataset });\n });\n\n app.post('/admin/sync-shapes', async (req, res) => {\n if (!requireAdmin(req, res)) return;\n let request: { packages: string[] };\n try {\n request = parseSyncShapesBody(req.body);\n } catch (err) {\n res.status(400).json({ error: (err as Error).message });\n return;\n }\n try {\n res.status(200).json(await handlers.syncShapes(request));\n } catch (err) {\n const status = err instanceof AdminRequestError ? 400 : 500;\n res.status(status).json({ error: err instanceof Error ? err.message : String(err) });\n }\n });\n}\n"]}
|
|
@@ -70,6 +70,13 @@ export declare function readInstalledPackage(name: string, fromDir: string): {
|
|
|
70
70
|
* (it is only installed nested) it is the first copy found.
|
|
71
71
|
*/
|
|
72
72
|
export declare function discoverLinkedDependencies(appDir: string, appPackageJson: any): LinkedDependency[];
|
|
73
|
+
/**
|
|
74
|
+
* Package name → the names of its direct `dependencies` and `peerDependencies`, for the app
|
|
75
|
+
* (`appPackageJson`) and every package in `packageDirs` (name → package root, as discovery
|
|
76
|
+
* found it). The shape check scopes its direction-I errors with it. A package whose
|
|
77
|
+
* `package.json` cannot be read is left out.
|
|
78
|
+
*/
|
|
79
|
+
export declare function readDependencyLists(packageDirs: Iterable<[string, string]>, appPackageJson?: any): Record<string, string[]>;
|
|
73
80
|
/**
|
|
74
81
|
* The conditions a backend entry is resolved with on the Node path. These are
|
|
75
82
|
* the ones Node's ESM loader applies to `import()` — so the file found is the
|
|
@@ -131,6 +131,35 @@ export function discoverLinkedDependencies(appDir, appPackageJson) {
|
|
|
131
131
|
}
|
|
132
132
|
return out;
|
|
133
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* Package name → the names of its direct `dependencies` and `peerDependencies`, for the app
|
|
136
|
+
* (`appPackageJson`) and every package in `packageDirs` (name → package root, as discovery
|
|
137
|
+
* found it). The shape check scopes its direction-I errors with it. A package whose
|
|
138
|
+
* `package.json` cannot be read is left out.
|
|
139
|
+
*/
|
|
140
|
+
export function readDependencyLists(packageDirs, appPackageJson) {
|
|
141
|
+
const lists = {};
|
|
142
|
+
const add = (name, json) => {
|
|
143
|
+
var _a, _b;
|
|
144
|
+
if (typeof name !== 'string' || !name)
|
|
145
|
+
return;
|
|
146
|
+
lists[name] = [
|
|
147
|
+
...new Set([
|
|
148
|
+
...Object.keys((_a = json === null || json === void 0 ? void 0 : json.dependencies) !== null && _a !== void 0 ? _a : {}),
|
|
149
|
+
...Object.keys((_b = json === null || json === void 0 ? void 0 : json.peerDependencies) !== null && _b !== void 0 ? _b : {}),
|
|
150
|
+
]),
|
|
151
|
+
].sort();
|
|
152
|
+
};
|
|
153
|
+
if (appPackageJson)
|
|
154
|
+
add(appPackageJson.name, appPackageJson);
|
|
155
|
+
for (const [name, dir] of packageDirs) {
|
|
156
|
+
try {
|
|
157
|
+
add(name, JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')));
|
|
158
|
+
}
|
|
159
|
+
catch (_a) { }
|
|
160
|
+
}
|
|
161
|
+
return lists;
|
|
162
|
+
}
|
|
134
163
|
function realpathOr(p) {
|
|
135
164
|
try {
|
|
136
165
|
return fs.realpathSync(p);
|