Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

-
- 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

Expand All @@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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
- tx: a request with no client side cache over uncachedMaxBodyMB, behind the cluster launcher, mostly got a 502 "the tx process did not answer (EPIPE)", not the 413 too-costly: the process answered and closed the connection with the body still coming. It now takes the rest of the body (without parsing it) and then answers (#461)
- tx: a JSON Bundle (a search page, say) was made in one go: a search for CodeSystems, 200 a page, with no _summary or _elements, made a page of 89 MB and held the server for 3 seconds (tx.fhir.org). A Bundle is now made an entry at a time, letting other requests run between, and written out in its parts (with no ETag: it isn't hashed)
- The shl module and the VSAC value set database turned on sqlite3's verbose mode, which is for the whole process: every query of every module (the XIG and packages on npm.fhir.org) then captured a stack trace and formatted its arguments, to make the stack of an error longer. It is no longer turned on

### Removed

Expand Down
1 change: 1 addition & 0 deletions library/server/daily-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const MODULE_TITLES = {
tx: 'Terminology server',
registry: 'Terminology server registry',
packages: 'Packages',
rest: 'FHIR REST',
xig: 'XIG',
shl: 'SMART Health Links',
ips: 'IPS',
Expand Down
8 changes: 7 additions & 1 deletion rest/endpoint/endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,13 @@ class Endpoint {
}
} finally {
if (this.options.stats) {
this.options.stats.countRequest(interaction, Date.now() - start);
// under the endpoint, for the daily report (rest.js); a bundle as what it is
let name = interaction;
if (name === 'bundle') {
const type = freq && freq.body && freq.body.type;
name = type === 'transaction' || type === 'batch' ? type : 'bundle';
}
this.options.stats.countRequest(name, Date.now() - start, this.path);
}
}
}
Expand Down
56 changes: 56 additions & 0 deletions rest/rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,48 @@ class RestModule {
return this.endpoints.map(ep => ep.path);
}

/**
* The module's paragraph in the daily report (library/server/daily-report.js): for each
* endpoint, its reads, searches, writes and transactions over the period (and batches,
* and anything else, when there were any)
*/
dailyReport({ since, now }) {
if (!this.stats) {
return null;
}
const counts = this.stats.countsSince(since, now);
// the configured endpoints first, in order, then any counted that aren't configured now
const paths = this.endpoints.map(ep => ep.path);
for (const p of Object.keys(counts.endpoints || {})) {
if (!paths.includes(p)) {
paths.push(p);
}
}
if (!paths.length) {
return null;
}
const n = (count, word, plural) => `${count.toLocaleString('en-US')} ${count === 1 ? word : (plural || word + 's')}`;
const lines = paths.map(p => {
const ops = (counts.endpoints && counts.endpoints[p]) || {};
const k = { reads: 0, searches: 0, writes: 0, transactions: 0, batches: 0, other: 0 };
for (const [op, c] of Object.entries(ops)) {
k[categoryOf(op)] += c;
}
let line = `- ${p || '(no endpoint)'}: ${n(k.reads, 'read')}, ${n(k.searches, 'search', 'searches')}, ${n(k.writes, 'write')}, ${n(k.transactions, 'transaction')}`;
const more = [];
if (k.batches) {
more.push(n(k.batches, 'batch', 'batches'));
}
if (k.other) {
more.push(n(k.other, 'other request'));
}
return more.length ? `${line} (and ${more.join(', ')})` : line;
});
const total = counts.total || 0;
const head = total === 0 ? 'No requests were served.' : `${n(total, 'request')} ${total === 1 ? 'was' : 'were'} served.`;
return `${head}\n\n${lines.join('\n')}`;
}

getStatus() {
return { enabled: true, endpoints: this.endpoints.map(ep => ({ path: ep.path, fhirVersion: ep.settings && ep.settings.fhirVersion, database: ep.cfg.database.type })) };
}
Expand All @@ -162,4 +204,18 @@ class RestModule {
}
}

