divbase-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,553 @@
1
+ """
2
+ Service layer for DivBase CLI S3 file operations.
3
+ """
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+ import typer
11
+ from rich import print
12
+
13
+ from divbase_cli.cli_exceptions import (
14
+ FileAlreadyUploadedError,
15
+ FileDoesNotExistInSpecifiedVersionError,
16
+ FileNotFoundInProjectError,
17
+ InvalidInputError,
18
+ )
19
+ from divbase_cli.services.pre_signed_urls import (
20
+ DownloadOutcome,
21
+ FailedUpload,
22
+ SkippedUpload,
23
+ SuccessfulUpload,
24
+ UploadOutcome,
25
+ download_multiple_pre_signed_urls,
26
+ perform_multipart_upload,
27
+ upload_multiple_singlepart_pre_signed_urls,
28
+ )
29
+ from divbase_cli.services.project_versions import get_version_details_command
30
+ from divbase_cli.user_auth import make_authenticated_request
31
+ from divbase_lib.api_schemas.s3 import (
32
+ FileChecksumResponse,
33
+ ListDeletedObjectsRequest,
34
+ ListObjectsRequest,
35
+ ListObjectsResponse,
36
+ MakeDirectoriesRequest,
37
+ MakeDirectoriesResponse,
38
+ ObjectDetails,
39
+ ObjectInfoResponse,
40
+ PreSignedDownloadResponse,
41
+ PreSignedSinglePartUploadResponse,
42
+ RestoreObjectsResponse,
43
+ SoftDeletedObjectDetails,
44
+ )
45
+ from divbase_lib.divbase_constants import (
46
+ MAX_S3_API_BATCH_SIZE,
47
+ QUERY_RESULTS_FILE_PREFIX,
48
+ S3_MULTIPART_UPLOAD_THRESHOLD,
49
+ )
50
+ from divbase_lib.s3_checksums import (
51
+ MD5CheckSumFormat,
52
+ calculate_composite_md5_s3_etag,
53
+ calculate_md5_checksum,
54
+ convert_checksum_hex_to_base64,
55
+ )
56
+
57
+
58
+ @dataclass
59
+ class ToDownload:
60
+ """
61
+ Represent a file to be download in the download-all command. This unifies the 2 ways we get the files needed:
62
+ 1. From the latest files in the bucket (listing files)
63
+ 2. From a user defined project version (getting the files from the version details)"
64
+ """
65
+
66
+ s3_key: str
67
+ etag: str
68
+ size_bytes: int
69
+ version_id: str | None = None # latest version if None
70
+
71
+
72
+ @dataclass
73
+ class ToUpload:
74
+ """
75
+ Represents a file to be uploaded in the files upload command.
76
+ """
77
+
78
+ file_path: Path
79
+ destination_key: str # what the file will be called in the project store. Can include "/"s to represent "folder" paths e.g. "some/subdirs/file.tsv"
80
+ checksum_local: str | None = None # None if not uploaded with "safe-mode"
81
+
82
+ @property
83
+ def file_name(self) -> str:
84
+ return self.file_path.name
85
+
86
+ @property
87
+ def file_size(self) -> int:
88
+ return self.file_path.stat().st_size
89
+
90
+
91
+ def list_files_command(
92
+ divbase_base_url: str,
93
+ project_name: str,
94
+ prefix: str | None = None,
95
+ include_results_files: bool = False,
96
+ file_system_view: bool = True,
97
+ ) -> tuple[list[ObjectDetails], list[str]]:
98
+ """
99
+ List files and (optionally) folders in a project.
100
+
101
+ file_system_view = true will return both files and folders at the current prefix level, simulating a file system view.
102
+ Otherwise all files are returned in a flat list
103
+ """
104
+ if file_system_view:
105
+ delimiter = "/"
106
+ else:
107
+ delimiter = None
108
+
109
+ api_route = f"v1/s3/list?project_name={project_name}"
110
+ initial_request = ListObjectsRequest(prefix=prefix, delimiter=delimiter, next_token=None)
111
+
112
+ response = make_authenticated_request(
113
+ method="POST",
114
+ divbase_base_url=divbase_base_url,
115
+ api_route=api_route,
116
+ json=initial_request.model_dump(),
117
+ )
118
+ response_data = ListObjectsResponse(**response.json())
119
+ folders, files = list(response_data.folders), list(response_data.files)
120
+
121
+ while response_data.next_token:
122
+ next_request = ListObjectsRequest(prefix=prefix, delimiter=delimiter, next_token=response_data.next_token)
123
+ response = make_authenticated_request(
124
+ method="POST",
125
+ divbase_base_url=divbase_base_url,
126
+ api_route=api_route,
127
+ json=next_request.model_dump(),
128
+ )
129
+ response_data = ListObjectsResponse(**response.json())
130
+ folders.extend(response_data.folders)
131
+ files.extend(response_data.files)
132
+
133
+ # Hide DivBase query results files unless explicitly requested.
134
+ # we do this here instead of in the api query so we can use the prefix filter to filter on other things
135
+ if not include_results_files:
136
+ files = [obj for obj in files if not obj.name.startswith(QUERY_RESULTS_FILE_PREFIX)]
137
+
138
+ return files, folders
139
+
140
+
141
+ def list_soft_deleted_files_command(
142
+ divbase_base_url: str, project_name: str, prefix: str | None = None
143
+ ) -> list[SoftDeletedObjectDetails]:
144
+ """List all soft-deleted files in a project, with optional prefix filtering."""
145
+ api_route = f"v1/s3/list/soft-deleted?project_name={project_name}"
146
+
147
+ response = make_authenticated_request(
148
+ method="POST",
149
+ divbase_base_url=divbase_base_url,
150
+ api_route=api_route,
151
+ json=ListDeletedObjectsRequest(prefix=prefix).model_dump(),
152
+ )
153
+ return [SoftDeletedObjectDetails(**obj) for obj in response.json()]
154
+
155
+
156
+ def get_file_info_command(divbase_base_url: str, project_name: str, object_name: str) -> ObjectInfoResponse:
157
+ """Get detailed information about a specific file/object in a project."""
158
+ response = make_authenticated_request(
159
+ method="GET",
160
+ divbase_base_url=divbase_base_url,
161
+ api_route=f"v1/s3/info?project_name={project_name}&object_name={object_name}",
162
+ )
163
+ return ObjectInfoResponse(**response.json())
164
+
165
+
166
+ def make_directories_command(
167
+ divbase_base_url: str, project_name: str, directories: list[str]
168
+ ) -> MakeDirectoriesResponse:
169
+ """
170
+ Create directories in the project's store.
171
+ Pagination not supported here, so up to MAX_S3_API_BATCH_SIZE directories can be created at once.
172
+ """
173
+ cleaned_directories = MakeDirectoriesRequest(directories=directories)
174
+ response = make_authenticated_request(
175
+ method="POST",
176
+ divbase_base_url=divbase_base_url,
177
+ api_route=f"v1/s3/mkdir?project_name={project_name}",
178
+ json=cleaned_directories.model_dump(),
179
+ )
180
+ return MakeDirectoriesResponse(**response.json())
181
+
182
+
183
+ def soft_delete_objects_command(divbase_base_url: str, project_name: str, all_files: list[str]) -> list[str]:
184
+ """
185
+ Soft delete objects from the project's bucket.
186
+ Returns a list of the soft deleted objects
187
+ """
188
+ deleted_objects = []
189
+ for i in range(0, len(all_files), MAX_S3_API_BATCH_SIZE):
190
+ batch_files = all_files[i : i + MAX_S3_API_BATCH_SIZE]
191
+ response = make_authenticated_request(
192
+ method="DELETE",
193
+ divbase_base_url=divbase_base_url,
194
+ api_route=f"v1/s3/?project_name={project_name}",
195
+ json=batch_files,
196
+ )
197
+ deleted_objects.extend(response.json())
198
+ return deleted_objects
199
+
200
+
201
+ def restore_objects_command(divbase_base_url: str, project_name: str, all_files: list[str]) -> RestoreObjectsResponse:
202
+ """
203
+ Restore soft_deleted objects in the project's bucket.
204
+ Returns an object containing a list of the restored objects, and those that were not restored.
205
+ """
206
+ all_restored = []
207
+ all_not_restored = []
208
+ for i in range(0, len(all_files), MAX_S3_API_BATCH_SIZE):
209
+ batch_files = all_files[i : i + MAX_S3_API_BATCH_SIZE]
210
+ response = make_authenticated_request(
211
+ method="POST",
212
+ divbase_base_url=divbase_base_url,
213
+ api_route=f"v1/s3/restore?project_name={project_name}",
214
+ json=batch_files,
215
+ )
216
+ batch_response = RestoreObjectsResponse(**response.json())
217
+ all_restored.extend(batch_response.restored)
218
+ all_not_restored.extend(batch_response.not_restored)
219
+
220
+ return RestoreObjectsResponse(restored=all_restored, not_restored=all_not_restored)
221
+
222
+
223
+ def download_files_command(
224
+ divbase_base_url: str,
225
+ project_name: str,
226
+ raw_files_input: list[str],
227
+ download_dir: Path,
228
+ flatten: bool,
229
+ verify_checksums: bool,
230
+ dry_run: bool,
231
+ project_version: str | None = None,
232
+ ) -> DownloadOutcome:
233
+ """
234
+ Download files from the given project's S3 bucket.
235
+ """
236
+ if not download_dir.is_dir():
237
+ raise NotADirectoryError(
238
+ f"The specified download directory '{download_dir}' is not a directory. Please create it or specify a valid directory before continuing."
239
+ )
240
+
241
+ if project_version:
242
+ offending_files = [file for file in raw_files_input if ":" in file]
243
+ if offending_files:
244
+ raise InvalidInputError(
245
+ "If you provide a global project version (using --project-version) "
246
+ "you cannot also specify specific versions of individual files to download.\n"
247
+ "Offending files in your input:\n"
248
+ f"{'\n'.join(offending_files)}"
249
+ )
250
+
251
+ project_version_details = get_version_details_command(
252
+ project_name=project_name, divbase_base_url=divbase_base_url, version_name=project_version
253
+ )
254
+
255
+ # check if all files specified exist for download exist at this project version
256
+ missing_objects = [f for f in raw_files_input if f not in project_version_details.files]
257
+ if missing_objects:
258
+ raise FileDoesNotExistInSpecifiedVersionError(
259
+ project_name=project_name,
260
+ project_version=project_version,
261
+ missing_files=missing_objects,
262
+ )
263
+
264
+ json_data = []
265
+ for file_name, file_details in project_version_details.files.items():
266
+ if file_name in raw_files_input:
267
+ json_data.append({"name": file_name, "version_id": file_details["version_id"]})
268
+ else:
269
+ # parse raw file inputs to see if any specific version ids were provided using format:
270
+ # file_name:version_id (not possible when using project_version)
271
+ json_data: list[dict[str, str | None]] = []
272
+ for file_input in raw_files_input:
273
+ if ":" in file_input:
274
+ name, version_id = file_input.split(sep=":", maxsplit=1)
275
+ json_data.append({"name": name, "version_id": version_id})
276
+ else:
277
+ json_data.append({"name": file_input, "version_id": None})
278
+
279
+ if dry_run:
280
+ print("\n[green bold]Dry run enabled, The following files would have been downloaded:[/green bold]")
281
+ for file_info in json_data:
282
+ version_id = file_info["version_id"]
283
+ if version_id:
284
+ print(f"- '{file_info['name']}' (version_id: '{version_id}')")
285
+ else:
286
+ print(f"- '{file_info['name']}' (latest version)")
287
+ raise typer.Exit(0)
288
+
289
+ successful_downloads, failed_downloads = [], []
290
+ for i in range(0, len(json_data), MAX_S3_API_BATCH_SIZE):
291
+ batch_json_data = json_data[i : i + MAX_S3_API_BATCH_SIZE]
292
+ response = make_authenticated_request(
293
+ method="POST",
294
+ divbase_base_url=divbase_base_url,
295
+ api_route=f"v1/s3/download?project_name={project_name}",
296
+ json=batch_json_data,
297
+ )
298
+ pre_signed_urls = [PreSignedDownloadResponse(**item) for item in response.json()]
299
+
300
+ batch_download_success, batch_download_failed = download_multiple_pre_signed_urls(
301
+ pre_signed_urls=pre_signed_urls,
302
+ download_dir=download_dir,
303
+ flatten=flatten,
304
+ verify_checksums=verify_checksums,
305
+ )
306
+ successful_downloads.extend(batch_download_success)
307
+ failed_downloads.extend(batch_download_failed)
308
+
309
+ return DownloadOutcome(successful=successful_downloads, failed=failed_downloads)
310
+
311
+
312
+ def stream_file_command(
313
+ divbase_base_url: str, project_name: str, file_name: str, version_id: str | None = None
314
+ ) -> None:
315
+ """Stream the contents of a single file in the project's S3 bucket to stdout."""
316
+ json_data = [{"name": file_name, "version_id": version_id}]
317
+ response = make_authenticated_request(
318
+ method="POST",
319
+ divbase_base_url=divbase_base_url,
320
+ api_route=f"v1/s3/download?project_name={project_name}",
321
+ json=json_data,
322
+ )
323
+ pre_signed_url = PreSignedDownloadResponse(**response.json()[0]).pre_signed_url
324
+
325
+ try:
326
+ with httpx.stream("GET", pre_signed_url, timeout=None) as response:
327
+ if response.status_code == 404:
328
+ raise FileNotFoundInProjectError(project_name=project_name, file_name=file_name, version_id=version_id)
329
+ response.raise_for_status()
330
+
331
+ for chunk in response.iter_bytes():
332
+ sys.stdout.buffer.write(chunk)
333
+ except BrokenPipeError:
334
+ # This happens when the user pipes to a command that closes early
335
+ # (e.g., `[divbase-cli stream command] | head -n 10`).
336
+ pass
337
+
338
+
339
+ def upload_files_command(
340
+ project_name: str,
341
+ divbase_base_url: str,
342
+ all_files: list[ToUpload],
343
+ safe_mode: bool,
344
+ skip_existing: bool = False,
345
+ dry_run: bool = False,
346
+ ) -> UploadOutcome:
347
+ """
348
+ Upload files to the project's S3 bucket.
349
+ Returns an UploadOutcome object containing details about how uploading went for each file.
350
+
351
+ - Safe mode:
352
+ 1. checks if any of the files that are to be uploaded already exist in the bucket (by comparing checksums)
353
+ 2. Adds checksum to upload request to allow server to verify upload.
354
+ """
355
+ all_successful_uploads: list[SuccessfulUpload] = []
356
+ all_failed_uploads: list[FailedUpload] = []
357
+ all_skipped_uploads: list[SkippedUpload] = []
358
+
359
+ if safe_mode:
360
+ if dry_run:
361
+ print(
362
+ "[green]Dry run enabled, calculating the checksums of all files to upload to determine which would be uploaded vs skipped...[/green]"
363
+ )
364
+ else:
365
+ print("[green]Preparing to upload files, calculating the checksums of all files to upload...[/green]")
366
+
367
+ to_upload, already_uploaded = filter_already_uploaded_files(
368
+ project_name=project_name,
369
+ divbase_base_url=divbase_base_url,
370
+ all_files=all_files,
371
+ )
372
+
373
+ if already_uploaded:
374
+ # skip_existing means we just skip uploading those files that are already there
375
+ if not skip_existing:
376
+ files_str = "\n".join(f"'{f.file_path}' (Checksum: '{f.checksum_local}')" for f in already_uploaded)
377
+ message = (
378
+ f"For the project: '{project_name}'\n"
379
+ "The exact version of the following files that you're trying to upload already exist inside the project:\n"
380
+ f"{files_str}\n\n"
381
+ "[bold green]Tip: if you want to skip re-uploading these files and continue uploading the other files, "
382
+ "re-run this command with the '--skip-existing' flag.[/bold green]"
383
+ )
384
+ if dry_run:
385
+ message = "The following upload attempt would have failed due to the below error:\n" + message
386
+ raise FileAlreadyUploadedError(message)
387
+ else:
388
+ for file in already_uploaded:
389
+ all_skipped_uploads.append(
390
+ SkippedUpload(
391
+ object_name=file.destination_key,
392
+ file_path=file.file_path,
393
+ reason=f"The file with checksum {file.checksum_local} already exists in the project",
394
+ )
395
+ )
396
+ else:
397
+ # we don't provide checksums to server
398
+ to_upload = all_files
399
+
400
+ if dry_run:
401
+ if to_upload:
402
+ print("\n[green bold]The following files would have been uploaded:[/green bold]")
403
+ for file in to_upload:
404
+ print(f"- '{file.file_path}' -> would be stored as: '{file.destination_key}' in the project")
405
+ if all_skipped_uploads:
406
+ print("\n[yellow bold]The following files would have been skipped from upload:[/yellow bold]")
407
+ for file in all_skipped_uploads:
408
+ print(f"- [yellow]'{file.file_path}' Reason: {file.reason}[/yellow]")
409
+
410
+ raise typer.Exit(0)
411
+
412
+ # Split files into those that need single vs multipart upload
413
+ files_below_threshold: list[ToUpload] = []
414
+ files_above_threshold: list[ToUpload] = []
415
+ for file in to_upload:
416
+ if file.file_size <= S3_MULTIPART_UPLOAD_THRESHOLD:
417
+ files_below_threshold.append(file)
418
+ else:
419
+ files_above_threshold.append(file)
420
+
421
+ # P1. Process all single-part uploads in batches of max size allowed by divbase server.
422
+ for i in range(0, len(files_below_threshold), MAX_S3_API_BATCH_SIZE):
423
+ batch_files = files_below_threshold[i : i + MAX_S3_API_BATCH_SIZE]
424
+ batch_of_objects_to_upload = []
425
+ for file in batch_files:
426
+ upload_object = {
427
+ "name": file.destination_key,
428
+ "content_length": file.file_size,
429
+ }
430
+ if safe_mode and file.checksum_local:
431
+ # server expects base64 encoded checksum when provided
432
+ upload_object["md5_hash"] = convert_checksum_hex_to_base64(hex_checksum=file.checksum_local)
433
+ batch_of_objects_to_upload.append(upload_object)
434
+
435
+ response = make_authenticated_request(
436
+ method="POST",
437
+ divbase_base_url=divbase_base_url,
438
+ api_route=f"v1/s3/upload/single-part?project_name={project_name}",
439
+ json=batch_of_objects_to_upload,
440
+ )
441
+ pre_signed_urls = [PreSignedSinglePartUploadResponse(**item) for item in response.json()]
442
+ dest_key_to_path = {f.destination_key: f.file_path for f in batch_files}
443
+
444
+ successful_uploads, failed_uploads = upload_multiple_singlepart_pre_signed_urls(
445
+ pre_signed_urls=pre_signed_urls, dest_key_to_path=dest_key_to_path
446
+ )
447
+ all_successful_uploads.extend(successful_uploads)
448
+ all_failed_uploads.extend(failed_uploads)
449
+
450
+ # P2. process all multipart uploads.
451
+ for file in files_above_threshold:
452
+ outcome = perform_multipart_upload(
453
+ project_name=project_name,
454
+ divbase_base_url=divbase_base_url,
455
+ file_path=file.file_path,
456
+ safe_mode=safe_mode,
457
+ destination_name=file.destination_key,
458
+ )
459
+
460
+ if isinstance(outcome, SuccessfulUpload):
461
+ all_successful_uploads.append(outcome)
462
+ else:
463
+ all_failed_uploads.append(outcome)
464
+
465
+ return UploadOutcome(successful=all_successful_uploads, failed=all_failed_uploads, skipped=all_skipped_uploads)
466
+
467
+
468
+ def filter_already_uploaded_files(
469
+ project_name: str,
470
+ divbase_base_url: str,
471
+ all_files: list[ToUpload],
472
+ ) -> tuple[list[ToUpload], list[ToUpload]]:
473
+ """
474
+ Separate files into whether they are already in the projects bucket or not.
475
+ (1st list to be uploaded, 2nd list is files already in projects bucket)
476
+
477
+ For a file to be considered already in the project,
478
+ there must be an object with the same key and checksum in the project's S3 bucket.
479
+
480
+ This is only ran if 'safe_mode' is enabled for uploads.
481
+ These checksums are later used when uploading to the server so the server can verify the upload.
482
+ """
483
+ already_uploaded: list[ToUpload] = []
484
+ to_be_uploaded: list[ToUpload] = []
485
+
486
+ # have to batch requests if above max number allowed by divbase server
487
+ for i in range(0, len(all_files), MAX_S3_API_BATCH_SIZE):
488
+ batch_files = all_files[i : i + MAX_S3_API_BATCH_SIZE]
489
+ batch_object_keys = [file.destination_key for file in batch_files]
490
+
491
+ response = make_authenticated_request(
492
+ method="POST",
493
+ divbase_base_url=divbase_base_url,
494
+ api_route=f"v1/s3/checksums?project_name={project_name}",
495
+ json=batch_object_keys,
496
+ )
497
+ server_checksum_responses = [FileChecksumResponse(**item) for item in response.json()]
498
+ server_checksums = {item.object_name: item.md5_checksum for item in server_checksum_responses}
499
+
500
+ for file in batch_files:
501
+ local_checksum = _calc_local_checksum(file_path=file.file_path)
502
+ file_to_upload = ToUpload(
503
+ file_path=file.file_path, destination_key=file.destination_key, checksum_local=local_checksum
504
+ )
505
+
506
+ if server_checksums.get(file.destination_key) and server_checksums[file.destination_key] == local_checksum:
507
+ already_uploaded.append(file_to_upload)
508
+ else:
509
+ to_be_uploaded.append(file_to_upload)
510
+
511
+ print(f"MD5 Checksum calculated for file: '{file.file_path}'")
512
+
513
+ return to_be_uploaded, already_uploaded
514
+
515
+
516
+ def filter_out_already_downloaded_files(
517
+ all_files: list[ToDownload], download_dir: Path, flatten: bool = False
518
+ ) -> tuple[list[ToDownload], list[ToDownload]]:
519
+ """
520
+ Filter out files that already exist in a local directory with the same checksum.
521
+
522
+ Returns two lists:
523
+ 1. Files that do not exist locally and need to be downloaded.
524
+ 2. Files that are not identical to the file in S3 and will be overwritten if the user wants to download them.
525
+ """
526
+ files_to_download, files_to_overwrite = [], []
527
+
528
+ for s3_file in all_files:
529
+ local_name = Path(s3_file.s3_key).name if flatten else s3_file.s3_key
530
+ local_file_path = download_dir / local_name
531
+
532
+ if not local_file_path.exists():
533
+ files_to_download.append(s3_file)
534
+ continue
535
+
536
+ local_checksum = _calc_local_checksum(file_path=local_file_path)
537
+ if local_checksum != s3_file.etag:
538
+ files_to_overwrite.append(s3_file)
539
+
540
+ return files_to_download, files_to_overwrite
541
+
542
+
543
+ def _calc_local_checksum(file_path: Path) -> str:
544
+ """
545
+ Calculate the checksum for a local file. Handles whether to use a single or composite checksum based on file size.
546
+
547
+ This is used to validate the integrity of a file before upload.
548
+ Or determine if a file can be skipped from downloading.
549
+ """
550
+ if file_path.stat().st_size > S3_MULTIPART_UPLOAD_THRESHOLD:
551
+ return calculate_composite_md5_s3_etag(file_path=file_path)
552
+ else:
553
+ return calculate_md5_checksum(file_path=file_path, output_format=MD5CheckSumFormat.HEX)