/
FhirIO.java
1890 lines (1706 loc) · 73.8 KB
/
FhirIO.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io.gcp.healthcare;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.services.healthcare.v1.model.DeidentifyConfig;
import com.google.api.services.healthcare.v1.model.HttpBody;
import com.google.api.services.healthcare.v1.model.Operation;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.io.FileIO;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.fs.EmptyMatchTreatment;
import org.apache.beam.sdk.io.fs.MatchResult;
import org.apache.beam.sdk.io.fs.MatchResult.Metadata;
import org.apache.beam.sdk.io.fs.MatchResult.Status;
import org.apache.beam.sdk.io.fs.MoveOptions.StandardMoveOptions;
import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions;
import org.apache.beam.sdk.io.fs.ResourceId;
import org.apache.beam.sdk.io.gcp.healthcare.FhirIO.Import.ContentStructure;
import org.apache.beam.sdk.io.gcp.healthcare.HttpHealthcareApiClient.FhirResourcePagesIterator;
import org.apache.beam.sdk.io.gcp.healthcare.HttpHealthcareApiClient.HealthcareHttpException;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Distribution;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Wait;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollection.IsBounded;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.PInput;
import org.apache.beam.sdk.values.POutput;
import org.apache.beam.sdk.values.PValue;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.apache.beam.sdk.values.TypeDescriptors;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Throwables;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link FhirIO} provides an API for reading and writing resources to <a
* href="https://cloud.google.com/healthcare/docs/concepts/fhir">Google Cloud Healthcare Fhir API.
* </a>
*
* <h3>Reading</h3>
*
* <p>FHIR resources can be read with {@link FhirIO.Read}, which supports use cases where you have a
* ${@link PCollection} of FHIR resource names in the format of projects/{p}/locations/{l}/datasets/{d}/fhirStores/{f}/fhir/{resourceType}/{id}.
* This is appropriate for reading the Fhir notifications from
* a Pub/Sub subscription with {@link PubsubIO#readStrings()} or in cases where you have a manually
* prepared list of resources that you need to process (e.g. in a text file read with {@link
* org.apache.beam.sdk.io.TextIO}*) .
*
* <p>Get Resource contents from the FHIR Store based on the {@link PCollection} of FHIR resource name strings
* {@link FhirIO.Read.Result} where one can call {@link Read.Result#getResources()} to retrieve a
* {@link PCollection} containing the successfully fetched json resources as {@link String}s and/or {@link
* FhirIO.Read.Result#getFailedReads()} to retrieve a {@link PCollection} of {@link HealthcareIOError}
* containing the resources that could not be fetched and the exception as a
* {@link HealthcareIOError}, this can be used to write to the dead letter storage system of your
* choosing. This error handling is mainly to transparently surface errors where the upstream {@link
* PCollection} contains FHIR resources that are not valid or are not reachable due to permissions issues.
*
* Additionally, you can query an entire FHIR Patient resource's compartment (resources that
* refer to the patient, and are referred to by the patient) by calling {@link FhirIO.getPatientEverything} to
* execute a FHIR GetPatientEverythingRequest.
*
* <h3>Writing</h3>
*
* <p>Write Resources can be written to FHIR with two different methods: Import or Execute Bundle.
*
* <p>Execute Bundle This is best for use cases where you are writing to a non-empty FHIR store
* with other clients or otherwise need referential integrity (e.g. A Streaming HL7v2 to FHIR ETL
* pipeline).
*
* <p>Import This is best for use cases where you are populating an empty FHIR store with no other
* clients. It is faster than the execute bundles method but does not respect referential integrity
* and the resources are not written transactionally (e.g. a historical backfill on a new FHIR
* store) This requires each resource to contain a client provided ID. It is important that when
* using import you give the appropriate permissions to the Google Cloud Healthcare Service Agent.
*
* <p>Export This is to export FHIR resources from a FHIR store to Google Cloud Storage. The output
* resources are in ndjson (newline delimited json) of FHIR resources. It is important that when
* using export you give the appropriate permissions to the Google Cloud Healthcare Service Agent.
*
* <p>Deidentify This is to de-identify FHIR resources from a source FHIR store and write the
* result to a destination FHIR store. It is important that the destination store must already
* exist.
*
* <p>Search This is to search FHIR resources within a given FHIR store. The inputs are individual
* FHIR Search queries, represented by the FhirSearchParameter class. The outputs are results of
* each Search, represented as a Json array of FHIR resources in string form, with pagination
* handled, and an optional input key.
*
* @see <a href=>https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores.fhir/executeBundle></a>
* @see <a href=>https://cloud.google.com/healthcare/docs/how-tos/permissions-healthcare-api-gcp-products#fhir_store_cloud_storage_permissions></a>
* @see <a href=>https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores/import></a>
* @see <a href=>https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores/export></a>
* @see <a href=>https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores/deidentify></a>
* @see <a href=>https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores/search></a>
* A {@link PCollection} of {@link String} can be ingested into an Fhir store using {@link
* FhirIO.Write#fhirStoresImport(String, String, String, FhirIO.Import.ContentStructure)} This will
* return a {@link FhirIO.Write.Result} on which you can call {@link
* FhirIO.Write.Result#getFailedBodies()} to retrieve a {@link PCollection} of {@link
* HealthcareIOError} containing the {@link String} that failed to be ingested and the exception.
* <p>Example
* <pre>{@code
* Pipeline pipeline = ...
*
* // Tail the FHIR store by retrieving resources based on Pub/Sub notifications.
* FhirIO.Read.Result readResult = p
* .apply("Read FHIR notifications",
* PubsubIO.readStrings().fromSubscription(options.getNotificationSubscription()))
* .apply(FhirIO.readResources());
*
* // happily retrived resources
* PCollection<String> resources = readResult.getResources();
* // resource paths that couldn't be retrieved + error context
* PCollection<HealthcareIOError<String>> failedReads = readResult.getFailedReads();
*
* failedReads.apply("Write Resources / Stacktrace for Failed Reads to BigQuery",
* BigQueryIO
* .write()
* .to(option.getBQFhirExecuteBundlesDeadLetterTable())
* .withFormatFunction(new HealthcareIOErrorToTableRow()));
*
* output = resources.apply("Happy path transformations", ...);
* FhirIO.Write.Result writeResult =
* output.apply("Execute FHIR Bundles", FhirIO.executeBundles(options.getExistingFhirStore()));
*
* PCollection<HealthcareIOError<String>> failedBundles = writeResult.getFailedInsertsWithErr();
*
* failedBundles.apply("Write failed bundles to BigQuery",
* BigQueryIO
* .write()
* .to(option.getBQFhirExecuteBundlesDeadLetterTable())
* .withFormatFunction(new HealthcareIOErrorToTableRow()));
*
* // Alternatively you could use import for high throughput to a new store.
* FhirIO.Write.Result writeResult =
* output.apply("Import FHIR Resources", FhirIO.executeBundles(options.getNewFhirStore()));
*
* // Export FHIR resources to Google Cloud Storage.
* String fhirStoreName = ...;
* String exportGcsUriPrefix = ...;
* PCollection<String> resources =
* pipeline.apply(FhirIO.exportResourcesToGcs(fhirStoreName, exportGcsUriPrefix));
*
* // De-identify FHIR resources.
* String sourceFhirStoreName = ...;
* String destinationFhirStoreName = ...;
* DeidentifyConfig deidConfig = new DeidentifyConfig(); // use default DeidentifyConfig
* pipeline.apply(FhirIO.deidentify(fhirStoreName, destinationFhirStoreName, deidConfig));
*
* // Search FHIR resources using an "OR" query.
* Map<String, String> queries = new HashMap<>();
* queries.put("name", "Alice,Bob");
* FhirSearchParameter<String> searchParameter = FhirSearchParameter.of("Patient", queries);
* PCollection<FhirSearchParameter<String>> searchQueries =
* pipeline.apply(
* Create.of(searchParameter)
* .withCoder(FhirSearchParameterCoder.of(StringUtf8Coder.of())));
* FhirIO.Search.Result searchResult =
* searchQueries.apply(FhirIO.searchResources(options.getFhirStore()));
* PCollection<JsonArray> resources = searchResult.getResources(); // JsonArray of results
*
* // Search FHIR resources using an "AND" query with a key.
* Map<String, List<String>> listQueries = new HashMap<>();
* listQueries.put("name", Arrays.asList("Alice", "Bob"));
* FhirSearchParameter<List<String>> listSearchParameter =
* FhirSearchParameter.of("Patient", "Alice-Bob-Search", listQueries);
* PCollection<FhirSearchParameter<List<String>>> listSearchQueries =
* pipeline.apply(
* Create.of(listSearchParameter)
* .withCoder(FhirSearchParameterCoder.of(ListCoder.of(StringUtf8Coder.of()))));
* FhirIO.Search.Result listSearchResult =
* searchQueries.apply(FhirIO.searchResources(options.getFhirStore()));
* PCollection<KV<String, JsonArray>> listResource =
* listSearchResult.getKeyedResources(); // KV<"Alice-Bob-Search", JsonArray of results>
*
* </pre>
*
* <h3>Updates to the I/O connector code</h3>
*
* For any significant updates to this I/O connector, please consider involving corresponding code
* reviewers mentioned
* <a href="https://github.com/apache/beam/blob/master/sdks/java/io/google-cloud-platform/OWNERS">
* here</a>.
*/
@SuppressWarnings({
"nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class FhirIO {
static final String BASE_METRIC_PREFIX = "fhirio/";
private static final String LRO_COUNTER_KEY = "counter";
private static final String LRO_SUCCESS_KEY = "success";
private static final String LRO_FAILURE_KEY = "failure";
private static final Logger LOG = LoggerFactory.getLogger(FhirIO.class);
/**
* Read resources from a PCollection of resource IDs (e.g. when subscribing the pubsub
* notifications)
*
* @return the read
* @see Read
*/
public static Read readResources() {
return new Read();
}
/**
* Search resources from a Fhir store with String parameter values.
*
* @return the search
* @see Search
*/
public static Search<String> searchResources(String fhirStore) {
return new Search<>(fhirStore);
}
/**
* Search resources from a Fhir store with any type of parameter values.
*
* @return the search
* @see Search
*/
public static Search<?> searchResourcesWithGenericParameters(String fhirStore) {
return new Search<>(fhirStore);
}
/**
* Import resources. Intended for use on empty FHIR stores
*
* @param fhirStore the fhir store
* @param tempDir the temp dir
* @param deadLetterDir the dead letter dir
* @param contentStructure the content structure
* @return the import
* @see Import
*/
public static Import importResources(
String fhirStore,
String tempDir,
String deadLetterDir,
FhirIO.Import.@Nullable ContentStructure contentStructure) {
return new Import(fhirStore, tempDir, deadLetterDir, contentStructure);
}
/**
* Import resources. Intended for use on empty FHIR stores
*
* @param fhirStore the fhir store
* @param tempDir the temp dir
* @param deadLetterDir the dead letter dir
* @param contentStructure the content structure
* @return the import
* @see Import
*/
public static Import importResources(
ValueProvider<String> fhirStore,
ValueProvider<String> tempDir,
ValueProvider<String> deadLetterDir,
FhirIO.Import.@Nullable ContentStructure contentStructure) {
return new Import(fhirStore, tempDir, deadLetterDir, contentStructure);
}
/**
* Export resources to GCS. Intended for use on non-empty FHIR stores
*
* @param fhirStore the fhir store, in the format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param exportGcsUriPrefix the destination GCS dir, in the format:
* gs://YOUR_BUCKET_NAME/path/to/a/dir
* @return the export
* @see Export
*/
public static Export exportResourcesToGcs(String fhirStore, String exportGcsUriPrefix) {
return new Export(
StaticValueProvider.of(fhirStore), StaticValueProvider.of(exportGcsUriPrefix));
}
/**
* Export resources to GCS. Intended for use on non-empty FHIR stores
*
* @param fhirStore the fhir store, in the format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param exportGcsUriPrefix the destination GCS dir, in the format:
* gs://YOUR_BUCKET_NAME/path/to/a/dir
* @return the export
* @see Export
*/
public static Export exportResourcesToGcs(
ValueProvider<String> fhirStore, ValueProvider<String> exportGcsUriPrefix) {
return new Export(fhirStore, exportGcsUriPrefix);
}
/**
* Deidentify FHIR resources. Intended for use on non-empty FHIR stores
*
* @param sourceFhirStore the source fhir store, in the format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param destinationFhirStore the destination fhir store to write de-identified resources, in the
* format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param deidConfig the DeidentifyConfig
* @return the deidentify
* @see Deidentify
*/
public static Deidentify deidentify(
String sourceFhirStore, String destinationFhirStore, DeidentifyConfig deidConfig) {
return new Deidentify(
StaticValueProvider.of(sourceFhirStore),
StaticValueProvider.of(destinationFhirStore),
StaticValueProvider.of(deidConfig));
}
/**
* Deidentify FHIR resources. Intended for use on non-empty FHIR stores
*
* @param sourceFhirStore the source fhir store, in the format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param destinationFhirStore the destination fhir store to write de-identified resources, in the
* format:
* projects/project_id/locations/location_id/datasets/dataset_id/fhirStores/fhir_store_id
* @param deidConfig the DeidentifyConfig
* @return the deidentify
* @see Deidentify
*/
public static Deidentify deidentify(
ValueProvider<String> sourceFhirStore,
ValueProvider<String> destinationFhirStore,
ValueProvider<DeidentifyConfig> deidConfig) {
return new Deidentify(sourceFhirStore, destinationFhirStore, deidConfig);
}
/**
* Get the patient compartment for a FHIR Patient using the GetPatientEverything/$everything API.
*
* @see <a
* href=https://cloud.google.com/healthcare-api/docs/reference/rest/v1/projects.locations.datasets.fhirStores.fhir/Patient-everything></a>
* @return the patient everything
* @see FhirIOPatientEverything
*/
public static FhirIOPatientEverything getPatientEverything() {
return new FhirIOPatientEverything();
}
/**
* Increments success and failure counters for an LRO. To be used after the LRO has completed.
* This function leverages the fact that the LRO metadata is always of the format: "counter": {
* "success": "1", "failure": "1" }
*
* @param operation LRO operation object.
* @param operationSuccessCounter the success counter for the operation.
* @param operationFailureCounter the failure counter for the operation.
* @param resourceSuccessCounter the success counter for individual resources in the operation.
* @param resourceFailureCounter the failure counter for individual resources in the operation.
*/
private static void incrementLroCounters(
Operation operation,
Counter operationSuccessCounter,
Counter operationFailureCounter,
Counter resourceSuccessCounter,
Counter resourceFailureCounter) {
// Update operation counters.
com.google.api.services.healthcare.v1.model.Status error = operation.getError();
if (error == null) {
operationSuccessCounter.inc();
LOG.debug(String.format("Operation %s finished successfully.", operation.getName()));
} else {
operationFailureCounter.inc();
LOG.error(
String.format(
"Operation %s failed with error code: %d and message: %s.",
operation.getName(), error.getCode(), error.getMessage()));
}
// Update resource counters.
Map<String, Object> opMetadata = operation.getMetadata();
if (opMetadata.containsKey(LRO_COUNTER_KEY)) {
try {
Map<String, String> counters = (Map<String, String>) opMetadata.get(LRO_COUNTER_KEY);
if (counters.containsKey(LRO_SUCCESS_KEY)) {
resourceSuccessCounter.inc(Long.parseLong(counters.get(LRO_SUCCESS_KEY)));
}
if (counters.containsKey(LRO_FAILURE_KEY)) {
Long numFailures = Long.parseLong(counters.get(LRO_FAILURE_KEY));
resourceFailureCounter.inc(numFailures);
if (numFailures > 0) {
LOG.error("Operation " + operation.getName() + " had " + numFailures + " failures.");
}
}
} catch (Exception e) {
LOG.error("failed to increment LRO counters, error message: " + e.getMessage());
}
}
}
/** The type Read. */
public static class Read extends PTransform<PCollection<String>, FhirIO.Read.Result> {
/** Instantiates a new Read. */
public Read() {}
/** The type Result. */
public static class Result implements POutput, PInput {
private PCollection<String> resources;
private PCollection<HealthcareIOError<String>> failedReads;
/** The Pct. */
PCollectionTuple pct;
/**
* Create FhirIO.Read.Result form PCollectionTuple with OUT and DEAD_LETTER tags.
*
* @param pct the pct
* @return the read result
* @throws IllegalArgumentException the illegal argument exception
*/
static FhirIO.Read.Result of(PCollectionTuple pct) throws IllegalArgumentException {
if (pct.has(OUT) && pct.has(DEAD_LETTER)) {
return new FhirIO.Read.Result(pct);
} else {
throw new IllegalArgumentException(
"The PCollection tuple must have the FhirIO.Read.OUT "
+ "and FhirIO.Read.DEAD_LETTER tuple tags");
}
}
private Result(PCollectionTuple pct) {
this.pct = pct;
this.resources = pct.get(OUT);
this.failedReads =
pct.get(DEAD_LETTER).setCoder(HealthcareIOErrorCoder.of(StringUtf8Coder.of()));
}
/**
* Gets failed reads.
*
* @return the failed reads
*/
public PCollection<HealthcareIOError<String>> getFailedReads() {
return failedReads;
}
/**
* Gets resources.
*
* @return the resources
*/
public PCollection<String> getResources() {
return resources;
}
@Override
public Pipeline getPipeline() {
return this.pct.getPipeline();
}
@Override
public Map<TupleTag<?>, PValue> expand() {
return ImmutableMap.of(OUT, resources);
}
@Override
public void finishSpecifyingOutput(
String transformName, PInput input, PTransform<?, ?> transform) {}
}
/** The tag for the main output of FHIR resources. */
public static final TupleTag<String> OUT = new TupleTag<String>() {};
/** The tag for the deadletter output of FHIR resources. */
public static final TupleTag<HealthcareIOError<String>> DEAD_LETTER =
new TupleTag<HealthcareIOError<String>>() {};
@Override
public FhirIO.Read.Result expand(PCollection<String> input) {
return input.apply("Read FHIR Resources", new GetResourceJsonString());
}
/**
* DoFn to fetch a resource from an Google Cloud Healthcare FHIR store based on resource path.
*
* <p>This DoFn consumes a {@link PCollection} of notifications {@link String}s from the FHIR
* store, and fetches the actual {@link String} object based on the path in the notification and
* will output a {@link PCollectionTuple} which contains the output and dead-letter {@link
* PCollection}*.
*
* <p>The {@link PCollectionTuple} output will contain the following {@link PCollection}:
*
* <ul>
* <li>{@link FhirIO.Read#OUT} - Contains all {@link PCollection} records successfully read
* from the Fhir store.
* <li>{@link FhirIO.Read#DEAD_LETTER} - Contains all {@link PCollection} of {@link
* HealthcareIOError}* of resources which failed to be fetched from the FHIR store, with
* error message and stacktrace.
* </ul>
*/
static class GetResourceJsonString extends PTransform<PCollection<String>, FhirIO.Read.Result> {
/** Instantiates a new Get FHIR resource DoFn. */
public GetResourceJsonString() {}
@Override
public FhirIO.Read.Result expand(PCollection<String> resourceIds) {
return new FhirIO.Read.Result(
resourceIds.apply(
ParDo.of(new ReadResourceFn())
.withOutputTags(FhirIO.Read.OUT, TupleTagList.of(FhirIO.Read.DEAD_LETTER))));
}
/** DoFn for getting resources from the FHIR store with error handling. */
static class ReadResourceFn extends DoFn<String, String> {
private static final Logger LOG = LoggerFactory.getLogger(ReadResourceFn.class);
private static final Counter READ_RESOURCE_ERRORS =
Metrics.counter(ReadResourceFn.class, BASE_METRIC_PREFIX + "read_resource_error_count");
private static final Counter READ_RESOURCE_SUCCESS =
Metrics.counter(
ReadResourceFn.class, BASE_METRIC_PREFIX + "read_resource_success_count");
private static final Distribution READ_RESOURCE_LATENCY_MS =
Metrics.distribution(
ReadResourceFn.class, BASE_METRIC_PREFIX + "read_resource_latency_ms");
private HealthcareApiClient client;
private ObjectMapper mapper;
/** Instantiates a new get FHIR resource fn. */
ReadResourceFn() {}
/**
* Instantiate healthcare client.
*
* @throws IOException the io exception
*/
@Setup
public void instantiateHealthcareClient() throws IOException {
this.client = new HttpHealthcareApiClient();
this.mapper = new ObjectMapper();
}
/**
* Process element.
*
* @param context the context
*/
@ProcessElement
public void processElement(ProcessContext context) {
String resourceId = context.element();
try {
context.output(fetchResource(this.client, resourceId));
} catch (Exception e) {
READ_RESOURCE_ERRORS.inc();
LOG.warn(
String.format(
"Error fetching Fhir resource with ID %s writing to Dead Letter "
+ "Queue. Cause: %s Stack Trace: %s",
resourceId, e.getMessage(), Throwables.getStackTraceAsString(e)));
context.output(FhirIO.Read.DEAD_LETTER, HealthcareIOError.of(resourceId, e));
}
}
private String fetchResource(HealthcareApiClient client, String resourceName)
throws IOException, IllegalArgumentException {
long startTime = Instant.now().toEpochMilli();
HttpBody resource = client.readFhirResource(resourceName);
READ_RESOURCE_LATENCY_MS.update(Instant.now().toEpochMilli() - startTime);
if (resource == null) {
throw new IOException(String.format("GET request for %s returned null", resourceName));
}
READ_RESOURCE_SUCCESS.inc();
return mapper.writeValueAsString(resource);
}
}
}
}
/** The type Write. */
@AutoValue
public abstract static class Write extends PTransform<PCollection<String>, Write.Result> {
/** The tag for successful writes to FHIR store. */
public static final TupleTag<String> SUCCESSFUL_BODY = new TupleTag<String>() {};
/** The tag for the failed writes to FHIR store. */
public static final TupleTag<HealthcareIOError<String>> FAILED_BODY =
new TupleTag<HealthcareIOError<String>>() {};
/** The tag for the files that failed to FHIR store. */
public static final TupleTag<HealthcareIOError<String>> FAILED_FILES =
new TupleTag<HealthcareIOError<String>>() {};
/** The tag for temp files for import to FHIR store. */
public static final TupleTag<ResourceId> TEMP_FILES = new TupleTag<ResourceId>() {};
/** The enum Write method. */
public enum WriteMethod {
/**
* Execute Bundle Method executes a batch of requests as a single transaction @see <a
* href=https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores.fhir/executeBundle></a>.
*/
EXECUTE_BUNDLE,
/**
* Import Method bulk imports resources from GCS. This is ideal for initial loads to empty
* FHIR stores. <a
* href=https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores/import></a>.
*/
IMPORT
}
/** The type Result. */
public static class Result implements POutput {
private final Pipeline pipeline;
private final PCollection<String> successfulBodies;
private final PCollection<HealthcareIOError<String>> failedBodies;
private final PCollection<HealthcareIOError<String>> failedFiles;
/**
* Creates a {@link FhirIO.Write.Result} in the given {@link Pipeline}.
*
* @param pipeline the pipeline
* @param bodies the successful and failing bodies results.
* @return the result
*/
static Result in(Pipeline pipeline, PCollectionTuple bodies) throws IllegalArgumentException {
if (bodies.has(SUCCESSFUL_BODY) && bodies.has(FAILED_BODY)) {
return new Result(pipeline, bodies.get(SUCCESSFUL_BODY), bodies.get(FAILED_BODY), null);
} else {
throw new IllegalArgumentException(
"The PCollection tuple bodies must have the FhirIO.Write.SUCCESSFUL_BODY "
+ "and FhirIO.Write.FAILED_BODY tuple tags.");
}
}
static Result in(
Pipeline pipeline,
PCollection<HealthcareIOError<String>> failedBodies,
PCollection<HealthcareIOError<String>> failedFiles) {
return new Result(pipeline, null, failedBodies, failedFiles);
}
/**
* Gets successful bodies from Write.
*
* @return the entries that were inserted
*/
public PCollection<String> getSuccessfulBodies() {
return this.successfulBodies;
}
/**
* Gets failed bodies with err.
*
* @return the failed inserts with err
*/
public PCollection<HealthcareIOError<String>> getFailedBodies() {
return this.failedBodies;
}
/**
* Gets failed file imports with err.
*
* @return the failed GCS uri with err
*/
public PCollection<HealthcareIOError<String>> getFailedFiles() {
return this.failedFiles;
}
@Override
public Pipeline getPipeline() {
return this.pipeline;
}
@Override
public Map<TupleTag<?>, PValue> expand() {
return ImmutableMap.of(
SUCCESSFUL_BODY,
successfulBodies,
FAILED_BODY,
failedBodies,
Write.FAILED_FILES,
failedFiles);
}
@Override
public void finishSpecifyingOutput(
String transformName, PInput input, PTransform<?, ?> transform) {}
private Result(
Pipeline pipeline,
@Nullable PCollection<String> successfulBodies,
PCollection<HealthcareIOError<String>> failedBodies,
@Nullable PCollection<HealthcareIOError<String>> failedFiles) {
this.pipeline = pipeline;
if (successfulBodies == null) {
successfulBodies =
(PCollection<String>) pipeline.apply(Create.empty(StringUtf8Coder.of()));
}
this.successfulBodies = successfulBodies;
this.failedBodies = failedBodies;
if (failedFiles == null) {
failedFiles =
(PCollection<HealthcareIOError<String>>)
pipeline.apply(Create.empty(HealthcareIOErrorCoder.of(StringUtf8Coder.of())));
}
this.failedFiles = failedFiles;
}
}
/**
* Gets Fhir store.
*
* @return the Fhir store
*/
abstract ValueProvider<String> getFhirStore();
/**
* Gets write method.
*
* @return the write method
*/
abstract WriteMethod getWriteMethod();
/**
* Gets content structure.
*
* @return the content structure
*/
abstract Optional<FhirIO.Import.ContentStructure> getContentStructure();
/**
* Gets import gcs temp path.
*
* @return the import gcs temp path
*/
abstract Optional<ValueProvider<String>> getImportGcsTempPath();
/**
* Gets import gcs dead letter path.
*
* @return the import gcs dead letter path
*/
abstract Optional<ValueProvider<String>> getImportGcsDeadLetterPath();
/** The type Builder. */
@AutoValue.Builder
abstract static class Builder {
/**
* Sets Fhir store.
*
* @param fhirStore the Fhir store
* @return the Fhir store
*/
abstract Builder setFhirStore(ValueProvider<String> fhirStore);
/**
* Sets write method.
*
* @param writeMethod the write method
* @return the write method
*/
abstract Builder setWriteMethod(WriteMethod writeMethod);
/**
* Sets content structure.
*
* @param contentStructure the content structure
* @return the content structure
*/
abstract Builder setContentStructure(FhirIO.Import.ContentStructure contentStructure);
/**
* Sets import gcs temp path.
*
* @param gcsTempPath the gcs temp path
* @return the import gcs temp path
*/
abstract Builder setImportGcsTempPath(ValueProvider<String> gcsTempPath);
/**
* Sets import gcs dead letter path.
*
* @param gcsDeadLetterPath the gcs dead letter path
* @return the import gcs dead letter path
*/
abstract Builder setImportGcsDeadLetterPath(ValueProvider<String> gcsDeadLetterPath);
/**
* Build write.
*
* @return the write
*/
abstract Write build();
}
/**
* Import method for batch writing resources. @see <a
* href=https://cloud.google.com/healthcare-api/docs/reference/rest/v1/projects.locations.datasets.fhirStores/import></a>
*
* @param fhirStore the FHIR store
* @param gcsTempPath the gcs temp path
* @param gcsDeadLetterPath the gcs dead letter path
* @param contentStructure the content structure
* @return the write
*/
public static Write fhirStoresImport(
String fhirStore,
String gcsTempPath,
String gcsDeadLetterPath,
FhirIO.Import.@Nullable ContentStructure contentStructure) {
return new AutoValue_FhirIO_Write.Builder()
.setFhirStore(StaticValueProvider.of(fhirStore))
.setWriteMethod(Write.WriteMethod.IMPORT)
.setContentStructure(contentStructure)
.setImportGcsTempPath(StaticValueProvider.of(gcsTempPath))
.setImportGcsDeadLetterPath(StaticValueProvider.of(gcsDeadLetterPath))
.build();
}
public static Write fhirStoresImport(
String fhirStore,
String gcsDeadLetterPath,
FhirIO.Import.@Nullable ContentStructure contentStructure) {
return new AutoValue_FhirIO_Write.Builder()
.setFhirStore(StaticValueProvider.of(fhirStore))
.setWriteMethod(Write.WriteMethod.IMPORT)
.setContentStructure(contentStructure)
.setImportGcsDeadLetterPath(StaticValueProvider.of(gcsDeadLetterPath))
.build();
}
public static Write fhirStoresImport(
ValueProvider<String> fhirStore,
ValueProvider<String> gcsTempPath,
ValueProvider<String> gcsDeadLetterPath,
FhirIO.Import.@Nullable ContentStructure contentStructure) {
return new AutoValue_FhirIO_Write.Builder()
.setFhirStore(fhirStore)
.setWriteMethod(Write.WriteMethod.IMPORT)
.setContentStructure(contentStructure)
.setImportGcsTempPath(gcsTempPath)
.setImportGcsDeadLetterPath(gcsDeadLetterPath)
.build();
}
/**
* Execute Bundle Method executes a batch of requests in batch or as a single transaction @see
* <a
* href=https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores.fhir/executeBundle></a>.
*
* @param fhirStore the fhir store
* @return the write
*/
public static Write executeBundles(String fhirStore) {
return new AutoValue_FhirIO_Write.Builder()
.setFhirStore(StaticValueProvider.of(fhirStore))
.setWriteMethod(WriteMethod.EXECUTE_BUNDLE)
.build();
}
/**
* Execute Bundle Method executes a batch of requests in batch or as a single transaction @see
* <a
* href=https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores.fhir/executeBundle></a>.
*
* @param fhirStore the fhir store
* @return the write
*/
public static Write executeBundles(ValueProvider<String> fhirStore) {
return new AutoValue_FhirIO_Write.Builder()
.setFhirStore(fhirStore)
.setWriteMethod(WriteMethod.EXECUTE_BUNDLE)
.build();
}
private static final Logger LOG = LoggerFactory.getLogger(Write.class);
@Override
public Result expand(PCollection<String> input) {
switch (this.getWriteMethod()) {
case IMPORT:
LOG.warn(
"Make sure the Cloud Healthcare Service Agent has permissions when using import:"
+ " https://cloud.google.com/healthcare/docs/how-tos/permissions-healthcare-api-gcp-products#fhir_store_cloud_storage_permissions");
ValueProvider<String> deadPath =
getImportGcsDeadLetterPath().orElseThrow(IllegalArgumentException::new);
FhirIO.Import.ContentStructure contentStructure =
getContentStructure().orElseThrow(IllegalArgumentException::new);
ValueProvider<String> tempPath =
getImportGcsTempPath()
.orElse(
StaticValueProvider.of(input.getPipeline().getOptions().getTempLocation()));
return input.apply(new Import(getFhirStore(), tempPath, deadPath, contentStructure));
case EXECUTE_BUNDLE:
default:
return input.apply(new ExecuteBundles(this.getFhirStore()));
}
}
}
/**
* Writes each bundle of elements to a new-line delimited JSON file on GCS and issues a
* fhirStores.import Request for that file. This is intended for batch use only to facilitate
* large backfills to empty FHIR stores and should not be used with unbounded PCollections. If
* your use case is streaming checkout using {@link ExecuteBundles} to more safely execute bundles
* as transactions which is safer practice for a use on a "live" FHIR store.
*/
public static class Import extends Write {
private static final Logger LOG = LoggerFactory.getLogger(Import.class);
private final ValueProvider<String> fhirStore;
private final ValueProvider<String> deadLetterGcsPath;
private final ValueProvider<String> tempGcsPath;
private final ContentStructure contentStructure;
/*
* Instantiates a new Import.
*
* @param fhirStore the fhir store
* @param tempGcsPath the temp gcs path
* @param deadLetterGcsPath the dead letter gcs path
* @param contentStructure the content structure
*/
Import(
ValueProvider<String> fhirStore,
ValueProvider<String> tempGcsPath,
ValueProvider<String> deadLetterGcsPath,
@Nullable ContentStructure contentStructure) {
this.fhirStore = fhirStore;
this.tempGcsPath = tempGcsPath;
this.deadLetterGcsPath = deadLetterGcsPath;
if (contentStructure == null) {
this.contentStructure = ContentStructure.CONTENT_STRUCTURE_UNSPECIFIED;
} else {
this.contentStructure = contentStructure;
}
}
Import(
ValueProvider<String> fhirStore,
ValueProvider<String> deadLetterGcsPath,