divbase-lib 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,120 @@
1
+ """
2
+ Manages creation/validation of S3 object checksums for both file uploads and downloads.
3
+
4
+ We do not support multipart uploads/downloads at this time.
5
+ Single part uploads/downloads have a limit of 5GBs.
6
+ Docs: https://docs.netapp.com/us-en/storagegrid/s3/put-object.html
7
+ """
8
+
9
+ import base64
10
+ import hashlib
11
+ import logging
12
+ from enum import StrEnum
13
+ from pathlib import Path
14
+ from typing import Iterator
15
+
16
+ from divbase_lib.divbase_constants import S3_MULTIPART_CHUNK_SIZE
17
+ from divbase_lib.exceptions import ChecksumVerificationError
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class MD5CheckSumFormat(StrEnum):
23
+ HEX = "hex"
24
+ BASE64 = "base64"
25
+
26
+
27
+ def verify_downloaded_checksum(
28
+ file_path: Path,
29
+ expected_checksum: str,
30
+ ) -> None:
31
+ """
32
+ Verify a downloaded file against its S3's ETag.
33
+
34
+ For files uploaded as single part, this is just the MD5 checksum in hex format.
35
+ For files uploaded as multipart, this is a composite checksum of all the parts
36
+ """
37
+ if "-" in expected_checksum:
38
+ calculated_checksum = calculate_composite_md5_s3_etag(file_path)
39
+ else:
40
+ calculated_checksum = calculate_md5_checksum(file_path=file_path, output_format=MD5CheckSumFormat.HEX)
41
+
42
+ if calculated_checksum != expected_checksum:
43
+ raise ChecksumVerificationError(expected_checksum=expected_checksum, calculated_checksum=calculated_checksum)
44
+
45
+
46
+ def _read_file_chunks(file_path: Path, chunk_size: int) -> Iterator[bytes]:
47
+ """Helper function to read a file in 'chunk_size' sized chunks."""
48
+
49
+ with file_path.open(mode="rb") as infile:
50
+ yield from iter(lambda: infile.read(chunk_size), b"")
51
+
52
+
53
+ def calculate_md5_checksum(
54
+ file_path: Path, output_format: MD5CheckSumFormat, chunk_size: int = S3_MULTIPART_CHUNK_SIZE
55
+ ) -> str:
56
+ """
57
+ Calculate the MD5 checksum of a file.
58
+ Returns the checksum in either hex-encoded (lowercase) or base64-encoded format.
59
+
60
+ Used for:
61
+ - BASE64: The "Content-MD5" header used in uploads to S3.
62
+ - HEX: Verifying downloaded files against S3's ETag for the file.
63
+
64
+ (only works for files which will be uploaded as single part - not composite/multipart uploads)
65
+ """
66
+ md5_hash = hashlib.md5()
67
+
68
+ for chunk in _read_file_chunks(file_path=file_path, chunk_size=chunk_size):
69
+ md5_hash.update(chunk)
70
+
71
+ if output_format == MD5CheckSumFormat.HEX:
72
+ return md5_hash.hexdigest()
73
+ elif output_format == MD5CheckSumFormat.BASE64:
74
+ return base64.b64encode(md5_hash.digest()).decode("utf-8")
75
+ else:
76
+ raise ValueError(f"Unknown output format: {output_format}")
77
+
78
+
79
+ def calculate_md5_checksum_for_chunk(file_path: Path, start_byte: int, chunk_size: int) -> str:
80
+ """
81
+ Calculate the base64-encoded MD5 checksum for a specific chunk of a file.
82
+ S3 uses this checksum (Content-MD5 header) when uploading parts of a file.
83
+ """
84
+ md5_hash = hashlib.md5()
85
+ with file_path.open("rb") as f:
86
+ f.seek(start_byte)
87
+ chunk = f.read(chunk_size)
88
+ md5_hash.update(chunk)
89
+ return base64.b64encode(md5_hash.digest()).decode("utf-8")
90
+
91
+
92
+ def calculate_composite_md5_s3_etag(
93
+ file_path: Path,
94
+ chunk_size: int = S3_MULTIPART_CHUNK_SIZE,
95
+ ) -> str:
96
+ """
97
+ Calculate the composite ETag for a file that was uploaded via multipart upload to S3.
98
+ This is used to validate the downloaded file's integrity.
99
+
100
+ The process involves calculating the MD5 hash of each part, then combining these hashes to form a final ETag.
101
+ So the part size used here must match the part size used during upload.
102
+ """
103
+ md5_digests = []
104
+ part_count = 0
105
+
106
+ for chunk in _read_file_chunks(file_path=file_path, chunk_size=chunk_size):
107
+ md5_digests.append(hashlib.md5(chunk).digest())
108
+ part_count += 1
109
+
110
+ composite_hash = hashlib.md5(b"".join(md5_digests))
111
+ return f"{composite_hash.hexdigest()}-{part_count}"
112
+
113
+
114
+ def convert_checksum_hex_to_base64(hex_checksum: str) -> str:
115
+ """
116
+ Convert a hex-encoded MD5 checksum to base64-encoded format.
117
+ """
118
+ raw_bytes = bytes.fromhex(hex_checksum)
119
+ base64_checksum = base64.b64encode(raw_bytes).decode("utf-8")
120
+ return base64_checksum
divbase_lib/utils.py ADDED
@@ -0,0 +1,133 @@
1
+ from datetime import datetime, timezone
2
+ from typing import Literal, TypeAlias
3
+ from zoneinfo import ZoneInfo
4
+
5
+ from divbase_lib.divbase_constants import (
6
+ DEFAULT_CLI_DISPLAY_DATETIME_FORMAT,
7
+ DEFAULT_DISPLAY_DATETIME_FORMAT,
8
+ DIVBASE_SERVER_TIMEZONE,
9
+ )
10
+
11
+ QuoteChar: TypeAlias = Literal["'", '"']
12
+
13
+
14
+ def set_default_timezone(dt: datetime) -> datetime:
15
+ """
16
+ If the datetime is naive (aka no timezone info), set it to UTC.
17
+ If it already has timezone info, return it unchanged.
18
+ """
19
+ if dt.tzinfo is None:
20
+ dt = dt.replace(tzinfo=timezone.utc)
21
+ return dt
22
+
23
+
24
+ def to_unix_timestamp(dt: datetime) -> int:
25
+ """
26
+ Convert a datetime to a unix timestamp (whole seconds since epoch, UTC).
27
+ Datetimes are assumed to be UTC timezone if not already a timezone aware object.
28
+ """
29
+ dt = set_default_timezone(dt)
30
+ return int(dt.timestamp())
31
+
32
+
33
+ def format_datetime(
34
+ dt: datetime,
35
+ desired_timezone: str = DIVBASE_SERVER_TIMEZONE,
36
+ format: str = DEFAULT_DISPLAY_DATETIME_FORMAT,
37
+ ) -> str:
38
+ """
39
+ Convert a datetime into a human-readable string in a given timezone.
40
+ Datetimes are assumed to be UTC timezone if not already a timezone aware object.
41
+ """
42
+ dt = set_default_timezone(dt)
43
+ return dt.astimezone(ZoneInfo(desired_timezone)).strftime(format)
44
+
45
+
46
+ def format_datetime_for_cli(dt: datetime, format: str = DEFAULT_CLI_DISPLAY_DATETIME_FORMAT) -> str:
47
+ """
48
+ Convert a datetime into a human-readable string in the user's local system timezone.
49
+
50
+ For use by DivBase CLI commands, which are run on the user's own machine and
51
+ should therefore display timestamps in their local timezone.
52
+ """
53
+ dt = set_default_timezone(dt)
54
+ return dt.astimezone().strftime(format)
55
+
56
+
57
+ def format_unix_timestamp_for_cli(unix_timestamp: int | float, fmt: str = DEFAULT_CLI_DISPLAY_DATETIME_FORMAT) -> str:
58
+ """Convert a unix timestamp into a human-readable string in the user's local system timezone."""
59
+ dt = datetime.fromtimestamp(unix_timestamp, tz=timezone.utc)
60
+ return format_datetime_for_cli(dt=dt, format=fmt)
61
+
62
+
63
+ def format_file_size(size_bytes: int | float | None, decimals: int = 2) -> str:
64
+ """
65
+ Converts a file size in bytes to a human-readable format.
66
+
67
+ Uses powers of 1000 so KB, MB, GB, TB and not 1024 KiB, MiB, GiB, TiB.
68
+ """
69
+ if size_bytes is None:
70
+ return "N/A"
71
+ if size_bytes == 0:
72
+ return "0 B"
73
+ power = 1000
74
+ n = 0
75
+ power_labels = {0: "", 1: "K", 2: "M", 3: "G", 4: "T"}
76
+ while size_bytes >= power and n < len(power_labels) - 1:
77
+ size_bytes /= power
78
+ n += 1
79
+ return f"{size_bytes:.{decimals}f} {power_labels[n]}B"
80
+
81
+
82
+ def split_semicolon_bcftools_command_segments(command: str) -> list[str]:
83
+ """
84
+ Split a user provided bcftools command string on semicolons while respecting quoted substrings.
85
+
86
+ bcftools view allows semicolons for certain options (e.g. -i 'FILTER="A;B"'), so we need to ensure that we only
87
+ split on semicolons that are not inside quotes.
88
+
89
+ --command "view -i 'FILTER=\"A;B\"'; view -r 1:1-1000"
90
+
91
+ Slides character by character through the command string to identify the true semicolon delimiters, whilst ignoring semicolons inside quotes.
92
+ The command strings are not that long, so we can afford to do this on a character level.
93
+ """
94
+ command_segments: list[str] = []
95
+ segment_chars: list[str] = []
96
+
97
+ single_quote = "'"
98
+ double_quote = '"'
99
+
100
+ # Possible states None = outside quotes, "'" = inside single-quoted substring, '"' = inside double-quoted substring.
101
+ open_quote_char: QuoteChar | None = None
102
+ is_escaped = False
103
+
104
+ for char in command:
105
+ if is_escaped:
106
+ segment_chars.append(char)
107
+ is_escaped = False
108
+ continue
109
+
110
+ # Handle backslash-escaped characters in the received command text.
111
+ # In single-quoted regions, backslashes are treated as literal chars.
112
+ if char == "\\" and open_quote_char != single_quote:
113
+ segment_chars.append(char)
114
+ is_escaped = True
115
+ continue
116
+
117
+ if char in (double_quote, single_quote):
118
+ segment_chars.append(char)
119
+ if open_quote_char is None:
120
+ open_quote_char = char
121
+ elif open_quote_char == char:
122
+ open_quote_char = None
123
+ continue
124
+
125
+ if char == ";" and open_quote_char is None:
126
+ command_segments.append("".join(segment_chars))
127
+ segment_chars = []
128
+ continue
129
+
130
+ segment_chars.append(char)
131
+
132
+ command_segments.append("".join(segment_chars))
133
+ return command_segments
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.5
2
+ Name: divbase-lib
3
+ Version: 0.1.0
4
+ Summary: Library module for Divbase
5
+ Project-URL: Homepage, https://divbase.scilifelab-2-prod.sys.kth.se
6
+ Project-URL: Documentation, https://scilifelabdatacentre.github.io/divbase
7
+ Project-URL: Repository, https://github.com/ScilifelabDataCentre/divbase
8
+ Project-URL: Issues, https://github.com/ScilifelabDataCentre/divbase/issues
9
+ Author-email: SciLifeLab Data Centre <datacentre@scilifelab.se>
10
+ License-Expression: MIT
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: httpx==0.28.1
22
+ Requires-Dist: pandas==2.3.3
23
+ Requires-Dist: pydantic==2.13.5
24
+ Requires-Dist: pyyaml==6.0.3
25
+ Requires-Dist: stamina==26.1.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # divbase-lib
29
+
30
+ This is library package for Divbase. Code from this library is shared between the Divbase CLI and API packages.
31
+
32
+ ## Installation and usage
33
+
34
+ It is highly unlikely that you will need to use/install this package directly. Instead, it will be installed automatically by other packages (e.g. Divbase CLI) as a dependency.
35
+
36
+ ## Development
37
+
38
+ This package is developed in the [DivBase repository](https://github.com/ScilifelabDataCentre/divbase) by Scilifelab Data Centre.
@@ -0,0 +1,18 @@
1
+ divbase_lib/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ divbase_lib/divbase_constants.py,sha256=WcfELSy1AcOoyKdsq3xEmOh5S4SSM6JrxL8JMRW4Uv8,3557
3
+ divbase_lib/exceptions.py,sha256=9Nl2YhMZtM3obbrCJckBbDePwKFyxWwH8Mlmd3lRsVg,5210
4
+ divbase_lib/metadata_validator.py,sha256=TlVjGmcrl-3hWbcsLPIpsyg9DjQrb3YF_D0JujyVe-U,39483
5
+ divbase_lib/s3_checksums.py,sha256=pAaGDsxAoP916gRR_70frJXEl2GpWC7D_DVTsYfcPmg,4135
6
+ divbase_lib/utils.py,sha256=TIa19UBmZeFwMLZc1JoNy6mFLVAPa9XWpFkLAMeG1-s,4626
7
+ divbase_lib/api_schemas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ divbase_lib/api_schemas/announcements.py,sha256=sEKTlxoBiA5uIH9KC832iQw2jle6cav-9UsVVKhsXqI,596
9
+ divbase_lib/api_schemas/auth.py,sha256=aJASfbFZARpjkTVQLyKIT_rhGvCB3QlrHL9PyDUViEw,1559
10
+ divbase_lib/api_schemas/personal_access_tokens.py,sha256=ZX3xnpLq4vtbNftt8a9E8zFbv8rro5fx00ccJUFv4r8,1682
11
+ divbase_lib/api_schemas/project_versions.py,sha256=9AoI1lLSb_VvuSAymfVnvDlrxg5ENHoN-Rc9wXWXFyo,3365
12
+ divbase_lib/api_schemas/queries.py,sha256=J9mStb8PYE9ZvB1hod4KFpoAB6z4A2xDDTJtNo1rauY,7458
13
+ divbase_lib/api_schemas/s3.py,sha256=VvUGc3wc6NSV1ywg31QwXqmKoBfns4m1f9yOyUe8V1A,14708
14
+ divbase_lib/api_schemas/task_history.py,sha256=IbzQS5hvxXyQe4tHUM9lPU1g2zBGCxz64pLQUDP9XWc,1532
15
+ divbase_lib/api_schemas/vcf_dimensions.py,sha256=pnglegymOWh-_v4KGYcga20hFjCkSwVP-Stvx9OmJX0,2080
16
+ divbase_lib-0.1.0.dist-info/METADATA,sha256=XZ9jOfM-pPEQ_4q8iKySdELjnXDkFUK1vowe81comSU,1592
17
+ divbase_lib-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
18
+ divbase_lib-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any