@_linked/server 3.9.0 → 3.11.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 +23 -0
- package/lib/esm/shapes/LinkedServer.js +12 -1
- package/lib/esm/shapes/LinkedServer.js.map +1 -1
- package/lib/esm/utils/adminChannel.d.ts +2 -11
- package/lib/esm/utils/adminChannel.js +4 -46
- package/lib/esm/utils/adminChannel.js.map +1 -1
- package/lib/esm/utils/effectiveRoutes.d.ts +12 -1
- package/lib/esm/utils/effectiveRoutes.js +5 -1
- package/lib/esm/utils/effectiveRoutes.js.map +1 -1
- package/lib/esm/utils/graphTargets.d.ts +20 -0
- package/lib/esm/utils/graphTargets.js +53 -0
- package/lib/esm/utils/graphTargets.js.map +1 -0
- package/lib/esm/utils/ontologySync.d.ts +14 -0
- package/lib/esm/utils/ontologySync.js +40 -7
- package/lib/esm/utils/ontologySync.js.map +1 -1
- package/lib/esm/utils/syncShapes.d.ts +12 -1
- package/lib/esm/utils/syncShapes.js +32 -6
- package/lib/esm/utils/syncShapes.js.map +1 -1
- package/package.json +2 -2
- package/readme.md +45 -7
|
@@ -3,17 +3,10 @@ import type { ShapeGraphsReport } from './syncShapes.js';
|
|
|
3
3
|
import { type EffectiveRoutes } from './effectiveRoutes.js';
|
|
4
4
|
/** The environment variable that holds the control channel's secret. */
|
|
5
5
|
export declare const ADMIN_SECRET_ENV = "APP_ADMIN_SECRET";
|
|
6
|
-
/** Its former name, read when {@link ADMIN_SECRET_ENV} is unset. @deprecated */
|
|
7
|
-
export declare const LEGACY_ADMIN_SECRET_ENV = "CN_APP_ADMIN_SECRET";
|
|
8
6
|
/** The request header that carries the secret. */
|
|
9
7
|
export declare const ADMIN_SECRET_HEADER = "x-app-admin-secret";
|
|
10
|
-
/**
|
|
11
|
-
export declare
|
|
12
|
-
/**
|
|
13
|
-
* The control channel's secret: `APP_ADMIN_SECRET`, else the deprecated `CN_APP_ADMIN_SECRET`
|
|
14
|
-
* (logged once per process), else `undefined` (no control channel).
|
|
15
|
-
*/
|
|
16
|
-
export declare function resolveAdminSecret(env?: Record<string, string | undefined>, warn?: (message: string) => void): string | undefined;
|
|
8
|
+
/** The control channel's secret: `APP_ADMIN_SECRET`, else `undefined` (no control channel). */
|
|
9
|
+
export declare function resolveAdminSecret(env?: Record<string, string | undefined>): string | undefined;
|
|
17
10
|
/** What one shape sync did. */
|
|
18
11
|
export interface ShapeSyncResult {
|
|
19
12
|
/**
|
|
@@ -80,8 +73,6 @@ export interface AdminChannelHandlers {
|
|
|
80
73
|
graphRegistryChanged?: (dataset: string) => void;
|
|
81
74
|
/** The effective graph routes (see `GET /admin/routes`). Default: {@link effectiveGraphRoutes}. */
|
|
82
75
|
routes?: () => EffectiveRoutes;
|
|
83
|
-
/** Where deprecation warnings go. Default: `console.warn`. */
|
|
84
|
-
warn?: (message: string) => void;
|
|
85
76
|
}
|
|
86
77
|
/**
|
|
87
78
|
* Drop the process's cached graph registry after the host changed the graphs of `dataset`.
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
var _a;
|
|
2
|
-
var _b, _c;
|
|
3
1
|
/**
|
|
4
2
|
* The host→app control channel: `/admin/*` routes a host uses on an app process it
|
|
5
3
|
* started. Present only when the process was started with a shared secret in
|
|
@@ -30,56 +28,17 @@ var _b, _c;
|
|
|
30
28
|
* router knows (shape IRI → graph IRI) and the shapes each one writes to its default graph,
|
|
31
29
|
* as core's routing holds them once the app's storage file has run. The routes are written
|
|
32
30
|
* only in the app's storage file; this route lets a host check what actually runs.
|
|
33
|
-
*
|
|
34
|
-
* Deprecated names, still read: `CN_APP_ADMIN_SECRET` when `APP_ADMIN_SECRET` is unset, and the
|
|
35
|
-
* `x-cn-admin-secret` header when `x-app-admin-secret` is absent; each logs one warning.
|
|
36
31
|
*/
|
|
37
32
|
import { createHash, timingSafeEqual } from 'crypto';
|
|
38
33
|
import { invalidateGraphRegistry } from '@_linked/core/utils/graphRegistryCache';
|
|
39
34
|
import { effectiveGraphRoutes } from './effectiveRoutes.js';
|
|
40
35
|
/** The environment variable that holds the control channel's secret. */
|
|
41
36
|
export const ADMIN_SECRET_ENV = 'APP_ADMIN_SECRET';
|
|
42
|
-
/** Its former name, read when {@link ADMIN_SECRET_ENV} is unset. @deprecated */
|
|
43
|
-
export const LEGACY_ADMIN_SECRET_ENV = 'CN_APP_ADMIN_SECRET';
|
|
44
37
|
/** The request header that carries the secret. */
|
|
45
38
|
export const ADMIN_SECRET_HEADER = 'x-app-admin-secret';
|
|
46
|
-
/**
|
|
47
|
-
export
|
|
48
|
-
|
|
49
|
-
* Which deprecation warnings this process has logged. On the shared global, so a module that
|
|
50
|
-
* evaluates twice still warns once.
|
|
51
|
-
*/
|
|
52
|
-
const warned = ((_a = (_b = globalThis)[_c = Symbol.for('@_linked/server:adminChannelDeprecationsWarned')]) !== null && _a !== void 0 ? _a : (_b[_c] = new Set()));
|
|
53
|
-
function warnOnce(key, message, warn) {
|
|
54
|
-
if (warned.has(key))
|
|
55
|
-
return;
|
|
56
|
-
warned.add(key);
|
|
57
|
-
warn(message);
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* The control channel's secret: `APP_ADMIN_SECRET`, else the deprecated `CN_APP_ADMIN_SECRET`
|
|
61
|
-
* (logged once per process), else `undefined` (no control channel).
|
|
62
|
-
*/
|
|
63
|
-
export function resolveAdminSecret(env = process.env, warn = console.warn) {
|
|
64
|
-
const secret = env[ADMIN_SECRET_ENV];
|
|
65
|
-
if (secret)
|
|
66
|
-
return secret;
|
|
67
|
-
const legacy = env[LEGACY_ADMIN_SECRET_ENV];
|
|
68
|
-
if (!legacy)
|
|
69
|
-
return undefined;
|
|
70
|
-
warnOnce('env', `[linked] ${LEGACY_ADMIN_SECRET_ENV} is deprecated; set ${ADMIN_SECRET_ENV} instead (read as a fallback for now).`, warn);
|
|
71
|
-
return legacy;
|
|
72
|
-
}
|
|
73
|
-
/** The secret a request carries: the `x-app-admin-secret` header, else the deprecated one. */
|
|
74
|
-
function providedSecret(req, warn) {
|
|
75
|
-
const current = req.get(ADMIN_SECRET_HEADER);
|
|
76
|
-
if (current)
|
|
77
|
-
return current;
|
|
78
|
-
const legacy = req.get(LEGACY_ADMIN_SECRET_HEADER);
|
|
79
|
-
if (legacy) {
|
|
80
|
-
warnOnce('header', `[linked] the ${LEGACY_ADMIN_SECRET_HEADER} header is deprecated; send ${ADMIN_SECRET_HEADER} instead.`, warn);
|
|
81
|
-
}
|
|
82
|
-
return legacy;
|
|
39
|
+
/** The control channel's secret: `APP_ADMIN_SECRET`, else `undefined` (no control channel). */
|
|
40
|
+
export function resolveAdminSecret(env = process.env) {
|
|
41
|
+
return env[ADMIN_SECRET_ENV] || undefined;
|
|
83
42
|
}
|
|
84
43
|
/** npm's package-name rule: optional `@scope/`, lower case, URL-safe, no leading `.` or `_` (a scope may start with `_`, as `@_linked` does). */
|
|
85
44
|
const NPM_NAME = /^(?:@[a-z0-9-~_][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
|
|
@@ -158,12 +117,11 @@ export function parseSyncShapesBody(body) {
|
|
|
158
117
|
/** Mount the control channel's routes on `app`. */
|
|
159
118
|
export function registerAdminRoutes(app, secret, handlers) {
|
|
160
119
|
const requireAdmin = (req, res) => {
|
|
161
|
-
var _a;
|
|
162
120
|
if (!secret) {
|
|
163
121
|
res.sendStatus(404); // no control channel in this mode
|
|
164
122
|
return false;
|
|
165
123
|
}
|
|
166
|
-
if (!adminSecretMatches(secret,
|
|
124
|
+
if (!adminSecretMatches(secret, req.get(ADMIN_SECRET_HEADER))) {
|
|
167
125
|
res.sendStatus(401);
|
|
168
126
|
return false;
|
|
169
127
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adminChannel.js","sourceRoot":"","sources":["../../../src/utils/adminChannel.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,UA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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 uses on an app process it\n * started. Present only when the process was started with a shared secret in\n * `APP_ADMIN_SECRET` (see {@link resolveAdminSecret}); without it every route answers\n * 404, so a standalone app has no control channel. Every request carries the secret in\n * the `x-app-admin-secret` header (401 otherwise).\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 (each package's shape graph and the app's own,\n * skipped when unchanged), as the boot does, and answers 200 with\n * {@link ShapeSyncResult}, whose `shapeGraphs` reports the shape graphs. 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 * - `GET /admin/routes` → 200 {@link EffectiveRoutes}: the graph routes of every dataset the\n * router knows (shape IRI → graph IRI) and the shapes each one writes to its default graph,\n * as core's routing holds them once the app's storage file has run. The routes are written\n * only in the app's storage file; this route lets a host check what actually runs.\n *\n * Deprecated names, still read: `CN_APP_ADMIN_SECRET` when `APP_ADMIN_SECRET` is unset, and the\n * `x-cn-admin-secret` header when `x-app-admin-secret` is absent; each logs one warning.\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport type express from 'express';\nimport { invalidateGraphRegistry } from '@_linked/core/utils/graphRegistryCache';\nimport type { ShapeGraphsReport } from './syncShapes.js';\nimport { effectiveGraphRoutes, type EffectiveRoutes } from './effectiveRoutes.js';\n\n/** The environment variable that holds the control channel's secret. */\nexport const ADMIN_SECRET_ENV = 'APP_ADMIN_SECRET';\n/** Its former name, read when {@link ADMIN_SECRET_ENV} is unset. @deprecated */\nexport const LEGACY_ADMIN_SECRET_ENV = 'CN_APP_ADMIN_SECRET';\n/** The request header that carries the secret. */\nexport const ADMIN_SECRET_HEADER = 'x-app-admin-secret';\n/** Its former name, read when {@link ADMIN_SECRET_HEADER} is absent. @deprecated */\nexport const LEGACY_ADMIN_SECRET_HEADER = 'x-cn-admin-secret';\n\n/**\n * Which deprecation warnings this process has logged. On the shared global, so a module that\n * evaluates twice still warns once.\n */\nconst warned: Set<string> = ((globalThis as Record<symbol, unknown>)[\n Symbol.for('@_linked/server:adminChannelDeprecationsWarned')\n] ??= new Set<string>()) as Set<string>;\n\nfunction warnOnce(key: string, message: string, warn: (message: string) => void): void {\n if (warned.has(key)) return;\n warned.add(key);\n warn(message);\n}\n\n/**\n * The control channel's secret: `APP_ADMIN_SECRET`, else the deprecated `CN_APP_ADMIN_SECRET`\n * (logged once per process), else `undefined` (no control channel).\n */\nexport function resolveAdminSecret(\n env: Record<string, string | undefined> = process.env,\n warn: (message: string) => void = console.warn\n): string | undefined {\n const secret = env[ADMIN_SECRET_ENV];\n if (secret) return secret;\n const legacy = env[LEGACY_ADMIN_SECRET_ENV];\n if (!legacy) return undefined;\n warnOnce(\n 'env',\n `[linked] ${LEGACY_ADMIN_SECRET_ENV} is deprecated; set ${ADMIN_SECRET_ENV} instead (read as a fallback for now).`,\n warn\n );\n return legacy;\n}\n\n/** The secret a request carries: the `x-app-admin-secret` header, else the deprecated one. */\nfunction providedSecret(req: express.Request, warn: (message: string) => void): string | undefined {\n const current = req.get(ADMIN_SECRET_HEADER);\n if (current) return current;\n const legacy = req.get(LEGACY_ADMIN_SECRET_HEADER);\n if (legacy) {\n warnOnce(\n 'header',\n `[linked] the ${LEGACY_ADMIN_SECRET_HEADER} header is deprecated; send ${ADMIN_SECRET_HEADER} instead.`,\n warn\n );\n }\n return legacy;\n}\n\n/** What one shape sync did. */\nexport interface ShapeSyncResult {\n /**\n * Shape graphs written (package graphs and the app's own graph) because their stored hash\n * differed; on a store without graph queries, the default-graph sync's writes.\n */\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 shape graph sync: packages written and skipped, the graphs written, the app's own shape\n * graph, the registered packages without `shapes.ttl` (so without a shape graph) and the\n * default-graph shapes removed. Absent when no sync ran.\n */\n shapeGraphs?: ShapeGraphsReport;\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 /** The effective graph routes (see `GET /admin/routes`). Default: {@link effectiveGraphRoutes}. */\n routes?: () => EffectiveRoutes;\n /** Where deprecation warnings go. Default: `console.warn`. */\n warn?: (message: 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/**\n * Compare the provided secret with the configured one in constant time. Both sides are hashed\n * first, so the comparison does not reveal the secret's length either.\n */\nexport function adminSecretMatches(\n secret: string | undefined,\n provided: string | undefined\n): boolean {\n if (!secret || !provided) return false;\n const digest = (value: string) => createHash('sha256').update(value).digest();\n return timingSafeEqual(digest(provided), digest(secret));\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, providedSecret(req, handlers.warn ?? console.warn))) {\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.get('/admin/routes', (req, res) => {\n if (!requireAdmin(req, res)) return;\n try {\n res.status(200).json((handlers.routes ?? effectiveGraphRoutes)());\n } catch (err) {\n res.status(500).json({ error: err instanceof Error ? err.message : String(err) });\n }\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"]}
|
|
1
|
+
{"version":3,"file":"adminChannel.js","sourceRoot":"","sources":["../../../src/utils/adminChannel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAErD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAEjF,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAElF,wEAAwE;AACxE,MAAM,CAAC,MAAM,gBAAgB,GAAG,kBAAkB,CAAC;AACnD,kDAAkD;AACl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G,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 uses on an app process it\n * started. Present only when the process was started with a shared secret in\n * `APP_ADMIN_SECRET` (see {@link resolveAdminSecret}); without it every route answers\n * 404, so a standalone app has no control channel. Every request carries the secret in\n * the `x-app-admin-secret` header (401 otherwise).\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 (each package's shape graph and the app's own,\n * skipped when unchanged), as the boot does, and answers 200 with\n * {@link ShapeSyncResult}, whose `shapeGraphs` reports the shape graphs. 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 * - `GET /admin/routes` → 200 {@link EffectiveRoutes}: the graph routes of every dataset the\n * router knows (shape IRI → graph IRI) and the shapes each one writes to its default graph,\n * as core's routing holds them once the app's storage file has run. The routes are written\n * only in the app's storage file; this route lets a host check what actually runs.\n */\nimport { createHash, timingSafeEqual } from 'crypto';\nimport type express from 'express';\nimport { invalidateGraphRegistry } from '@_linked/core/utils/graphRegistryCache';\nimport type { ShapeGraphsReport } from './syncShapes.js';\nimport { effectiveGraphRoutes, type EffectiveRoutes } from './effectiveRoutes.js';\n\n/** The environment variable that holds the control channel's secret. */\nexport const ADMIN_SECRET_ENV = 'APP_ADMIN_SECRET';\n/** The request header that carries the secret. */\nexport const ADMIN_SECRET_HEADER = 'x-app-admin-secret';\n\n/** The control channel's secret: `APP_ADMIN_SECRET`, else `undefined` (no control channel). */\nexport function resolveAdminSecret(\n env: Record<string, string | undefined> = process.env\n): string | undefined {\n return env[ADMIN_SECRET_ENV] || undefined;\n}\n\n/** What one shape sync did. */\nexport interface ShapeSyncResult {\n /**\n * Shape graphs written (package graphs and the app's own graph) because their stored hash\n * differed; on a store without graph queries, the default-graph sync's writes.\n */\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 shape graph sync: packages written and skipped, the graphs written, the app's own shape\n * graph, the registered packages without `shapes.ttl` (so without a shape graph) and the\n * default-graph shapes removed. Absent when no sync ran.\n */\n shapeGraphs?: ShapeGraphsReport;\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 /** The effective graph routes (see `GET /admin/routes`). Default: {@link effectiveGraphRoutes}. */\n routes?: () => EffectiveRoutes;\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/**\n * Compare the provided secret with the configured one in constant time. Both sides are hashed\n * first, so the comparison does not reveal the secret's length either.\n */\nexport function adminSecretMatches(\n secret: string | undefined,\n provided: string | undefined\n): boolean {\n if (!secret || !provided) return false;\n const digest = (value: string) => createHash('sha256').update(value).digest();\n return timingSafeEqual(digest(provided), digest(secret));\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(ADMIN_SECRET_HEADER))) {\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.get('/admin/routes', (req, res) => {\n if (!requireAdmin(req, res)) return;\n try {\n res.status(200).json((handlers.routes ?? effectiveGraphRoutes)());\n } catch (err) {\n res.status(500).json({ error: err instanceof Error ? err.message : String(err) });\n }\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"]}
|
|
@@ -16,11 +16,22 @@ export interface DatasetRoutes {
|
|
|
16
16
|
* default graph: no route of their own and no routed super-shape. Sorted.
|
|
17
17
|
*/
|
|
18
18
|
defaultGraphShapes: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Where the dataset keeps the packages' ontology data and shapes (core's graph targets:
|
|
21
|
+
* `'package'`, `'default'` or a shared graph IRI), when its store has them.
|
|
22
|
+
*/
|
|
23
|
+
ontologyGraph?: string;
|
|
24
|
+
shapeGraph?: string;
|
|
19
25
|
}
|
|
20
26
|
/** The body of `GET /admin/routes`. */
|
|
21
27
|
export interface EffectiveRoutes {
|
|
22
28
|
/** Every dataset the router knows, the default one first, then in the order they were pinned. */
|
|
23
29
|
datasets: DatasetRoutes[];
|
|
30
|
+
/**
|
|
31
|
+
* `LINKED_ONTOLOGY_GRAPH` / `LINKED_SHAPE_GRAPH` as the process has them (unset ones left out),
|
|
32
|
+
* so a host sees them also for stores that take no graph targets.
|
|
33
|
+
*/
|
|
34
|
+
graphTargetEnv: Record<string, string>;
|
|
24
35
|
}
|
|
25
36
|
/** The routes of every dataset the router knows (see {@link EffectiveRoutes}). */
|
|
26
|
-
export declare function effectiveGraphRoutes(): EffectiveRoutes;
|
|
37
|
+
export declare function effectiveGraphRoutes(env?: Record<string, string | undefined>): EffectiveRoutes;
|
|
@@ -8,8 +8,9 @@ import { LinkedStorage } from '@_linked/core/utils/LinkedStorage';
|
|
|
8
8
|
import { getShapeGraphs, graphRoutingFor } from '@_linked/core/utils/graphRouting';
|
|
9
9
|
import { getAllShapeClasses } from '@_linked/core/utils/ShapeClass';
|
|
10
10
|
import { graphs } from '@_linked/core/ontologies/graphs';
|
|
11
|
+
import { graphTargetEnv } from './graphTargets.js';
|
|
11
12
|
/** The routes of every dataset the router knows (see {@link EffectiveRoutes}). */
|
|
12
|
-
export function effectiveGraphRoutes() {
|
|
13
|
+
export function effectiveGraphRoutes(env = process.env) {
|
|
13
14
|
var _a, _b;
|
|
14
15
|
const datasets = [...LinkedStorage.getDatasets()];
|
|
15
16
|
const defaultDataset = LinkedStorage.getDefaultDataset();
|
|
@@ -27,14 +28,17 @@ export function effectiveGraphRoutes() {
|
|
|
27
28
|
datasets: datasets.map((dataset) => {
|
|
28
29
|
var _a, _b;
|
|
29
30
|
const id = dataset.id;
|
|
31
|
+
const targets = typeof (dataset === null || dataset === void 0 ? void 0 : dataset.graphTargets) === 'function' ? dataset.graphTargets() : undefined;
|
|
30
32
|
return {
|
|
31
33
|
store: ((_a = dataset === null || dataset === void 0 ? void 0 : dataset.constructor) === null || _a === void 0 ? void 0 : _a.name) || 'unknown',
|
|
32
34
|
...(typeof id === 'string' && id ? { id } : {}),
|
|
33
35
|
default: dataset === defaultDataset,
|
|
34
36
|
routes: getShapeGraphs(dataset),
|
|
35
37
|
defaultGraphShapes: ((_b = defaultGraphShapes.get(dataset)) !== null && _b !== void 0 ? _b : []).sort(),
|
|
38
|
+
...(targets ? { ontologyGraph: targets.ontologyGraph, shapeGraph: targets.shapeGraph } : {}),
|
|
36
39
|
};
|
|
37
40
|
}),
|
|
41
|
+
graphTargetEnv: graphTargetEnv(env),
|
|
38
42
|
};
|
|
39
43
|
}
|
|
40
44
|
//# sourceMappingURL=effectiveRoutes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effectiveRoutes.js","sourceRoot":"","sources":["../../../src/utils/effectiveRoutes.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"effectiveRoutes.js","sourceRoot":"","sources":["../../../src/utils/effectiveRoutes.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAuCnD,kFAAkF;AAClF,MAAM,UAAU,oBAAoB,CAAC,MAA0C,OAAO,CAAC,GAAG;;IACxF,MAAM,QAAQ,GAAG,CAAC,GAAG,aAAa,CAAC,WAAW,EAAE,CAAC,CAAC;IAClD,MAAM,cAAc,GAAG,aAAa,CAAC,iBAAiB,EAAE,CAAC;IACzD,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAqB,QAAQ,CAAC,GAAG,CAAC,CAAC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GAAG,CAAC,OAAO,CAAC,mCAAI,EAAE,CAAC,CAAC,IAAI,EAAE;gBAClE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC7F,CAAC;QACJ,CAAC,CAAC;QACF,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC;KACpC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The graph routes the process runs with, as core's routing holds them once the app's storage\n * file has run (`LinkedStorage.setDatasetForShapes(dataset, shapes, {graph})`, or `loadStores`\n * for a datasets config that still carries routes). Answered by `GET /admin/routes`, so a host\n * can compare what it wrote into the storage file with what actually runs.\n */\nimport { LinkedStorage } from '@_linked/core/utils/LinkedStorage';\nimport { getShapeGraphs, graphRoutingFor } from '@_linked/core/utils/graphRouting';\nimport { getAllShapeClasses } from '@_linked/core/utils/ShapeClass';\nimport { graphs } from '@_linked/core/ontologies/graphs';\nimport type { IDataset } from '@_linked/core/interfaces/IDataset';\nimport { graphTargetEnv } from './graphTargets.js';\n\n/** One dataset the router knows, and its graph routes. */\nexport interface DatasetRoutes {\n /**\n * The store's class name (`FusekiStore`, `RemoteDataset`, …). The server never sees the\n * aliases of the storage config, so a dataset is told apart by this, `default` and `id`.\n */\n store: string;\n /** The store's `id`, when it has one (a named `RemoteDataset` does). */\n id?: string;\n /** Whether this is the default dataset (the one for every shape without a pin). */\n default: boolean;\n /** The dataset's routes as registered: shape IRI → graph IRI. */\n routes: Record<string, string>;\n /**\n * The registered shapes that resolve to this dataset and whose instances are written to its\n * default graph: no route of their own and no routed super-shape. Sorted.\n */\n defaultGraphShapes: string[];\n /**\n * Where the dataset keeps the packages' ontology data and shapes (core's graph targets:\n * `'package'`, `'default'` or a shared graph IRI), when its store has them.\n */\n ontologyGraph?: string;\n shapeGraph?: string;\n}\n\n/** The body of `GET /admin/routes`. */\nexport interface EffectiveRoutes {\n /** Every dataset the router knows, the default one first, then in the order they were pinned. */\n datasets: DatasetRoutes[];\n /**\n * `LINKED_ONTOLOGY_GRAPH` / `LINKED_SHAPE_GRAPH` as the process has them (unset ones left out),\n * so a host sees them also for stores that take no graph targets.\n */\n graphTargetEnv: Record<string, string>;\n}\n\n/** The routes of every dataset the router knows (see {@link EffectiveRoutes}). */\nexport function effectiveGraphRoutes(env: Record<string, string | undefined> = process.env): EffectiveRoutes {\n const datasets = [...LinkedStorage.getDatasets()];\n const defaultDataset = LinkedStorage.getDefaultDataset();\n const defaultGraphShapes = new Map<IDataset, string[]>(datasets.map((ds) => [ds, []]));\n for (const [iri, shapeClass] of getAllShapeClasses()) {\n const dataset = LinkedStorage.getDatasetForShapeClass(shapeClass);\n const list = dataset && defaultGraphShapes.get(dataset);\n if (!list) continue;\n const graph = graphRoutingFor(dataset)?.graphForShape(iri) ?? graphs.default;\n if (graph === graphs.default) list.push(iri);\n }\n return {\n datasets: datasets.map((dataset) => {\n const id = (dataset as { id?: unknown }).id;\n const targets = typeof dataset?.graphTargets === 'function' ? dataset.graphTargets() : undefined;\n return {\n store: dataset?.constructor?.name || 'unknown',\n ...(typeof id === 'string' && id ? { id } : {}),\n default: dataset === defaultDataset,\n routes: getShapeGraphs(dataset),\n defaultGraphShapes: (defaultGraphShapes.get(dataset) ?? []).sort(),\n ...(targets ? { ontologyGraph: targets.ontologyGraph, shapeGraph: targets.shapeGraph } : {}),\n };\n }),\n graphTargetEnv: graphTargetEnv(env),\n };\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the stores keep the registered packages' ontology data and shapes: core's graph targets
|
|
3
|
+
* (`ontologyGraph`, `shapeGraph`; `@_linked/core/utils/graphTargets`), filled from the environment
|
|
4
|
+
* at boot. `LINKED_ONTOLOGY_GRAPH` and `LINKED_SHAPE_GRAPH` each take `'package'` (the default, one
|
|
5
|
+
* graph per package), `'default'` (the default graph) or the absolute IRI of one shared graph.
|
|
6
|
+
*
|
|
7
|
+
* The server reads them, checks them (an invalid value stops the boot, naming the variable), and
|
|
8
|
+
* sets them on every store registered in `LinkedStorage` at boot that takes graph targets, for
|
|
9
|
+
* what the store's own options leave unset. A store that takes none (`RemoteDataset`) runs `'package'`.
|
|
10
|
+
*/
|
|
11
|
+
import { type GraphTargets } from '@_linked/core/utils/graphTargets';
|
|
12
|
+
/**
|
|
13
|
+
* Read `LINKED_ONTOLOGY_GRAPH` / `LINKED_SHAPE_GRAPH` from `env` (checked: an invalid value throws,
|
|
14
|
+
* naming the variable) and fill every store in `stores` that takes graph targets with them, where
|
|
15
|
+
* its own options leave a setting unset. A store that takes none gets one warning when the env sets
|
|
16
|
+
* a mode other than `'package'` (it runs `'package'`). Returns the settings the env gave.
|
|
17
|
+
*/
|
|
18
|
+
export declare function applyGraphTargetsFromEnv(env: Record<string, string | undefined>, stores: Iterable<unknown>, warn?: (message: string) => void): Partial<GraphTargets>;
|
|
19
|
+
/** The env variables as set (unset and empty ones left out), for `GET /admin/routes`. */
|
|
20
|
+
export declare function graphTargetEnv(env: Record<string, string | undefined>): Record<string, string>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the stores keep the registered packages' ontology data and shapes: core's graph targets
|
|
3
|
+
* (`ontologyGraph`, `shapeGraph`; `@_linked/core/utils/graphTargets`), filled from the environment
|
|
4
|
+
* at boot. `LINKED_ONTOLOGY_GRAPH` and `LINKED_SHAPE_GRAPH` each take `'package'` (the default, one
|
|
5
|
+
* graph per package), `'default'` (the default graph) or the absolute IRI of one shared graph.
|
|
6
|
+
*
|
|
7
|
+
* The server reads them, checks them (an invalid value stops the boot, naming the variable), and
|
|
8
|
+
* sets them on every store registered in `LinkedStorage` at boot that takes graph targets, for
|
|
9
|
+
* what the store's own options leave unset. A store that takes none (`RemoteDataset`) runs `'package'`.
|
|
10
|
+
*/
|
|
11
|
+
import { GRAPH_TARGET_ENV, graphTargetOptionsFromEnv, } from '@_linked/core/utils/graphTargets';
|
|
12
|
+
/**
|
|
13
|
+
* Read `LINKED_ONTOLOGY_GRAPH` / `LINKED_SHAPE_GRAPH` from `env` (checked: an invalid value throws,
|
|
14
|
+
* naming the variable) and fill every store in `stores` that takes graph targets with them, where
|
|
15
|
+
* its own options leave a setting unset. A store that takes none gets one warning when the env sets
|
|
16
|
+
* a mode other than `'package'` (it runs `'package'`). Returns the settings the env gave.
|
|
17
|
+
*/
|
|
18
|
+
export function applyGraphTargetsFromEnv(env, stores, warn = console.warn) {
|
|
19
|
+
var _a, _b, _c, _d, _e;
|
|
20
|
+
const fromEnv = graphTargetOptionsFromEnv(env);
|
|
21
|
+
if (Object.keys(fromEnv).length === 0)
|
|
22
|
+
return fromEnv;
|
|
23
|
+
const nonDefault = Object.values(fromEnv).some((value) => value !== 'package');
|
|
24
|
+
for (const store of stores) {
|
|
25
|
+
const target = store;
|
|
26
|
+
if (typeof (target === null || target === void 0 ? void 0 : target.setGraphTargets) === 'function') {
|
|
27
|
+
try {
|
|
28
|
+
target.setGraphTargets(fromEnv, { onlyUnset: true });
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw new Error(`${GRAPH_TARGET_ENV.ontologyGraph} / ${GRAPH_TARGET_ENV.shapeGraph} do not fit ` +
|
|
32
|
+
`${(_b = (_a = target.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : 'a store'}'s own graph targets: ${(_c = error === null || error === void 0 ? void 0 : error.message) !== null && _c !== void 0 ? _c : error}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else if (nonDefault) {
|
|
36
|
+
warn(`[LinkedServer] ${(_e = (_d = target === null || target === void 0 ? void 0 : target.constructor) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : 'a store'} takes no graph targets, so it runs ` +
|
|
37
|
+
`'package' for the ontology and shape graphs whatever ${GRAPH_TARGET_ENV.ontologyGraph} / ` +
|
|
38
|
+
`${GRAPH_TARGET_ENV.shapeGraph} set.`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return fromEnv;
|
|
42
|
+
}
|
|
43
|
+
/** The env variables as set (unset and empty ones left out), for `GET /admin/routes`. */
|
|
44
|
+
export function graphTargetEnv(env) {
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const name of [GRAPH_TARGET_ENV.ontologyGraph, GRAPH_TARGET_ENV.shapeGraph]) {
|
|
47
|
+
const value = env[name];
|
|
48
|
+
if (value)
|
|
49
|
+
out[name] = value;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=graphTargets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graphTargets.js","sourceRoot":"","sources":["../../../src/utils/graphTargets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EACL,gBAAgB,EAChB,yBAAyB,GAE1B,MAAM,kCAAkC,CAAC;AAQ1C;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,GAAuC,EACvC,MAAyB,EACzB,OAAkC,OAAO,CAAC,IAAI;;IAE9C,MAAM,OAAO,GAAG,yBAAyB,CAAC,GAAG,CAAC,CAAC;IAC/C,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,OAAO,CAAC;IACtD,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC;IAC/E,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,MAAM,GAAG,KAAuC,CAAC;QACvD,IAAI,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,eAAe,CAAA,KAAK,UAAU,EAAE,CAAC;YAClD,IAAI,CAAC;gBACH,MAAM,CAAC,eAAe,CAAC,OAAO,EAAE,EAAC,SAAS,EAAE,IAAI,EAAC,CAAC,CAAC;YACrD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,KAAK,CACb,GAAG,gBAAgB,CAAC,aAAa,MAAM,gBAAgB,CAAC,UAAU,cAAc;oBAC9E,GAAG,MAAA,MAAA,MAAM,CAAC,WAAW,0CAAE,IAAI,mCAAI,SAAS,yBAAyB,MAAC,KAAe,aAAf,KAAK,uBAAL,KAAK,CAAY,OAAO,mCAAI,KAAK,EAAE,CACxG,CAAC;YACJ,CAAC;QACH,CAAC;aAAM,IAAI,UAAU,EAAE,CAAC;YACtB,IAAI,CACF,kBAAkB,MAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,WAAW,0CAAE,IAAI,mCAAI,SAAS,sCAAsC;gBAC5F,wDAAwD,gBAAgB,CAAC,aAAa,KAAK;gBAC3F,GAAG,gBAAgB,CAAC,UAAU,OAAO,CACxC,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,cAAc,CAAC,GAAuC;IACpE,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,CAAC,gBAAgB,CAAC,aAAa,EAAE,gBAAgB,CAAC,UAAU,CAAC,EAAE,CAAC;QACjF,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;QACxB,IAAI,KAAK;YAAE,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IAC/B,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Where the stores keep the registered packages' ontology data and shapes: core's graph targets\n * (`ontologyGraph`, `shapeGraph`; `@_linked/core/utils/graphTargets`), filled from the environment\n * at boot. `LINKED_ONTOLOGY_GRAPH` and `LINKED_SHAPE_GRAPH` each take `'package'` (the default, one\n * graph per package), `'default'` (the default graph) or the absolute IRI of one shared graph.\n *\n * The server reads them, checks them (an invalid value stops the boot, naming the variable), and\n * sets them on every store registered in `LinkedStorage` at boot that takes graph targets, for\n * what the store's own options leave unset. A store that takes none (`RemoteDataset`) runs `'package'`.\n */\nimport {\n GRAPH_TARGET_ENV,\n graphTargetOptionsFromEnv,\n type GraphTargets,\n} from '@_linked/core/utils/graphTargets';\n\n/** A store as this module sees it: one that may take graph targets. */\ntype TargetStore = {\n setGraphTargets?: (options: Partial<GraphTargets>, how?: {onlyUnset?: boolean}) => void;\n constructor?: {name?: string};\n};\n\n/**\n * Read `LINKED_ONTOLOGY_GRAPH` / `LINKED_SHAPE_GRAPH` from `env` (checked: an invalid value throws,\n * naming the variable) and fill every store in `stores` that takes graph targets with them, where\n * its own options leave a setting unset. A store that takes none gets one warning when the env sets\n * a mode other than `'package'` (it runs `'package'`). Returns the settings the env gave.\n */\nexport function applyGraphTargetsFromEnv(\n env: Record<string, string | undefined>,\n stores: Iterable<unknown>,\n warn: (message: string) => void = console.warn,\n): Partial<GraphTargets> {\n const fromEnv = graphTargetOptionsFromEnv(env);\n if (Object.keys(fromEnv).length === 0) return fromEnv;\n const nonDefault = Object.values(fromEnv).some((value) => value !== 'package');\n for (const store of stores) {\n const target = store as TargetStore | null | undefined;\n if (typeof target?.setGraphTargets === 'function') {\n try {\n target.setGraphTargets(fromEnv, {onlyUnset: true});\n } catch (error) {\n throw new Error(\n `${GRAPH_TARGET_ENV.ontologyGraph} / ${GRAPH_TARGET_ENV.shapeGraph} do not fit ` +\n `${target.constructor?.name ?? 'a store'}'s own graph targets: ${(error as Error)?.message ?? error}`,\n );\n }\n } else if (nonDefault) {\n warn(\n `[LinkedServer] ${target?.constructor?.name ?? 'a store'} takes no graph targets, so it runs ` +\n `'package' for the ontology and shape graphs whatever ${GRAPH_TARGET_ENV.ontologyGraph} / ` +\n `${GRAPH_TARGET_ENV.shapeGraph} set.`,\n );\n }\n }\n return fromEnv;\n}\n\n/** The env variables as set (unset and empty ones left out), for `GET /admin/routes`. */\nexport function graphTargetEnv(env: Record<string, string | undefined>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of [GRAPH_TARGET_ENV.ontologyGraph, GRAPH_TARGET_ENV.shapeGraph]) {\n const value = env[name];\n if (value) out[name] = value;\n }\n return out;\n}\n"]}
|
|
@@ -34,6 +34,8 @@ export interface OntologyCore {
|
|
|
34
34
|
written: string[];
|
|
35
35
|
skipped: string[];
|
|
36
36
|
pruned: string[];
|
|
37
|
+
target?: string;
|
|
38
|
+
fallback?: true;
|
|
37
39
|
}>;
|
|
38
40
|
checkShapeHierarchy(options: {
|
|
39
41
|
dependencies?: Record<string, string[]>;
|
|
@@ -136,6 +138,18 @@ export declare function runOntologyPhase(ds: unknown, { core, sync, orphanScope,
|
|
|
136
138
|
log?: (message: string) => void;
|
|
137
139
|
warn?: (message: string, err?: unknown) => void;
|
|
138
140
|
}): Promise<OntologyPhaseResult>;
|
|
141
|
+
/**
|
|
142
|
+
* The graphs a sync left written and those it left dropped, from its successful graph queries in
|
|
143
|
+
* order. A graph the run created and then dropped (the inference probe's temporary graphs) is in
|
|
144
|
+
* neither list.
|
|
145
|
+
*/
|
|
146
|
+
export declare function graphsWrittenAndDropped(ops: Array<{
|
|
147
|
+
kind: string;
|
|
148
|
+
graph: string;
|
|
149
|
+
}>): {
|
|
150
|
+
graphs: string[];
|
|
151
|
+
droppedGraphs: string[];
|
|
152
|
+
};
|
|
139
153
|
/**
|
|
140
154
|
* The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology
|
|
141
155
|
* phase failed. The ontology phase's failure is then thrown, so the route answers with it, as
|
|
@@ -80,21 +80,30 @@ export async function runOntologyPhase(ds, { core, sync, orphanScope, dependenci
|
|
|
80
80
|
}
|
|
81
81
|
let hierarchyLoaded = false;
|
|
82
82
|
if (sync && ds) {
|
|
83
|
-
|
|
84
|
-
const
|
|
83
|
+
// Every graph query that succeeded, in the order the sync sent them.
|
|
84
|
+
const ops = [];
|
|
85
85
|
const pending = [];
|
|
86
86
|
const stop = (_a = core.observeGraphQueries) === null || _a === void 0 ? void 0 : _a.call(core, ds, (query, settled) => {
|
|
87
|
-
|
|
87
|
+
const op = { kind: query.kind, graph: query.graph };
|
|
88
|
+
ops.push(op);
|
|
89
|
+
pending.push(settled.then(() => (op.ok = true), () => undefined));
|
|
88
90
|
});
|
|
89
91
|
try {
|
|
90
92
|
const sync = await core.syncOntologies(ds, { orphanScope });
|
|
91
93
|
await Promise.all(pending);
|
|
92
|
-
const graphs =
|
|
93
|
-
const droppedGraphs = [...dropped].sort();
|
|
94
|
+
const { graphs, droppedGraphs } = graphsWrittenAndDropped(ops.filter((op) => op.ok));
|
|
94
95
|
result.ontologies = { written: sync.written, skipped: sync.skipped, graphs, droppedGraphs };
|
|
95
96
|
hierarchyLoaded = true;
|
|
96
|
-
|
|
97
|
-
|
|
97
|
+
// Core ≥ 2.41 says where it wrote (the store's `ontologyGraph`); an older core is told
|
|
98
|
+
// apart by a write that sent no graph query.
|
|
99
|
+
const where = sync.target === 'default'
|
|
100
|
+
? " (default graph: ontologyGraph is 'default')"
|
|
101
|
+
: sync.fallback || (sync.target === undefined && !!stop && sync.written.length > 0 && graphs.length === 0)
|
|
102
|
+
? ' (default graph: the store has no graph queries)'
|
|
103
|
+
: sync.target && sync.target !== 'package'
|
|
104
|
+
? ` (one shared graph <${sync.target}>)`
|
|
105
|
+
: '';
|
|
106
|
+
log(`[LinkedServer] ontology sync${where}: ` +
|
|
98
107
|
`written ${list(sync.written)}; skipped ${list(sync.skipped)}` +
|
|
99
108
|
(orphanScope === 'all' ? `; pruned ${list(sync.pruned)}` : '') +
|
|
100
109
|
(graphs.length ? `; graphs written ${list(graphs)}` : '') +
|
|
@@ -130,6 +139,30 @@ export async function runOntologyPhase(ds, { core, sync, orphanScope, dependenci
|
|
|
130
139
|
}
|
|
131
140
|
return result;
|
|
132
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* The graphs a sync left written and those it left dropped, from its successful graph queries in
|
|
144
|
+
* order. A graph the run created and then dropped (the inference probe's temporary graphs) is in
|
|
145
|
+
* neither list.
|
|
146
|
+
*/
|
|
147
|
+
export function graphsWrittenAndDropped(ops) {
|
|
148
|
+
var _a;
|
|
149
|
+
const byGraph = new Map();
|
|
150
|
+
for (const { kind, graph } of ops) {
|
|
151
|
+
const kinds = (_a = byGraph.get(graph)) !== null && _a !== void 0 ? _a : [];
|
|
152
|
+
kinds.push(kind);
|
|
153
|
+
byGraph.set(graph, kinds);
|
|
154
|
+
}
|
|
155
|
+
const graphs = [];
|
|
156
|
+
const droppedGraphs = [];
|
|
157
|
+
for (const [graph, kinds] of byGraph) {
|
|
158
|
+
const last = kinds[kinds.length - 1];
|
|
159
|
+
if (last !== 'graph_drop')
|
|
160
|
+
graphs.push(graph);
|
|
161
|
+
else if (kinds[0] !== 'graph_create')
|
|
162
|
+
droppedGraphs.push(graph);
|
|
163
|
+
}
|
|
164
|
+
return { graphs: graphs.sort(), droppedGraphs: droppedGraphs.sort() };
|
|
165
|
+
}
|
|
133
166
|
/**
|
|
134
167
|
* The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology
|
|
135
168
|
* phase failed. The ontology phase's failure is then thrown, so the route answers with it, as
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ontologySync.js","sourceRoot":"","sources":["../../../src/utils/ontologySync.ts"],"names":[],"mappings":"AAwEA;;;;GAIG;AACH,MAAM,UAAU,WAAW,CACzB,GAAuC,EACvC,UAAmB;IAEnB,OAAO,UAAU,KAAK,KAAK,IAAI,GAAG,CAAC,0BAA0B,KAAK,OAAO,CAAC;AAC5E,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CACjC,GAAuC,EACvC,UAAoB;IAEpB,OAAO,WAAW,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,GAAG,CAAC,8BAA8B,KAAK,OAAO,CAAC;AACxF,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,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boot and\n * when the host asks for a re-sync (`POST /admin/sync-shapes`).\n *\n * - The ontology sync (core `syncOntologies`) writes each registered package's ontology data into\n * its own named graph of the app's default dataset (`{package IRI}/graph/ontology`, with a\n * record in the graph registry that marks it as a hierarchy source), skipping a package whose\n * stored hash matches, so the store's RDFS view infers the class hierarchy. A store without\n * graph queries (it answers `unsupported-query-kind`, or has no `graphQuery`) gets core's\n * earlier sync of the `rdfs:subClassOf` triples into the default graph instead. The graphs the\n * sync wrote or dropped are observed on core's query dispatch and reported by name.\n * - The shape check (core `checkShapeHierarchy`) compares the registered shapes with that\n * hierarchy. A running app is never stopped by it: its findings are logged and counted.\n * - The in-memory class hierarchy (core `loadOntologyHierarchy`) is loaded also when the sync\n * is off; the sync loads it itself when it runs.\n * - Before either, every linked package directory the server discovered registers its ontologies\n * (core `registerInstalledOntologies`): a package the app only deep-imports shape files from\n * never evaluates its register modules, so its data would be missing from both. A source\n * package without built register modules (a workspace package in dev) registers through\n * `importModule` (Vite's `ssrLoadModule`), when the caller passes one.\n *\n * The four core modules (`ontology/syncOntologies`, `shapes/checkShapeHierarchy`,\n * `ontology/hierarchy`, `ontology/registerInstalled`) are server only and not in core's index, so\n * {@link loadOntologyCore} imports them by their fixed subpaths when the phase runs; the core\n * this server depends on has all of them. Kept apart from `LinkedServer` so the order and the failure handling can be tested without\n * booting a server.\n */\nimport type {BootOrphanScope} from './syncShapes.js';\n\n/** The subset of core's ontology and shape-check API this module calls. */\nexport interface OntologyCore {\n syncOntologies(\n ds: unknown,\n options: {orphanScope: BootOrphanScope},\n ): Promise<{written: string[]; skipped: string[]; pruned: string[]}>;\n checkShapeHierarchy(options: {dependencies?: Record<string, string[]>}): Promise<\n Array<{kind: string; severity: 'error' | 'warning'; shape?: string; iri?: string; message: string}>\n >;\n /** Loads the in-memory class hierarchy. Optional so a test double can leave it out. */\n loadOntologyHierarchy?: () => Promise<unknown>;\n /**\n * Calls `onGraph` for every graph query on `ds` that succeeds until the returned function is\n * called (core's `subscribeQueryDispatch`). Optional so a test double can leave it out.\n */\n observeGraphQueries?: (\n ds: unknown,\n onGraph: (query: {kind: string; graph: string}, settled: Promise<unknown>) => void,\n ) => () => void;\n /**\n * Registers the ontologies of the installed packages in the given directories. Optional so a\n * test double can leave it out.\n */\n registerInstalledOntologies?: (\n packageDirs: string[],\n options?: {importModule?: (file: string) => Promise<unknown>},\n ) => Promise<string[]>;\n}\n\n/** What the ontology sync and the shape check did, as `POST /admin/sync-shapes` reports it. */\nexport interface OntologyPhaseResult {\n /**\n * Packages whose ontology graph (or, on a store without graph queries, hierarchy) was written,\n * packages left as they were (unchanged or unreadable), and the graphs the sync wrote and\n * dropped (empty on a store without graph queries).\n */\n ontologies: {written: string[]; skipped: string[]; graphs?: string[]; droppedGraphs?: string[]};\n /** The shape check's findings, counted by severity. */\n shapeCheck: {errors: number; warnings: number};\n /** The first error the sync or the check threw; the phase went on without it. */\n failure?: Error;\n}\n\n/**\n * Whether the server syncs shapes (and so ontologies) into its app data: off when `linked.config`\n * sets `syncShapesOnBoot: false` or the environment sets `LINKED_SYNC_SHAPES_ON_BOOT=false`. One\n * switch for both syncs, at boot and on the host's request.\n */\nexport function shapeSyncOn(\n env: Record<string, string | undefined>,\n configFlag: unknown,\n): boolean {\n return configFlag !== false && env.LINKED_SYNC_SHAPES_ON_BOOT !== 'false';\n}\n\n/**\n * Whether the boot syncs ontologies: when shape sync is on ({@link shapeSyncOn}) and the\n * environment does not opt out with `LINKED_SYNC_ONTOLOGIES_ON_BOOT=false`.\n */\nexport function bootSyncsOntologies(\n env: Record<string, string | undefined>,\n configFlag?: unknown,\n): boolean {\n return shapeSyncOn(env, configFlag) && env.LINKED_SYNC_ONTOLOGIES_ON_BOOT !== 'false';\n}\n\n/**\n * Import core's ontology sync, shape check, hierarchy loader and installed packages'\n * registration.\n */\nexport async function loadOntologyCore(): Promise<OntologyCore> {\n const sync = await import('@_linked/core/ontology/syncOntologies');\n const check = await import('@_linked/core/shapes/checkShapeHierarchy');\n const hierarchy = await import('@_linked/core/ontology/hierarchy');\n const registerInstalled = await import('@_linked/core/ontology/registerInstalled');\n const dispatch = await import('@_linked/core/queries/queryDispatch');\n return {\n syncOntologies: (ds, options) =>\n sync.syncOntologies(ds as Parameters<typeof sync.syncOntologies>[0], options),\n checkShapeHierarchy: (options) => check.checkShapeHierarchy(options),\n loadOntologyHierarchy: () => hierarchy.loadOntologyHierarchy(),\n registerInstalledOntologies: (packageDirs, options) =>\n registerInstalled.registerInstalledOntologies(packageDirs, options),\n observeGraphQueries: (ds, onGraph) =>\n dispatch.subscribeQueryDispatch((event) => {\n if (event.kind === 'graph' && event.target === ds) onGraph(event.query, event.result);\n }),\n };\n}\n\n/**\n * The package directories whose ontologies register before the sync: every linked package\n * discovered in the app's dependency tree, then the app's own workspace packages (an ontology\n * package in `packages/` that no package imports is one, so the dependency walk never reaches it).\n * Order kept, duplicates dropped.\n */\nexport function ontologyPackageDirs(\n linkedPackageDirs: Iterable<string>,\n workspacePackageDirs: Iterable<string>,\n): string[] {\n return [...new Set([...linkedPackageDirs, ...workspacePackageDirs])];\n}\n\n/**\n * In dev, the loader for source register modules: Vite's `ssrLoadModule`, so a workspace package\n * that was never built registers on the core the SSR graph uses. Undefined without Vite (a built\n * app), where source packages are skipped.\n */\nexport function sourceModuleImporter(\n vite: {ssrLoadModule?: (url: string) => Promise<unknown>} | undefined | null,\n): ((file: string) => Promise<unknown>) | undefined {\n const ssrLoadModule = vite?.ssrLoadModule;\n return typeof ssrLoadModule === 'function' ? (file) => ssrLoadModule.call(vite, file) : undefined;\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));\nconst list = (names: string[]) => (names.length ? names.join(', ') : 'none');\n\n/**\n * Register the ontologies of the installed linked packages in `packageDirs` (package roots), sync\n * the registered ontologies into `ds` (when `sync` is set and there is a dataset), then run the\n * shape check. Never throws: a failed registration is logged and the phase goes on; a failed sync is logged and returned as `failure`, and the\n * check still runs; a failed check likewise. Logs one line for the sync, one summary line for\n * the check and one line per finding.\n */\nexport async function runOntologyPhase(\n ds: unknown,\n {\n core,\n sync,\n orphanScope,\n dependencies,\n packageDirs = [],\n importModule,\n log = console.log,\n warn = console.warn,\n }: {\n core: OntologyCore;\n sync: boolean;\n orphanScope: BootOrphanScope;\n dependencies?: Record<string, string[]>;\n /** Every linked package directory the server discovered (transitively). */\n packageDirs?: string[];\n /**\n * Imports a source register module (`src/ontologies/*.register.ts`) of a package directory\n * without built ones; in dev, Vite's `ssrLoadModule`.\n */\n importModule?: (file: string) => Promise<unknown>;\n log?: (message: string) => void;\n warn?: (message: string, err?: unknown) => void;\n },\n): Promise<OntologyPhaseResult> {\n const result: OntologyPhaseResult = {\n ontologies: {written: [], skipped: [], graphs: [], droppedGraphs: []},\n shapeCheck: {errors: 0, warnings: 0},\n };\n\n if (core.registerInstalledOntologies && packageDirs.length) {\n try {\n if (importModule) await core.registerInstalledOntologies(packageDirs, {importModule});\n else await core.registerInstalledOntologies(packageDirs);\n } catch (err) {\n warn(\"[LinkedServer] registering the installed packages' ontologies failed:\", err);\n }\n }\n\n let hierarchyLoaded = false;\n if (sync && ds) {\n const written = new Set<string>();\n const dropped = new Set<string>();\n const pending: Promise<unknown>[] = [];\n const stop = core.observeGraphQueries?.(ds, (query, settled) => {\n pending.push(\n settled.then(\n () => (query.kind === 'graph_drop' ? dropped : written).add(query.graph),\n () => undefined,\n ),\n );\n });\n try {\n const sync = await core.syncOntologies(ds, {orphanScope});\n await Promise.all(pending);\n const graphs = [...written].sort();\n const droppedGraphs = [...dropped].sort();\n result.ontologies = {written: sync.written, skipped: sync.skipped, graphs, droppedGraphs};\n hierarchyLoaded = true;\n const defaultGraph = !!stop && sync.written.length > 0 && graphs.length === 0;\n log(\n `[LinkedServer] ontology sync${defaultGraph ? ' (default graph: the store has no graph queries)' : ''}: ` +\n `written ${list(sync.written)}; skipped ${list(sync.skipped)}` +\n (orphanScope === 'all' ? `; pruned ${list(sync.pruned)}` : '') +\n (graphs.length ? `; graphs written ${list(graphs)}` : '') +\n (droppedGraphs.length ? `; graphs dropped ${list(droppedGraphs)}` : ''),\n );\n } catch (err) {\n result.failure = asError(err);\n warn('[LinkedServer] ontology sync failed:', err);\n } finally {\n stop?.();\n }\n }\n if (!hierarchyLoaded && core.loadOntologyHierarchy) {\n try {\n await core.loadOntologyHierarchy();\n } catch (err) {\n warn('[LinkedServer] loading the class hierarchy failed:', err);\n }\n }\n\n try {\n const findings = await core.checkShapeHierarchy({dependencies});\n const errors = findings.filter((f) => f.severity === 'error').length;\n result.shapeCheck = {errors, warnings: findings.length - errors};\n log(`[LinkedServer] shape check: ${errors} error(s), ${findings.length - errors} warning(s)`);\n for (const f of findings) warn(`[LinkedServer] shape check ${f.severity} (${f.kind}): ${f.message}`);\n } catch (err) {\n result.failure ??= asError(err);\n warn('[LinkedServer] shape check failed:', err);\n }\n return result;\n}\n\n/**\n * The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology\n * phase failed. The ontology phase's failure is then thrown, so the route answers with it, as\n * it does for a failed shape sync.\n */\nexport async function syncOntologiesThenShapes<T extends object>(\n ontologyPhase: () => Promise<OntologyPhaseResult>,\n shapeSync: () => Promise<T>,\n): Promise<T & Pick<OntologyPhaseResult, 'ontologies' | 'shapeCheck'>> {\n const {ontologies, shapeCheck, failure} = await ontologyPhase();\n const shapes = await shapeSync();\n if (failure) throw failure;\n return {...shapes, ontologies, shapeCheck};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ontologySync.js","sourceRoot":"","sources":["../../../src/utils/ontologySync.ts"],"names":[],"mappings":"AAwEA;;;;GAIG;AACH,MAAM,UAAU,WAAW,CACzB,GAAuC,EACvC,UAAmB;IAEnB,OAAO,UAAU,KAAK,KAAK,IAAI,GAAG,CAAC,0BAA0B,KAAK,OAAO,CAAC;AAC5E,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CACjC,GAAuC,EACvC,UAAoB;IAEpB,OAAO,WAAW,CAAC,GAAG,EAAE,UA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AC,GAAG,MAAM,EAAE,UAAU,EAAE,UAAU,EAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Ontology sync and the shape check, as the server runs them before its shape sync: at boot and\n * when the host asks for a re-sync (`POST /admin/sync-shapes`).\n *\n * - The ontology sync (core `syncOntologies`) writes each registered package's ontology data into\n * its own named graph of the app's default dataset (`{package IRI}/graph/ontology`, with a\n * record in the graph registry that marks it as a hierarchy source), skipping a package whose\n * stored hash matches, so the store's RDFS view infers the class hierarchy. A store without\n * graph queries (it answers `unsupported-query-kind`, or has no `graphQuery`) gets core's\n * earlier sync of the `rdfs:subClassOf` triples into the default graph instead. The graphs the\n * sync wrote or dropped are observed on core's query dispatch and reported by name.\n * - The shape check (core `checkShapeHierarchy`) compares the registered shapes with that\n * hierarchy. A running app is never stopped by it: its findings are logged and counted.\n * - The in-memory class hierarchy (core `loadOntologyHierarchy`) is loaded also when the sync\n * is off; the sync loads it itself when it runs.\n * - Before either, every linked package directory the server discovered registers its ontologies\n * (core `registerInstalledOntologies`): a package the app only deep-imports shape files from\n * never evaluates its register modules, so its data would be missing from both. A source\n * package without built register modules (a workspace package in dev) registers through\n * `importModule` (Vite's `ssrLoadModule`), when the caller passes one.\n *\n * The four core modules (`ontology/syncOntologies`, `shapes/checkShapeHierarchy`,\n * `ontology/hierarchy`, `ontology/registerInstalled`) are server only and not in core's index, so\n * {@link loadOntologyCore} imports them by their fixed subpaths when the phase runs; the core\n * this server depends on has all of them. Kept apart from `LinkedServer` so the order and the failure handling can be tested without\n * booting a server.\n */\nimport type {BootOrphanScope} from './syncShapes.js';\n\n/** The subset of core's ontology and shape-check API this module calls. */\nexport interface OntologyCore {\n syncOntologies(\n ds: unknown,\n options: {orphanScope: BootOrphanScope},\n ): Promise<{written: string[]; skipped: string[]; pruned: string[]; target?: string; fallback?: true}>;\n checkShapeHierarchy(options: {dependencies?: Record<string, string[]>}): Promise<\n Array<{kind: string; severity: 'error' | 'warning'; shape?: string; iri?: string; message: string}>\n >;\n /** Loads the in-memory class hierarchy. Optional so a test double can leave it out. */\n loadOntologyHierarchy?: () => Promise<unknown>;\n /**\n * Calls `onGraph` for every graph query on `ds` that succeeds until the returned function is\n * called (core's `subscribeQueryDispatch`). Optional so a test double can leave it out.\n */\n observeGraphQueries?: (\n ds: unknown,\n onGraph: (query: {kind: string; graph: string}, settled: Promise<unknown>) => void,\n ) => () => void;\n /**\n * Registers the ontologies of the installed packages in the given directories. Optional so a\n * test double can leave it out.\n */\n registerInstalledOntologies?: (\n packageDirs: string[],\n options?: {importModule?: (file: string) => Promise<unknown>},\n ) => Promise<string[]>;\n}\n\n/** What the ontology sync and the shape check did, as `POST /admin/sync-shapes` reports it. */\nexport interface OntologyPhaseResult {\n /**\n * Packages whose ontology graph (or, on a store without graph queries, hierarchy) was written,\n * packages left as they were (unchanged or unreadable), and the graphs the sync wrote and\n * dropped (empty on a store without graph queries).\n */\n ontologies: {written: string[]; skipped: string[]; graphs?: string[]; droppedGraphs?: string[]};\n /** The shape check's findings, counted by severity. */\n shapeCheck: {errors: number; warnings: number};\n /** The first error the sync or the check threw; the phase went on without it. */\n failure?: Error;\n}\n\n/**\n * Whether the server syncs shapes (and so ontologies) into its app data: off when `linked.config`\n * sets `syncShapesOnBoot: false` or the environment sets `LINKED_SYNC_SHAPES_ON_BOOT=false`. One\n * switch for both syncs, at boot and on the host's request.\n */\nexport function shapeSyncOn(\n env: Record<string, string | undefined>,\n configFlag: unknown,\n): boolean {\n return configFlag !== false && env.LINKED_SYNC_SHAPES_ON_BOOT !== 'false';\n}\n\n/**\n * Whether the boot syncs ontologies: when shape sync is on ({@link shapeSyncOn}) and the\n * environment does not opt out with `LINKED_SYNC_ONTOLOGIES_ON_BOOT=false`.\n */\nexport function bootSyncsOntologies(\n env: Record<string, string | undefined>,\n configFlag?: unknown,\n): boolean {\n return shapeSyncOn(env, configFlag) && env.LINKED_SYNC_ONTOLOGIES_ON_BOOT !== 'false';\n}\n\n/**\n * Import core's ontology sync, shape check, hierarchy loader and installed packages'\n * registration.\n */\nexport async function loadOntologyCore(): Promise<OntologyCore> {\n const sync = await import('@_linked/core/ontology/syncOntologies');\n const check = await import('@_linked/core/shapes/checkShapeHierarchy');\n const hierarchy = await import('@_linked/core/ontology/hierarchy');\n const registerInstalled = await import('@_linked/core/ontology/registerInstalled');\n const dispatch = await import('@_linked/core/queries/queryDispatch');\n return {\n syncOntologies: (ds, options) =>\n sync.syncOntologies(ds as Parameters<typeof sync.syncOntologies>[0], options),\n checkShapeHierarchy: (options) => check.checkShapeHierarchy(options),\n loadOntologyHierarchy: () => hierarchy.loadOntologyHierarchy(),\n registerInstalledOntologies: (packageDirs, options) =>\n registerInstalled.registerInstalledOntologies(packageDirs, options),\n observeGraphQueries: (ds, onGraph) =>\n dispatch.subscribeQueryDispatch((event) => {\n if (event.kind === 'graph' && event.target === ds) onGraph(event.query, event.result);\n }),\n };\n}\n\n/**\n * The package directories whose ontologies register before the sync: every linked package\n * discovered in the app's dependency tree, then the app's own workspace packages (an ontology\n * package in `packages/` that no package imports is one, so the dependency walk never reaches it).\n * Order kept, duplicates dropped.\n */\nexport function ontologyPackageDirs(\n linkedPackageDirs: Iterable<string>,\n workspacePackageDirs: Iterable<string>,\n): string[] {\n return [...new Set([...linkedPackageDirs, ...workspacePackageDirs])];\n}\n\n/**\n * In dev, the loader for source register modules: Vite's `ssrLoadModule`, so a workspace package\n * that was never built registers on the core the SSR graph uses. Undefined without Vite (a built\n * app), where source packages are skipped.\n */\nexport function sourceModuleImporter(\n vite: {ssrLoadModule?: (url: string) => Promise<unknown>} | undefined | null,\n): ((file: string) => Promise<unknown>) | undefined {\n const ssrLoadModule = vite?.ssrLoadModule;\n return typeof ssrLoadModule === 'function' ? (file) => ssrLoadModule.call(vite, file) : undefined;\n}\n\nconst asError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));\nconst list = (names: string[]) => (names.length ? names.join(', ') : 'none');\n\n/**\n * Register the ontologies of the installed linked packages in `packageDirs` (package roots), sync\n * the registered ontologies into `ds` (when `sync` is set and there is a dataset), then run the\n * shape check. Never throws: a failed registration is logged and the phase goes on; a failed sync is logged and returned as `failure`, and the\n * check still runs; a failed check likewise. Logs one line for the sync, one summary line for\n * the check and one line per finding.\n */\nexport async function runOntologyPhase(\n ds: unknown,\n {\n core,\n sync,\n orphanScope,\n dependencies,\n packageDirs = [],\n importModule,\n log = console.log,\n warn = console.warn,\n }: {\n core: OntologyCore;\n sync: boolean;\n orphanScope: BootOrphanScope;\n dependencies?: Record<string, string[]>;\n /** Every linked package directory the server discovered (transitively). */\n packageDirs?: string[];\n /**\n * Imports a source register module (`src/ontologies/*.register.ts`) of a package directory\n * without built ones; in dev, Vite's `ssrLoadModule`.\n */\n importModule?: (file: string) => Promise<unknown>;\n log?: (message: string) => void;\n warn?: (message: string, err?: unknown) => void;\n },\n): Promise<OntologyPhaseResult> {\n const result: OntologyPhaseResult = {\n ontologies: {written: [], skipped: [], graphs: [], droppedGraphs: []},\n shapeCheck: {errors: 0, warnings: 0},\n };\n\n if (core.registerInstalledOntologies && packageDirs.length) {\n try {\n if (importModule) await core.registerInstalledOntologies(packageDirs, {importModule});\n else await core.registerInstalledOntologies(packageDirs);\n } catch (err) {\n warn(\"[LinkedServer] registering the installed packages' ontologies failed:\", err);\n }\n }\n\n let hierarchyLoaded = false;\n if (sync && ds) {\n // Every graph query that succeeded, in the order the sync sent them.\n const ops: Array<{kind: string; graph: string; ok?: boolean}> = [];\n const pending: Promise<unknown>[] = [];\n const stop = core.observeGraphQueries?.(ds, (query, settled) => {\n const op: {kind: string; graph: string; ok?: boolean} = {kind: query.kind, graph: query.graph};\n ops.push(op);\n pending.push(\n settled.then(\n () => (op.ok = true),\n () => undefined,\n ),\n );\n });\n try {\n const sync = await core.syncOntologies(ds, {orphanScope});\n await Promise.all(pending);\n const {graphs, droppedGraphs} = graphsWrittenAndDropped(ops.filter((op) => op.ok));\n result.ontologies = {written: sync.written, skipped: sync.skipped, graphs, droppedGraphs};\n hierarchyLoaded = true;\n // Core ≥ 2.41 says where it wrote (the store's `ontologyGraph`); an older core is told\n // apart by a write that sent no graph query.\n const where =\n sync.target === 'default'\n ? \" (default graph: ontologyGraph is 'default')\"\n : sync.fallback || (sync.target === undefined && !!stop && sync.written.length > 0 && graphs.length === 0)\n ? ' (default graph: the store has no graph queries)'\n : sync.target && sync.target !== 'package'\n ? ` (one shared graph <${sync.target}>)`\n : '';\n log(\n `[LinkedServer] ontology sync${where}: ` +\n `written ${list(sync.written)}; skipped ${list(sync.skipped)}` +\n (orphanScope === 'all' ? `; pruned ${list(sync.pruned)}` : '') +\n (graphs.length ? `; graphs written ${list(graphs)}` : '') +\n (droppedGraphs.length ? `; graphs dropped ${list(droppedGraphs)}` : ''),\n );\n } catch (err) {\n result.failure = asError(err);\n warn('[LinkedServer] ontology sync failed:', err);\n } finally {\n stop?.();\n }\n }\n if (!hierarchyLoaded && core.loadOntologyHierarchy) {\n try {\n await core.loadOntologyHierarchy();\n } catch (err) {\n warn('[LinkedServer] loading the class hierarchy failed:', err);\n }\n }\n\n try {\n const findings = await core.checkShapeHierarchy({dependencies});\n const errors = findings.filter((f) => f.severity === 'error').length;\n result.shapeCheck = {errors, warnings: findings.length - errors};\n log(`[LinkedServer] shape check: ${errors} error(s), ${findings.length - errors} warning(s)`);\n for (const f of findings) warn(`[LinkedServer] shape check ${f.severity} (${f.kind}): ${f.message}`);\n } catch (err) {\n result.failure ??= asError(err);\n warn('[LinkedServer] shape check failed:', err);\n }\n return result;\n}\n\n/**\n * The graphs a sync left written and those it left dropped, from its successful graph queries in\n * order. A graph the run created and then dropped (the inference probe's temporary graphs) is in\n * neither list.\n */\nexport function graphsWrittenAndDropped(ops: Array<{kind: string; graph: string}>): {\n graphs: string[];\n droppedGraphs: string[];\n} {\n const byGraph = new Map<string, string[]>();\n for (const {kind, graph} of ops) {\n const kinds = byGraph.get(graph) ?? [];\n kinds.push(kind);\n byGraph.set(graph, kinds);\n }\n const graphs: string[] = [];\n const droppedGraphs: string[] = [];\n for (const [graph, kinds] of byGraph) {\n const last = kinds[kinds.length - 1];\n if (last !== 'graph_drop') graphs.push(graph);\n else if (kinds[0] !== 'graph_create') droppedGraphs.push(graph);\n }\n return {graphs: graphs.sort(), droppedGraphs: droppedGraphs.sort()};\n}\n\n/**\n * The host's re-sync: the ontology phase, then the shape sync, which runs also when the ontology\n * phase failed. The ontology phase's failure is then thrown, so the route answers with it, as\n * it does for a failed shape sync.\n */\nexport async function syncOntologiesThenShapes<T extends object>(\n ontologyPhase: () => Promise<OntologyPhaseResult>,\n shapeSync: () => Promise<T>,\n): Promise<T & Pick<OntologyPhaseResult, 'ontologies' | 'shapeCheck'>> {\n const {ontologies, shapeCheck, failure} = await ontologyPhase();\n const shapes = await shapeSync();\n if (failure) throw failure;\n return {...shapes, ontologies, shapeCheck};\n}\n"]}
|
|
@@ -20,6 +20,10 @@ export interface ShapeGraphSyncResult {
|
|
|
20
20
|
cleaned: number;
|
|
21
21
|
appGraph?: 'written' | 'skipped' | 'dropped';
|
|
22
22
|
defaultGraph?: number;
|
|
23
|
+
/** The store's `shapeGraph` target the run wrote in (core ≥ 2.41): `'package'`, `'default'` or an IRI. */
|
|
24
|
+
target?: string;
|
|
25
|
+
/** Set when a store without graph queries took the default-graph sync instead of `target`. */
|
|
26
|
+
fallback?: true;
|
|
23
27
|
}
|
|
24
28
|
/** The subset of core's shape graph API this module calls. */
|
|
25
29
|
export interface ShapeGraphCore {
|
|
@@ -100,8 +104,15 @@ export interface ShapeGraphsReport {
|
|
|
100
104
|
withoutTurtle: string[];
|
|
101
105
|
/** Shapes an earlier sync had written into the default graph, removed now. */
|
|
102
106
|
cleaned: number;
|
|
103
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* Set when the shapes went into the default graph (the store's `shapeGraph` is `'default'`, or
|
|
109
|
+
* it has no graph queries): the default-graph sync's writes.
|
|
110
|
+
*/
|
|
104
111
|
defaultGraph?: number;
|
|
112
|
+
/** The store's `shapeGraph` target (`'package'`, `'default'` or a shared graph IRI), when core reports it. */
|
|
113
|
+
target?: string;
|
|
114
|
+
/** Set when the store has no graph queries, so the shapes went into the default graph instead of `target`. */
|
|
115
|
+
fallback?: true;
|
|
105
116
|
}
|
|
106
117
|
/**
|
|
107
118
|
* Sync the registered shapes into `ds`, one shape graph per package (see the module doc), and log
|