// what each counted interaction is, for the daily report: other is history, operations,
// capabilities, and requests that weren't a FHIR interaction
const CATEGORIES = {
read: 'reads', vread: 'reads',
'search-type': 'searches', 'search-system': 'searches',
create: 'writes', update: 'writes', patch: 'writes', delete: 'writes',
'conditional-update': 'writes', 'conditional-delete': 'writes', 'conditional-patch': 'writes',
transaction: 'transactions', batch: 'batches'
};

function categoryOf(interaction) {
return CATEGORIES[interaction] || 'other';
}

module.exports = RestModule;
2 changes: 1 addition & 1 deletion shl/shl.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//

const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const sqlite3 = require('sqlite3');
const path = require('path');
const crypto = require('crypto');
const cron = require('node-cron');
Expand Down
20 changes: 20 additions & 0 deletions tests/server/module-daily-reports.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const PublisherModule = require('../../publisher/publisher');
const TestingModule = require('../../testing/testing');
const { TestReportStore: TestingStore } = require('../../testing/store');
const IpsModule = require('../../ips/ips');
const RestModule = require('../../rest/rest');
const { IpsStore } = require('../../ips/store');

const HOUR = 60 * 60 * 1000;
Expand Down Expand Up @@ -118,6 +119,25 @@ describe('module paragraphs', () => {

});

test('rest: reads, searches, writes and transactions for each endpoint', () => {
const module = Object.create(RestModule.prototype);
module.endpoints = [{ path: '/fhir/r4' }, { path: '/fhir/r5' }];
const r4 = { read: 1000, vread: 200, 'search-type': 40, 'search-system': 2, create: 3, update: 4, 'conditional-update': 1,
patch: 1, delete: 1, transaction: 2, batch: 1, 'history-instance': 5, operation: 3 };
const old = { read: 1 }; // an endpoint no longer configured
const total = [r4, old].reduce((t, o) => t + Object.values(o).reduce((a, b) => a + b, 0), 0);
module.stats = { countsSince: () => ({ total, operations: {}, endpoints: { '/fhir/r4': r4, '/fhir/old': old }, persisted: true }) };
expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('1,264 requests were served.\n\n' +
'- /fhir/r4: 1,200 reads, 42 searches, 10 writes, 2 transactions (and 1 batch, 8 other requests)\n' +
'- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions\n' +
'- /fhir/old: 1 read, 0 searches, 0 writes, 0 transactions');

module.stats = statsWith({});
expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('No requests were served.\n\n' +
'- /fhir/r4: 0 reads, 0 searches, 0 writes, 0 transactions\n' +
'- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions');
});

test('registry: client requests, servers registered, and those that never answered', () => {
const data = new ServerRegistries();
const registry = new ServerRegistry();
Expand Down
124 changes: 124 additions & 0 deletions tests/tx/sqlite-v2-cli-options.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* The sqlite-v2 importers take the classic importers' options (tx/importers/sqlite-v2/cli-options.js):
* -v, --version and -y, --yes, with their earlier names (--loinc-version, --overwrite...) still
* working, hidden. An existing destination without -y is asked about, or refused with no one to ask.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const { Command } = require('commander');
const inquirer = require('inquirer');
const { addCommonOptions, resolveCommonOptions, importAction } = require('../../tx/importers/sqlite-v2/cli-options');

const VERSION = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true };

// parse args as tx-import <module> import would, and resolve the common options
async function run(args, version = VERSION) {
let result;
const program = new Command().exitOverride();
addCommonOptions(program.command('import')
.requiredOption('-s, --source <dir>', 'source')
.requiredOption('-d, --dest <file>', 'dest'), version)
.exitOverride()
.action(async (o) => {
result = await resolveCommonOptions(o, version);
});
await program.parseAsync(['import', ...args], { from: 'user' });
return result;
}

describe('sqlite-v2 importer options', () => {
let dir;
let dest;
let tty;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'v2-cli-'));
dest = path.join(dir, 'loinc.db');
tty = process.stdin.isTTY;
});
afterEach(() => {
process.stdin.isTTY = tty;
jest.restoreAllMocks();
fs.rmSync(dir, { recursive: true, force: true });
});

