-
Notifications
You must be signed in to change notification settings - Fork 400
/
repo.ts
2109 lines (1897 loc) · 69.5 KB
/
repo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AccessPolicyInteraction,
OperationOutcomeError,
Operator,
SearchParameterDetails,
SearchParameterType,
SearchRequest,
allOk,
badRequest,
canReadResourceType,
canWriteResourceType,
created,
deepEquals,
evalFhirPath,
evalFhirPathTyped,
forbidden,
formatSearchQuery,
getSearchParameterDetails,
getSearchParameters,
getStatus,
gone,
isGone,
isNotFound,
isOk,
multipleMatches,
normalizeErrorString,
normalizeOperationOutcome,
notFound,
parseReference,
parseSearchRequest,
preconditionFailed,
protectedResourceTypes,
resolveId,
satisfiedAccessPolicy,
serverError,
stringify,
toPeriod,
validateResource,
validateResourceType,
} from '@medplum/core';
import { BaseRepository, FhirRepository } from '@medplum/fhir-router';
import {
AccessPolicy,
Binary,
Bundle,
BundleEntry,
Meta,
OperationOutcome,
Reference,
Resource,
ResourceType,
SearchParameter,
StructureDefinition,
} from '@medplum/fhirtypes';
import { randomUUID } from 'node:crypto';
import { Readable } from 'node:stream';
import { Pool, PoolClient } from 'pg';
import { Operation, applyPatch } from 'rfc6902';
import validator from 'validator';
import { getConfig } from '../config';
import { getLogger, getRequestContext } from '../context';
import { getDatabasePool } from '../database';
import { globalLogger } from '../logger';
import { getRedis } from '../redis';
import { r4ProjectId } from '../seed';
import {
AuditEventOutcome,
AuditEventSubtype,
CreateInteraction,
DeleteInteraction,
HistoryInteraction,
PatchInteraction,
ReadInteraction,
SearchInteraction,
UpdateInteraction,
VreadInteraction,
logRestfulEvent,
} from '../util/auditevent';
import { addBackgroundJobs } from '../workers';
import { addSubscriptionJobs } from '../workers/subscription';
import { validateResourceWithJsonSchema } from './jsonschema';
import { AddressTable } from './lookups/address';
import { CodingTable } from './lookups/coding';
import { HumanNameTable } from './lookups/humanname';
import { LookupTable } from './lookups/lookuptable';
import { ReferenceTable } from './lookups/reference';
import { TokenTable } from './lookups/token';
import { ValueSetElementTable } from './lookups/valuesetelement';
import { getPatients } from './patient';
import { validateReferences } from './references';
import { getFullUrl } from './response';
import { RewriteMode, rewriteAttachments } from './rewrite';
import { buildSearchExpression, searchImpl } from './search';
import { Condition, DeleteQuery, Disjunction, Expression, InsertQuery, SelectQuery, periodToRangeString } from './sql';
import { getBinaryStorage } from './storage';
/**
* The RepositoryContext interface defines standard metadata for repository actions.
* In practice, there will be one Repository per HTTP request.
* And the RepositoryContext represents the context of that request,
* such as "who is the current user?" and "what is the current project?"
*/
export interface RepositoryContext {
/**
* The current author reference.
* This should be a FHIR reference string (i.e., "resourceType/id").
* Where resource type is ClientApplication, Patient, Practitioner, etc.
* This value will be included in every resource as meta.author.
*/
author: Reference;
remoteAddress?: string;
/**
* Projects that the Repository is allowed to access.
* This should include the ID/UUID of the current project, but may also include other accessory Projects.
* If this is undefined, the current user is a server user (e.g. Super Admin)
* The usual case has two elements: the user's Project and the base R4 Project
* The user's "primary" Project will be the first element in the array (i.e. projects[0])
* This value will be included in every resource as meta.project.
*/
projects?: string[];
/**
* Optional compartment restriction.
* If the compartments array is provided,
* all queries will be restricted to those compartments.
*/
accessPolicy?: AccessPolicy;
/**
* Optional flag for system administrators,
* which grants system-level access.
*/
superAdmin?: boolean;
/**
* Optional flag for project administrators,
* which grants additional project-level access.
*/
projectAdmin?: boolean;
/**
* Optional flag to validate resources in strict mode.
* Strict mode validates resources against StructureDefinition resources,
* which includes strict date validation, backbone elements, and more.
* Non-strict mode uses the official FHIR JSONSchema definition, which is
* significantly more relaxed.
*/
strictMode?: boolean;
/**
* Optional flag to validate references on write operations.
* If enabled, the repository will check that all references are valid,
* and that the current user has access to the referenced resource.
*/
checkReferencesOnWrite?: boolean;
/**
* Optional flag to include Medplum extended meta fields.
* Medplum tracks additional metadata for each resource, such as:
* 1) "author" - Reference to the last user who modified the resource.
* 2) "project" - Reference to the project that owns the resource.
* 3) "account" - Optional reference to a subaccount that owns the resource.
*/
extendedMode?: boolean;
}
export interface CacheEntry<T extends Resource = Resource> {
resource: T;
projectId: string;
}
export type ReadResourceOptions = {
allowReadFrom?: ('cache' | 'database')[];
};
/**
* The lookup tables array includes a list of special tables for search indexing.
*/
const lookupTables: LookupTable[] = [
new AddressTable(),
new HumanNameTable(),
new TokenTable(),
new ValueSetElementTable(),
new ReferenceTable(),
new CodingTable(),
];
/**
* The Repository class manages reading and writing to the FHIR repository.
* It is a thin layer on top of the database.
* Repository instances should be created per author and project.
*/
export class Repository extends BaseRepository implements FhirRepository<PoolClient>, Disposable {
private readonly context: RepositoryContext;
private closed = false;
constructor(context: RepositoryContext) {
super();
this.context = context;
this.context.projects?.push?.(r4ProjectId);
if (!this.context.author?.reference) {
throw new Error('Invalid author reference');
}
}
clone(): Repository {
return new Repository(this.context);
}
async createResource<T extends Resource>(resource: T): Promise<T> {
const resourceWithId = {
...resource,
id: randomUUID(),
};
try {
const result = await this.updateResourceImpl(resourceWithId, true);
this.logEvent(CreateInteraction, AuditEventOutcome.Success, undefined, result);
return result;
} catch (err) {
this.logEvent(CreateInteraction, AuditEventOutcome.MinorFailure, err, resourceWithId);
throw err;
}
}
async readResource<T extends Resource>(
resourceType: T['resourceType'],
id: string,
options?: ReadResourceOptions
): Promise<T> {
try {
const result = this.removeHiddenFields(await this.readResourceImpl<T>(resourceType, id, options));
this.logEvent(ReadInteraction, AuditEventOutcome.Success, undefined, result);
return result;
} catch (err) {
this.logEvent(ReadInteraction, AuditEventOutcome.MinorFailure, err);
throw err;
}
}
private async readResourceImpl<T extends Resource>(
resourceType: T['resourceType'],
id: string,
options?: ReadResourceOptions
): Promise<T> {
if (!id || !validator.isUUID(id)) {
throw new OperationOutcomeError(notFound);
}
validateResourceType(resourceType);
if (!this.canReadResourceType(resourceType)) {
throw new OperationOutcomeError(forbidden);
}
const allowReadFrom = options?.allowReadFrom ?? (['cache', 'database'] as const);
if (allowReadFrom.includes('cache')) {
const cacheRecord = await getCacheEntry<T>(resourceType, id);
if (cacheRecord) {
// This is an optimization to avoid a database query.
// However, it depends on all values in the cache having "meta.compartment"
// Old versions of Medplum did not populate "meta.compartment"
// So this optimization is blocked until we add a migration.
// if (!this.canReadCacheEntry(cacheRecord)) {
// throw new OperationOutcomeError(notFound);
// }
if (this.canReadCacheEntry(cacheRecord)) {
return cacheRecord.resource;
}
}
}
if (!allowReadFrom.includes('database')) {
throw new OperationOutcomeError(notFound);
}
return this.readResourceFromDatabase(resourceType, id);
}
private async readResourceFromDatabase<T extends Resource>(resourceType: string, id: string): Promise<T> {
const builder = new SelectQuery(resourceType).column('content').column('deleted').where('id', '=', id);
this.addSecurityFilters(builder, resourceType);
const rows = await builder.execute(this.getDatabaseClient());
if (rows.length === 0) {
throw new OperationOutcomeError(notFound);
}
if (rows[0].deleted) {
throw new OperationOutcomeError(gone);
}
const resource = JSON.parse(rows[0].content as string) as T;
await setCacheEntry(resource);
return resource;
}
private canReadCacheEntry(cacheEntry: CacheEntry): boolean {
if (this.isSuperAdmin()) {
return true;
}
if (!this.context.projects?.includes(cacheEntry.projectId)) {
return false;
}
if (!satisfiedAccessPolicy(cacheEntry.resource, AccessPolicyInteraction.READ, this.context.accessPolicy)) {
return false;
}
return true;
}
async readReferences(references: Reference[]): Promise<(Resource | Error)[]> {
const cacheEntries = await getCacheEntries(references);
const result: (Resource | Error)[] = new Array(references.length);
for (let i = 0; i < result.length; i++) {
const reference = references[i];
const cacheEntry = cacheEntries[i];
let entryResult = await this.processReadReferenceEntry(reference, cacheEntry);
if (entryResult instanceof Error) {
this.logEvent(ReadInteraction, AuditEventOutcome.MinorFailure, entryResult);
} else {
entryResult = this.removeHiddenFields(entryResult);
this.logEvent(ReadInteraction, AuditEventOutcome.Success, undefined, entryResult);
}
result[i] = entryResult;
}
return result;
}
private async processReadReferenceEntry(
reference: Reference,
cacheEntry: CacheEntry | undefined
): Promise<Resource | Error> {
try {
const [resourceType, id] = reference.reference?.split('/') as [ResourceType, string];
validateResourceType(resourceType);
if (!this.canReadResourceType(resourceType)) {
return new OperationOutcomeError(forbidden);
}
if (cacheEntry) {
if (!this.canReadCacheEntry(cacheEntry)) {
return new OperationOutcomeError(notFound);
}
return cacheEntry.resource;
}
return await this.readResourceFromDatabase(resourceType, id);
} catch (err) {
if (err instanceof OperationOutcomeError) {
return err;
}
return new OperationOutcomeError(normalizeOperationOutcome(err), err);
}
}
async readReference<T extends Resource>(reference: Reference<T>): Promise<T> {
let parts: [T['resourceType'], string];
try {
parts = parseReference(reference);
} catch (err) {
throw new OperationOutcomeError(badRequest('Invalid reference'));
}
return this.readResource(parts[0], parts[1]);
}
/**
* Returns resource history.
*
* Results are sorted with oldest versions last
*
* See: https://www.hl7.org/fhir/http.html#history
* @param resourceType - The FHIR resource type.
* @param id - The FHIR resource ID.
* @returns Operation outcome and a history bundle.
*/
async readHistory<T extends Resource>(resourceType: T['resourceType'], id: string): Promise<Bundle<T>> {
try {
let resource: T | undefined = undefined;
try {
resource = await this.readResourceImpl<T>(resourceType, id);
} catch (err) {
if (!(err instanceof OperationOutcomeError) || !isGone(err.outcome)) {
throw err;
}
}
const rows = await new SelectQuery(resourceType + '_History')
.column('versionId')
.column('id')
.column('content')
.column('lastUpdated')
.where('id', '=', id)
.orderBy('lastUpdated', true)
.limit(100)
.execute(this.getDatabaseClient());
const entries: BundleEntry<T>[] = [];
for (const row of rows) {
const resource = row.content ? this.removeHiddenFields(JSON.parse(row.content as string)) : undefined;
const outcome: OperationOutcome = row.content
? allOk
: {
resourceType: 'OperationOutcome',
id: 'gone',
issue: [
{
severity: 'error',
code: 'deleted',
details: {
text: 'Deleted on ' + row.lastUpdated,
},
},
],
};
entries.push({
fullUrl: getFullUrl(resourceType, row.id),
request: {
method: 'GET',
url: `${resourceType}/${row.id}/_history/${row.versionId}`,
},
response: {
status: getStatus(outcome).toString(),
outcome,
},
resource,
});
}
this.logEvent(HistoryInteraction, AuditEventOutcome.Success, undefined, resource);
return {
resourceType: 'Bundle',
type: 'history',
entry: entries,
};
} catch (err) {
this.logEvent(HistoryInteraction, AuditEventOutcome.MinorFailure, err);
throw err;
}
}
async readVersion<T extends Resource>(resourceType: T['resourceType'], id: string, vid: string): Promise<T> {
try {
if (!validator.isUUID(vid)) {
throw new OperationOutcomeError(notFound);
}
try {
await this.readResourceImpl<T>(resourceType, id);
} catch (err) {
if (!isGone(normalizeOperationOutcome(err))) {
throw err;
}
}
const rows = await new SelectQuery(resourceType + '_History')
.column('content')
.where('id', '=', id)
.where('versionId', '=', vid)
.execute(this.getDatabaseClient());
if (rows.length === 0) {
throw new OperationOutcomeError(notFound);
}
const result = this.removeHiddenFields(JSON.parse(rows[0].content as string));
this.logEvent(VreadInteraction, AuditEventOutcome.Success, undefined, result);
return result;
} catch (err) {
this.logEvent(VreadInteraction, AuditEventOutcome.MinorFailure, err);
throw err;
}
}
async updateResource<T extends Resource>(resource: T, versionId?: string): Promise<T> {
try {
const result = await this.updateResourceImpl(resource, false, versionId);
this.logEvent(UpdateInteraction, AuditEventOutcome.Success, undefined, result);
return result;
} catch (err) {
this.logEvent(UpdateInteraction, AuditEventOutcome.MinorFailure, err, resource);
throw err;
}
}
async conditionalUpdate<T extends Resource>(
resource: T,
search: SearchRequest
): Promise<{ resource: T; outcome: OperationOutcome }> {
if (search.resourceType !== resource.resourceType) {
throw new OperationOutcomeError(badRequest('Search type must match resource type for conditional update'));
}
return this.withTransaction(async () => {
const matches = await this.searchResources(search);
if (matches.length === 0) {
if (resource.id) {
throw new OperationOutcomeError(
badRequest('Cannot perform create as update with client-assigned ID', resource.resourceType + '.id')
);
}
resource = await this.createResource(resource);
return { resource, outcome: created };
} else if (matches.length > 1) {
throw new OperationOutcomeError(multipleMatches);
}
const existing = matches[0];
if (resource.id && resource.id !== existing.id) {
throw new OperationOutcomeError(
badRequest('Resource ID did not match resolved ID', resource.resourceType + '.id')
);
}
resource.id = existing.id;
resource = await this.updateResource(resource);
return { resource, outcome: allOk };
});
}
private async updateResourceImpl<T extends Resource>(resource: T, create: boolean, versionId?: string): Promise<T> {
const { resourceType, id } = resource;
if (!id) {
throw new OperationOutcomeError(badRequest('Missing id'));
}
if (!validator.isUUID(id)) {
throw new OperationOutcomeError(badRequest('Invalid id'));
}
await this.validateResource(resource);
if (!this.canWriteResourceType(resourceType)) {
throw new OperationOutcomeError(forbidden);
}
const existing = await this.checkExistingResource<T>(resourceType, id, create);
if (existing) {
(existing.meta as Meta).compartment = this.getCompartments(existing);
if (!this.canWriteToResource(existing)) {
// Check before the update
throw new OperationOutcomeError(forbidden);
}
if (versionId && existing.meta?.versionId !== versionId) {
throw new OperationOutcomeError(preconditionFailed);
}
}
const updated = await rewriteAttachments<T>(RewriteMode.REFERENCE, this, {
...this.restoreReadonlyFields(resource, existing),
});
const resultMeta = {
...updated.meta,
versionId: randomUUID(),
lastUpdated: this.getLastUpdated(existing, resource),
author: this.getAuthor(resource),
};
const result: T = { ...updated, meta: resultMeta };
const project = this.getProjectId(existing, updated);
if (project) {
resultMeta.project = project;
}
const account = await this.getAccount(existing, updated, create);
if (account) {
resultMeta.account = account;
}
resultMeta.compartment = this.getCompartments(result);
if (this.context.checkReferencesOnWrite) {
await validateReferences(result, this.context.projects);
}
if (this.isNotModified(existing, result)) {
this.removeHiddenFields(existing);
return existing;
}
if (!this.isResourceWriteable(existing, result)) {
// Check after the update
throw new OperationOutcomeError(forbidden);
}
await this.handleBinaryUpdate(existing, result);
await this.handleMaybeCacheOnly(result, create);
await setCacheEntry(result);
await addBackgroundJobs(result, { interaction: create ? 'create' : 'update' });
this.removeHiddenFields(result);
return result;
}
/**
* Handles a Binary resource update.
* If the resource has embedded base-64 data, writes the data to the binary storage.
* Otherwise if the resource already exists, copies the existing binary to the new resource.
* @param existing - Existing binary if it exists.
* @param resource - The resource to write to the database.
*/
private async handleBinaryUpdate<T extends Resource>(existing: T | undefined, resource: T): Promise<void> {
if (resource.resourceType !== 'Binary') {
return;
}
if (resource.data) {
await this.handleBinaryData(resource);
} else if (existing) {
await getBinaryStorage().copyBinary(existing as Binary, resource);
}
}
/**
* Handles a Binary resource with embedded base-64 data.
* Writes the data to the binary storage and removes the data field from the resource.
* @param resource - The resource to write to the database.
*/
private async handleBinaryData(resource: Binary): Promise<void> {
// Parse result.data as a base64 string
const buffer = Buffer.from(resource.data as string, 'base64');
// Convert buffer to a Readable stream
const stream = new Readable({
read() {
this.push(buffer);
this.push(null); // Signifies the end of the stream (EOF)
},
});
// Write the stream to the binary storage
await getBinaryStorage().writeBinary(resource, undefined, resource.contentType, stream);
// Remove the data field from the resource
resource.data = undefined;
}
private async handleMaybeCacheOnly(result: Resource, create: boolean): Promise<void> {
if (!this.isCacheOnly(result)) {
await this.writeToDatabase(result, create);
} else if (result.resourceType === 'Subscription' && result.channel?.type === 'websocket') {
const redis = getRedis();
const project = result?.meta?.project;
if (!project) {
throw new OperationOutcomeError(serverError(new Error('No project connected to the specified Subscription.')));
}
// WebSocket Subscriptions are also cache-only, but also need to be added to a special cache key
await redis.sadd(`medplum:subscriptions:r4:project:${project}:active`, `Subscription/${result.id}`);
}
}
/**
* Validates a resource against the current project configuration.
* If strict mode is enabled (default), validates against base StructureDefinition and all profiles.
* If strict mode is disabled, validates against the legacy JSONSchema validator.
* Throws on validation errors.
* Returns silently on success.
* @param resource - The candidate resource to validate.
*/
async validateResource(resource: Resource): Promise<void> {
if (this.context.strictMode) {
const logger = getLogger();
const start = process.hrtime.bigint();
const issues = validateResource(resource);
for (const issue of issues) {
logger.warn(`Validator warning: ${issue.details?.text}`, { project: this.context.projects?.[0], issue });
}
const profileUrls = resource.meta?.profile;
if (profileUrls) {
await this.validateProfiles(resource, profileUrls);
}
const elapsedTime = Number(process.hrtime.bigint() - start);
const MILLISECONDS = 1e6; // Conversion factor from ns to ms
if (elapsedTime > 10 * MILLISECONDS) {
logger.debug('High validator latency', {
resourceType: resource.resourceType,
id: resource.id,
time: elapsedTime / MILLISECONDS,
});
}
} else {
validateResourceWithJsonSchema(resource);
}
}
private async validateProfiles(resource: Resource, profileUrls: string[]): Promise<void> {
const logger = getLogger();
for (const url of profileUrls) {
const loadStart = process.hrtime.bigint();
const profile = await this.loadProfile(url);
const loadTime = Number(process.hrtime.bigint() - loadStart);
if (!profile) {
logger.warn('Unknown profile referenced', {
resource: `${resource.resourceType}/${resource.id}`,
url,
});
continue;
}
const validateStart = process.hrtime.bigint();
validateResource(resource, { profile });
const validateTime = Number(process.hrtime.bigint() - validateStart);
logger.debug('Profile loaded', {
url,
loadTime,
validateTime,
});
}
}
private async loadProfile(url: string): Promise<StructureDefinition | undefined> {
const projectIds = this.context.projects;
if (projectIds?.length) {
// Try loading from cache, using all available Project IDs
const cacheKeys = projectIds.map((id) => getProfileCacheKey(id, url));
const results = await getRedis().mget(...cacheKeys);
const cachedProfile = results.find(Boolean) as string | undefined;
if (cachedProfile) {
return (JSON.parse(cachedProfile) as CacheEntry<StructureDefinition>).resource;
}
}
// Fall back to loading from the DB; descending version sort approximates version resolution for some cases
const profile = await this.searchOne<StructureDefinition>({
resourceType: 'StructureDefinition',
filters: [
{
code: 'url',
operator: Operator.EQUALS,
value: url,
},
],
sortRules: [
{
code: 'version',
descending: true,
},
],
});
if (projectIds?.length && profile) {
// Store loaded profile in cache
await setProfileCacheEntry(projectIds[0], profile);
}
return profile;
}
/**
* Writes the resource to the database.
* This is a single atomic operation inside of a transaction.
* @param resource - The resource to write to the database.
* @param create - If true, then the resource is being created.
*/
private async writeToDatabase<T extends Resource>(resource: T, create: boolean): Promise<void> {
await this.withTransaction(async (client) => {
await this.writeResource(client, resource);
await this.writeResourceVersion(client, resource);
await this.writeLookupTables(client, resource, create);
});
}
/**
* Tries to return the existing resource, if it is available.
* Handles the following cases:
* - Previous version exists
* - Previous version was deleted, and user is restoring it
* - Previous version does not exist, and user does not have permission to create by ID
* - Previous version does not exist, and user does have permission to create by ID
* @param resourceType - The FHIR resource type.
* @param id - The resource ID.
* @param create - Flag for "creating" vs "updating".
* @returns The existing resource, if found.
*/
private async checkExistingResource<T extends Resource>(
resourceType: T['resourceType'],
id: string,
create: boolean
): Promise<T | undefined> {
try {
return await this.readResourceImpl<T>(resourceType, id);
} catch (err) {
const outcome = normalizeOperationOutcome(err);
if (!isOk(outcome) && !isNotFound(outcome) && !isGone(outcome)) {
throw new OperationOutcomeError(outcome, err);
}
if (!create && isNotFound(outcome) && !this.canSetId()) {
throw new OperationOutcomeError(outcome, err);
}
// Otherwise, it is ok if the resource is not found.
// This is an "update" operation, and the outcome is "not-found" or "gone",
// and the current user has permission to create a new version.
return undefined;
}
}
/**
* Returns true if the resource is not modified from the existing resource.
* @param existing - The existing resource.
* @param updated - The updated resource.
* @returns True if the resource is not modified.
*/
private isNotModified<T extends Resource>(existing: T | undefined, updated: T): existing is T {
if (!existing) {
return false;
}
// When stricter FHIR validation is enabled, then this can be removed.
// At present, there are some cases where a server accepts "empty" values that escape the deep equals.
const cleanExisting = JSON.parse(stringify(existing));
const cleanUpdated = JSON.parse(stringify(updated));
return deepEquals(cleanExisting, cleanUpdated);
}
/**
* Rebuilds compartments for all resources of the specified type.
* This is only available to super admins.
* @param resourceType - The resource type.
*/
async rebuildCompartmentsForResourceType(resourceType: ResourceType): Promise<void> {
if (!this.isSuperAdmin()) {
throw new OperationOutcomeError(forbidden);
}
await this.forAllResources(resourceType, async (resource) => {
try {
(resource.meta as Meta).compartment = this.getCompartments(resource);
await this.updateResourceImpl(resource, false);
} catch (err) {
getLogger().error('Failed to rebuild compartments for resource', {
error: normalizeErrorString(err),
});
}
});
}
/**
* Reindexes all resources of the specified type.
* This is only available to the system account.
* This should not result in any change to resources or history.
* @param resourceType - The resource type.
*/
async reindexResourceType(resourceType: ResourceType): Promise<void> {
if (!this.isSuperAdmin()) {
throw new OperationOutcomeError(forbidden);
}
await this.forAllResources(resourceType, async (resource) => {
try {
await this.reindexResourceImpl(resource);
} catch (err) {
getLogger().error('Failed to reindex resource', { error: normalizeErrorString(err) });
}
});
}
/**
* Loops over all resources of the specified type and executes the callback function.
*
* Search for all resources of the specified type.
* Order by lastUpdated ascending to process oldest resources first.
*
* Historically, we used database cursors for this functionality.
* However, for large tables (1 million+ rows), the cursor approach caused performance issues.
*
* Instead, this implementation uses a search query with a sort by lastUpdated.
* This will be slower than the cursor approach, but it is more reliable.
*
* @param resourceType - The resource type.
* @param callback - The callback function to be executed for each resource of the specified type.
*/
async forAllResources<T extends Resource>(
resourceType: T['resourceType'],
callback: (resource: T) => Promise<void>
): Promise<void> {
const batchSize = 1000;
let hasMore = true;
let currentTimestamp: string | undefined = undefined;
while (hasMore) {
const searchRequest: SearchRequest<T> = {
resourceType,
count: batchSize,
sortRules: [{ code: '_lastUpdated', descending: false }],
};
if (currentTimestamp) {
searchRequest.filters = [
{ code: '_lastUpdated', operator: Operator.GREATER_THAN_OR_EQUALS, value: currentTimestamp },
];
}
const bundle = await this.search(searchRequest);
if (bundle.entry) {
for (const entry of bundle.entry) {
const resource = entry.resource as T;
await callback(resource);
const lastUpdated = resource.meta?.lastUpdated as string;
currentTimestamp = lastUpdated;
}
}
hasMore = !!bundle.link?.find((link) => link.relation === 'next');
}
}
/**
* Reindexes the resource.
* This is only available to the system and super admin accounts.
* This should not result in any change to the resource or its history.
* @param resourceType - The resource type.
* @param id - The resource ID.
* @returns Promise to complete.
*/
async reindexResource<T extends Resource = Resource>(resourceType: T['resourceType'], id: string): Promise<void> {
if (!this.isSuperAdmin()) {
throw new OperationOutcomeError(forbidden);
}
await this.withTransaction(async () => {
const resource = await this.readResourceImpl<T>(resourceType, id);
return this.reindexResourceImpl(resource);
});
}
/**
* Internal implementation of reindexing a resource.
* This accepts a resource as a parameter, rather than a resource type and ID.
* When doing a bulk reindex, this will be more efficient because it avoids unnecessary reads.
* @param resource - The resource.
* @returns The reindexed resource.
*/
private async reindexResourceImpl<T extends Resource>(resource: T): Promise<void> {
(resource.meta as Meta).compartment = this.getCompartments(resource);
await this.withTransaction(async (conn) => {
await this.writeResource(conn, resource);
await this.writeLookupTables(conn, resource, false);
});
}
/**
* Resends subscriptions for the resource.
* This is only available to the admin accounts.
* This should not result in any change to the resource or its history.
* @param resourceType - The resource type.
* @param id - The resource ID.
* @returns Promise to complete.
*/
async resendSubscriptions<T extends Resource = Resource>(resourceType: T['resourceType'], id: string): Promise<void> {
if (!this.isSuperAdmin() && !this.isProjectAdmin()) {
throw new OperationOutcomeError(forbidden);
}
const resource = await this.readResourceImpl<T>(resourceType, id);
return addSubscriptionJobs(resource, { interaction: 'update' });
}
async deleteResource<T extends Resource = Resource>(resourceType: T['resourceType'], id: string): Promise<void> {
let resource: Resource;
try {
resource = await this.readResourceImpl<T>(resourceType, id);
} catch (err) {
const outcomeErr = err as OperationOutcomeError;
if (isGone(outcomeErr.outcome)) {
return; // Resource is already deleted, return successfully
}
throw err;
}
try {
if (!this.canWriteResourceType(resourceType) || !this.isResourceWriteable(undefined, resource)) {
throw new OperationOutcomeError(forbidden);
}
await deleteCacheEntry(resourceType, id);
await this.withTransaction(async (conn) => {
const lastUpdated = new Date();
const content = '';
const columns: Record<string, any> = {
id,
lastUpdated,
deleted: true,
projectId: resource.meta?.project,
compartments: this.getCompartments(resource).map((ref) => resolveId(ref)),
content,
};
const searchParams = getSearchParameters(resourceType);
if (searchParams) {
for (const searchParam of Object.values(searchParams)) {
this.buildColumn({ resourceType } as Resource, columns, searchParam);
}