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,500 @@
1
+ """
2
+ Module responsible for taking pre-signed urls and using them to do file download and upload.
3
+
4
+ Grouped into 4 sections:
5
+ - Downloading singlepart files
6
+ - Downloading multipart files (based on size threshold)
7
+ - Uploading singlepart files
8
+ - Uploading multipart files (based on size threshold)
9
+
10
+ Size thresholds are defined in divbase_lib.divbase_constants and which function to call is determined by the caller.
11
+
12
+ Retry logic here uses the stamina library.
13
+
14
+ For files uploaded/downloaded in parts/chunks, we print a dot for each part to show progress for the user.
15
+ """
16
+
17
+ import io
18
+ import logging
19
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ import httpx
24
+ import stamina
25
+ from rich import print
26
+
27
+ from divbase_cli.cli_exceptions import DivBaseAPIConnectionError, DivBaseAPIError
28
+ from divbase_cli.retries import retry_only_on_retryable_http_errors
29
+ from divbase_cli.user_auth import make_authenticated_request
30
+ from divbase_lib.api_schemas.s3 import (
31
+ AbortMultipartUploadRequest,
32
+ CompleteMultipartUploadRequest,
33
+ CompleteMultipartUploadResponse,
34
+ CreateMultipartUploadRequest,
35
+ CreateMultipartUploadResponse,
36
+ GetPresignedPartUrlsRequest,
37
+ PreSignedDownloadResponse,
38
+ PreSignedSinglePartUploadResponse,
39
+ PresignedUploadPartUrlResponse,
40
+ UploadedPart,
41
+ )
42
+ from divbase_lib.divbase_constants import (
43
+ MAX_S3_API_BATCH_SIZE,
44
+ S3_MULTIPART_CHUNK_SIZE,
45
+ )
46
+ from divbase_lib.exceptions import ChecksumVerificationError
47
+ from divbase_lib.s3_checksums import calculate_md5_checksum_for_chunk, verify_downloaded_checksum
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ # Used for multipart file transfers
52
+ MAX_CONCURRENCY = 10
53
+
54
+ MB = 1024 * 1024
55
+ # We can download in whatever chunk size we want,
56
+ # the checksum validation has to use the right chunk size though
57
+ # Uploads should use the same threshold and chunk size as divbase-api
58
+ # So those are defined in a shared lib.
59
+ MULTIPART_DOWNLOAD_THRESHOLD = 32 * MB
60
+ DOWNLOAD_CHUNK_SIZE = 8 * MB
61
+
62
+
63
+ @dataclass
64
+ class SuccessfulDownload:
65
+ """Represents a successfully downloaded file."""
66
+
67
+ file_path: Path
68
+ object_name: str
69
+
70
+
71
+ @dataclass
72
+ class FailedDownload:
73
+ """Represents a failed download attempt."""
74
+
75
+ object_name: str
76
+ file_path: Path
77
+ exception: Exception
78
+
79
+
80
+ @dataclass
81
+ class DownloadOutcome:
82
+ """Outcome of attempting to download multiple files."""
83
+
84
+ successful: list[SuccessfulDownload]
85
+ failed: list[FailedDownload]
86
+
87
+
88
+ def download_multiple_pre_signed_urls(
89
+ pre_signed_urls: list[PreSignedDownloadResponse], verify_checksums: bool, download_dir: Path, flatten: bool = False
90
+ ) -> tuple[list[SuccessfulDownload], list[FailedDownload]]:
91
+ """
92
+ Download files using pre-signed URLs.
93
+ Returns a tuple of both the successful and failed downloads.
94
+ """
95
+ successful_downloads, failed_downloads = [], []
96
+ with httpx.Client() as client:
97
+ for obj in pre_signed_urls:
98
+ if flatten:
99
+ # If flatten, we only use the file name and ignore any s3 "folder" structure
100
+ output_file_path = download_dir / Path(obj.name).name
101
+ else:
102
+ output_file_path = download_dir / obj.name
103
+ object_name = obj.name
104
+
105
+ print(f"Downloading '{object_name}'...", end=" ")
106
+ try:
107
+ result = _download_single_pre_signed_url(
108
+ httpx_client=client,
109
+ pre_signed_url=obj.pre_signed_url,
110
+ verify_checksums=verify_checksums,
111
+ output_file_path=output_file_path,
112
+ object_name=object_name,
113
+ )
114
+ print("[bold green]Success[/bold green]")
115
+ except httpx.HTTPError as err:
116
+ logger.info(f"Failed to download object '{object_name}' from pre-signed URL., Error: {err}")
117
+ output_file_path.unlink(missing_ok=True) # Clean up possible partial file
118
+ result = FailedDownload(object_name=object_name, file_path=output_file_path, exception=err)
119
+ print("[bold red]Failed[/bold red]")
120
+
121
+ if isinstance(result, SuccessfulDownload):
122
+ successful_downloads.append(result)
123
+ else:
124
+ failed_downloads.append(result)
125
+
126
+ return successful_downloads, failed_downloads
127
+
128
+
129
+ def _download_single_pre_signed_url(
130
+ httpx_client: httpx.Client, pre_signed_url: str, verify_checksums: bool, output_file_path: Path, object_name: str
131
+ ) -> SuccessfulDownload | FailedDownload:
132
+ """
133
+ Download a single file using a pre-signed URL.
134
+ If the file is large enough, we download in chunks.
135
+ Helper function, do not call directly from outside this module.
136
+ """
137
+ content_length, server_checksum = _get_content_length_and_checksum(
138
+ httpx_client=httpx_client, pre_signed_url=pre_signed_url
139
+ )
140
+ output_file_path.parent.mkdir(parents=True, exist_ok=True)
141
+ if content_length < MULTIPART_DOWNLOAD_THRESHOLD:
142
+ _perform_singlepart_download(
143
+ httpx_client=httpx_client,
144
+ pre_signed_url=pre_signed_url,
145
+ output_file_path=output_file_path,
146
+ )
147
+
148
+ else:
149
+ logger.info(f"Starting multipart download for large file '{object_name}' of size {content_length} bytes.")
150
+ _perform_multipart_download(
151
+ httpx_client=httpx_client,
152
+ pre_signed_url=pre_signed_url,
153
+ output_file_path=output_file_path,
154
+ content_length=content_length,
155
+ )
156
+
157
+ if verify_checksums:
158
+ try:
159
+ verify_downloaded_checksum(file_path=output_file_path, expected_checksum=server_checksum)
160
+ except ChecksumVerificationError as err:
161
+ output_file_path.unlink()
162
+ return FailedDownload(object_name=object_name, file_path=output_file_path, exception=err)
163
+
164
+ return SuccessfulDownload(file_path=output_file_path, object_name=object_name)
165
+
166
+
167
+ @stamina.retry(on=retry_only_on_retryable_http_errors, attempts=3)
168
+ def _get_content_length_and_checksum(httpx_client: httpx.Client, pre_signed_url: str) -> tuple[int, str]:
169
+ """
170
+ "HEAD" a pre-signed download URL to get it's content length and checksum.
171
+
172
+ As you can't HEAD a presigned GET, we do a GET with a Range header to only get the first byte.
173
+ Otherwise would have to be given a separate pre-signed HEAD url to do this.
174
+ """
175
+ with httpx_client.stream("GET", pre_signed_url, headers={"Range": "bytes=0-0"}) as head_response:
176
+ head_response.raise_for_status()
177
+ content_range = head_response.headers["Content-Range"]
178
+ # format is "bytes 0-0/12345"
179
+ content_length = int(content_range.split("/")[-1])
180
+ server_checksum = head_response.headers["ETag"].strip('"')
181
+ return content_length, server_checksum
182
+
183
+
184
+ @stamina.retry(on=retry_only_on_retryable_http_errors, attempts=3)
185
+ def _perform_singlepart_download(httpx_client: httpx.Client, pre_signed_url: str, output_file_path: Path) -> None:
186
+ """Used on objects smaller than the multipart threshold cutoff"""
187
+ with httpx_client.stream("GET", pre_signed_url) as response:
188
+ response.raise_for_status()
189
+
190
+ with open(output_file_path, "wb") as file:
191
+ for chunk in response.iter_bytes(chunk_size=8192):
192
+ file.write(chunk)
193
+
194
+
195
+ def _perform_multipart_download(
196
+ httpx_client: httpx.Client, pre_signed_url: str, output_file_path: Path, content_length: int
197
+ ) -> None:
198
+ """
199
+ Download a large file in multiple chunks using range requests.
200
+
201
+ As we write to the file concurrently, the file is first created with the correct size,
202
+ and then each chunk is written to the correct position in the file.
203
+ """
204
+ with open(output_file_path, "wb") as f:
205
+ f.seek(content_length - 1)
206
+ f.write(b"\0")
207
+ with ThreadPoolExecutor(max_workers=MAX_CONCURRENCY) as executor:
208
+ futures = []
209
+ for i in range(0, content_length, DOWNLOAD_CHUNK_SIZE):
210
+ start = i
211
+ end = min(i + DOWNLOAD_CHUNK_SIZE, content_length)
212
+ futures.append(
213
+ executor.submit(
214
+ _download_chunk,
215
+ client=httpx_client,
216
+ url=pre_signed_url,
217
+ start=start,
218
+ end=end,
219
+ output_file_path=output_file_path,
220
+ )
221
+ )
222
+
223
+ for future in futures:
224
+ future.result()
225
+
226
+
227
+ @stamina.retry(on=retry_only_on_retryable_http_errors, attempts=3)
228
+ def _download_chunk(client: httpx.Client, url: str, start: int, end: int, output_file_path: Path) -> None:
229
+ """
230
+ Downloads a specific range of bytes of a file (aka chunk),
231
+ and writes it to the correct place in the file.
232
+ """
233
+ headers = {"Range": f"bytes={start}-{end - 1}"}
234
+ with client.stream("GET", url, headers=headers) as response:
235
+ response.raise_for_status()
236
+ with open(output_file_path, "rb+") as f:
237
+ f.seek(start)
238
+ for chunk in response.iter_bytes():
239
+ f.write(chunk)
240
+ print(".", end="") # Print a dot for each completed chunk to show progress
241
+
242
+
243
+ @dataclass
244
+ class SuccessfulUpload:
245
+ """Represents a successfully uploaded file."""
246
+
247
+ file_path: Path
248
+ object_name: str
249
+
250
+
251
+ @dataclass
252
+ class FailedUpload:
253
+ """Represents a failed upload attempt."""
254
+
255
+ object_name: str
256
+ file_path: Path
257
+ exception: Exception
258
+
259
+
260
+ @dataclass
261
+ class SkippedUpload:
262
+ """Represents a skipped upload attempt."""
263
+
264
+ object_name: str
265
+ file_path: Path
266
+ reason: str
267
+
268
+
269
+ @dataclass
270
+ class UploadOutcome:
271
+ """Outcome of attempting to upload multiple files."""
272
+
273
+ successful: list[SuccessfulUpload]
274
+ failed: list[FailedUpload]
275
+ skipped: list[SkippedUpload]
276
+
277
+
278
+ def upload_multiple_singlepart_pre_signed_urls(
279
+ pre_signed_urls: list[PreSignedSinglePartUploadResponse],
280
+ dest_key_to_path: dict[str, Path],
281
+ ) -> tuple[list[SuccessfulUpload], list[FailedUpload]]:
282
+ """
283
+ Upload singlepart files using pre-signed PUT URLs.
284
+ Returns a tuple of both the successful and failed uploads.
285
+
286
+ dest_key_to_path maps each object's destination key (aka name in bucket) to its location in the local file path.
287
+ """
288
+ successful_uploads, failed_uploads = [], []
289
+ with httpx.Client() as client:
290
+ for obj in pre_signed_urls:
291
+ destination_key = obj.name
292
+ file_path = dest_key_to_path[destination_key]
293
+
294
+ if file_path.name != destination_key:
295
+ print(f"Uploading '{file_path}' to '{destination_key}'...", end=" ")
296
+ else:
297
+ print(f"Uploading '{file_path}'...", end=" ")
298
+
299
+ result = _upload_one_singlepart_pre_signed_url(
300
+ httpx_client=client,
301
+ pre_signed_url=obj.pre_signed_url,
302
+ file_path=file_path,
303
+ object_name=destination_key,
304
+ headers=obj.put_headers,
305
+ )
306
+
307
+ if isinstance(result, SuccessfulUpload):
308
+ print("[bold green]Success[/bold green]")
309
+ successful_uploads.append(result)
310
+ else:
311
+ print("[bold red]Failed[/bold red]")
312
+ failed_uploads.append(result)
313
+
314
+ return successful_uploads, failed_uploads
315
+
316
+
317
+ def _upload_one_singlepart_pre_signed_url(
318
+ httpx_client: httpx.Client,
319
+ pre_signed_url: str,
320
+ file_path: Path,
321
+ object_name: str,
322
+ headers: dict[str, str],
323
+ ) -> SuccessfulUpload | FailedUpload:
324
+ """Upload one singlepart file to S3 using a pre-signed PUT URL."""
325
+ try:
326
+ for attempt in stamina.retry_context(on=retry_only_on_retryable_http_errors, attempts=3):
327
+ with attempt, open(file_path, "rb") as file:
328
+ response = httpx_client.put(
329
+ pre_signed_url,
330
+ content=file,
331
+ headers=headers,
332
+ timeout=httpx.Timeout(connect=10.0, read=60.0, write=60.0, pool=None),
333
+ )
334
+ response.raise_for_status()
335
+ except httpx.HTTPError as err:
336
+ logger.info(f"Failed to upload object '{object_name}' via single part upload, Error: {err}")
337
+ return FailedUpload(object_name=object_name, file_path=file_path, exception=err)
338
+
339
+ return SuccessfulUpload(file_path=file_path, object_name=object_name)
340
+
341
+
342
+ ### multipart upload logic below ###
343
+
344
+
345
+ def perform_multipart_upload(
346
+ project_name: str,
347
+ divbase_base_url: str,
348
+ file_path: Path,
349
+ safe_mode: bool,
350
+ destination_name: str,
351
+ ) -> SuccessfulUpload | FailedUpload:
352
+ """
353
+ Manages the entire multi-part upload process for a single file.
354
+ See the docs docs/development/s3_transfers.md for high level overview of the process.
355
+ """
356
+ file_size = file_path.stat().st_size
357
+ if file_path.name != destination_name:
358
+ print(f"Uploading '{file_path.name}' to '{destination_name}'...", end=" ")
359
+ else:
360
+ print(f"Uploading '{file_path.name}'...", end=" ")
361
+
362
+ # 1. Create multipart upload
363
+ create_request = CreateMultipartUploadRequest(name=destination_name, content_length=file_size)
364
+ response = make_authenticated_request(
365
+ method="POST",
366
+ divbase_base_url=divbase_base_url,
367
+ api_route=f"v1/s3/upload/multi-part/create?project_name={project_name}",
368
+ json=create_request.model_dump(),
369
+ )
370
+ object_data = CreateMultipartUploadResponse(**response.json())
371
+
372
+ # 2. Upload each part in batches as divbase server limits how many part urls it will give at once
373
+ parts_to_request = list(range(1, object_data.number_of_parts + 1))
374
+ try:
375
+ uploaded_parts: list[UploadedPart] = []
376
+ for i in range(0, len(parts_to_request), MAX_S3_API_BATCH_SIZE):
377
+ part_batch_numbers = parts_to_request[i : i + MAX_S3_API_BATCH_SIZE]
378
+ part_urls = _get_part_urls(
379
+ project_name=project_name,
380
+ divbase_base_url=divbase_base_url,
381
+ object_name=destination_name,
382
+ upload_id=object_data.upload_id,
383
+ part_numbers=part_batch_numbers,
384
+ file_path=file_path,
385
+ safe_mode=safe_mode,
386
+ )
387
+ batch_uploads = _upload_parts(part_urls=part_urls, file_path=file_path)
388
+ uploaded_parts.extend(batch_uploads)
389
+
390
+ # 3. Complete multipart upload
391
+ # must be uploaded in part order otherwise InvalidPartOrder error from S3
392
+ uploaded_parts.sort(key=lambda part: part.part_number)
393
+ complete_request_body = CompleteMultipartUploadRequest(
394
+ name=destination_name,
395
+ upload_id=object_data.upload_id,
396
+ parts=uploaded_parts,
397
+ )
398
+ response = make_authenticated_request(
399
+ method="POST",
400
+ divbase_base_url=divbase_base_url,
401
+ api_route=f"v1/s3/upload/multi-part/complete?project_name={project_name}",
402
+ json=complete_request_body.model_dump(),
403
+ )
404
+ completed_upload = CompleteMultipartUploadResponse(**response.json())
405
+ print("[bold green]Success[/bold green]")
406
+ return SuccessfulUpload(file_path=file_path, object_name=completed_upload.name)
407
+
408
+ # 4. If any unexpected error occurs, abort the multipart upload
409
+ # To avoid leaving incomplete uploads in S3
410
+ except Exception as e:
411
+ try:
412
+ abort_request = AbortMultipartUploadRequest(name=destination_name, upload_id=object_data.upload_id)
413
+ make_authenticated_request(
414
+ method="DELETE",
415
+ divbase_base_url=divbase_base_url,
416
+ api_route=f"v1/s3/upload/multi-part/abort?project_name={project_name}",
417
+ json=abort_request.model_dump(),
418
+ )
419
+ except (DivBaseAPIConnectionError, DivBaseAPIError):
420
+ logger.warning(f"Failed to abort multipart upload for object '{destination_name}' after an upload error.")
421
+
422
+ print("[bold red]Failed[/bold red]")
423
+ return FailedUpload(object_name=destination_name, file_path=file_path, exception=e)
424
+
425
+
426
+ def _get_part_urls(
427
+ project_name: str,
428
+ divbase_base_url: str,
429
+ object_name: str,
430
+ upload_id: str,
431
+ part_numbers: list[int],
432
+ file_path: Path,
433
+ safe_mode: bool,
434
+ ) -> list[PresignedUploadPartUrlResponse]:
435
+ """
436
+ Gets up to 100 pre-signed URLs (from divbase server) for uploading parts of a large file to S3.
437
+
438
+ Not responsible for uploading the parts, just getting the URLs.
439
+ """
440
+ md5_checksums = None
441
+ if safe_mode:
442
+ md5_checksums = []
443
+ for part_num in part_numbers:
444
+ checksum = calculate_md5_checksum_for_chunk(
445
+ file_path=file_path,
446
+ start_byte=(part_num - 1) * S3_MULTIPART_CHUNK_SIZE,
447
+ chunk_size=S3_MULTIPART_CHUNK_SIZE,
448
+ )
449
+ md5_checksums.append(checksum)
450
+
451
+ request_body = GetPresignedPartUrlsRequest(
452
+ name=object_name,
453
+ upload_id=upload_id,
454
+ parts_range_start=part_numbers[0],
455
+ parts_range_end=part_numbers[-1],
456
+ md5_checksums=md5_checksums,
457
+ )
458
+ response = make_authenticated_request(
459
+ method="POST",
460
+ divbase_base_url=divbase_base_url,
461
+ api_route=f"v1/s3/upload/multi-part/part-urls?project_name={project_name}",
462
+ json=request_body.model_dump(),
463
+ )
464
+ return [PresignedUploadPartUrlResponse(**item) for item in response.json()]
465
+
466
+
467
+ def _upload_parts(part_urls: list[PresignedUploadPartUrlResponse], file_path: Path) -> list[UploadedPart]:
468
+ """Uploads a batch of parts in parallel and returns their ETag info."""
469
+ completed_parts = []
470
+ with ThreadPoolExecutor(max_workers=MAX_CONCURRENCY) as executor:
471
+ future_to_part = {executor.submit(_upload_chunk, part=part, file_path=file_path): part for part in part_urls}
472
+ for future in as_completed(future_to_part):
473
+ part_number, etag = future.result()
474
+ completed_parts.append(UploadedPart(part_number=part_number, etag=etag))
475
+ print(".", end="") # Print a dot for each completed part to show progress
476
+ return completed_parts
477
+
478
+
479
+ @stamina.retry(on=retry_only_on_retryable_http_errors, attempts=3)
480
+ def _upload_chunk(part: PresignedUploadPartUrlResponse, file_path: Path) -> tuple[int, str]:
481
+ """Uploads a single chunk of a file to a pre-signed URL and returns its part number and ETag."""
482
+
483
+ start_byte = (part.part_number - 1) * S3_MULTIPART_CHUNK_SIZE
484
+ with open(file_path, "rb") as f:
485
+ f.seek(start_byte)
486
+ data_to_upload = f.read(S3_MULTIPART_CHUNK_SIZE)
487
+
488
+ with httpx.Client() as client:
489
+ response = client.put(
490
+ part.pre_signed_url,
491
+ # By passing each part as a file-like object (wrap in io.BytesIO), httpx sends chunk in 64 KiB parts.
492
+ # Otherwise it sends the whole part (32 MiB) in one go (which can fail on slower connections even with a high write timeout).
493
+ content=io.BytesIO(data_to_upload),
494
+ headers=part.headers,
495
+ timeout=httpx.Timeout(connect=10.0, read=60.0, write=60.0, pool=None),
496
+ )
497
+ response.raise_for_status()
498
+ # ETag is returned with quotes, which must be stripped prior to comparison
499
+ etag = response.headers["ETag"].strip('"')
500
+ return part.part_number, etag
@@ -0,0 +1,103 @@
1
+ """
2
+ Service layer for DivBase CLI project version operations.
3
+ """
4
+
5
+ from divbase_cli.user_auth import make_authenticated_request
6
+ from divbase_lib.api_schemas.project_versions import (
7
+ AddVersionRequest,
8
+ AddVersionResponse,
9
+ DeleteVersionRequest,
10
+ DeleteVersionResponse,
11
+ ProjectVersionDetailResponse,
12
+ ProjectVersionInfo,
13
+ UpdateVersionRequest,
14
+ UpdateVersionResponse,
15
+ )
16
+
17
+
18
+ def add_version_command(project_name: str, divbase_base_url: str, name: str, description: str) -> AddVersionResponse:
19
+ """Add a new version to the project versions table stored on the divbase server"""
20
+ request_data = AddVersionRequest(name=name, description=description)
21
+
22
+ response = make_authenticated_request(
23
+ method="PATCH",
24
+ divbase_base_url=divbase_base_url,
25
+ api_route=f"v1/project-versions/add?project_name={project_name}",
26
+ json=request_data.model_dump(),
27
+ )
28
+
29
+ return AddVersionResponse(**response.json())
30
+
31
+
32
+ def list_versions_command(project_name: str, include_deleted: bool, divbase_base_url: str) -> list[ProjectVersionInfo]:
33
+ """
34
+ List all versions in the project versions table stored on the divbase server.
35
+ Returns a dict of version names (keys) to details about the versions.
36
+ """
37
+ response = make_authenticated_request(
38
+ method="GET",
39
+ divbase_base_url=divbase_base_url,
40
+ api_route=f"v1/project-versions/list?project_name={project_name}&include_deleted={str(include_deleted).lower()}",
41
+ )
42
+
43
+ project_versions = []
44
+ response_data = response.json()
45
+ for version in response_data:
46
+ project_versions.append(ProjectVersionInfo(**version))
47
+
48
+ return project_versions
49
+
50
+
51
+ def get_version_details_command(
52
+ project_name: str, divbase_base_url: str, version_name: str
53
+ ) -> ProjectVersionDetailResponse:
54
+ """Get details about a specific project version, including all files and their version IDs at that version."""
55
+ response = make_authenticated_request(
56
+ method="GET",
57
+ divbase_base_url=divbase_base_url,
58
+ api_route=f"v1/project-versions/version_details?project_name={project_name}&version_name={version_name}",
59
+ )
60
+
61
+ return ProjectVersionDetailResponse(**response.json())
62
+
63
+
64
+ def update_version_command(
65
+ project_name: str,
66
+ divbase_base_url: str,
67
+ version_name: str,
68
+ new_name: str | None,
69
+ new_description: str | None,
70
+ ) -> UpdateVersionResponse:
71
+ """Update the name and/or description of an existing project version entry."""
72
+ request_data = UpdateVersionRequest(
73
+ version_name=version_name,
74
+ new_name=new_name,
75
+ new_description=new_description,
76
+ )
77
+
78
+ response = make_authenticated_request(
79
+ method="PATCH",
80
+ divbase_base_url=divbase_base_url,
81
+ api_route=f"v1/project-versions/update?project_name={project_name}",
82
+ json=request_data.model_dump(),
83
+ )
84
+
85
+ return UpdateVersionResponse(**response.json())
86
+
87
+
88
+ def delete_version_command(project_name: str, divbase_base_url: str, version_name: str) -> DeleteVersionResponse:
89
+ """
90
+ Delete a version from the project versions table stored on the divbase server.
91
+ This marks the version as (soft) deleted server side,
92
+ and it will eventually be permanently deleted (after some grace period).
93
+ """
94
+ request_data = DeleteVersionRequest(version_name=version_name)
95
+
96
+ response = make_authenticated_request(
97
+ method="DELETE",
98
+ divbase_base_url=divbase_base_url,
99
+ api_route=f"v1/project-versions/delete?project_name={project_name}",
100
+ json=request_data.model_dump(),
101
+ )
102
+
103
+ return DeleteVersionResponse(**response.json())