test('-v and --version give the version; the earlier name still works', async () => {
expect((await run(['-s', dir, '-d', dest, '-v', '2.83'])).version).toBe('2.83');
expect((await run(['-s', dir, '-d', dest, '--version', '2.83'])).version).toBe('2.83');
expect((await run(['-s', dir, '-d', dest, '--loinc-version', '2.83'])).version).toBe('2.83');
});

test('a required version that is missing is an error that says how to give it', async () => {
await expect(run(['-s', dir, '-d', dest])).rejects.toThrow('-v, --version <version> is required (e.g. 2.83)');
});

test('an importer that takes no version has no -v', async () => {
await expect(run(['-s', dir, '-d', dest, '-v', 'x'], null)).rejects.toThrow(/unknown option '-v'/);
expect((await run(['-s', dir, '-d', dest], null)).version).toBeUndefined();
});

test('a destination that isn\'t there needs nothing; -y, --yes or --overwrite replace one that is', async () => {
expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(false);
fs.writeFileSync(dest, 'x');
expect((await run(['-s', dir, '-d', dest, '-v', '1', '-y'])).overwrite).toBe(true);
expect((await run(['-s', dir, '-d', dest, '-v', '1', '--yes'])).overwrite).toBe(true);
expect((await run(['-s', dir, '-d', dest, '-v', '1', '--overwrite'])).overwrite).toBe(true);
});

test('an existing destination without -y is asked about, or refused with no one to ask', async () => {
fs.writeFileSync(dest, 'x');
process.stdin.isTTY = false;
await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('use -y, --yes to replace it');
process.stdin.isTTY = true;
const prompt = jest.spyOn(inquirer, 'prompt').mockResolvedValueOnce({ replace: true }).mockResolvedValueOnce({ replace: false });
expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(true);
await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('Import cancelled');
expect(prompt).toHaveBeenCalledTimes(2);
});

test('a failure is reported as the classic importers do, with exit code 1, not thrown', async () => {
const logged = [];
const module = { getName: () => 'loinc-v2', logError: (m) => logged.push(m) };
const exitCode = process.exitCode;
const stack = jest.spyOn(console, 'error').mockImplementation(() => {});
try {
await importAction(module, async () => { throw new Error('required LOINC file missing'); })({});
expect(logged).toEqual(['loinc-v2 import failed: required LOINC file missing']);
expect(process.exitCode).toBe(1);
expect(stack).not.toHaveBeenCalled();
await importAction(module, async () => { throw new Error('x'); })({ verbose: true });
expect(stack).toHaveBeenCalledTimes(1);
} finally {
process.exitCode = exitCode;
}
});

test('--verbose shows the stack wherever it is on the command line (tx-import has a --verbose of its own)', async () => {
const module = { getName: () => 'loinc-v2', logError: () => {} };
const exitCode = process.exitCode;
const stack = jest.spyOn(console, 'error').mockImplementation(() => {});
try {
for (const args of [['loinc-v2', 'import', '-d', 'x.db', '--verbose'], ['--verbose', 'loinc-v2', 'import', '-d', 'x.db']]) {
stack.mockClear();
const program = new Command().exitOverride().option('--verbose', 'enable verbose logging');
addCommonOptions(program.command('loinc-v2').command('import').option('-d, --dest <file>'))
.action(importAction(module, async () => { throw new Error('required LOINC file missing'); }));
await program.parseAsync(args, { from: 'user' });
expect(stack).toHaveBeenCalledTimes(1);
}
} finally {
process.exitCode = exitCode;
}
});

test('the help shows -v, --version and -y, --yes, not the earlier names', () => {
const program = new Command();
const cmd = addCommonOptions(program.command('import'), VERSION);
const help = cmd.helpInformation();
expect(help).toContain('-v, --version <version>');
expect(help).toContain('-y, --yes');
expect(help).toContain('--verbose');
expect(help).not.toContain('--loinc-version');
expect(help).not.toContain('--overwrite');
});
});
17 changes: 9 additions & 8 deletions tx/importers/import-loinc-v2-classic.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
// literal either way, as cs-loinc.js reports them).

