-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
1397 lines (1276 loc) · 49.8 KB
/
data.py
File metadata and controls
1397 lines (1276 loc) · 49.8 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
"""API functions related to data."""
import uuid
from datetime import datetime, date
from databricks.sdk import WorkspaceClient
from typing import Annotated, Any, Dict, List
from pydantic import BaseModel
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.responses import FileResponse
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from sqlalchemy.future import select
import os
import logging
from sqlalchemy.exc import IntegrityError
from ..config import databricks_vars, env_vars, gcs_vars
import mlflow
from mlflow.exceptions import MlflowException
import tempfile
from ..utilities import (
has_access_to_inst_or_err,
has_full_data_access_or_err,
BaseUser,
model_owner_and_higher_or_err,
uuid_to_str,
str_to_uuid,
get_current_active_user,
DataSource,
get_external_bucket_name,
decode_url_piece,
)
from ..database import (
get_session,
local_session,
BatchTable,
FileTable,
InstTable,
)
from ..databricks import DatabricksControl
from ..gcsdbutils import update_db_from_bucket
from ..gcsutil import StorageControl
# Set the logging
logging.basicConfig(format="%(asctime)s [%(levelname)s]: %(message)s")
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
router = APIRouter(
prefix="/institutions",
tags=["data"],
)
LOGGER = logging.getLogger(__name__)
class BatchCreationRequest(BaseModel):
"""The Batch creation request."""
# Must be unique within an institution to avoid confusion
name: str
# Disabled data means it is no longer in use or not available for use.
batch_disabled: bool = False
# You can specify files to include as ids or names.
file_ids: set[str] | None = None
file_names: set[str] | None = None
completed: bool | None = None
# Set this to set this batch for deletion.
deleted: bool = False
class BatchInfo(BaseModel):
"""The Batch Data object that's returned."""
# In order to allow PATCH commands, each field must be marked as nullable.
batch_id: str | None = None
inst_id: str | None = None
file_names_to_ids: Dict[str, str] = {}
# Must be unique within an institution to avoid confusion
name: str | None = None
# User id of uploader or person who triggered this data ingestion.
created_by: str | None = None
# Deleted data means this batch has a pending deletion request and can no longer be used.
deleted: bool | None = None
# Completed batches means this batch is ready for use. Completed batches will
# trigger notifications to Datakind.
# Can be modified after completion, but this information will not re-trigger
# notifications to Datakind.
completed: bool | None = None
# Date in form YYMMDD. Deletion of a batch will apply to all files in a batch,
# unless the file is present in other batches.
deletion_request_time: str | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
# The following is the user who last updated this batch.
updated_by: str | None = None
class DataInfo(BaseModel):
"""The Data object that's returned. Generally maps to a file, but technically maps to a GCS blob."""
# Must be unique within an institution to avoid confusion.
name: str
data_id: str
# The batch(es) that this data is present in.
batch_ids: set[str] = set()
inst_id: str
# Size to the nearest MB.
# size_mb: int
# User id of uploader or person who triggered this data ingestion. For SST generated files, this field would be null.
uploader: str | None = None
# Can be PDP_SFTP, MANUAL_UPLOAD etc.
source: DataSource | None = None
# Deleted data means this file has a pending deletion request or is deleted and can no longer be used.
deleted: bool = False
# Date in form YYMMDD
deletion_request_time: date | None = None
# How long to retain the data.
# By default (None) -- it is deleted after a successful run. For training dataset it
# is deleted after the trained model is approved. For inference input, it is deleted
# after the inference run occurs. For inference output, it is retained indefinitely
# unless an ad hoc deletion request is received. The type of data is determined by
# the storage location.
retention_days: int | None = None
# Whether the file was generated by SST. (e.g. was it input or output)
sst_generated: bool
# Whether the file was validated (in the case of input) or approved (in the case of output).
valid: bool = False
uploaded_date: datetime
class ValidationResult(BaseModel):
"""The returned validation result."""
# Must be unique within an institution to avoid confusion.
name: str
inst_id: str
file_types: List[str]
source: str
class DataOverview(BaseModel):
"""All data for a given institution (batches and files)."""
batches: list[BatchInfo]
files: list[DataInfo]
# Data related operations. Input files mean files sourced from the institution. Output files are generated by SST.
def get_all_files(
inst_id: str,
sst_generated_value: bool | None,
sess: Session,
storage_control: Any,
) -> list[DataInfo]:
"""Retrieve all files."""
# Update from bucket
if sst_generated_value:
update_db_from_bucket(inst_id, sess, storage_control)
sess.commit()
# construct query
query = None
if sst_generated_value is None:
query = select(FileTable).where(
FileTable.inst_id == str_to_uuid(inst_id),
)
else:
query = select(FileTable).where(
and_(
FileTable.inst_id == str_to_uuid(inst_id),
FileTable.sst_generated == sst_generated_value,
)
)
result_files = []
for e in sess.execute(query).all():
elem = e[0]
result_files.append(
{
"name": elem.name,
"data_id": uuid_to_str(elem.id),
"batch_ids": uuids_to_strs(elem.batches),
"inst_id": uuid_to_str(elem.inst_id),
# "size_mb": elem.size_mb,
"uploader": uuid_to_str(elem.uploader),
"source": elem.source,
"deleted": False if elem.deleted is None else elem.deleted,
"deletion_request_time": elem.deleted_at,
"retention_days": elem.retention_days,
"sst_generated": elem.sst_generated,
"valid": elem.valid,
"uploaded_date": elem.created_at,
}
)
return result_files # type: ignore
def get_all_batches(
inst_id: str, output_batches_only: bool, sess: Session
) -> list[BatchInfo]:
"""Some batches are associated with output. This function lets you decide if you want only those batches."""
query_result_batches = sess.execute(
select(BatchTable).where(BatchTable.inst_id == str_to_uuid(inst_id))
).all()
result_batches = []
for e in query_result_batches:
# Note that batches may show file ids of invalid or unapproved files.
# And will show input and output files.
elem = e[0]
if output_batches_only:
output_files = [x for x in elem.files if x.sst_generated]
if not output_files:
continue
result_batches.append(
{
"batch_id": uuid_to_str(elem.id),
"inst_id": uuid_to_str(elem.inst_id),
"name": elem.name,
"file_names_to_ids": {x.name: uuid_to_str(x.id) for x in elem.files},
"created_by": uuid_to_str(elem.created_by),
"deleted": False if elem.deleted is None else elem.deleted,
"completed": False if elem.completed is None else elem.completed,
"deletion_request_time": elem.deleted_at,
"created_at": elem.created_at,
"updated_by": uuid_to_str(elem.updated_by),
"updated_at": elem.updated_at,
}
)
return result_batches # type: ignore
def uuids_to_strs(files: Any) -> set[str]:
"""Convert a set of uuids to strings.
The input is of type sqlalchemy.orm.collections.InstrumentedSet.
"""
return [uuid_to_str(x.id) for x in files] # type: ignore
def strs_to_uuids(files: Any) -> set[uuid.UUID]:
"""Convert a set of strs to uuids."""
return [str_to_uuid(x) for x in files] # type: ignore
@router.get("/{inst_id}/input", response_model=DataOverview)
def read_inst_all_input_files(
inst_id: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Returns top-level overview of input data (date uploaded, size, file names etc.).
Only visible to data owners of that institution or higher.
"""
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "input data")
# Datakinders can see unapproved files as well.
local_session.set(sql_session)
return {
"batches": get_all_batches(inst_id, False, local_session.get()),
# Set sst_generated_value=false to get input only
"files": get_all_files(inst_id, False, local_session.get(), None),
}
@router.get("/{inst_id}/output", response_model=DataOverview)
def read_inst_all_output_files(
inst_id: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],
) -> Any:
"""Returns top-level overview of output data (date uploaded, size, file names etc.) and batch info.
Only visible to data owners of that institution or higher.
"""
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "output data")
local_session.set(sql_session)
return {
# Set output_batches_only=true to get output related batches only.
"batches": get_all_batches(inst_id, True, local_session.get()),
# Set sst_generated_value=true to get output only.
"files": get_all_files(
inst_id,
True,
local_session.get(),
storage_control,
),
}
# TODO: rename this function to better reflect its behavior.
@router.post("/{inst_id}/update-data")
def update_data(
inst_id: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],
) -> Any:
"""Updates the database depending on what's new in the bucket. For instance, if
a pipeline run completed and there are new outputs in the bucket, we want to
update the database so that the API can be aware of these changes."""
has_access_to_inst_or_err(inst_id, current_user)
local_session.set(sql_session)
update_db_from_bucket(inst_id, local_session.get(), storage_control)
local_session.get().commit()
@router.get("/{inst_id}/output-file-contents/{file_name:path}", response_model=bytes)
def retrieve_file_as_bytes(
inst_id: str,
file_name: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],
) -> Any:
"""Returns top-level overview of output data (date uploaded, size, file names etc.) and batch info.
Only visible to data owners of that institution or higher.
"""
file_name = decode_url_piece(file_name)
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "output file")
local_session.set(sql_session)
# TODO: consider removing this call here and forcing users to call <inst-id>/update-data
update_db_from_bucket(inst_id, local_session.get(), storage_control)
local_session.get().commit()
# We don't include the valid check, because we want to return unapproved AND approved data.
query_result = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.sst_generated,
FileTable.name == file_name,
FileTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No such output file exists.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Multiple matches found. Unexpected.",
)
if query_result[0][0].sst_generated:
if query_result[0][0].valid:
file_name = "approved/" + file_name
else:
file_name = "unapproved/" + file_name
else:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Only SST generated files can be retrieved.",
)
res = storage_control.get_file_contents(
get_external_bucket_name(inst_id), file_name
)
return Response(res)
@router.get("/{inst_id}/batch/{batch_id}", response_model=DataOverview)
def read_batch_info(
inst_id: str,
batch_id: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Returns batch info and files in that batch.
Only visible to users of that institution or Datakinder access types.
"""
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "batch data")
local_session.set(sql_session)
query_result = (
local_session.get()
.execute(
select(BatchTable).where(
and_(
BatchTable.id == str_to_uuid(batch_id),
BatchTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if not query_result or len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No such batch exists.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Batch duplicates found.",
)
res = query_result[0][0]
batch_info = {
"batch_id": uuid_to_str(res.id),
"inst_id": uuid_to_str(res.inst_id),
"name": res.name,
"file_names_to_ids": {x.name: uuid_to_str(x.id) for x in res.files},
"created_by": uuid_to_str(res.created_by),
"deleted": False if res.deleted is None else res.deleted,
"completed": False if res.completed is None else res.completed,
"deletion_request_time": res.deleted_at,
"created_at": res.created_at,
"updated_at": res.updated_at,
"updated_by": uuid_to_str(res.updated_by),
}
data_infos = []
for elem in res.files:
data_infos.append(
{
"name": elem.name,
"data_id": uuid_to_str(elem.id),
"batch_ids": uuids_to_strs(elem.batches),
"inst_id": uuid_to_str(elem.inst_id),
# "size_mb": elem.size_mb,
"uploader": uuid_to_str(elem.uploader),
"source": elem.source,
"deleted": False if elem.deleted is None else elem.deleted,
"deletion_request_time": elem.deleted_at,
"retention_days": elem.retention_days,
"sst_generated": elem.sst_generated,
"valid": elem.valid,
"uploaded_date": elem.created_at,
}
)
return {"batches": [batch_info], "files": data_infos}
@router.post("/{inst_id}/batch", response_model=BatchInfo)
def create_batch(
inst_id: str,
req: BatchCreationRequest,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Create a new batch."""
has_access_to_inst_or_err(inst_id, current_user)
model_owner_and_higher_or_err(current_user, "batch")
local_session.set(sql_session)
query_result = (
local_session.get()
.execute(
select(BatchTable).where(
and_(
BatchTable.name == req.name,
BatchTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if len(query_result) == 0:
batch = BatchTable(
name=req.name,
inst_id=str_to_uuid(inst_id),
created_by=str_to_uuid(current_user.user_id), # type: ignore
)
f_names = [] if not req.file_names else req.file_names
f_ids = [] if not req.file_ids else strs_to_uuids(req.file_ids)
# Check that the files requested for this batch exists.
# Only valid non-sst generated files can be added to a batch at creation time.
query_result_files = (
local_session.get()
.execute(
select(FileTable).where(
and_(
or_(
FileTable.id.in_(f_ids),
FileTable.name.in_(f_names),
),
FileTable.inst_id == str_to_uuid(inst_id),
FileTable.valid == True,
FileTable.sst_generated == False,
)
)
)
.all()
)
if not query_result_files or len(query_result_files) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="file in request not found.",
)
for elem in query_result_files:
batch.files.add(elem[0])
local_session.get().add(batch)
local_session.get().commit()
query_result = (
local_session.get()
.execute(
select(BatchTable).where(
and_(
BatchTable.name == req.name,
BatchTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if not query_result:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Database write of the batch creation failed.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Database write of the batch created duplicate entries.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Batch with this name already exists.",
)
return {
"batch_id": uuid_to_str(query_result[0][0].id),
"inst_id": uuid_to_str(query_result[0][0].inst_id),
"name": query_result[0][0].name,
"file_names_to_ids": {
x.name: uuid_to_str(x.id) for x in query_result[0][0].files
},
"created_by": uuid_to_str(query_result[0][0].created_by),
"deleted": False,
"completed": False,
"deletion_request_time": None,
"created_at": query_result[0][0].created_at,
"updated_by": uuid_to_str(query_result[0][0].updated_by),
"updated_at": query_result[0][0].updated_at,
}
@router.patch("/{inst_id}/batch/{batch_id}", response_model=BatchInfo)
def update_batch(
inst_id: str,
batch_id: str,
request: BatchCreationRequest,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Modifies an existing batch. Only some fields are allowed to be modified."""
has_access_to_inst_or_err(inst_id, current_user)
model_owner_and_higher_or_err(current_user, "modify batch")
update_data_req = request.model_dump(exclude_unset=True)
local_session.set(sql_session)
# Check that the batch exists.
query_result = (
local_session.get()
.execute(
select(BatchTable).where(
and_(
BatchTable.id == str_to_uuid(batch_id),
BatchTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if not query_result or len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Batch not found.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Multiple batches with same unique id found.",
)
existing_batch = query_result[0][0]
if existing_batch.deleted:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Batch is set for deletion, no modifications allowed.",
)
if "deleted" in update_data_req and update_data_req["deleted"]:
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail="Batch deletion not yet implemented.",
)
if "file_ids" in update_data_req or "file_names" in update_data_req:
existing_batch.files.clear()
if "file_ids" in update_data_req:
for f in strs_to_uuids(update_data_req["file_ids"]):
# Check that the files requested for this batch exists
query_result_file = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.id == f,
FileTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if not query_result_file or len(query_result_file) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="file in request not found.",
)
if len(query_result_file) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Multiple files in request with same unique id found.",
)
existing_batch.files.add(query_result_file[0][0])
if "file_names" in update_data_req:
for f in update_data_req["file_names"]:
# Check that the files requested for this batch exists
query_result_file = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.name == f,
FileTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
if not query_result_file or len(query_result_file) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="file in request not found.",
)
if len(query_result_file) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Multiple files in request with same unique id found.",
)
existing_batch.files.add(query_result_file[0][0])
if "name" in update_data_req:
existing_batch.name = update_data_req["name"]
if "completed" in update_data_req:
existing_batch.completed = update_data_req["completed"]
existing_batch.updated_by = str_to_uuid(current_user.user_id) # type: ignore
local_session.get().commit()
res = (
local_session.get()
.execute(
select(BatchTable).where(
and_(
BatchTable.id == str_to_uuid(batch_id),
BatchTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
return {
"batch_id": uuid_to_str(res[0][0].id),
"inst_id": uuid_to_str(res[0][0].inst_id),
"name": res[0][0].name,
"file_names_to_ids": {x.name: uuid_to_str(x.id) for x in res[0][0].files},
"created_by": uuid_to_str(res[0][0].created_by),
"deleted": res[0][0].deleted,
"completed": res[0][0].completed,
"deletion_request_time": res[0][0].deleted_at,
"created_at": res[0][0].created_at,
"updated_by": uuid_to_str(query_result[0][0].updated_by),
"updated_at": query_result[0][0].updated_at,
}
@router.get("/{inst_id}/file-id/{file_id}", response_model=DataInfo)
def read_file_id_info(
inst_id: str,
file_id: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Returns details on a given file.
Only visible to users of that institution or Datakinder access types.
"""
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "file data")
local_session.set(sql_session)
query_result = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.id == str_to_uuid(file_id),
FileTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
# This should only result in a match of a single file.
if not query_result or len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="File duplicates found.",
)
res = query_result[0][0]
return {
"name": res.name,
"data_id": uuid_to_str(res.id),
"batch_ids": uuids_to_strs(res.batches),
"inst_id": uuid_to_str(res.inst_id),
# "size_mb": res.size_mb,
"uploader": uuid_to_str(res.uploader),
"source": res.source,
"deleted": False if res.deleted is None else res.deleted,
"deletion_request_time": res.deleted_at,
"retention_days": res.retention_days,
"sst_generated": res.sst_generated,
"valid": res.valid,
"uploaded_date": res.created_at,
}
@router.get("/{inst_id}/file/{file_name:path}", response_model=DataInfo)
def read_file_info(
inst_id: str,
file_name: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Returns a given file's data.
Only visible to users of that institution or Datakinder access types.
"""
file_name = decode_url_piece(file_name)
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "file data")
local_session.set(sql_session)
query_result = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.name == file_name,
FileTable.inst_id == str_to_uuid(inst_id),
)
)
)
.all()
)
# This should only result in a match of a single file.
if not query_result or len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="File duplicates found.",
)
res = query_result[0][0]
return {
"name": res.name,
"data_id": uuid_to_str(res.id),
"batch_ids": uuids_to_strs(res.batches),
"inst_id": uuid_to_str(res.inst_id),
# "size_mb": res.size_mb,
"uploader": uuid_to_str(res.uploader),
"source": res.source,
"deleted": False if res.deleted is None else res.deleted,
"deletion_request_time": res.deleted_at,
"retention_days": res.retention_days,
"sst_generated": res.sst_generated,
"valid": res.valid,
"uploaded_date": res.created_at,
}
@router.get("/{inst_id}/download-url/{file_name:path}", response_model=str)
def download_url_inst_file(
inst_id: str,
file_name: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
sql_session: Annotated[Session, Depends(get_session)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],
) -> Any:
"""Enables download of output files (approved and unapproved).
Only visible to users of that institution or Datakinder access types.
"""
file_name = decode_url_piece(file_name)
has_access_to_inst_or_err(inst_id, current_user)
has_full_data_access_or_err(current_user, "file data")
local_session.set(sql_session)
query_result = (
local_session.get()
.execute(
select(FileTable).where(
and_(
FileTable.name == file_name,
FileTable.inst_id == str_to_uuid(inst_id),
FileTable.sst_generated,
)
)
)
.all()
)
# This should only result in a match of a single file.
if not query_result or len(query_result) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File does not exist or is not available for download.",
)
if len(query_result) > 1:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="File duplicates found.",
)
if query_result[0][0].deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File has been deleted.",
)
if query_result[0][0].sst_generated:
if query_result[0][0].valid:
file_name = "approved/" + file_name
else:
file_name = "unapproved/" + file_name
else:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Only SST generated files can be downloaded.",
)
return storage_control.generate_download_signed_url(
get_external_bucket_name(inst_id), file_name
)
def infer_models_from_filename(file_path: str, institution_id: str) -> List[str]:
name = os.path.basename(file_path).lower()
inferred = set()
if "course" in name:
inferred.add("COURSE")
if "student" in name:
inferred.add("STUDENT")
if "semester" in name:
inferred.add("SEMESTER")
if "cohort" in name:
inferred.add("STUDENT")
if "course" not in name and ("ar" in name or "deidentified" in name):
inferred.add("STUDENT")
if not inferred:
logging.error(
ValueError(
f"Could not infer model(s) from file name: {name}, filenames sould be descriptive of the kind of data it contains e.g. course, cohort"
)
)
inferred.add("UNKNOWN")
return sorted(inferred)
def validation_helper(
source_str: str,
inst_id: str,
file_name: str,
current_user: BaseUser,
storage_control: StorageControl,
sql_session: Session,
) -> Any:
"""Helper function for file validation."""
has_access_to_inst_or_err(inst_id, current_user)
if file_name.find("/") != -1:
raise HTTPException(
status_code=422,
detail="File name can't contain '/'.",
)
local_session.set(sql_session)
allowed_schemas = None
if not allowed_schemas:
allowed_schemas = infer_models_from_filename(file_name, "pdp")
inferred_schemas: list[str] = []
try:
inferred_schemas = storage_control.validate_file(
get_external_bucket_name(inst_id),
file_name,
allowed_schemas,
)
logging.debug(
f"!!!!!!!!!!Inferred Schemas was successful {list(inferred_schemas)}"
)
except Exception as e:
logging.debug(f"!!!!!!!!!!Inferred Schemas FAILED {e}")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="File type is not valid and/or not accepted by this institution: "
+ str(e),
) from e
existing_file = (
local_session.get()
.query(FileTable)
.filter_by(
name=file_name,
inst_id=str_to_uuid(inst_id),
)
.first()
)
if existing_file:
logging.info(f"File '{file_name}' already exists for institution {inst_id}.")
db_status = f"File '{file_name}' already exists for institution {inst_id}."
else:
try:
new_file_record = FileTable(
name=file_name,
inst_id=str_to_uuid(inst_id),
uploader=str_to_uuid(current_user.user_id), # type: ignore
source=source_str,
sst_generated=False,
schemas=list(allowed_schemas),
valid=True,
)
local_session.get().add(new_file_record)
local_session.get().flush()
logging.info(f"File record inserted for '{file_name}'")
db_status = f"File record inserted for '{file_name}'"
except IntegrityError as e:
local_session.get().rollback()
logging.warning(f"IntegrityError: {e}")
db_status = "Already exists"
except Exception as e:
local_session.get().rollback()
logging.error(f"Unexpected DB error: {e}")
raise HTTPException(
status_code=500,
detail=f"Unexpected database error while inserting file record: {e}",
)
return {
"name": file_name,
"inst_id": inst_id,
"file_types": list(allowed_schemas),
"source": source_str,
"status": db_status,
}
@router.post(
"/{inst_id}/input/validate-sftp/{file_name:path}", response_model=ValidationResult
)
def validate_file_sftp(
inst_id: str,
file_name: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],
sql_session: Annotated[Session, Depends(get_session)],
) -> Any:
"""Validate a given file pulled from SFTP. The file_name should be url encoded."""
file_name = decode_url_piece(file_name)
if not current_user.is_datakinder: # type: ignore
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="SFTP validation needs to be done by a datakinder.",
)
return validation_helper(
"PDP_SFTP", inst_id, file_name, current_user, storage_control, sql_session
)
@router.post(
"/{inst_id}/input/validate-upload/{file_name:path}", response_model=ValidationResult
)
def validate_file_manual_upload(
inst_id: str,
file_name: str,
current_user: Annotated[BaseUser, Depends(get_current_active_user)],
storage_control: Annotated[StorageControl, Depends(StorageControl)],