|
| 1 | +"""Data class for declaring data dependencies in remote functions. |
| 2 | +
|
| 3 | +Wraps local file/directory paths or GCS URIs. On the remote side, Data |
| 4 | +resolves to a plain filesystem path — the user's function only sees paths. |
| 5 | +""" |
| 6 | + |
| 7 | +import hashlib |
| 8 | +import os |
| 9 | +import posixpath |
| 10 | + |
| 11 | +from absl import logging |
| 12 | + |
| 13 | + |
| 14 | +class Data: |
| 15 | + """A reference to data that should be available on the remote pod. |
| 16 | +
|
| 17 | + Wraps a local file/directory path or a GCS URI. When passed as a function |
| 18 | + argument or used in the ``volumes`` decorator parameter, Data is resolved |
| 19 | + to a plain filesystem path on the remote side. The user's function code |
| 20 | + never needs to know about Data — it just receives paths. |
| 21 | +
|
| 22 | + Args: |
| 23 | + path: Local file/directory path (absolute or relative) or GCS URI |
| 24 | + (``gs://bucket/prefix``). |
| 25 | +
|
| 26 | + .. note:: |
| 27 | +
|
| 28 | + For GCS URIs, a trailing slash indicates a directory (prefix). |
| 29 | + ``Data("gs://my-bucket/dataset/")`` is treated as a directory, |
| 30 | + while ``Data("gs://my-bucket/dataset")`` is treated as a single |
| 31 | + object. If you intend to reference a GCS directory, always |
| 32 | + include the trailing slash. |
| 33 | +
|
| 34 | + Examples:: |
| 35 | +
|
| 36 | + # Local directory |
| 37 | + Data("./my_dataset/") |
| 38 | +
|
| 39 | + # Local file |
| 40 | + Data("./config.json") |
| 41 | +
|
| 42 | + # GCS directory — trailing slash required |
| 43 | + Data("gs://my-bucket/datasets/imagenet/") |
| 44 | +
|
| 45 | + # GCS single object |
| 46 | + Data("gs://my-bucket/datasets/weights.h5") |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, path: str): |
| 50 | + if not path: |
| 51 | + raise ValueError("Data path must not be empty") |
| 52 | + self._raw_path = path |
| 53 | + if self.is_gcs: |
| 54 | + self._resolved_path = path |
| 55 | + _warn_if_missing_trailing_slash(path) |
| 56 | + else: |
| 57 | + self._resolved_path = os.path.abspath(os.path.expanduser(path)) |
| 58 | + if not os.path.exists(self._resolved_path): |
| 59 | + raise FileNotFoundError( |
| 60 | + f"Data path does not exist: {path} " |
| 61 | + f"(resolved to {self._resolved_path})" |
| 62 | + ) |
| 63 | + |
| 64 | + @property |
| 65 | + def path(self) -> str: |
| 66 | + return self._resolved_path |
| 67 | + |
| 68 | + @property |
| 69 | + def is_gcs(self) -> bool: |
| 70 | + return self._raw_path.startswith("gs://") |
| 71 | + |
| 72 | + @property |
| 73 | + def is_dir(self) -> bool: |
| 74 | + if self.is_gcs: |
| 75 | + return self._raw_path.endswith("/") |
| 76 | + return os.path.isdir(self._resolved_path) |
| 77 | + |
| 78 | + def content_hash(self) -> str: |
| 79 | + """SHA-256 hash of all file contents, sorted by relative path. |
| 80 | +
|
| 81 | + Includes a type prefix ("dir:" or "file:") to prevent collisions |
| 82 | + between a single file and a directory containing only that file. |
| 83 | +
|
| 84 | + Symlinked directories are not recursed into (followlinks=False) |
| 85 | + to prevent infinite recursion from circular symlinks. Symlinked |
| 86 | + files are read and their resolved contents are hashed, so the |
| 87 | + hash reflects the actual data visible at runtime. |
| 88 | + """ |
| 89 | + if self.is_gcs: |
| 90 | + raise ValueError("Cannot compute content hash for GCS URI") |
| 91 | + |
| 92 | + h = hashlib.sha256() |
| 93 | + if os.path.isdir(self._resolved_path): |
| 94 | + h.update(b"dir:") |
| 95 | + for root, dirs, files in os.walk(self._resolved_path, followlinks=False): |
| 96 | + dirs.sort() |
| 97 | + for fname in sorted(files): |
| 98 | + fpath = os.path.join(root, fname) |
| 99 | + relpath = os.path.relpath(fpath, self._resolved_path) |
| 100 | + h.update(relpath.encode("utf-8")) |
| 101 | + h.update(b"\0") |
| 102 | + with open(fpath, "rb") as f: |
| 103 | + while True: |
| 104 | + chunk = f.read(65536) # 64 KB chunks |
| 105 | + if not chunk: |
| 106 | + break |
| 107 | + h.update(chunk) |
| 108 | + h.update(b"\0") |
| 109 | + else: |
| 110 | + h.update(b"file:") |
| 111 | + h.update(os.path.basename(self._resolved_path).encode("utf-8")) |
| 112 | + h.update(b"\0") |
| 113 | + with open(self._resolved_path, "rb") as f: |
| 114 | + while True: |
| 115 | + chunk = f.read(65536) |
| 116 | + if not chunk: |
| 117 | + break |
| 118 | + h.update(chunk) |
| 119 | + return h.hexdigest() |
| 120 | + |
| 121 | + def __repr__(self): |
| 122 | + return f"Data({self._raw_path!r})" |
| 123 | + |
| 124 | + |
| 125 | +def _warn_if_missing_trailing_slash(path: str) -> None: |
| 126 | + """Log a warning if a GCS path looks like a directory but has no trailing slash.""" |
| 127 | + if path.endswith("/"): |
| 128 | + return |
| 129 | + gcs_path = path.split("//", 1)[1] # strip gs:// |
| 130 | + last_segment = posixpath.basename(gcs_path) |
| 131 | + if last_segment and "." not in last_segment: |
| 132 | + logging.warning( |
| 133 | + "GCS path %r does not end with '/' but the last segment " |
| 134 | + "(%r) has no file extension. If this is a directory " |
| 135 | + "(prefix), add a trailing slash: %r", |
| 136 | + path, |
| 137 | + last_segment, |
| 138 | + path + "/", |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +def _make_data_ref( |
| 143 | + gcs_uri: str, is_dir: bool, mount_path: str | None = None |
| 144 | +) -> dict[str, object]: |
| 145 | + """Create a serializable data reference dict. |
| 146 | +
|
| 147 | + These dicts replace Data objects in the payload before serialization. |
| 148 | + The remote runner identifies them by the __data_ref__ key. |
| 149 | + """ |
| 150 | + return { |
| 151 | + "__data_ref__": True, |
| 152 | + "gcs_uri": gcs_uri, |
| 153 | + "is_dir": is_dir, |
| 154 | + "mount_path": mount_path, |
| 155 | + } |
| 156 | + |
| 157 | + |
| 158 | +def is_data_ref(obj: object) -> bool: |
| 159 | + """Check if an object is a serialized data reference.""" |
| 160 | + return isinstance(obj, dict) and obj.get("__data_ref__") is True |
0 commit comments