const fs = require('fs');
const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const Database = require('better-sqlite3');
const { BaseTerminologyModule } = require('./tx-import-base');
const { TerminologyBuilder, vacuumFile } = require('./sqlite-v2/builder');
Expand Down Expand Up @@ -237,17 +238,17 @@ class LoincV2ClassicModule extends BaseTerminologyModule {
getSupportedFormats() { return ['sqlite']; }

registerCommands(cmd) {
cmd.command('import')
const version = { arg: 'version', help: 'checked against the classic Config (default: its version)', oldFlag: 'loinc-version' };
addCommonOptions(cmd.command('import')
.description('Convert a classic FHIRsmith LOINC .db into a terminology file')
.requiredOption('-s, --source <file>', 'classic LOINC .db (e.g. loinc-2.77-a.db)')
.requiredOption('-d, --dest <file>', 'destination .db')
.option('-v, --loinc-version <version>', 'checked against the classic Config (default: its version)')
.option('--overwrite', 'replace the destination')
.action(async (o) => {
const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: o.loincVersion,
overwrite: !!o.overwrite, log: (m) => this.logInfo(m) });
.requiredOption('-d, --dest <file>', 'destination .db'), version)
.action(importAction(this, async (o) => {
const c = await resolveCommonOptions(o, version);
const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: c.version,
overwrite: c.overwrite, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
});
}));
}
}

Expand Down
15 changes: 8 additions & 7 deletions tx/importers/import-loinc-v2.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
// parent / child entry order) only when the parent links' seq does not reproduce it.

const fs = require('fs');
const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const path = require('path');
const Database = require('better-sqlite3');
const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder');
Expand Down Expand Up @@ -519,16 +520,16 @@ class LoincV2Module extends BaseTerminologyModule {
getSupportedFormats() { return ['directory']; }

registerCommands(cmd) {
cmd.command('import')
const version = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true };
addCommonOptions(cmd.command('import')
.description('Import an unzipped LOINC release into a terminology file')
.requiredOption('-s, --source <dir>', 'release root (contains LoincTable/ and AccessoryFiles/)')
.requiredOption('-d, --dest <file>', 'destination .db')
.requiredOption('-v, --loinc-version <version>', 'e.g. 2.83')
.option('--overwrite', 'replace the destination')
.action(async (o) => {
const s = await importLoincV2({ source: o.source, dest: o.dest, version: o.loincVersion, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) });
.requiredOption('-d, --dest <file>', 'destination .db'), version)
.action(importAction(this, async (o) => {
const c = await resolveCommonOptions(o, version);
const s = await importLoincV2({ source: o.source, dest: o.dest, version: c.version, overwrite: c.overwrite, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
});
}));
}
}

Expand Down
17 changes: 9 additions & 8 deletions tx/importers/import-rxnorm-v2.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
// order concepts by (primary TTY rank, ingredient group): the numbering's sort key.

const fs = require('fs');
const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const path = require('path');
const { BaseTerminologyModule } = require('./tx-import-base');
const { TerminologyBuilder } = require('./sqlite-v2/builder');
Expand Down Expand Up @@ -289,18 +290,18 @@ class RxNormV2Module extends BaseTerminologyModule {
getSupportedFormats() { return ['directory']; }

registerCommands(cmd) {
cmd.command('import')
const version = { arg: 'MMDDYYYY', help: 'e.g. 03022026', oldFlag: 'rxnorm-version', required: true };
addCommonOptions(cmd.command('import')
.description('Import an unzipped RxNorm full release (rrf folder) into a terminology file')
.requiredOption('-s, --source <dir>', 'the rrf/ folder of the release')
.requiredOption('-d, --dest <file>', 'destination .db')
.requiredOption('-v, --rxnorm-version <MMDDYYYY>', 'e.g. 03022026')
.option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI:<rxaui> filters (otherwise refused)')
.option('--overwrite', 'replace the destination')
.action(async (o) => {
const s = await importRxNormV2({ source: o.source, dest: o.dest, version: o.rxnormVersion,
overwrite: !!o.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) });
.option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI:<rxaui> filters (otherwise refused)'), version)
.action(importAction(this, async (o) => {
const c = await resolveCommonOptions(o, version);
const s = await importRxNormV2({ source: o.source, dest: o.dest, version: c.version,
overwrite: c.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
});
}));
}
}

Expand Down
Loading
Loading