|
| 1 | +# Copyright (c) 2025, Salesforce, Inc. |
| 2 | +# SPDX-License-Identifier: Apache-2 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +"""Generate config.json ``dataLineage`` by tracing a script's Spark plans.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import builtins |
| 20 | +import json |
| 21 | +import os |
| 22 | +import subprocess |
| 23 | +import sys |
| 24 | +import tempfile |
| 25 | +from typing import ( |
| 26 | + Any, |
| 27 | + Dict, |
| 28 | + NoReturn, |
| 29 | + Optional, |
| 30 | + Sequence, |
| 31 | +) |
| 32 | + |
| 33 | +from datacustomcode.lineage.capture import ( |
| 34 | + LineageCaptureReader, |
| 35 | + LineageCaptureWriter, |
| 36 | + LineageCollector, |
| 37 | + LineageResult, |
| 38 | + install_capture, |
| 39 | +) |
| 40 | +from datacustomcode.lineage.tracer import LineageTraceError |
| 41 | + |
| 42 | +__all__ = [ |
| 43 | + "LineageCaptureReader", |
| 44 | + "LineageCaptureWriter", |
| 45 | + "LineageCollector", |
| 46 | + "LineageResult", |
| 47 | + "LineageTraceError", |
| 48 | + "generate_lineage", |
| 49 | + "install_capture", |
| 50 | +] |
| 51 | + |
| 52 | + |
| 53 | +def generate_lineage( |
| 54 | + entrypoint: str, |
| 55 | + config_file: Optional[str] = None, |
| 56 | + dependencies: Sequence[str] = (), |
| 57 | + profile: str = "default", |
| 58 | + sf_cli_org: Optional[str] = None, |
| 59 | +) -> LineageResult: |
| 60 | + """Run a script entrypoint and return the field-level lineage it produces. |
| 61 | +
|
| 62 | + The entrypoint runs exactly as with ``run`` (same config resolution, reader |
| 63 | + and credentials), except that writes are traced instead of performed. It runs |
| 64 | + in a fresh Python process, so no client or config from the caller's process |
| 65 | + leaks into the capture. The process inherits this one's working directory, |
| 66 | + environment, ``sys.path`` and stdout/stderr. |
| 67 | +
|
| 68 | + Args: |
| 69 | + entrypoint: The script entrypoint to run. |
| 70 | + config_file: Optional SDK config file, as for ``run``. |
| 71 | + dependencies: Modules to import before running, as for ``run``. |
| 72 | + profile: The credentials profile to use. |
| 73 | + sf_cli_org: Optional SF CLI org alias or username. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + The captured :class:`LineageResult`. |
| 77 | +
|
| 78 | + Raises: |
| 79 | + ValueError: If the package is not a batch script. |
| 80 | + Exception: Whatever the run raised, re-raised as the same built-in |
| 81 | + exception type or :class:`LineageTraceError`, else ``RuntimeError``. |
| 82 | + """ |
| 83 | + with tempfile.TemporaryDirectory(prefix="datacustomcode-lineage-") as tmp: |
| 84 | + request_file = os.path.join(tmp, "request.json") |
| 85 | + response_file = os.path.join(tmp, "response.json") |
| 86 | + with open(request_file, "w", encoding="utf-8") as f: |
| 87 | + json.dump( |
| 88 | + { |
| 89 | + "args": { |
| 90 | + "entrypoint": entrypoint, |
| 91 | + "config_file": config_file, |
| 92 | + "dependencies": list(dependencies), |
| 93 | + "profile": profile, |
| 94 | + "sf_cli_org": sf_cli_org, |
| 95 | + }, |
| 96 | + "response_file": response_file, |
| 97 | + }, |
| 98 | + f, |
| 99 | + ) |
| 100 | + # The worker sees the same modules this process does |
| 101 | + env = dict(os.environ) |
| 102 | + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) |
| 103 | + completed = subprocess.run( |
| 104 | + [sys.executable, "-m", "datacustomcode.lineage._worker", request_file], |
| 105 | + env=env, |
| 106 | + check=False, |
| 107 | + ) |
| 108 | + if not os.path.exists(response_file): |
| 109 | + raise RuntimeError( |
| 110 | + f"Lineage generation exited with code {completed.returncode} " |
| 111 | + "without a result" |
| 112 | + ) |
| 113 | + with open(response_file, encoding="utf-8") as f: |
| 114 | + response = json.load(f) |
| 115 | + if "error" in response: |
| 116 | + _raise(response["error"]) |
| 117 | + return LineageResult.from_dict(response["result"]) |
| 118 | + |
| 119 | + |
| 120 | +def _raise(error: Dict[str, Any]) -> NoReturn: |
| 121 | + """Re-raise an error reported by the worker as the closest local type.""" |
| 122 | + message = error["message"] |
| 123 | + if error["type"] == LineageTraceError.__name__: |
| 124 | + raise LineageTraceError(message) |
| 125 | + exc_type = getattr(builtins, error["type"], None) |
| 126 | + if ( |
| 127 | + error["module"] == "builtins" |
| 128 | + and isinstance(exc_type, type) |
| 129 | + and issubclass(exc_type, Exception) |
| 130 | + ): |
| 131 | + try: |
| 132 | + exc = exc_type(message) |
| 133 | + except TypeError: # e.g. UnicodeDecodeError takes more arguments |
| 134 | + pass |
| 135 | + else: |
| 136 | + raise exc |
| 137 | + raise RuntimeError(f"{error['module']}.{error['type']}: {message}") |
0 commit comments