-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
5725 lines (4775 loc) · 251 KB
/
app.py
File metadata and controls
5725 lines (4775 loc) · 251 KB
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 sys
import collections
from typing import Callable, List, Optional, Annotated
from datetime import datetime
from flask import Flask, g, jsonify, abort, request, Response, redirect, make_response
from neo4j.exceptions import TransactionError
import os
import re
import csv
import requests
from requests.adapters import HTTPAdapter, Retry
import threading
import urllib.request
from io import StringIO
# Don't confuse urllib (Python native library) with urllib3 (3rd-party library, requests also uses urllib3)
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from pathlib import Path
import logging
import json
import time
# pymemcache.client.base.PooledClient is a thread-safe client pool
# that provides the same API as pymemcache.client.base.Client
from pymemcache.client.base import PooledClient
from pymemcache import serde
# Local modules
import app_neo4j_queries
import provenance
from schema import schema_manager
from schema import schema_errors
from schema import schema_triggers
from schema import schema_validators
from schema import schema_neo4j_queries
from schema.schema_constants import SchemaConstants
from schema.schema_constants import DataVisibilityEnum
from schema.schema_constants import MetadataScopeEnum
from schema.schema_constants import TriggerTypeEnum
from metadata_constraints import get_constraints, constraints_json_is_valid
# from lib.ontology import initialize_ubkg, init_ontology, Ontology, UbkgSDK
# HuBMAP commons
from hubmap_commons import string_helper
from hubmap_commons import file_helper as hm_file_helper
from hubmap_commons import neo4j_driver
from hubmap_commons.hm_auth import AuthHelper
from hubmap_commons.exceptions import HTTPException
from hubmap_commons.S3_worker import S3Worker
# Specify the absolute path of the instance folder and use the config file relative to the instance path
app = Flask(__name__, instance_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'instance'), instance_relative_config = True)
app.config.from_pyfile('app.cfg')
# Root logger configuration
global logger
# Set logging format and level
if app.config['DEBUG_MODE']:
logging.basicConfig(format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S')
else:
logging.basicConfig(format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Use `getLogger()` instead of `getLogger(__name__)` to apply the config to the root logger
# will be inherited by the sub-module loggers
logger = logging.getLogger()
# Remove trailing slash / from URL base to avoid "//" caused by config with trailing slash
app.config['UUID_API_URL'] = app.config['UUID_API_URL'].strip('/')
app.config['INGEST_API_URL'] = app.config['INGEST_API_URL'].strip('/')
app.config['ONTOLOGY_API_URL'] = app.config['ONTOLOGY_API_URL'].strip('/')
app.config['ENTITY_API_URL'] = app.config['ENTITY_API_URL'].strip('/')
app.config['SEARCH_API_URL'] = app.config['SEARCH_API_URL'].strip('/')
S3_settings_dict = {'large_response_threshold': app.config['LARGE_RESPONSE_THRESHOLD']
, 'aws_access_key_id': app.config['AWS_ACCESS_KEY_ID']
, 'aws_secret_access_key': app.config['AWS_SECRET_ACCESS_KEY']
, 'aws_s3_bucket_name': app.config['AWS_S3_BUCKET_NAME']
, 'aws_object_url_expiration_in_secs': app.config['AWS_OBJECT_URL_EXPIRATION_IN_SECS']
, 'service_configured_obj_prefix': app.config['AWS_S3_OBJECT_PREFIX']}
# This mode when set True disables the PUT and POST calls, used on STAGE to make entity-api READ-ONLY
# to prevent developers from creating new UUIDs and new entities or updating existing entities
READ_ONLY_MODE = app.config['READ_ONLY_MODE']
# Whether Memcached is being used or not
# Default to false if the property is missing in the configuration file
if 'MEMCACHED_MODE' in app.config:
MEMCACHED_MODE = app.config['MEMCACHED_MODE']
# Use prefix to distinguish the cached data of same source across different deployments
MEMCACHED_PREFIX = app.config['MEMCACHED_PREFIX']
else:
MEMCACHED_MODE = False
MEMCACHED_PREFIX = 'NONE'
# Read the secret key which may be submitted in HTTP Request Headers to override the lockout of
# updates to entities with characteristics prohibiting their modification.
LOCKED_ENTITY_UPDATE_OVERRIDE_KEY = app.config['LOCKED_ENTITY_UPDATE_OVERRIDE_KEY']
# Suppress InsecureRequestWarning warning when requesting status on https with ssl cert verify disabled
requests.packages.urllib3.disable_warnings(category = InsecureRequestWarning)
####################################################################################################
## Register error handlers
####################################################################################################
# Error handler for 400 Bad Request with custom error message
@app.errorhandler(400)
def http_bad_request(e):
return jsonify(error = str(e)), 400
# Error handler for 401 Unauthorized with custom error message
@app.errorhandler(401)
def http_unauthorized(e):
return jsonify(error = str(e)), 401
# Error handler for 403 Forbidden with custom error message
@app.errorhandler(403)
def http_forbidden(e):
return jsonify(error = str(e)), 403
# Error handler for 404 Not Found with custom error message
@app.errorhandler(404)
def http_not_found(e):
return jsonify(error = str(e)), 404
# Error handler for 500 Internal Server Error with custom error message
@app.errorhandler(500)
def http_internal_server_error(e):
return jsonify(error = str(e)), 500
####################################################################################################
## AuthHelper initialization
####################################################################################################
# Initialize AuthHelper class and ensure singleton
try:
if AuthHelper.isInitialized() == False:
auth_helper_instance = AuthHelper.create(app.config['APP_CLIENT_ID'],
app.config['APP_CLIENT_SECRET'])
logger.info('Initialized auth_helper_instance successfully :)')
else:
auth_helper_instance = AuthHelper.instance()
except Exception:
msg = 'Failed to initialize the auth_helper_instance :('
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
####################################################################################################
## Neo4j connection initialization
####################################################################################################
# The neo4j_driver (from commons package) is a singleton module
# This neo4j_driver_instance will be used for application-specific neo4j queries
# as well as being passed to the schema_manager
try:
neo4j_driver_instance = neo4j_driver.instance(app.config['NEO4J_URI'],
app.config['NEO4J_USERNAME'],
app.config['NEO4J_PASSWORD'])
logger.info('Initialized neo4j_driver_instance successfully :)')
except Exception:
msg = 'Failed to initialize the neo4j_driver_instance :('
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
####################################################################################################
## Memcached client initialization
####################################################################################################
memcached_client_instance = None
if MEMCACHED_MODE:
try:
# Use client pool to maintain a pool of already-connected clients for improved performance
# The uwsgi config launches the app across multiple threads (16) inside each process (16), making essentially 256 processes
# Set the connect_timeout and timeout to avoid blocking the process when memcached is slow, defaults to "forever"
# connect_timeout: seconds to wait for a connection to the memcached server
# timeout: seconds to wait for send or reveive calls on the socket connected to memcached
# Use the ignore_exc flag to treat memcache/network errors as cache misses on calls to the get* methods
# Set the no_delay flag to sent TCP_NODELAY (disable Nagle's algorithm to improve TCP/IP networks and decrease the number of packets)
# If you intend to use anything but str as a value, it is a good idea to use a serializer
memcached_client_instance = PooledClient(app.config['MEMCACHED_SERVER'],
max_pool_size = 256,
connect_timeout = 1,
timeout = 30,
ignore_exc = True,
no_delay = True,
serde = serde.pickle_serde)
# memcached_client_instance can be instantiated without connecting to the Memcached server
# A version() call will throw error (e.g., timeout) when failed to connect to server
# Need to convert the version in bytes to string
logger.info('Initialized memcached_client_instance successfully :)')
except Exception:
msg = 'Failed to initialize memcached_client_instance :('
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
# Turn off the caching
MEMCACHED_MODE = False
####################################################################################################
## Schema initialization
####################################################################################################
try:
try:
_schema_yaml_file = app.config['SCHEMA_YAML_FILE']
except KeyError as ke:
logger.error("Expected configuration failed to load %s from app_config=%s.", ke, app.config)
raise Exception("Expected configuration failed to load. See the logs.")
# The schema_manager is a singleton module
# Pass in auth_helper_instance, neo4j_driver instance, and memcached_client_instance
schema_manager.initialize(_schema_yaml_file,
app.config['UUID_API_URL'],
app.config['INGEST_API_URL'],
app.config['ONTOLOGY_API_URL'],
app.config['ENTITY_API_URL'],
auth_helper_instance,
neo4j_driver_instance,
memcached_client_instance,
MEMCACHED_PREFIX)
logger.info('Initialized schema_manager successfully :)')
except Exception:
msg = f"Failed to initialize the schema_manager with" \
f" _schema_yaml_file={_schema_yaml_file}."
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
####################################################################################################
## Initialize an S3Worker from hubmap-commons
####################################################################################################
try:
anS3Worker = S3Worker(ACCESS_KEY_ID=S3_settings_dict['aws_access_key_id']
, SECRET_ACCESS_KEY=S3_settings_dict['aws_secret_access_key']
, S3_BUCKET_NAME=S3_settings_dict['aws_s3_bucket_name']
, S3_OBJECT_URL_EXPIRATION_IN_SECS=S3_settings_dict['aws_object_url_expiration_in_secs']
, LARGE_RESPONSE_THRESHOLD=S3_settings_dict['large_response_threshold']
, SERVICE_S3_OBJ_PREFIX=S3_settings_dict['service_configured_obj_prefix'])
logger.info('Initialized anS3Worker successfully :)')
except Exception:
msg = 'Failed to initialize anS3Worker :('
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
####################################################################################################
## REFERENCE DOI Redirection
####################################################################################################
## Read tsv file with the REFERENCE entity redirects
## sets the reference_redirects dict which is used
## by the /redirect method below
try:
reference_redirects = {}
url = app.config['REDIRECTION_INFO_URL']
# Use Memcached to improve performance
response = schema_manager.make_request_get(url)
resp_txt = response.content.decode('utf-8')
cr = csv.reader(resp_txt.splitlines(), delimiter='\t')
first = True
id_column = None
redir_url_column = None
for row in cr:
if first:
first = False
header = row
column = 0
for label in header:
if label == 'hubmap_id': id_column = column
if label == 'data_information_page': redir_url_column = column
column = column + 1
if id_column is None: raise Exception(f"Column hubmap_id not found in {url}")
if redir_url_column is None: raise Exception (f"Column data_information_page not found in {url}")
else:
reference_redirects[row[id_column].upper().strip()] = row[redir_url_column]
rr = redirect('abc', code = 307)
print(rr)
except Exception:
logger.exception("Failed to read tsv file with REFERENCE redirect information")
####################################################################################################
## Constants
####################################################################################################
# For now, don't use the constants from commons
# All lowercase for easy comparision
#
# Places where these constants are used should be evaluated for refactoring to directly reference the
# constants in SchemaConstants. Constants defined here should be evaluated to move to SchemaConstants.
# All this should be done when the endpoints with changed code can be verified with solid tests.
ACCESS_LEVEL_PUBLIC = SchemaConstants.ACCESS_LEVEL_PUBLIC
ACCESS_LEVEL_CONSORTIUM = SchemaConstants.ACCESS_LEVEL_CONSORTIUM
ACCESS_LEVEL_PROTECTED = SchemaConstants.ACCESS_LEVEL_PROTECTED
DATASET_STATUS_PUBLISHED = SchemaConstants.DATASET_STATUS_PUBLISHED
COMMA_SEPARATOR = ','
####################################################################################################
## API Endpoints
####################################################################################################
"""
The default route
Returns
-------
str
A welcome message
"""
@app.route('/', methods = ['GET'])
def index():
return "Hello! This is HuBMAP Entity API service :)"
"""
Show status of Neo4j connection and Memcached connection (if enabled) with the current VERSION and BUILD
Returns
-------
json
A json containing the status details
"""
@app.route('/status', methods = ['GET'])
def get_status():
try:
file_version_content = (Path(__file__).absolute().parent.parent / 'VERSION').read_text().strip()
except Exception as e:
file_version_content = str(e)
try:
file_build_content = (Path(__file__).absolute().parent.parent / 'BUILD').read_text().strip()
except Exception as e:
file_build_content = str(e)
status_data = {
# Use strip() to remove leading and trailing spaces, newlines, and tabs
'version': file_version_content,
'build': file_build_content,
'neo4j_connection': False
}
# Don't use try/except here
is_neo4j_connected = app_neo4j_queries.check_connection(neo4j_driver_instance)
if is_neo4j_connected:
status_data['neo4j_connection'] = True
# Only show the Memcached connection status when the caching is enabled
if MEMCACHED_MODE:
status_data['memcached_connection'] = False
try:
# If can't connect, won't be able to get the Memcached version
memcached_client_instance.version()
logger.info(f'Connected to Memcached server {memcached_client_instance.version().decode()} :)')
status_data['memcached_connection'] = True
except Exception:
logger.error('Failed to connect to Memcached server :(')
return jsonify(status_data)
"""
Currently for debugging purpose
Essentially does the same as ingest-api's `/metadata/usergroups` using the deprecated commons method
Globus groups token is required by AWS API Gateway lambda authorizer
Returns
-------
json
A json list of globus groups this user belongs to
"""
@app.route('/usergroups', methods = ['GET'])
def get_user_groups():
token = get_user_token(request)
groups_list = auth_helper_instance.get_user_groups_deprecated(token)
return jsonify(groups_list)
"""
Delete ALL the following cached data from Memcached, Data-Admin access is required in AWS API Gateway:
- cached individual entity dict
- cached IDs dict from uuid-api
- cached yaml content from github raw URLs
- cached TSV file content for reference DOIs redirect
Returns
-------
str
A confirmation message
"""
@app.route('/flush-all-cache', methods = ['DELETE'])
def flush_all_cache():
msg = ''
if MEMCACHED_MODE:
memcached_client_instance.flush_all()
msg = 'All cached data (entities, IDs, yamls, tsv) has been deleted from Memcached'
else:
msg = 'No caching is being used because Memcached mode is not enabled at all'
return msg
"""
Delete the cached data from Memcached for a given entity, HuBMAP-Read access is required in AWS API Gateway
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity (Donor/Dataset/Sample/Upload/Collection/Publication)
Returns
-------
str
A confirmation message
"""
@app.route('/flush-cache/<id>', methods = ['DELETE'])
def flush_cache(id):
msg = ''
if MEMCACHED_MODE:
entity_dict = query_target_entity(id, get_internal_token())
delete_cache(entity_dict['uuid'], entity_dict['entity_type'])
msg = f'The cached data has been deleted from Memcached for entity {id}'
else:
msg = 'No caching is being used because Memcached mode is not enabled at all'
return msg
"""
Retrieve the ancestor organ(s) of a given entity
The gateway treats this endpoint as public accessible
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity (Dataset/Sample)
Returns
-------
json
List of organs that are ancestors of the given entity
- Only dataset entities can return multiple ancestor organs
as Samples can only have one parent.
- If no organ ancestors are found an empty list is returned
- If requesting the ancestor organ of a Sample of type Organ or Donor/Collection/Upload
a 400 response is returned.
"""
@app.route('/entities/<id>/ancestor-organs', methods = ['GET'])
def get_ancestor_organs(id):
# Token is not required, but if an invalid token provided,
# we need to tell the client with a 401 error
validate_token_if_auth_header_exists(request)
# Use the internal token to query the target entity
# since public entities don't require user token
token = get_internal_token()
# Get the entity dict from cache if exists
# Otherwise query against uuid-api and neo4j to get the entity dict if the id exists
entity_dict = query_target_entity(id, token)
normalized_entity_type = entity_dict['entity_type']
# A bit validation
if normalized_entity_type not in ['Sample'] and \
not schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
bad_request_error(f"Unable to get the ancestor organs for this: {normalized_entity_type},"
" supported entity types: Sample, Dataset, Publication")
if normalized_entity_type == 'Sample' and entity_dict['sample_category'].lower() == 'organ':
bad_request_error("Unable to get the ancestor organ of an organ.")
public_entity = True
if schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
# Only published/public datasets don't require token
if entity_dict['status'].lower() != DATASET_STATUS_PUBLISHED:
public_entity = False
# Token is required and the user must belong to HuBMAP-READ group
token = get_user_token(request, non_public_access_required = True)
else:
# The `data_access_level` of Sample can only be either 'public' or 'consortium'
if entity_dict['data_access_level'] == ACCESS_LEVEL_CONSORTIUM:
public_entity = False
token = get_user_token(request, non_public_access_required = True)
# By now, either the entity is public accessible or the user token has the correct access level
organs = app_neo4j_queries.get_ancestor_organs(neo4j_driver_instance, entity_dict['uuid'])
excluded_fields = schema_manager.get_fields_to_exclude('Sample')
# Skip executing the trigger method to get Sample.direct_ancestor
properties_to_skip = ['direct_ancestor']
complete_entities_list = schema_manager.get_complete_entities_list(request.args, token, organs, properties_to_skip)
# Final result after normalization
final_result = schema_manager.normalize_entities_list_for_response(complete_entities_list)
if public_entity and not user_in_hubmap_read_group(request):
filtered_organs_list = []
for organ in final_result:
filtered_organs_list.append(schema_manager.exclude_properties_from_response(excluded_fields, organ))
final_result = filtered_organs_list
return jsonify(final_result)
"""
Check if the given entity is a specific type
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity (Dataset/Sample)
type : str
One of the valid entity types
Returns
-------
bool
"""
@app.route('/entities/<id>/instanceof/<type>', methods=['GET'])
def get_entities_instanceof(id, type):
try:
uuid = schema_manager.get_hubmap_ids(id.strip())['uuid']
instanceof: bool = schema_manager.entity_instanceof(uuid, type)
except requests.exceptions.RequestException as e:
status_code = e.response.status_code
if status_code == 400:
bad_request_error(e.response.text)
if status_code == 404:
not_found_error(e.response.text)
else:
internal_server_error(e.response.text)
except:
bad_request_error("Unable to process request")
return make_response(jsonify({'instanceof': instanceof}), 200)
"""
Check if the given entity type A is an instance of the given type B
Parameters
----------
type_a : str
The given entity type A
type_a : str
The given entity type B
Returns
-------
bool
"""
@app.route('/entities/type/<type_a>/instanceof/<type_b>', methods=['GET'])
def get_entities_type_instanceof(type_a, type_b):
try:
instanceof: bool = schema_manager.entity_type_instanceof(type_a, type_b)
except:
bad_request_error("Unable to process request")
return make_response(jsonify({'instanceof': instanceof}), 200)
"""
Endpoint which sends the "visibility" of an entity using values from DataVisibilityEnum.
Not exposed through the gateway. Used by services like search-api to, for example, determine if
a Collection can be in a public index while encapsulating the logic to determine that in this service.
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target collection
Returns
-------
json
A value from DataVisibilityEnum
"""
@app.route('/visibility/<id>', methods = ['GET'])
def get_entity_visibility(id):
# Token is not required, but if an invalid token provided,
# we need to tell the client with a 401 error
validate_token_if_auth_header_exists(request)
# Use the internal token to query the target entity
# since public entities don't require user token
token = get_internal_token()
# Get the entity dict from cache if exists
# Otherwise query against uuid-api and neo4j to get the entity dict if the id exists
entity_dict = query_target_entity(id, token)
normalized_entity_type = entity_dict['entity_type']
# Get the generated complete entity result from cache if exists
# Otherwise re-generate on the fly. To verify if a Collection is public, it is
# necessary to have its Datasets, which are populated as triggered data, so
# pull back the complete entity
complete_dict = schema_manager.get_complete_entity_result(request.args, token, entity_dict)
# Determine if the entity is publicly visible base on its data, only.
entity_scope = _get_entity_visibility(normalized_entity_type=normalized_entity_type, entity_dict=complete_dict)
return jsonify(entity_scope.value)
"""
Retrieve the full provenance metadata information of a given entity by id, as
produced for metadata.json files.
This endpoint as publicly accessible. Without presenting a token, only data for
published Datasets may be requested.
When a valid token is presented, a member of the HuBMAP-Read Globus group is authorized to
access any Dataset. Otherwise, only access to published Datasets is authorized.
An HTTP 400 Response is returned for reasons described in the error message, such as
requesting data for a non-Dataset.
An HTTP 401 Response is returned when a token is presented that is not valid.
An HTTP 403 Response is returned if user is not authorized to access the Dataset, as described above.
An HTTP 404 Response is returned if the requested Dataset is not found.
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity
Returns
-------
json
Valid JSON for the full provenance metadata of the requested Dataset
"""
@app.route('/datasets/<id>/prov-metadata', methods=['GET'])
def get_provenance_metadata_by_id_for_auth_level(id):
# Token is not required, but if an invalid token provided,
# we need to tell the client with a 401 error
validate_token_if_auth_header_exists(request)
# Use the internal token to query the target entity
# since public entities don't require user token
token = get_internal_token()
# The argument id that shadows Python's built-in id should be an identifier for a Dataset.
# Get the entity dict from cache if exists
# Otherwise query against uuid-api and neo4j to get the entity dict if the id exists
dataset_dict = query_target_entity(id, token)
normalized_entity_type = dataset_dict['entity_type']
# A bit validation
if not schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
bad_request_error(f"Unable to get the provenance metatdata for this: {normalized_entity_type},"
" supported entity types: Dataset, Publication")
# Get the generated complete entity result from cache if exists
# Otherwise re-generate on the fly
complete_dict = schema_manager.get_complete_entity_result(request_args=request.args
, token=token
, entity_dict=dataset_dict)
# Determine if the entity is publicly visible base on its data, only.
# To verify if a Collection is public, it is necessary to have its Datasets, which
# are populated as triggered data. So pull back the complete entity for
# _get_entity_visibility() to check.
entity_scope = _get_entity_visibility( normalized_entity_type=normalized_entity_type
,entity_dict=complete_dict)
public_entity = (entity_scope is DataVisibilityEnum.PUBLIC)
# Set a variable reflecting the user's authorization by being in the HuBMAP-READ Globus Group
user_authorized = user_in_hubmap_read_group(request=request)
# Get user token from Authorization header
user_token = get_user_token(request)
# For non-public documents, reject the request if the user is not authorized
if not public_entity:
if user_token is None:
forbidden_error( f"{normalized_entity_type} for {complete_dict['uuid']} is not"
f" accessible without presenting a token.")
if not user_authorized:
forbidden_error( f"The requested {normalized_entity_type} has non-public data."
f" A Globus token with access permission is required.")
# We'll need to return all the properties including those generated by
# `on_read_trigger` to have a complete result e.g., the 'next_revision_uuid' and
# 'previous_revision_uuid' being used below.
# Collections, however, will filter out only public properties for return.
# Also normalize the result based on schema
final_result = schema_manager.normalize_entity_result_for_response(complete_dict)
# Identify fields to exclude from non-authorized responses for the entity type.
fields_to_exclude = schema_manager.get_fields_to_exclude(normalized_entity_type)
# Remove fields which do not belong in provenance metadata, regardless of
# entity scope or user authorization.
final_result = schema_manager.exclude_properties_from_response(fields_to_exclude, final_result)
# Retrieve the associated data for the entity, and add it to the expanded dictionary.
associated_organ_list = _get_dataset_associated_metadata( dataset_dict=final_result
, dataset_visibility=entity_scope
, valid_user_token=user_token
, request=request
, associated_data='Organs')
final_result['organs'] = associated_organ_list
associated_sample_list = _get_dataset_associated_metadata( dataset_dict=final_result
, dataset_visibility=entity_scope
, valid_user_token=user_token
, request=request
, associated_data='Samples')
final_result['samples'] = associated_sample_list
associated_donor_list = _get_dataset_associated_metadata( dataset_dict=final_result
, dataset_visibility=entity_scope
, valid_user_token=user_token
, request=request
, associated_data='Donors')
final_result['donors'] = associated_donor_list
# Return JSON for the dictionary containing the entity metadata as well as metadata for the associated data.
return jsonify(final_result)
"""
Retrieve the metadata information of a given entity by id
The gateway treats this endpoint as public accessible
Result filtering is supported based on query string
For example: /entities/<id>?property=data_access_level
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity
Returns
-------
json
All the properties or filtered property of the target entity
"""
@app.route('/entities/<id>', methods = ['GET'])
def get_entity_by_id(id):
global anS3Worker
# Token is not required, but if an invalid token provided,
# we need to tell the client with a 401 error
validate_token_if_auth_header_exists(request)
# Use the internal token to query the target entity
# since public entities don't require user token
token = get_internal_token()
# Get the entity dict from cache if exists
# Otherwise query against uuid-api and neo4j to get the entity dict if the id exists
entity_dict = query_target_entity(id, token)
normalized_entity_type = entity_dict['entity_type']
# These are the top-level fields and nested fields defined in the schema yaml
fields_to_exclude = schema_manager.get_fields_to_exclude(normalized_entity_type)
# Only support defined query string parameters for filtering purposes
# 'property' was initially introduced to return one of the single fields ['data_access_level', 'status']
# 'exclude' is newly added to reduce the large paylod caused by certain fields (`direct_ancestors.files` for instance)
# When both 'property' and 'exclude' are specified in the URL, 'property' dominates
# since the final result is a single field value - Zhou 10/1/2025
supported_query_params = ['property', 'exclude']
# There are three types of properties that can be excluded from the GET response
# - top-level properties generated by trigger methods
# - top-level properties returned as part of Neo4j node properties
# - second-level properties returned by Neo4j but nested and can't be skipped in Cypher query
triggered_top_props_to_skip = []
neo4j_top_props_to_skip = []
neo4j_nested_props_to_skip = []
if bool(request.args):
# First make sure the user provided query params are valid
for param in request.args:
if param not in supported_query_params:
bad_request_error(f"Only the following URL query parameters (case-sensitive) are supported: {COMMA_SEPARATOR.join(supported_query_params)}")
# Return a single property key and value using ?property=<property_key>
if 'property' in request.args:
single_property_key = request.args.get('property')
# Single property key that is immediately avaibale in Neo4j without running any triggers
# The `data_access_level` property is available in all entities Donor/Sample/Dataset
# and this filter is being used by gateway to check the data_access_level for file assets
# The `status` property is only available in Dataset and being used by search-api for revision
supported_property_keys = ['data_access_level', 'status']
# Validate the target property
if single_property_key not in supported_property_keys:
bad_request_error(f"Only the following property keys are supported in the query parameter: {COMMA_SEPARATOR.join(supported_property_keys)}")
if single_property_key == 'status' and \
not schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
bad_request_error(f"Only Dataset or Publication supports 'status' property key in the query parameter")
# Response with the property value directly
# Don't use jsonify() on string value
return entity_dict[single_property_key]
# Exclude fields—either top-level or nested—specified by the user via the URL query string,
# using the format `?exclude=a.b,a.c,x`, where:
# - `x` is a top-level property of the target entity
# - `a.b` and `a.c` are nested fields in a dot-notated form (b and c could be from a different entity type)
#
# Note: This is not the most efficient approach, as exclusion is performed after the Neo4j query
# rather than within it. However, it leverages the existing `exclude_properties_from_response()`
# function for simplicity and maintainability. - Zhou 10/1/2025
try:
all_props_to_exclude = schema_manager.get_excluded_query_props(request.args)
# Determine which top-level properties to exclude from triggers and which to exclude directly from the resulting Neo4j `entity_dict`
# Also get nested properties that are directly returned from Neo4j, which will be handled differently
triggered_top_props_to_skip, neo4j_top_props_to_skip, neo4j_nested_props_to_skip = schema_manager.get_exclusion_types(normalized_entity_type, all_props_to_exclude)
except ValueError as e:
bad_request_error(e)
except Exception as e:
internal_server_error(e)
# Get the generated complete entity result from cache (only when NO skipped properties) if exists
# Otherwise re-generate on the fly
# NOTE: top-level properties in `triggered_top_props_to_skip` will skip the trigger methods
# Nested properties like `direct_ancestors.files` will be handled by the trigger method - Zhou 10/1/2025
complete_dict = schema_manager.get_complete_entity_result(request.args, token, entity_dict, triggered_top_props_to_skip)
# Determine if the entity is publicly visible base on its data, only.
# To verify if a Collection is public, it is necessary to have its Datasets, which
# are populated as triggered data. So pull back the complete entity for
# _get_entity_visibility() to check.
entity_scope = _get_entity_visibility(normalized_entity_type=normalized_entity_type, entity_dict=complete_dict)
public_entity = False
# Initialize the user as authorized if the data is public. Otherwise, the
# user is not authorized and credentials must be checked.
if entity_scope == DataVisibilityEnum.PUBLIC:
user_authorized = True
public_entity = True
else:
# It's highly possible that there's no token provided
user_token = get_user_token(request)
# The user_token is flask.Response on error
# Without token, the user can only access public collections, modify the collection result
# by only returning public datasets attached to this collection
if isinstance(user_token, Response):
forbidden_error(f"{normalized_entity_type} for {id} is not accessible without presenting a token.")
else:
# When the groups token is valid, but the user doesn't belong to HuBMAP-READ group
# Or the token is valid but doesn't contain group information (auth token or transfer token)
user_authorized = user_in_hubmap_read_group(request)
# We'll need to return all the properties including those generated by
# `on_read_trigger` to have a complete result e.g., the 'next_revision_uuid' and
# 'previous_revision_uuid' being used below.
# Collections, however, will filter out only public properties for return.
if not user_authorized:
forbidden_error(f"The requested {normalized_entity_type} has non-public data."
f" A Globus token with access permission is required.")
# Remove the top-level properties that are directly available in the resulting Neo4j `entity_dict`
# Due to the use of entity cache from `query_target_entity()`, we don't want to exclude the `neo4j_top_props_to_skip`
# from actual Neo4j query. And it's not s performance concern neither. - Zhou 10/1/2025
for item in neo4j_top_props_to_skip:
# Use default value to avoid KeyError if the key is not found
complete_dict.pop(item, f'Key {item} not found')
# Also normalize the result based on schema
final_result = schema_manager.normalize_entity_result_for_response(complete_dict)
# In addition, there may be nested fields like `ingest_metadata.dag_provenance_list` (for Dataset)
# where `ingest_metadata` is an actual Neo4j node string property containing `dag_provenance_list`
# For such cases, we can't handle via simple Neo4j query. Instead, exclude at Python app level.
# NOTE: need to convert the `neo4j_nested_props_to_skip` to a format that can be used by
# `exclude_properties_from_response()` - Zhou 10/1/2025
final_result = schema_manager.exclude_properties_from_response(schema_manager.group_dot_notation_props(neo4j_nested_props_to_skip), final_result)
# Response with the dict
if public_entity and not user_in_hubmap_read_group(request):
final_result = schema_manager.exclude_properties_from_response(fields_to_exclude, final_result)
# Check the size of what is to be returned through the AWS Gateway, and replace it with
# a response that links to an Object in the AWS S3 Bucket, if appropriate.
resp_body = json.dumps(final_result).encode('utf-8')
try_resp = try_stash_response_body(resp_body)
if try_resp is not None:
return try_resp
# Return a regular response through the AWS Gateway
return jsonify(final_result)
"""
Retrieve the JSON containing the metadata information for a given entity which is to go into an
OpenSearch document for the entity. Note this is a subset of the "complete" entity metadata returned by the
`GET /entities/<id>` endpoint, with information design and coding design to perform reasonably for
large volumes of indexing.
The gateway treats this endpoint as public accessible.
Result filtering is supported based on query string
For example: /documents/<id>?property=data_access_level
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity
Returns
-------
json
Metadata for the entity appropriate for an OpenSearch document, and filtered by an additional
`property` arguments in the HTTP request.
"""
@app.route('/documents/<id>', methods = ['GET'])
def get_document_by_id(id):
result_dict = _get_metadata_by_id(entity_id=id, metadata_scope=MetadataScopeEnum.INDEX)
return jsonify(result_dict)
"""
Retrive the full tree above the referenced entity and build the provenance document
The gateway treats this endpoint as public accessible
Parameters
----------
id : str
The HuBMAP ID (e.g. HBM123.ABCD.456) or UUID of target entity
Returns
-------
json
All the provenance details associated with this entity
"""
@app.route('/entities/<id>/provenance', methods = ['GET'])
def get_entity_provenance(id):
# Token is not required, but if an invalid token provided,
# we need to tell the client with a 401 error
validate_token_if_auth_header_exists(request)
# Use the internal token to query the target entity
# since public entities don't require user token
token = get_internal_token()
# Get the entity dict from cache if exists
# Otherwise query against uuid-api and neo4j to get the entity dict if the id exists
entity_dict = query_target_entity(id, token)
uuid = entity_dict['uuid']
normalized_entity_type = entity_dict['entity_type']
# A bit validation to prevent Lab or Collection being queried
if normalized_entity_type not in ['Donor', 'Sample'] and \
not schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
bad_request_error(f"Unable to get the provenance for this {normalized_entity_type},"
" supported entity types: Donor, Sample, Dataset, Publication")
if schema_manager.entity_type_instanceof(normalized_entity_type, 'Dataset'):
# Only published/public datasets don't require token
if entity_dict['status'].lower() != DATASET_STATUS_PUBLISHED:
# Token is required and the user must belong to HuBMAP-READ group
token = get_user_token(request, non_public_access_required = True)
else:
# The `data_access_level` of Donor/Sample can only be either 'public' or 'consortium'
if entity_dict['data_access_level'] == ACCESS_LEVEL_CONSORTIUM:
token = get_user_token(request, non_public_access_required = True)
# By now, either the entity is public accessible or the user token has the correct access level
# Will just proceed to get the provenance information
# Get the `depth` from query string if present and it's used by neo4j query
# to set the maximum number of hops in the traversal
depth = None
if 'depth' in request.args:
depth = int(request.args.get('depth'))
# Convert neo4j json to dict