diff --git a/CHANGELOG.md b/CHANGELOG.md index bbda88d0f..5eaa18e55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,15 +13,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- tx: the `generalizes` filter on a code system resource (the code and its ancestors) - tx: `vsacCfg.enabled: false` - a server whose library names VSAC (`internal:vsac`) doesn't load it, and needs no API key: a library such as tx.fhir.org.yml can be used by a server without a VSAC account. Before, the server wouldn't start ### Changed +- tx: the `cache-id` parameter is refused, wherever it is (a parameter, a part, a `$batch-validate-code` validation entry, the query): a 400 (`TX_PARAM_CACHE_ID_WITHDRAWN`) that says to start a cache with `$cache-control` and send its id in the `X-Cache-Id` header. The tx-ecosystem IG withdrew it (servers SHOULD NOT accept it); `$batch-validate-code` ignored it, so a bad cache-id went unnoticed. Clients from before June 2026 that send it already got 404 cache-id-unknown, as the server issues the ids +- tx: a media type (`urn:ietf:bcp:13`) is valid only if it follows the grammar of RFC 9110 section 8.3.1 / RFC 2045: a parameter with no name or no value, an unclosed quoted string, a value that isn't a token or a quoted string (an unquoted URI, say), and whitespace around the `/` or `=` or at the ends are invalid, and the issue says where (`MIMETYPE_INVALID`). A `;` in a quoted value is part of the value (it split the parameter, and broke the normal form) +- tx: `$subsumes` on a code system whose `hierarchyMeaning` is not is-a (part-of, grouped-by, classified-with) is refused (422, `SUBSUMPTION_CS_HIERARCHY_MEANING`), as core's: its hierarchy doesn't describe subsumption. `$closure` finds no subsumption in it +- tx: a display for a code with no display, only other designations (a synonym), that is none of them: the message says there is no known display, and names the designations (`NO_KNOWN_DISPLAY`), on every path. It was a warning with a garbled message ("one of 0 choices: ") +- tx: SNOMED CT ECL: an exclusion has one expression on each side, so `A MINUS B MINUS C` needs brackets (it was accepted); `<<125605004.363698007` (a dotted attribute with no spaces) is accepted - a number with a decimal point is only read as one after `#` - tx: `check-system-version` never influences which version of a code system is used (community decision on Zulip, Terminology Service Test Cases, check-system-version semantics): the version is chosen as if it weren't there - from the coding, the value set, `system-version`/`force-system-version`, or the default - and the operation fails (`VALUESET_VERSION_CHECK`) if that version doesn't match. Before, when nothing else named a version, the check's version was used. This includes the edition of an implicit SNOMED CT value set, and `$closure` tables. It is no longer echoed in expansion parameters. `check-valueset-version` is unchanged - tx-import: the sqlite-v2 importers (`loinc-v2`, `loinc-v2-classic`, `snomed-v2`, `snomed-v2-from-cache`, `rxnorm-v2`) take the classic importers' options: `-v, --version` for the release's version (`snomed-v2`'s was `--snomed-version`) and `-y, --yes` to replace an existing destination; without `-y` an existing destination is asked about. The earlier names (`--loinc-version`, `--rxnorm-version`, `--snomed-version`, `--overwrite`) still work. Documented in tx/importers/readme.md ### Fixed +- tx: a parameter whose value isn't what its value[x] says (`valueInteger: "x"`), or a known parameter with a value of the wrong kind (a `url` as a valueInteger), is a 400 (`TX_PARAM_INVALID_VALUE`, `TX_PARAM_WRONG_TYPE`), in the body or the query; it crashed, or echoed the invalid content back +- tx: a `system-version` (etc.) rule that isn't url|version is a 400 that says so (`TX_PARAM_VERSION_RULE_INVALID`) +- tx: `$expand` gave valueset-unclosed (0..1) and its reason once for each include that made the expansion unclosed (two includes of a fragment, say); now once, with the reasons together +- tx: SNOMED CT ECL `R 116680003 |Is a| = X` (reversed is-a: X's parents) matched nothing; is-a is an attribute in either direction. In sqlite-v2 files, a wildcard attribute (`* : * = X`) and `<< 246061005` include is-a, as in cs-snomed.js +- tx: SNOMED CT: a single concept written as an expression (`64572001 |Disease|`, `===64572001`) had no normal form (no `normalized-code`); it is the concept id. `<<<` (a subtype of) is kept in the normal form, of a simple expression and of a refined one (it was dropped) +- tx: SNOMED CT `$lookup` of a post-coordinated expression gave the refinement's attributes as properties when other properties were asked for; now only when they are asked for, or no property is +- tx: a designation whose use is `designation-usage#display` is a display: it is among the valid displays a wrong display is told about +- tx: a code that isn't in a fragment code system with no version said version 'null' (`UNKNOWN_CODE_IN_FRAGMENT_NO_VERSION`) +- tx: UCUM's unit `1`: a wrong display listed '1' (en) twice +- tx: a code system version that is known but can't be used for codes (content example or not-present) was listed among the valid versions when it was the one asked for; it is still listed, and says so (`CODESYSTEM_VERSION_NOT_USABLE`) +- tx: `$expand` with more than one version of a code system: the codes of an imported value set had no version, the others did - tx: converting a ValueSet or CodeSystem to R3 treated the `generalizes` filter operator as one R3 doesn't have (a CodeSystem's was dropped, a ValueSet filter's put in the filter.op extension); STU3's filter-operator has it, as R4's does - tx: ValueSet and ConceptMap `getFHIRVersion()` and `getInfo().fhirVersion` gave the resource's own version, not the FHIR version it was read as; ConceptMap `getInfo()` failed outright; ValueSet `getCode()`/`hasCode()` without a version didn't find a code whose expansion entry has one - tests: the ValueSet, ConceptMap and NamingSystem library tests (tests/library/*.tests.js, 104 tests) were never run, as jest runs only *.test.js; renamed, and a test now fails when a file of tests is one jest won't run diff --git a/extension-tracker/extension-tracker.js b/extension-tracker/extension-tracker.js index 8a8f79411..778aff681 100644 --- a/extension-tracker/extension-tracker.js +++ b/extension-tracker/extension-tracker.js @@ -1,8 +1,6 @@ const express = require('express'); const path = require('path'); -const Database = require('better-sqlite3'); -const sqlite3 = require('sqlite3'); -const { SqlitePool } = require('../library/sql/sqlite-pool'); +const { SqliteDatabase, SqliteWorkerPool } = require('../library/sql/node-sqlite'); const htmlServer = require('../library/html/html-server'); const escape = require('escape-html'); const packageJson = require('../package.json'); @@ -161,23 +159,24 @@ class ExtensionTrackerModule { } /** - * Submissions are written through one better-sqlite3 connection (a transaction, and quick). - * The pages read through a pool of sqlite3 connections (library/sql/sqlite-pool.js), so their - * queries - the unfiltered ones read whole tables - run off the event loop: better-sqlite3 is - * synchronous, and a page held the whole server while its query ran. Read-write connections - * that only read, so they see what the writer commits (WAL). + * Submissions are written through one connection on this thread (library/sql/node-sqlite.js + * SqliteDatabase: a transaction, and quick). The pages read through a pool of worker threads + * (SqliteWorkerPool), so their queries - the unfiltered ones read whole tables - run off the + * event loop: node:sqlite is synchronous, and a page's query on this thread would hold the + * whole server while it ran. Read-write connections that only read, so they see what the + * writer commits (WAL). */ async initialize(config, app) { this.config = config; const dbPath = config.database || path.join(config.folder || '.', 'extension-tracker.db'); - this.db = new Database(dbPath); - this.db.pragma('journal_mode = WAL'); - this.db.pragma('foreign_keys = ON'); + // foreign keys on: deleting a package cascades to its extensions, profiles and usages + this.db = new SqliteDatabase(dbPath, { enableForeignKeyConstraints: true }); + this.db.exec('PRAGMA journal_mode = WAL'); this.createSchema(); this.prepareStatements(); - this.readDb = await SqlitePool.open(dbPath, { + this.readDb = await SqliteWorkerPool.open(dbPath, { size: Number.isInteger(config.connections) && config.connections > 0 ? config.connections : 2, - mode: sqlite3.OPEN_READWRITE + readOnly: false }); this.urlBase = config.url || '/ext-tracker'; @@ -266,24 +265,24 @@ class ExtensionTrackerModule { prepareStatements() { this.stmts = { - deletePackage: this.db.prepare('DELETE FROM packages WHERE package = ?'), - countSubmission: this.db.prepare( + deletePackage: this.db.statement('DELETE FROM packages WHERE package = ?'), + countSubmission: this.db.statement( 'INSERT INTO submissions (package, n, since, last_at) VALUES (?, 1, ?, ?) ' + 'ON CONFLICT (package) DO UPDATE SET n = n + 1, last_at = excluded.last_at' ), - insertPackage: this.db.prepare( + insertPackage: this.db.statement( 'INSERT INTO packages (package, version, fhir_version, jurisdiction, submitted_at) VALUES (?, ?, ?, ?, ?)' ), - insertExtension: this.db.prepare( + insertExtension: this.db.statement( 'INSERT INTO extensions (package_id, url, title) VALUES (?, ?, ?)' ), - insertExtensionType: this.db.prepare( + insertExtensionType: this.db.statement( 'INSERT INTO extension_types (extension_id, type) VALUES (?, ?)' ), - insertProfile: this.db.prepare( + insertProfile: this.db.statement( 'INSERT INTO profiles (package_id, resource_type, url, title) VALUES (?, ?, ?, ?)' ), - insertUsage: this.db.prepare( + insertUsage: this.db.statement( 'INSERT INTO usages (package_id, extension_url, location) VALUES (?, ?, ?)' ) }; @@ -392,15 +391,11 @@ class ExtensionTrackerModule { // ---- Reading (the pages) ---- all(sql, params = []) { - return new Promise((resolve, reject) => { - this.readDb.all(sql, params, (err, rows) => err ? reject(err) : resolve(rows)); - }); + return this.readDb.all(sql, params); } get(sql, params = []) { - return new Promise((resolve, reject) => { - this.readDb.get(sql, params, (err, row) => err ? reject(err) : resolve(row)); - }); + return this.readDb.get(sql, params); } // ---- Template rendering ---- @@ -459,24 +454,24 @@ class ExtensionTrackerModule { } ingestData(data) { - const ingest = this.db.transaction(() => { + this.db.transaction(() => { // delete any existing entry for this package (cascade cleans children) - this.stmts.deletePackage.run(data.package); + this.stmts.deletePackage.run([data.package]); // insert package const now = new Date().toISOString(); - const result = this.stmts.insertPackage.run( + const result = this.stmts.insertPackage.run([ data.package, data.version, data.fhirVersion, data.jurisdiction || null, now - ); - this.stmts.countSubmission.run(data.package, now, now); - const packageId = result.lastInsertRowid; + ]); + this.stmts.countSubmission.run([data.package, now, now]); + const packageId = result.lastID; // insert extensions if (Array.isArray(data.extensions)) { for (const ext of data.extensions) { - const extResult = this.stmts.insertExtension.run(packageId, ext.url, ext.title || null); - const extId = extResult.lastInsertRowid; + const extResult = this.stmts.insertExtension.run([packageId, ext.url, ext.title || null]); + const extId = extResult.lastID; // deduplicate types if (Array.isArray(ext.types)) { @@ -484,7 +479,7 @@ class ExtensionTrackerModule { for (const type of ext.types) { if (!seen.has(type)) { seen.add(type); - this.stmts.insertExtensionType.run(extId, type); + this.stmts.insertExtensionType.run([extId, type]); } } } @@ -496,7 +491,7 @@ class ExtensionTrackerModule { for (const [resourceType, profileList] of Object.entries(data.profiles)) { if (Array.isArray(profileList)) { for (const profile of profileList) { - this.stmts.insertProfile.run(packageId, resourceType, profile.url, profile.title || null); + this.stmts.insertProfile.run([packageId, resourceType, profile.url, profile.title || null]); } } } @@ -507,14 +502,13 @@ class ExtensionTrackerModule { for (const [extUrl, locations] of Object.entries(data.usage)) { if (Array.isArray(locations)) { for (const location of locations) { - this.stmts.insertUsage.run(packageId, extUrl, location); + this.stmts.insertUsage.run([packageId, extUrl, location]); } } } } }); - ingest(); this.usageCache = null; // the aggregated usage page (handleUsage) is out of date now this.generation++; } @@ -708,10 +702,10 @@ class ExtensionTrackerModule { /** * Usages, aggregated across packages: of one extension (?url=, as the package pages link - * to), or of all of them. The query is synchronous (better-sqlite3), and all of them is the - * whole table: 2 s and 800 KB on tx.fhir.org, which a spider following the package pages' - * links asked for 500 times a day, as the url was ignored. All of them is kept until the next - * submission (usageCache). + * to), or of all of them. All of them is the whole table: 2 s and 800 KB on tx.fhir.org (when + * the query still ran on the main thread, holding the server), which a spider following the + * package pages' links asked for 500 times a day, as the url was ignored. All of them is kept + * until the next submission (usageCache). */ async handleUsage(req, res) { const startTime = Date.now(); @@ -908,10 +902,11 @@ class ExtensionTrackerModule { // ---- Module lifecycle ---- - shutdown() { + async shutdown() { if (this.readDb) { - this.readDb.close(); + const readDb = this.readDb; this.readDb = null; + await readDb.close(); } if (this.db) { this.db.close(); @@ -925,7 +920,7 @@ class ExtensionTrackerModule { return { status: 'closed' }; } // synchronous (the server's status asks for it so), but the packages table is small - const count = this.db.prepare('SELECT COUNT(*) as count FROM packages').get().count; + const count = this.db.get('SELECT COUNT(*) as count FROM packages').count; this.stats.countRequest('search', Date.now() - startTime); return { status: 'running', packages: count }; } diff --git a/library/fhir/fhirpath/fhirpath-engine.js b/library/fhir/fhirpath/fhirpath-engine.js index 0ea6f1052..0de1d994f 100644 --- a/library/fhir/fhirpath/fhirpath-engine.js +++ b/library/fhir/fhirpath/fhirpath-engine.js @@ -1488,7 +1488,8 @@ class FHIRPathEngine { this.checkParamTypes(exp, code, paramTypes, S(FP_String)); const p = exp.parameters[0]; if (p.kind === Kind.Constant && p.constant != null) { - const url = primitiveValue(p.constant); + // (a %constant as it was written, as Java has it - for the warning when it isn't known) + const url = p.constant.type === 'constant' ? javaConstant(primitiveValue(p.constant)) : primitiveValue(p.constant); if (!isAbsoluteUrl(url) && focus.hasType('Extension')) { const res = new TypeDetails(CollectionStatus.ORDERED); const profiles = focus.getProfiles('Extension'); diff --git a/library/sql/node-sqlite.js b/library/sql/node-sqlite.js new file mode 100644 index 000000000..d81a3ab87 --- /dev/null +++ b/library/sql/node-sqlite.js @@ -0,0 +1,485 @@ +/** + * SQLite on node:sqlite (built into Node), for modules moving off the sqlite3 package. + * + * node:sqlite is synchronous: a query runs on the thread that asks for it. So there are two + * ways in: + * + * - SqliteDatabase: on the calling thread. For databases whose queries are always small + * (publisher, shl), and for writes that must be one transaction (extension-tracker's + * submissions): a transaction needs one connection, and a pool can't promise that. + * + * - SqliteWorkerPool: several connections, each on its own worker thread, each running one + * query at a time; a query waits in a queue for the first that is free. For queries that + * can take a while (whole-table reads): they run off the event loop, and a slow one only + * holds up the others when every worker is busy. The main thread only sends the query and + * takes the rows back (a structured clone: cheap next to the query, but not free for a + * very big result). + * + * Both keep what sqlite3 did where node:sqlite differs, so a module moves without changing what + * it stores or reads: + * - undefined is bound as NULL and a boolean as 1 or 0 (node:sqlite refuses both) + * - rows are ordinary objects (node:sqlite's have no prototype) + * - foreign key constraints are not enforced unless asked for (node:sqlite turns them on by + * default; publisher's tables reference a users table that the server's auth store replaced) + * + * Every connection waits up to busyTimeout ms (default 5000, as better-sqlite3) for a lock another + * holds, rather than failing at once with "database is locked". Several connections reading a + * WAL database for the first time at once need this: the first read sets up the WAL index, under + * a lock, and without a timeout the others fail while it does. + * + * Double-quoted string literals stay refused (node:sqlite's default): write 'now', not "now". + */ +const sqlite = require('node:sqlite'); +const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads'); + +// Node 26.11 renamed DatabaseSync to Database, and keeps the old name as a deprecated alias +const NodeDatabase = sqlite.Database || sqlite.DatabaseSync; + +// marks a worker thread started by SqliteWorkerPool (other worker threads may load this file too) +const WORKER_MARK = 'fhirsmithSqliteWorker'; + +const DEFAULT_POOL_SIZE = 2; + +const DEFAULT_BUSY_TIMEOUT = 5000; + +// prepared statements kept per connection; past this many (dynamic SQL) the cache starts again +const STATEMENT_CACHE_SIZE = 200; + +function bindable(value) { + if (value === undefined) { + return null; + } + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + return value; +} + +function bindAll(params) { + return (params || []).map(bindable); +} + +function plain(row) { + return row === undefined ? undefined : { ...row }; +} + +function runResult(result) { + return { lastID: Number(result.lastInsertRowid), changes: Number(result.changes) }; +} + +function openConnection(path, options = {}) { + const { busyTimeout, ...nodeOptions } = options; + const db = new NodeDatabase(path, { enableForeignKeyConstraints: false, ...nodeOptions }); + const timeout = Number.isInteger(busyTimeout) && busyTimeout >= 0 ? busyTimeout : DEFAULT_BUSY_TIMEOUT; + try { + db.exec(`PRAGMA busy_timeout = ${timeout}`); + } catch (err) { + db.close(); + throw err; + } + return db; +} + +/** A prepared statement on one connection, kept (and used) by the caller */ +class SqliteStatement { + constructor(statement) { + this.statement = statement; + } + + /** @returns {{lastID: number, changes: number}} */ + run(params) { + return runResult(this.statement.run(...bindAll(params))); + } + + /** @returns {Object|undefined} */ + get(params) { + return plain(this.statement.get(...bindAll(params))); + } + + /** @returns {Object[]} */ + all(params) { + return this.statement.all(...bindAll(params)).map(plain); + } +} + +class SqliteDatabase { + /** + * @param {string} path - the database file, or ':memory:' + * @param {Object} [options] - node:sqlite options (readOnly, enableForeignKeyConstraints, ...); + * enableForeignKeyConstraints defaults to false. And busyTimeout: ms to wait for a lock (default 5000) + */ + constructor(path, options = {}) { + this.db = openConnection(path, options); + } + + /** Statements with no parameters and no result (CREATE TABLE ..., PRAGMA ...); several may be given at once */ + exec(sql) { + this.db.exec(sql); + } + + /** + * @returns {{lastID: number, changes: number}} what sqlite3 gave a run() callback as this.lastID / this.changes + */ + run(sql, params) { + return runResult(this.db.prepare(sql).run(...bindAll(params))); + } + + /** @returns {Object|undefined} the first row, or undefined if there is none */ + get(sql, params) { + return plain(this.db.prepare(sql).get(...bindAll(params))); + } + + /** @returns {Object[]} */ + all(sql, params) { + return this.db.prepare(sql).all(...bindAll(params)).map(plain); + } + + /** + * A statement prepared once, for one that is run often (its run/get/all take the parameters as an array) + * @returns {SqliteStatement} + */ + statement(sql) { + return new SqliteStatement(this.db.prepare(sql)); + } + + /** + * Run fn in a transaction: committed if it returns, rolled back if it throws (and the error + * thrown on). fn must be synchronous - nothing else may use the connection while the + * transaction is open - and transactions don't nest. + * @returns what fn returns + */ + transaction(fn) { + this.db.exec('BEGIN'); + let result; + try { + result = fn(); + } catch (err) { + try { + this.db.exec('ROLLBACK'); + } catch { + // SQLite already rolled it back (some errors do) + } + throw err; + } + this.db.exec('COMMIT'); + return result; + } + + close() { + this.db.close(); + } +} + +// ---- The worker pool ---- + +/** What crosses from a worker: node:sqlite's errors carry code (ERR_SQLITE_ERROR), errcode and errstr */ +function errorInfo(err) { + return { + message: err && err.message ? err.message : String(err), + code: err && err.code, + errcode: err && err.errcode, + errstr: err && err.errstr + }; +} + +function rebuildError(info, sql) { + const err = new Error(info.message); + for (const key of ['code', 'errcode', 'errstr']) { + if (info[key] !== undefined) { + err[key] = info[key]; + } + } + if (sql) { + err.sql = sql; + } + return err; +} + +class SqliteWorkerPool { + + /** + * Open a pool. Resolves once every worker has its connection open; rejects (stopping the + * others) if any can't. + * + * @param {string} path - the database file + * @param {Object} [options] + * @param {number} [options.size] - how many workers (connections); default 2 + * @param {boolean} [options.readOnly] - default true. A database another connection writes to + * (WAL) is better read through read-write connections that only read: a read-only one may + * not see a schema change the writer makes + * @param {string[]} [options.pragmas] - run on each connection as it opens + * @param {number} [options.busyTimeout] - ms a connection waits for a lock another holds (default 5000) + * @param {Object} [options.options] - other node:sqlite open options + * @returns {Promise} + */ + static async open(path, options = {}) { + const pool = new SqliteWorkerPool(path, options); + try { + await Promise.all(pool.slots.map(slot => slot.ready)); + } catch (err) { + await pool.close(); + throw err; + } + return pool; + } + + constructor(path, { size, readOnly = true, pragmas = [], busyTimeout, options = {} } = {}) { + this.config = { [WORKER_MARK]: true, path, options: { ...options, readOnly, busyTimeout }, pragmas }; + this.queue = []; // queries waiting for a worker: {id, method, sql, params, resolve, reject} + this.closed = false; + this.nextId = 1; + const count = Number.isInteger(size) && size > 0 ? size : DEFAULT_POOL_SIZE; + this.slots = Array.from({ length: count }, () => { + const slot = { worker: null, state: 'starting', job: null, started: false, ready: null }; + this._start(slot); + return slot; + }); + } + + /** How many workers */ + get size() { + return this.slots.length; + } + + /** How many queries are in hand: running, and waiting for a worker */ + get pending() { + return this.queue.length + this.slots.filter(slot => slot.job).length; + } + + /** @returns {Promise} the first row, or undefined if there is none */ + get(sql, params) { + return this._query('get', sql, params); + } + + /** @returns {Promise} */ + all(sql, params) { + return this._query('all', sql, params); + } + + /** + * One statement, on whichever connection is free: nothing that needs one connection (a + * transaction, a temporary table) goes through a pool + * @returns {Promise<{lastID: number, changes: number}>} + */ + run(sql, params) { + return this._query('run', sql, params); + } + + /** + * Refuse new queries, fail those still waiting, let the running ones finish, then close the + * connections and stop the workers. + */ + async close() { + if (this.closed) { + return; + } + this.closed = true; + for (const job of this.queue.splice(0)) { + job.reject(new Error('The database was closed before the query ran')); + } + await Promise.all(this.slots.map(slot => this._stop(slot))); + } + + _query(method, sql, params) { + if (this.closed) { + return Promise.reject(new Error('The database is closed')); + } + return new Promise((resolve, reject) => { + this.queue.push({ id: this.nextId++, method, sql, params: bindAll(params), resolve, reject }); + this._dispatch(); + }); + } + + _start(slot) { + const worker = new Worker(__filename, { workerData: this.config }); + slot.worker = worker; + slot.state = 'starting'; + slot.started = false; + slot.job = null; + slot.ready = new Promise((resolve, reject) => { + slot.onReady = { resolve, reject }; + }); + slot.ready.catch(() => {}); // open() looks at it; a restart's failure is handled in _exit + worker.on('message', msg => this._message(slot, worker, msg)); + worker.on('error', err => { + if (slot.worker === worker) { + slot.lastError = err; + } + }); + worker.on('exit', code => this._exit(slot, worker, code)); + } + + _message(slot, worker, msg) { + if (slot.worker !== worker) { + return; + } + if ('ready' in msg) { + if (msg.ready) { + slot.state = 'idle'; + slot.started = true; + worker.unref(); // an idle pool doesn't keep the process alive + slot.onReady.resolve(); + this._dispatch(); + } else { + slot.state = 'failed'; + slot.onReady.reject(rebuildError(msg.error)); + } + return; + } + const job = slot.job; + if (!job || job.id !== msg.id) { + return; + } + slot.job = null; + slot.state = 'idle'; + worker.unref(); + if (msg.error) { + job.reject(rebuildError(msg.error, job.sql)); + } else { + job.resolve(msg.result); + } + if (slot.onIdle) { + slot.onIdle(); + } + this._dispatch(); + } + + _exit(slot, worker, code) { + if (slot.worker !== worker) { + return; + } + const why = slot.lastError ? slot.lastError.message : `exit code ${code}`; + slot.lastError = null; + if (slot.job) { + const job = slot.job; + slot.job = null; + job.reject(new Error(`The SQLite worker stopped while running the query (${why})`)); + } + if (slot.state === 'starting') { + slot.onReady.reject(new Error(`The SQLite worker stopped before its connection was open (${why})`)); + } + const wasRunning = slot.started && slot.state !== 'failed'; + slot.worker = null; + slot.state = 'stopped'; + if (slot.onIdle) { + slot.onIdle(); + } + if (!this.closed && wasRunning) { + // replace it: its connection opened before, so it should again + this._start(slot); + slot.ready.catch(err => { + slot.state = 'failed'; + this._failQueueIfNoWorkers(err); + }); + } else { + this._failQueueIfNoWorkers(new Error(`No SQLite worker is running (${why})`)); + } + } + + _failQueueIfNoWorkers(err) { + if (this.slots.some(slot => slot.state === 'idle' || slot.state === 'starting' || slot.job)) { + return; + } + for (const job of this.queue.splice(0)) { + job.reject(err); + } + } + + _dispatch() { + while (this.queue.length > 0) { + const slot = this.slots.find(s => s.state === 'idle'); + if (!slot) { + return; + } + const job = this.queue.shift(); + slot.job = job; + slot.state = 'busy'; + slot.worker.ref(); // a query in hand keeps the process alive until it's answered + slot.worker.postMessage({ id: job.id, method: job.method, sql: job.sql, params: job.params }); + } + } + + async _stop(slot) { + if (slot.job) { + await new Promise(resolve => { + slot.onIdle = resolve; + }); + } + slot.onIdle = null; + const worker = slot.worker; + if (!worker) { + return; + } + worker.ref(); // the caller waits for it to stop: the process must not end first + await new Promise(resolve => { + const timer = setTimeout(() => worker.terminate().then(resolve, resolve), 5000); + timer.unref(); + worker.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + worker.postMessage({ method: 'close' }); + }); + } +} + +// ---- In a worker thread ---- + +function runWorker({ path, options, pragmas }) { + let db; + try { + db = openConnection(path, options); + for (const pragma of pragmas || []) { + db.exec(pragma); + } + } catch (err) { + parentPort.postMessage({ ready: false, error: errorInfo(err) }); + return; // nothing listening: the thread ends + } + const statements = new Map(); + const prepared = sql => { + let statement = statements.get(sql); + if (!statement) { + if (statements.size >= STATEMENT_CACHE_SIZE) { + statements.clear(); + } + statement = db.prepare(sql); + statements.set(sql, statement); + } + return statement; + }; + parentPort.on('message', ({ id, method, sql, params }) => { + if (method === 'close') { + statements.clear(); + try { + db.close(); + } catch { + // closing anyway + } + parentPort.close(); + return; + } + try { + const statement = prepared(sql); + let result; + if (method === 'get') { + result = statement.get(...params); + } else if (method === 'all') { + result = statement.all(...params); + } else { + result = runResult(statement.run(...params)); + } + // rows without a prototype arrive as ordinary objects (structured clone) + parentPort.postMessage({ id, result }); + } catch (err) { + parentPort.postMessage({ id, error: errorInfo(err) }); + } + }); + parentPort.postMessage({ ready: true }); +} + +if (!isMainThread && workerData && workerData[WORKER_MARK]) { + runWorker(workerData); +} + +module.exports = { SqliteDatabase, SqliteStatement, SqliteWorkerPool }; diff --git a/publisher/publisher.js b/publisher/publisher.js index 063d6258e..3cbbe0630 100644 --- a/publisher/publisher.js +++ b/publisher/publisher.js @@ -4,14 +4,13 @@ const fs = require('fs'); const validation = require('./validation'); const gitRemote = require('./git-remote'); const githubRelease = require('./github-release'); -const Database = require('sqlite3').Database; +const { SqliteDatabase } = require('../library/sql/node-sqlite'); const auth = require('../library/security/auth'); const rateLimit = require('express-rate-limit'); const folders = require('../library/server/folder-setup'); const escape = require('escape-html'); const { requireSameOrigin } = require('../library/security/same-origin'); const {Utilities} = require("../library/utils/utilities"); -const { guarded } = require('../library/sql/sqlite-utilities'); // GitHub refuses any file larger than this at the pre-receive hook, and the rejection takes down // the whole push rather than just the offending file. @@ -96,18 +95,14 @@ class PublisherModule { this.logger.info('Created database directory: ' + dbDir); } - return new Promise((resolve, reject) => { - this.db = new Database(dbPath, (err) => { - if (err) { - this.logger.error('Failed to connect to database:', err); - reject(err); - return; - } - - this.logger.info('Connected to SQLite database: ' + dbPath); - this.createTables().then(resolve).catch(reject); - }); - }); + try { + this.db = new SqliteDatabase(dbPath); + } catch (err) { + this.logger.error('Failed to connect to database:', err); + throw err; + } + this.logger.info('Connected to SQLite database: ' + dbPath); + await this.createTables(); } async createTables() { @@ -196,16 +191,12 @@ class PublisherModule { ]; for (const sql of tables) { - await new Promise((resolve, reject) => { - this.db.run(sql, guarded(reject, (err) => { - if (err) { - this.logger.error('Failed to create table:', err); - reject(err); - } else { - resolve(); - } - })); - }); + try { + this.db.exec(sql); + } catch (err) { + this.logger.error('Failed to create table:', err); + throw err; + } } // Schema migrations for existing databases @@ -214,63 +205,28 @@ class PublisherModule { async runMigrations() { // Add announcement column if it doesn't exist (added after initial schema) - const columns = await new Promise((resolve, reject) => { - this.db.all("PRAGMA table_info(tasks)", guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + const columns = this.db.all("PRAGMA table_info(tasks)"); const columnNames = columns.map(c => c.name); if (!columnNames.includes('announcement')) { - await new Promise((resolve, reject) => { - this.db.run('ALTER TABLE tasks ADD COLUMN announcement TEXT', guarded(reject, (err) => { - if (err) reject(err); - else { - this.logger.info('Migration: added announcement column to tasks table'); - resolve(); - } - })); - }); + this.db.exec('ALTER TABLE tasks ADD COLUMN announcement TEXT'); + this.logger.info('Migration: added announcement column to tasks table'); } if (!columnNames.includes('publisher_version')) { - await new Promise((resolve, reject) => { - this.db.run('ALTER TABLE tasks ADD COLUMN publisher_version TEXT', guarded(reject, (err) => { - if (err) reject(err); - else { - this.logger.info('Migration: added publisher_version column to tasks table'); - resolve(); - } - })); - }); + this.db.exec('ALTER TABLE tasks ADD COLUMN publisher_version TEXT'); + this.logger.info('Migration: added publisher_version column to tasks table'); } if (!columnNames.includes('release_url')) { - await new Promise((resolve, reject) => { - this.db.run('ALTER TABLE tasks ADD COLUMN release_url TEXT', guarded(reject, (err) => { - if (err) reject(err); - else { - this.logger.info('Migration: added release_url column to tasks table'); - resolve(); - } - })); - }); + this.db.exec('ALTER TABLE tasks ADD COLUMN release_url TEXT'); + this.logger.info('Migration: added release_url column to tasks table'); } - const websiteColumns = await new Promise((resolve, reject) => { - this.db.all("PRAGMA table_info(websites)", guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + const websiteColumns = this.db.all("PRAGMA table_info(websites)"); const websiteColumnNames = websiteColumns.map(c => c.name); // who queued and approved a task, and who took an action, by name: the users are the // server's (library/security/auth), in another database, so the pages can't join to them for (const [table, column] of [['tasks', 'created_by_label'], ['tasks', 'approved_by_label'], ['user_actions', 'actor_label']]) { - const cols = await new Promise((resolve, reject) => { - this.db.all(`PRAGMA table_info(${table})`, guarded(reject, (err, rows) => err ? reject(err) : resolve(rows || []))); - }); + const cols = this.db.all(`PRAGMA table_info(${table})`); if (!cols.some(c => c.name === column)) { - await new Promise((resolve, reject) => { - this.db.run(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`, guarded(reject, (err) => err ? reject(err) : resolve())); - }); + this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`); this.logger.info(`Migration: added ${column} column to ${table} table`); } } @@ -278,15 +234,8 @@ class PublisherModule { // neither, and every insert or update of a website failed for (const column of ['git_root', 'history_templates', 'web_templates']) { if (!websiteColumnNames.includes(column)) { - await new Promise((resolve, reject) => { - this.db.run(`ALTER TABLE websites ADD COLUMN ${column} TEXT`, guarded(reject, (err) => { - if (err) reject(err); - else { - this.logger.info(`Migration: added ${column} column to websites table`); - resolve(); - } - })); - }); + this.db.exec(`ALTER TABLE websites ADD COLUMN ${column} TEXT`); + this.logger.info(`Migration: added ${column} column to websites table`); } } } @@ -444,29 +393,11 @@ class PublisherModule { } async getNextQueuedTask() { - return new Promise((resolve, reject) => { - this.db.get( - 'SELECT * FROM tasks WHERE status = ? ORDER BY queued_at ASC LIMIT 1', - ['queued'], - guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - }) - ); - }); + return this.db.get('SELECT * FROM tasks WHERE status = ? ORDER BY queued_at ASC LIMIT 1', ['queued']); } async getNextApprovedTask() { - return new Promise((resolve, reject) => { - this.db.get( - 'SELECT * FROM tasks WHERE status = ? ORDER BY publishing_at ASC LIMIT 1', - ['publishing'], - guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - }) - ); - }); + return this.db.get('SELECT * FROM tasks WHERE status = ? ORDER BY publishing_at ASC LIMIT 1', ['publishing']); } async updateTaskStatus(taskId, status, additionalFields = {}) { @@ -495,16 +426,7 @@ class PublisherModule { values.push(taskId); - return new Promise((resolve, reject) => { - this.db.run( - 'UPDATE tasks SET ' + fields.join(', ') + ' WHERE id = ?', - values, - guarded(reject, (err) => { - if (err) reject(err); - else resolve(); - }) - ); - }); + this.db.run('UPDATE tasks SET ' + fields.join(', ') + ' WHERE id = ?', values); } // Update arbitrary task fields WITHOUT touching status. Use this from long-running @@ -517,26 +439,16 @@ class PublisherModule { const values = keys.map(key => fields[key]); values.push(taskId); - return new Promise((resolve, reject) => { - this.db.run( - 'UPDATE tasks SET ' + assignments.join(', ') + ' WHERE id = ?', - values, - guarded(reject, (err) => { - if (err) reject(err); - else resolve(); - }) - ); - }); + this.db.run('UPDATE tasks SET ' + assignments.join(', ') + ' WHERE id = ?', values); } async logTaskMessage(taskId, level, message) { - return new Promise((resolve, reject) => { - this.db.run( - 'INSERT INTO task_logs (task_id, level, message) VALUES (?, ?, ?)', - [taskId.toString(), level, message], - guarded(reject, () => resolve()) // Don't fail if logging fails - ); - }); + try { + this.db.run('INSERT INTO task_logs (task_id, level, message) VALUES (?, ?, ?)', [taskId.toString(), level, message]); + } catch (err) { + // Don't fail if logging fails + this.logger.warn('Could not log a message for task #' + taskId + ': ' + err.message); + } } async processDraftBuild(task) { @@ -1861,18 +1773,10 @@ class PublisherModule { } // Insert task (ID will be auto-generated) - const result = await new Promise((resolve, reject) => { - this.db.run( - 'INSERT INTO tasks (user_id, created_by_label, website_id, github_org, github_repo, git_branch, npm_package_id, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - [req.pub.userId, this.label(req), website_id, github_org, github_repo, git_branch, npm_package_id, version], - guarded(reject, function (err) { - if (err) reject(err); - else resolve(this.lastID); - }) - ); - }); - - const taskId = result; + const taskId = this.db.run( + 'INSERT INTO tasks (user_id, created_by_label, website_id, github_org, github_repo, git_branch, npm_package_id, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + [req.pub.userId, this.label(req), website_id, github_org, github_repo, git_branch, npm_package_id, version] + ).lastID; // Log the action this.logUserAction(req.pub.userId, 'create_task', taskId.toString(), req.ip); @@ -1911,16 +1815,10 @@ class PublisherModule { } // Update task status - await new Promise((resolve, reject) => { - this.db.run( - 'UPDATE tasks SET status = ?, approved_by = ?, approved_by_label = ?, publishing_at = CURRENT_TIMESTAMP WHERE id = ?', - ['publishing', req.pub.userId, this.label(req), taskId], - guarded(reject, (err) => { - if (err) reject(err); - else resolve(); - }) - ); - }); + this.db.run( + 'UPDATE tasks SET status = ?, approved_by = ?, approved_by_label = ?, publishing_at = CURRENT_TIMESTAMP WHERE id = ?', + ['publishing', req.pub.userId, this.label(req), taskId] + ); // Log the action this.logUserAction(req.pub.userId, 'approve_task', taskId, req.ip); @@ -1975,20 +1873,10 @@ class PublisherModule { } // Delete task logs - await new Promise((resolve, reject) => { - this.db.run('DELETE FROM task_logs WHERE task_id = ?', [taskId.toString()], guarded(reject, (err) => { - if (err) reject(err); - else resolve(); - })); - }); + this.db.run('DELETE FROM task_logs WHERE task_id = ?', [taskId.toString()]); // Delete task record - await new Promise((resolve, reject) => { - this.db.run('DELETE FROM tasks WHERE id = ?', [taskId], guarded(reject, (err) => { - if (err) reject(err); - else resolve(); - })); - }); + this.db.run('DELETE FROM tasks WHERE id = ?', [taskId]); this.logUserAction(req.pub.userId, 'delete_task', taskId, req.ip); this.logger.info('Task deleted: ' + taskId + ' by user ' + req.pub.userId); @@ -2014,13 +1902,10 @@ class PublisherModule { if (!canQueue) return res.status(403).send('You do not have permission to queue tasks for this website'); const existingTask = await this.findActiveTask(task.npm_package_id, task.version); if (existingTask) return res.status(400).send('An active task for this package and version is already in progress.'); - const newTaskId = await new Promise((resolve, reject) => { - this.db.run( - 'INSERT INTO tasks (user_id, created_by_label, website_id, github_org, github_repo, git_branch, npm_package_id, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - [req.pub.userId, this.label(req), task.website_id, task.github_org, task.github_repo, task.git_branch, task.npm_package_id, task.version], - guarded(reject, function (err) { if (err) reject(err); else resolve(this.lastID); }) - ); - }); + const newTaskId = this.db.run( + 'INSERT INTO tasks (user_id, created_by_label, website_id, github_org, github_repo, git_branch, npm_package_id, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + [req.pub.userId, this.label(req), task.website_id, task.github_org, task.github_repo, task.git_branch, task.npm_package_id, task.version] + ).lastID; this.logUserAction(req.pub.userId, 'retry_task', newTaskId.toString(), req.ip); this.logger.info('Task retried: new ID=' + newTaskId + ' from task #' + taskId); res.redirect('/publisher/tasks/' + newTaskId + '/history'); @@ -2429,13 +2314,10 @@ class PublisherModule { const { name, local_folder, git_root, history_templates, web_templates, server_update_script, is_active } = req.body; const websiteId = req.params.id; - await new Promise((resolve, reject) => { - this.db.run( - 'UPDATE websites SET name=?, local_folder=?, git_root = ?, history_templates=?, web_templates=?, server_update_script=?, is_active=? WHERE id=?', - [name, local_folder, git_root, history_templates, web_templates, server_update_script, is_active === '1' ? 1 : 0, websiteId], - guarded(reject, (err) => err ? reject(err) : resolve()) - ); - }); + this.db.run( + 'UPDATE websites SET name=?, local_folder=?, git_root = ?, history_templates=?, web_templates=?, server_update_script=?, is_active=? WHERE id=?', + [name, local_folder, git_root, history_templates, web_templates, server_update_script, is_active === '1' ? 1 : 0, websiteId] + ); this.logUserAction(req.pub.userId, 'update_website', websiteId, req.ip); await this.refreshWebsiteList(); @@ -2547,16 +2429,10 @@ class PublisherModule { try { const {name, local_folder, git_root, history_templates, web_templates, server_update_script} = req.body; - await new Promise((resolve, reject) => { - this.db.run( - 'INSERT INTO websites (name, local_folder, git_root, history_templates, web_templates, server_update_script) VALUES (?, ?, ?, ?, ?, ?)', - [name, local_folder, git_root, history_templates, web_templates, server_update_script], - guarded(reject, function (err) { - if (err) reject(err); - else resolve(); - }) - ); - }); + this.db.run( + 'INSERT INTO websites (name, local_folder, git_root, history_templates, web_templates, server_update_script) VALUES (?, ?, ?, ?, ?, ?)', + [name, local_folder, git_root, history_templates, web_templates, server_update_script] + ); this.logUserAction(req.pub.userId, 'create_website', name, req.ip); await this.refreshWebsiteList(); @@ -2575,57 +2451,33 @@ class PublisherModule { // Helper methods async getTasks(limit = null) { - return new Promise((resolve, reject) => { - let sql = 'SELECT t.*, COALESCE(t.created_by_label, u.name) as user_name, w.name as website_name, COALESCE(t.approved_by_label, approver.name) as approved_by_name FROM tasks t LEFT JOIN users u ON t.user_id = u.id AND t.created_by_label IS NULL JOIN websites w ON t.website_id = w.id LEFT JOIN users approver ON t.approved_by = approver.id AND t.approved_by_label IS NULL ORDER BY t.queued_at DESC'; - - if (limit) { - sql += ' LIMIT ' + limit; - } + let sql = 'SELECT t.*, COALESCE(t.created_by_label, u.name) as user_name, w.name as website_name, COALESCE(t.approved_by_label, approver.name) as approved_by_name FROM tasks t LEFT JOIN users u ON t.user_id = u.id AND t.created_by_label IS NULL JOIN websites w ON t.website_id = w.id LEFT JOIN users approver ON t.approved_by = approver.id AND t.approved_by_label IS NULL ORDER BY t.queued_at DESC'; - this.db.all(sql, guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + if (limit) { + sql += ' LIMIT ' + limit; + } + return this.db.all(sql); } async getTask(taskId) { - return new Promise((resolve, reject) => { - this.db.get( - 'SELECT t.*, COALESCE(t.created_by_label, u.name) as user_name, u.login as user_login, w.name as website_name, COALESCE(t.approved_by_label, approver.name) as approved_by_name FROM tasks t LEFT JOIN users u ON t.user_id = u.id AND t.created_by_label IS NULL JOIN websites w ON t.website_id = w.id LEFT JOIN users approver ON t.approved_by = approver.id AND t.approved_by_label IS NULL WHERE t.id = ?', - [taskId], - guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - }) - ); - }); + return this.db.get( + 'SELECT t.*, COALESCE(t.created_by_label, u.name) as user_name, u.login as user_login, w.name as website_name, COALESCE(t.approved_by_label, approver.name) as approved_by_name FROM tasks t LEFT JOIN users u ON t.user_id = u.id AND t.created_by_label IS NULL JOIN websites w ON t.website_id = w.id LEFT JOIN users approver ON t.approved_by = approver.id AND t.approved_by_label IS NULL WHERE t.id = ?', + [taskId] + ); } async getTaskLogs(taskId) { - return new Promise((resolve, reject) => { - this.db.all( - 'SELECT * FROM task_logs WHERE task_id = ? ORDER BY timestamp ASC', - [taskId.toString()], - guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - }) - ); - }); + return this.db.all( + 'SELECT * FROM task_logs WHERE task_id = ? ORDER BY timestamp ASC', + [taskId.toString()] + ); } async getTaskActions(taskId) { - return new Promise((resolve, reject) => { - this.db.all( - 'SELECT ua.*, COALESCE(ua.actor_label, u.name) as user_name, u.login as user_login FROM user_actions ua LEFT JOIN users u ON ua.user_id = u.id AND ua.actor_label IS NULL WHERE ua.target_id = ? ORDER BY ua.timestamp ASC', - [taskId.toString()], - guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - }) - ); - }); + return this.db.all( + 'SELECT ua.*, COALESCE(ua.actor_label, u.name) as user_name, u.login as user_login FROM user_actions ua LEFT JOIN users u ON ua.user_id = u.id AND ua.actor_label IS NULL WHERE ua.target_id = ? ORDER BY ua.timestamp ASC', + [taskId.toString()] + ); } /** The active websites a user may queue for (the publisher "queue" role, library/security/auth) */ @@ -2658,47 +2510,25 @@ class PublisherModule { } async findActiveTask(packageId, version) { - return new Promise((resolve, reject) => { - this.db.get( - 'SELECT * FROM tasks WHERE npm_package_id = ? AND version = ? AND status NOT IN (?, ?) ORDER BY queued_at DESC LIMIT 1', - [packageId, version, 'complete', 'failed'], - guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - }) - ); - }); + return this.db.get( + 'SELECT * FROM tasks WHERE npm_package_id = ? AND version = ? AND status NOT IN (?, ?) ORDER BY queued_at DESC LIMIT 1', + [packageId, version, 'complete', 'failed'] + ); } async findExistingTask(packageId, version) { - return new Promise((resolve, reject) => { - this.db.get( - 'SELECT * FROM tasks WHERE npm_package_id = ? AND version = ? ORDER BY queued_at DESC LIMIT 1', - [packageId, version], - guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - }) - ); - }); + return this.db.get( + 'SELECT * FROM tasks WHERE npm_package_id = ? AND version = ? ORDER BY queued_at DESC LIMIT 1', + [packageId, version] + ); } async getWebsites() { - return new Promise((resolve, reject) => { - this.db.all('SELECT * FROM websites ORDER BY name', guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + return this.db.all('SELECT * FROM websites ORDER BY name'); } async getWebsite(websiteId) { - return new Promise((resolve, reject) => { - this.db.get('SELECT * FROM websites WHERE id = ?', [websiteId], guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - })); - }); + return this.db.get('SELECT * FROM websites WHERE id = ?', [websiteId]); } async runCommand(command, args, options, taskId, description) { @@ -2807,8 +2637,7 @@ class PublisherModule { if (!this.db) { return 'The database is not open.'; } - const get = (sql, params) => new Promise((resolve, reject) => - this.db.get(sql, params, guarded(reject, (err, row) => err ? reject(err) : resolve(row)))); + const get = (sql, params) => this.db.get(sql, params); // the timestamps are CURRENT_TIMESTAMP: UTC, 'YYYY-MM-DD HH:MM:SS' const utc = ms => new Date(ms).toISOString().replace('T', ' ').substring(0, 19); try { @@ -2850,16 +2679,12 @@ class PublisherModule { // Close database if (this.db) { - return new Promise((resolve, reject) => { - this.db.close(guarded(reject, (err) => { - if (err) { - this.logger.error('Error closing database:', err); - } else { - this.logger.info('Database closed'); - } - resolve(); - })); - }); + try { + this.db.close(); + this.logger.info('Database closed'); + } catch (err) { + this.logger.error('Error closing database:', err); + } } } @@ -2875,15 +2700,18 @@ class PublisherModule { return colors[status] || 'secondary'; } - // Fire-and-forget audit logging: callers don't await this, and it must never fail a - // request, so it returns void and swallows any DB error in the callback. + // Audit logging: callers don't await this, and it must never fail a request, so it + // returns void and swallows any DB error. logUserAction(userId, action, targetId, ipAddress) { const p = userId ? auth.principalById(userId) : null; - this.db.run( - 'INSERT INTO user_actions (user_id, actor_label, action, target_id, ip_address) VALUES (?, ?, ?, ?, ?)', - [userId, p ? `${p.name} (${p.login})` : null, action, targetId, ipAddress], - () => {} // don't fail (or block) the request if audit logging fails - ); + try { + this.db.run( + 'INSERT INTO user_actions (user_id, actor_label, action, target_id, ip_address) VALUES (?, ?, ?, ?, ?)', + [userId, p ? `${p.name} (${p.login})` : null, action, targetId, ipAddress] + ); + } catch (err) { + this.logger.warn('Could not record the user action ' + action + ': ' + err.message); + } } getStatus() { diff --git a/shl/shl.js b/shl/shl.js index 932e57770..0c714b84c 100644 --- a/shl/shl.js +++ b/shl/shl.js @@ -5,7 +5,7 @@ // const express = require('express'); -const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../library/sql/node-sqlite'); const path = require('path'); const crypto = require('crypto'); const cron = require('node-cron'); @@ -16,7 +16,6 @@ const fs = require('fs'); const folders = require('../library/server/folder-setup'); const auth = require('../library/security/auth'); const rateLimit = require('express-rate-limit'); -const { guarded, failRequest } = require('../library/sql/sqlite-utilities'); const Logger = require('../library/server/logger'); const shlLog = Logger.getInstance().child({ module: 'shl' }); @@ -278,107 +277,65 @@ class SHLModule { } async initializeDatabase() { - return new Promise((resolve, reject) => { + const dbPath = folders.filePath('shl', this.config.database); // <-- CHANGE + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); - const dbPath = folders.filePath('shl', this.config.database); // <-- CHANGE - fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + try { + this.db = new SqliteDatabase(dbPath); + } catch (err) { + shlLog.error('Error opening SHL SQLite database at "'+dbPath+'":', err.message); + throw err; + } + shlLog.info('Connected to SHL SQLite database at "'+dbPath+'"'); - this.db = new sqlite3.Database(dbPath, (err) => { - if (err) { - shlLog.error('Error opening SHL SQLite database at "'+dbPath+'":', err.message); - reject(err); - } else { - shlLog.info('Connected to SHL SQLite database at "'+dbPath+'"'); - - // Check if tables already exist before creating them - this.db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='SHL'", guarded(reject, (err, row) => { - if (err) { - reject(err); - } else if (row) { - // Tables already exist, no need to create them - resolve(); - } else { - // Tables don't exist, create them - this.createTables().then(resolve).catch(reject); - } - })); - } - }); - }); + // Check if tables already exist before creating them + if (!this.db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='SHL'")) { + await this.createTables(); + } } async createTables() { - return new Promise((resolve, reject) => { - const createSHLTable = ` - CREATE TABLE IF NOT EXISTS SHL ( - uuid TEXT PRIMARY KEY, - vhl BOOLEAN NOT NULL, - expires_at DATETIME NOT NULL, - password TEXT NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - ) - `; - - const createSHLFilesTable = ` - CREATE TABLE IF NOT EXISTS SHLFiles ( - id TEXT PRIMARY KEY, - shl_uuid TEXT NOT NULL, - cnt TEXT NOT NULL, - type TEXT NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (shl_uuid) REFERENCES SHL (uuid) ON DELETE CASCADE - ) - `; - - const createSHLViewsTable = ` - CREATE TABLE IF NOT EXISTS SHLViews ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - shl_uuid TEXT NOT NULL, - recipient TEXT, - ip_address TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (shl_uuid) REFERENCES SHL (uuid) ON DELETE CASCADE - ) - `; - - let tablesCreated = 0; - const totalTables = 3; - - const checkComplete = () => { - tablesCreated++; - if (tablesCreated === totalTables) { - shlLog.info('SHL database initialized'); - resolve(); - } - }; - - this.db.run(createSHLTable, guarded(reject, (err) => { - if (err) { - shlLog.error('Error creating SHL table:', err.message); - reject(err); - } else { - checkComplete(); - } - })); - - this.db.run(createSHLFilesTable, guarded(reject, (err) => { - if (err) { - shlLog.error('Error creating SHLFiles table:', err.message); - reject(err); - } else { - checkComplete(); - } - })); - - this.db.run(createSHLViewsTable, guarded(reject, (err) => { - if (err) { - shlLog.error('Error creating SHLViews table:', err.message); - reject(err); - } else { - checkComplete(); - } - })); - }); + const createSHLTable = ` + CREATE TABLE IF NOT EXISTS SHL ( + uuid TEXT PRIMARY KEY, + vhl BOOLEAN NOT NULL, + expires_at DATETIME NOT NULL, + password TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + ) + `; + + const createSHLFilesTable = ` + CREATE TABLE IF NOT EXISTS SHLFiles ( + id TEXT PRIMARY KEY, + shl_uuid TEXT NOT NULL, + cnt TEXT NOT NULL, + type TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (shl_uuid) REFERENCES SHL (uuid) ON DELETE CASCADE + ) + `; + + const createSHLViewsTable = ` + CREATE TABLE IF NOT EXISTS SHLViews ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + shl_uuid TEXT NOT NULL, + recipient TEXT, + ip_address TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (shl_uuid) REFERENCES SHL (uuid) ON DELETE CASCADE + ) + `; + + for (const [name, sql] of [['SHL', createSHLTable], ['SHLFiles', createSHLFilesTable], ['SHLViews', createSHLViewsTable]]) { + try { + this.db.exec(sql); + } catch (err) { + shlLog.error('Error creating ' + name + ' table:', err.message); + throw err; + } + } + shlLog.info('SHL database initialized'); } async initializeFhirValidator() { @@ -440,16 +397,28 @@ class SHLModule { } } + // The files and views of an expired link go with it. The schema says ON DELETE CASCADE, but + // foreign keys aren't enforced (they never were), so they are deleted here, along with any + // left behind by earlier cleanups that didn't (rows whose link is gone) cleanupExpiredEntries() { - const deleteSql = 'DELETE FROM SHL WHERE expires_at < datetime("now")'; - - this.db.run(deleteSql, guarded(null, function(err) { - if (err) { - shlLog.error('SHL cleanup error:', err.message); - } else if (this.changes > 0) { - shlLog.info(`Cleaned up ${this.changes} expired SHL entries`); + try { + this.db.exec('BEGIN'); + try { + // expires_at is an ISO string (2026-12-04T01:00:00.000Z): datetime() it to compare with datetime('now') + const { changes } = this.db.run("DELETE FROM SHL WHERE datetime(expires_at) < datetime('now')"); + const files = this.db.run('DELETE FROM SHLFiles WHERE shl_uuid NOT IN (SELECT uuid FROM SHL)').changes; + const views = this.db.run('DELETE FROM SHLViews WHERE shl_uuid NOT IN (SELECT uuid FROM SHL)').changes; + this.db.exec('COMMIT'); + if (changes > 0 || files > 0 || views > 0) { + shlLog.info(`Cleaned up ${changes} expired SHL entries (${files} files, ${views} views)`); + } + } catch (err) { + this.db.exec('ROLLBACK'); + throw err; } - })); + } catch (err) { + shlLog.error('SHL cleanup error:', err.message); + } } generateUUID() { @@ -700,7 +669,7 @@ class SHLModule { }); // SHL create endpoint (creator, above). A "password" in the body, as clients sent before, is ignored - this.router.post('/create', creator, this.validateJsonBody(['vhl', 'days'], ['password']), (req, res, next) => { + this.router.post('/create', creator, this.validateJsonBody(['vhl', 'days'], ['password']), (req, res) => { const start = Date.now(); try { const {vhl, days} = req.body; @@ -736,27 +705,27 @@ class SHLModule { const insertSql = 'INSERT INTO SHL (uuid, vhl, expires_at, password) VALUES (?, ?, ?, ?)'; - this.db.run(insertSql, [uuid, vhl, expiryDateString, newPassword], guarded(next, function (err) { - if (err) { - return res.status(500).json({error: 'Failed to create SHL entry: ' + err.message}); - } + try { + this.db.run(insertSql, [uuid, vhl, expiryDateString, newPassword]); + } catch (err) { + return res.status(500).json({error: 'Failed to create SHL entry: ' + err.message}); + } - const host = req.get('host') || 'localhost:3000'; - shlLog.info(`SHL ${uuid} made by ${req.user.via === 'internal' ? 'this server' : `'${req.user.login}'`} (${vhl ? 'VHL' : 'SHL'}, ${daysNumber} days)`); + const host = req.get('host') || 'localhost:3000'; + shlLog.info(`SHL ${uuid} made by ${req.user.via === 'internal' ? 'this server' : `'${req.user.login}'`} (${vhl ? 'VHL' : 'SHL'}, ${daysNumber} days)`); - res.status(201).json({ - uuid: uuid, - pword: newPassword, - link: `https://${host}/shl/access/${uuid}` - }); - })); + res.status(201).json({ + uuid: uuid, + pword: newPassword, + link: `https://${host}/shl/access/${uuid}` + }); } finally { this.stats.countRequest('create', Date.now() - start); } }); // SHL upload endpoint - this.router.post('/upload', creator, this.validateJsonBody(['uuid', 'pword', 'files']), (req, res, next) => { + this.router.post('/upload', creator, this.validateJsonBody(['uuid', 'pword', 'files']), (req, res) => { const start = Date.now(); try { const {uuid, pword, files} = req.body; @@ -777,51 +746,39 @@ class SHLModule { const checkSHLSql = 'SELECT vhl, password FROM SHL WHERE uuid = ?'; - this.db.get(checkSHLSql, [uuid], guarded(next, (err, row) => { - if (err) { - return res.status(500).json({error: 'Database error'}); - } - - if (!row) { - return res.status(404).json({error: 'SHL entry not found'}); - } + let row; + try { + row = this.db.get(checkSHLSql, [uuid]); + } catch (err) { + return res.status(500).json({error: 'Database error'}); + } - if (row.password !== pword) { - return res.status(401).json({error: 'Unauthorized'}); - } + if (!row) { + return res.status(404).json({error: 'SHL entry not found'}); + } - const deleteExistingFilesSql = 'DELETE FROM SHLFiles WHERE shl_uuid = ?'; + if (row.password !== pword) { + return res.status(401).json({error: 'Unauthorized'}); + } - this.db.run(deleteExistingFilesSql, [uuid], guarded(next, (err) => { - if (err) { - return res.status(500).json({error: 'Failed to clear existing files'}); - } + const deleteExistingFilesSql = 'DELETE FROM SHLFiles WHERE shl_uuid = ?'; - const insertPromises = files.map((f) => { - return new Promise((resolve, reject) => { - const fileId = this.generateUUID(); - const insertFileSql = 'INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)'; - - this.db.run(insertFileSql, [fileId, uuid, f.cnt, f.type], guarded(reject, function (err) { - if (err) { - reject(err); - } else { - resolve(); - } - })); - }); - }); + try { + this.db.run(deleteExistingFilesSql, [uuid]); + } catch (err) { + return res.status(500).json({error: 'Failed to clear existing files'}); + } - Promise.all(insertPromises) - .then(() => { - res.json({msg: 'ok'}); - }) - .catch((error) => { - shlLog.error('File upload error:', error); - res.status(500).json({error: 'Failed to upload files'}); - }); - })); - })); + try { + const insertFileSql = 'INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)'; + for (const f of files) { + this.db.run(insertFileSql, [this.generateUUID(), uuid, f.cnt, f.type]); + } + res.json({msg: 'ok'}); + } catch (error) { + shlLog.error('File upload error:', error); + res.status(500).json({error: 'Failed to upload files'}); + } } finally { this.stats.countRequest('upload', Date.now() - start); } @@ -862,77 +819,80 @@ class SHLModule { (req.connection.socket ? req.connection.socket.remoteAddress : null) || req.headers['x-forwarded-for'] || 'unknown'; - const checkSHLSql = 'SELECT uuid, vhl FROM SHL WHERE uuid = ? AND expires_at > datetime("now")'; + // expires_at is an ISO string: compared as text with datetime('now'), the 'T' kept a link alive to the end of its last day + const checkSHLSql = "SELECT uuid, vhl FROM SHL WHERE uuid = ? AND datetime(expires_at) > datetime('now')"; - this.db.get(checkSHLSql, [uuid], guarded(failRequest(res), (err, shlRow) => { - if (err) { - return res.status(500).json({error: 'Database error'}); - } + let shlRow; + try { + shlRow = this.db.get(checkSHLSql, [uuid]); + } catch (err) { + return res.status(500).json({error: 'Database error'}); + } - if (!shlRow) { - return res.status(404).json({error: 'SHL entry not found or expired'}); - } + if (!shlRow) { + return res.status(404).json({error: 'SHL entry not found or expired'}); + } - const logAccessSql = 'INSERT INTO SHLViews (shl_uuid, recipient, ip_address) VALUES (?, ?, ?)'; + const logAccessSql = 'INSERT INTO SHLViews (shl_uuid, recipient, ip_address) VALUES (?, ?, ?)'; - this.db.run(logAccessSql, [uuid, recipient, clientIP], guarded(failRequest(res), (logErr) => { - if (logErr) { - shlLog.error('Failed to log SHL access:', logErr.message); - } + try { + this.db.run(logAccessSql, [uuid, recipient, clientIP]); + } catch (logErr) { + shlLog.error('Failed to log SHL access:', logErr.message); + } - const getFilesSql = 'SELECT id, cnt, type FROM SHLFiles WHERE shl_uuid = ?'; + const getFilesSql = 'SELECT id, cnt, type FROM SHLFiles WHERE shl_uuid = ?'; - this.db.all(getFilesSql, [uuid], guarded(failRequest(res), (err, fileRows) => { - if (err) { - return res.status(500).json({error: 'Failed to retrieve files'}); - } + let fileRows; + try { + fileRows = this.db.all(getFilesSql, [uuid]); + } catch (err) { + return res.status(500).json({error: 'Failed to retrieve files'}); + } - // U flag: return the one file directly - if (isGet && !shlRow.vhl && fileRows.length === 1) { - try { - res.set('Content-Type', 'application/jose'); - return res.send(Buffer.from(fileRows[0].cnt, 'base64')); - } catch (decodeErr) { - return res.status(500).json({error: 'Failed to decode file content'}); - } - } + // U flag: return the one file directly + if (isGet && !shlRow.vhl && fileRows.length === 1) { + try { + res.set('Content-Type', 'application/jose'); + return res.send(Buffer.from(fileRows[0].cnt, 'base64')); + } catch (decodeErr) { + return res.status(500).json({error: 'Failed to decode file content'}); + } + } - // SHL links are always https; the server always sits behind an https proxy - const host = req.get('host') || 'localhost:3000'; - const maxLength = embeddedLengthMax ? parseInt(embeddedLengthMax) : undefined; + // SHL links are always https; the server always sits behind an https proxy + const host = req.get('host') || 'localhost:3000'; + const maxLength = embeddedLengthMax ? parseInt(embeddedLengthMax) : undefined; - const files = fileRows.map(file => { - const fileResponse = { - contentType: file.type, - location: `https://${host}/shl/file/${file.id}` - }; + const files = fileRows.map(file => { + const fileResponse = { + contentType: file.type, + location: `https://${host}/shl/file/${file.id}` + }; - // cnt is stored base64-encoded; embedded must be the JWE compact serialization itself - const jwe = Buffer.from(file.cnt, 'base64').toString('utf8'); - if (maxLength === undefined || jwe.length <= maxLength) { - fileResponse.embedded = jwe; - } + // cnt is stored base64-encoded; embedded must be the JWE compact serialization itself + const jwe = Buffer.from(file.cnt, 'base64').toString('utf8'); + if (maxLength === undefined || jwe.length <= maxLength) { + fileResponse.embedded = jwe; + } - return fileResponse; - }); + return fileResponse; + }); - // finalized: content is fixed for the life of the link (expired links 404 above) - const standardResponse = {status: 'finalized', files}; + // finalized: content is fixed for the life of the link (expired links 404 above) + const standardResponse = {status: 'finalized', files}; - if (shlRow.vhl && vhlProcessor) { - try { - const vhlResponse = vhlProcessor.processVHL(host, uuid, standardResponse); - res.json(vhlResponse); - } catch (vhlErr) { - shlLog.error('VHL processing error:', vhlErr.message); - res.json(standardResponse); - } - } else { - res.json(standardResponse); - } - })); - })); - })); + if (shlRow.vhl && vhlProcessor) { + try { + const vhlResponse = vhlProcessor.processVHL(host, uuid, standardResponse); + res.json(vhlResponse); + } catch (vhlErr) { + shlLog.error('VHL processing error:', vhlErr.message); + res.json(standardResponse); + } + } else { + res.json(standardResponse); + } } finally { this.stats.countRequest('access', Date.now() - start); } @@ -943,7 +903,7 @@ class SHLModule { this.router.post('/access/:uuid', this.validateJsonBody(['recipient'], ['embeddedLengthMax']), handleSHLAccess); // SHL file endpoint - serves individual files - this.router.get('/file/:fileId', (req, res, next) => { + this.router.get('/file/:fileId', (req, res) => { const start = Date.now(); try { const {fileId} = req.params; @@ -957,40 +917,36 @@ class SHLModule { (req.connection.socket ? req.connection.socket.remoteAddress : null) || req.headers['x-forwarded-for'] || 'unknown'; - const getFileSql = 'SELECT id, shl_uuid, cnt, type FROM SHLFiles WHERE id = ?'; + // only while its link is live: an expired link's files are not served (cleanup deletes them later) + const getFileSql = "SELECT f.id, f.shl_uuid, f.cnt, f.type FROM SHLFiles f JOIN SHL s ON s.uuid = f.shl_uuid WHERE f.id = ? AND datetime(s.expires_at) > datetime('now')"; - this.db.get(getFileSql, [fileId], guarded(next, (err, fileRow) => { - if (err) { - return res.status(500).json({error: 'Database error'}); - } - - if (!fileRow) { - return res.status(404).json({error: 'File not found'}); - } + let fileRow; + try { + fileRow = this.db.get(getFileSql, [fileId]); + } catch (err) { + return res.status(500).json({error: 'Database error'}); + } - const logMasterAccessSql = 'INSERT INTO SHLViews (shl_uuid, recipient, ip_address) VALUES (?, ?, ?)'; - const logFileAccessSql = 'INSERT INTO SHLViews (shl_uuid, recipient, ip_address) VALUES (?, ?, ?)'; + if (!fileRow) { + return res.status(404).json({error: 'File not found'}); + } - this.db.run(logMasterAccessSql, [fileRow.shl_uuid, null, clientIP], guarded(next, function (logErr) { - if (logErr) { - shlLog.error('Failed to log master SHL file access:', logErr.message); - } - })); + // one view, of the link the file belongs to + const logAccessSql = 'INSERT INTO SHLViews (shl_uuid, recipient, ip_address) VALUES (?, ?, ?)'; - this.db.run(logFileAccessSql, [fileRow.id, null, clientIP], guarded(next, function (logErr) { - if (logErr) { - shlLog.error('Failed to log file-specific access:', logErr.message); - } - })); + try { + this.db.run(logAccessSql, [fileRow.shl_uuid, null, clientIP]); + } catch (logErr) { + shlLog.error('Failed to log SHL file access:', logErr.message); + } - try { - const fileBuffer = Buffer.from(fileRow.cnt, 'base64'); - res.set('Content-Type', 'application/jose'); - res.send(fileBuffer); - } catch (decodeErr) { - res.status(500).json({error: 'Failed to decode file content'}); - } - })); + try { + const fileBuffer = Buffer.from(fileRow.cnt, 'base64'); + res.set('Content-Type', 'application/jose'); + res.send(fileBuffer); + } catch (decodeErr) { + res.status(500).json({error: 'Failed to decode file content'}); + } } finally { this.stats.countRequest('file', Date.now() - start); } @@ -1117,8 +1073,7 @@ class SHLModule { if (!this.db) { return 'The database is not open.'; } - const get = (sql, params) => new Promise((resolve, reject) => - this.db.get(sql, params, guarded(reject, (err, row) => err ? reject(err) : resolve(row)))); + const get = (sql, params) => this.db.get(sql, params); // created_at is CURRENT_TIMESTAMP: UTC, 'YYYY-MM-DD HH:MM:SS' const utc = ms => new Date(ms).toISOString().replace('T', ' ').substring(0, 19); try { @@ -1156,16 +1111,12 @@ class SHLModule { } if (this.db) { - return new Promise((resolve, reject) => { - this.db.close(guarded(reject, (err) => { - if (err) { - shlLog.error('Error closing SHL database:', err.message); - } else { - shlLog.info('SHL database connection closed'); - } - resolve(); - })); - }); + try { + this.db.close(); + shlLog.info('SHL database connection closed'); + } catch (err) { + shlLog.error('Error closing SHL database:', err.message); + } } } diff --git a/tests/cs/cs-mimetypes.test.js b/tests/cs/cs-mimetypes.test.js index 0ab07fb36..9ae43d50a 100644 --- a/tests/cs/cs-mimetypes.test.js +++ b/tests/cs/cs-mimetypes.test.js @@ -98,7 +98,8 @@ describe('MimeTypeServices', () => { for (const invalidType of invalidMimeTypes) { const result = await provider.locate(invalidType); expect(result.context).toBeNull(); - expect(result.message).toBeUndefined(); + // why (RFC 9110 section 8.3.1), and where + expect(result.message).toMatch(/^The code '.*' isn't a valid media type \(RFC 9110 section 8\.3\.1\): the error is at character \d+$/); } const result = await provider.locate(''); @@ -106,7 +107,7 @@ describe('MimeTypeServices', () => { expect(result.message).toContain('Empty code'); }); - test('should handle whitespace in MIME types', async () => { + test('whitespace around a MIME type makes it invalid (RFC 9110 section 8.3.1)', async () => { const mimeTypesWithWhitespace = [ ' text/plain ', '\ttext/html\t', @@ -116,8 +117,7 @@ describe('MimeTypeServices', () => { for (const mimeType of mimeTypesWithWhitespace) { const result = await provider.locate(mimeType); - expect(result.context).toBeTruthy(); - expect(result.message).toBeNull(); + expect(result.context).toBeNull(); } }); }); @@ -131,18 +131,12 @@ describe('MimeTypeServices', () => { }); test('should return null for invalid MIME types', async () => { - await expect(provider.code('invalid-mime-type')).rejects.toThrow("Invalid MIME type 'invalid-mime-type'"); + await expect(provider.code('invalid-mime-type')).rejects.toThrow("The code 'invalid-mime-type' isn't a valid media type"); }); - test('should return correct display (trimmed code)', async () => { - const testMimeType = ' text/plain '; - const result = await provider.locate(testMimeType); - const display = await provider.display(result.context); - expect(display).toBe('text/plain'); - }); test('should throw error for invalid MIME types', async () => { - await expect(provider.display('invalid')).rejects.toThrow("Invalid MIME type 'invalid'"); + await expect(provider.display('invalid')).rejects.toThrow("The code 'invalid' isn't a valid media type"); }); test('should return null definition', async () => { diff --git a/tests/cs/cs-snomed-ecl.test.js b/tests/cs/cs-snomed-ecl.test.js index 6d3d11b9d..4602dc6ff 100644 --- a/tests/cs/cs-snomed-ecl.test.js +++ b/tests/cs/cs-snomed-ecl.test.js @@ -376,6 +376,20 @@ describe('ECL Validator Test Suite', () => { expect(await count('<< 105590001 : R 363698007 = *')).toBe(0); }); + test('R 116680003 |Is a| is the parents (triage B6): is-a is an attribute in either direction', async () => { + for (const x of ['126081001', '763158003', '105590001']) { + const parents = await codes('>! ' + x); + expect(parents.length).toBeGreaterThan(0); + expect(await codes('* : R 116680003 = ' + x)).toEqual(parents); + expect(await codes('* : 116680003 = ' + x)).toEqual(await codes('! 126081001 OR >! 763158003')); + expect(await codes('* : R * = 126081001')).toEqual(expect.arrayContaining(await codes('>! 126081001'))); + // a reversed attribute other than is-a still leaves the parents out + expect(await codes('* : R 127489000 = 776168003')).toEqual(['126081001']); + }); + test('a comma is a conjunction at the expression level', async () => { expect(await codes('138875005 , 138875005')).toEqual(['138875005']); expect(await count('138875005 , 10200004')).toBe(0); @@ -708,8 +722,9 @@ describe('ECL Validator Test Suite', () => { }); test('should handle numeric literals correctly', async () => { - const lexer = new ECLLexer('123 -456 78.9 -12.34'); - const tokens = lexer.tokenize(); + // a number with a decimal point is only lexed as one after # (a dotted attribute is A.B) + const lexer = new ECLLexer('123 -456 #78.9 -12.34'); + const tokens = lexer.tokenize().filter(t => t.type !== ECLTokenType.HASH); // With Option 1: all positive digit sequences are treated as SCTIDs expect(tokens[0]).toMatchObject({ @@ -721,7 +736,7 @@ describe('ECL Validator Test Suite', () => { type: ECLTokenType.INTEGER, value: '-456' }); - // Decimal sequences parsed as SCTID (will be validated semantically) + // Decimal sequences after # expect(tokens[2]).toMatchObject({ type: ECLTokenType.DECIMAL, value: '78.9' diff --git a/tests/cs/mimetype-case.test.js b/tests/cs/mimetype-case.test.js index 6e866e432..1657ea7a6 100644 --- a/tests/cs/mimetype-case.test.js +++ b/tests/cs/mimetype-case.test.js @@ -68,7 +68,7 @@ describe('media type case folding', () => { ['a boundary value, which is case sensitive', 'multipart/form-data; BOUNDARY=AbC123', 'multipart/form-data; boundary=AbC123'], ['a profile value, which may be a case-sensitive URI', - 'application/fhir+json; Profile=http://Example.org/X', 'application/fhir+json; profile=http://Example.org/X'], + 'application/fhir+json; Profile="http://Example.org/X"', 'application/fhir+json; profile="http://Example.org/X"'], ['a version value, since no general definition says it folds', 'Text/Plain; Version=1.0A', 'text/plain; version=1.0A'], ['an unknown parameter value', 'TEXT/Plain; Foo=BaR', 'text/plain; foo=BaR'] @@ -100,18 +100,18 @@ describe('media type case folding', () => { test.each([ ['no space after the semicolon', 'text/plain;charset=UTF-8', 'text/plain; charset=utf-8'], - ['too much space', 'text/plain; charset=UTF-8 ', 'text/plain; charset=utf-8'], - ['space around the type', ' text/plain ', 'text/plain'], + ['too much space', 'text/plain ; charset=UTF-8', 'text/plain; charset=utf-8'], ['a trailing semicolon', 'text/plain;', 'text/plain'] ])('spacing is canonicalised: %s', (_label, submitted, expected) => { expect(new MimeTypeConcept(submitted).normalized).toBe(expected); }); - test('a segment that is not name=value is carried through untouched', () => { - // the parser ignores it, but the canonical form must not claim the code said less than - // it did. Its case is left alone: only parameter NAMES fold, and there is nothing here - // to say this is one - expect(new MimeTypeConcept('TEXT/PLAIN; Broken').normalized).toBe('text/plain; Broken'); + test('what isn\'t a media type by the RFC grammar isn\'t valid, and isn\'t normalised', () => { + // a segment that is not name=value, whitespace around the type, an unquoted URI + for (const code of ['TEXT/PLAIN; Broken', ' text/plain ', 'text/plain; profile=http://example.org/X']) { + expect(new MimeTypeConcept(code).isValid()).toBe(false); + expect(new MimeTypeConcept(code).normalized).toBe(code); + } }); test('reordering is a normal-form difference, not a case difference', () => { @@ -148,7 +148,7 @@ describe('media type case folding', () => { ['a delsp value', 'text/plain; delsp=YES', 'text/plain; delsp=yes'], ['everything at once', 'TEXT/PLAIN; CharSet=UTF-8; Format=Flowed', 'text/plain; charset=utf-8; format=flowed'], ['the name of a parameter the server does not understand', - 'application/fhir+json; PROFILE=http://example.org/X', 'application/fhir+json; profile=http://example.org/X'] + 'application/fhir+json; PROFILE="http://example.org/X"', 'application/fhir+json; profile="http://example.org/X"'] ])('a difference of case in %s is not a difference', async (_label, a, b) => { expect(await outcome(a, b)).toBe('equivalent'); }); diff --git a/tests/data/fhirpath-check-java.json b/tests/data/fhirpath-check-java.json index 8b0b5ec2c..ab492f0cd 100644 --- a/tests/data/fhirpath-check-java.json +++ b/tests/data/fhirpath-check-java.json @@ -1384,7 +1384,7 @@ "$this is Period implies ($this is dateTime implies $this.toString().length() >= 10)\tObservation.effective\tPeriod|Timing\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"}, "$this is Element implies $this.toString().length() >= 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"error":"PathEngineException: Error evaluating FHIRPath expression: The function toString can only be used on primitives, but this type is [http://hl7.org/fhir/StructureDefinition/Period] (@char 32)"}, "$this.start is dateTime implies $this.toString().length() >= 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"error":"PathEngineException: Error evaluating FHIRPath expression: The function toString can only be used on primitives, but this type is [http://hl7.org/fhir/StructureDefinition/Period] (@char 39)"}, - "$this.ofType(dateTime).toString().length() >= 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]","warnings":["FHIRPATH_OFTYPE_IMPOSSIBLE: The type specified in ofType() is http://hl7.org/fhir/StructureDefinition/dateTime which is not a possible candidate for the existing types (FHIR.Period) in the expression ofType(dateTime).toString().length(). Check the paths and types to be sure this is what is intended"]}, + "$this.ofType(dateTime).toString().length() >= 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"}, "($this as dateTime).toString().length() >= 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"}, "Bundle.section('http://loinc.org', '11450-4').count()\t\t\tbundle-document-ips.json\tcustom" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"}, "Bundle.section('http://loinc.org', '11450-4').title\t\t\tbundle-document-ips.json\tcustom" : {"types":"ORDERED[http://hl7.org/fhir/StructureDefinition/string]"}, diff --git a/tests/extension-tracker/submitted-content.test.js b/tests/extension-tracker/submitted-content.test.js index 642e3ec60..40fed1585 100644 --- a/tests/extension-tracker/submitted-content.test.js +++ b/tests/extension-tracker/submitted-content.test.js @@ -50,8 +50,8 @@ describe('extension tracker: submitted content', () => { }); }); - afterAll(() => { - module.shutdown(); + afterAll(async () => { + await module.shutdown(); jest.restoreAllMocks(); fs.rmSync(dir, { recursive: true, force: true }); }); @@ -129,8 +129,8 @@ describe('extension tracker: submitting', () => { await module.initialize({ database: path.join(dir, 'ext.db'), token: 'the-token' }, app); }); - afterAll(() => { - module.shutdown(); + afterAll(async () => { + await module.shutdown(); jest.restoreAllMocks(); fs.rmSync(dir, { recursive: true, force: true }); }); @@ -146,21 +146,21 @@ describe('extension tracker: submitting', () => { .send({ ...PUBLISHER, package: 'other.pkg', profiles: { [EVIL]: [{ url: 'http://x/p' }] } }); expect(res.status).toBe(400); expect(res.body.issues.join()).toMatch(/is not a resource type/); - expect(module.db.prepare('SELECT COUNT(*) AS n FROM packages WHERE package = ?').get('other.pkg').n).toBe(0); - expect(module.db.prepare('SELECT COUNT(*) AS n FROM submissions WHERE package = ?').get('other.pkg').n).toBe(0); + expect(module.db.get('SELECT COUNT(*) AS n FROM packages WHERE package = ?', ['other.pkg']).n).toBe(0); + expect(module.db.get('SELECT COUNT(*) AS n FROM submissions WHERE package = ?', ['other.pkg']).n).toBe(0); }); test('each package id\'s submissions are counted, across the data being replaced, and shown', async () => { const submit = (body) => request(app).post('/ext-tracker').set('Authorization', 'Bearer the-token').send(body); - const before = module.db.prepare('SELECT n FROM submissions WHERE package = ?').get(PUBLISHER.package); + const before = module.db.get('SELECT n FROM submissions WHERE package = ?', [PUBLISHER.package]); const n0 = before ? before.n : 0; expect((await submit(PUBLISHER)).status).toBe(200); expect((await submit({ ...PUBLISHER, version: '9.9.9' })).status).toBe(200); expect((await submit({ ...PUBLISHER, package: 'another.pkg' })).status).toBe(200); - const row = module.db.prepare('SELECT n, since, last_at FROM submissions WHERE package = ?').get(PUBLISHER.package); + const row = module.db.get('SELECT n, since, last_at FROM submissions WHERE package = ?', [PUBLISHER.package]); expect(row.n).toBe(n0 + 2); expect(row.since <= row.last_at).toBe(true); - expect(module.db.prepare('SELECT n FROM submissions WHERE package = ?').get('another.pkg').n).toBe(1); + expect(module.db.get('SELECT n FROM submissions WHERE package = ?', ['another.pkg']).n).toBe(1); const home = await request(app).get('/ext-tracker'); expect(home.text).toContain('Submissions'); @@ -185,8 +185,8 @@ describe('extension tracker: usage of one extension', () => { }); }); - afterAll(() => { - module.shutdown(); + afterAll(async () => { + await module.shutdown(); jest.restoreAllMocks(); fs.rmSync(dir, { recursive: true, force: true }); }); @@ -246,8 +246,8 @@ describe('extension tracker: long values wrap', () => { }); }); - afterAll(() => { - module.shutdown(); + afterAll(async () => { + await module.shutdown(); jest.restoreAllMocks(); fs.rmSync(dir, { recursive: true, force: true }); }); diff --git a/tests/helpers/fhirpath-check-java/FPCheck.java b/tests/helpers/fhirpath-check-java/FPCheck.java index 08ab5e322..d08841851 100644 --- a/tests/helpers/fhirpath-check-java/FPCheck.java +++ b/tests/helpers/fhirpath-check-java/FPCheck.java @@ -2,7 +2,7 @@ // Licensed under BSD-3: https://opensource.org/license/bsd-3-clause // // Makes tests/data/fhirpath-check-java.json: what the Java FHIRPathEngine's check() / checkOnTypes() -// says of each test in the fhir-test-cases FHIRPath suite, as FHIRPathTests runs them, so that +// says of each test (the types, or the error; the type warnings are in fhir-test-cases) in the fhir-test-cases FHIRPath suite, as FHIRPathTests runs them, so that // tests/library/fhir/fhirpath-check.test.js can hold the JS port to it. // // javac -proc:none -cp {cp} FPCheck.java @@ -73,9 +73,8 @@ public static void main(String[] args) throws Exception { else if (!ctxt.isEmpty()) td = fp.check(res, rt, rt, ctxt, node); else if (res == null) td = fp.check(null, null, null, node); else td = fp.check(res, rt, rt, rt, node); - StringBuilder ws = new StringBuilder(); - for (FHIRPathEngine.IssueMessage m : w) { if (ws.length() > 0) ws.append(","); ws.append(esc(m.getId() + ": " + m.getMessage())); } - result = "{\"name\":" + esc(name) + ",\"ok\":true,\"types\":" + esc(td.toString()) + ",\"warnings\":[" + ws + "]}"; + // (the type warnings aren't in the fixture: they're in fhir-test-cases, tests-fhir-r5-warnings.xml) + result = "{\"name\":" + esc(name) + ",\"ok\":true,\"types\":" + esc(td.toString()) + "}"; } catch (org.hl7.fhir.r5.fhirpath.FHIRLexer.FHIRLexerException e) { result = "{\"name\":" + esc(name) + ",\"parse\":" + esc(e.getMessage()) + "}"; } catch (Throwable e) { diff --git a/tests/helpers/fhirpath-check-java/make-fixture.js b/tests/helpers/fhirpath-check-java/make-fixture.js index 84eb8a346..17c904904 100644 --- a/tests/helpers/fhirpath-check-java/make-fixture.js +++ b/tests/helpers/fhirpath-check-java/make-fixture.js @@ -26,11 +26,8 @@ if (process.argv[2] === '--input-types') { cases.forEach((t, i) => { const j = java[i]; if (j.parse === undefined) { - const e = j.ok ? { types: j.types } : { error: j.error }; - if (j.warnings && j.warnings.length) { - e.warnings = j.warnings; - } - results[caseKey(t)] = e; + // (the type warnings aren't here: they're in fhir-test-cases, tests-fhir-r5-warnings.xml) + results[caseKey(t)] = j.ok ? { types: j.types } : { error: j.error }; } }); const entries = Object.entries(results); diff --git a/tests/helpers/fhirpath-check-java/suite.js b/tests/helpers/fhirpath-check-java/suite.js index c38c9b6df..e10e0310c 100644 --- a/tests/helpers/fhirpath-check-java/suite.js +++ b/tests/helpers/fhirpath-check-java/suite.js @@ -6,14 +6,15 @@ /** * The fhir-test-cases FHIRPath suite (r5/fhirpath/tests-fhir-r5.xml), read for the type check tests - * (tests/library/fhir/fhirpath-check.test.js) and the Java fixture they compare with (FPCheck.java). + * (tests/library/fhir/fhirpath-check.test.js) and the Java fixture they compare with (FPCheck.java), + * and its companion, r5/fhirpath/tests-fhir-r5-warnings.xml: the type warnings each test should produce. */ const fs = require('fs'); const { XMLParser } = require('fast-xml-parser'); const { testCaseFile } = require('../fhir-test-cases'); -/** The tests, in order: {name, expression, invalid, mode, inputfile, context, contextType, skipStaticCheck} */ +/** The tests, in order: {name, testName, expression, invalid, mode, inputfile, context, contextType, skipStaticCheck} */ function readSuite() { const xml = fs.readFileSync(testCaseFile('r5/fhirpath/tests-fhir-r5.xml'), 'utf8'); const doc = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '', textNodeName: '#text', isArray: (n) => ['group', 'test'].includes(n) }) @@ -24,6 +25,7 @@ function readSuite() { const e = t.expression; tests.push({ name: `${t.name || '??'} - G ${g.name}[${i + 1}]`, + testName: t.name || null, expression: typeof e === 'object' ? String(e['#text'] ?? '') : String(e), invalid: typeof e === 'object' ? e.invalid || null : null, mode: t.mode || g.mode || null, @@ -63,4 +65,19 @@ function inputType(input) { return inputTypes.get(input); } -module.exports = { readSuite, checkedCases, caseKey, inputType }; +/** + * The type warnings the tests should produce when they're checked (tests-fhir-r5-warnings.xml), by + * test name: the messages, as text. A test that isn't there should produce none + */ +function readTypeWarnings() { + const xml = fs.readFileSync(testCaseFile('r5/fhirpath/tests-fhir-r5-warnings.xml'), 'utf8'); + const doc = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '', textNodeName: '#text', isArray: (n) => ['test', 'warning'].includes(n) }) + .parse(xml); + const map = new Map(); + for (const t of (doc.warnings && doc.warnings.test) || []) { + map.set(t.name, (t.warning || []).map(w => typeof w === 'object' ? String(w['#text'] ?? '') : String(w))); + } + return map; +} + +module.exports = { readSuite, checkedCases, caseKey, inputType, readTypeWarnings }; diff --git a/tests/library/fhir/fhirpath-check.test.js b/tests/library/fhir/fhirpath-check.test.js index af7a61499..b450930f0 100644 --- a/tests/library/fhir/fhirpath-check.test.js +++ b/tests/library/fhir/fhirpath-check.test.js @@ -7,8 +7,9 @@ // library/fhir/fhirpath/fhirpath-engine.js: the FHIRPath type checking, against the fhir-test-cases // FHIRPath suite as the Java FHIRPathTests runs it (each test is checked, on its contextType, its // context, or its input's type, unless it says skipStaticCheck: a test marked invalid="semantic" -// must fail the check, and every other test must pass it), with the same types, errors and -// warnings as the Java engine (tests/data/fhirpath-check-java.json); and the parts on their own. +// must fail the check, and every other test must pass it), with the same types and errors as the +// Java engine (tests/data/fhirpath-check-java.json), and the type warnings the suite says it should +// produce (fhir-test-cases r5/fhirpath/tests-fhir-r5-warnings.xml); and the parts on their own. const fs = require('fs'); const path = require('path'); @@ -20,7 +21,7 @@ const { FHIRPathEngine, PathEngineException, FHIRPathConstantEvaluationMode } = const { BaseHostServices, TERMINOLOGY_FUNCTIONS } = require('../../../library/fhir/fhirpath/base-host-services'); const { TypeDetails, ProfiledType, javaHashSetOrder, FP_String, FP_Integer, FP_Boolean } = require('../../../library/fhir/fhirpath/type-details'); const { CollectionStatus } = require('../../../library/fhir/fhirpath/expression-node'); -const { readSuite, checkedCases, caseKey, inputType } = require('../../helpers/fhirpath-check-java/suite'); +const { readSuite, checkedCases, caseKey, inputType, readTypeWarnings } = require('../../helpers/fhirpath-check-java/suite'); const SD = 'http://hl7.org/fhir/StructureDefinition/'; @@ -37,6 +38,10 @@ async function loadContext() { const name = await new PackageManager(['https://packages2.fhir.org/packages', 'https://packages.fhir.org'], cache).fetch('hl7.fhir.r5.core', '5.0.0'); const c = new StructureDefinitionContext(); c.seeAll(readStructureDefinitions(path.isAbsolute(name) ? name : path.join(cache, name)), { id: 'hl7.fhir.r5.core', version: '5.0.0' }); + // as Java's FHIRPathTests (TestingUtilities.getSharedWorkerContext): the extensions pack too, so + // the extensions the tests use are known + const ext = await new PackageManager(['https://packages2.fhir.org/packages', 'https://packages.fhir.org'], cache).fetch('hl7.fhir.uv.extensions', '5.2.0'); + c.seeAll(readStructureDefinitions(path.isAbsolute(ext) ? ext : path.join(cache, ext)), { id: 'hl7.fhir.uv.extensions', version: '5.2.0' }); return c; } @@ -72,10 +77,9 @@ function checkTest(engine, t) { try { const rt = t.inputfile ? inputType(t.inputfile) : null; const res = t.inputfile ? { resourceType: rt } : null; - const warnings = []; let types; if (t.contextType) { - types = engine.checkOnTypes(res, rt, rt, t.contextType.split('|'), node, warnings); + types = engine.checkOnTypes(res, rt, rt, t.contextType.split('|'), node, []); } else if (t.context) { types = engine.check(res, rt, rt, t.context, node); } else if (res == null) { @@ -83,7 +87,8 @@ function checkTest(engine, t) { } else { types = engine.check(res, rt, rt, rt, node); } - return { types, warnings }; + // the warnings from any form of the check (the engine is new for each test) + return { types, warnings: engine.getTypeWarnings() }; } catch (e) { return { check: e, warnings: [] }; } @@ -96,12 +101,15 @@ const PARSER_STRICTER = new Set(['text.div.htmlChecks()', '@T14:34:28Z.is(Time)' describe('the fhir-test-cases FHIRPath suite (r5/fhirpath/tests-fhir-r5.xml)', () => { const suite = readSuite(); const cases = checkedCases(suite); + const typeWarnings = readTypeWarnings(); test('the suite is there', () => { expect(suite.length).toBeGreaterThan(1000); expect(suite.filter(t => t.invalid === 'semantic').length).toBeGreaterThan(20); // most have the Java engine's answer to compare with expect(cases.filter(t => JAVA.results[caseKey(t)]).length).toBeGreaterThan(cases.length * 0.9); + // and the warnings the tests should produce + expect(typeWarnings.size).toBeGreaterThan(20); }); test.each(cases.map(t => [t.name, t]))('%s', (name, t) => { @@ -120,13 +128,14 @@ describe('the fhir-test-cases FHIRPath suite (r5/fhirpath/tests-fhir-r5.xml)', ( } else if (r.check) { throw new Error(`Unexpected exception checking '${t.expression}': ${r.check.message}`); } - // and what the Java engine said, exactly: the types, or the error, and the warnings + // the type warnings the suite says it should produce (tests-fhir-r5-warnings.xml) + if (!r.check) { + expect(r.warnings.map(w => w.message)).toEqual(typeWarnings.get(t.testName) || []); + } + // and what the Java engine said, exactly: the types, or the error const java = JAVA.results[caseKey(t)]; if (java) { const js = r.check ? { error: (r.check instanceof PathEngineException ? 'PathEngineException' : r.check.constructor.name) + ': ' + r.check.message } : { types: r.types.toString() }; - if (r.warnings.length) { - js.warnings = r.warnings.map(w => w.id + ': ' + w.message); - } expect(js).toEqual(java); } }); diff --git a/tests/library/sql/node-sqlite.test.js b/tests/library/sql/node-sqlite.test.js new file mode 100644 index 000000000..50f9a8125 --- /dev/null +++ b/tests/library/sql/node-sqlite.test.js @@ -0,0 +1,230 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { SqliteDatabase, SqliteWorkerPool } = require('../../../library/sql/node-sqlite'); + +// a good part of a second of work for SQLite, on one connection +const SLOW_COUNT = 12000000; +const SLOW = `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < ${SLOW_COUNT}) SELECT COUNT(*) AS n FROM c`; + +describe('SqliteDatabase', () => { + let db; + beforeEach(() => { + db = new SqliteDatabase(':memory:'); + db.exec('CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT, b INTEGER, p INTEGER REFERENCES parent (id))'); + }); + afterEach(() => db.close()); + + test('binds undefined as NULL and booleans as 1 and 0, as sqlite3 did', () => { + const r = db.run('INSERT INTO t (a, b) VALUES (?, ?)', [undefined, true]); + expect(r).toEqual({ lastID: 1, changes: 1 }); + db.run('INSERT INTO t (a, b) VALUES (?, ?)', ['x', false]); + expect(db.all('SELECT a, b FROM t ORDER BY id')).toEqual([{ a: null, b: 1 }, { a: 'x', b: 0 }]); + }); + + test('rows are ordinary objects; no row is undefined', () => { + db.run('INSERT INTO t (a) VALUES (?)', ['x']); + expect(Object.getPrototypeOf(db.get('SELECT * FROM t'))).toBe(Object.prototype); + expect(db.get('SELECT * FROM t WHERE id = ?', [99])).toBeUndefined(); + }); + + test('foreign keys are not enforced unless asked for', () => { + expect(() => db.run('INSERT INTO t (p) VALUES (?)', [42])).not.toThrow(); + const strict = new SqliteDatabase(':memory:', { enableForeignKeyConstraints: true }); + strict.exec('CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE t (p INTEGER REFERENCES parent (id))'); + expect(() => strict.run('INSERT INTO t (p) VALUES (?)', [42])).toThrow(/FOREIGN KEY/); + strict.close(); + }); + + test('a transaction commits when fn returns, and rolls back when it throws', () => { + expect(db.transaction(() => db.run('INSERT INTO t (a) VALUES (?)', ['in']).lastID)).toBe(1); + expect(() => db.transaction(() => { + db.run('INSERT INTO t (a) VALUES (?)', ['lost']); + throw new Error('stop'); + })).toThrow('stop'); + expect(db.all('SELECT a FROM t').map(r => r.a)).toEqual(['in']); + // and the connection is usable after + db.transaction(() => db.run('INSERT INTO t (a) VALUES (?)', ['after'])); + expect(db.get('SELECT COUNT(*) AS n FROM t').n).toBe(2); + }); + + test('a prepared statement takes its parameters as an array', () => { + const insert = db.statement('INSERT INTO t (a, b) VALUES (?, ?)'); + insert.run(['one', true]); + insert.run(['two', undefined]); + const select = db.statement('SELECT a, b FROM t WHERE a = ?'); + expect(select.get(['two'])).toEqual({ a: 'two', b: null }); + expect(db.statement('SELECT a FROM t ORDER BY id').all([]).map(r => r.a)).toEqual(['one', 'two']); + }); +}); + +describe('SqliteWorkerPool', () => { + let dir; + let file; + let pool; + + beforeAll(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'node-sqlite-pool-')); + file = path.join(dir, 'test.db'); + const db = new SqliteDatabase(file); + db.exec('PRAGMA journal_mode = WAL; CREATE TABLE t (id INTEGER PRIMARY KEY, a TEXT, b INTEGER)'); + db.transaction(() => { + for (let i = 1; i <= 100; i++) { + db.run('INSERT INTO t (a, b) VALUES (?, ?)', ['row' + i, i % 2 === 0]); + } + }); + db.close(); + }); + + afterEach(async () => { + if (pool) { + await pool.close(); + pool = null; + } + }); + + afterAll(() => fs.rmSync(dir, { recursive: true, force: true })); + + test('reads, with ordinary rows and the bindings sqlite3 allowed', async () => { + pool = await SqliteWorkerPool.open(file, { size: 2 }); + expect(pool.size).toBe(2); + const row = await pool.get('SELECT a, b FROM t WHERE id = ?', [2]); + expect(row).toEqual({ a: 'row2', b: 1 }); + // an ordinary object (from the worker it is the main realm's Object, which isn't jest's, so not toBe) + expect(Object.getPrototypeOf(row)).not.toBeNull(); + expect(typeof row.toString).toBe('function'); + expect(await pool.get('SELECT * FROM t WHERE id = ?', [999])).toBeUndefined(); + expect((await pool.all('SELECT id FROM t WHERE b = ?', [true])).length).toBe(50); + expect(await pool.get('SELECT COUNT(*) AS n FROM t WHERE a IS ?', [undefined])).toEqual({ n: 0 }); + }); + + test('read-only unless asked otherwise', async () => { + pool = await SqliteWorkerPool.open(file); + await expect(pool.run('INSERT INTO t (a) VALUES (?)', ['x'])).rejects.toThrow(/readonly/i); + await pool.close(); + pool = await SqliteWorkerPool.open(file, { readOnly: false, pragmas: ['PRAGMA busy_timeout = 5000'] }); + const r = await pool.run('INSERT INTO t (a) VALUES (?)', ['written']); + expect(r.changes).toBe(1); + expect((await pool.get('SELECT a FROM t WHERE id = ?', [r.lastID])).a).toBe('written'); + await pool.run('DELETE FROM t WHERE id = ?', [r.lastID]); + }); + + test('an error keeps its SQLite details and says which SQL', async () => { + pool = await SqliteWorkerPool.open(file); + const err = await pool.all('SELECT * FROM nope').catch(e => e); + expect(err).toBeInstanceOf(Error); + expect(err.message).toMatch(/no such table: nope/); + expect(err.code).toBe('ERR_SQLITE_ERROR'); + expect(err.sql).toBe('SELECT * FROM nope'); + // and the worker carries on + expect((await pool.get('SELECT COUNT(*) AS n FROM t')).n).toBe(100); + }); + + test('more queries than workers: they queue, and all are answered', async () => { + pool = await SqliteWorkerPool.open(file, { size: 2 }); + const answers = await Promise.all(Array.from({ length: 25 }, (_, i) => pool.get('SELECT a FROM t WHERE id = ?', [i + 1]))); + expect(answers.map(r => r.a)).toEqual(Array.from({ length: 25 }, (_, i) => 'row' + (i + 1))); + expect(pool.pending).toBe(0); + }); + + test('a slow query does not hold the event loop, nor the other workers', async () => { + pool = await SqliteWorkerPool.open(file, { size: 2 }); + let ticks = 0; + const timer = setInterval(() => ticks++, 10); + try { + const started = Date.now(); + const slow = pool.get(SLOW); + // the other worker answers while the slow one runs + expect((await pool.get('SELECT a FROM t WHERE id = 1')).a).toBe('row1'); + const quickAt = Date.now() - started; + expect((await slow).n).toBe(SLOW_COUNT); + const slowTook = Date.now() - started; + expect(quickAt).toBeLessThan(slowTook / 2); + // the timer kept firing (it couldn't at all if the query ran on this thread) + expect(ticks).toBeGreaterThan(slowTook / 10 / 3); + } finally { + clearInterval(timer); + } + }); + + test('a worker that dies fails its query, and is replaced', async () => { + pool = await SqliteWorkerPool.open(file, { size: 1 }); + const slow = pool.get(SLOW); + const waiting = pool.get('SELECT a FROM t WHERE id = 3'); + await new Promise(resolve => setTimeout(resolve, 50)); + await pool.slots[0].worker.terminate(); + await expect(slow).rejects.toThrow(/stopped while running the query/); + // the one waiting runs on the replacement + expect((await waiting).a).toBe('row3'); + expect((await pool.get('SELECT COUNT(*) AS n FROM t')).n).toBe(100); + }); + + test('close lets a running query finish, fails those waiting, and refuses new ones', async () => { + pool = await SqliteWorkerPool.open(file, { size: 1 }); + const running = pool.get(SLOW); + const waiting = pool.get('SELECT 1 AS one'); + await new Promise(resolve => setTimeout(resolve, 20)); + const closing = pool.close(); + await expect(waiting).rejects.toThrow(/closed before the query ran/); + expect((await running).n).toBe(SLOW_COUNT); + await closing; + await expect(pool.get('SELECT 1')).rejects.toThrow(/closed/); + expect(pool.slots.every(slot => slot.worker === null)).toBe(true); + pool = null; + }); + + test('connections reading a WAL database for the first time all at once wait for each other, not fail', async () => { + // the first read sets up the WAL index under a lock: without a busy timeout the others got + // 'database is locked' (about a third of the time) + for (let i = 0; i < 10; i++) { + const walFile = path.join(dir, `wal-${i}.db`); + const db = new SqliteDatabase(walFile); + db.exec('PRAGMA journal_mode = WAL; CREATE TABLE t (id INTEGER PRIMARY KEY, a TEXT)'); + db.transaction(() => { + for (let k = 1; k <= 20; k++) { + db.run('INSERT INTO t (a) VALUES (?)', ['x' + k]); + } + }); + db.close(); + pool = await SqliteWorkerPool.open(walFile, { size: 4 }); + const rows = await Promise.all(Array.from({ length: 20 }, (_, k) => pool.get('SELECT a FROM t WHERE id = ?', [k + 1]))); + expect(rows.map(r => r.a)).toEqual(Array.from({ length: 20 }, (_, k) => 'x' + (k + 1))); + await pool.close(); + pool = null; + } + }); + + test('a query waits for a lock another connection holds (busyTimeout), or fails at once with 0', async () => { + const lockFile = path.join(dir, 'lock.db'); + const writer = new SqliteDatabase(lockFile); + writer.exec('CREATE TABLE t (a TEXT); INSERT INTO t VALUES (\'x\')'); // a rollback journal: an exclusive lock keeps readers out + pool = await SqliteWorkerPool.open(lockFile, { size: 1 }); + const impatient = await SqliteWorkerPool.open(lockFile, { size: 1, busyTimeout: 0 }); + try { + writer.exec('BEGIN EXCLUSIVE'); + setTimeout(() => writer.exec('COMMIT'), 200); + await expect(impatient.get('SELECT a FROM t')).rejects.toThrow(/locked/); + expect(await pool.get('SELECT a FROM t')).toEqual({ a: 'x' }); + } finally { + await impatient.close(); + writer.close(); + } + }); + + test('a script that awaits close() carries on after it (the workers keep the process alive while they stop)', () => { + const script = ` + const { SqliteWorkerPool } = require(${JSON.stringify(path.join(__dirname, '../../../library/sql/node-sqlite.js'))}); + (async () => { + const pool = await SqliteWorkerPool.open(':memory:', { readOnly: false }); + await pool.get('SELECT 1'); + await pool.close(); + console.log('after close'); + })();`; + const out = require('child_process').execFileSync(process.execPath, ['--no-warnings', '-e', script], { encoding: 'utf8', timeout: 20000 }); + expect(out.trim()).toBe('after close'); + }); + + test('a database that cannot be opened fails open()', async () => { + await expect(SqliteWorkerPool.open(path.join(dir, 'missing', 'nothing.db'))).rejects.toThrow(/unable to open/i); + }); +}); diff --git a/tests/server/module-daily-reports.test.js b/tests/server/module-daily-reports.test.js index 79f8750e4..bc67d5344 100644 --- a/tests/server/module-daily-reports.test.js +++ b/tests/server/module-daily-reports.test.js @@ -5,6 +5,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); const ServerStats = require('../../stats'); const { ServerRegistries, ServerRegistry, ServerInformation, ServerVersionInformation } = require('../../registry/model'); @@ -103,6 +104,15 @@ function asyncDb(statements) { }); } +// an in-memory node:sqlite database (library/sql/node-sqlite: what publisher and shl use) +function nodeDb(statements) { + const db = new SqliteDatabase(':memory:'); + for (const sql of statements) { + db.exec(sql); + } + return db; +} + const utc = ms => new Date(ms).toISOString().replace('T', ' ').substring(0, 19); describe('module paragraphs', () => { @@ -206,7 +216,7 @@ describe('module paragraphs', () => { test('shl: QR codes created in either form, accesses, and the documents behind them', async () => { const module = Object.create(SHLModule.prototype); - module.db = await asyncDb([ + module.db = nodeDb([ 'CREATE TABLE SHL (uuid TEXT PRIMARY KEY, vhl BOOLEAN, created_at DATETIME)', 'CREATE TABLE SHLFiles (id TEXT, shl_uuid TEXT)', 'CREATE TABLE SHLViews (id INTEGER PRIMARY KEY, shl_uuid TEXT, created_at DATETIME)', @@ -226,7 +236,7 @@ describe('module paragraphs', () => { test('publisher: runs started and finished', async () => { const module = Object.create(PublisherModule.prototype); - module.db = await asyncDb([ + module.db = nodeDb([ "CREATE TABLE tasks (id INTEGER PRIMARY KEY, status TEXT, building_at DATETIME, completed_at DATETIME, failed_at DATETIME)", `INSERT INTO tasks (status, building_at, completed_at) VALUES ('complete', '${utc(SINCE + HOUR)}', '${utc(SINCE + 2 * HOUR)}')`, `INSERT INTO tasks (status, building_at, failed_at) VALUES ('failed', '${utc(SINCE + 3 * HOUR)}', '${utc(SINCE + 4 * HOUR)}')`, diff --git a/tests/shl/shl.test.js b/tests/shl/shl.test.js index 0140e0fc0..69c58965e 100644 --- a/tests/shl/shl.test.js +++ b/tests/shl/shl.test.js @@ -1,6 +1,6 @@ const express = require('express'); const request = require('supertest'); -const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); const jose = require('jose'); const crypto = require('crypto'); const SHLModule = require('../../shl/shl'); @@ -9,10 +9,8 @@ const { setupAuth, makeUser, tokenFor, auth } = require('../helpers/auth'); describe('SHL Module', () => { let app, mod, key, jwe; - const run = (sql, params = []) => new Promise((resolve, reject) => - mod.db.run(sql, params, (err) => err ? reject(err) : resolve())); - const all = (sql, params = []) => new Promise((resolve, reject) => - mod.db.all(sql, params, (err, rows) => err ? reject(err) : resolve(rows))); + const run = async (sql, params = []) => { mod.db.run(sql, params); }; + const all = async (sql, params = []) => mod.db.all(sql, params); const addShl = async (uuid, vhl, fileCount) => { await run('INSERT INTO SHL (uuid, vhl, expires_at, password) VALUES (?, ?, ?, ?)', [uuid, vhl, new Date(Date.now() + 86400000 * 2).toISOString(), 'pw']); @@ -28,7 +26,7 @@ describe('SHL Module', () => { .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', cty: 'application/fhir+json' }) .encrypt(new Uint8Array(key)); mod = new SHLModule({ countRequest: () => {} }); - mod.db = new sqlite3.Database(':memory:'); + mod.db = new SqliteDatabase(':memory:'); await mod.createTables(); await addShl('one', false, 1); await addShl('two', false, 2); @@ -216,4 +214,70 @@ describe('SHL Module', () => { expect((await load(admin)).status).toBe(503); }); }); + + describe('file endpoint', () => { + test('logs one view, of the link the file belongs to', async () => { + const fileId = crypto.randomUUID(); + await run('INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)', + [fileId, 'one', Buffer.from(jwe, 'utf8').toString('base64'), 'application/fhir+json']); + const [{ last }] = await all('SELECT COALESCE(MAX(id), 0) AS last FROM SHLViews'); + const r = await request(app).get('/shl/file/' + fileId); + expect(r.status).toBe(200); + const after = await all('SELECT shl_uuid FROM SHLViews WHERE id > ?', [last]); + expect(after.map(v => v.shl_uuid)).toEqual(['one']); + await run('DELETE FROM SHLFiles WHERE id = ?', [fileId]); + }); + }); + + describe('expiry', () => { + test('a link that expired earlier today is not served, nor are its files', async () => { + const fileId = crypto.randomUUID(); + await run('INSERT INTO SHL (uuid, vhl, expires_at, password) VALUES (?, ?, ?, ?)', + ['just-expired', false, new Date(Date.now() - 60000).toISOString(), 'pw']); + await run('INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)', + [fileId, 'just-expired', Buffer.from(jwe, 'utf8').toString('base64'), 'application/fhir+json']); + expect((await request(app).get('/shl/access/just-expired?recipient=x')).status).toBe(404); + expect((await request(app).post('/shl/access/just-expired').send({ recipient: 'x' })).status).toBe(404); + expect((await request(app).get('/shl/file/' + fileId)).status).toBe(404); + // and it is cleaned up, though its date is today + mod.cleanupExpiredEntries(); + expect(await all("SELECT uuid FROM SHL WHERE uuid = 'just-expired'")).toEqual([]); + expect(await all('SELECT id FROM SHLFiles WHERE id = ?', [fileId])).toEqual([]); + }); + + test('a link that expires later today still is', async () => { + const fileId = crypto.randomUUID(); + await run('INSERT INTO SHL (uuid, vhl, expires_at, password) VALUES (?, ?, ?, ?)', + ['soon', false, new Date(Date.now() + 60000).toISOString(), 'pw']); + await run('INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)', + [fileId, 'soon', Buffer.from(jwe, 'utf8').toString('base64'), 'application/fhir+json']); + expect((await request(app).get('/shl/access/soon?recipient=x')).status).toBe(200); + expect((await request(app).get('/shl/file/' + fileId)).status).toBe(200); + mod.cleanupExpiredEntries(); + expect((await all("SELECT uuid FROM SHL WHERE uuid = 'soon'")).length).toBe(1); + }); + }); + + describe('cleanup', () => { + test('an expired link goes with its files and views, and rows whose link is already gone go too', async () => { + await run('INSERT INTO SHL (uuid, vhl, expires_at, password) VALUES (?, ?, ?, ?)', ['expired', false, '2000-01-01T00:00:00.000Z', 'pw']); + await run('INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)', ['expired-f0', 'expired', 'x', 'x']); + await run('INSERT INTO SHLViews (shl_uuid, recipient) VALUES (?, ?)', ['expired', 'r']); + // left behind by an earlier cleanup, and a view logged against a file id + await run('INSERT INTO SHLFiles (id, shl_uuid, cnt, type) VALUES (?, ?, ?, ?)', ['orphan-f0', 'long-gone', 'x', 'x']); + await run('INSERT INTO SHLViews (shl_uuid, recipient) VALUES (?, ?)', ['one-f0', null]); + const liveFiles = (await all("SELECT id FROM SHLFiles WHERE shl_uuid IN ('one', 'two')")).length; + const liveViews = (await all("SELECT id FROM SHLViews WHERE shl_uuid IN ('one', 'two')")).length; + + mod.cleanupExpiredEntries(); + + expect(await all("SELECT uuid FROM SHL WHERE uuid = 'expired'")).toEqual([]); + expect(await all("SELECT id FROM SHLFiles WHERE shl_uuid IN ('expired', 'long-gone')")).toEqual([]); + expect(await all("SELECT id FROM SHLViews WHERE shl_uuid IN ('expired', 'one-f0')")).toEqual([]); + // the live links keep theirs + expect((await all("SELECT id FROM SHLFiles WHERE shl_uuid IN ('one', 'two')")).length).toBe(liveFiles); + expect((await all("SELECT id FROM SHLViews WHERE shl_uuid IN ('one', 'two')")).length).toBe(liveViews); + expect((await request(app).get('/shl/access/one?recipient=x')).status).toBe(200); + }); + }); }); diff --git a/tests/tx/cache-control.test.js b/tests/tx/cache-control.test.js index d5573dbf6..e18b1ee1f 100644 --- a/tests/tx/cache-control.test.js +++ b/tests/tx/cache-control.test.js @@ -302,15 +302,13 @@ describe('$cache-control routing (scaffolding)', () => { expect(cacheId).toBeDefined(); // The front-loaded ValueSet should now resolve by url under that cache-id. - // (validate still reads cache-id from the parameter in this step; the header - // read path is a later change.) const validated = await request(app) .post('/tx/r5/ValueSet/$validate-code') .set('Content-Type', 'application/json') + .set('X-Cache-Id', cacheId) .send({ resourceType: 'Parameters', parameter: [ - { name: 'cache-id', valueId: cacheId }, { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } ] diff --git a/tests/tx/cache-id.test.js b/tests/tx/cache-id.test.js index 0f477c854..57ef2d3dd 100644 --- a/tests/tx/cache-id.test.js +++ b/tests/tx/cache-id.test.js @@ -5,10 +5,11 @@ * `cache-id`, then refer to it by url on later requests with the same cache-id. * This is in routine use by every fhir-core consumer, so it must be exercised hard. * - * Background on the two bugs these tests guard: - * 1. fhir-core sends cache-id as an IdType -> {"name":"cache-id","valueId":"..."}. - * If the server can't read valueId, cacheId is null and the whole protocol - * silently no-ops, so every by-reference call fails "could not be found". + * The cache-id travels in the X-Cache-Id header; the old cache-id parameter is refused. + * + * Background on the bugs these tests guard: + * 1. If the server loses the cache-id, the whole protocol silently no-ops, so + * every by-reference call fails "could not be found". * 2. The server must cache the primary `valueSet` parameter (not only * `tx-resource`), or the by-reference follow-up can't resolve the main VS. * @@ -43,19 +44,22 @@ const colorsVS = { compose: { include: [{ system: colorsCS.url }] } }; -// Send cache-id either as valueId (fhir-core's real format) or valueString. -function cacheIdParam(value, as) { - return as === 'valueString' - ? { name: 'cache-id', valueString: value } - : { name: 'cache-id', valueId: value }; +// The cache-id a request uses. post() sends it in the X-Cache-Id header: the cache-id +// parameter is withdrawn, and refused (see 'the cache-id parameter is refused' below) +function cacheIdParam(value) { + return { name: 'cache-id', valueId: value }; } function post(app, url, parameter) { - return request(app) + const cid = parameter.find(p => p.name === 'cache-id'); + const req = request(app) .post(url) .set('Accept', 'application/json') - .set('Content-Type', 'application/json') - .send({ resourceType: 'Parameters', parameter }); + .set('Content-Type', 'application/json'); + if (cid) { + req.set('x-cache-id', cid.valueId); + } + return req.send({ resourceType: 'Parameters', parameter: parameter.filter(p => p.name !== 'cache-id') }); } // Create a real cache via $cache-control and return its server-issued id. Caches @@ -96,17 +100,14 @@ describe('cache-id protocol (integration)', () => { await shutdownTestApp(); }); - // The headline regression: cache-id as valueId, register inline then validate by url. - describe.each([ - ['valueId (fhir-core wire format)', 'valueId'], - ['valueString', 'valueString'], - ])('$validate-code round trip with cache-id as %s', (_label, as) => { + // The headline regression: register inline then validate by url + describe('$validate-code round trip with a cache-id', () => { test('register CS+VS under cache-id, then validate a valid code by url', async () => { const cid = await startCache(app); // 1st call: send CS (tx-resource) and the primary VS (inline) under cache-id. const r1 = await post(app, VALIDATE, [ - cacheIdParam(cid, as), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -116,7 +117,7 @@ describe('cache-id protocol (integration)', () => { // 2nd call: refer to the VS by url only, same cache-id, nothing re-sent. const r2 = await post(app, VALIDATE, [ - cacheIdParam(cid, as), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } ]); @@ -127,14 +128,14 @@ describe('cache-id protocol (integration)', () => { test('by-reference validation of an invalid code returns result=false (really validating)', async () => { const cid = await startCache(app); await post(app, VALIDATE, [ - cacheIdParam(cid, as), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } ]); const r2 = await post(app, VALIDATE, [ - cacheIdParam(cid, as), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'magenta' } } ]); @@ -148,7 +149,7 @@ describe('cache-id protocol (integration)', () => { const cid = await startCache(app); // Register under the started cache. const reg = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'green' } } @@ -157,7 +158,7 @@ describe('cache-id protocol (integration)', () => { // Same cache-id, by url -> resolves from cache. const same = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'green' } } ]); @@ -202,9 +203,8 @@ describe('cache-id protocol (integration)', () => { test('CodeSystem/$validate-code with an unknown cache-id is answered (it used to never respond)', async () => { const res = await request(app).post('/tx/r5/CodeSystem/$validate-code').timeout(10000) - .set('Content-Type', 'application/json') + .set('Content-Type', 'application/json').set('x-cache-id', 'never-issued-this-cache') .send({ resourceType: 'Parameters', parameter: [ - { name: 'cache-id', valueId: 'never-issued-this-cache' }, { name: 'coding', valueCoding: { system: 'http://hl7.org/fhir/administrative-gender', code: 'male' } } ] }); expect(res.status).toBe(404); @@ -215,7 +215,7 @@ describe('cache-id protocol (integration)', () => { // goes over a limit of 4 only together with what the cache already holds const shadesCS = { ...colorsCS, id: 'shades', url: 'http://example.org/fhir/CodeSystem/shades' }; const seedCache = (cid) => post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: shadesCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -228,7 +228,7 @@ describe('cache-id protocol (integration)', () => { const cid = await startCache(app); cache.setLimits(2, Infinity); // colorsCS has 3 concepts: no cache can take it const r = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -251,7 +251,7 @@ describe('cache-id protocol (integration)', () => { cache.setLimits(4, Infinity); // colorsCS has 3 concepts: one fits, two don't await seedCache(cid); // the cache holds 3 concepts, so colorsCS fits on its own, but not with them const over = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -271,7 +271,7 @@ describe('cache-id protocol (integration)', () => { 'This operation has not been performed. Start a new cache, and send the request again'); const after = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } ]); @@ -324,7 +324,7 @@ describe('cache-id protocol (integration)', () => { } }; const send = (cid, cs) => post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: cs }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -346,7 +346,7 @@ describe('cache-id protocol (integration)', () => { // the cache still works, by reference expect(cache.has(cid)).toBe(true); const byUrl = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } ]); @@ -368,7 +368,7 @@ describe('cache-id protocol (integration)', () => { const out = []; for (let i = 0; i < 2; i++) { out.push(await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'valueSet', resource: { ...colorsVS, compose: { include: [{ system: colorsCS.url, concept: [{ code: 'red' }] }] } } }, { name: 'tx-resource', resource: i === 0 ? colorsCS : { ...colorsCS, url: colorsCS.url + '-other', version: '2' } }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'red' } } @@ -459,7 +459,7 @@ describe('cache-id protocol (integration)', () => { // 1st call registers the CS (and a first VS) under the cache-id. const r1 = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'blue' } } @@ -475,7 +475,7 @@ describe('cache-id protocol (integration)', () => { compose: { include: [{ system: colorsCS.url, concept: [{ code: 'blue' }] }] } }; const r2 = await post(app, VALIDATE, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'valueSet', resource: secondVS }, { name: 'coding', valueCoding: { system: colorsCS.url, code: 'blue' } } ]); @@ -489,7 +489,7 @@ describe('cache-id protocol (integration)', () => { const cid = await startCache(app); const r1 = await post(app, EXPAND, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'tx-resource', resource: colorsCS }, { name: 'valueSet', resource: colorsVS } ]); @@ -497,7 +497,7 @@ describe('cache-id protocol (integration)', () => { expect(r1.body.resourceType).toBe('ValueSet'); const r2 = await post(app, EXPAND, [ - cacheIdParam(cid, 'valueId'), + cacheIdParam(cid), { name: 'url', valueString: colorsVS.url } ]); expect(r2.status).toBe(200); diff --git a/tests/tx/expand.test.js b/tests/tx/expand.test.js index 805c39703..70d879b37 100644 --- a/tests/tx/expand.test.js +++ b/tests/tx/expand.test.js @@ -441,13 +441,10 @@ describe('Expand Worker', () => { .post('/tx/r5/ValueSet/$expand') .set('Accept', 'application/json') .set('Content-Type', 'application/json') + .set('X-Cache-Id', cacheId) .send({ resourceType: 'Parameters', parameter: [ - { - name: 'cache-id', - valueString: cacheId - }, { name: 'tx-resource', resource: testCodeSystem @@ -468,13 +465,10 @@ describe('Expand Worker', () => { .post('/tx/r5/ValueSet/$expand') .set('Accept', 'application/json') .set('Content-Type', 'application/json') + .set('X-Cache-Id', cacheId) .send({ resourceType: 'Parameters', parameter: [ - { - name: 'cache-id', - valueString: cacheId - }, { name: 'valueSet', resource: secondValueSet @@ -500,18 +494,15 @@ describe('Expand Worker', () => { const cacheId = await startCache(app); // First request: primary ValueSet sent inline as `valueSet`, plus the - // CodeSystem it needs as tx-resource, both under the cache-id. - // NB: cache-id is sent as `valueId` here, exactly as fhir-core sends it - // (IdType). getParameterValue must understand valueId or the cache-id is - // read as null and the whole protocol silently no-ops. + // CodeSystem it needs as tx-resource, both under the cache-id (in the X-Cache-Id header). const response1 = await request(app) .post('/tx/r5/ValueSet/$expand') .set('Accept', 'application/json') .set('Content-Type', 'application/json') + .set('X-Cache-Id', cacheId) .send({ resourceType: 'Parameters', parameter: [ - { name: 'cache-id', valueId: cacheId }, { name: 'tx-resource', resource: testCodeSystem }, { name: 'valueSet', resource: testValueSet } ] @@ -527,10 +518,10 @@ describe('Expand Worker', () => { .post('/tx/r5/ValueSet/$expand') .set('Accept', 'application/json') .set('Content-Type', 'application/json') + .set('X-Cache-Id', cacheId) .send({ resourceType: 'Parameters', parameter: [ - { name: 'cache-id', valueId: cacheId }, { name: 'url', valueString: testValueSet.url } ] }); diff --git a/tests/tx/fixtures/triage-library.yaml b/tests/tx/fixtures/triage-library.yaml new file mode 100644 index 000000000..43b34ecde --- /dev/null +++ b/tests/tx/fixtures/triage-library.yaml @@ -0,0 +1,9 @@ +# Test library for the triage tests (tests/tx/triage-b.test.js): R5 core, loaded automatically, +# and the internal code systems the tests use + +base: + url: https://storage.googleapis.com/tx-fhir-org + +sources: + - internal:mimetypes + - ucum:tx/data/ucum-essence.xml diff --git a/tests/tx/logging-quiet.test.js b/tests/tx/logging-quiet.test.js index dc3a66369..00fd54e65 100644 --- a/tests/tx/logging-quiet.test.js +++ b/tests/tx/logging-quiet.test.js @@ -42,8 +42,8 @@ describe('routine client errors are not logged', () => { test('an unknown cache-id', async () => { const { res, logged } = await send('POST', '/tx/r5/ValueSet/$validate-code', P([ { name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, - { name: 'code', valueCode: 'male' }, { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender' }, - { name: 'cache-id', valueId: '813c6d23-0c4a-47db-bfb2-9ba8ac1346ef' }])); + { name: 'code', valueCode: 'male' }, { name: 'system', valueUri: 'http://hl7.org/fhir/administrative-gender' }]), + { 'X-Cache-Id': '813c6d23-0c4a-47db-bfb2-9ba8ac1346ef' }); expect(res.status).toBe(404); expect(problems(logged)).toEqual([]); }); diff --git a/tests/tx/parser-depth-limits.test.js b/tests/tx/parser-depth-limits.test.js index 80fff028c..3ce96d37a 100644 --- a/tests/tx/parser-depth-limits.test.js +++ b/tests/tx/parser-depth-limits.test.js @@ -143,7 +143,8 @@ describe('ECL parser limits', () => { }); test('a compound chain up to the term limit parses', () => { - for (const op of ['OR', 'AND', 'MINUS']) { + // (MINUS doesn't chain without brackets: an exclusion has one expression on each side) + for (const op of ['OR', 'AND']) { expect(() => parse(chain(MAX_ECL_TERMS, op))).not.toThrow(); } }); diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 410a26d79..432203fff 100644 --- a/tests/tx/sqlite-v2-sct-ecl.test.js +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -101,6 +101,23 @@ describe('SNOMED CT ECL description filters and compound ECL, as cs-snomed.js', }); }); +describe('SNOMED CT ECL reversed is-a (triage B6), as cs-snomed.js', () => { + test('R 116680003 |Is a| = X is X\'s parents; 116680003 = X its children', async () => { + for (const x of ['126081001', '763158003', '105590001']) { + const parents = await same('* : R 116680003 = ' + x); + expect(new Set(parents)).toEqual(new Set(await ecl(main, '>! ' + x))); + expect(parents.length).toBeGreaterThan(0); + await same('* : 116680003 = ' + x); + } + // a wildcard attribute, and an attribute set, include is-a, both ways + await same('* : R * = 126081001'); + await same('* : * = 105590001'); + await same('* : R << 246061005 = 126081001'); + await same('* : << 246061005 = 105590001'); + await same('* : R 127489000 = 776168003'); + }); +}); + describe('SNOMED CT ECL the engine hands to main\'s ECL (sct-main-ecl.js)', () => { test('evaluated by main\'s (async) ECL first, then compiled: the same codes as cs-snomed.js', async () => { const texts = ['< 404684003 : { [1..1] 363698007 = << 123037004 }', '< 404684003 : { [0..1] 363698007 = * }']; diff --git a/tests/tx/sqlite-v2-sct-postcoord.test.js b/tests/tx/sqlite-v2-sct-postcoord.test.js index 87ff5d365..8a6eb5aa1 100644 --- a/tests/tx/sqlite-v2-sct-postcoord.test.js +++ b/tests/tx/sqlite-v2-sct-postcoord.test.js @@ -151,6 +151,35 @@ describe('sqlite-v2 SNOMED CT post-coordination (native) and ECL fallback', () = expect(nf).toBeGreaterThan(100); }); + test('the normal form of a single concept written as an expression (triage B8): the id, and <<< if given', async () => { + const p = await factory.build(op, []); + for (const [code, normal] of [['64572001', '64572001'], ['64572001|Disease|', '64572001'], ['64572001 |Disease|', '64572001'], + ['===64572001', '64572001'], ['=== 64572001 |Disease|', '64572001'], ['<<<64572001', '<<<64572001'], ['<<< 64572001 |Disease|', '<<<64572001'], + ['128241005|Inflammatory disease of liver|:{363698007=181268008}', '128241005:{363698007=181268008}'], + ['<<<128241005:{363698007=181268008}', '<<<128241005:{363698007=181268008}'], + ['===128241005:{363698007=181268008}', '128241005:{363698007=181268008}']]) { + const r = await p.locate(code); + expect([code, r.message || null]).toEqual([code, null]); + expect([code, await p.code(r.context)]).toEqual([code, normal]); + } + }); + + test('an expression\'s refinement attributes are properties only when asked for, or nothing is (triage B9)', async () => { + const p = await factory.build(op, []); + const r = await p.locate('128241005:{363698007=181268008}'); + const props = async (asked) => { + const params = []; + await p.extendLookup(r.context, asked, params); + // code=value: the focus concept's own finding site is one, the refinement's (181268008) another + return params.filter(x => x.name === 'property').map(x => x.part.find(y => y.name === 'code').valueCode + '=' + + ((x.part.find(y => y.name === 'value') || {}).valueCode || '')); + }; + expect((await props(['normalForm'])).filter(p => p.startsWith('363698007'))).toEqual([]); + expect(await props(['363698007'])).toContain('363698007=181268008'); + expect(await props([])).toContain('363698007=181268008'); + expect(await props(['*'])).toContain('363698007=181268008'); + }); + test('ancestorsOf agrees with subsumesTest for plain concept ids; expressions and other spellings get null', async () => { const p = await factory.build(op, []); const all = factory.store.db.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); diff --git a/tests/tx/test-cases.test.js b/tests/tx/test-cases.test.js index 7d65d5a5d..65aaa9b47 100644 --- a/tests/tx/test-cases.test.js +++ b/tests/tx/test-cases.test.js @@ -1778,6 +1778,189 @@ describe('language2', () => { }); +describe('no-display', () => { + // Validating the display of a code that has no display, only other designations (synonyms): a display that is none of them is reported as such - there is no known display, and what the code does have - on every path (code, Coding, CodeableConcept; CodeSystem and ValueSet $validate-code; a code that is not in the value set) + + it("no-display-cs-code" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-code"}, "5.0"); + }); + + it("no-display-cs-code" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-code"}, "4.0"); + }); + + it("no-display-cs-coding" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-coding"}, "5.0"); + }); + + it("no-display-cs-coding" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-coding"}, "4.0"); + }); + + it("no-display-cs-codeableconcept" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-codeableconcept"}, "5.0"); + }); + + it("no-display-cs-codeableconcept" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-codeableconcept"}, "4.0"); + }); + + it("no-display-cs-synonym" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-synonym"}, "5.0"); + }); + + it("no-display-cs-synonym" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-synonym"}, "4.0"); + }); + + it("no-display-vs-code" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-code"}, "5.0"); + }); + + it("no-display-vs-code" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-code"}, "4.0"); + }); + + it("no-display-vs-coding-two" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-coding-two"}, "5.0"); + }); + + it("no-display-vs-coding-two" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-coding-two"}, "4.0"); + }); + + it("no-display-vs-codeableconcept" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-codeableconcept"}, "5.0"); + }); + + it("no-display-vs-codeableconcept" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-codeableconcept"}, "4.0"); + }); + + it("no-display-vs-not-in" + 'R5', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-not-in"}, "5.0"); + }); + + it("no-display-vs-not-in" + 'R4', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-not-in"}, "4.0"); + }); + +}); + +describe('designation-display', () => { + // Displays in designations: a designation whose use is designation-usage#display is a display as much as the code's own display is, so it is a valid display, and a display that is not valid is told about it among the valid displays + + it("designation-display-cs-wrong" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-wrong"}, "5.0"); + }); + + it("designation-display-cs-wrong" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-wrong"}, "4.0"); + }); + + it("designation-display-cs-alt" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-alt"}, "5.0"); + }); + + it("designation-display-cs-alt" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-alt"}, "4.0"); + }); + + it("designation-display-vs-wrong" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-wrong"}, "5.0"); + }); + + it("designation-display-vs-wrong" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-wrong"}, "4.0"); + }); + + it("designation-display-vs-alt" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-alt"}, "5.0"); + }); + + it("designation-display-vs-alt" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-alt"}, "4.0"); + }); + + it("designation-display-vs-cc-wrong" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-cc-wrong"}, "5.0"); + }); + + it("designation-display-vs-cc-wrong" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-cc-wrong"}, "4.0"); + }); + + it("designation-display-lang-wrong" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-wrong"}, "5.0"); + }); + + it("designation-display-lang-wrong" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-wrong"}, "4.0"); + }); + + it("designation-display-lang-de" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-de"}, "5.0"); + }); + + it("designation-display-lang-de" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-de"}, "4.0"); + }); + + it("designation-display-only-wrong" + 'R5', async () => { + await runTest({"suite":"designation-display","test":"designation-display-only-wrong"}, "5.0"); + }); + + it("designation-display-only-wrong" + 'R4', async () => { + await runTest({"suite":"designation-display","test":"designation-display-only-wrong"}, "4.0"); + }); + +}); + +describe('hierarchy-meaning', () => { + // CodeSystem.hierarchyMeaning and $subsumes: only an is-a hierarchy (or one whose meaning isn't stated) describes subsumption; for a code system whose hierarchy means something else, subsumption can't be tested + + it("hierarchy-meaning-none-subsumes" + 'R5', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-none-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-none-subsumes" + 'R4', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-none-subsumes"}, "4.0"); + }); + + it("hierarchy-meaning-is-a-subsumes" + 'R5', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-is-a-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-is-a-subsumes" + 'R4', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-is-a-subsumes"}, "4.0"); + }); + + it("hierarchy-meaning-part-of-subsumes" + 'R5', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-part-of-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-part-of-subsumes" + 'R4', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-part-of-subsumes"}, "4.0"); + }); + + it("hierarchy-meaning-grouped-by-subsumes" + 'R5', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-grouped-by-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-grouped-by-subsumes" + 'R4', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-grouped-by-subsumes"}, "4.0"); + }); + + it("hierarchy-meaning-classified-with-subsumes" + 'R5', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-classified-with-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-classified-with-subsumes" + 'R4', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-classified-with-subsumes"}, "4.0"); + }); + +}); + describe('global-lang-pack', () => { // Global language packs: a language pack (codesystem-supplement-type = lang-pack) marked with codesystem-supplement-global = true is used for the code system it supplements whether or not it is referenced; any other supplement is only used when it is referenced @@ -13215,6 +13398,54 @@ describe('mimetypes', () => { await runTest({"suite":"mimetypes","test":"mimetype-subsumes-invalid-code"}, "4.0"); }); + it("mimetype-cs-validate-empty-param-name" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-empty-param-name"}, "5.0"); + }); + + it("mimetype-cs-validate-empty-param-name" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-empty-param-name"}, "4.0"); + }); + + it("mimetype-cs-validate-param-no-value" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-param-no-value"}, "5.0"); + }); + + it("mimetype-cs-validate-param-no-value" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-param-no-value"}, "4.0"); + }); + + it("mimetype-cs-validate-unclosed-quote" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unclosed-quote"}, "5.0"); + }); + + it("mimetype-cs-validate-unclosed-quote" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unclosed-quote"}, "4.0"); + }); + + it("mimetype-cs-validate-unquoted-uri" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unquoted-uri"}, "5.0"); + }); + + it("mimetype-cs-validate-unquoted-uri" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unquoted-uri"}, "4.0"); + }); + + it("mimetype-cs-validate-space-in-type" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-space-in-type"}, "5.0"); + }); + + it("mimetype-cs-validate-space-in-type" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-space-in-type"}, "4.0"); + }); + + it("mimetype-cs-validate-quoted-semicolon" + 'R5', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-quoted-semicolon"}, "5.0"); + }); + + it("mimetype-cs-validate-quoted-semicolon" + 'R4', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-quoted-semicolon"}, "4.0"); + }); + it("mimetype-filter-base-type-in" + 'R5', async () => { await runTest({"suite":"mimetypes","test":"mimetype-filter-base-type-in"}, "5.0"); }); @@ -18331,6 +18562,105 @@ describe('language2', () => { }); +describe('no-display', () => { + // Validating the display of a code that has no display, only other designations (synonyms): a display that is none of them is reported as such - there is no known display, and what the code does have - on every path (code, Coding, CodeableConcept; CodeSystem and ValueSet $validate-code; a code that is not in the value set) + + it("no-display-cs-code" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-code"}, "5.0"); + }); + + it("no-display-cs-coding" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-coding"}, "5.0"); + }); + + it("no-display-cs-codeableconcept" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-codeableconcept"}, "5.0"); + }); + + it("no-display-cs-synonym" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-cs-synonym"}, "5.0"); + }); + + it("no-display-vs-code" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-code"}, "5.0"); + }); + + it("no-display-vs-coding-two" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-coding-two"}, "5.0"); + }); + + it("no-display-vs-codeableconcept" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-codeableconcept"}, "5.0"); + }); + + it("no-display-vs-not-in" + 'R5-cached', async () => { + await runTest({"suite":"no-display","test":"no-display-vs-not-in"}, "5.0"); + }); + +}); + +describe('designation-display', () => { + // Displays in designations: a designation whose use is designation-usage#display is a display as much as the code's own display is, so it is a valid display, and a display that is not valid is told about it among the valid displays + + it("designation-display-cs-wrong" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-wrong"}, "5.0"); + }); + + it("designation-display-cs-alt" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-cs-alt"}, "5.0"); + }); + + it("designation-display-vs-wrong" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-wrong"}, "5.0"); + }); + + it("designation-display-vs-alt" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-alt"}, "5.0"); + }); + + it("designation-display-vs-cc-wrong" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-vs-cc-wrong"}, "5.0"); + }); + + it("designation-display-lang-wrong" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-wrong"}, "5.0"); + }); + + it("designation-display-lang-de" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-lang-de"}, "5.0"); + }); + + it("designation-display-only-wrong" + 'R5-cached', async () => { + await runTest({"suite":"designation-display","test":"designation-display-only-wrong"}, "5.0"); + }); + +}); + +describe('hierarchy-meaning', () => { + // CodeSystem.hierarchyMeaning and $subsumes: only an is-a hierarchy (or one whose meaning isn't stated) describes subsumption; for a code system whose hierarchy means something else, subsumption can't be tested + + it("hierarchy-meaning-none-subsumes" + 'R5-cached', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-none-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-is-a-subsumes" + 'R5-cached', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-is-a-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-part-of-subsumes" + 'R5-cached', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-part-of-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-grouped-by-subsumes" + 'R5-cached', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-grouped-by-subsumes"}, "5.0"); + }); + + it("hierarchy-meaning-classified-with-subsumes" + 'R5-cached', async () => { + await runTest({"suite":"hierarchy-meaning","test":"hierarchy-meaning-classified-with-subsumes"}, "5.0"); + }); + +}); + describe('global-lang-pack', () => { // Global language packs: a language pack (codesystem-supplement-type = lang-pack) marked with codesystem-supplement-global = true is used for the code system it supplements whether or not it is referenced; any other supplement is only used when it is referenced @@ -24196,6 +24526,30 @@ describe('mimetypes', () => { await runTest({"suite":"mimetypes","test":"mimetype-subsumes-invalid-code"}, "5.0"); }); + it("mimetype-cs-validate-empty-param-name" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-empty-param-name"}, "5.0"); + }); + + it("mimetype-cs-validate-param-no-value" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-param-no-value"}, "5.0"); + }); + + it("mimetype-cs-validate-unclosed-quote" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unclosed-quote"}, "5.0"); + }); + + it("mimetype-cs-validate-unquoted-uri" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-unquoted-uri"}, "5.0"); + }); + + it("mimetype-cs-validate-space-in-type" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-space-in-type"}, "5.0"); + }); + + it("mimetype-cs-validate-quoted-semicolon" + 'R5-cached', async () => { + await runTest({"suite":"mimetypes","test":"mimetype-cs-validate-quoted-semicolon"}, "5.0"); + }); + it("mimetype-filter-base-type-in" + 'R5-cached', async () => { await runTest({"suite":"mimetypes","test":"mimetype-filter-base-type-in"}, "5.0"); }); diff --git a/tests/tx/triage-b.test.js b/tests/tx/triage-b.test.js new file mode 100644 index 000000000..14324330d --- /dev/null +++ b/tests/tx/triage-b.test.js @@ -0,0 +1,579 @@ +/** + * Triage tier B (Dec 2026): smaller bugs and edge cases in the tx operations - each describe block + * is one item (B1, B2...), with what was decided for it. + */ + +const path = require('path'); +const express = require('express'); +const request = require('supertest'); +const TXModule = require('../../tx/tx'); + +jest.setTimeout(60000); + +const G = 'http://hl7.org/fhir/administrative-gender'; + +describe('triage tier B', () => { + let app; + let txModule; + + beforeAll(async () => { + app = express(); + app.use(express.json({ limit: '10mb' })); + txModule = new TXModule(); + await txModule.initialize({ + librarySource: path.join(__dirname, 'fixtures', 'triage-library.yaml'), + endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }] + }, app); + }); + + afterAll(async () => { + if (txModule) { + await txModule.shutdown(); + } + }); + + const post = (op, parameter) => request(app).post('/tx/r5/' + op).set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter }); + const msgId = (res) => { + const issue = (res.body.issue || [])[0] || {}; + const ext = (issue.extension || []).find(e => e.url === 'http://hl7.org/fhir/StructureDefinition/operationoutcome-message-id'); + return ext ? ext.valueString : null; + }; + const param = (res, name) => (res.body.parameter || []).find(p => p.name === name); + + // B1: a value that isn't what its value[x] says it is, or a parameter with a value of the wrong + // kind: a 400, not a crash, and not an answer that echoes invalid content + describe('B1 parameter value types', () => { + test('url as a valueInteger: 400', async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueInteger: 123 }]); + expect(res.status).toBe(400); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(msgId(res)).toBe('TX_PARAM_WRONG_TYPE'); + expect(res.body.issue[0].expression).toEqual(['Parameters.parameter[0]']); + expect(res.body.issue[0].details.text).toMatch(/'url'/); + }); + + test('code as a valueInteger: 400, not valueCode: 42 in the answer', async () => { + const res = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: G }, { name: 'code', valueInteger: 42 }]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_WRONG_TYPE'); + expect(res.body.issue[0].expression).toEqual(['Parameters.parameter[1]']); + }); + + test('valueCode: 42 (not valid JSON for a code): 400', async () => { + const res = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: G }, { name: 'code', valueCode: 42 }]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_INVALID_VALUE'); + }); + + test('valueBoolean: "yes": 400', async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'activeOnly', valueBoolean: 'yes' }]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_INVALID_VALUE'); + }); + + test('an invalid value in a part: 400, with the part\'s path', async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'x-thing', part: [{ name: 'a', valueInteger: 1.5 }] }]); + expect(res.status).toBe(400); + expect(res.body.issue[0].expression).toEqual(['Parameters.parameter[1].part[0]']); + }); + + test('count as a string of digits is fine; as other text it is not', async () => { + const ok = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'count', valueString: '2' }]); + expect(ok.status).toBe(200); + const bad = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'count', valueString: 'two' }]); + expect(bad.status).toBe(400); + expect(msgId(bad)).toBe('TX_PARAM_WRONG_TYPE'); + }); + + test('GET: code=true is the code "true", not a boolean', async () => { + const res = await request(app).get('/tx/r5/CodeSystem/$validate-code').query({ url: G, code: 'true' }); + expect(res.status).toBe(200); + expect(param(res, 'result').valueBoolean).toBe(false); + expect(param(res, 'code').valueCode).toBe('true'); + }); + + test('a parameter it doesn\'t know, with a valid value of any type, is left alone', async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }, + { name: 'x-thing', valueInteger: 3 }]); + expect(res.status).toBe(200); + }); + }); + + // B2: a version rule is url|version: anything else is a 400 that says which parameter, and why + describe('B2 version rules', () => { + const VS = 'http://hl7.org/fhir/ValueSet/administrative-gender'; + for (const [name, value] of [['force-system-version', 'http://loinc.org|'], ['check-system-version', '|2.83'], + ['force-system-version', 'http://loinc.org'], ['system-version', '|'], ['default-valueset-version', VS]]) { + test(`${name}=${value}: 400`, async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueUri: VS }, { name, valueCanonical: value }]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_VERSION_RULE_INVALID'); + expect(res.body.issue[0].details.text).toContain(`'${name}'`); + }); + } + + test('a version with | in it is still a version', async () => { + const res = await post('ValueSet/$expand', [{ name: 'url', valueUri: VS }, { name: 'system-version', valueCanonical: 'http://loinc.org|a|b' }]); + expect(res.status).toBe(200); + }); + + test('GET: count=two is a 400', async () => { + const res = await request(app).get('/tx/r5/ValueSet/$expand').query({ url: VS, count: 'two' }); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_WRONG_TYPE'); + }); + }); + + // B3: the cache-id parameter is withdrawn (the tx-ecosystem IG: servers SHOULD NOT accept it); + // a cache-id goes in the X-Cache-Id header. A request with the parameter, wherever it is, is a + // 400 that says so - $batch-validate-code used to ignore it, so a bad cache-id went unnoticed + describe('B3 cache-id parameter', () => { + const batch = (parameter) => post('CodeSystem/$batch-validate-code', parameter); + const validation = (...parameter) => ({ name: 'validation', resource: { resourceType: 'Parameters', parameter } }); + + test('$batch-validate-code with a cache-id parameter: 400', async () => { + const res = await batch([{ name: 'cache-id', valueId: 'never-issued-id' }, { name: 'url', valueUri: G }, + validation({ name: 'code', valueCode: 'male' })]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_CACHE_ID_WITHDRAWN'); + expect(res.body.issue[0].code).toBe('not-supported'); + expect(res.body.issue[0].expression).toEqual(['Parameters.parameter[0]']); + expect(res.body.issue[0].details.text).toMatch(/X-Cache-Id/); + }); + + test('in a batch\'s validation entry: 400', async () => { + const res = await batch([{ name: 'url', valueUri: G }, + validation({ name: 'code', valueCode: 'male' }, { name: 'cache-id', valueString: 'x' })]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_CACHE_ID_WITHDRAWN'); + expect(res.body.issue[0].expression).toEqual(['Parameters.parameter[1].resource.parameter[1]']); + }); + + test.each(['CodeSystem/$validate-code', 'ValueSet/$expand', 'CodeSystem/$lookup'])('%s with a cache-id parameter: 400', async (op) => { + const res = await post(op, [{ name: 'system', valueUri: G }, { name: 'code', valueCode: 'male' }, { name: 'cache-id', valueId: 'abc' }]); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_CACHE_ID_WITHDRAWN'); + }); + + test('in the query: 400', async () => { + const res = await request(app).get('/tx/r5/CodeSystem/$lookup').query({ system: G, code: 'male', 'cache-id': 'abc' }); + expect(res.status).toBe(400); + expect(msgId(res)).toBe('TX_PARAM_CACHE_ID_WITHDRAWN'); + }); + + test('a never-issued cache-id in the X-Cache-Id header on $batch-validate-code is the coded unknown-cache error', async () => { + const res = await request(app).post('/tx/r5/CodeSystem/$batch-validate-code').set('Content-Type', 'application/json') + .set('X-Cache-Id', 'never-issued-id') + .send({ resourceType: 'Parameters', parameter: [{ name: 'url', valueUri: G }, validation({ name: 'code', valueCode: 'male' })] }); + expect(res.status).toBe(404); + expect(JSON.stringify(res.body)).toMatch(/cache-id-unknown/); + }); + }); + + // B4: valueset-unclosed is 0..1: once on the expansion, with one reason, however many includes + // (here, two of a fragment) make it unclosed + describe('B4 valueset-unclosed once', () => { + const UNCLOSED = 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed'; + const REASON = UNCLOSED + '-reason'; + const frag = { resourceType: 'CodeSystem', url: 'http://example.org/cs/frag', version: '1.0', status: 'active', content: 'fragment', + concept: [{ code: 'A', display: 'A' }, { code: 'B', display: 'B' }] }; + const exts = (res, url) => ((res.body.expansion || {}).extension || []).filter(e => e.url === url); + + test('two includes of a fragment: one unclosed, one reason', async () => { + const res = await post('ValueSet/$expand', [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', url: 'http://example.org/vs/frag', status: 'active', compose: { include: [ + { system: frag.url, concept: [{ code: 'A' }] }, { system: frag.url, concept: [{ code: 'B' }] }] } } }, + { name: 'tx-resource', resource: frag }]); + expect(res.status).toBe(200); + expect(exts(res, UNCLOSED)).toEqual([{ url: UNCLOSED, valueBoolean: true }]); + expect(exts(res, REASON)).toHaveLength(1); + expect(exts(res, REASON)[0].valueString).toMatch(/fragment of the code system http:\/\/example.org\/cs\/frag$/); + }); + + test('a fragment and another fragment: one reason, naming both', async () => { + const frag2 = { ...frag, url: 'http://example.org/cs/frag2' }; + const res = await post('ValueSet/$expand', [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', url: 'http://example.org/vs/frag2', status: 'active', compose: { include: [ + { system: frag.url }, { system: frag2.url }] } } }, + { name: 'tx-resource', resource: frag }, { name: 'tx-resource', resource: frag2 }]); + expect(res.status).toBe(200); + expect(exts(res, UNCLOSED)).toHaveLength(1); + expect(exts(res, REASON)).toHaveLength(1); + expect(exts(res, REASON)[0].valueString).toMatch(/cs\/frag; .*cs\/frag2/); + }); + }); + + // B5: a media type is what the RFC 9110 section 8.3.1 (RFC 2045 section 5.1) grammar says it is - + // anything else is invalid. A ';' in a quoted value is part of the value + describe('B5 media type grammar', () => { + const { MimeTypeConcept } = require('../../tx/cs/cs-mimetypes'); + + test.each([ + ['an empty parameter name', 'text/plain; =v'], + ['a parameter with no value', 'text/plain; foo='], + ['a parameter with no =', 'text/plain; foo'], + ['an unclosed quoted string', 'text/plain; foo="a;b'], + ['a bad escape at the end of a quoted string', 'text/plain; foo="a\\'], + ['a control character in a quoted string', 'text/plain; foo="a\u0001b"'], + ['space around the /', 'text /plain'], + ['space around the =', 'text/plain; foo = bar'], + ['leading whitespace', ' text/plain'], + ['trailing whitespace', 'text/plain '], + ['trailing whitespace after a ;', 'text/plain; '], + ['no subtype', 'text/'], + ['no type', '/plain'], + ['no /', 'text'], + ['two /', 'text/plain/x'], + ['a tspecial in the subtype', 'text/pl@in'], + ['a tspecial in a parameter name', 'text/plain; f(o)o=bar'], + ['an unquoted value with a tspecial', 'application/fhir+json; profile=http://example.org/X'], + ['an unquoted value with a space', 'text/plain; foo=a b'], + ['something after a quoted value', 'text/plain; foo="a"b'], + ['a ; missing between parameters', 'text/plain; a=b c=d'] + ])('%s: invalid', (_label, code) => { + expect(new MimeTypeConcept(code).isValid()).toBe(false); + }); + + test.each([ + ['a quoted value with a ;', 'text/plain; foo="a;b"', 'text/plain; foo="a;b"', 'a;b'], + ['a quoted value with an escaped quote', 'text/plain; foo="a\\"b"', 'text/plain; foo="a\\"b"', 'a"b'], + ['an empty quoted value', 'text/plain; foo=""', 'text/plain; foo=""', ''], + ['a quoted URI', 'application/fhir+json; profile="http://example.org/X"', 'application/fhir+json; profile="http://example.org/X"', 'http://example.org/X'], + ['no space after the ;', 'text/plain;foo=bar', 'text/plain; foo=bar', 'bar'], + ['space before the ;', 'text/plain ;foo=bar', 'text/plain; foo=bar', 'bar'], + ['an empty parameter', 'text/plain;; foo=bar', 'text/plain; foo=bar', 'bar'], + ['every tchar', "a!#$%&'*+-.^_`|~1/b", "a!#$%&'*+-.^_`|~1/b", undefined] + ])('%s: valid', (_label, code, normal, foo) => { + const c = new MimeTypeConcept(code); + expect(c.isValid()).toBe(true); + expect(c.normalized).toBe(normal); + expect(c.mimeType.params.get('foo') ?? c.mimeType.params.get('profile')).toBe(foo); + }); + + test('a quoted ; does not split the parameter: the parameters sort as two, not three', () => { + expect(new MimeTypeConcept('text/plain; z="a;b=c"; a=1').normalized).toBe('text/plain; a=1; z="a;b=c"'); + }); + }); + + describe('B5 media type grammar, in $validate-code', () => { + const v = (code) => post('CodeSystem/$validate-code', [{ name: 'url', valueUri: 'urn:ietf:bcp:13' }, { name: 'code', valueCode: code }]); + + test('an empty parameter name: not valid, and the issue says where', async () => { + const res = await v('text/plain; =v'); + expect(param(res, 'result').valueBoolean).toBe(false); + const texts = param(res, 'issues').resource.issue.map(i => i.details.text); + expect(texts).toContain("The code 'text/plain; =v' isn't a valid media type (RFC 9110 section 8.3.1): the error is at character 13"); + }); + + test('a ; in a quoted value: valid, and the normal form sorts the two parameters', async () => { + const res = await v('text/plain; z="a;b=c"; a=1'); + expect(param(res, 'result').valueBoolean).toBe(true); + expect(param(res, 'normalized-code').valueCode).toBe('text/plain; a=1; z="a;b=c"'); + }); + }); + + // B7: the ECL grammar - a dotted attribute needs no spaces around the '.' (a number with a decimal + // point only comes after '#'); and an exclusion has one expression on each side, so a chain of + // MINUS needs brackets (AND and OR chain) + describe('B7 ECL grammar', () => { + const { ECLLexer, ECLParser, ECLTokenType, ECLNodeType } = require('../../tx/sct/ecl'); + const parse = (text) => new ECLParser(new ECLLexer(text).tokenize()).parse(); + const types = (text) => new ECLLexer(text).tokenize().map(t => t.type); + + test.each(['<<125605004.363698007', '<< 125605004 . 363698007', '<<125605004 .363698007', '<<125605004. 363698007'])('%s is a dotted attribute', (text) => { + expect(types(text)).not.toContain(ECLTokenType.DECIMAL); + const ast = parse(text); + expect(ast.type).toBe(ECLNodeType.DOTTED_EXPRESSION_CONSTRAINT); + expect(JSON.stringify(ast)).toMatch(/363698007/); + }); + + test('a chained dot: < { + expect(JSON.stringify(parse('<<125605004.363698007.272741003'))).toMatch(/272741003/); + }); + + test('a decimal after #: still a number', () => { + expect(types('< 763158003 : 1142135004 = #1.5')).toContain(ECLTokenType.DECIMAL); + expect(types('< 763158003 : 1142135004 > #-0.25')).toContain(ECLTokenType.DECIMAL); + expect(JSON.stringify(parse('< 763158003 : 1142135004 >= #2.75'))).toMatch(/"2\.75"/); + }); + + test('A MINUS B MINUS C is refused; with brackets, it\'s fine', () => { + expect(() => parse('<<125605004 MINUS <<71620000 MINUS <<263225007')).toThrow(/MINUS/); + expect(() => parse('(<<125605004 MINUS <<71620000) MINUS <<263225007')).not.toThrow(); + expect(() => parse('<<125605004 MINUS (<<71620000 MINUS <<263225007)')).not.toThrow(); + expect(() => parse('<<125605004 MINUS <<71620000')).not.toThrow(); + }); + + test('AND and OR still chain', () => { + expect(() => parse('<<125605004 AND <<71620000 AND <<263225007')).not.toThrow(); + expect(() => parse('<<125605004 OR <<71620000 OR <<263225007')).not.toThrow(); + expect(() => parse('<<125605004, <<71620000, <<263225007')).not.toThrow(); + }); + }); + + // B8: a single concept written as an expression - with a term, or a definition status - has a + // normal form: the concept id, with <<< if it was given (<<< X is a subtype of X, not X) + describe('B8 SNOMED CT simple expressions are normalised', () => { + const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + + test.each([ + ['64572001', '64572001'], ['64572001|Disease|', '64572001'], ['64572001 |Disease|', '64572001'], + ['===64572001', '64572001'], ['=== 64572001 |Disease|', '64572001'], ['<<<64572001', '<<<64572001'], ['<<< 64572001 |Disease|', '<<<64572001'], + ['64572001|Disease|:{363698007|Finding site|=39057004}', '64572001:{363698007=39057004}'], + ['<<<64572001:{363698007=39057004}', '<<<64572001:{363698007=39057004}'], + ['===64572001:{363698007=39057004}', '64572001:{363698007=39057004}'] + ])('%s: %s', async (code, normal) => { + const op = new OperationContext('en', await TestUtilities.loadTranslations()); + const factory = new SnomedServicesFactory(op.i18n, path.join(__dirname, '../../tx/data/snomed-testing.cache')); + await factory.load(); + const p = await factory.build(op, []); + const r = await p.locate(code); + expect(r.context).toBeTruthy(); + expect(await p.code(r.context)).toBe(normal); + }); + }); + + // B9: a post-coordinated expression's $lookup gives the refinement's attributes as properties only + // when they're asked for - or when no property is asked for + describe('B9 SNOMED CT expression lookup properties', () => { + const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const EXPR = '64572001:{363698007=39057004}'; + + const lookup = async (props) => { + const op = new OperationContext('en', await TestUtilities.loadTranslations()); + const factory = new SnomedServicesFactory(op.i18n, path.join(__dirname, '../../tx/data/snomed-testing.cache')); + await factory.load(); + const p = await factory.build(op, []); + const r = await p.locate(EXPR); + const params = []; + await p.extendLookup(r.context, props, params); + return params.filter(x => x.name === 'property').map(x => x.part.find(y => y.name === 'code').valueCode); + }; + + test('property=normalForm: the normal form, not the finding site', async () => { + expect(await lookup(['normalForm'])).toEqual(['normalForm']); + }); + test('property=363698007: the finding site', async () => { + expect(await lookup(['363698007'])).toEqual(['363698007']); + }); + test('no property asked for, or *: the finding site', async () => { + expect(await lookup([])).toContain('363698007'); + expect(await lookup(['*'])).toContain('363698007'); + }); + }); + + // B10: a display for a code that has no display, only other designations (synonyms), that is none + // of them: the message says there's no known display, and what the code has - on every path + // (tx-ecosystem no-display suite) + describe('B10 no known display', () => { + const CS = { resourceType: 'CodeSystem', url: 'http://example.org/cs/syn', version: '1.0', status: 'active', content: 'complete', + concept: [{ code: 'SYN', designation: [{ language: 'de', use: { system: 'http://snomed.info/sct', code: '900000000000013009' }, value: 'Deutsches Synonym' }] }, + { code: 'SYN3', designation: [{ language: 'de', use: { system: 'http://snomed.info/sct', code: '900000000000013009' }, value: 'Drittes Synonym' }] }] }; + const VS = { resourceType: 'ValueSet', url: 'http://example.org/vs/syn', status: 'active', compose: { include: [{ system: CS.url, concept: [{ code: 'SYN' }] }] } }; + const res = (op, params) => post(op, [...params, { name: 'tx-resource', resource: CS }, { name: 'tx-resource', resource: VS }]); + const NO_DISPLAY = "Wrong Display Name 'Wrong' for http://example.org/cs/syn#SYN. There is no known display for this code (for the language(s) '--'), only the designation 'Deutsches Synonym' (de)"; + const coding = (code, display) => ({ system: CS.url, code, display }); + + test.each([ + ['CodeSystem, code', 'CodeSystem/$validate-code', [{ name: 'url', valueUri: CS.url }, { name: 'code', valueCode: 'SYN' }, { name: 'display', valueString: 'Wrong' }], 'display'], + ['CodeSystem, Coding', 'CodeSystem/$validate-code', [{ name: 'coding', valueCoding: coding('SYN', 'Wrong') }], 'Coding.display'], + ['CodeSystem, CodeableConcept', 'CodeSystem/$validate-code', [{ name: 'codeableConcept', valueCodeableConcept: { coding: [coding('SYN', 'Wrong')] } }], 'CodeableConcept.coding[0].display'], + ['ValueSet, code', 'ValueSet/$validate-code', [{ name: 'url', valueUri: VS.url }, { name: 'system', valueUri: CS.url }, { name: 'code', valueCode: 'SYN' }, { name: 'display', valueString: 'Wrong' }], 'display'], + ['ValueSet, Coding', 'ValueSet/$validate-code', [{ name: 'url', valueUri: VS.url }, { name: 'coding', valueCoding: coding('SYN', 'Wrong') }], 'Coding.display'], + ['ValueSet, CodeableConcept', 'ValueSet/$validate-code', [{ name: 'url', valueUri: VS.url }, { name: 'codeableConcept', valueCodeableConcept: { coding: [coding('SYN', 'Wrong')] } }], 'CodeableConcept.coding[0].display'] + ])('%s: not valid, and the message says there is no known display', async (_label, op, params, expression) => { + const r = await res(op, params); + expect(r.status).toBe(200); + expect(param(r, 'result').valueBoolean).toBe(false); + expect(param(r, 'message').valueString).toBe(NO_DISPLAY); + const issue = param(r, 'issues').resource.issue[0]; + expect([issue.severity, issue.extension[0].valueString, issue.expression]).toEqual(['error', 'NO_KNOWN_DISPLAY', [expression]]); + }); + + test('a code that is not in the value set: the same message about its display', async () => { + const r = await res('ValueSet/$validate-code', [{ name: 'url', valueUri: VS.url }, { name: 'coding', valueCoding: coding('SYN3', 'Wrong') }]); + expect(param(r, 'result').valueBoolean).toBe(false); + expect(param(r, 'issues').resource.issue.map(i => i.extension[0].valueString)).toContain('NO_KNOWN_DISPLAY'); + }); + + test('lenient-display-validation: a warning, and valid', async () => { + const r = await res('CodeSystem/$validate-code', [{ name: 'coding', valueCoding: coding('SYN', 'Wrong') }, { name: 'lenient-display-validation', valueBoolean: true }]); + expect(param(r, 'result').valueBoolean).toBe(true); + expect(param(r, 'issues').resource.issue[0].severity).toBe('warning'); + }); + + test('the synonym as the display: valid', async () => { + const r = await res('CodeSystem/$validate-code', [{ name: 'coding', valueCoding: coding('SYN', 'Deutsches Synonym') }]); + expect(param(r, 'result').valueBoolean).toBe(true); + expect(param(r, 'issues')).toBeUndefined(); + }); + }); + + // B11: a designation whose use is designation-usage#display is a display: valid as one, and among + // the valid displays a wrong display is told about (tx-ecosystem designation-display suite) + describe('B11 designation-usage#display', () => { + const CS = { resourceType: 'CodeSystem', url: 'http://example.org/cs/du', version: '1.0', status: 'active', content: 'complete', + concept: [{ code: 'B', display: 'Beta', designation: [{ use: { system: 'http://terminology.hl7.org/CodeSystem/designation-usage', code: 'display' }, value: 'Beta alt' }] }] }; + const v = (display) => post('CodeSystem/$validate-code', [{ name: 'url', valueUri: CS.url }, { name: 'code', valueCode: 'B' }, { name: 'display', valueString: display }, { name: 'tx-resource', resource: CS }]); + + test('a wrong display: both are named', async () => { + const r = await v('Wrong'); + expect(param(r, 'result').valueBoolean).toBe(false); + expect(param(r, 'message').valueString).toBe("Wrong Display Name 'Wrong' for http://example.org/cs/du#B. Valid display is one of 2 choices: 'Beta' or 'Beta alt' (for the language(s) '--')"); + }); + test('the designation as the display: valid', async () => { + expect(param(await v('Beta alt'), 'result').valueBoolean).toBe(true); + }); + }); + + // B13: a code that isn't in a fragment code system with no version: no version 'null' in the message + describe('B13 fragment with no version', () => { + const FRAG = { resourceType: 'CodeSystem', url: 'http://example.org/cs/frag', status: 'active', content: 'fragment', concept: [{ code: 'A', display: 'A' }] }; + test.each([ + ['code', [{ name: 'url', valueUri: FRAG.url }, { name: 'code', valueCode: 'NOPE' }]], + ['Coding', [{ name: 'coding', valueCoding: { system: FRAG.url, code: 'NOPE' } }]], + ['CodeableConcept', [{ name: 'codeableConcept', valueCodeableConcept: { coding: [{ system: FRAG.url, code: 'NOPE' }] } }]] + ])('%s', async (_label, params) => { + const r = await post('CodeSystem/$validate-code', [...params, { name: 'tx-resource', resource: FRAG }]); + const issue = param(r, 'issues').resource.issue.find(i => i.extension && i.extension[0].valueString.startsWith('UNKNOWN_CODE_IN_FRAGMENT')); + expect(issue.extension[0].valueString).toBe('UNKNOWN_CODE_IN_FRAGMENT_NO_VERSION'); + expect(issue.details.text).toBe("Unknown Code 'NOPE' in the CodeSystem 'http://example.org/cs/frag' - note that the code system is labeled as a fragment, so the code may be valid in some other fragment"); + }); + + test('in a value set', async () => { + const VS = { resourceType: 'ValueSet', url: 'http://example.org/vs/frag', status: 'active', compose: { include: [{ system: FRAG.url }] } }; + const r = await post('ValueSet/$validate-code', [{ name: 'url', valueUri: VS.url }, { name: 'coding', valueCoding: { system: FRAG.url, code: 'NOPE' } }, + { name: 'tx-resource', resource: FRAG }, { name: 'tx-resource', resource: VS }]); + expect(JSON.stringify(r.body)).not.toMatch(/version 'null'|version ''/); + expect(JSON.stringify(r.body)).toMatch(/UNKNOWN_CODE_IN_FRAGMENT_NO_VERSION/); + }); + + test('with a version: as before', async () => { + const r = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: FRAG.url }, { name: 'code', valueCode: 'NOPE' }, { name: 'tx-resource', resource: { ...FRAG, version: '2' } }]); + expect(JSON.stringify(r.body)).toMatch(/in the CodeSystem 'http:\/\/example.org\/cs\/frag' version '2' - note/); + }); + }); + + // B14: UCUM's unit 1: its display isn't listed twice + describe('B14 UCUM 1', () => { + test('a wrong display for 1: one valid display', async () => { + const r = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: 'http://unitsofmeasure.org' }, { name: 'code', valueCode: '1' }, { name: 'display', valueString: 'milligram' }]); + expect(param(r, 'message').valueString).toBe("Wrong Display Name 'milligram' for http://unitsofmeasure.org#1. Valid display is '1' (en) (for the language(s) '--')"); + }); + test('mg: the code, and its analysis', async () => { + const r = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: 'http://unitsofmeasure.org' }, { name: 'code', valueCode: 'mg' }, { name: 'display', valueString: 'Wrong' }]); + expect(param(r, 'message').valueString).toMatch(/'mg' \(en\)/); + }); + }); + + // B15: an expansion with more than one version of a code system gives every code its version - + // the codes of an imported value set too; with one version of each, no code has one + describe('B15 versions of imported codes', () => { + const cs = (version, code) => ({ resourceType: 'CodeSystem', url: 'http://example.org/cs/mix', version, status: 'active', content: 'complete', concept: [{ code, display: code }] }); + const expand = (include) => post('ValueSet/$expand', [{ name: 'valueSet', resource: { resourceType: 'ValueSet', url: 'http://example.org/vs/mix', status: 'active', compose: { include } } }, + { name: 'tx-resource', resource: cs('1', 'a') }, { name: 'tx-resource', resource: cs('2', 'b') }]); + const G = { valueSet: ['http://hl7.org/fhir/ValueSet/administrative-gender'] }; + + test('two versions, and an import: every code has its version', async () => { + const r = await expand([{ system: 'http://example.org/cs/mix', version: '1', concept: [{ code: 'a' }] }, { system: 'http://example.org/cs/mix', version: '2', concept: [{ code: 'b' }] }, G]); + expect(r.status).toBe(200); + const contains = r.body.expansion.contains; + expect(contains.find(c => c.code === 'a').version).toBe('1'); + expect(contains.find(c => c.code === 'b').version).toBe('2'); + const gender = contains.filter(c => c.system === 'http://hl7.org/fhir/administrative-gender'); + expect(gender.length).toBe(4); + expect(gender.every(c => c.version === '5.0.0')).toBe(true); + }); + + test('one version of each: no code has a version', async () => { + const r = await expand([{ system: 'http://example.org/cs/mix', version: '1', concept: [{ code: 'a' }] }, G]); + expect(r.body.expansion.contains.every(c => c.version === undefined)).toBe(true); + }); + + test('the imported value set\'s own expansion is unchanged afterwards', async () => { + await expand([{ system: 'http://example.org/cs/mix', version: '1', concept: [{ code: 'a' }] }, { system: 'http://example.org/cs/mix', version: '2', concept: [{ code: 'b' }] }, G]); + const r = await post('ValueSet/$expand', [{ name: 'url', valueUri: 'http://hl7.org/fhir/ValueSet/administrative-gender' }]); + expect(r.body.expansion.contains.every(c => c.version === undefined)).toBe(true); + }); + }); + + // B16: a hierarchy that is not is-a doesn't describe subsumption: $subsumes can't be tested + // (tx-ecosystem hierarchy-meaning suite), and $closure finds no subsumption in it + describe('B16 hierarchyMeaning', () => { + const cs = (hierarchyMeaning) => ({ resourceType: 'CodeSystem', url: 'http://example.org/cs/part', version: '1.0', status: 'active', content: 'complete', + ...(hierarchyMeaning ? { hierarchyMeaning } : {}), concept: [{ code: 'A', display: 'A', concept: [{ code: 'A1', display: 'A1' }] }] }); + const subsumes = (meaning) => post('CodeSystem/$subsumes', [{ name: 'system', valueUri: 'http://example.org/cs/part' }, { name: 'codeA', valueCode: 'A' }, + { name: 'codeB', valueCode: 'A1' }, { name: 'tx-resource', resource: cs(meaning) }]); + + test.each(['part-of', 'grouped-by', 'classified-with'])('%s: 422, subsumption can\'t be tested', async (meaning) => { + const r = await subsumes(meaning); + expect(r.status).toBe(422); + expect(msgId(r)).toBe('SUBSUMPTION_CS_HIERARCHY_MEANING'); + expect(r.body.issue[0].details.text).toBe(`The CodeSystem 'http://example.org/cs/part|1.0' has hierarchyMeaning = ${meaning}, so its hierarchy does not describe subsumption, and subsumption cannot be tested`); + }); + test.each([['is-a'], [null]])('%s: subsumes', async (meaning) => { + const r = await subsumes(meaning); + expect(r.status).toBe(200); + expect(param(r, 'outcome').valueCode).toBe('subsumes'); + }); + }); + + // B17: the generalizes filter on a code system resource: the code and its ancestors + describe('B17 generalizes', () => { + const CS = { resourceType: 'CodeSystem', url: 'http://example.org/cs/gen', version: '1.0', status: 'active', content: 'complete', hierarchyMeaning: 'is-a', + concept: [{ code: 'A', display: 'A', concept: [{ code: 'A1', display: 'A1', concept: [{ code: 'A1a', display: 'A1a' }] }, { code: 'A2', display: 'A2' }] }, { code: 'B', display: 'B' }] }; + const VS = (value) => ({ resourceType: 'ValueSet', url: 'http://example.org/vs/gen', status: 'active', compose: { include: [{ system: CS.url, filter: [{ property: 'concept', op: 'generalizes', value }] }] } }); + + test('$expand: the code and its ancestors', async () => { + const r = await post('ValueSet/$expand', [{ name: 'valueSet', resource: VS('A1a') }, { name: 'tx-resource', resource: CS }]); + expect(r.status).toBe(200); + expect(r.body.expansion.contains.map(c => c.code).sort()).toEqual(['A', 'A1', 'A1a']); + }); + test('a root: only itself', async () => { + const r = await post('ValueSet/$expand', [{ name: 'valueSet', resource: VS('B') }, { name: 'tx-resource', resource: CS }]); + expect(r.body.expansion.contains.map(c => c.code)).toEqual(['B']); + }); + test('$validate-code: an ancestor is in, a descendant or sibling is not', async () => { + const v = async (code) => param(await post('ValueSet/$validate-code', [{ name: 'valueSet', resource: VS('A1') }, { name: 'coding', valueCoding: { system: CS.url, code } }, + { name: 'tx-resource', resource: CS }]), 'result').valueBoolean; + expect(await v('A')).toBe(true); + expect(await v('A1')).toBe(true); + expect(await v('A1a')).toBe(false); + expect(await v('A2')).toBe(false); + }); + }); + + // B12: a code system version that is known but can't be used for codes (content example or + // not-present) is still listed among the versions, and the list says why it can't be used + describe('B12 known but unusable versions', () => { + const cs = (version, content) => ({ resourceType: 'CodeSystem', url: 'http://example.org/cs/ex', version, status: 'active', content, concept: [{ code: 'A', display: 'A' }] }); + const vs = { resourceType: 'ValueSet', url: 'http://example.org/vs/ex', status: 'active', compose: { include: [{ system: 'http://example.org/cs/ex', version: '2026-01' }] } }; + + test('$expand: the example version is listed, as one that can\'t be used', async () => { + const r = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'tx-resource', resource: cs('2026-01', 'example') }]); + expect(r.status).toBe(422); + expect(r.body.issue[0].details.text).toMatch(/Valid versions: 2026-01 \(known, but its content is example, so it can't be used\)$/); + }); + + test('with a usable version as well: only the unusable one is marked', async () => { + const r = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'tx-resource', resource: cs('2026-01', 'not-present') }, + { name: 'tx-resource', resource: cs('2025-01', 'complete') }]); + expect(r.body.issue[0].details.text).toMatch(/2025-01 or 2026-01 \(known, but its content is not-present, so it can't be used\)/); + }); + + test('$validate-code: the same', async () => { + const r = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: 'http://example.org/cs/ex' }, { name: 'version', valueString: '2026-02' }, + { name: 'code', valueCode: 'A' }, { name: 'tx-resource', resource: cs('2026-01', 'example') }]); + expect(JSON.stringify(r.body)).toMatch(/2026-01 \(known, but its content is example, so it can't be used\)/); + }); + }); +}); diff --git a/tests/xig/xig-illegal-filter.test.js b/tests/xig/xig-illegal-filter.test.js index 1b07f7365..8d4c44f79 100644 --- a/tests/xig/xig-illegal-filter.test.js +++ b/tests/xig/xig-illegal-filter.test.js @@ -67,9 +67,9 @@ describe('the list with a filter value the XIG doesn\'t have', () => { beforeEach(() => { queries = []; - const record = (rows) => (sql, params, callback) => { + const record = (rows) => async (sql) => { queries.push(sql); - (typeof params === 'function' ? params : callback)(null, rows(sql)); + return rows(sql); }; xig.setDatabaseForTests({ get: record(sql => (/COUNT\(/.test(sql) ? { total: 0, count: 0 } : undefined)), diff --git a/tests/xig/xig-list-cache.test.js b/tests/xig/xig-list-cache.test.js index c6ce57e5f..2542e34a4 100644 --- a/tests/xig/xig-list-cache.test.js +++ b/tests/xig/xig-list-cache.test.js @@ -107,21 +107,15 @@ describe('GET /xig (the list)', () => { // remembers what it was asked let queries; let delay; - const answer = (sql, params, callback) => { - if (typeof params === 'function') { - callback = params; - } - queries.push(sql); - setTimeout(() => callback(null, /COUNT\(/.test(sql) ? { total: 500, count: 500 } : undefined), delay); - }; + const later = (value) => new Promise(resolve => setTimeout(() => resolve(value), delay)); const db = { - get: answer, - all: (sql, params, callback) => { - if (typeof params === 'function') { - callback = params; - } + get: (sql) => { + queries.push(sql); + return later(/COUNT\(/.test(sql) ? { total: 500, count: 500 } : undefined); + }, + all: (sql) => { queries.push(sql); - setTimeout(() => callback(null, []), delay); + return later([]); } }; const counts = () => queries.filter(q => /COUNT\(\*\)/.test(q) && !/LIMIT/.test(q)).length; @@ -191,8 +185,8 @@ describe('GET /xig with auth.loginForExpensive: a filtered list past its first p let app; let token; const db = { - get: (sql, params, callback) => (typeof params === 'function' ? params : callback)(null, { total: 500, count: 500 }), - all: (sql, params, callback) => (typeof params === 'function' ? params : callback)(null, []) + get: async () => ({ total: 500, count: 500 }), + all: async () => [] }; beforeAll(async () => { diff --git a/tests/xig/xig-paging.test.js b/tests/xig/xig-paging.test.js index 76c22b7ee..3b855d954 100644 --- a/tests/xig/xig-paging.test.js +++ b/tests/xig/xig-paging.test.js @@ -1,7 +1,7 @@ // XIG lists are at most PAGE_SIZE rows, paged by offset; resources too big to show inline are // only offered as JSON; every request is logged with its time and size. -const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); const zlib = require('zlib'); const express = require('express'); const request = require('supertest'); @@ -56,7 +56,7 @@ describe('XIG paging helpers', () => { describe('XIG resource page', () => { let db; - const run = (sql, p = []) => new Promise((res, rej) => db.run(sql, p, e => e ? rej(e) : res())); + const run = async (sql, p = []) => { db.run(sql, p); }; const small = { resourceType: 'ValueSet', id: 'small', text: { div: '
small x
' } }; const big = { resourceType: 'ValueSet', id: 'big', compose: { include: [{ concept: [] }] } }; for (let i = 0; big.compose.include[0].concept.length * 40 < MAX_INLINE_RESOURCE * 1.2; i++) { @@ -64,7 +64,7 @@ describe('XIG resource page', () => { } beforeAll(async () => { - db = new sqlite3.Database(':memory:'); + db = new SqliteDatabase(':memory:'); await run('CREATE TABLE Resources (ResourceKey INTEGER, ResourceType TEXT, Id TEXT, Url TEXT, Web TEXT, Name TEXT, Title TEXT, PackageKey INTEGER)'); await run('CREATE TABLE Packages (PackageKey INTEGER, PID TEXT)'); await run('CREATE TABLE DependencyList (TargetKey INTEGER, SourceKey INTEGER, PRIMARY KEY (TargetKey, SourceKey))'); @@ -83,7 +83,7 @@ describe('XIG resource page', () => { afterAll(async () => { xig.setDatabaseForTests(null); - await new Promise(r => db.close(r)); + db.close(); }); test('a long dependency list is shown a page at a time', async () => { diff --git a/tests/xig/xig-resource-filter.test.js b/tests/xig/xig-resource-filter.test.js index 0111f04da..185d14c46 100644 --- a/tests/xig/xig-resource-filter.test.js +++ b/tests/xig/xig-resource-filter.test.js @@ -1,7 +1,7 @@ // The XIG resource list filters: every value from the request goes in as a parameter, never into // the SQL itself, and the text and package searches match what was typed, literally. -const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); const { buildResourceFilter, buildSecureResourceQuery, buildSecureResourceCountQuery } = require('../../xig/xig'); describe('XIG resource filter', () => { @@ -46,9 +46,9 @@ describe('XIG resource filter', () => { }); test('text and package searches run in SQLite, and match literally', async () => { - const db = new sqlite3.Database(':memory:'); - const run = (sql, p = []) => new Promise((res, rej) => db.run(sql, p, e => e ? rej(e) : res())); - const all = (sql, p = []) => new Promise((res, rej) => db.all(sql, p, (e, rows) => e ? rej(e) : res(rows))); + const db = new SqliteDatabase(':memory:'); + const run = async (sql, p = []) => { db.run(sql, p); }; + const all = async (sql, p = []) => db.all(sql, p); try { await run('CREATE TABLE Resources (ResourceKey INTEGER, ResourceType TEXT, Type TEXT, Description TEXT, PackageKey INTEGER, Realm TEXT, Authority TEXT)'); await run('CREATE TABLE Packages (PackageKey INTEGER, Id TEXT, Version TEXT)'); @@ -71,7 +71,7 @@ describe('XIG resource filter', () => { // a quote in a value is just a character expect(await keys({ realm: "uv' OR '1'='1" })).toEqual([]); } finally { - await new Promise(r => db.close(r)); + db.close(); } }); }); diff --git a/tests/xig/xig-sitemap.test.js b/tests/xig/xig-sitemap.test.js index 31bd0928a..6d5808b48 100644 --- a/tests/xig/xig-sitemap.test.js +++ b/tests/xig/xig-sitemap.test.js @@ -1,7 +1,7 @@ // /xig/sitemap.xml: an index of gzipped sitemap files naming every resource page, so crawlers can // find them without paging through the lists (which robots.txt keeps them out of) -const sqlite3 = require('sqlite3'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); const zlib = require('zlib'); const express = require('express'); const request = require('supertest'); @@ -10,7 +10,7 @@ const xig = require('../../xig/xig'); describe('XIG sitemap', () => { let db; let app; - const run = (sql, p = []) => new Promise((res, rej) => db.run(sql, p, e => e ? rej(e) : res())); + const run = async (sql, p = []) => { db.run(sql, p); }; const gunzip = (res, cb) => { const chunks = []; res.on('data', c => chunks.push(c)); @@ -18,7 +18,7 @@ describe('XIG sitemap', () => { }; beforeAll(async () => { - db = new sqlite3.Database(':memory:'); + db = new SqliteDatabase(':memory:'); await run('CREATE TABLE Resources (ResourceKey INTEGER PRIMARY KEY, ResourceType TEXT, Id TEXT, PackageKey INTEGER)'); await run('CREATE TABLE Packages (PackageKey INTEGER, PID TEXT)'); await run("INSERT INTO Packages VALUES (1, 'test.pkg#1.0.0'), (2, 'other.pkg#2.0.0')"); @@ -39,7 +39,7 @@ describe('XIG sitemap', () => { afterAll(async () => { xig.setSitemapSizeForTests(xig.SITEMAP_SIZE); xig.setDatabaseForTests(null); - await new Promise(r => db.close(r)); + db.close(); }); test('the index names one file per SITEMAP_SIZE resources', async () => { diff --git a/translations/Messages.properties b/translations/Messages.properties index 708db7191..8f50058eb 100644 --- a/translations/Messages.properties +++ b/translations/Messages.properties @@ -564,6 +564,8 @@ No_type_found_on_ = No type found on ''{0}'' no_url_in_expand_value_set = No url in expand value set no_url_in_expand_value_set_2 = No url in expand value set 2 NO_VALID_DISPLAY_AT_ALL = Cannot validate display ''{0}'' for {1}#{2} in language {3}: No displays are known +NO_KNOWN_DISPLAY_one = Wrong Display Name ''{4}'' for {1}#{2}. There is no known display for this code (for the language(s) ''{5}''), only the designation {3} +NO_KNOWN_DISPLAY_other = Wrong Display Name ''{4}'' for {1}#{2}. There is no known display for this code (for the language(s) ''{5}''), only {0} designations: {3} NO_VALID_DISPLAY_FOUND_LANG_NONE_one = ''{5}'' is the default display; the code system {1} has no Display Names for the language {4} NO_VALID_DISPLAY_FOUND_LANG_NONE_other = ''{5}'' is the default display; the code system {1} has no Display Names found for the language {4} NO_VALID_DISPLAY_FOUND_LANG_SOME_one = ''{5}'' is the default display; no valid Display Names found for {1}#{2} in the language {4} @@ -1196,6 +1198,7 @@ UNICODE_XML_BAD_CHARS_one = This content includes the character {1} (hex value). UNICODE_XML_BAD_CHARS_other = This content includes the characters {1} (hex values). These characters are illegal in the XML version of FHIR, and there is generally no valid use for such characters Unknown_Code_in = Unknown code ''{0}'' in the CodeSystem ''{1}'' UNKNOWN_CODE_IN_FRAGMENT = Unknown Code ''{0}'' in the CodeSystem ''{1}'' version ''{2}'' - note that the code system is labeled as a fragment, so the code may be valid in some other fragment +UNKNOWN_CODE_IN_FRAGMENT_NO_VERSION = Unknown Code ''{0}'' in the CodeSystem ''{1}'' - note that the code system is labeled as a fragment, so the code may be valid in some other fragment Unknown_Code_in_Version = Unknown code ''{0}'' in the CodeSystem ''{1}'' version ''{2}'' Unknown_Code_in_Version_SCT = Unknown code ''{0}'' in the CodeSystem ''{1}'' version ''{2}'' ({3}) NO_CODE_PROVIDED = No code provided for CodeSystem ''{0}'' @@ -1206,6 +1209,7 @@ UNKNOWN_CODESYSTEM_VERSION_NONE = A definition for CodeSystem ''{0}'' version '' UNKNOWN_CODESYSTEM_CODING_NOT_CHECKED = A definition for the code system ''{0}'' could not be found, so this coding was not checked. The CodeableConcept is still valid: another coding is in the value set UNKNOWN_CODESYSTEM_EXP = A definition for CodeSystem ''{0}'' could not be found, so the value set cannot be expanded UNKNOWN_CODESYSTEM_VERSION_EXP = A definition for CodeSystem ''{0}'' version ''{1}'' could not be found, so the value set cannot be expanded. Valid versions: {2} +CODESYSTEM_VERSION_NOT_USABLE = {0} (known, but its content is {1}, so it can''t be used) UNKNOWN_CODESYSTEM_VERSION_EXP_NONE = A definition for CodeSystem ''{0}'' version ''{1}'' could not be found, so the value set cannot be expanded. No versions of this code system are known Unknown_Data_format_ = Unknown Data format ''{0}'' Unknown_Date_format_ = Unknown Date format ''{0}'' @@ -1502,6 +1506,10 @@ TX_PARAM_NOT_SUPPORTED = The parameter ''{0}'' is not supported by this system TX_PARAM_PROFILE_RESOURCE = The parameter ''profile'' is only supported as an inline Parameters resource, not a resource of type {0} TX_PARAM_PROFILE_TYPE = The parameter ''profile'' is only supported as an inline Parameters resource, not a value of type {0} TX_PARAM_PROFILE_VALUE = The parameter ''profile'' is only supported as an inline Parameters resource, not the value ''{0}'' +TX_PARAM_INVALID_VALUE = The parameter ''{0}'' has the value {1} as a {2}, which isn''t valid: a {2} is a JSON {3} +TX_PARAM_WRONG_TYPE = The parameter ''{0}'' has {1}, but its value must be {2} +TX_PARAM_VERSION_RULE_INVALID = The value ''{1}'' of the parameter ''{0}'' isn''t valid: it must be the url of a {2}, then ''|'', then the version +TX_PARAM_CACHE_ID_WITHDRAWN = The parameter ''cache-id'' is no longer supported: start a cache with $cache-control (mode=start), and send the cache-id it returns in the HTTP header ''X-Cache-Id'' FILTER_VALUE_UNKNOWN_CODE = The filter value ''{0}'' is not a code in {1} XHTML_CONTROL_NO_SOURCE = The xhtml node at ''{0}'' does not have a class attribute to indicate its source (boilerplate, generated, or original) and this is required by the profile {1} XHTML_XHTML_MIXED_LANG = The xhtml has some language sections ({0}), and also has content that is not in a language section @@ -1623,4 +1631,5 @@ TRANSLATION_WARNING_NOMAP_other = This CodeableConcept has the codes {1} and {2} TRANSLATION_WARNING_DENIED_one = This CodeableConcept has the codes {1} and {2}, but the ConceptMap {3} says that {1} is not related to {2} TRANSLATION_WARNING_DENIED_other = This CodeableConcept has the codes {1} and {2}, but the ConceptMaps {3} say that {1} is not related to {2} TRANSLATION_WARNING_OTHER_one = This CodeableConcept has the codes {1} and {2}, but the ConceptMap {3} maps {1} to {4}. Check that these codes belong together -TRANSLATION_WARNING_OTHER_other = This CodeableConcept has the codes {1} and {2}, but the ConceptMaps {3} map {1} to {4}. Check that these codes belong together \ No newline at end of file +TRANSLATION_WARNING_OTHER_other = This CodeableConcept has the codes {1} and {2}, but the ConceptMaps {3} map {1} to {4}. Check that these codes belong together +MIMETYPE_INVALID = The code ''{0}'' isn''t a valid media type (RFC 9110 section 8.3.1): the error is at character {1} diff --git a/tx/cs/cs-api.js b/tx/cs/cs-api.js index 92935eb50..8462b5c52 100644 --- a/tx/cs/cs-api.js +++ b/tx/cs/cs-api.js @@ -484,6 +484,12 @@ class CodeSystemProvider { */ hasParents() { return false; } + /** + * @returns {string|null} what the code system's hierarchy means (CodeSystem.hierarchyMeaning: is-a, + * part-of, grouped-by, classified-with), if it says; null means is-a + */ + hierarchyMeaning() { return null; } + /** * @returns {string} true if the code system nominates an enumeration to use in place of iterating (UCUM) */ diff --git a/tx/cs/cs-cs.js b/tx/cs/cs-cs.js index ebab417c5..95bf13ad6 100644 --- a/tx/cs/cs-cs.js +++ b/tx/cs/cs-cs.js @@ -366,6 +366,13 @@ class FhirCodeSystemProvider extends BaseCSServices { return this.hasHierarchyFlag; } + /** + * @returns {string|null} CodeSystem.hierarchyMeaning, if it has one + */ + hierarchyMeaning() { + return (this.codeSystem && this.codeSystem.jsonObj && this.codeSystem.jsonObj.hierarchyMeaning) || null; + } + /** * @param {string} checkVersion - First version * @param {string} actualVersion - Second version @@ -1025,7 +1032,9 @@ class FhirCodeSystemProvider extends BaseCSServices { if (!(ctxt instanceof FhirCodeSystemProviderContext) || (typeof code === 'string' && ctxt.code !== code)) { return null; } - return new Set(this.hasParents() ? this.codeSystem.getAncestors(ctxt.code) : []); + // a hierarchy that isn't is-a doesn't say anything subsumes anything (triage B16) + const isA = !this.hierarchyMeaning() || this.hierarchyMeaning() === 'is-a'; + return new Set(this.hasParents() && isA ? this.codeSystem.getAncestors(ctxt.code) : []); } /** @@ -1207,7 +1216,7 @@ class FhirCodeSystemProvider extends BaseCSServices { } // Supported hierarchy filters if ((prop === 'concept' || prop === 'code') && - ['is-a', 'descendent-of', 'descendent-leaf', 'is-not-a', 'child-of', 'in', 'not-in', '=', 'regex'].includes(op)) { + ['is-a', 'descendent-of', 'descendent-leaf', 'is-not-a', 'child-of', 'generalizes', 'in', 'not-in', '=', 'regex'].includes(op)) { return true; } @@ -1619,6 +1628,19 @@ class FhirCodeSystemProvider extends BaseCSServices { } else if (op === 'child-of') { // Find all descendants of the specified code await this._addChildren(results, value); + } else if (op === 'generalizes') { + // the code and the codes it is a kind of: its ancestors (triage B17) + const concept = this.codeSystem.getConceptByCode(value); + if (concept) { + results.add(concept, 0); + for (const code of this.codeSystem.getAncestors(value)) { + this.opContext.deadCheck('cs:conceptFilter:generalizes'); + const ancestor = this.codeSystem.getConceptByCode(code); + if (ancestor && code !== value) { + results.add(ancestor, 0); + } + } + } } else if (op === 'is-not-a') { // Find all concepts that are NOT descendants of the specified code const excludeDescendants = this.codeSystem.getDescendants(value); diff --git a/tx/cs/cs-mimetypes.js b/tx/cs/cs-mimetypes.js index 738ebf959..c95206d43 100644 --- a/tx/cs/cs-mimetypes.js +++ b/tx/cs/cs-mimetypes.js @@ -135,6 +135,12 @@ const IANA_MEDIA_TYPES_URL = 'https://www.iana.org/assignments/media-types/media const IANA_MEDIA_TYPES_FILE = 'media-types.xml'; const IANA_DOWNLOAD_TIMEOUT = 15000; +// RFC 9110 section 5.6.2: tchar (a token is 1*tchar), and section 5.6.4: qdtext and the second +// character of a quoted-pair (obs-text, %x80-FF, included) +const TCHAR = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]$/; +const QDTEXT = /^[\t !\x23-\x5B\x5D-\x7E\x80-\xFF]$/; +const QPAIR = /^[\t \x21-\x7E\x80-\xFF]$/; + class MimeTypeConcept { constructor(code) { this.code = code; @@ -171,71 +177,116 @@ class MimeTypeConcept { if (!this.mimeType.isValid) { return code; } - const segments = code.split(';'); - const params = []; - for (const segment of segments.slice(1)) { - const trimmed = segment.trim(); - if (trimmed === '') { - continue; - } - const eq = trimmed.indexOf('='); - if (eq === -1) { - // not a name=value pair. The parser ignores it, but dropping it here would make the - // canonical form say something the submitted code did not, so it is carried through - - // untouched, since only parameter NAMES fold and nothing says this is one - params.push({ name: trimmed.toLowerCase(), text: trimmed }); - continue; - } - const name = trimmed.slice(0, eq).trim().toLowerCase(); - const value = trimmed.slice(eq + 1).trim(); - params.push({ - name: name, - text: name + '=' + (CASE_INSENSITIVE_VALUES.has(name) ? value.toLowerCase() : value) - }); - } + const params = this.mimeType.raw.map(p => ({ + name: p.name, + text: p.name + '=' + (CASE_INSENSITIVE_VALUES.has(p.name) ? p.text.toLowerCase() : p.text) + })); // by name, then by the whole parameter, so a repeated name is still ordered predictably params.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : (a.text < b.text ? -1 : a.text > b.text ? 1 : 0))); - return [segments[0].trim().toLowerCase(), ...params.map(p => p.text)].join('; '); + return [this.mimeType.type + '/' + this.mimeType.subtype, ...params.map(p => p.text)].join('; '); } + /** + * Parse a media type by the grammar of RFC 9110 section 8.3.1 (which is RFC 2045 section 5.1's, + * written for HTTP): + * + * media-type = type "/" subtype parameters + * type, subtype = token + * parameters = *( OWS ";" OWS [ parameter ] ) + * parameter = parameter-name "=" parameter-value + * parameter-name = token + * parameter-value = ( token / quoted-string ) + * + * Anything else is not a media type: no whitespace around the '/' or the '=', a parameter has a + * name and a value, a quoted string is closed (a ';' inside one is part of the value), and no + * leading or trailing whitespace. Type, subtype and parameter names are case-insensitive; + * parameter values are case-sensitive unless the parameter says otherwise (CASE_INSENSITIVE_VALUES) + * @param {string} code + * @returns {{type: string, subtype: string, params: Map, raw: Object[], isValid: boolean, source: string, errorAt?: number}} + */ #parseMimeType(code) { - // type/subtype with optional parameters. Type, subtype and parameter names are all - // case-insensitive (RFC 9110); parameter values are case-sensitive unless the parameter - // says otherwise, and charset is the one in common use that says otherwise (RFC 2046) - const trimmed = code.trim(); - const segments = trimmed.split(';'); - const typeParts = segments[0].trim().split('/'); - - if (typeParts.length !== 2 || !typeParts[0].trim() || !typeParts[1].trim()) { - return { type: '', subtype: '', params: new Map(), isValid: false, source: trimmed }; + let i = 0; + // where it went wrong: i, 1-based, so the start of the code is character 1 + const fail = () => ({ type: '', subtype: '', params: new Map(), raw: [], isValid: false, source: code, errorAt: Math.min(i, code.length - 1) + 1 }); + const token = () => { + const st = i; + while (i < code.length && TCHAR.test(code[i])) { + i++; + } + return code.substring(st, i); + }; + const ows = () => { + while (i < code.length && (code[i] === ' ' || code[i] === '\t')) { + i++; + } + }; + const type = token(); + if (!type || code[i] !== '/') { + return fail(); + } + i++; + const subtype = token(); + if (!subtype) { + return fail(); } - const params = new Map(); - for (const segment of segments.slice(1)) { - const eq = segment.indexOf('='); - if (eq === -1) { + const raw = []; + while (i < code.length) { + ows(); + if (code[i] !== ';') { + return fail(); + } + i++; + ows(); + if (i === code.length || code[i] === ';') { + // an empty parameter: allowed (RFC 9110 '[ parameter ]'), but not trailing whitespace + if (i === code.length && /\s$/.test(code)) { + return fail(); + } continue; } - const name = segment.slice(0, eq).trim().toLowerCase(); - let value = segment.slice(eq + 1).trim(); - if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) { - value = value.slice(1, -1); + const name = token().toLowerCase(); + if (!name || code[i] !== '=') { + return fail(); + } + i++; + let value; + let text; + if (code[i] === '"') { + const st = i; + i++; + value = ''; + while (i < code.length && code[i] !== '"') { + if (code[i] === '\\') { + i++; + if (i === code.length || !QPAIR.test(code[i])) { + return fail(); + } + } else if (!QDTEXT.test(code[i])) { + return fail(); + } + value = value + code[i]; + i++; + } + if (i === code.length) { + return fail(); // not closed + } + i++; + text = code.substring(st, i); + } else { + value = token(); + if (!value) { + return fail(); + } + text = value; } if (CASE_INSENSITIVE_VALUES.has(name)) { value = value.toLowerCase(); } - if (name) { - params.set(name, value); - } + params.set(name, value); + raw.push({ name, text }); } - - return { - type: typeParts[0].trim().toLowerCase(), - subtype: typeParts[1].trim().toLowerCase(), - params: params, - isValid: true, - source: trimmed - }; + return { type: type.toLowerCase(), subtype: subtype.toLowerCase(), params, raw, isValid: true, source: code }; } isValid() { @@ -432,7 +483,10 @@ class MimeTypeServices extends CodeSystemProvider { return { context: concept, message: null }; } - return { context: null, message: undefined}; + // why it isn't one, as well as that the code isn't known + const at = concept.mimeType.errorAt; + return { context: null, message: at && this.opContext && this.opContext.i18n + ? this.opContext.i18n.translate('MIMETYPE_INVALID', this.opContext.langs, [code, at]) : undefined }; } /** diff --git a/tx/cs/cs-snomed.js b/tx/cs/cs-snomed.js index df22a3dca..2516ba007 100644 --- a/tx/cs/cs-snomed.js +++ b/tx/cs/cs-snomed.js @@ -7,7 +7,7 @@ const { } = require('../sct/structures'); const { SnomedExpressionServices, SnomedExpression, SnomedConcept, - SnomedExpressionParser, NO_REFERENCE, SnomedServicesRenderOption + SnomedExpressionParser, NO_REFERENCE, SnomedServicesRenderOption, SnomedExpressionStatus } = require('../sct/expressions'); const {DesignationUse} = require("../library/designations"); const {BaseCSServices} = require("./cs-base"); @@ -2392,8 +2392,8 @@ class SnomedServices { const baseSet = this._eclResolveSet(await this._evalECLNode(node.base, opContext), opContext); // Only gather what this refinement can look at: the inbound relationships (for R // attributes) and the concrete values are costly to collect for every concept - const needs = this._refinementNeeds(node.refinement); await this._eclPrepareRefinement(node.refinement, opContext); + const needs = this._refinementNeeds(node.refinement); // The concepts that can possibly match, found from the attribute values' inbound // relationships - when that is a smaller job than testing every concept in the base const candidates = await this._refinementCandidates(node.refinement, baseSet.length, opContext); @@ -2412,23 +2412,31 @@ class SnomedServices { /** * What the relationship records for a refinement must include: inbound relationships - * when some attribute is reversed (R), concrete values when some comparison is concrete - * (numeric / string / boolean). + * when some attribute is reversed (R) - the inbound is-a relationships (a concept's children) + * only when the reversed attribute can be is-a, as there are many of them - and concrete values + * when some comparison is concrete (numeric / string / boolean). After _eclPrepareRefinement, + * which works out the attribute types * @param {object} refinement - * @returns {{inbound: boolean, concrete: boolean}} + * @returns {{inbound: boolean, inboundIsA: boolean, concrete: boolean}} */ _refinementNeeds = function (refinement) { - const needs = { inbound: false, concrete: false, lean: true }; + const needs = { inbound: false, inboundIsA: false, concrete: false, lean: true }; const walk = (n) => { if (!n) return; if (n.type === ECLNodeType.ATTRIBUTE) { - if (n.reverse) needs.inbound = true; + if (n.reverse) { + needs.inbound = true; + // R 116680003 |Is a| = X: is-a is an attribute (a 246061005 |Attribute|), in either direction + const t = n._eclResolved && n._eclResolved.types; + if (!t || t.any || t.types.has(this.isAIndex)) needs.inboundIsA = true; + } if (n.comparison && n.comparison.type !== ECLNodeType.EXPRESSION_COMPARISON) needs.concrete = true; } else if (Array.isArray(n.attributes)) { n.attributes.forEach(walk); } else { // a refinement shape this doesn't know: collect everything needs.inbound = true; + needs.inboundIsA = true; needs.concrete = true; } }; @@ -2821,7 +2829,8 @@ class SnomedServices { if (inbounds) { for (const relIdx of this.refs.getReferences(inbounds) || []) { const rel = lean ? this.relationships.getRelationshipCore(relIdx) : this.relationships.getRelationship(relIdx); - if (rel.active && rel.relType !== this.isAIndex) { + // the inbound is-a relationships only when asked for (_refinementNeeds) + if (rel.active && (rel.relType !== this.isAIndex || (needs && needs.inboundIsA))) { out.push({ ...rel, inbound: true }); } } @@ -3324,6 +3333,11 @@ class SnomedProvider extends BaseCSServices { if (ctxt.isComplex()) { return this.sct.expressionServices.renderExpression(ctxt.expression, SnomedServicesRenderOption.Minimal); + } else if (ctxt.source && ctxt.expression && ctxt.getReference() !== NO_REFERENCE) { + // a single concept written as an expression (with its term, or a definition status): the + // normal form is the concept id, and <<< if it was given (triage B8) + const id = this.sct.getConceptId(ctxt.getReference()); + return (ctxt.expression.status === SnomedExpressionStatus.SubsumedBy ? '<<<' : '') + id; } else { return ctxt.getCode() || this.sct.getConceptId(ctxt.getReference()); } @@ -3843,13 +3857,18 @@ class SnomedProvider extends BaseCSServices { // the normal forms: only when asked for by name (not by default, not by property=*) this.#addNormalFormProperties(ctxt, props, params); if (ctxt instanceof SnomedExpressionContext) { - // ignore concepts for now, but list refinements and refinement groups + // ignore concepts for now, but list refinements and refinement groups: the attributes + // asked for, as for a concept's (all of them when no property is asked for; triage B9) for (const refinement of ctxt.expression.refinements) { - await this._addRefinementProperty(params, refinement); + if (this._hasProp(props, refinement.name.code, true)) { + await this._addRefinementProperty(params, refinement); + } } for (const refinementGroup of ctxt.expression.refinementGroups) { for (const refinement of refinementGroup.refinements) { - await this._addRefinementProperty(params, refinement); + if (this._hasProp(props, refinement.name.code, true)) { + await this._addRefinementProperty(params, refinement); + } } } } @@ -4701,7 +4720,9 @@ class SnomedProvider extends BaseCSServices { return null; } const id = this.sct.getConceptId(ref); - if ((await this.code(ctxt)) !== id) { + // only the concept id as it is: not another spelling of it (a term, ===), which code() now + // normalises to the id (triage B8) + if ((ctxt.source || id) !== id) { return null; } const seen = new Set(); diff --git a/tx/cs/cs-ucum.js b/tx/cs/cs-ucum.js index 757168e0a..d88ec76a7 100644 --- a/tx/cs/cs-ucum.js +++ b/tx/cs/cs-ucum.js @@ -187,7 +187,10 @@ class UcumCodeSystemProvider extends BaseCSServices { // Primary display (analysis) const analysis = this.ucumService.analyse(ctxt.code); displays.addDesignation(true, 'active', 'en', DesignationUse.DISPLAY, ctxt.code); - displays.addDesignation(true, 'active', 'en', DesignationUse.SYNONYM, analysis); + // not again when it's the code (the unit 1, say: triage B14) + if (analysis && analysis !== ctxt.code) { + displays.addDesignation(true, 'active', 'en', DesignationUse.SYNONYM, analysis); + } // Common unit display if available if (this.commonUnits) { diff --git a/tx/library/designations.js b/tx/library/designations.js index 31d65cfad..271610473 100644 --- a/tx/library/designations.js +++ b/tx/library/designations.js @@ -187,6 +187,8 @@ const DisplayDifference = { }; +const DESIGNATION_USAGE = 'http://terminology.hl7.org/CodeSystem/designation-usage'; + /** * Standard use codes for designations */ @@ -744,7 +746,10 @@ class Designations { if ((cd.use.system === DesignationUse.DISPLAY.system && cd.use.code === DesignationUse.DISPLAY.code) || (cd.use.system === DesignationUse.PREFERRED.system && - cd.use.code === DesignationUse.PREFERRED.code)) { + cd.use.code === DesignationUse.PREFERRED.code) || + // designation-usage#display (THO; 303 R4 core resources use it): a display, so it is one of + // the valid displays a wrong display is told about (triage B11) + (cd.use.system === DESIGNATION_USAGE && cd.use.code === 'display')) { return true; } return this.source && this.source.isDisplay(cd); diff --git a/tx/library/parameter-types.js b/tx/library/parameter-types.js new file mode 100644 index 000000000..412d3f7c5 --- /dev/null +++ b/tx/library/parameter-types.js @@ -0,0 +1,190 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Checks the types of the values of a request's parameters, before any of them is read: a value + * that isn't what its value[x] says it is (valueCode: 42 - not valid FHIR JSON), or a parameter + * the operations know with a value of the wrong kind (url as a valueInteger), is a 400 with an + * OperationOutcome saying which parameter, not a crash, or an answer that echoes invalid content. + * + * Parameters this doesn't know aren't checked here (the operations ignore or refuse them). + */ + +const { Issue } = require('./operation-outcome'); + +// value[x] primitive types, by the JSON type FHIR represents them with +const JSON_STRING = ['String', 'Code', 'Uri', 'Url', 'Canonical', 'Id', 'Oid', 'Uuid', 'Markdown', 'Base64Binary', + 'Date', 'DateTime', 'Instant', 'Time', 'Integer64']; +const JSON_NUMBER = ['Integer', 'PositiveInt', 'UnsignedInt', 'Decimal']; +const JSON_BOOLEAN = ['Boolean']; +const WHOLE = ['Integer', 'PositiveInt', 'UnsignedInt']; + +// the kind of value each parameter the operations read must have +const KINDS = { + string: ['url', 'valueSetVersion', 'system', 'systemVersion', 'version', 'code', 'display', 'displayLanguage', + 'filter', 'context', 'property', 'designation', 'useSupplement', 'system-version', 'check-system-version', + 'force-system-version', 'default-valueset-version', 'check-valueset-version', 'force-valueset-version', + 'codeA', 'codeB', 'sourceCode', 'sourceSystem', 'sourceScope', 'targetCode', 'targetSystem', 'targetScope', + 'conceptMapVersion', 'cache-id', 'date'], + boolean: ['activeOnly', 'excludeNested', 'excludeNotForUI', 'excludePostCoordinated', 'includeDesignations', + 'includeDefinition', 'abstract', 'lenient-display-validation', 'membershipOnly', 'inferSystem', + 'default-to-latest-version', 'no-cache', 'valueset-membership-only', 'diagnostics', 'reverse'], + integer: ['count', 'offset', 'limit'], + Coding: ['coding', 'codingA', 'codingB', 'sourceCoding', 'targetCoding'], + CodeableConcept: ['codeableConcept', 'sourceCodeableConcept'] +}; +const KIND_OF = new Map(); +for (const [kind, names] of Object.entries(KINDS)) { + for (const n of names) { + KIND_OF.set(n, kind); + } +} + +/** whether a parameter is one the operations read as a string (a query string's 'true' is the string 'true' then) */ +function isStringParameter(name) { + return KIND_OF.get(name) === 'string'; +} + +/** the value[x] of a parameter: [type (e.g. 'Code'), value], or null */ +function valueOf(p) { + for (const key of Object.keys(p)) { + if (key.startsWith('value') && key.length > 5 && key[5] === key[5].toUpperCase()) { + return [key.substring(5), p[key]]; + } + } + return null; +} + +/** why the value isn't valid JSON for its type, or null */ +function jsonProblem(type, value) { + if (JSON_STRING.includes(type)) { + return typeof value === 'string' ? null : 'string'; + } + if (JSON_NUMBER.includes(type)) { + if (typeof value !== 'number' || !Number.isFinite(value)) { + return 'number'; + } + return WHOLE.includes(type) && !Number.isInteger(value) ? 'whole number' : null; + } + if (JSON_BOOLEAN.includes(type)) { + return typeof value === 'boolean' ? null : 'boolean'; + } + return null; // a complex type: its own content isn't looked at here +} + +/** whether a value of this type is a value of this kind */ +function kindAccepts(kind, type, value) { + switch (kind) { + case 'string': + return JSON_STRING.includes(type); + case 'boolean': + return type === 'Boolean' || (JSON_STRING.includes(type) && (value === 'true' || value === 'false')); + case 'integer': + return WHOLE.includes(type) || (JSON_STRING.includes(type) && /^-?[0-9]+$/.test(value)); + default: + return type === kind; + } +} + +const KIND_NAMES = { + string: 'a string (or code, uri...)', + boolean: 'a boolean', + integer: 'an integer', + Coding: 'a Coding', + CodeableConcept: 'a CodeableConcept' +}; + +function display(value) { + const s = JSON.stringify(value); + return s && s.length > 60 ? s.substring(0, 60) + '...' : String(s); +} + +/** + * The first problem with the types of the parameters' values, as a 400 Issue, or null + * @param {Object} params - the Parameters resource (JSON) + * @param {Object} i18n - the worker's I18nSupport + * @param {Object} langs - the languages for the message + * @returns {Issue|null} + */ +function parameterTypeIssue(params, i18n, langs) { + const check = (list, path) => { + let i = 0; + for (const p of Array.isArray(list) ? list : []) { + const here = `${path}[${i}]`; + i++; + if (!p || typeof p !== 'object') { + continue; + } + // the cache-id parameter is withdrawn (it's the X-Cache-Id header now), wherever it is + if (p.name === 'cache-id') { + return cacheIdIssue(here, i18n, langs); + } + const v = valueOf(p); + if (v) { + const [type, value] = v; + const wanted = jsonProblem(type, value); + if (wanted) { + const msg = i18n.translate('TX_PARAM_INVALID_VALUE', langs, [p.name, display(value), 'value' + type, wanted]); + return new Issue('error', 'invalid', here, 'TX_PARAM_INVALID_VALUE', msg, 'invalid-data', 400).handleAsOO(400); + } + } + const kind = path === 'Parameters.parameter' ? KIND_OF.get(p.name) : null; + if (kind) { + const ok = v ? kindAccepts(kind, v[0], v[1]) : false; + if (!ok && (v || p.resource || p.part)) { + const actual = v ? 'a value' + v[0] : p.resource ? 'a resource' : 'parts'; + const msg = i18n.translate('TX_PARAM_WRONG_TYPE', langs, [p.name, actual, KIND_NAMES[kind]]); + return new Issue('error', 'invalid', here, 'TX_PARAM_WRONG_TYPE', msg, 'invalid-data', 400).handleAsOO(400); + } + } + if (p.part) { + const issue = check(p.part, here + '.part'); + if (issue) { + return issue; + } + } + // a Parameters inside a parameter (e.g. $batch-validate-code's validation): only for the + // cache-id, as its parameters' types are the inner operation's business + if (p.resource && p.resource.resourceType === 'Parameters') { + const inner = cacheIdIn(p.resource.parameter, here + '.resource.parameter', i18n, langs); + if (inner) { + return inner; + } + } + } + return null; + }; + return params ? check(params.parameter, 'Parameters.parameter') : null; +} + +/** the 400 for a cache-id parameter at the path */ +function cacheIdIssue(path, i18n, langs) { + const msg = i18n.translate('TX_PARAM_CACHE_ID_WITHDRAWN', langs, []); + return new Issue('error', 'not-supported', path, 'TX_PARAM_CACHE_ID_WITHDRAWN', msg, 'not-supported', 400).handleAsOO(400); +} + +/** a cache-id parameter anywhere in the list (parts and nested Parameters too), as a 400 Issue, or null */ +function cacheIdIn(list, path, i18n, langs) { + let i = 0; + for (const p of Array.isArray(list) ? list : []) { + const here = `${path}[${i}]`; + i++; + if (!p || typeof p !== 'object') { + continue; + } + if (p.name === 'cache-id') { + return cacheIdIssue(here, i18n, langs); + } + const inner = cacheIdIn(p.part, here + '.part', i18n, langs) + || (p.resource && p.resource.resourceType === 'Parameters' ? cacheIdIn(p.resource.parameter, here + '.resource.parameter', i18n, langs) : null); + if (inner) { + return inner; + } + } + return null; +} + +module.exports = { parameterTypeIssue, isStringParameter }; diff --git a/tx/openapi-operations.js b/tx/openapi-operations.js index feab8d99d..b822f2710 100644 --- a/tx/openapi-operations.js +++ b/tx/openapi-operations.js @@ -26,8 +26,8 @@ const p = (name, type, max, doc, extra = {}) => ({ name, type, min: 0, max, doc, // Additional resources, and the cache they can be kept in. Every operation that resolves // code systems or value sets reads these. const RESOURCES = [ - p('tx-resource', 'Resource', '*', 'A CodeSystem, ValueSet or ConceptMap the operation may need (e.g. a value set that the value set being expanded imports), used instead of any the server has with the same url and version'), - p('cache-id', 'id', '1', 'A cache of tx-resources started with $cache-control (mode=start). Sending it in the `X-Cache-Id` header instead is preferred') + p('tx-resource', 'Resource', '*', 'A CodeSystem, ValueSet or ConceptMap the operation may need (e.g. a value set that the value set being expanded imports), used instead of any the server has with the same url and version. ' + + 'To keep them in a cache, start one with $cache-control (mode=start) and send its id in the `X-Cache-Id` header (the old `cache-id` parameter is refused)') ]; // TxParameters (params.js): read by every operation that works with code systems and value sets diff --git a/tx/params.js b/tx/params.js index 624efe235..c4e7d7bfc 100644 --- a/tx/params.js +++ b/tx/params.js @@ -568,12 +568,19 @@ class TxParameters { return result; } + /** + * A version rule: the url of a code system (or value set), '|', and the version. Anything else + * (no '|', or nothing either side of it) is a 400 that says which parameter, and why + */ seeVersionRule(url, vs, mode) { - let sl = url ? url.split('|') : []; - if (sl.length === 2) { - this.versionRules.push(new VersionRule(sl[0], sl[1], vs, mode)); + const i = typeof url === 'string' ? url.indexOf('|') : -1; + if (i > 0 && i < url.length - 1) { + this.versionRules.push(new VersionRule(url.substring(0, i), url.substring(i + 1), vs, mode)); } else { - throw new Error('Unable to understand ' + mode + ' system version "' + url + '"'); + const name = new VersionRule('', '', vs, mode).asParam().split('=')[0]; + throw new Issue('error', 'invalid', null, 'TX_PARAM_VERSION_RULE_INVALID', + this.i18n.translate('TX_PARAM_VERSION_RULE_INVALID', this.HTTPLanguages, [name, url, vs ? 'value set' : 'code system']), + 'invalid-data', 400).handleAsOO(400); } } diff --git a/tx/provider.js b/tx/provider.js index 80c6c25a2..7b425ddb2 100644 --- a/tx/provider.js +++ b/tx/provider.js @@ -533,6 +533,22 @@ class Provider { return result; } + /** + * The versions of a code system the library has as a resource that can't be used for codes: + * its content is example or not-present (see listCodeSystemVersions) + * @param {string} url + * @returns {Map} version -> content + */ + unusableCodeSystemVersions(url) { + const result = new Map(); + for (const cs of this.codeSystems.values()) { + if (cs.url == url && cs.version && ['example', 'not-present'].includes(cs.content)) { + result.set(cs.version, cs.content); + } + } + return result; + } + async listCodeSystemVersions(url) { let result = new Set(); for (let cs of this.codeSystems.values()) { diff --git a/tx/sct/ecl.js b/tx/sct/ecl.js index 65c28eb0b..ed3f9bea7 100644 --- a/tx/sct/ecl.js +++ b/tx/sct/ecl.js @@ -415,8 +415,9 @@ class ECLLexer { pos++; } - // Check if immediately followed by .digit (decimal number) - if (pos < this.input.length && + // Check if immediately followed by .digit (decimal number), after a # (see tokenize): + // <<125605004.363698007 is a dotted attribute + if (this.afterHash && pos < this.input.length && this.input[pos] === '.' && pos + 1 < this.input.length && /\d/.test(this.input[pos + 1])) { @@ -473,6 +474,9 @@ class ECLLexer { do { token = this.getNextToken(); tokens.push(token); + // a number with a decimal point is only a number after # (decimalValue = ["-"] 1*digit "." 1*digit, + // always in "#" numericValue): elsewhere a "." after an SCTID is the dot of a dotted attribute + this.afterHash = token.type === ECLTokenType.HASH; } while (token.type !== ECLTokenType.EOF); return tokens; @@ -579,6 +583,13 @@ class ECLParser { 'operators cannot be mixed without parentheses (ECL 6.4). ' + 'Use round brackets to disambiguate.'); } + // exclusionExpressionConstraint = subExpressionConstraint ws exclusion ws subExpressionConstraint: + // one MINUS - unlike AND and OR, A MINUS B MINUS C needs brackets + if (compoundOp === ECLTokenType.MINUS) { + throw new Error( + 'Ambiguous ECL expression: an exclusion (MINUS) has one expression on each side (ECL 6.4); ' + + 'use round brackets for more, e.g. (A MINUS B) MINUS C'); + } compoundOp = operator.type; this.advance(); const right = this.parseRefinedExpressionConstraint(); diff --git a/tx/sct/expressions.js b/tx/sct/expressions.js index 78d01987f..5527d50f2 100644 --- a/tx/sct/expressions.js +++ b/tx/sct/expressions.js @@ -2529,6 +2529,13 @@ class SnomedExpressionServices { */ renderExpression(source, option = SnomedServicesRenderOption.AsIs) { const parts = []; + // the definition status, which is part of what the expression means: <<< (subtype of) is + // always kept; === (equivalent to) is the default, so only as it was given (AsIs) + if (source.status === SnomedExpressionStatus.SubsumedBy) { + parts.push('<<<'); + } else if (source.status === SnomedExpressionStatus.Equivalent && option === SnomedServicesRenderOption.AsIs) { + parts.push('==='); + } this.renderExpressionParts(parts, source, option); return parts.join(''); } diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index c81fe669b..bf0ad6d63 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -769,7 +769,9 @@ class Compiler { return p && p.refinable ? [p.id] : []; } if (name.type === 'Wildcard') { - return [...S.props.values()].filter((p) => p.wildcard).map((p) => p.id); + // any attribute, is-a included: it is an attribute (a 246061005 |Attribute|) like the others, + // in either direction (triage B6), as cs-snomed.js has it + return [...S.props.values()].filter((p) => p.wildcard || (p.isHierarchy && p.refinable)).map((p) => p.id); } if (name.type === 'SubExpressionConstraint' && name.focus.type === 'ConceptReference' && !name.filters) { const id = this.eclConcept(name.focus.conceptId); @@ -780,13 +782,14 @@ class Compiler { const ids = d.toArray(); if (op === 'DESCENDANT_OR_SELF_OF') ids.push(id); const rows = S.conceptRows(ids, this.stats); - const out = []; + // is-a too, when it is one of them (it is a descendant of 246061005 |Attribute|) + const out = new Set(); for (const r of rows.values()) { const p = S.props.get(r.code); - if (p && p.refinable && !p.isHierarchy) out.push(p.id); + if (p && p.refinable) out.add(p.id); } - if (op === 'DESCENDANT_OR_SELF_OF' && S.hierarchy && S.hierarchy.code === name.focus.conceptId) out.push(S.hierarchy.id); - return out; + if (op === 'DESCENDANT_OR_SELF_OF' && S.hierarchy && S.hierarchy.code === name.focus.conceptId) out.add(S.hierarchy.id); + return [...out]; } } throw new Unsupported('ecl-feature', 'attribute name expression'); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 652ccfdaf..16c6a3059 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -399,8 +399,9 @@ class SnomedV2Provider extends SqliteV2Provider { try { const exp = new E.SnomedExpressionParser().parse(code); await svc.checkExpression(exp); // async in main since 1.0.5 (the MRCM range check runs ECL) - if (exp.isSimple() && !exp.concepts[0].literal) { - // a single concept (with its term, say): the concept itself + if (exp.isSimple() && !exp.concepts[0].literal && exp.status !== E.SnomedExpressionStatus.SubsumedBy) { + // a single concept (with its term, or ===, say): the concept itself. Not <<< X, which is + // a subtype of X, not X (triage B8): its normal form keeps the <<< return super._locate(exp.concepts[0].code); } return { context: new NativeExprContext(code, exp), message: null }; @@ -467,7 +468,10 @@ class SnomedV2Provider extends SqliteV2Provider { } this._addNormalForms(null, ctxt.expression, props, params); const svc = this._native(); + // the refinement's attributes asked for, as for a concept's (all of them when no property is + // asked for; triage B9) const add = async (refinement) => { + if (!this._hasProp(props, refinement.name.code, true)) return; const value = new NativeExprContext('', refinement.value); const code = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.Minimal) : refinement.value.concepts[0].code; const description = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.FillMissing) : svc.getDisplayName(refinement.value.concepts[0].reference); @@ -586,7 +590,8 @@ class SnomedV2Provider extends SqliteV2Provider { _nativeAnswer(m, ctxt, rest) { const svc = this._native(); switch (m) { - case 'code': return ctxt.isComplex() ? svc.renderExpression(ctxt.expression, E.SnomedServicesRenderOption.Minimal) : ctxt.source; + case 'code': return ctxt.isComplex() || ctxt.expression.status === E.SnomedExpressionStatus.SubsumedBy + ? svc.renderExpression(ctxt.expression, E.SnomedServicesRenderOption.Minimal) : ctxt.source; case 'display': { const sup = this._displayFromSupplements(ctxt.source); if (sup) return sup; diff --git a/tx/tx.js b/tx/tx.js index 27cd91fac..bf5add782 100644 --- a/tx/tx.js +++ b/tx/tx.js @@ -79,6 +79,7 @@ const {valueSetFromR5} = require("./xversion/xv-valueset"); const {terminologyCapabilitiesFromR5} = require("./xversion/xv-terminologyCapabilities"); const {capabilityStatementFromR5} = require("./xversion/xv-capabiliityStatement"); const {bundleFromR5} = require("./xversion/xv-bundle"); +const { parameterTypeIssue } = require('./library/parameter-types'); const {convertResourceToR5} = require("./xversion/xv-resource"); const ClosureWorker = require("./workers/closure"); const { ClosureStore } = require("./closure/closure-store"); @@ -836,8 +837,8 @@ class TXModule { // Normalise the cache-id from the X-Cache-Id header onto the operation // context once, here, so every worker honours a front-loaded cache no // matter how it later assembles its Parameters (some use buildParameters, - // others read req.body / query directly). An explicit cache-id parameter - // on the request still wins (see setupAdditionalResources). + // others read req.body / query directly). The cache-id parameter is + // withdrawn: a request with one is refused (parameter-types.js). opContext.cacheId = req.get('X-Cache-Id') || null; // named in the message if the operation runs out of time opContext.operationName = OperationContext.operationNameFor(req.path); @@ -1025,6 +1026,26 @@ class TXModule { // CORS layer and produces duplicate, conflicting headers that browsers // reject. + // The query's values (all strings) against the kinds of the parameters the operations know + // (parameter-types.js): count=two is a 400 here, for every operation + router.use((req, res, next) => { + if (req.query && Object.keys(req.query).length > 0) { + const parameter = []; + for (const [name, value] of Object.entries(req.query)) { + for (const v of (Array.isArray(value) ? value : [value])) { + if (typeof v === 'string') { + parameter.push({ name, valueString: v }); + } + } + } + const issue = parameterTypeIssue({ resourceType: 'Parameters', parameter }, this.i18n, this.requestLanguages(req)); + if (issue) { + return res.status(400).json(outcomeFromError(issue)); + } + } + next(); + }); + // JSON body parsing - accept both application/json and application/fhir+json // Handle body that may already be read as a Buffer by app-level middleware router.use((req, res, next) => { @@ -1045,6 +1066,14 @@ class TXModule { } catch (e) { return res.status(e.statusCode || 400).json(outcomeFromError(e)); } + // the parameters' values are what they say they are, and what the parameter needs + // (parameter-types.js): not a crash later, or an answer that echoes invalid content + if (req.body && req.body.resourceType === 'Parameters') { + const issue = parameterTypeIssue(req.body, this.i18n, this.requestLanguages(req)); + if (issue) { + return res.status(400).json(outcomeFromError(issue)); + } + } next(); }; @@ -2147,6 +2176,17 @@ class TXModule { }; } + /** + * The languages a request asks for its messages in (Accept-Language), or the default + */ + requestLanguages(req) { + try { + return this.languages.parse(req.headers ? req.headers['accept-language'] : null); + } catch (e) { + return this.languages.parse(null); + } + } + async shutdown() { this.log.info('Shutting down TX module'); for (const timer of this.timers) { diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 34fc4c002..5a7ad73cc 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -238,6 +238,8 @@ class ValueSetExpander { worker; params; doingVersion = true; + /** the code system versions of the value set being imported (importValueSet) */ + importVersions = null; excludedSystems = new Set(); excludedProviders = []; // {system, cs} - see checkForExclusionVersionSpecialCase excluded = new Set(); @@ -777,6 +779,46 @@ class ValueSetExpander { * reported once - an import used twice, or two imports with the same problem, or one this * expansion has found itself (e.g. a request supplement's), is not reported again */ + /** + * valueset-unclosed (0..1) and its reason, once each on the expansion, whatever number of + * includes (fragments, grammars, imports, a stored expansion) marked it: the first unclosed, + * and one reason with the different reasons in it + * @param {Object} exp - the expansion + */ + #singleUnclosed(exp) { + if (!Array.isArray(exp.extension)) { + return; + } + const UNCLOSED = 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed'; + const REASON = 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason'; + const reasons = []; + let unclosed = null; + let reason = null; + const kept = []; + for (const ext of exp.extension) { + if (ext.url === UNCLOSED) { + if (!unclosed) { + unclosed = ext; + kept.push(ext); + } + } else if (ext.url === REASON) { + if (ext.valueString && !reasons.includes(ext.valueString)) { + reasons.push(ext.valueString); + } + if (!reason) { + reason = { ...ext }; + kept.push(reason); + } + } else { + kept.push(ext); + } + } + if (reason && reasons.length > 0) { + reason.valueString = reasons.join('; '); + } + exp.extension = kept; + } + #addImportedIssues(vs, exp) { if (!this.importedIssues) { return; @@ -1020,9 +1062,24 @@ class ValueSetExpander { // the expansions whose property declarations the codes returned use: the import's, and, for // codes whose details were read only now (see #buildDeferred), the ones that added them const sources = new Set([vs.expansion]); - for (const c of vs.expansion.contains || []) { - await this.worker.checkAndYield('importValueSet'); - count += await this.importValueSetItem(null, c, imports, offset, imported, sources); + // the versions of the code systems the import used: when this expansion has more than one + // version of a code system (doingVersion), its codes carry versions, the imported ones too + // (triage B15) + const prior = this.importVersions; + this.importVersions = new Map(); + for (const p of vs.expansion.parameter || []) { + const v = p.name === 'used-codesystem' ? getValuePrimitive(p) : null; + if (v && v.includes('|')) { + this.importVersions.set(v.substring(0, v.indexOf('|')), v.substring(v.indexOf('|') + 1)); + } + } + try { + for (const c of vs.expansion.contains || []) { + await this.worker.checkAndYield('importValueSet'); + count += await this.importValueSetItem(null, c, imports, offset, imported, sources); + } + } finally { + this.importVersions = prior; } for (const source of sources) { this.importPropertyDefinitions(expansion, source.property, imported); @@ -1033,6 +1090,12 @@ class ValueSetExpander { async importValueSetItem(p, c, imports, offset, imported, sources) { let count = 0; await this.worker.checkAndYield('importValueSetItem'); + const orig = c; + if (this.doingVersion && !c.version && this.importVersions && this.importVersions.has(c.system)) { + // a copy: the import's expansion isn't changed (its own contains are walked below) + c = { ...c, version: this.importVersions.get(c.system) }; + delete c.contains; + } const s = this.keyC(c); if (this.paging && (this.walked < this.offset || this.pageFilled()) && this.passesImports(imports, c.system, c.code, offset) && !(await this.isExcluded(c.system, c.version, c.code))) { @@ -1059,7 +1122,7 @@ class ValueSetExpander { } this.map.set(s, c); } - for (const cc of c.contains || []) { + for (const cc of orig.contains || []) { await this.worker.checkAndYield('importValueSetItem'); count += await this.importValueSetItem(c, cc, imports, offset, imported, sources); } @@ -2550,6 +2613,7 @@ class ValueSetExpander { this.worker.opContext.log('finish up'); + this.#singleUnclosed(exp); let list; if (notClosed.value) { if (!Extensions.has(exp, 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed')) { diff --git a/tx/workers/subsumes.js b/tx/workers/subsumes.js index ec930a9bb..90f456ac4 100644 --- a/tx/workers/subsumes.js +++ b/tx/workers/subsumes.js @@ -295,6 +295,15 @@ class SubsumesWorker extends TerminologyWorker { throw error; } + // a hierarchy that is not is-a (part-of, grouped-by, classified-with) doesn't describe + // subsumption, so it can't be tested (triage B16; as core's TerminologySubsumptionTester) + const meaning = csProvider.hierarchyMeaning(); + if (meaning && meaning !== 'is-a') { + const vurl = csProvider.system() + (csProvider.version() ? '|' + csProvider.version() : ''); + throw new Issue('error', 'not-supported', null, 'SUBSUMPTION_CS_HIERARCHY_MEANING', + this.i18n.translate('SUBSUMPTION_CS_HIERARCHY_MEANING', txp ? txp.HTTPLanguages : null, [vurl, meaning]), 'not-supported', 422); + } + // Validate both codes exist const locateA = await csProvider.locate(codingA.code); if (!locateA || !locateA.context) { diff --git a/tx/workers/validate.js b/tx/workers/validate.js index 59ed5c745..fe555fb9a 100644 --- a/tx/workers/validate.js +++ b/tx/workers/validate.js @@ -642,9 +642,9 @@ class ValueSetChecker { result = true; cause.value = 'code-invalid'; this.worker.opContext.addNote(this.valueSet, 'Not found in Incomplete Code System', this.indentCount); - let msg = this.worker.i18n.translate('UNKNOWN_CODE_IN_FRAGMENT', this.params.HTTPLanguages, [code, cs.system(), cs.version()]); + const [fid, msg] = this.unknownInFragment(code, cs.system(), cs.version()); // messages.push(msg); disabled 15-1-2026 GG - it's not considered invalid if it's just a warning - op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), 'UNKNOWN_CODE_IN_FRAGMENT', msg, 'invalid-code')); + op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), fid, msg, 'invalid-code')); } else { result = false; cause.value = 'code-invalid'; @@ -740,9 +740,9 @@ class ValueSetChecker { result = true; cause.value = 'code-invalid'; this.worker.opContext.addNote(this.valueSet, 'Not found in Incomplete Code System', this.indentCount); - let msg = this.worker.i18n.translate('UNKNOWN_CODE_IN_FRAGMENT', this.params.HTTPLanguages, [code, system, version]); + const [fid, msg] = this.unknownInFragment(code, system, version); // messages.push(msg); it's just a warning - op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), 'UNKNOWN_CODE_IN_FRAGMENT', msg, 'invalid-code')); + op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), fid, msg, 'invalid-code')); } else { result = false; cause.value = 'code-invalid'; @@ -1324,10 +1324,11 @@ class ValueSetChecker { msg(m); op.addIssue(new Issue('error', 'code-invalid', addToPath(path, 'code'), 'Unknown_Code_in_Version', m, 'invalid-code'), true); } else { - m = this.worker.i18n.translate('UNKNOWN_CODE_IN_FRAGMENT', this.params.HTTPLanguages, [c.code, ws, prov.version()]); + let fid; + [fid, m] = this.unknownInFragment(c.code, ws, prov.version()); cause.value = 'code-invalid'; // msg(m); - it's just a warning - op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), 'UNKNOWN_CODE_IN_FRAGMENT', m, 'invalid-code'), true); + op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), fid, m, 'invalid-code'), true); } } } else { @@ -1377,7 +1378,12 @@ class ValueSetChecker { let dc = list.displayCount(this.params.workingLanguages(), null, true); let m; - if (dc === 0) { + if (dc === 0 && list.displayCount(this.params.workingLanguages(), null, false) > 0) { + // no display, but other designations (a synonym, say): a display that is none of + // them is as wrong as any other wrong display + baseMsg = 'NO_KNOWN_DISPLAY'; + m = this.noKnownDisplayMessage(list, defLang, prov.system(), c); + } else if (dc === 0) { severity = 'warning'; baseMsg = 'NO_VALID_DISPLAY_AT_ALL'; m = this.worker.i18n.translate('NO_VALID_DISPLAY_AT_ALL', this.params.HTTPLanguages, @@ -1649,6 +1655,34 @@ class ValueSetChecker { } } + /** + * The message (and its id) for a code that isn't in a code system that is a fragment + * @param {string} code + * @param {string} system + * @param {string|null} version + * @returns {string[]} [message id, message] + */ + unknownInFragment(code, system, version) { + // a code system with no version: no version '' (or 'null') in the message (triage B13) + const id = version ? 'UNKNOWN_CODE_IN_FRAGMENT' : 'UNKNOWN_CODE_IN_FRAGMENT_NO_VERSION'; + return [id, this.worker.i18n.translate(id, this.params.HTTPLanguages, version ? [code, system, version] : [code, system])]; + } + + /** + * The message for a display that isn't right for a code that has no display (for the languages), + * only other designations (a synonym, say): that there's no known display, and what it does have + * @param {Designations} list + * @param {Object} defLang + * @param {string} system + * @param {Object} c - the coding (code, display) + * @returns {string} + */ + noKnownDisplayMessage(list, defLang, system, c) { + const shown = list.presentCount(this.params.workingLanguages(), defLang.value, false); + return this.worker.i18n.translate('NO_KNOWN_DISPLAY' + (shown === 1 ? '_one' : '_other'), this.params.HTTPLanguages, + [shown === 1 ? '' : shown.toString(), system, c.code, list.present(this.params.workingLanguages(), defLang.value, false), c.display, this.params.langSummary()]); + } + async checkDisplays(list, defLang, c, msg, op, path) { let hd = list.hasDisplay(this.params.workingLanguages(), null, c.display, false, DisplayCheckingStyle.CASE_INSENSITIVE) if (!hd.found) { @@ -1667,10 +1701,19 @@ class ValueSetChecker { } let dc = list.displayCount(this.params.workingLanguages(), null, true); let mid = baseMsg; + // no display, but other designations (a synonym, say): they are what the message lists + let noDisplay = false; if (severity !== 'information') { if (dc === 0) { + const s0 = severity; severity = 'warning'; dc = list.displayCount(this.params.workingLanguages(), null, false); + noDisplay = dc > 0; + if (noDisplay) { + // the designations it has are what a display can be, so a display that is none of them + // is as wrong as any other wrong display + severity = s0; + } } } @@ -1678,7 +1721,7 @@ class ValueSetChecker { if (dc === 0) { ds = await list.preferredDisplay(null); if (!ds) { - m = this.worker.i18n.translate('NO_VALID_DISPLAY_AT_ALL', this.params.HTTPLanguages, [c.display, c.system, c.code]); + m = this.worker.i18n.translate('NO_VALID_DISPLAY_AT_ALL', this.params.HTTPLanguages, [c.display, c.system, c.code, this.params.langSummary()]); mid = 'NO_VALID_DISPLAY_AT_ALL'; } else { // no displays in the requested language(s): fall back to checking against the @@ -1699,6 +1742,9 @@ class ValueSetChecker { } } } + } else if (noDisplay) { + m = this.noKnownDisplayMessage(list, defLang, c.system, c); + mid = 'NO_KNOWN_DISPLAY'; } else { // the count in the message is the number of choices the message lists const shown = list.presentCount(this.params.workingLanguages(), defLang.value, true); @@ -1867,7 +1913,8 @@ class ValueSetChecker { this.worker.opContext.addNote(this.valueSet, 'Code "' + code + '" not found in ' + this.worker.renderer.displayCoded(cs)+": "+loc.message, this.indentCount); if (!this.params.membershipOnly && role !== 'not in') { if (cs.contentMode() !== 'complete') { - op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), 'UNKNOWN_CODE_IN_FRAGMENT', this.worker.i18n.translate('UNKNOWN_CODE_IN_FRAGMENT', this.params.HTTPLanguages, [code, cs.system(), cs.version()]), 'invalid-code')); + const [fid, fmsg] = this.unknownInFragment(code, cs.system(), cs.version()); + op.addIssue(new Issue('warning', 'code-invalid', addToPath(path, 'code'), fid, fmsg, 'invalid-code')); result = true; } else { unknownMsg = this.worker.i18n.translate(Unknown_Code_in_VersionSCT(cs.system(), cs.version()), this.params.HTTPLanguages, [code, cs.system(), cs.version(), SCTVersion(cs.system(), cs.version())]); diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 84c24e2cd..2a95d6b94 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -1,3 +1,4 @@ +const { isStringParameter } = require('../library/parameter-types'); const { TerminologyError} = require('../library/errors'); const { parseVCL, vclFromImplicitUrl, VCL_URI } = require('../../vcl/vcl-parser'); const { CodeSystem } = require('../library/codesystem'); @@ -267,6 +268,9 @@ class TerminologyWorker { */ async listVersions(url) { const versions = new Set(); + // the ones that are known but can't be used for codes (content example or not-present): still + // listed, and presentVersionList says so (triage B12) + const unusable = this.provider.unusableCodeSystemVersions ? this.provider.unusableCodeSystemVersions(url) : new Map(); // Check additional resources (a supplement can have the url of the code system it supplements, // but its version is not a version of that code system) @@ -275,6 +279,11 @@ class TerminologyWorker { this.deadCheck('listVersions-additional'); if (resource.resourceType === 'CodeSystem' && resource.content !== 'supplement' && resource.url === url && resource.version) { versions.add(resource.version); + if (['example', 'not-present'].includes(resource.content)) { + unusable.set(resource.version, resource.content); + } else { + unusable.delete(resource.version); + } } } } @@ -286,7 +295,10 @@ class TerminologyWorker { versions.add(version); } - return Array.from(versions).sort(); + const result = Array.from(versions).sort(); + // not enumerable: the list is still a list of versions to compare with + Object.defineProperty(result, 'unusable', { value: unusable, enumerable: false }); + return result; } async listDisplaysFromCodeSystem(displays, cs, c) { @@ -690,9 +702,9 @@ class TerminologyWorker { // Assume it's a complex type like Coding or CodeableConcept params.parameter.push(this.buildComplexParameter(name, value)); } - } else if (value == 'true') { + } else if (value == 'true' && !isStringParameter(name)) { params.parameter.push({name, valueBoolean: true}); - } else if (value == 'false') { + } else if (value == 'false' && !isStringParameter(name)) { params.parameter.push({name, valueBoolean: false}); } else { params.parameter.push({name, valueString: String(value)}); @@ -707,10 +719,9 @@ class TerminologyWorker { /** * Normalise the cache-id from the `${CACHE_ID_HEADER}` header into a `cache-id` - * parameter, so all downstream code can read the cache-id the same way whether - * the client sent it as a header (the going-forward mechanism) or, for now, still - * as a parameter. If a cache-id parameter is already present it is left as-is, so - * an explicit parameter wins and there's no surprising override. + * parameter, so all downstream code can read the cache-id the same way. A client + * can't send the cache-id parameter itself: it's withdrawn, and the request is + * refused before it gets here (parameter-types.js) * @param {express.Request} req * @param {Object} params - Parameters resource (mutated in place) */ @@ -819,9 +830,10 @@ class TerminologyWorker { // primary resource is included. const { txResources, primaryResources } = await this.collectSuppliedResources(params); - // Check for cache-id. An explicit cache-id *parameter* wins; otherwise fall - // back to the cache-id the middleware lifted off the X-Cache-Id header onto - // the operation context. This fallback is what makes the header work on the + // Check for cache-id: the parameter applyCacheIdHeader made from the X-Cache-Id + // header, or the cache-id the middleware lifted off the header onto the operation + // context (a client's own cache-id parameter is refused before this). The context + // is what makes the header work on the // op paths that don't route their Parameters through buildParameters // (expand, related, batch-validate) or that hand setupAdditionalResources a // raw req.body (lookup) - previously those silently ignored a front-loaded @@ -1367,8 +1379,11 @@ class TerminologyWorker { } presentVersionList(items) { - // a code system with no version is listed as one (null): say so, rather than 'null' - const list = items.map(v => (v === null || v === undefined || v === '') ? '(no version)' : v); + // a code system with no version is listed as one (null): say so, rather than 'null'; and a + // version that is known but can't be used (listVersions) says why + const unusable = items.unusable || new Map(); + const list = items.map(v => (v === null || v === undefined || v === '') ? '(no version)' + : unusable.has(v) ? this.i18n.translate('CODESYSTEM_VERSION_NOT_USABLE', this.opContext ? this.opContext.langs : null, [v, unusable.get(v)]) : v); if (list.length === 0) return ''; if (list.length === 1) return list[0]; if (list.length === 2) return `${list[0]} or ${list[1]}`; diff --git a/xig/xig.js b/xig/xig.js index 196675c8e..0c82ccac9 100644 --- a/xig/xig.js +++ b/xig/xig.js @@ -10,14 +10,12 @@ const path = require('path'); const https = require('https'); const http = require('http'); const cron = require('node-cron'); -const sqlite3 = require('sqlite3').verbose(); const { EventEmitter } = require('events'); const zlib = require('zlib'); const htmlServer = require('../library/html/html-server'); const folders = require('../library/server/folder-setup'); const escape = require('escape-html'); -const { guarded } = require('../library/sql/sqlite-utilities'); -const { SqlitePool } = require('../library/sql/sqlite-pool'); +const { SqliteDatabase, SqliteWorkerPool } = require('../library/sql/node-sqlite'); const Logger = require('../library/server/logger'); const {describeCron} = require("../library/utils/cron-utilities"); @@ -600,18 +598,13 @@ function countResources(queryParams) { return listCache.get('count ' + filterKey(queryParams), () => queryResourceCount(queryParams), () => 16); } -function queryResourceCount(queryParams) { +async function queryResourceCount(queryParams) { const { query, params } = buildSecureResourceCountQuery(queryParams); - return new Promise((resolve, reject) => { - if (!xigDb) { - resolve(0); - return; - } - xigDb.get(query, params, guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row ? row.total : 0); - })); - }); + if (!xigDb) { + return 0; + } + const row = await xigDb.get(query, params); + return row ? row.total : 0; } function buildPaginationUrl(baseUrl, params) { @@ -752,12 +745,7 @@ async function buildResourceTable(queryParams, resourceCount, offset = 0, loginU parts.push('Usage #'); parts.push(''); - const resourceRows = await new Promise((resolve, reject) => { - xigDb.all(resourceQuery, qp, guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + const resourceRows = await xigDb.all(resourceQuery, qp); // Determine resource type prefix for links let resourceTypePrefix = ''; @@ -898,12 +886,7 @@ async function buildResourceTable(queryParams, resourceCount, offset = 0, loginU async function fetchResourceRows(queryParams, offset = 0, limit = PAGE_SIZE) { const { query: resourceQuery, params: qp } = buildSecureResourceQuery(queryParams, offset, limit); - return new Promise((resolve, reject) => { - xigDb.all(resourceQuery, qp, guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + return xigDb.all(resourceQuery, qp); } function rowToObject(row, queryParams) { @@ -1056,12 +1039,8 @@ async function querySummaryStats(queryParams, baseUrl) { } const sql = `SELECT COUNT(*) as count FROM Resources ${where} AND ${version} = 1`; - const count = await new Promise((resolve, reject) => { - xigDb.get(sql, params, guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row ? row.count : 0); - })); - }); + const row = await xigDb.get(sql, params); + const count = row ? row.count : 0; const linkUrl = buildVersionLinkUrl(baseUrl, queryParams, version); html += `
  • ${escape(version)}: ${count.toLocaleString()}
  • `; @@ -1076,12 +1055,7 @@ async function querySummaryStats(queryParams, baseUrl) { const sql = `SELECT Authority, COUNT(*) as count FROM Resources ${where} GROUP BY Authority ORDER BY Authority`; - const authorityResults = await new Promise((resolve, reject) => { - xigDb.all(sql, params, guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + const authorityResults = await xigDb.all(sql, params); authorityResults.forEach(row => { const authority = row.Authority; @@ -1104,12 +1078,7 @@ async function querySummaryStats(queryParams, baseUrl) { const sql = `SELECT Realm, COUNT(*) as count FROM Resources ${where} GROUP BY Realm ORDER BY Realm`; - const realmResults = await new Promise((resolve, reject) => { - xigDb.all(sql, params, guarded(reject, (err, rows) => { - if (err) reject(err); - else resolve(rows || []); - })); - }); + const realmResults = await xigDb.all(sql, params); var c = 0; realmResults.forEach(row => { @@ -1763,32 +1732,26 @@ function downloadFile(url, destination, maxRedirects = 5) { }); } -function validateDatabaseFile(filePath) { - return new Promise((resolve, reject) => { - if (!fs.existsSync(filePath)) { - reject(new Error('Database file does not exist')); - return; - } - - // Try to open the SQLite database to validate it - const testDb = new sqlite3.Database(filePath, sqlite3.OPEN_READONLY, (err) => { - if (err) { - reject(new Error(`Invalid SQLite database: ${err.message}`)); - return; - } - - // Try a simple query to ensure the database is accessible - testDb.get("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1", guarded(reject, (err) => { - testDb.close(); +async function validateDatabaseFile(filePath) { + if (!fs.existsSync(filePath)) { + throw new Error('Database file does not exist'); + } - if (err) { - reject(new Error(`Database validation failed: ${err.message}`)); - } else { - resolve(); - } - })); - }); - }); + // Try to open the SQLite database to validate it (on this thread: a quick look) + let testDb; + try { + testDb = new SqliteDatabase(filePath, { readOnly: true }); + } catch (err) { + throw new Error(`Invalid SQLite database: ${err.message}`); + } + try { + // Try a simple query to ensure the database is accessible + testDb.get("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1"); + } catch (err) { + throw new Error(`Database validation failed: ${err.message}`); + } finally { + testDb.close(); + } } async function loadConfigCache() { @@ -1812,17 +1775,7 @@ async function loadConfigCache() { }; // Helper function for simple queries - const executeQuery = (sql, params = []) => { - return new Promise((resolve, reject) => { - xigDb.all(sql, params, guarded(reject, (err, rows) => { - if (err) { - reject(err); - } else { - resolve(rows); - } - })); - }); - }; + const executeQuery = (sql, params = []) => xigDb.all(sql, params); // Load metadata const metadataRows = await executeQuery('SELECT Name, Value FROM Metadata'); @@ -1966,9 +1919,11 @@ function initializeDatabase() { return; } - // Several connections (library/sql/sqlite-pool.js): one runs one query at a time, and a crawler - // paging deep into the lists queued every XIG request behind its slow pages (npm.fhir.org) - SqlitePool.open(XIG_DB_PATH, { size: xigSettings.connections }).then(async (pool) => { + // Several connections, each on its own worker thread (library/sql/node-sqlite.js + // SqliteWorkerPool): the queries run off the event loop, and one runs one query at a time, so a + // crawler paging deep into the lists only holds up the rest when every worker is busy (npm.fhir.org) + const size = Number.isInteger(xigSettings.connections) && xigSettings.connections > 0 ? xigSettings.connections : 4; + SqliteWorkerPool.open(XIG_DB_PATH, { size }).then(async (pool) => { xigDb = pool; try { await loadConfigCache(); @@ -2023,15 +1978,14 @@ async function updateXigDatabase(trigger = 'manual') { entry.status = 'validated'; if (xigDb) { - await new Promise((resolve, reject) => { - xigDb.close(guarded(reject, (err) => { - if (err) { - xigLog.warn(`Warning: Error closing existing database: ${err.message}`); - } - xigDb = null; - resolve(); - })); - }); + // the queries running finish first; any that come while it closes see no database + const db = xigDb; + xigDb = null; + try { + await db.close(); + } catch (err) { + xigLog.warn(`Warning: Error closing existing database: ${err.message}`); + } } if (fs.existsSync(XIG_DB_PATH)) { @@ -2115,12 +2069,15 @@ function getDatabaseTableCounts() { if (tableCountCache.db !== xigDb) { const db = xigDb; let failed = false; - const count = (table) => new Promise((resolve) => { - db.get(`SELECT COUNT(*) as count FROM ${table}`, [], (err, row) => { - failed = failed || Boolean(err) || !row; - resolve(err || !row ? 0 : row.count); + const count = (table) => Promise.resolve(db.get(`SELECT COUNT(*) as count FROM ${table}`, [])).then( + (row) => { + failed = failed || !row; + return row ? row.count : 0; + }, + () => { + failed = true; + return 0; }); - }); const counts = Promise.all([count('Packages'), count('Resources')]) .then(([packages, resources]) => { if (failed && tableCountCache.counts === counts) { @@ -2340,30 +2297,22 @@ function buildStatsTable(statsData) { return html; } -function getDatabaseInfo() { - return new Promise((resolve, reject) => { - if (!xigDb) { - resolve({ - connected: false, - lastModified: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).mtime : null, - fileSize: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).size : 0 - }); - return; - } +async function getDatabaseInfo() { + if (!xigDb) { + return { + connected: false, + lastModified: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).mtime : null, + fileSize: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).size : 0 + }; + } - xigDb.get("SELECT COUNT(*) as tableCount FROM sqlite_master WHERE type='table'", guarded(reject, (err, row) => { - if (err) { - reject(err); - } else { - resolve({ - connected: true, - tableCount: row.tableCount, - lastModified: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).mtime : null, - fileSize: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).size : 0 - }); - } - })); - }); + const row = await xigDb.get("SELECT COUNT(*) as tableCount FROM sqlite_master WHERE type='table'"); + return { + connected: true, + tableCount: row.tableCount, + lastModified: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).mtime : null, + fileSize: fs.existsSync(XIG_DB_PATH) ? fs.statSync(XIG_DB_PATH).size : 0 + }; } function getRequestedFormat(req) { @@ -2822,12 +2771,7 @@ router.get('/resource/:packagePid/:resourceType/:resourceId', async (req, res) = WHERE PackageKey = ? AND ResourceType = ? AND Id = ? `; - const resourceData = await new Promise((resolve, reject) => { - xigDb.get(resourceQuery, [packageObj.PackageKey, resourceType, resourceId], guarded(reject, (err, row) => { - if (err) reject(err); - else resolve(row); - })); - }); + const resourceData = await xigDb.get(resourceQuery, [packageObj.PackageKey, resourceType, resourceId]); if (!resourceData) { return res.status(404).send(renderPage('Resource Not Found', @@ -2994,16 +2938,12 @@ const RESOURCE_LISTS = { examples: 'examplesOffset' }; -function dbGet(sql, params) { - return new Promise((resolve, reject) => { - xigDb.get(sql, params, guarded(reject, (err, row) => err ? reject(err) : resolve(row))); - }); +async function dbGet(sql, params) { + return xigDb.get(sql, params); } -function dbAll(sql, params) { - return new Promise((resolve, reject) => { - xigDb.all(sql, params, guarded(reject, (err, rows) => err ? reject(err) : resolve(rows || []))); - }); +async function dbAll(sql, params) { + return xigDb.all(sql, params); } // One page of a list: how many rows there are, and the PAGE_SIZE of them from offset. @@ -3179,10 +3119,15 @@ function buildDependencyTable(dependencies) { return html; } -// The resource's stored JSON, still gzipped, or null +// The resource's stored JSON, still gzipped, or null. A Buffer: node:sqlite gives a BLOB as a +// Uint8Array (wrapped here, not copied) async function loadResourceBlob(resourceKey) { const row = await dbGet('SELECT Json FROM Contents WHERE ResourceKey = ?', [resourceKey]); - return row && row.Json ? row.Json : null; + if (!row || !row.Json) { + return null; + } + const json = row.Json; + return Buffer.isBuffer(json) ? json : Buffer.from(json.buffer, json.byteOffset, json.byteLength); } // The uncompressed size of gzipped data, from its trailer (the size mod 2^32, which is @@ -3569,8 +3514,7 @@ async function dailyReport({since, now}) { sentences.push('The database is not open: it could not be accessed.'); } else { try { - const row = await new Promise((resolve, reject) => - xigDb.get('SELECT COUNT(*) AS n FROM Resources', [], guarded(reject, (err, row) => err ? reject(err) : resolve(row)))); + const row = await xigDb.get('SELECT COUNT(*) AS n FROM Resources', []); sentences.push(`The database holds ${plural(row.n, 'resource')}.`); } catch (e) { sentences.push(`The database could not be accessed: ${e.message}.`); @@ -3579,21 +3523,17 @@ async function dailyReport({since, now}) { return sentences.join(' '); } -function shutdown() { - return new Promise((resolve, reject) => { - if (xigDb) { - xigDb.close(guarded(reject, (err) => { - if (err) { - xigLog.error(`Error closing XIG database: ${err.message}`); - } else { - xigLog.error('XIG database connection closed'); - } - resolve(); - })); - } else { - resolve(); +async function shutdown() { + if (xigDb) { + const db = xigDb; + xigDb = null; + try { + await db.close(); + xigLog.info('XIG database connection closed'); + } catch (err) { + xigLog.error(`Error closing XIG database: ${err.message}`); } - }); + } } // Export everything