|
| 1 | +"""Checksum utilities for SEG-Y ingestion. |
| 2 | +
|
| 3 | +This module provides optional CRC32C checksum functionality for SEG-Y ingestion. |
| 4 | +All checksum-related imports and logic are isolated here to maintain loose coupling |
| 5 | +with the core functionality. |
| 6 | +
|
| 7 | +Checksum calculation is controlled by the MDIO__IMPORT__DO_CRC32C environment variable |
| 8 | +and requires optional dependencies (google-crc32c, crc32c_dist_rs). |
| 9 | +
|
| 10 | +IMPORTANT: This module uses distributed CRC32C calculation to avoid reading entire files |
| 11 | +into memory. Never add functions that read entire files - this has severe performance |
| 12 | +and cost implications, especially for cloud storage. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | +from typing import TYPE_CHECKING |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +if TYPE_CHECKING: |
| 23 | + from segy.arrays import HeaderArray |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | +# Try to import CRC32C libraries, but gracefully handle if they're not installed |
| 28 | +_CHECKSUM_AVAILABLE = False |
| 29 | +_IMPORT_ERROR_MSG = "" |
| 30 | + |
| 31 | +try: |
| 32 | + import google_crc32c |
| 33 | + from crc32c_dist_rs import DistributedCRC32C |
| 34 | + |
| 35 | + _CHECKSUM_AVAILABLE = True |
| 36 | +except ImportError as e: |
| 37 | + _IMPORT_ERROR_MSG = ( |
| 38 | + f"CRC32C checksum libraries not available: {e}. " |
| 39 | + "Install with: pip install multidimio[checksum] or pip install google-crc32c crc32c_dist_rs" |
| 40 | + ) |
| 41 | + # Define placeholder types for type checking |
| 42 | + google_crc32c = None # type: ignore[assignment] |
| 43 | + DistributedCRC32C = None # type: ignore[assignment,misc] |
| 44 | + |
| 45 | + |
| 46 | +def is_checksum_available() -> bool: |
| 47 | + """Check if checksum libraries are available. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + True if google-crc32c and crc32c_dist_rs are installed, False otherwise. |
| 51 | + """ |
| 52 | + return _CHECKSUM_AVAILABLE |
| 53 | + |
| 54 | + |
| 55 | +def should_calculate_checksum() -> bool: |
| 56 | + """Determine if checksum calculation should be performed. |
| 57 | +
|
| 58 | + Checks both the environment variable and library availability. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + True if MDIO__IMPORT__DO_CRC32C is enabled and libraries are available. |
| 62 | + """ |
| 63 | + env_enabled = os.getenv("MDIO__IMPORT__DO_CRC32C", "false").lower() in ("1", "true", "yes", "on") |
| 64 | + |
| 65 | + if env_enabled and not _CHECKSUM_AVAILABLE: |
| 66 | + logger.warning( |
| 67 | + "MDIO__IMPORT__DO_CRC32C is enabled but checksum libraries are not available. " |
| 68 | + "Checksum calculation will be skipped. %s", |
| 69 | + _IMPORT_ERROR_MSG, |
| 70 | + ) |
| 71 | + return False |
| 72 | + |
| 73 | + return env_enabled |
| 74 | + |
| 75 | + |
| 76 | +def require_checksum_libraries() -> None: |
| 77 | + """Raise an error if checksum libraries are not available. |
| 78 | +
|
| 79 | + Raises: |
| 80 | + ImportError: If checksum libraries are not installed. |
| 81 | + """ |
| 82 | + if not _CHECKSUM_AVAILABLE: |
| 83 | + raise ImportError(_IMPORT_ERROR_MSG) |
| 84 | + |
| 85 | + |
| 86 | +def calculate_bytes_crc32c(data: bytes) -> int: |
| 87 | + """Calculate CRC32C checksum for a byte array. |
| 88 | +
|
| 89 | + Args: |
| 90 | + data: Byte array to checksum. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + CRC32C checksum as integer. |
| 94 | +
|
| 95 | + Raises: |
| 96 | + ImportError: If checksum libraries are not available. |
| 97 | + """ |
| 98 | + require_checksum_libraries() |
| 99 | + |
| 100 | + crc = google_crc32c.Checksum(data) |
| 101 | + return int.from_bytes(crc.digest(), byteorder="big") |
| 102 | + |
| 103 | + |
| 104 | +def create_distributed_crc32c(initial_bytes: bytes, total_length: int) -> Any: |
| 105 | + """Create a distributed CRC32C combiner instance. |
| 106 | +
|
| 107 | + Args: |
| 108 | + initial_bytes: Initial bytes (e.g., file header). |
| 109 | + total_length: Total expected file length in bytes. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + DistributedCRC32C instance. |
| 113 | +
|
| 114 | + Raises: |
| 115 | + ImportError: If checksum libraries are not available. |
| 116 | + """ |
| 117 | + require_checksum_libraries() |
| 118 | + |
| 119 | + return DistributedCRC32C(initial_bytes, total_length) |
| 120 | + |
| 121 | + |
| 122 | +def finalize_distributed_checksum( |
| 123 | + results: list[tuple[HeaderArray, tuple[int, int, int]]], combiner: Any |
| 124 | +) -> tuple[HeaderArray, int]: |
| 125 | + """Finalize a distributed CRC32C checksum from scan results. |
| 126 | +
|
| 127 | + Args: |
| 128 | + results: List of (HeaderArray, (byte_offset, partial_crc, byte_length)) tuples. |
| 129 | + combiner: DistributedCRC32C instance. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + Tuple of (concatenated HeaderArray, final CRC32C checksum). |
| 133 | +
|
| 134 | + Raises: |
| 135 | + ValueError: If checksum finalization fails. |
| 136 | + ImportError: If checksum libraries are not available. |
| 137 | + """ |
| 138 | + require_checksum_libraries() |
| 139 | + |
| 140 | + import numpy as np |
| 141 | + |
| 142 | + headers: list[HeaderArray] = [] |
| 143 | + for result in results: |
| 144 | + headers.append(result[0]) |
| 145 | + byte_offset, partial_crc, byte_length = result[1] |
| 146 | + combiner.add_fragment(byte_offset, byte_length, partial_crc) |
| 147 | + |
| 148 | + combined_crc = combiner.try_finalize() |
| 149 | + if combined_crc is None: |
| 150 | + msg = "Failed to finalize CRC32C - file may not be fully covered" |
| 151 | + raise ValueError(msg) |
| 152 | + |
| 153 | + # Merge headers and return with checksum |
| 154 | + return np.concatenate(headers), combined_crc |
| 155 | + |
| 156 | + |
| 157 | +__all__ = [ |
| 158 | + "is_checksum_available", |
| 159 | + "should_calculate_checksum", |
| 160 | + "require_checksum_libraries", |
| 161 | + "calculate_bytes_crc32c", |
| 162 | + "create_distributed_crc32c", |
| 163 | + "finalize_distributed_checksum", |
| 164 | +] |
| 165 | + |
0 commit comments