:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): import csv and excel file contents from sharepoint (#114496)
Tom Owersf6247a3d78e4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/excel_parsing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/excel_parsing.pynew file mode 100644index 000000000000..bdc912b2eced--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/excel_parsing.py@@ -0,0 +1,134 @@+import zipfile+from collections.abc import Iterator+from contextlib import contextmanager+from datetime import date, datetime, time, timedelta+from typing import IO, Any++import openpyxl+from openpyxl.utils.exceptions import InvalidFileException+from openpyxl.workbook.workbook import Workbook+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ CHUNK_SIZE,+ dedupe_headers,+)++EXCEL_ERROR = "Can't read the Excel file"+MAX_EXCEL_FILE_BYTES = 100 * 1024 * 1024+MAX_SHARED_STRINGS_BYTES = 256 * 1024 * 1024+MAX_WORKBOOK_PART_BYTES = 64 * 1024 * 1024+MAX_WORKSHEET_BYTES = 1024 * 1024 * 1024++ExcelValue = int | float | bool | str | datetime | None+++class ExcelFileError(Exception):+ def __init__(self, message: str) -> None:+ super().__init__(f"{EXCEL_ERROR} {message}")+++@contextmanager+def _open_workbook(file: IO[bytes], file_name: str) -> Iterator[Workbook]:+ workbook = None+ try:+ try:+ file.seek(0)+ with zipfile.ZipFile(file) as archive:+ # openpyxl loads every part except the worksheets into memory, even in read-only mode.+ # It also holds each worksheet cell in memory whole, so worksheets get a larger limit.+ for part in archive.infolist():+ if part.filename == "xl/sharedStrings.xml":+ limit = MAX_SHARED_STRINGS_BYTES+ elif part.filename.startswith("xl/worksheets/"):+ limit = MAX_WORKSHEET_BYTES+ else:+ limit = MAX_WORKBOOK_PART_BYTES+ if part.file_size > limit:+ if part.filename == "xl/sharedStrings.xml":+ raise ExcelFileError(+ f"'{file_name}': shared strings exceed the size limit. Split the workbook."+ )+ raise ExcelFileError(+ f"'{file_name}': '{part.filename}' exceeds the size limit. Split the workbook."+ )+ finally:+ file.seek(0)+ # Cached results keep formulas out of the data. Uncached formulas read as None.+ workbook = openpyxl.load_workbook(file, read_only=True, data_only=True)+ yield workbook+ except (zipfile.BadZipFile, InvalidFileException, KeyError, SyntaxError, ValueError, OSError) as error:+ raise ExcelFileError(f"'{file_name}'. Save it as .xlsx again, then refresh the source's tables.") from error+ finally:+ if workbook is not None:+ workbook.close()+++def list_worksheets(file: IO[bytes], file_name: str) -> list[str]:+ with _open_workbook(file, file_name) as workbook:+ return [ws.title for ws in workbook.worksheets if ws.sheet_state == "visible"]+++def normalize_cell(value: object) -> ExcelValue:+ if isinstance(value, datetime):+ return value+ if isinstance(value, (date, time)):+ return value.isoformat()+ if isinstance(value, timedelta):+ return str(value)+ if value is None or isinstance(value, (int, float, bool, str)):+ return value+ return str(value)+++def normalize_chunk(rows: list[dict[str, ExcelValue]]) -> list[dict[str, ExcelValue]]:+ if not rows:+ return []+ mixed = set()+ for column in rows[0]:+ kinds = {+ float if type(value) in (int, float) else type(value) for row in rows if (value := row[column]) is not None+ }+ if len(kinds) > 1:+ mixed.add(column)+ return [+ {column: str(value) if column in mixed and value is not None else value for column, value in row.items()}+ for row in rows+ ]+++def iter_worksheet_rows(+ file: IO[bytes],+ file_name: str,+ worksheet: str,+ chunk_size: int = CHUNK_SIZE,+ logger: FilteringBoundLogger | None = None,+) -> Iterator[list[dict[str, Any]]]:+ with _open_workbook(file, file_name) as workbook:+ ws = next((sheet for sheet in workbook.worksheets if sheet.title == worksheet), None)+ if ws is None:+ raise ExcelFileError(+ f"'{file_name}' has no worksheet named '{worksheet}'. "+ "It may have been renamed or deleted. Refresh the source's tables."+ )+ # Other writers can leave dimensions that hide rows or add empty columns.+ ws.reset_dimensions()+ rows = ws.iter_rows(values_only=True)+ headers = [str(cell) if cell is not None else "" for cell in next(rows, ())]+ while headers and not headers[-1].strip():+ headers.pop()+ if not headers:+ return+ headers = dedupe_headers(headers)+ chunk: list[dict[str, ExcelValue]] = []+ for row in rows:+ values = list(row[: len(headers)])+ if all(value is None or (isinstance(value, str) and not value.strip()) for value in values):+ continue+ values.extend([None] * (len(headers) - len(values)))+ chunk.append(dict(zip(headers, map(normalize_cell, values))))+ if len(chunk) >= chunk_size:+ yield normalize_chunk(chunk)+ chunk = []+ if chunk:+ yield normalize_chunk(chunk)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/file_parsing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/file_parsing.pynew file mode 100644index 000000000000..c258cc97b52e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/file_parsing.py@@ -0,0 +1,237 @@+import io+import re+import csv+import gzip+import json+import posixpath+import dataclasses+from collections.abc import Iterator+from typing import IO, Any, Literal, cast++from structlog.types import FilteringBoundLogger++FileFormat = Literal["csv", "jsonl", "json"]+ConfiguredFileFormat = Literal["infer", "csv", "jsonl", "json"]++# A whole-document JSON file has to be materialized to parse it, so cap how many decompressed bytes+# we read before giving up and steering the user to JSON Lines (which streams). Also stops a small+# gzip file from decompressing into unbounded memory.+MAX_JSON_DOCUMENT_BYTES = 256 * 1024 * 1024++CHUNK_SIZE = 5000++# Every row carries which file it came from, so a table built from many files stays traceable.+FILE_PATH_COLUMN = "_file_name"+FILE_MODIFIED_AT_COLUMN = "_file_modified_at"++EXTENSION_FORMATS: dict[str, FileFormat] = {+ ".csv": "csv",+ ".tsv": "csv",+ ".txt": "csv",+ ".jsonl": "jsonl",+ ".ndjson": "jsonl",+ ".json": "json",+}++EXTENSION_DELIMITERS: dict[str, str] = {".tsv": "\t"}++DEFAULT_DELIMITER = ","++FORMAT_ERROR = "Can't work out the format of the remote file"+DELIMITER_ERROR = "The CSV delimiter must be a single character"+++class FileFormatError(Exception):+ """A file could not be parsed with the configured or inferred format."""+++class FileDelimiterError(ValueError):+ """The configured delimiter is not a single character."""++[email protected](frozen=True)+class ResolvedFormat:+ file_format: FileFormat+ delimiter: str+ compressed: bool+++def normalize_delimiter(delimiter: str | None) -> str | None:+ """Accept a literal tab, an escaped `\\t`, or the word `tab` for tab-separated files."""+ if delimiter is None:+ return None+ if delimiter in ("\\t", "tab", "\t"):+ return "\t"+ if delimiter == "":+ return None+ if len(delimiter) != 1:+ raise FileDelimiterError(f"{DELIMITER_ERROR} (got {delimiter!r}). Use \\t for tab-separated files.")+ return delimiter+++def is_format_inferable(relative_path: str) -> bool:+ lowered = relative_path.lower()+ if lowered.endswith(".gz"):+ lowered = lowered[: -len(".gz")]+ return posixpath.splitext(lowered)[1] in EXTENSION_FORMATS+++def resolve_file_format(+ relative_path: str,+ configured_format: ConfiguredFileFormat | str | None = "infer",+ delimiter: str | None = None,+) -> ResolvedFormat:+ lowered = relative_path.lower()+ compressed = lowered.endswith(".gz")+ if compressed:+ lowered = lowered[: -len(".gz")]+ extension = posixpath.splitext(lowered)[1]++ if configured_format and configured_format != "infer":+ file_format = cast(FileFormat, configured_format)+ else:+ inferred = EXTENSION_FORMATS.get(extension)+ if inferred is None:+ raise FileFormatError(+ f"{FORMAT_ERROR} '{relative_path}'. Set the file format explicitly, or restrict the file "+ "pattern to .csv, .json, or .jsonl files."+ )+ file_format = inferred++ resolved_delimiter = normalize_delimiter(delimiter) or EXTENSION_DELIMITERS.get(extension, DEFAULT_DELIMITER)+ return ResolvedFormat(file_format=file_format, delimiter=resolved_delimiter, compressed=compressed)+++def normalize_column_name(header: str) -> str:+ """Headers like 'Order Total (USD)' become stable snake_case columns."""+ normalized = re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()+ return normalized or "column"+++def dedupe_headers(headers: list[str]) -> list[str]:+ seen: dict[str, int] = {}+ result = []+ for header in headers:+ name = normalize_column_name(header)+ if name in seen:+ seen[name] += 1+ name = f"{name}_{seen[name]}"+ else:+ seen[name] = 1+ result.append(name)+ return result+++def _decompressed_stream(stream: IO[bytes], compressed: bool) -> IO[bytes]:+ return cast(IO[bytes], gzip.GzipFile(fileobj=stream)) if compressed else stream+++def _text_stream(binary: IO[bytes]) -> IO[str]:+ return io.TextIOWrapper(binary, encoding="utf-8", errors="replace", newline="")+++def _iter_csv_rows(+ text: IO[str],+ delimiter: str,+ relative_path: str,+ chunk_size: int,+ logger: FilteringBoundLogger | None,+) -> Iterator[list[dict[str, Any]]]:+ reader = csv.reader(text, delimiter=delimiter)+ headers: list[str] | None = None+ chunk: list[dict[str, Any]] = []++ for line_number, row in enumerate(reader, start=1):+ if headers is None:+ headers = dedupe_headers(row)+ continue+ if not any(cell.strip() for cell in row):+ continue+ if len(row) > len(headers):+ # More values than headers means the file is malformed or the delimiter is wrong.+ # Dropping the row keeps the extra values from silently landing in the wrong columns.+ if logger is not None:+ logger.warning(+ "Skipping CSV row with more values than headers",+ file=relative_path,+ line=line_number,+ expected=len(headers),+ got=len(row),+ )+ continue+ values: list[str | None] = [*row, *([None] * (len(headers) - len(row)))]+ chunk.append(dict(zip(headers, values)))+ if len(chunk) >= chunk_size:+ yield chunk+ chunk = []++ if chunk:+ yield chunk+++def _as_rows(value: Any) -> list[dict[str, Any]]:+ if isinstance(value, dict):+ return [value]+ if isinstance(value, list):+ return [item if isinstance(item, dict) else {"value": item} for item in value]+ return [{"value": value}]+++def _iter_jsonl_rows(text: IO[str], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:+ chunk: list[dict[str, Any]] = []+ for line_number, line in enumerate(text, start=1):+ if not line.strip():+ continue+ try:+ parsed = json.loads(line)+ except json.JSONDecodeError as e:+ raise FileFormatError(+ f"Line {line_number} of '{relative_path}' isn't valid JSON: {e}. If the file holds one "+ "JSON document rather than one object per line, set the file format to JSON."+ ) from e+ chunk.extend(_as_rows(parsed))+ if len(chunk) >= chunk_size:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def _iter_json_rows(binary: IO[bytes], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:+ # A whole-document JSON file can't be chunked, so it has to fit in memory. Read one decompressed+ # byte past the limit to detect an oversized (or gzip-bomb) document before materializing it, and+ # point the user at JSON Lines, which streams. The byte cap is what bounds memory here, so it runs+ # on the decompressed bytes rather than a decoded-character count.+ raw = binary.read(MAX_JSON_DOCUMENT_BYTES + 1)+ if len(raw) > MAX_JSON_DOCUMENT_BYTES:+ raise FileFormatError(+ f"'{relative_path}' is larger than the {MAX_JSON_DOCUMENT_BYTES // (1024 * 1024)} MB limit for a "+ "single JSON document. Convert it to JSON Lines (one object per line) so it can stream in."+ )+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError as e:+ raise FileFormatError(+ f"'{relative_path}' isn't valid JSON: {e}. If the file holds one JSON object per line, "+ "set the file format to JSON Lines."+ ) from e++ rows = _as_rows(parsed)+ for start in range(0, len(rows), chunk_size):+ yield rows[start : start + chunk_size]+++def iter_file_rows(+ stream: IO[bytes],+ resolved: ResolvedFormat,+ relative_path: str,+ chunk_size: int = CHUNK_SIZE,+ logger: FilteringBoundLogger | None = None,+) -> Iterator[list[dict[str, Any]]]:+ binary = _decompressed_stream(stream, resolved.compressed)+ if resolved.file_format == "csv":+ yield from _iter_csv_rows(_text_stream(binary), resolved.delimiter, relative_path, chunk_size, logger)+ elif resolved.file_format == "jsonl":+ yield from _iter_jsonl_rows(_text_stream(binary), relative_path, chunk_size)+ else:+ yield from _iter_json_rows(binary, relative_path, chunk_size)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.pyindex 540583aa6eec..3e003e159a74 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/observer.py@@ -19,6 +19,9 @@ from __future__ import annotationsimport timeimport logging+from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVarfrom dataclasses import dataclassimport structlog@@ -45,6 +48,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httlogger = structlog.get_logger(__name__)_fallback_logger = logging.getLogger(__name__)+_redact_request_urls: ContextVar[bool] = ContextVar("redact_request_urls", default=False)+++@contextmanager+def redact_request_urls() -> Iterator[None]:+ # Download redirects can carry credentials in both paths and query parameters.+ token = _redact_request_urls.set(True)+ try:+ yield+ finally:+ _redact_request_urls.reset(token)+@dataclass(frozen=True)class RequestRecord:@@ -114,6 +129,10 @@ def record_request(scrubbed_url = redact_literal_values(scrubbed_url, redact_values)template = redact_literal_values(template, redact_values)host = host_of(raw_url)+ if _redact_request_urls.get():+ scrubbed_url = "REDACTED"+ template = "REDACTED"+ capture = Falsestatus_code = response.status_code if response is not None else Noneerror_class = type(exception).__name__ if exception is not None else Nonerequest_bytes = _request_size(request)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_excel_parsing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_excel_parsing.pynew file mode 100644index 000000000000..735ff41896d2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_excel_parsing.py@@ -0,0 +1,188 @@+import io+import re+import zipfile+from datetime import date, datetime, time, timedelta++import pytest+from unittest.mock import patch++from openpyxl import Workbook+from openpyxl.chart import BarChart, Reference+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.excel_parsing import (+ EXCEL_ERROR,+ ExcelFileError,+ ExcelValue,+ iter_worksheet_rows,+ list_worksheets,+ normalize_chunk,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.excel_parsing"+++def workbook_stream(rows: list[list[object]]) -> io.BytesIO:+ workbook = Workbook(iso_dates=True)+ try:+ ws = workbook.worksheets[0]+ for row in rows:+ ws.append(row)+ stream = io.BytesIO()+ workbook.save(stream)+ stream.seek(0)+ return stream+ finally:+ workbook.close()+++class TestExcelParsing:+ def test_lists_visible_worksheets_in_workbook_order(self) -> None:+ workbook = Workbook()+ try:+ first = workbook.worksheets[0]+ first.title = "Z first"+ first.append([1])+ workbook.create_sheet("hidden").sheet_state = "hidden"+ chart = BarChart()+ chart.add_data(Reference(first, min_col=1, min_row=1, max_row=1))+ workbook.create_chartsheet("Chart").add_chart(chart)+ workbook.create_sheet("very hidden").sheet_state = "veryHidden"+ workbook.create_sheet("A last")+ stream = io.BytesIO()+ workbook.save(stream)+ finally:+ workbook.close()++ assert list_worksheets(stream, "report.xlsx") == ["Z first", "A last"]+ assert not stream.closed++ def test_normalizes_headers_and_row_widths(self) -> None:+ stream = workbook_stream(+ [+ ["Order Total (USD)", None, "Name", "name", 42, None, " "],+ [10, "inside", "a", "b", "c", "ignored"],+ [None, " ", "\t"],+ [20],+ [None, None, None, None, None, "outside"],+ ]+ )++ assert list(iter_worksheet_rows(stream, "report.xlsx", "Sheet")) == [+ [+ {"order_total_usd": 10, "column": "inside", "name": "a", "name_2": "b", "42": "c"},+ {"order_total_usd": 20, "column": None, "name": None, "name_2": None, "42": None},+ ]+ ]++ @parameterized.expand([("empty", []), ("blank_header", [[None, " "], [1, 2]])])+ def test_no_headers_yields_nothing(self, _name: str, rows: list[list[object]]) -> None:+ assert list(iter_worksheet_rows(workbook_stream(rows), "report.xlsx", "Sheet")) == []++ @parameterized.expand(+ [+ ("integer", 7, 7),+ ("float", 1.5, 1.5),+ ("boolean", True, True),+ ("text", "hello", "hello"),+ ("datetime", datetime(2026, 1, 2, 3, 4, 5), datetime(2026, 1, 2, 3, 4, 5)),+ ("date", date(2026, 1, 2), "2026-01-02"),+ ("time", time(3, 4, 5), "03:04:05"),+ ("duration", timedelta(days=2, seconds=3), "2 days, 0:00:03"),+ ("uncached_formula", "=1+1", None),+ ]+ )+ def test_cell_values(self, _name: str, value: object, expected: ExcelValue) -> None:+ stream = workbook_stream([["value", "id"], [value, 1]])++ row = next(iter_worksheet_rows(stream, "report.xlsx", "Sheet"))[0]++ assert row == {"value": expected, "id": 1}+ assert type(row["value"]) is type(expected)++ @parameterized.expand(+ [+ ("number_text", [1, "two", None], ["1", "two", None]),+ ("numeric", [1, 2.5], [1, 2.5]),+ ("boolean_number", [True, 1], ["True", "1"]),+ ("null", [None, 1], [None, 1]),+ ("all_null", [None, None], [None, None]),+ ("date_text", [datetime(2026, 1, 2), "later"], ["2026-01-02 00:00:00", "later"]),+ ]+ )+ def test_mixed_columns(self, _name: str, values: list[ExcelValue], expected: list[ExcelValue]) -> None:+ rows = [{"value": value} for value in values]++ assert normalize_chunk(rows) == [{"value": value} for value in expected]+ assert rows == [{"value": value} for value in values]+ sheet_rows: list[list[object]] = [["value", "id"]]+ for index, value in enumerate(values):+ row: list[object] = [value, index]+ sheet_rows.append(row)+ stream = workbook_stream(sheet_rows)+ parsed = list(iter_worksheet_rows(stream, "report.xlsx", "Sheet"))+ assert [row["value"] for chunk in parsed for row in chunk] == expected++ def test_chunks_and_normalizes_each_chunk_independently(self) -> None:+ stream = workbook_stream([["value"], [1], ["two"], [3], [4.5], [True]])++ assert list(iter_worksheet_rows(stream, "report.xlsx", "Sheet", chunk_size=2)) == [+ [{"value": "1"}, {"value": "two"}],+ [{"value": 3}, {"value": 4.5}],+ [{"value": True}],+ ]++ def test_ignores_incorrect_dimensions(self) -> None:+ original = workbook_stream([["first", "second"], [1, 2], [3]])+ stream = io.BytesIO()+ with zipfile.ZipFile(original) as source, zipfile.ZipFile(stream, "w") as target:+ for member in source.infolist():+ content = source.read(member.filename)+ if member.filename == "xl/worksheets/sheet1.xml":+ content = re.sub(rb'<dimension ref="[^"]+"', b'<dimension ref="A1:A1"', content)+ target.writestr(member, content)++ assert list(iter_worksheet_rows(stream, "report.xlsx", "Sheet")) == [+ [{"first": 1, "second": 2}, {"first": 3, "second": None}]+ ]++ @parameterized.expand(+ [("not_zip",), ("missing_part",), ("shared_strings",), ("large_part",), ("large_worksheet",), ("invalid_xml",)]+ )+ def test_invalid_workbooks_have_stable_errors(self, case: str) -> None:+ stream = io.BytesIO(b"not a zip")+ if case != "not_zip":+ stream = io.BytesIO()+ with zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ if case == "shared_strings":+ archive.writestr("xl/sharedStrings.xml", b"x" * 100)+ elif case == "large_part":+ archive.writestr("xl/theme/theme1.xml", b"x" * 100)+ elif case == "large_worksheet":+ archive.writestr("xl/worksheets/sheet1.xml", b"x" * 100)+ elif case == "invalid_xml":+ archive.writestr("[Content_Types].xml", b"not xml")++ with (+ patch(f"{MODULE}.MAX_SHARED_STRINGS_BYTES", 50),+ patch(f"{MODULE}.MAX_WORKBOOK_PART_BYTES", 50),+ patch(f"{MODULE}.MAX_WORKSHEET_BYTES", 50),+ ):+ with pytest.raises(ExcelFileError, match=f"^{EXCEL_ERROR}") as error:+ list_worksheets(stream, "broken.xlsx")+ assert "broken.xlsx" in str(error.value)+ if case in ("large_part", "large_worksheet"):+ assert "xl/" in str(error.value) and "exceeds the size limit" in str(error.value)+ elif case != "shared_strings":+ assert "Save it as .xlsx again" in str(error.value)+ with pytest.raises(ExcelFileError, match=f"^{EXCEL_ERROR}"):+ list(iter_worksheet_rows(stream, "broken.xlsx", "Sheet"))++ def test_missing_worksheet_has_refresh_instruction(self) -> None:+ with pytest.raises(ExcelFileError, match=f"^{EXCEL_ERROR}") as error:+ list(iter_worksheet_rows(workbook_stream([["id"], [1]]), "report.xlsx", "Old name"))++ assert str(error.value) == (+ f"{EXCEL_ERROR} 'report.xlsx' has no worksheet named 'Old name'. "+ "It may have been renamed or deleted. Refresh the source's tables."+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_file_parsing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_file_parsing.pynew file mode 100644index 000000000000..faef50dda4d8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_file_parsing.py@@ -0,0 +1,178 @@+import io+import gzip+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ FORMAT_ERROR,+ FileDelimiterError,+ FileFormatError,+ ResolvedFormat,+ iter_file_rows,+ normalize_delimiter,+ resolve_file_format,+)+++def csv_stream(text: str) -> io.BytesIO:+ return io.BytesIO(text.encode("utf-8"))+++class TestDelimiterNormalization:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ (None, None),+ ("", None),+ (",", ","),+ (";", ";"),+ ("\t", "\t"),+ ("\\t", "\t"),+ ("tab", "\t"),+ ],+ )+ def test_normalize_delimiter(self, raw: str | None, expected: str | None) -> None:+ assert normalize_delimiter(raw) == expected++ def test_normalize_delimiter_rejects_multiple_characters(self) -> None:+ with pytest.raises(FileDelimiterError, match="single character"):+ normalize_delimiter("||")+++class TestResolveFileFormat:+ @pytest.mark.parametrize(+ ("relative_path", "expected"),+ [+ ("orders.csv", ResolvedFormat("csv", ",", False)),+ ("orders.CSV", ResolvedFormat("csv", ",", False)),+ ("orders.tsv", ResolvedFormat("csv", "\t", False)),+ ("orders.txt", ResolvedFormat("csv", ",", False)),+ ("orders.jsonl", ResolvedFormat("jsonl", ",", False)),+ ("orders.ndjson", ResolvedFormat("jsonl", ",", False)),+ ("orders.json", ResolvedFormat("json", ",", False)),+ ("orders.csv.gz", ResolvedFormat("csv", ",", True)),+ ("orders.jsonl.gz", ResolvedFormat("jsonl", ",", True)),+ ],+ )+ def test_infers_from_extension(self, relative_path: str, expected: ResolvedFormat) -> None:+ assert resolve_file_format(relative_path, "infer") == expected++ def test_explicit_format_wins_over_extension(self) -> None:+ assert resolve_file_format("orders.txt", "jsonl") == ResolvedFormat("jsonl", ",", False)++ def test_explicit_delimiter_wins_over_extension_default(self) -> None:+ assert resolve_file_format("orders.tsv", "infer", ";") == ResolvedFormat("csv", ";", False)++ def test_unknown_extension_without_explicit_format_raises(self) -> None:+ with pytest.raises(FileFormatError, match=FORMAT_ERROR):+ resolve_file_format("orders.parquet", "infer")+++class TestIterFileRows:+ @parameterized.expand(+ [+ ("named", "Order Total (USD),name,Name", {"order_total_usd": "1", "name": "a", "name_2": "b"}),+ ("blank", "Order ID,,", {"order_id": "1", "column": "a", "column_2": "b"}),+ ]+ )+ def test_csv_headers_are_normalized_and_deduplicated(+ self, _name: str, headers: str, expected: dict[str, str]+ ) -> None:+ stream = csv_stream(f"{headers}\n1,a,b\n")++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))++ assert chunks == [[expected]]++ def test_csv_quoting_and_blank_lines(self) -> None:+ stream = csv_stream('a,b\n"x,y",2\n\n"multi\nline",3\n')++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))++ assert chunks == [[{"a": "x,y", "b": "2"}, {"a": "multi\nline", "b": "3"}]]++ def test_csv_short_rows_are_padded(self) -> None:+ stream = csv_stream("a,b,c\n1,2\n")++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))++ assert chunks == [[{"a": "1", "b": "2", "c": None}]]++ def test_csv_rows_with_extra_values_are_skipped_and_logged(self) -> None:+ stream = csv_stream("a,b\n1,2\n1,2,3\n")+ logger = MagicMock()++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", logger=logger))++ assert chunks == [[{"a": "1", "b": "2"}]]+ assert logger.warning.called++ def test_csv_uses_the_configured_delimiter(self) -> None:+ stream = csv_stream("a\tb\n1\t2\n")++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", "\t", False), "orders.tsv"))++ assert chunks == [[{"a": "1", "b": "2"}]]++ def test_gzipped_csv_is_decompressed(self) -> None:+ stream = io.BytesIO(gzip.compress(b"a,b\n1,2\n"))++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", True), "orders.csv.gz"))++ assert chunks == [[{"a": "1", "b": "2"}]]++ def test_rows_are_chunked(self) -> None:+ stream = csv_stream("a\n1\n2\n3\n4\n5\n")++ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", chunk_size=2))++ assert [len(chunk) for chunk in chunks] == [2, 2, 1]++ @pytest.mark.parametrize(+ ("payload", "file_format", "expected"),+ [+ (b'{"id": 1}\n{"id": 2}\n', "jsonl", [{"id": 1}, {"id": 2}]),+ (b'\n{"id": 1}\n\n', "jsonl", [{"id": 1}]),+ (b'[{"id": 1}, {"id": 2}]\n', "jsonl", [{"id": 1}, {"id": 2}]),+ (b'[{"id": 1}, {"id": 2}]', "json", [{"id": 1}, {"id": 2}]),+ (b'{"id": 1}', "json", [{"id": 1}]),+ (b'["a", "b"]', "json", [{"value": "a"}, {"value": "b"}]),+ ],+ )+ def test_json_shapes(self, payload: bytes, file_format: str, expected: list[dict[str, Any]]) -> None:+ resolved = ResolvedFormat(cast(Any, file_format), ",", False)++ chunks = list(iter_file_rows(io.BytesIO(payload), resolved, "orders.json"))++ assert [row for chunk in chunks for row in chunk] == expected++ def test_malformed_jsonl_line_reports_its_line_number(self) -> None:+ stream = io.BytesIO(b'{"id": 1}\nnot json\n')++ with pytest.raises(FileFormatError, match="Line 2"):+ list(iter_file_rows(stream, ResolvedFormat("jsonl", ",", False), "orders.jsonl"))++ def test_malformed_json_document_points_at_json_lines(self) -> None:+ stream = io.BytesIO(b'{"id": 1}\n{"id": 2}\n')++ with pytest.raises(FileFormatError, match="JSON Lines"):+ list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))++ def test_json_chunking(self) -> None:+ stream = io.BytesIO(b"[1, 2, 3]")++ chunks = list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json", chunk_size=2))++ assert [len(chunk) for chunk in chunks] == [2, 1]++ def test_oversized_json_document_is_rejected_before_it_is_parsed(self) -> None:+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing"+ stream = io.BytesIO(b"[" + b"0," * 100 + b"0]")++ with patch(f"{module}.MAX_JSON_DOCUMENT_BYTES", 8):+ with pytest.raises(FileFormatError, match="single JSON document"):+ list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.pyindex 7ade1bab197a..94b0f89fff56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sharepoint.py@@ -4,9 +4,16 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class SharePointImportFilesConfig(config.Config):+ enabled: bool = config.value(converter=config.str_to_bool, default=False)+ file_pattern: str | None = None++@config.configclass SharePointSourceConfig(config.Config):tenant_id: strclient_id: strclient_secret: strsite_urls: str | None = None+ import_files: SharePointImportFilesConfig | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.pyindex 788b327c21d0..d23aff8a0a88 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py@@ -1,19 +1,9 @@-from typing import Literal--FileFormat = Literal["csv", "jsonl", "json"]-ConfiguredFileFormat = Literal["infer", "csv", "jsonl", "json"]-DEFAULT_PORT = 22CONNECT_TIMEOUT_SECONDS = 30# Per-operation read timeout for directory and file transfers. A responsive server keeps data# flowing well within this, so it only trips on a stalled server holding an iterator thread.READ_TIMEOUT_SECONDS = 300-# A whole-document JSON file has to be materialized to parse it, so cap how many decompressed bytes-# we read before giving up and steering the user to JSON Lines (which streams). Also stops a small-# gzip file from decompressing into unbounded memory.-MAX_JSON_DOCUMENT_BYTES = 256 * 1024 * 1024-# Paramiko builds one prefetch descriptor per 32 KiB block up to the requested size, so a server that# reports an enormous file size could balloon that list. Cap it: bytes past this are read on demand.MAX_PREFETCH_BYTES = 256 * 1024 * 1024@@ -27,22 +17,3 @@ MAX_FILES = 1000# each level unbounded. Capping how many folders are ever queued bounds both the listing round trips# and the queue itself.MAX_DIRECTORIES = 1000--CHUNK_SIZE = 5000--# Every row carries which file it came from, so a table built from many files stays traceable.-FILE_PATH_COLUMN = "_file_name"-FILE_MODIFIED_AT_COLUMN = "_file_modified_at"--EXTENSION_FORMATS: dict[str, FileFormat] = {- ".csv": "csv",- ".tsv": "csv",- ".txt": "csv",- ".jsonl": "jsonl",- ".ndjson": "jsonl",- ".json": "json",-}--EXTENSION_DELIMITERS: dict[str, str] = {".tsv": "\t"}--DEFAULT_DELIMITER = ","diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.pyindex e72f0c58f44a..76a36acb5d8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py@@ -1,8 +1,4 @@-import ioimport re-import csv-import gzip-import jsonimport statimport socketimport posixpath@@ -11,7 +7,7 @@ from collections.abc import Generator, Iterable, Iteratorfrom contextlib import contextmanagerfrom datetime import UTC, datetimefrom io import StringIO-from typing import IO, Any, Protocol, cast+from typing import Any, Protocol, castimport re2import paramiko@@ -20,23 +16,25 @@ from structlog.types import FilteringBoundLoggerfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.models.ssh_tunnel import from_private_key-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import (+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (CHUNK_SIZE,- CONNECT_TIMEOUT_SECONDS,- DEFAULT_DELIMITER,- EXTENSION_DELIMITERS,- EXTENSION_FORMATS,FILE_MODIFIED_AT_COLUMN,FILE_PATH_COLUMN,+ ConfiguredFileFormat,+ FileDelimiterError,+ is_format_inferable,+ iter_file_rows,+ normalize_delimiter,+ resolve_file_format,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import (+ CONNECT_TIMEOUT_SECONDS,MAX_DIRECTORIES,MAX_DIRECTORY_DEPTH,MAX_FILES,- MAX_JSON_DOCUMENT_BYTES,MAX_PREFETCH_BYTES,READ_TIMEOUT_SECONDS,- ConfiguredFileFormat,- FileFormat,)# Error message prefixes. `get_non_retryable_errors` matches on these, so they have to stay stable@@ -48,18 +46,12 @@ DIRECTORY_ERROR = "Couldn't read the remote directory"PATTERN_ERROR = "The file pattern isn't a valid regular expression"NO_FILES_ERROR = "No remote files are available for table"NO_MATCHING_FILES_ERROR = "No importable files were found"-FORMAT_ERROR = "Can't work out the format of the remote file"-DELIMITER_ERROR = "The CSV delimiter must be a single character"class SFTPCredentialsError(Exception):"""A permanent configuration problem: unreachable host, rejected credentials, missing directory."""-class SFTPFileFormatError(Exception):- """A remote file couldn't be parsed with the configured (or inferred) format."""--class RemoteAttributes(Protocol):filename: strst_mode: int | None@@ -83,13 +75,6 @@ class RemoteFile:modified_at: datetime[email protected](frozen=True)-class ResolvedFormat:- file_format: FileFormat- delimiter: str- compressed: bool--def normalize_remote_path(path: str | None) -> str:stripped = (path or "").strip()if not stripped:@@ -98,19 +83,6 @@ def normalize_remote_path(path: str | None) -> str:return normalized.rstrip("/") or "/"-def normalize_delimiter(delimiter: str | None) -> str | None:- """Accept a literal tab, an escaped `\\t`, or the word `tab` for tab-separated files."""- if delimiter is None:- return None- if delimiter in ("\\t", "tab", "\t"):- return "\t"- if delimiter == "":- return None- if len(delimiter) != 1:- raise SFTPCredentialsError(f"{DELIMITER_ERROR} (got {delimiter!r}). Use \\t for tab-separated files.")- return delimiter--def load_private_key(private_key: str, passphrase: str | None = None) -> paramiko.PKey:try:return from_private_key(StringIO(private_key), passphrase or None)@@ -324,13 +296,6 @@ def group_files_by_table(return grouped-def is_format_inferable(relative_path: str) -> bool:- lowered = relative_path.lower()- if lowered.endswith(".gz"):- lowered = lowered[: -len(".gz")]- return posixpath.splitext(lowered)[1] in EXTENSION_FORMATS--def parseable_files(files: Iterable[RemoteFile], configured_format: ConfiguredFileFormat | str | None = "infer") -> list[RemoteFile]:@@ -344,167 +309,6 @@ def parseable_files(return [file for file in files if is_format_inferable(file.relative_path)]-def resolve_file_format(- relative_path: str,- configured_format: ConfiguredFileFormat | str | None = "infer",- delimiter: str | None = None,-) -> ResolvedFormat:- lowered = relative_path.lower()- compressed = lowered.endswith(".gz")- if compressed:- lowered = lowered[: -len(".gz")]- extension = posixpath.splitext(lowered)[1]-- if configured_format and configured_format != "infer":- file_format = cast(FileFormat, configured_format)- else:- inferred = EXTENSION_FORMATS.get(extension)- if inferred is None:- raise SFTPFileFormatError(- f"{FORMAT_ERROR} '{relative_path}'. Set the file format explicitly, or restrict the file "- "pattern to .csv, .json, or .jsonl files."- )- file_format = inferred-- resolved_delimiter = normalize_delimiter(delimiter) or EXTENSION_DELIMITERS.get(extension, DEFAULT_DELIMITER)- return ResolvedFormat(file_format=file_format, delimiter=resolved_delimiter, compressed=compressed)---def normalize_column_name(header: str) -> str:- """Headers like 'Order Total (USD)' become stable snake_case columns."""- normalized = re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()- return normalized or "column"---def _dedupe_headers(headers: list[str]) -> list[str]:- seen: dict[str, int] = {}- result = []- for header in headers:- name = normalize_column_name(header)- if name in seen:- seen[name] += 1- name = f"{name}_{seen[name]}"- else:- seen[name] = 1- result.append(name)- return result---def _decompressed_stream(stream: IO[bytes], compressed: bool) -> IO[bytes]:- return cast(IO[bytes], gzip.GzipFile(fileobj=stream)) if compressed else stream---def _text_stream(binary: IO[bytes]) -> IO[str]:- return io.TextIOWrapper(binary, encoding="utf-8", errors="replace", newline="")---def _iter_csv_rows(- text: IO[str],- delimiter: str,- relative_path: str,- chunk_size: int,- logger: FilteringBoundLogger | None,-) -> Iterator[list[dict[str, Any]]]:- reader = csv.reader(text, delimiter=delimiter)- headers: list[str] | None = None- chunk: list[dict[str, Any]] = []-- for line_number, row in enumerate(reader, start=1):- if headers is None:- headers = _dedupe_headers(row)- continue- if not any(cell.strip() for cell in row):- continue- if len(row) > len(headers):- # More values than headers means the file is malformed or the delimiter is wrong.- # Dropping the row keeps the extra values from silently landing in the wrong columns.- if logger is not None:- logger.warning(- "Skipping SFTP CSV row with more values than headers",- file=relative_path,- line=line_number,- expected=len(headers),- got=len(row),- )- continue- values: list[str | None] = [*row, *([None] * (len(headers) - len(row)))]- chunk.append(dict(zip(headers, values)))- if len(chunk) >= chunk_size:- yield chunk- chunk = []-- if chunk:- yield chunk---def _as_rows(value: Any) -> list[dict[str, Any]]:- if isinstance(value, dict):- return [value]- if isinstance(value, list):- return [item if isinstance(item, dict) else {"value": item} for item in value]- return [{"value": value}]---def _iter_jsonl_rows(text: IO[str], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:- chunk: list[dict[str, Any]] = []- for line_number, line in enumerate(text, start=1):- if not line.strip():- continue- try:- parsed = json.loads(line)- except json.JSONDecodeError as e:- raise SFTPFileFormatError(- f"Line {line_number} of '{relative_path}' isn't valid JSON: {e}. If the file holds one "- "JSON document rather than one object per line, set the file format to JSON."- ) from e- chunk.extend(_as_rows(parsed))- if len(chunk) >= chunk_size:- yield chunk- chunk = []- if chunk:- yield chunk---def _iter_json_rows(binary: IO[bytes], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:- # A whole-document JSON file can't be chunked, so it has to fit in memory. Read one decompressed- # byte past the limit to detect an oversized (or gzip-bomb) document before materializing it, and- # point the user at JSON Lines, which streams. The byte cap is what bounds memory here, so it runs- # on the decompressed bytes rather than a decoded-character count.- raw = binary.read(MAX_JSON_DOCUMENT_BYTES + 1)- if len(raw) > MAX_JSON_DOCUMENT_BYTES:- raise SFTPFileFormatError(- f"'{relative_path}' is larger than the {MAX_JSON_DOCUMENT_BYTES // (1024 * 1024)} MB limit for a "- "single JSON document. Convert it to JSON Lines (one object per line) so it can stream in."- )- try:- parsed = json.loads(raw)- except json.JSONDecodeError as e:- raise SFTPFileFormatError(- f"'{relative_path}' isn't valid JSON: {e}. If the file holds one JSON object per line, "- "set the file format to JSON Lines."- ) from e-- rows = _as_rows(parsed)- for start in range(0, len(rows), chunk_size):- yield rows[start : start + chunk_size]---def iter_file_rows(- stream: IO[bytes],- resolved: ResolvedFormat,- relative_path: str,- chunk_size: int = CHUNK_SIZE,- logger: FilteringBoundLogger | None = None,-) -> Iterator[list[dict[str, Any]]]:- binary = _decompressed_stream(stream, resolved.compressed)- if resolved.file_format == "csv":- yield from _iter_csv_rows(_text_stream(binary), resolved.delimiter, relative_path, chunk_size, logger)- elif resolved.file_format == "jsonl":- yield from _iter_jsonl_rows(_text_stream(binary), relative_path, chunk_size)- else:- yield from _iter_json_rows(binary, relative_path, chunk_size)--def iter_table_rows(client: RemoteClient,files: Iterable[RemoteFile],@@ -514,7 +318,10 @@ def iter_table_rows(logger: FilteringBoundLogger | None = None,) -> Iterator[list[dict[str, Any]]]:for file in files:- resolved = resolve_file_format(file.relative_path, configured_format, delimiter)+ try:+ resolved = resolve_file_format(file.relative_path, configured_format, delimiter)+ except FileDelimiterError as e:+ raise SFTPCredentialsError(str(e)) from ewith client.open(file.path, "rb") as handle:prefetch = getattr(handle, "prefetch", None)if callable(prefetch) and file.size:@@ -574,7 +381,10 @@ def validate_credentials("""_compile_pattern(file_pattern)# Catch a bad delimiter here rather than on every sync — it's a permanent misconfiguration.- normalize_delimiter(delimiter)+ try:+ normalize_delimiter(delimiter)+ except FileDelimiterError as e:+ raise SFTPCredentialsError(str(e)) from ewith sftp_connection(host=host, port=port, user=user, auth=auth) as client:files = parseable_files(list_remote_files(client, path, file_pattern), configured_format)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.pyindex c3c512119193..ca6d8b88d85f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py@@ -11,6 +11,10 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldSwitchGroupConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ DELIMITER_ERROR,+ FORMAT_ERROR,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema@@ -19,9 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (AUTH_FAILED_ERROR,CONNECTION_FAILED_ERROR,- DELIMITER_ERROR,DIRECTORY_ERROR,- FORMAT_ERROR,NO_FILES_ERROR,PATTERN_ERROR,PRIVATE_KEY_ERROR,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.pyindex f595c7a31819..b83e6486c35c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py@@ -1,5 +1,4 @@import io-import gzipimport statfrom collections.abc import Callable, Iteratorfrom contextlib import contextmanager@@ -14,34 +13,29 @@ from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import ed25519from paramiko.file import BufferedFile-from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import (+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ DELIMITER_ERROR,FILE_MODIFIED_AT_COLUMN,FILE_PATH_COLUMN,+ FileFormatError,)from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (AUTH_FAILED_ERROR,CONNECTION_FAILED_ERROR,- DELIMITER_ERROR,DIRECTORY_ERROR,- FORMAT_ERROR,NO_FILES_ERROR,NO_MATCHING_FILES_ERROR,PATTERN_ERROR,PRIVATE_KEY_ERROR,RemoteFile,- ResolvedFormat,SFTPAuth,SFTPCredentialsError,- SFTPFileFormatError,get_rows,group_files_by_table,- iter_file_rows,iter_table_rows,list_remote_files,load_private_key,- normalize_delimiter,normalize_remote_path,- resolve_file_format,sftp_connection,sftp_source,table_name_for_file,@@ -125,11 +119,7 @@ def make_file(relative_path: str, modified_at: datetime | None = None) -> Remote)-def csv_stream(text: str) -> io.BytesIO:- return io.BytesIO(text.encode("utf-8"))---class TestPathAndDelimiterNormalization:+class TestPathNormalization:@pytest.mark.parametrize(("raw", "expected"),[@@ -145,25 +135,6 @@ class TestPathAndDelimiterNormalization:def test_normalize_remote_path(self, raw: str | None, expected: str) -> None:assert normalize_remote_path(raw) == expected- @pytest.mark.parametrize(- ("raw", "expected"),- [- (None, None),- ("", None),- (",", ","),- (";", ";"),- ("\t", "\t"),- ("\\t", "\t"),- ("tab", "\t"),- ],- )- def test_normalize_delimiter(self, raw: str | None, expected: str | None) -> None:- assert normalize_delimiter(raw) == expected-- def test_normalize_delimiter_rejects_multiple_characters(self) -> None:- with pytest.raises(SFTPCredentialsError, match="single character"):- normalize_delimiter("||")-class TestListRemoteFiles:def _tree_client(self) -> FakeClient:@@ -312,133 +283,6 @@ class TestTableGrouping:assert [file.relative_path for file in grouped["daily_orders"]] == ["a.csv", "b.csv"]-class TestResolveFileFormat:- @pytest.mark.parametrize(- ("relative_path", "expected"),- [- ("orders.csv", ResolvedFormat("csv", ",", False)),- ("orders.CSV", ResolvedFormat("csv", ",", False)),- ("orders.tsv", ResolvedFormat("csv", "\t", False)),- ("orders.txt", ResolvedFormat("csv", ",", False)),- ("orders.jsonl", ResolvedFormat("jsonl", ",", False)),- ("orders.ndjson", ResolvedFormat("jsonl", ",", False)),- ("orders.json", ResolvedFormat("json", ",", False)),- ("orders.csv.gz", ResolvedFormat("csv", ",", True)),- ("orders.jsonl.gz", ResolvedFormat("jsonl", ",", True)),- ],- )- def test_infers_from_extension(self, relative_path: str, expected: ResolvedFormat) -> None:- assert resolve_file_format(relative_path, "infer") == expected-- def test_explicit_format_wins_over_extension(self) -> None:- assert resolve_file_format("orders.txt", "jsonl") == ResolvedFormat("jsonl", ",", False)-- def test_explicit_delimiter_wins_over_extension_default(self) -> None:- assert resolve_file_format("orders.tsv", "infer", ";") == ResolvedFormat("csv", ";", False)-- def test_unknown_extension_without_explicit_format_raises(self) -> None:- with pytest.raises(SFTPFileFormatError, match=FORMAT_ERROR):- resolve_file_format("orders.parquet", "infer")---class TestIterFileRows:- def test_csv_headers_are_normalized_and_deduplicated(self) -> None:- stream = csv_stream("Order Total (USD),name,Name\n1,a,b\n")-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))-- assert chunks == [[{"order_total_usd": "1", "name": "a", "name_2": "b"}]]-- def test_csv_quoting_and_blank_lines(self) -> None:- stream = csv_stream('a,b\n"x,y",2\n\n"multi\nline",3\n')-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))-- assert chunks == [[{"a": "x,y", "b": "2"}, {"a": "multi\nline", "b": "3"}]]-- def test_csv_short_rows_are_padded(self) -> None:- stream = csv_stream("a,b,c\n1,2\n")-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))-- assert chunks == [[{"a": "1", "b": "2", "c": None}]]-- def test_csv_rows_with_extra_values_are_skipped_and_logged(self) -> None:- stream = csv_stream("a,b\n1,2\n1,2,3\n")- logger = MagicMock()-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", logger=logger))-- assert chunks == [[{"a": "1", "b": "2"}]]- assert logger.warning.called-- def test_csv_uses_the_configured_delimiter(self) -> None:- stream = csv_stream("a\tb\n1\t2\n")-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", "\t", False), "orders.tsv"))-- assert chunks == [[{"a": "1", "b": "2"}]]-- def test_gzipped_csv_is_decompressed(self) -> None:- stream = io.BytesIO(gzip.compress(b"a,b\n1,2\n"))-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", True), "orders.csv.gz"))-- assert chunks == [[{"a": "1", "b": "2"}]]-- def test_rows_are_chunked(self) -> None:- stream = csv_stream("a\n1\n2\n3\n4\n5\n")-- chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", chunk_size=2))-- assert [len(chunk) for chunk in chunks] == [2, 2, 1]-- @pytest.mark.parametrize(- ("payload", "file_format", "expected"),- [- (b'{"id": 1}\n{"id": 2}\n', "jsonl", [{"id": 1}, {"id": 2}]),- (b'\n{"id": 1}\n\n', "jsonl", [{"id": 1}]),- (b'[{"id": 1}, {"id": 2}]\n', "jsonl", [{"id": 1}, {"id": 2}]),- (b'[{"id": 1}, {"id": 2}]', "json", [{"id": 1}, {"id": 2}]),- (b'{"id": 1}', "json", [{"id": 1}]),- (b'["a", "b"]', "json", [{"value": "a"}, {"value": "b"}]),- ],- )- def test_json_shapes(self, payload: bytes, file_format: str, expected: list[dict[str, Any]]) -> None:- resolved = ResolvedFormat(cast(Any, file_format), ",", False)-- chunks = list(iter_file_rows(io.BytesIO(payload), resolved, "orders.json"))-- assert [row for chunk in chunks for row in chunk] == expected-- def test_malformed_jsonl_line_reports_its_line_number(self) -> None:- stream = io.BytesIO(b'{"id": 1}\nnot json\n')-- with pytest.raises(SFTPFileFormatError, match="Line 2"):- list(iter_file_rows(stream, ResolvedFormat("jsonl", ",", False), "orders.jsonl"))-- def test_malformed_json_document_points_at_json_lines(self) -> None:- stream = io.BytesIO(b'{"id": 1}\n{"id": 2}\n')-- with pytest.raises(SFTPFileFormatError, match="JSON Lines"):- list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))-- def test_json_chunking(self) -> None:- stream = io.BytesIO(b"[1, 2, 3]")-- chunks = list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json", chunk_size=2))-- assert [len(chunk) for chunk in chunks] == [2, 1]-- def test_oversized_json_document_is_rejected_before_it_is_parsed(self) -> None:- module = "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp"- stream = io.BytesIO(b"[" + b"0," * 100 + b"0]")-- with patch(f"{module}.MAX_JSON_DOCUMENT_BYTES", 8):- with pytest.raises(SFTPFileFormatError, match="single JSON document"):- list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))--class TestIterTableRows:def test_adds_file_metadata_to_every_row_across_files(self) -> None:modified_at = datetime(2024, 3, 1, 12, tzinfo=UTC)@@ -474,7 +318,7 @@ class TestIterTableRows:def test_unparseable_file_format_propagates(self) -> None:client = FakeClient({}, contents={"/data/a.parquet": b"junk"})- with pytest.raises(SFTPFileFormatError):+ with pytest.raises(FileFormatError):list(iter_table_rows(client, [make_file("a.parquet")]))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.pyindex 4addd6a2c154..e4b95f675459 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py@@ -5,16 +5,18 @@ from typing import Any, castimport pytestfrom unittest.mock import MagicMock, patch+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ DELIMITER_ERROR,+ FILE_PATH_COLUMN,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sftp import (SFTPAuthTypeConfig,SFTPCombineFilesConfig,SFTPSourceConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import FILE_PATH_COLUMNfrom products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (AUTH_FAILED_ERROR,- DELIMITER_ERROR,DIRECTORY_ERROR,SFTPAuth,SFTPCredentialsError,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/files.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/files.pynew file mode 100644index 000000000000..971cdafe6271--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/files.py@@ -0,0 +1,373 @@+import re+import hashlib+import tempfile+import posixpath+from collections import Counter+from collections.abc import Iterator+from contextlib import contextmanager+from dataclasses import replace+from datetime import datetime+from typing import IO, Protocol, TypedDict, cast+from urllib.parse import quote++import re2+import requests+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.excel_parsing import (+ MAX_EXCEL_FILE_BYTES,+ ExcelFileError,+ iter_worksheet_rows,+ list_worksheets,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import (+ FILE_MODIFIED_AT_COLUMN,+ FILE_PATH_COLUMN,+ FORMAT_ERROR,+ FileFormatError,+ iter_file_rows,+ resolve_file_format,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (+ ENDPOINTS,+ EXCEL_EXTENSIONS,+ FILE_EXTENSIONS,+ FILE_NOT_FOUND_ERROR,+ MAX_EXCEL_FILES,+ MAX_FILES,+ PATTERN_ERROR,+ SharePointEndpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint import (+ SharePointClient,+ _list_sites,+ _parse_datetime,+ _site_parents,+ _status,+ _walk_child_collection,+ parse_site_urls,+)+++@frozen+class SharePointFile:+ drive_id: str+ item_id: str+ path: str+ size: int+ modified_at: datetime | None+ worksheet: str | None = None++ @property+ def is_excel(self) -> bool:+ return posixpath.splitext(self.path)[1].lower() in EXCEL_EXTENSIONS++ @property+ def resource_id(self) -> str:+ resource_id = f"{self.drive_id}:{self.item_id}"+ return f"{resource_id}:{self.worksheet}" if self.worksheet is not None else resource_id++ @property+ def label(self) -> str:+ return f"{self.path} [{self.worksheet}]" if self.worksheet is not None else self.path++ @property+ def description(self) -> str:+ if self.worksheet is not None:+ return f"Rows of the worksheet {self.worksheet} in the Excel file {self.path}"+ return f"Rows of the CSV file {self.path}"+++@frozen+class _Folder:+ name: str+ parent_id: str | None+++class _ParentReference(TypedDict, total=False):+ id: str+++class _DriveItem(TypedDict, total=False):+ id: str+ name: str+ parentReference: _ParentReference+ file: dict[str, object]+ folder: dict[str, object]+ root: dict[str, object]+ deleted: dict[str, object]+ size: int+ lastModifiedDateTime: str+++class CompiledPattern(Protocol):+ def search(self, string: str) -> object | None: ...+++class SharePointFilePatternError(ValueError):+ pass+++def compile_file_pattern(pattern: str | None) -> CompiledPattern | None:+ if not pattern:+ return None+ # RE2 bounds matching time for user-supplied patterns.+ try:+ return cast(CompiledPattern, re2.compile(pattern))+ except re2.error as error:+ raise SharePointFilePatternError(f"{PATTERN_ERROR}: {error}") from error+++def _without_compression(path: str) -> str:+ return path[:-3] if path.lower().endswith(".gz") else path+++def _is_supported_file(name: str) -> bool:+ return (+ posixpath.splitext(_without_compression(name))[1].lower() in FILE_EXTENSIONS+ or posixpath.splitext(name)[1].lower() in EXCEL_EXTENSIONS+ )+++def _in_drive_path(name: str, parent_id: str | None, folders: dict[str, _Folder]) -> str:+ segments = [name]+ seen: set[str] = set()+ while parent_id:+ if parent_id in seen or parent_id not in folders:+ return name+ seen.add(parent_id)+ folder = folders[parent_id]+ if folder.name:+ segments.append(folder.name)+ parent_id = folder.parent_id+ return "/".join(reversed(segments))+++def discover_files(+ client: SharePointClient,+ site_urls: str | None,+ file_pattern: str | None,+ logger: FilteringBoundLogger,+) -> list[SharePointFile]:+ pattern = compile_file_pattern(file_pattern)+ site_paths = parse_site_urls(site_urls)+ if not site_paths:+ raise ValueError("Enter at least one site URL to import file contents.")+ sites = _list_sites(client, site_paths, logger)+ files: dict[str, SharePointFile] = {}+ for site in sites:+ drives = _site_parents(client, SharePointEndpoint.DRIVE_ITEMS, quote(site["id"], safe=",.-"), logger)+ for drive in drives:+ items: dict[str, _DriveItem] = {}+ path = f"/drives/{quote(drive['id'], safe='!-_')}/root/delta"+ params = {"$select": "id,name,parentReference,file,folder,root,deleted,size,lastModifiedDateTime"}+ # Delta omits parent paths and can repeat items, so resolve paths after the final page.+ for page in _walk_child_collection(client, path, params, None, lambda _: None, logger):+ for raw_item in page:+ if raw_item.get("id"):+ raw_item.pop("@microsoft.graph.downloadUrl", None)+ items[raw_item["id"]] = cast(_DriveItem, raw_item)++ folders = {+ item_id: _Folder(+ name="" if "root" in item else item.get("name", ""),+ parent_id=None if "root" in item else (item.get("parentReference") or {}).get("id"),+ )+ for item_id, item in items.items()+ if ("folder" in item or "root" in item) and item.get("deleted") is None+ }+ for item_id, item in items.items():+ name = item.get("name", "")+ if item.get("deleted") is not None or item.get("file") is None or not _is_supported_file(name):+ continue+ in_drive_path = _in_drive_path(name, (item.get("parentReference") or {}).get("id"), folders)+ file_path = f"{drive['name']}/{in_drive_path}"+ if len(sites) > 1:+ file_path = f"{site.get('displayName') or site.get('name') or site['id']}/{file_path}"+ if pattern is not None and not pattern.search(file_path):+ continue+ resource_id = f"{drive['id']}:{item_id}"+ files[resource_id] = SharePointFile(+ drive_id=drive["id"],+ item_id=item_id,+ path=file_path,+ size=item.get("size") or 0,+ modified_at=_parse_datetime(item.get("lastModifiedDateTime")),+ )+ if len(files) >= MAX_FILES:+ logger.warning("Reached the SharePoint file limit; later files are ignored", max_files=MAX_FILES)+ return list(files.values())+ return list(files.values())+++def _item_path(drive_id: str, item_id: str) -> str:+ return f"/drives/{quote(drive_id, safe='!-_')}/items/{quote(item_id, safe='!-_')}"+++@contextmanager+def _download_excel(client: SharePointClient, path: str, file_name: str, size: int) -> Iterator[IO[bytes]]:+ def check_size(size: int) -> None:+ if size > MAX_EXCEL_FILE_BYTES:+ raise ExcelFileError(f"'{file_name}' exceeds the 100 MB size limit. Split the workbook into smaller files.")++ check_size(size)+ temporary = tempfile.SpooledTemporaryFile(max_size=8 * 1024 * 1024)+ try:+ response = client.open_stream(f"{path}/content")+ try:+ response.raw.decode_content = True+ copied = 0+ while block := response.raw.read(min(1024 * 1024, MAX_EXCEL_FILE_BYTES - copied + 1)):+ copied += len(block)+ check_size(copied)+ temporary.write(block)+ finally:+ response.close()+ temporary.seek(0)+ yield cast(IO[bytes], temporary)+ finally:+ temporary.close()+++def expand_worksheets(+ client: SharePointClient, files: list[SharePointFile], logger: FilteringBoundLogger+) -> list[SharePointFile]:+ excel_count = sum(file.is_excel for file in files)+ if excel_count > MAX_EXCEL_FILES:+ logger.warning(+ "Reached the SharePoint Excel file limit; later workbooks are ignored",+ max_excel_files=MAX_EXCEL_FILES,+ skipped_files=excel_count - MAX_EXCEL_FILES,+ )+ expanded: list[SharePointFile] = []+ examined = 0+ for file in files:+ if not file.is_excel:+ expanded.append(file)+ continue+ examined += 1+ if examined > MAX_EXCEL_FILES:+ continue+ try:+ with _download_excel(client, _item_path(file.drive_id, file.item_id), file.path, file.size) as stream:+ worksheets = list_worksheets(stream, file.path)+ expanded.extend(replace(file, worksheet=title) for title in worksheets)+ except ExcelFileError as error:+ logger.warning("Skipping unreadable SharePoint workbook", path=file.path, reason=str(error))+ except requests.HTTPError as error:+ if _status(error) != 404:+ raise+ logger.warning("Skipping missing SharePoint workbook", path=file.path)+ return expanded+++def _table_base(file: SharePointFile, limit: int) -> str:+ path = posixpath.splitext(_without_compression(file.path))[0]+ base = re.sub(r"[^0-9a-zA-Z]+", "_", path).strip("_").lower() or "sharepoint_data"+ if file.worksheet is None:+ return base[:limit]+ worksheet = re.sub(r"[^0-9a-zA-Z]+", "_", file.worksheet).strip("_").lower() or "worksheet"+ worksheet = worksheet[: limit - 2]+ return f"{base[: limit - len(worksheet) - 1]}_{worksheet}"+++def files_by_table(files: list[SharePointFile]) -> dict[str, SharePointFile]:+ bases = [_table_base(file, 100) for file in files]+ counts = Counter(bases)+ colliding = {base for base in bases if counts[base] > 1 or base in ENDPOINTS}+ suffixes = [hashlib.sha256(file.resource_id.encode()).hexdigest()[:8] for file in files]+ while True:+ names = [+ f"{_table_base(file, 91)}_{suffix}" if base in colliding else base+ for file, base, suffix in zip(files, bases, suffixes)+ ]+ name_counts = Counter(names)+ # A literal filename can also match another file's generated suffix.+ additional = {base for base, name in zip(bases, names) if name_counts[name] > 1} - colliding+ if not additional:+ return dict(zip(names, files))+ colliding.update(additional)+++def discover_file_tables(+ client: SharePointClient,+ site_urls: str | None,+ file_pattern: str | None,+ logger: FilteringBoundLogger,+) -> dict[str, SharePointFile]:+ files = discover_files(client, site_urls, file_pattern, logger)+ return files_by_table(expand_worksheets(client, files, logger))+++@contextmanager+def _deleted_file_error(schema_name: str) -> Iterator[None]:+ """A file deleted after discovery answers 404 to any of its requests."""+ try:+ yield+ except requests.HTTPError as error:+ if _status(error) != 404:+ raise+ raise ValueError(+ f"{FILE_NOT_FOUND_ERROR} '{schema_name}' no longer exists. "+ "It may have been deleted. Refresh the source's tables."+ ) from None+++def _get_file_rows(+ client: SharePointClient,+ schema_name: str,+ drive_id: str,+ item_id: str,+ logger: FilteringBoundLogger,+ worksheet: str | None = None,+) -> Iterator[list[dict[str, object]]]:+ path = _item_path(drive_id, item_id)+ with _deleted_file_error(schema_name):+ item = cast(_DriveItem, client.get(path, params={"$select": "name,size,lastModifiedDateTime"}))++ name = item["name"]+ modified_at = _parse_datetime(item.get("lastModifiedDateTime"))+ if worksheet is not None:+ if posixpath.splitext(name)[1].lower() not in EXCEL_EXTENSIONS:+ raise ExcelFileError(f"'{name}'. Save it as .xlsx again, then refresh the source's tables.")+ with (+ _deleted_file_error(schema_name),+ _download_excel(client, path, name, item.get("size") or 0) as stream,+ ):+ for chunk in iter_worksheet_rows(stream, name, worksheet, logger=logger):+ yield [{**row, FILE_PATH_COLUMN: name, FILE_MODIFIED_AT_COLUMN: modified_at} for row in chunk]+ return+ if posixpath.splitext(_without_compression(name))[1].lower() not in FILE_EXTENSIONS:+ raise FileFormatError(+ f"{FORMAT_ERROR} '{name}'. Use a CSV, TSV, or XLSX file, then refresh the source's tables."+ )+ resolved = resolve_file_format(name)+ with _deleted_file_error(schema_name):+ response = client.open_stream(f"{path}/content")+ try:+ response.raw.decode_content = True+ # TextIOWrapper must be able to read EOF without urllib3 closing its underlying stream.+ response.raw.auto_close = False+ for chunk in iter_file_rows(cast(IO[bytes], response.raw), resolved, name, logger=logger):+ yield [{**row, FILE_PATH_COLUMN: name, FILE_MODIFIED_AT_COLUMN: modified_at} for row in chunk]+ finally:+ response.close()+++def sharepoint_file_source(+ client: SharePointClient, schema_name: str, resource_id: str | None, logger: FilteringBoundLogger+) -> SourceResponse:+ parts = resource_id.split(":", 2) if resource_id else []+ if len(parts) not in (2, 3) or not all(parts):+ raise ValueError(f"{FILE_NOT_FOUND_ERROR} '{schema_name}' is not identified. Refresh the source's tables.")+ drive_id, item_id = parts[:2]+ worksheet = parts[2] if len(parts) == 3 else None+ return SourceResponse(+ name=schema_name,+ items=lambda: _get_file_rows(client, schema_name, drive_id, item_id, logger, worksheet),+ primary_keys=None,+ supports_resume=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.pyindex 98ba0ad10afe..81cc6dc76a16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/settings.py@@ -14,6 +14,13 @@ TOKEN_SCOPE = "https://graph.microsoft.com/.default"# Hard cap per collection walk so a `@odata.nextLink` that never ends can't spin forever. Far# above any realistic list or document library at Graph's default page sizes.MAX_PAGES_PER_COLLECTION = 50_000+MAX_FILES = 1000+FILE_EXTENSIONS = {".csv", ".tsv"}+EXCEL_EXTENSIONS = {".xlsx"}+# Discovery downloads each workbook to list its worksheets.+MAX_EXCEL_FILES = 100+FILE_NOT_FOUND_ERROR = "The SharePoint file for table"+PATTERN_ERROR = "The file pattern isn't a valid regular expression"SITE_ID_COLUMN = "site_id"LIST_ID_COLUMN = "list_id"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.pyindex f0d56c9a3551..0373e8d3809f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/sharepoint.py@@ -9,6 +9,7 @@ import structlogfrom structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.observer import redact_request_urlsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (@@ -188,6 +189,47 @@ class SharePointClient:return response.json()+ def open_stream(self, path: str) -> requests.Response:+ if path.startswith("/"):+ url = f"{GRAPH_BASE_URL}{path}"+ elif path.startswith(f"{GRAPH_BASE_URL}/"):+ url = path+ else:+ raise ValueError("Refusing to follow a non-Graph URL")++ if self._token is None:+ self.mint_token()++ def download() -> requests.Response:+ # Requests removes Authorization when Graph redirects to another host.+ with redact_request_urls():+ try:+ return self._session.get(+ url,+ headers={"Authorization": f"Bearer {self._token}", "Accept": "*/*"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ stream=True,+ )+ except requests.RequestException as error:+ raise type(error)("SharePoint file download failed. Try the sync again.") from None++ response = download()+ if response.status_code == 401:+ response.close()+ self.mint_token()+ response = download()++ if not response.ok:+ response.close()+ # The final response URL grants file access, so keep it out of error messages.+ error_type = "Client" if response.status_code < 500 else "Server"+ raise requests.HTTPError(+ f"{response.status_code} {error_type} Error: {response.reason} for url: {url}",+ response=response,+ )++ return response+def _status(error: requests.HTTPError) -> Optional[int]:return error.response.status_code if error.response is not None else Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.pyindex e04f63f5b4ae..9c7b50fa7638 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/source.py@@ -1,16 +1,22 @@from typing import Optional, cast+import structlog+from products.warehouse_sources.backend.facade.source_config import (DataWarehouseSourceCategory,ReleaseStatus,SourceConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldSwitchGroupConfig,)+from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEYfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.excel_parsing import EXCEL_ERROR+from products.warehouse_sources.backend.temporal.data_imports.sources.common.file_parsing import FORMAT_ERRORfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (@@ -21,15 +27,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sharepoint import (SharePointSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.files import (+ SharePointFilePatternError,+ compile_file_pattern,+ discover_file_tables,+ sharepoint_file_source,+)from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (ENDPOINTS,+ FILE_NOT_FOUND_ERROR,INCREMENTAL_FIELDS,+ PATTERN_ERROR,SHAREPOINT_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint import (INVALID_SITE_URL_ERROR,SITES_DENIED_ERROR,+ SharePointClient,SharePointResumeConfig,+ SharePointSiteURLError,+ parse_site_urls,sharepoint_source,validate_credentials as validate_sharepoint_credentials,)@@ -38,7 +55,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeConfig]):- lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ lists_tables_without_credentials = True # Placeholder configs leave file import off and need no network access.+ # A renamed or moved file keeps its drive item id.+ uses_stable_schema_resource_ids = True# `v1.0` is Microsoft Graph's only GA channel; `beta` is preview and not for production use.supported_versions = ("v1.0",)default_version = "v1.0"@@ -57,6 +76,15 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCdef get_non_retryable_errors(self) -> dict[str, str | None]:return {INVALID_SITE_URL_ERROR: None,+ FILE_NOT_FOUND_ERROR: "The SharePoint file is missing. Refresh the source's tables or restore the file.",+ FORMAT_ERROR: (+ "PostHog could not read the file format. Use a CSV, TSV, or XLSX file and refresh the source's tables."+ ),+ EXCEL_ERROR: (+ "PostHog could not read the Excel worksheet. Check that the worksheet exists and the file is under 100 MB. "+ "Save it as .xlsx again, then refresh the source's tables."+ ),+ PATTERN_ERROR: "The file pattern is not a valid regular expression. Fix the pattern and try again.","400 Client Error: Bad Request for url: https://login.microsoftonline.com": ("Entra ID rejected the app registration. Check the tenant ID, application (client) ID, ""and client secret."@@ -84,12 +112,35 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(+ schemas = build_endpoint_schemas(ENDPOINTS,INCREMENTAL_FIELDS,- names,descriptions={name: endpoint.description for name, endpoint in SHAREPOINT_ENDPOINTS.items()},)+ import_files = config.import_files+ if (+ import_files is not None+ and import_files.enabled+ and not (names is not None and all(name in ENDPOINTS for name in names))+ ):+ logger = structlog.get_logger(__name__)+ client = SharePointClient(config.tenant_id, config.client_id, config.client_secret, logger)+ tables = discover_file_tables(client, config.site_urls, import_files.file_pattern, logger)+ schemas.extend(+ SourceSchema(+ name=name,+ supports_incremental=False,+ supports_append=False,+ label=file.label,+ description=file.description,+ schema_metadata={SCHEMA_RESOURCE_ID_METADATA_KEY: file.resource_id},+ )+ for name, file in tables.items()+ )+ if names is not None:+ requested = set(names)+ schemas = [schema for schema in schemas if schema.name in requested]+ return schemasdef validate_credentials(self,@@ -98,6 +149,14 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:+ import_files = config.import_files+ if import_files is not None and import_files.enabled:+ try:+ if not parse_site_urls(config.site_urls):+ return False, "Enter at least one site URL to import file contents."+ compile_file_pattern(import_files.file_pattern)+ except (SharePointSiteURLError, SharePointFilePatternError) as error:+ return False, str(error)return validate_sharepoint_credentials(tenant_id=config.tenant_id,client_id=config.client_id,@@ -116,6 +175,14 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCresumable_source_manager: ResumableSourceManager[SharePointResumeConfig],inputs: SourceInputs,) -> SourceResponse:+ if inputs.schema_name not in ENDPOINTS:+ resource_id = (inputs.schema_metadata or {}).get(SCHEMA_RESOURCE_ID_METADATA_KEY)+ return sharepoint_file_source(+ SharePointClient(config.tenant_id, config.client_id, config.client_secret, inputs.logger),+ inputs.schema_name,+ resource_id if isinstance(resource_id, str) else None,+ inputs.logger,+ )return sharepoint_source(tenant_id=config.tenant_id,client_id=config.client_id,@@ -135,7 +202,7 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCkeywords=["microsoft", "sharepoint online", "office 365", "microsoft 365"],caption=("Sync SharePoint Online sites, lists and list items, document libraries, and file metadata "- "through Microsoft Graph.\n\n"+ "through Microsoft Graph. You can also import CSV and Excel file contents as separate tables.\n\n""Create an Entra ID app registration and add a client secret. Grant it the **Sites.Read.All** ""Microsoft Graph application permission and give admin consent. To limit access to a few ""sites, grant **Sites.Selected** instead and list those site URLs below. Then enter the "@@ -181,6 +248,33 @@ class SharePointSource(ResumableSource[SharePointSourceConfig, SharePointResumeCcaption="One site URL per line. Leave empty to sync every site the app can read.",secret=False,),+ SourceFieldSwitchGroupConfig(+ name="import_files",+ label="Import CSV and Excel file contents?",+ default=False,+ caption=(+ "Turn this on to create one table for each CSV file and each Excel worksheet "+ "in the document libraries of the sites above. Each sync reads the files in full. "+ "Excel files over 100 MB are skipped. Site URLs are required when this is on."+ ),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="file_pattern",+ label="File pattern (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder=r"^Shared Documents/reports/",+ caption=(+ "A regular expression matched against each file's path, which starts with the "+ "document library name. Leave it empty to import every CSV and Excel file."+ ),+ secret=False,+ ),+ ],+ ),+ ),],),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.pyindex 2c5573f8250d..3cc08848e524 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sharepoint/tests/test_sharepoint.py@@ -1,32 +1,63 @@+import io+import gzip+import hashlib+from collections.abc import Iterable+from dataclasses import replacefrom datetime import UTC, datetime-from typing import Any, Optional, Union+from http import HTTPStatus+from typing import Any, Optional, Union, castimport pytestfrom unittest import mockimport requests+import responses+from openpyxl import Workbookfrom parameterized import parameterized+from structlog.testing import capture_logs+from urllib3.response import HTTPResponse+from products.warehouse_sources.backend.models.external_data_schema import SCHEMA_RESOURCE_ID_METADATA_KEY+from products.warehouse_sources.backend.temporal.data_imports.sources.common.excel_parsing import (+ EXCEL_ERROR,+ ExcelFileError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sharepoint import (+ SharePointSourceConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.canonical_descriptions import (CANONICAL_DESCRIPTIONS,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.files import (+ SharePointFile,+ discover_files,+ files_by_table,+ sharepoint_file_source,+)from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.settings import (ENDPOINTS,+ FILE_NOT_FOUND_ERROR,GRAPH_BASE_URL,+ MAX_FILES,+ PATTERN_ERROR,SHAREPOINT_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint import (INVALID_SITE_URL_ERROR,SITES_DENIED_ERROR,+ SharePointClient,SharePointResumeConfig,SharePointSiteURLError,_get_rows,parse_site_urls,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.source import SharePointSourceMODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.sharepoint"+FILES_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sharepoint.files"TENANT_ID = "11111111-1111-1111-1111-111111111111"CLIENT_ID = "22222222-2222-2222-2222-222222222222"@@ -35,12 +66,13 @@ CLIENT_SECRET = "super-secret"SITE_A = "contoso.sharepoint.com,aaaa,1111"SITE_B = "contoso.sharepoint.com,bbbb,2222"-Route = Union[dict[str, Any], int]+Route = Union[dict[str, Any], int, bytes]def _response(status: int = 200, json_body: Any = None) -> mock.MagicMock:response = mock.MagicMock(spec=requests.Response)response.status_code = status+ response.reason = HTTPStatus(status).phraseresponse.ok = 200 <= status < 300response.text = ""response.json.return_value = json_body if json_body is not None else {}@@ -62,6 +94,10 @@ def _session(routes: dict[str, Route], post_responses: Optional[list[mock.MagicMroute = routes[url]if isinstance(route, int):return _response(route)+ if isinstance(route, bytes):+ response = _response()+ response.raw = HTTPResponse(body=io.BytesIO(route), preload_content=False)+ return responsereturn _response(200, route)session.get.side_effect = _get@@ -302,3 +338,625 @@ def test_canonical_descriptions_document_every_primary_key() -> None:assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)for name, entry in CANONICAL_DESCRIPTIONS.items():assert set(SHAREPOINT_ENDPOINTS[name].primary_keys) <= set(entry["columns"])+++SITE_URL = "https://contoso.sharepoint.com/sites/a"+++def excel_bytes() -> bytes:+ workbook = Workbook()+ try:+ first = workbook.worksheets[0]+ first.title = "Sales - North"+ first.append(["Order ID", "total"])+ first.append([1, 20])+ workbook.create_sheet("Hidden").sheet_state = "hidden"+ workbook.create_sheet("Sales South").append(["id"])+ workbook.create_sheet("Very hidden").sheet_state = "veryHidden"+ stream = io.BytesIO()+ workbook.save(stream)+ return stream.getvalue()+ finally:+ workbook.close()+++def file_routes(items: list[dict[str, object]]) -> dict[str, Route]:+ return {+ _g("/sites/contoso.sharepoint.com:/sites/a:"): {"id": SITE_A, "displayName": "Site A"},+ _g(f"/sites/{SITE_A}/drives"): {"value": [{"id": "drive-a", "name": "Shared Documents"}]},+ _g("/drives/drive-a/root/delta"): {"value": items},+ }+++def _discover(session: mock.MagicMock, pattern: str | None = None, site_urls: str = SITE_URL) -> list[SharePointFile]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ client = SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger)+ return discover_files(client, site_urls, pattern, logger)+++class TestSharePointFileDiscovery:+ @parameterized.expand(+ [+ ("nested", "nested", "reports/2026/orders.csv"),+ ("root", "root", "orders.csv"),+ ("missing", "missing", "orders.csv"),+ ("missing_ancestor", "orphan", "orders.csv"),+ ("cycle", "cycle", "orders.csv"),+ ]+ )+ def test_resolves_parent_ids_across_pages(self, _name: str, parent: str, expected: str) -> None:+ routes = file_routes([{"id": "file-1", "name": "orders.csv", "file": {}, "parentReference": {"id": parent}}])+ cast(dict[str, object], routes[_g("/drives/drive-a/root/delta")])["@odata.nextLink"] = _g(+ "/drives/drive-a/root/delta?page=2"+ )+ routes[_g("/drives/drive-a/root/delta?page=2")] = {+ "value": [+ {"id": "root", "name": "Ignored root name", "root": {}, "folder": {}},+ {"id": "reports", "name": "reports", "folder": {}, "parentReference": {"id": "root"}},+ {"id": "nested", "name": "2026", "folder": {}, "parentReference": {"id": "reports"}},+ {"id": "orphan", "name": "lost", "folder": {}, "parentReference": {"id": "missing"}},+ {"id": "cycle", "name": "loop", "folder": {}, "parentReference": {"id": "cycle"}},+ ]+ }++ files = _discover(_session(routes))++ assert [file.path for file in files] == [f"Shared Documents/{expected}"]++ @parameterized.expand(+ [+ ("all", None, ["latest.CSV", "compressed.csv.gz", "tabs.TSV.GZ", "book.XLSX"]),+ ("search", r"Documents/latest", ["latest.CSV"]),+ ("no_match", r"^reports/", []),+ ]+ )+ def test_filters_final_delta_state(self, _name: str, pattern: str | None, expected: list[str]) -> None:+ routes = file_routes(+ [+ {"id": "renamed", "name": "old.csv", "file": {}},+ {"id": "deleted-later", "name": "gone.csv", "file": {}},+ {"id": "folder", "name": "folder.csv", "folder": {}},+ {"id": "text", "name": "notes.txt", "file": {}},+ {"id": "json", "name": "data.json", "file": {}},+ {"id": "xls", "name": "legacy.xls", "file": {}},+ {"id": "xlsm", "name": "macros.xlsm", "file": {}},+ {"id": "xlsx-gz", "name": "book.xlsx.gz", "file": {}},+ {"id": "deleted", "name": "deleted.csv", "file": {}, "deleted": {}},+ ]+ )+ cast(dict[str, object], routes[_g("/drives/drive-a/root/delta")])["@odata.nextLink"] = _g(+ "/drives/drive-a/root/delta?page=2"+ )+ routes[_g("/drives/drive-a/root/delta?page=2")] = {+ "value": [+ {"id": "renamed", "name": "latest.CSV", "file": {}},+ {"id": "deleted-later", "deleted": {}},+ {"id": "gzip", "name": "compressed.csv.gz", "file": {}},+ {"id": "tsv", "name": "tabs.TSV.GZ", "file": {}},+ {"id": "xlsx", "name": "book.XLSX", "file": {}},+ ]+ }++ files = _discover(_session(routes), pattern)++ assert [file.path for file in files] == [f"Shared Documents/{name}" for name in expected]++ def test_prefixes_each_site_when_multiple_sites_are_selected(self) -> None:+ routes = file_routes([{"id": "file-a", "name": "orders.csv", "file": {}}])+ routes.update(+ {+ _g("/sites/contoso.sharepoint.com:/sites/b:"): {"id": SITE_B, "name": "Site B"},+ _g(f"/sites/{SITE_B}/drives"): {"value": [{"id": "drive-b", "name": "Shared Documents"}]},+ _g("/drives/drive-b/root/delta"): {"value": [{"id": "file-b", "name": "orders.csv", "file": {}}]},+ }+ )++ files = _discover(_session(routes), site_urls=f"{SITE_URL}\nhttps://contoso.sharepoint.com/sites/b")++ assert [file.path for file in files] == [+ "Site A/Shared Documents/orders.csv",+ "Site B/Shared Documents/orders.csv",+ ]++ def test_stops_after_the_matched_file_limit(self) -> None:+ items: list[dict[str, Any]] = [+ {"id": "unmatched", "name": "skip.csv", "file": {}},+ *[{"id": str(index), "name": f"match-{index}.csv", "file": {}} for index in range(MAX_FILES + 1)],+ ]+ session = _session(file_routes(items))+ logger = mock.MagicMock()+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ client = SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger)+ files = discover_files(client, SITE_URL, "match-", logger)++ assert len(files) == MAX_FILES+ assert files[-1].item_id == str(MAX_FILES - 1)+ logger.warning.assert_called_once()+++def _file(path: str, item_id: str = "item-a") -> SharePointFile:+ return SharePointFile(drive_id="drive-a", item_id=item_id, path=path, size=10, modified_at=None)+++class TestSharePointFileNames:+ @parameterized.expand(+ [+ ("plain", "Shared Documents/Reports/Orders.CSV.GZ", "shared_documents_reports_orders"),+ ("static_collision", "sites.csv", "sites_bb1b37bb"),+ ("long", "a" * 120 + ".csv", "a" * 100),+ ]+ )+ def test_names_files(self, _name: str, path: str, expected: str) -> None:+ file = _file(path)+ assert files_by_table([file]) == {expected: file}++ @parameterized.expand(+ [+ ("normalized", "Orders 2026.csv", "orders-2026.csv", "orders_2026"),+ ("truncated", "a" * 101 + ".csv", "a" * 102 + ".csv", "a" * 91),+ ]+ )+ def test_suffixes_every_collision_independently_of_order(+ self, _name: str, first_path: str, second_path: str, base: str+ ) -> None:+ files = [_file(first_path, "item-a"), _file(second_path, "item-b")]+ expected = {+ f"{base}_{hashlib.sha256(f'{file.drive_id}:{file.item_id}'.encode()).hexdigest()[:8]}": file+ for file in files+ }++ assert files_by_table(files) == expected+ assert files_by_table(list(reversed(files))) == expected+ assert all(len(name) <= 100 for name in expected)++ def test_literal_hash_suffix_does_not_replace_another_file(self) -> None:+ suffix = hashlib.sha256(b"drive-a:item-a").hexdigest()[:8]+ files = [_file("orders.csv"), _file("orders.tsv", "item-b"), _file(f"orders_{suffix}.csv", "item-c")]++ tables = files_by_table(files)++ assert set(tables.values()) == set(files)+ assert tables == files_by_table(list(reversed(files)))++ @parameterized.expand(+ [+ ("long_file", "a" * 120, "Sales - North", "a" * 88 + "_sales_north"),+ ("long_worksheet", "report", "w" * 120, "r_" + "w" * 98),+ ]+ )+ def test_truncates_file_before_worksheet(self, _name: str, path: str, worksheet: str, expected: str) -> None:+ file = replace(_file(path + ".xlsx"), worksheet=worksheet)++ assert files_by_table([file]) == {expected: file}++ def test_worksheet_collisions_hash_the_full_resource_id(self) -> None:+ files = [replace(_file("a" * 120 + ".xlsx"), worksheet=title) for title in ("Sales - North", "Sales North")]+ expected = {+ f"{'a' * 79}_sales_north_{hashlib.sha256(file.resource_id.encode()).hexdigest()[:8]}": file+ for file in files+ }++ assert files_by_table(files) == expected+ assert files_by_table(list(reversed(files))) == expected+ assert all(len(name) == 100 for name in expected)+++class TestSharePointFileSync:+ def test_worksheet_rows_include_file_metadata(self) -> None:+ content = excel_bytes()+ session = _session(+ {+ _g("/drives/drive-a/items/item-a"): {+ "name": "renamed.xlsx",+ "size": len(content),+ "lastModifiedDateTime": "2026-01-02T03:04:05Z",+ },+ _g("/drives/drive-a/items/item-a/content"): content,+ }+ )+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ file = replace(_file("old.xlsx"), worksheet="Sales - North")+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger), "old_table", file.resource_id, logger+ )+ rows = [row for chunk in cast(Iterable[list[dict[str, object]]], response.items()) for row in chunk]++ assert rows == [+ {+ "order_id": 1,+ "total": 20,+ "_file_name": "renamed.xlsx",+ "_file_modified_at": datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ }+ ]++ @parameterized.expand([("reported", 51), ("grew", 1)])+ def test_rejects_oversized_workbook_at_sync(self, _name: str, reported_size: int) -> None:+ session = _session(+ {+ _g("/drives/drive-a/items/item-a"): {"name": "report.xlsx", "size": reported_size},+ _g("/drives/drive-a/items/item-a/content"): excel_bytes(),+ }+ )+ with (+ mock.patch(f"{MODULE}.make_tracked_session", return_value=session),+ mock.patch(f"{FILES_MODULE}.MAX_EXCEL_FILE_BYTES", 50),+ ):+ logger = mock.MagicMock()+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger),+ "report",+ "drive-a:item-a:Sales - North",+ logger,+ )+ with pytest.raises(ExcelFileError, match=f"^{EXCEL_ERROR}"):+ list(cast(Iterable[object], response.items()))++ @parameterized.expand(+ [+ ("csv", "renamed.csv", b"Order ID,total\n1,20\n"),+ ("tsv", "renamed.tsv", b"Order ID\ttotal\n1\t20\n"),+ ("gzip", "renamed.csv.gz", gzip.compress(b"Order ID,total\n1,20\n")),+ ]+ )+ def test_streams_rows_with_current_file_metadata(self, _name: str, name: str, content: bytes) -> None:+ download = _response()+ download.raw = HTTPResponse(body=io.BytesIO(content), preload_content=False)+ session = _session({})+ session.get.side_effect = [+ _response(200, {"name": name, "size": len(content), "lastModifiedDateTime": "2026-01-02T03:04:05Z"}),+ download,+ ]+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger),+ "original_table",+ "drive-a:item-a",+ logger,+ )+ rows = [row for chunk in cast(Iterable[list[dict[str, object]]], response.items()) for row in chunk]++ assert rows == [+ {+ "order_id": "1",+ "total": "20",+ "_file_name": name,+ "_file_modified_at": datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ }+ ]+ assert response.name == "original_table"+ assert response.primary_keys is None+ assert response.supports_resume is False+ assert session.get.call_args.args == (_g("/drives/drive-a/items/item-a/content"),)+ assert session.get.call_args.kwargs["stream"] is True+ assert session.get.call_args.kwargs["headers"]["Accept"] == "*/*"+ download.json.assert_not_called()+ download.close.assert_called_once()+ assert download.raw.decode_content is True++ @parameterized.expand(+ [+ ("missing_id", None, 0),+ ("malformed_id", "drive-a:", 0),+ ("deleted", "drive-a:item-a", 1),+ ("deleted_excel", "drive-a:item-a:Sales - North", 1),+ ("empty_worksheet", "drive-a:item-a:", 0),+ ]+ )+ def test_reports_missing_files(self, _name: str, resource_id: str | None, expected_requests: int) -> None:+ session = _session({_g("/drives/drive-a/items/item-a"): 404})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ with pytest.raises(ValueError, match=f"^{FILE_NOT_FOUND_ERROR}"):+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger), "orders", resource_id, logger+ )+ list(cast(Iterable[object], response.items()))++ assert session.get.call_count == expected_requests++ @parameterized.expand([("csv", "orders.csv", None), ("excel", "report.xlsx", "Sales - North")])+ def test_reports_files_deleted_before_download(self, _name: str, file_name: str, worksheet: str | None) -> None:+ session = _session(+ {_g("/drives/drive-a/items/item-a"): {"name": file_name}, _g("/drives/drive-a/items/item-a/content"): 404}+ )+ resource_id = "drive-a:item-a" + (f":{worksheet}" if worksheet else "")+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ with pytest.raises(ValueError, match=f"^{FILE_NOT_FOUND_ERROR}"):+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger), "orders", resource_id, logger+ )+ list(cast(Iterable[object], response.items()))++ assert session.get.call_count == 2++ @parameterized.expand([("refresh_success", 200), ("refresh_rejected", 401)])+ def test_content_request_refreshes_once(self, _name: str, final_status: int) -> None:+ first = _response(401)+ final = _response(final_status)+ session = _session({}, post_responses=[_token_response(), _token_response()])+ session.get.side_effect = [first, final]+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ client = SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())+ if final_status == 401:+ with pytest.raises(requests.HTTPError):+ client.open_stream("/drives/drive-a/items/item-a/content")+ final.close.assert_called_once()+ else:+ assert client.open_stream("/drives/drive-a/items/item-a/content") is final++ assert session.post.call_count == 2+ assert session.get.call_count == 2+ first.close.assert_called_once()++ def test_closes_download_when_parsing_fails(self) -> None:+ download = _response()+ download.raw = io.BytesIO(b"invalid gzip")+ session = _session({})+ session.get.side_effect = [_response(200, {"name": "orders.csv.gz"}), download]+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ logger = mock.MagicMock()+ response = sharepoint_file_source(+ SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, logger), "orders", "drive-a:item-a", logger+ )+ with pytest.raises(gzip.BadGzipFile):+ list(cast(Iterable[object], response.items()))++ download.close.assert_called_once()++ def test_refuses_non_graph_initial_download_url(self) -> None:+ session = _session({})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ client = SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())+ with pytest.raises(ValueError, match="non-Graph URL"):+ client.open_stream("https://example.com/content")++ session.get.assert_not_called()+ session.post.assert_not_called()++ @parameterized.expand([("success", 200), ("denied", 403)])+ def test_redirect_drops_authorization_and_keeps_download_urls_out_of_logs(self, _name: str, status: int) -> None:+ download_url = "https://download.example.com/temporary-file-secret?access=temporary-query-secret"+ client = SharePointClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())+ content_url = _g("/drives/drive-a/items/item-a/content")+ with responses.RequestsMock() as http, capture_logs() as logs:+ http.post(client.token_url, json={"access_token": "token-1"})+ http.get(content_url, status=302, headers={"Location": download_url})+ http.get(download_url, status=status, body=b"id\n1\n")+ http.get(_g("/sites/site-a"), json={"id": "site-a"})++ if status == 200:+ with client.open_stream(content_url) as response:+ assert response.content == b"id\n1\n"+ else:+ with pytest.raises(requests.HTTPError) as error:+ client.open_stream(content_url)+ assert "temporary-file-secret" not in str(error.value)+ assert "temporary-query-secret" not in str(error.value)+ client.get("/sites/site-a")++ assert http.calls[1].request.headers["Authorization"] == "Bearer token-1"+ assert "Authorization" not in http.calls[2].request.headers++ assert "temporary-file-secret" not in str(logs)+ assert "temporary-query-secret" not in str(logs)+ assert any(log.get("url") == "REDACTED" for log in logs)+ assert any(log.get("url") == _g("/sites/site-a") for log in logs)+++def make_config(+ enabled: bool | None = True, site_urls: str | None = SITE_URL, pattern: str | None = None+) -> SharePointSourceConfig:+ values: dict[str, object] = {+ "tenant_id": TENANT_ID,+ "client_id": CLIENT_ID,+ "client_secret": CLIENT_SECRET,+ "site_urls": site_urls,+ }+ if enabled is not None:+ values["import_files"] = {"enabled": enabled, "file_pattern": pattern}+ return SharePointSourceConfig.from_dict(values)+++def make_inputs(schema_name: str, resource_id: str | None) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=mock.MagicMock(),+ reset_pipeline=False,+ schema_metadata={SCHEMA_RESOURCE_ID_METADATA_KEY: resource_id} if resource_id is not None else None,+ )+++class TestSharePointSchemas:+ def test_discovers_one_table_per_visible_worksheet(self) -> None:+ routes = file_routes([{"id": "item-a", "name": "report.xlsx", "file": {}}])+ routes[_g("/drives/drive-a/items/item-a/content")] = excel_bytes()+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=_session(routes)):+ schemas = SharePointSource().get_schemas(make_config(), team_id=1)++ assert [+ (schema.name, schema.label, schema.description, schema.schema_metadata)+ for schema in schemas+ if schema.schema_metadata+ ] == [+ (+ "shared_documents_report_sales_north",+ "Shared Documents/report.xlsx [Sales - North]",+ "Rows of the worksheet Sales - North in the Excel file Shared Documents/report.xlsx",+ {SCHEMA_RESOURCE_ID_METADATA_KEY: "drive-a:item-a:Sales - North"},+ ),+ (+ "shared_documents_report_sales_south",+ "Shared Documents/report.xlsx [Sales South]",+ "Rows of the worksheet Sales South in the Excel file Shared Documents/report.xlsx",+ {SCHEMA_RESOURCE_ID_METADATA_KEY: "drive-a:item-a:Sales South"},+ ),+ ]++ @parameterized.expand([("reported_size",), ("download_size",), ("corrupt",), ("missing",)])+ def test_skips_unreadable_workbooks_and_keeps_sibling_csv(self, case: str) -> None:+ routes = file_routes(+ [+ {"id": "item-a", "name": "report.xlsx", "file": {}, "size": 51 if case == "reported_size" else 1},+ {"id": "csv", "name": "orders.csv", "file": {}},+ ]+ )+ routes[_g("/drives/drive-a/items/item-a/content")] = (+ 404 if case == "missing" else b"not a zip" if case == "corrupt" else excel_bytes()+ )+ session = _session(routes)+ with (+ mock.patch(f"{MODULE}.make_tracked_session", return_value=session),+ mock.patch(f"{FILES_MODULE}.MAX_EXCEL_FILE_BYTES", 50),+ capture_logs() as logs,+ ):+ schemas = SharePointSource().get_schemas(make_config(), team_id=1)++ assert [schema.name for schema in schemas if schema.schema_metadata] == ["shared_documents_orders"]+ assert any(+ log.get("log_level") == "warning" and log.get("path") == "Shared Documents/report.xlsx" for log in logs+ )+ if case == "reported_size":+ assert not any(call.args[0].endswith("/content") for call in session.get.call_args_list)++ def test_caps_excel_downloads_in_discovery_order(self) -> None:+ routes = file_routes(+ [+ {"id": "first", "name": "first.xlsx", "file": {}},+ {"id": "second", "name": "second.xlsx", "file": {}},+ {"id": "csv", "name": "orders.csv", "file": {}},+ ]+ )+ routes[_g("/drives/drive-a/items/first/content")] = excel_bytes()+ session = _session(routes)+ with (+ mock.patch(f"{MODULE}.make_tracked_session", return_value=session),+ mock.patch(f"{FILES_MODULE}.MAX_EXCEL_FILES", 1),+ capture_logs() as logs,+ ):+ schemas = SharePointSource().get_schemas(make_config(), team_id=1)++ assert [schema.name for schema in schemas if schema.schema_metadata] == [+ "shared_documents_first_sales_north",+ "shared_documents_first_sales_south",+ "shared_documents_orders",+ ]+ assert any(log.get("log_level") == "warning" and log.get("skipped_files") == 1 for log in logs)+ assert not any("second/content" in call.args[0] for call in session.get.call_args_list)++ @parameterized.expand(+ [+ ("absent", None, None),+ ("off", False, None),+ ("static_names", True, ["drives"]),+ ("empty_names", True, []),+ ]+ )+ def test_static_catalog_needs_no_requests(self, _name: str, enabled: bool | None, names: list[str] | None) -> None:+ session = _session({})+ source = SharePointSource()+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ expected = source.get_schemas(make_config(enabled=None, site_urls=None), team_id=1, names=names)+ schemas = source.get_schemas(make_config(enabled=enabled, site_urls=None), team_id=1, names=names)++ assert schemas == expected+ session.get.assert_not_called()+ session.post.assert_not_called()++ @parameterized.expand(+ [+ ("all", None),+ ("combined_names", ["sites", "shared_documents_orders"]),+ ]+ )+ def test_discovers_file_schemas_with_resource_ids(self, _name: str, names: list[str] | None) -> None:+ session = _session(file_routes([{"id": "item-a", "name": "orders.csv", "file": {}}]))+ source = SharePointSource()+ static = source.get_schemas(make_config(enabled=False), team_id=1, names=names)+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ schemas = source.get_schemas(make_config(), team_id=1, names=names)++ assert schemas[:-1] == static+ file = schemas[-1]+ assert file.name == "shared_documents_orders"+ assert file.label == "Shared Documents/orders.csv"+ assert file.description == "Rows of the CSV file Shared Documents/orders.csv"+ assert file.schema_metadata == {SCHEMA_RESOURCE_ID_METADATA_KEY: "drive-a:item-a"}+ assert not file.supports_append and not file.supports_incremental+++class TestSharePointCredentialValidation:+ @parameterized.expand(+ [+ ("missing_sites", None, None, "Enter at least one site URL to import file contents."),+ ("blank_sites", " ,\n ", None, "Enter at least one site URL to import file contents."),+ ("invalid_pattern", SITE_URL, "([", PATTERN_ERROR),+ ]+ )+ def test_rejects_invalid_file_settings_without_http(+ self, _name: str, site_urls: str | None, pattern: str | None, expected: str+ ) -> None:+ session = _session({})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ valid, error = SharePointSource().validate_credentials(make_config(site_urls=site_urls, pattern=pattern), 1)++ assert valid is False+ assert error is not None and error.startswith(expected)+ session.get.assert_not_called()+ session.post.assert_not_called()++ def test_validates_the_site_without_discovering_files(self) -> None:+ session = _session({_g("/sites/contoso.sharepoint.com:/sites/a:"): {"id": SITE_A}})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ assert SharePointSource().validate_credentials(make_config(pattern=r"\.csv$"), 1) == (True, None)++ assert session.get.call_count == 1+++class TestSharePointPipeline:+ @parameterized.expand([("static", "sites", None), ("file", "old_table_name", "drive-a:item-a")])+ def test_routes_static_tables_and_stored_file_ids(+ self, _name: str, schema_name: str, resource_id: str | None+ ) -> None:+ session = _session(+ {+ _g("/sites/contoso.sharepoint.com:/sites/a:"): {"id": SITE_A},+ _g("/drives/drive-a/items/item-a"): {"name": "new-name.csv"},+ _g("/drives/drive-a/items/item-a/content"): b"id\n1\n",+ }+ )+ manager = _manager()+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ response = SharePointSource().source_for_pipeline(+ make_config(), manager, make_inputs(schema_name, resource_id)+ )+ rows = [row for chunk in cast(Iterable[list[dict[str, object]]], response.items()) for row in chunk]++ if resource_id is None:+ assert rows == [{"id": SITE_A}]+ else:+ assert rows == [{"id": "1", "_file_name": "new-name.csv", "_file_modified_at": None}]+ assert response.supports_resume is False+ manager.save_state.assert_not_called()++ def test_missing_metadata_fails_before_http(self) -> None:+ session = _session({})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ with pytest.raises(ValueError, match=f"^{FILE_NOT_FOUND_ERROR}"):+ SharePointSource().source_for_pipeline(make_config(), _manager(), make_inputs("orders", None))++ session.get.assert_not_called()+ session.post.assert_not_called()