dq-export-connector 0.1.0.dev22__tar.gz → 0.1.0.dev23__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/PKG-INFO +2 -2
  2. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/README.md +1 -1
  3. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/datasets.py +8 -8
  4. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/export.py +22 -22
  5. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/paths.py +3 -3
  6. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/store.py +16 -17
  7. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/upload.py +7 -7
  8. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/validate.py +15 -7
  9. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/log.py +1 -1
  10. dq_export_connector-0.1.0.dev22/dq_export_connector/report.py → dq_export_connector-0.1.0.dev23/dq_export_connector/outcome.py +7 -7
  11. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/redact.py +5 -5
  12. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/runner.py +32 -36
  13. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/pyproject.toml +1 -1
  14. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_redact.py +4 -4
  15. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_runner.py +1 -1
  16. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_store.py +3 -3
  17. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/uv.lock +1 -1
  18. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/.gitignore +0 -0
  19. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/.python-version +0 -0
  20. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/__init__.py +0 -0
  21. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/__init__.py +0 -0
  22. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/application_message.py +0 -0
  23. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/bucket_validation_result.py +0 -0
  24. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/export_connector_credentials.py +0 -0
  25. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/export_receipt.py +0 -0
  26. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/_models/export_worker_config.py +0 -0
  27. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/bucket/__init__.py +0 -0
  28. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/dq_export_connector/errors.py +0 -0
  29. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/scripts/codegen-models.sh +0 -0
  30. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_live_buckets.py +0 -0
  31. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_models_are_current.py +0 -0
  32. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_paths.py +0 -0
  33. {dq_export_connector-0.1.0.dev22 → dq_export_connector-0.1.0.dev23}/tests/test_upload.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: dq-export-connector
3
- Version: 0.1.0.dev22
3
+ Version: 0.1.0.dev23
4
4
  Summary: Worker logic for the Export Connector DCR.
5
5
  Author: Decentriq
6
6
  Requires-Python: >=3.12
@@ -28,7 +28,7 @@ published to PyPI, since the compiled graph installs it from there.
28
28
  Application Warnings and Application Error. A run with an error fails.
29
29
  - `dq_export_connector.errors`: the codes the worker reports, and
30
30
  `ExportConnectorError`, which stops a run with one.
31
- - `dq_export_connector.report`: collects a run's error, warnings and receipt
31
+ - `dq_export_connector.outcome`: collects a run's error, warnings and receipt
32
32
  while it runs, and cuts each message to 1,000 characters, and a provider's
33
33
  own error to 4,000, once redacted.
34
34
  - `dq_export_connector.redact`: keeps every value from the sealed half, and
@@ -17,7 +17,7 @@ published to PyPI, since the compiled graph installs it from there.
17
17
  Application Warnings and Application Error. A run with an error fails.
18
18
  - `dq_export_connector.errors`: the codes the worker reports, and
19
19
  `ExportConnectorError`, which stops a run with one.
20
- - `dq_export_connector.report`: collects a run's error, warnings and receipt
20
+ - `dq_export_connector.outcome`: collects a run's error, warnings and receipt
21
21
  while it runs, and cuts each message to 1,000 characters, and a provider's
22
22
  own error to 4,000, once redacted.
23
23
  - `dq_export_connector.redact`: keeps every value from the sealed half, and
@@ -30,7 +30,7 @@ class DatasetFile:
30
30
 
31
31
 
32
32
  @dataclass(frozen=True)
33
- class Layout:
33
+ class DatasetLayout:
34
34
  """`raw_reason` says why a dataset isn't unpacked; `None` for a stored ZIP."""
35
35
 
36
36
  files: list[DatasetFile]
@@ -38,36 +38,36 @@ class Layout:
38
38
 
39
39
 
40
40
  @contextmanager
41
- def open_dataset(dataset_path: Path) -> Iterator[tuple[Layout, _Reader]]:
41
+ def open_dataset(dataset_path: Path) -> Iterator[tuple[DatasetLayout, _Reader]]:
42
42
  """Reads the dataset's layout, keeping a ZIP open while its entries upload.
43
43
  A ZIP's index sits at its end, so detecting one reads no more than that."""
44
44
  try:
45
45
  archive = zipfile.ZipFile(dataset_path)
46
46
  except zipfile.BadZipFile:
47
47
  size = dataset_path.stat().st_size
48
- yield Layout([DatasetFile(RAW_FILE_NAME, size)], "not a ZIP"), _RawReader(dataset_path)
48
+ yield DatasetLayout([DatasetFile(RAW_FILE_NAME, size)], "not a ZIP"), _RawReader(dataset_path)
49
49
  return
50
50
  with archive:
51
51
  entries = archive.infolist()
52
52
  if any(entry.compress_type != zipfile.ZIP_STORED for entry in entries):
53
53
  size = dataset_path.stat().st_size
54
- yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with compressed entries"), _RawReader(dataset_path)
54
+ yield DatasetLayout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with compressed entries"), _RawReader(dataset_path)
55
55
  return
56
56
  if any(entry.flag_bits & _ENCRYPTED for entry in entries):
57
57
  size = dataset_path.stat().st_size
58
- yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with encrypted entries"), _RawReader(dataset_path)
58
+ yield DatasetLayout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with encrypted entries"), _RawReader(dataset_path)
59
59
  return
60
- named = [(_name(entry), entry) for entry in entries]
60
+ named = [(_entry_name(entry), entry) for entry in entries]
61
61
  # An entry is a directory by its name alone, whatever its attributes say.
62
62
  files = [
63
63
  DatasetFile(name, entry.file_size, entry)
64
64
  for name, entry in named
65
65
  if not name.endswith("/") and name != CONTAINER_LOG
66
66
  ]
67
- yield Layout(files, None), _ZipReader(archive)
67
+ yield DatasetLayout(files, None), _ZipReader(archive)
68
68
 
69
69
 
70
- def _name(entry: zipfile.ZipInfo) -> str:
70
+ def _entry_name(entry: zipfile.ZipInfo) -> str:
71
71
  """`zipfile` reads a name as UTF-8 when the UTF-8 flag is set, takes it
72
72
  from an Info-ZIP Unicode Path extra field written for it, and decodes any
73
73
  other as CP437. Many tools write UTF-8 without setting the flag, so such a
@@ -23,11 +23,11 @@ from dq_export_connector._models.export_receipt import (
23
23
  from dq_export_connector._models.export_worker_config import BucketInput, ExportConnectorKind1, ProvisionedPolicy
24
24
  from dq_export_connector.bucket.datasets import DatasetFile, open_dataset
25
25
  from dq_export_connector.bucket.paths import InvalidPathError, check_dataset_path, check_key, fill_date_tokens, join_key
26
- from dq_export_connector.bucket.store import StorageError, classify_error, failure_sentence, location
26
+ from dq_export_connector.bucket.store import StorageError, classify_error, describe_destination, failure_sentence
27
27
  from dq_export_connector.bucket.upload import plan_upload, upload
28
28
  from dq_export_connector.errors import ErrorCode, ExportConnectorError
29
29
  from dq_export_connector.log import logger
30
- from dq_export_connector.report import ReportBuilder
30
+ from dq_export_connector.outcome import RunOutcome
31
31
 
32
32
 
33
33
  def export(
@@ -37,7 +37,7 @@ def export(
37
37
  inputs_dir: Path,
38
38
  now: datetime,
39
39
  build_store: Callable[[Any, BucketExportCredentials], Any],
40
- report: ReportBuilder,
40
+ outcome: RunOutcome,
41
41
  ) -> None:
42
42
  export_prefix = fill_date_tokens(connector.export_prefix, now) if connector.export_prefix else None
43
43
  policy_ids = {policy.leaf_id: policy.policy_id for policy in policies}
@@ -45,7 +45,7 @@ def export(
45
45
  logger.info(
46
46
  "Export started: provider %s, %s, path prefix %r, export prefix %r resolved to %r, Inputs %s",
47
47
  connection.type,
48
- location(connection),
48
+ describe_destination(connection),
49
49
  connection.path_prefix,
50
50
  connector.export_prefix,
51
51
  export_prefix,
@@ -55,23 +55,23 @@ def export(
55
55
  type="BUCKET",
56
56
  connection=ReceiptConnection.model_validate(connector.connection.model_dump(by_alias=True)),
57
57
  export_prefix=export_prefix,
58
- totals=_no_totals(),
58
+ totals=_zero_totals(),
59
59
  inputs=[
60
60
  BucketInputReceipt(
61
61
  leaf_id=bucket_input.leaf_id,
62
62
  destination_directory=bucket_input.destination_directory,
63
- totals=_no_totals(),
63
+ totals=_zero_totals(),
64
64
  )
65
65
  for bucket_input in connector.inputs
66
66
  ],
67
67
  )
68
- report.receipt = ExportReceiptV0(root=receipt)
68
+ outcome.receipt = ExportReceiptV0(root=receipt)
69
69
  store = build_store(connector.connection, credentials)
70
70
  for bucket_input in connector.inputs:
71
- _check_input(bucket_input, connection, export_prefix, inputs_dir, report)
71
+ _check_input(bucket_input, connection, export_prefix, inputs_dir, outcome)
72
72
  for bucket_input, receipt_input in zip(connector.inputs, receipt.inputs):
73
73
  _export_input(
74
- bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals], report
74
+ bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals], outcome
75
75
  )
76
76
  logger.info(
77
77
  "Export finished: %d Inputs, %d files, %d bytes",
@@ -86,10 +86,10 @@ def _check_input(
86
86
  connection: Any,
87
87
  export_prefix: str | None,
88
88
  inputs_dir: Path,
89
- report: ReportBuilder,
89
+ outcome: RunOutcome,
90
90
  ) -> None:
91
91
  destination = bucket_input.destination_directory
92
- with _reading(destination), open_dataset(inputs_dir / bucket_input.leaf_id) as (layout, _):
92
+ with _as_read_failed(destination), open_dataset(inputs_dir / bucket_input.leaf_id) as (layout, _):
93
93
  if layout.raw_reason is None:
94
94
  logger.info("Input %s is a stored ZIP with %d files", bucket_input.leaf_id, len(layout.files))
95
95
  else:
@@ -98,7 +98,7 @@ def _check_input(
98
98
  paths: set[str] = set()
99
99
  for file in layout.files:
100
100
  check_dataset_path(file.path)
101
- check_key(_key(connection, export_prefix, destination, file), connection)
101
+ check_key(_object_key(connection, export_prefix, destination, file), connection)
102
102
  # Two entries of one name would be written to one key.
103
103
  if file.path in paths:
104
104
  raise InvalidPathError(f"the path '{file.path}' appears more than once")
@@ -108,7 +108,7 @@ def _check_input(
108
108
  ErrorCode.BUCKET_INVALID_PATH, f"Nothing was exported: in the dataset for '{destination}/', {error}"
109
109
  ) from error
110
110
  if not layout.files:
111
- report.warn(
111
+ outcome.warn(
112
112
  ErrorCode.EMPTY_DATASET, f"The dataset for '{destination}/' has no files, so nothing was written there"
113
113
  )
114
114
 
@@ -120,15 +120,15 @@ def _export_input(
120
120
  inputs_dir: Path,
121
121
  store: Any,
122
122
  totals: list[ExportTotals],
123
- report: ReportBuilder,
123
+ outcome: RunOutcome,
124
124
  ) -> None:
125
125
  leaf_id = bucket_input.leaf_id
126
126
  destination = bucket_input.destination_directory
127
127
  started = time.monotonic()
128
128
  logger.info("Input %s started, destination directory %r", leaf_id, destination)
129
- with _reading(destination), open_dataset(inputs_dir / leaf_id) as (layout, reader):
129
+ with _as_read_failed(destination), open_dataset(inputs_dir / leaf_id) as (layout, reader):
130
130
  for uploaded, file in enumerate(layout.files):
131
- key = _key(connection, export_prefix, destination, file)
131
+ key = _object_key(connection, export_prefix, destination, file)
132
132
  plan = plan_upload(file.size)
133
133
  logger.info(
134
134
  "Upload of %r started: %d bytes, %s",
@@ -142,15 +142,15 @@ def _export_input(
142
142
  upload(store, key, source, plan)
143
143
  except StorageError as error:
144
144
  if plan.multipart:
145
- report.warn(
145
+ outcome.warn(
146
146
  ErrorCode.BUCKET_PARTS_MAY_REMAIN,
147
- f"Parts of the unfinished upload of '{key}' may remain in the {location(connection)}. They"
147
+ f"Parts of the unfinished upload of '{key}' may remain in the {describe_destination(connection)}. They"
148
148
  " don't show up as files, and a lifecycle rule for incomplete uploads removes them",
149
149
  )
150
150
  code = classify_error(error.cause)
151
151
  raise ExportConnectorError(
152
152
  code,
153
- f"{failure_sentence(code, location(connection))}, so writing '{key}' failed after"
153
+ f"{failure_sentence(code, describe_destination(connection))}, so writing '{key}' failed after"
154
154
  f" {uploaded} of {len(layout.files)} files for '{destination}/'",
155
155
  str(error),
156
156
  ) from error
@@ -162,7 +162,7 @@ def _export_input(
162
162
 
163
163
 
164
164
  @contextmanager
165
- def _reading(destination: str) -> Iterator[None]:
165
+ def _as_read_failed(destination: str) -> Iterator[None]:
166
166
  """A stored ZIP that is corrupt raises `BadZipFile`, or `EOFError` for an
167
167
  entry cut short, when its entry is read. One that needs a newer ZIP version
168
168
  than `zipfile` supports raises `NotImplementedError`."""
@@ -175,9 +175,9 @@ def _reading(destination: str) -> Iterator[None]:
175
175
  ) from error
176
176
 
177
177
 
178
- def _key(connection: Any, export_prefix: str | None, destination: str, file: DatasetFile) -> str:
178
+ def _object_key(connection: Any, export_prefix: str | None, destination: str, file: DatasetFile) -> str:
179
179
  return join_key(connection.path_prefix, export_prefix, destination, file.path)
180
180
 
181
181
 
182
- def _no_totals() -> ExportTotals:
182
+ def _zero_totals() -> ExportTotals:
183
183
  return ExportTotals(files=0, bytes=0, rows=None)
@@ -36,14 +36,14 @@ def fill_date_tokens(export_prefix: str, now: datetime) -> str:
36
36
  )
37
37
 
38
38
 
39
- def strip_part(part: str) -> str:
39
+ def _strip_one_slash(part: str) -> str:
40
40
  """One leading and one trailing `/` are ignored, as ddc's naming rules do."""
41
41
  part = part[1:] if part.startswith("/") else part
42
42
  return part[:-1] if part.endswith("/") else part
43
43
 
44
44
 
45
45
  def join_key(*parts: str | None) -> str:
46
- return "/".join(strip_part(part) for part in parts if part)
46
+ return "/".join(_strip_one_slash(part) for part in parts if part)
47
47
 
48
48
 
49
49
  def check_dataset_path(path: str) -> None:
@@ -78,7 +78,7 @@ def check_key(key: str, connection: BucketConnection1 | BucketConnection2 | Buck
78
78
 
79
79
 
80
80
  def _shortened(key: str) -> str:
81
- """Both ends of a key too long to quote whole in a report message."""
81
+ """Both ends of a key too long to quote whole in a message."""
82
82
  return key if len(key) <= 2 * _QUOTED_KEY_END else f"{key[:_QUOTED_KEY_END]}…{key[-_QUOTED_KEY_END:]}"
83
83
 
84
84
 
@@ -4,9 +4,10 @@ failures map to."""
4
4
  from __future__ import annotations
5
5
 
6
6
  import re
7
- from collections.abc import Callable
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
8
9
  from datetime import timedelta
9
- from typing import TYPE_CHECKING, Any, TypeVar
10
+ from typing import TYPE_CHECKING, Any
10
11
 
11
12
  import obstore.exceptions
12
13
  from obstore.store import AzureStore, GCSStore, S3Store
@@ -58,14 +59,11 @@ CLIENT_CONFIG: ClientConfig = {
58
59
  "read_timeout": timedelta(minutes=10),
59
60
  }
60
61
 
61
- T = TypeVar("T")
62
-
63
-
64
62
  _HTTP_ERROR = re.compile(r"HttpError \{\s*kind: (?P<kind>\w+),\s*source: reqwest::Error \{(?P<source>.*)", re.DOTALL)
65
63
  _STRING_LITERAL = re.compile(r'"((?:[^"\\]|\\.)*)"')
66
64
 
67
65
 
68
- def describe(error: Exception) -> str:
66
+ def describe_storage_error(error: Exception) -> str:
69
67
  """obstore's message without the `Debug source:` dump it appends. For a
70
68
  request that couldn't be sent, the message stops at "error sending
71
69
  request", so the causes the dump holds, such as a DNS failure or a refused
@@ -84,7 +82,7 @@ class StorageError(Exception):
84
82
  """A request to the Bucket Provider failed; `cause` is obstore's error."""
85
83
 
86
84
  def __init__(self, cause: Exception) -> None:
87
- super().__init__(describe(cause))
85
+ super().__init__(describe_storage_error(cause))
88
86
  self.cause = cause
89
87
 
90
88
 
@@ -94,11 +92,12 @@ class StorageError(Exception):
94
92
  _OBSTORE_ERRORS = (obstore.exceptions.BaseError, FileNotFoundError, NotImplementedError)
95
93
 
96
94
 
97
- def storage_call(call: Callable[[], T]) -> T:
98
- """Runs a request to the Bucket Provider, so its failures can't be
95
+ @contextmanager
96
+ def storage_request() -> Iterator[None]:
97
+ """Wraps a request to the Bucket Provider, so its failures can't be
99
98
  mistaken for failing to read a dataset."""
100
99
  try:
101
- return call()
100
+ yield
102
101
  except _OBSTORE_ERRORS as error:
103
102
  raise StorageError(error) from error
104
103
 
@@ -116,7 +115,7 @@ _RESPONSE_CODE = re.compile(r"<Code>(\w+)</Code>")
116
115
 
117
116
  # How object_store reports S3's redirect for a bucket in another region than
118
117
  # the connection's.
119
- _OTHER_REGION = "this normally indicates an incorrectly configured region"
118
+ _WRONG_REGION_MESSAGE = "this normally indicates an incorrectly configured region"
120
119
 
121
120
 
122
121
  def classify_error(error: Exception) -> ErrorCode:
@@ -132,7 +131,7 @@ def classify_error(error: Exception) -> ErrorCode:
132
131
  if isinstance(error, FileNotFoundError):
133
132
  return ErrorCode.DESTINATION_NOT_FOUND
134
133
  message, _, dump = str(error).partition("\n\nDebug source:")
135
- if message.endswith(_OTHER_REGION):
134
+ if message.endswith(_WRONG_REGION_MESSAGE):
136
135
  return ErrorCode.DESTINATION_NOT_FOUND
137
136
  # The request got no response: it couldn't connect, timed out or was cut off.
138
137
  if _HTTP_ERROR.search(dump) is not None:
@@ -140,7 +139,7 @@ def classify_error(error: Exception) -> ErrorCode:
140
139
  return ErrorCode.UNKNOWN
141
140
 
142
141
 
143
- def location(connection: BucketConnection1 | BucketConnection2 | BucketConnection3) -> str:
142
+ def describe_destination(connection: BucketConnection1 | BucketConnection2 | BucketConnection3) -> str:
144
143
  match connection:
145
144
  case BucketConnection1():
146
145
  return f"bucket '{connection.bucket}' in {connection.region}"
@@ -186,20 +185,20 @@ def build_store(connection: BucketConnection, credentials: BucketExportCredentia
186
185
  token fails before any request, as does an address no URL can hold, such as
187
186
  an Azure account name with a space."""
188
187
  try:
189
- return _store(connection, credentials)
188
+ return _create_store(connection, credentials)
190
189
  except obstore.exceptions.BaseError as error:
191
- message = describe(error)
190
+ message = describe_storage_error(error)
192
191
  if message.startswith(_CREDENTIAL_PARSE_ERRORS):
193
192
  without_values = _ECHOED_VALUE.sub(lambda value: f"{value[0][0]}{MASK}{value[0][-1]}", message)
194
193
  raise ExportConnectorError(
195
194
  ErrorCode.INVALID_CREDENTIALS, "The credentials couldn't be read", without_values
196
195
  ) from error
197
196
  raise ExportConnectorError(
198
- ErrorCode.UNREACHABLE, failure_sentence(ErrorCode.UNREACHABLE, location(connection.root)), message
197
+ ErrorCode.UNREACHABLE, failure_sentence(ErrorCode.UNREACHABLE, describe_destination(connection.root)), message
199
198
  ) from error
200
199
 
201
200
 
202
- def _store(connection: BucketConnection, credentials: BucketExportCredentials) -> Any:
201
+ def _create_store(connection: BucketConnection, credentials: BucketExportCredentials) -> Any:
203
202
  """ddc pins the provider pairing, so a mismatch here is a bug."""
204
203
  match (connection.root, credentials.root):
205
204
  case (BucketConnection1() as s3, BucketExportCredentials1() as s3_credentials):
@@ -18,7 +18,7 @@ from typing import Any, BinaryIO
18
18
 
19
19
  import obstore
20
20
 
21
- from dq_export_connector.bucket.store import storage_call
21
+ from dq_export_connector.bucket.store import storage_request
22
22
 
23
23
  MIB = 1024 * 1024
24
24
  MIN_PART_SIZE = 8 * MIB
@@ -34,20 +34,20 @@ class UploadPlan:
34
34
 
35
35
 
36
36
  def plan_upload(size: int) -> UploadPlan:
37
- parts_needed = -(-size // MAX_PARTS)
38
- part_size = max(MIN_PART_SIZE, -(-parts_needed // MIB) * MIB)
37
+ smallest_part_size = -(-size // MAX_PARTS)
38
+ part_size = max(MIN_PART_SIZE, -(-smallest_part_size // MIB) * MIB)
39
39
  return UploadPlan(multipart=size > part_size, part_size=part_size)
40
40
 
41
41
 
42
42
  def upload(store: Any, key: str, source: BinaryIO, plan: UploadPlan) -> None:
43
43
  if plan.multipart:
44
44
  chunks = _chunks(source, plan.part_size)
45
- storage_call(
46
- lambda: obstore.put(store, key, chunks, chunk_size=plan.part_size, max_concurrency=MAX_CONCURRENCY)
47
- )
45
+ with storage_request():
46
+ obstore.put(store, key, chunks, chunk_size=plan.part_size, max_concurrency=MAX_CONCURRENCY)
48
47
  else:
49
48
  content = source.read()
50
- storage_call(lambda: obstore.put(store, key, content, use_multipart=False))
49
+ with storage_request():
50
+ obstore.put(store, key, content, use_multipart=False)
51
51
 
52
52
 
53
53
  def _chunks(source: BinaryIO, size: int) -> Iterator[bytes]:
@@ -13,10 +13,16 @@ import obstore
13
13
  from dq_export_connector._models.export_connector_credentials import BucketExportCredentials
14
14
  from dq_export_connector._models.export_worker_config import BucketConnection
15
15
  from dq_export_connector.bucket.paths import join_key
16
- from dq_export_connector.bucket.store import StorageError, classify_error, failure_sentence, location, storage_call
16
+ from dq_export_connector.bucket.store import (
17
+ StorageError,
18
+ classify_error,
19
+ describe_destination,
20
+ failure_sentence,
21
+ storage_request,
22
+ )
17
23
  from dq_export_connector.errors import ErrorCode, ExportConnectorError
18
24
  from dq_export_connector.log import logger
19
- from dq_export_connector.report import ReportBuilder
25
+ from dq_export_connector.outcome import RunOutcome
20
26
 
21
27
  PROBE_CONTENT = b"Written by a Decentriq connection test; safe to delete."
22
28
 
@@ -29,28 +35,30 @@ def validate_connection(
29
35
  connection: BucketConnection,
30
36
  credentials: BucketExportCredentials,
31
37
  build_store: Callable[[BucketConnection, BucketExportCredentials], Any],
32
- report: ReportBuilder,
38
+ outcome: RunOutcome,
33
39
  ) -> None:
34
40
  logger.info("Connection test started: provider %s", connection.root.type)
35
41
  store = build_store(connection, credentials)
36
42
  key = probe_key(connection.root.path_prefix)
37
43
  try:
38
- storage_call(lambda: obstore.put(store, key, PROBE_CONTENT))
44
+ with storage_request():
45
+ obstore.put(store, key, PROBE_CONTENT)
39
46
  except StorageError as error:
40
47
  code = classify_error(error.cause)
41
48
  raise ExportConnectorError(
42
49
  code,
43
- f"{failure_sentence(code, location(connection.root))}, so the connection test couldn't write"
50
+ f"{failure_sentence(code, describe_destination(connection.root))}, so the connection test couldn't write"
44
51
  f" its test object '{key}'",
45
52
  str(error),
46
53
  ) from error
47
54
  logger.info("Wrote the probe %r", key)
48
55
 
49
56
  try:
50
- storage_call(lambda: obstore.delete(store, key))
57
+ with storage_request():
58
+ obstore.delete(store, key)
51
59
  except StorageError as error:
52
60
  logger.warning("Deleting the probe %r failed: %s", key, error)
53
- report.warn(
61
+ outcome.warn(
54
62
  ErrorCode.BUCKET_PROBE_NOT_DELETED,
55
63
  f"The connection test wrote its test object '{key}' but couldn't delete it; it's safe to delete",
56
64
  str(error),
@@ -28,7 +28,7 @@ class _RedactingFormatter(logging.Formatter):
28
28
  return self._redactor.redact(super().format(record))
29
29
 
30
30
 
31
- def configure(redactor: Redactor) -> None:
31
+ def configure_logger(redactor: Redactor) -> None:
32
32
  logger.setLevel(logging.INFO)
33
33
  logger.propagate = False
34
34
  logger.handlers.clear()
@@ -1,4 +1,4 @@
1
- """Collects what a run reports while it runs, so the receipt and the warnings
1
+ """Collects a run's outcome while it runs, so the receipt and the warnings
2
2
  gathered before an error survive it."""
3
3
 
4
4
  from __future__ import annotations
@@ -12,7 +12,7 @@ from dq_export_connector.errors import MAX_MESSAGE_LENGTH, MAX_PROVIDER_ERROR_LE
12
12
  from dq_export_connector.redact import Redactor
13
13
 
14
14
 
15
- class ReportBuilder:
15
+ class RunOutcome:
16
16
  def __init__(self) -> None:
17
17
  self.error: tuple[ErrorCode, str, str | None] | None = None
18
18
  self.warnings: list[tuple[ErrorCode, str, str | None]] = []
@@ -30,21 +30,21 @@ class ReportBuilder:
30
30
  return ExportReceipt.model_validate({"version": "V0", **self.receipt.model_dump(by_alias=True)})
31
31
 
32
32
  def application_warnings(self, redactor: Redactor) -> list[ApplicationMessage]:
33
- return [ApplicationMessage.model_validate(_message(*warning, redactor)) for warning in self.warnings]
33
+ return [ApplicationMessage.model_validate(_application_message(*warning, redactor)) for warning in self.warnings]
34
34
 
35
35
  def application_error(self, redactor: Redactor) -> ApplicationMessage | None:
36
- return None if self.error is None else ApplicationMessage.model_validate(_message(*self.error, redactor))
36
+ return None if self.error is None else ApplicationMessage.model_validate(_application_message(*self.error, redactor))
37
37
 
38
38
  def validation_result(self, redactor: Redactor) -> BucketValidationResult:
39
39
  return BucketValidationResult.model_validate(
40
40
  {
41
- "error": None if self.error is None else _message(*self.error, redactor),
42
- "warnings": [_message(*warning, redactor) for warning in self.warnings],
41
+ "error": None if self.error is None else _application_message(*self.error, redactor),
42
+ "warnings": [_application_message(*warning, redactor) for warning in self.warnings],
43
43
  }
44
44
  )
45
45
 
46
46
 
47
- def _message(code: ErrorCode, text: str, provider_error: str | None, redactor: Redactor) -> dict[str, Any]:
47
+ def _application_message(code: ErrorCode, text: str, provider_error: str | None, redactor: Redactor) -> dict[str, Any]:
48
48
  # Cut once redacted, so a cut can't leave part of a secret unmasked.
49
49
  message: dict[str, Any] = {"code": code.value, "message": truncate(redactor.redact(text), MAX_MESSAGE_LENGTH)}
50
50
  if provider_error is not None:
@@ -1,4 +1,4 @@
1
- """Keeps the sealed half out of everything the worker writes.
1
+ """Keeps the credentials' secrets out of everything the worker writes.
2
2
 
3
3
  Log lines reach Decentriq-readable platform logs, and result messages reach
4
4
  api-platform in plaintext. Every string value of the credentials but those of
@@ -35,20 +35,20 @@ PUBLIC_FIELDS = frozenset(
35
35
  _URL_QUERY = re.compile(r"(?P<url>[a-zA-Z][a-zA-Z0-9+.-]*://[^\s?#\"'<>]+)\?[^\s#\"'<>]*")
36
36
 
37
37
 
38
- def sealed_values(value: Any) -> list[str]:
38
+ def secret_values(value: Any) -> list[str]:
39
39
  """Every string in a JSON value but those of `PUBLIC_FIELDS`, including
40
40
  those inside strings that are themselves JSON, such as a GCS service
41
41
  account key."""
42
42
  if isinstance(value, dict):
43
- return [found for key, item in value.items() if key not in PUBLIC_FIELDS for found in sealed_values(item)]
43
+ return [found for key, item in value.items() if key not in PUBLIC_FIELDS for found in secret_values(item)]
44
44
  if isinstance(value, list):
45
- return [found for item in value for found in sealed_values(item)]
45
+ return [found for item in value for found in secret_values(item)]
46
46
  if isinstance(value, str):
47
47
  try:
48
48
  nested = json.loads(value)
49
49
  except ValueError:
50
50
  return [value]
51
- return [value, *sealed_values(nested)]
51
+ return [value, *secret_values(nested)]
52
52
  return []
53
53
 
54
54
 
@@ -9,7 +9,8 @@ Error."""
9
9
  from __future__ import annotations
10
10
 
11
11
  import json
12
- from collections.abc import Callable
12
+ from collections.abc import Callable, Iterator
13
+ from contextlib import contextmanager
13
14
  from datetime import datetime, timezone
14
15
  from importlib.metadata import version
15
16
  from pathlib import Path
@@ -23,9 +24,9 @@ from dq_export_connector._models.export_worker_config import (
23
24
  )
24
25
  from dq_export_connector._models.application_message import ApplicationMessage
25
26
  from dq_export_connector.errors import ErrorCode, ExportConnectorError, internal_error_message
26
- from dq_export_connector.log import configure, logger
27
- from dq_export_connector.redact import Redactor, sealed_values
28
- from dq_export_connector.report import ReportBuilder
27
+ from dq_export_connector.log import configure_logger, logger
28
+ from dq_export_connector.outcome import RunOutcome
29
+ from dq_export_connector.redact import Redactor, secret_values
29
30
 
30
31
  CONFIG_PATH = Path("/input/config.json")
31
32
  CREDENTIALS_PATH = Path("/input/credentials.json")
@@ -39,7 +40,7 @@ APPLICATION_WARNINGS_FILE = "application_warnings"
39
40
  APPLICATION_ERROR_FILE = "application_error"
40
41
 
41
42
 
42
- class WorkerFailed(Exception):
43
+ class WorkerCrashed(Exception):
43
44
  """Replaces an unexpected error, whose message could hold credentials: the
44
45
  container worker's `raw_errors` result doesn't pass the redaction."""
45
46
 
@@ -56,13 +57,13 @@ def main(
56
57
  build_store: Callable[[Any, Any], Any] | None = None,
57
58
  internal_dir: Path = INTERNAL_DIR,
58
59
  ) -> None:
59
- credentials_json = json.loads(credentials_path.read_text())
60
- redactor = Redactor(sealed_values(credentials_json))
61
- configure(redactor)
60
+ raw_credentials = json.loads(credentials_path.read_text())
61
+ redactor = Redactor(secret_values(raw_credentials))
62
+ configure_logger(redactor)
62
63
  try:
63
64
  error = run(
64
65
  ExportWorkerConfig.model_validate_json(config_path.read_text()),
65
- ExportConnectorCredentials.model_validate(credentials_json),
66
+ ExportConnectorCredentials.model_validate(raw_credentials),
66
67
  inputs_dir,
67
68
  output_dir,
68
69
  internal_dir,
@@ -74,7 +75,7 @@ def main(
74
75
  # A panic in obstore's Rust code is a `BaseException`.
75
76
  except BaseException:
76
77
  logger.exception("The export worker failed")
77
- raise WorkerFailed("The export worker failed; its redacted error is in the platform logs") from None
78
+ raise WorkerCrashed("The export worker failed; its redacted error is in the platform logs") from None
78
79
  if error is not None:
79
80
  raise RunFailed(f"The run failed with {error.code}; its Application Error says why")
80
81
 
@@ -98,46 +99,40 @@ def run(
98
99
  logger.info("dq-export-connector %s", version("dq-export-connector"))
99
100
  connector = config.connector.root
100
101
  bucket_credentials = credentials.root.credentials
101
- report = ReportBuilder()
102
+ outcome = RunOutcome()
102
103
  now = datetime.now(timezone.utc)
103
- unexpired_store = _unexpired(build_store or store.build_store, config.credentials_expire_at, now)
104
+ build_store = _with_expiry_check(build_store or store.build_store, config.credentials_expire_at, now)
104
105
  match config.action.root:
105
106
  case ExportConnectorDcrComputeAction1():
106
- _reporting(
107
- report,
108
- "connection test",
109
- lambda: validate_connection(connector.connection, bucket_credentials, unexpired_store, report),
110
- )
107
+ with _record_failure(outcome, "connection test"):
108
+ validate_connection(connector.connection, bucket_credentials, build_store, outcome)
111
109
  # A connection found broken is the answer the check exists to give;
112
110
  # an internal error means it couldn't run.
113
- if report.error is None or report.error[0] is not ErrorCode.INTERNAL_ERROR:
114
- result = report.validation_result(redactor)
111
+ if outcome.error is None or outcome.error[0] is not ErrorCode.INTERNAL_ERROR:
112
+ result = outcome.validation_result(redactor)
115
113
  _write(output_dir / VALIDATION_RESULT_FILE, result.model_dump_json(by_alias=True, exclude_none=True))
116
114
  return None
117
115
  case ExportConnectorDcrComputeAction2():
118
- _reporting(
119
- report,
120
- "export",
121
- lambda: export(connector, config.policies, bucket_credentials, inputs_dir, now, unexpired_store, report),
122
- )
123
- receipt = report.export_receipt()
116
+ with _record_failure(outcome, "export"):
117
+ export(connector, config.policies, bucket_credentials, inputs_dir, now, build_store, outcome)
118
+ receipt = outcome.export_receipt()
124
119
  if receipt is not None:
125
120
  _write(internal_dir / REPORT_FILE, receipt.model_dump_json(by_alias=True, exclude_none=True))
126
- return _write_application_outputs(internal_dir, report, redactor)
121
+ return _write_application_outputs(internal_dir, outcome, redactor)
127
122
 
128
123
 
129
- def _write_application_outputs(internal_dir: Path, report: ReportBuilder, redactor: Redactor) -> ApplicationMessage | None:
130
- warnings = report.application_warnings(redactor)
124
+ def _write_application_outputs(internal_dir: Path, outcome: RunOutcome, redactor: Redactor) -> ApplicationMessage | None:
125
+ warnings = outcome.application_warnings(redactor)
131
126
  if warnings:
132
127
  dumped = [warning.model_dump(by_alias=True, exclude_none=True) for warning in warnings]
133
128
  _write(internal_dir / APPLICATION_WARNINGS_FILE, json.dumps(dumped))
134
- error = report.application_error(redactor)
129
+ error = outcome.application_error(redactor)
135
130
  if error is not None:
136
131
  _write(internal_dir / APPLICATION_ERROR_FILE, error.model_dump_json(by_alias=True, exclude_none=True))
137
132
  return error
138
133
 
139
134
 
140
- def _unexpired(
135
+ def _with_expiry_check(
141
136
  build_store: Callable[[Any, Any], Any], expire_at: datetime | None, now: datetime
142
137
  ) -> Callable[[Any, Any], Any]:
143
138
  """A provider answers expired credentials like rejected ones, so building
@@ -154,20 +149,21 @@ def _unexpired(
154
149
  return build
155
150
 
156
151
 
157
- def _reporting(report: ReportBuilder, activity: str, action: Callable[[], None]) -> None:
158
- """Makes a failure the report's error, so the report keeps what the action
159
- did before it."""
152
+ @contextmanager
153
+ def _record_failure(outcome: RunOutcome, activity: str) -> Iterator[None]:
154
+ """Makes a failure of the block the outcome's error, so the outcome keeps
155
+ what the block did before it."""
160
156
  try:
161
- action()
157
+ yield
162
158
  except (KeyboardInterrupt, SystemExit):
163
159
  raise
164
160
  except ExportConnectorError as error:
165
161
  logger.error("The %s failed with %s: %s", activity, error.code.value, error.message)
166
- report.fail(error.code, error.message, error.provider_error)
162
+ outcome.fail(error.code, error.message, error.provider_error)
167
163
  # A panic in obstore's Rust code is a `BaseException`.
168
164
  except BaseException as error:
169
165
  logger.exception("An internal error stopped the %s", activity)
170
- report.fail(ErrorCode.INTERNAL_ERROR, internal_error_message(error, activity))
166
+ outcome.fail(ErrorCode.INTERNAL_ERROR, internal_error_message(error, activity))
171
167
 
172
168
 
173
169
  def _write(path: Path, content: str) -> None:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dq-export-connector"
3
- version = "0.1.0.dev22"
3
+ version = "0.1.0.dev23"
4
4
  description = "Worker logic for the Export Connector DCR."
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Decentriq" }]
@@ -1,12 +1,12 @@
1
1
  import json
2
2
 
3
- from dq_export_connector.redact import Redactor, sealed_values
3
+ from dq_export_connector.redact import Redactor, secret_values
4
4
 
5
5
 
6
6
  def test_every_value_of_the_sealed_half_is_found_including_inside_json_strings():
7
7
  service_account = json.dumps({"private_key": "-----BEGIN PRIVATE KEY-----\nabc\n", "private_key_id": "k1"})
8
8
  credentials = {"type": "bucket", "credentials": {"type": "gcs", "serviceAccountJson": service_account}}
9
- assert sealed_values(credentials) == [service_account, "-----BEGIN PRIVATE KEY-----\nabc\n", "k1"]
9
+ assert secret_values(credentials) == [service_account, "-----BEGIN PRIVATE KEY-----\nabc\n", "k1"]
10
10
 
11
11
 
12
12
  def test_the_public_fields_of_a_service_account_key_are_not_masked():
@@ -19,14 +19,14 @@ def test_the_public_fields_of_a_service_account_key_are_not_masked():
19
19
  "universe_domain": "googleapis.com",
20
20
  }
21
21
  )
22
- redactor = Redactor(sealed_values({"type": "gcs", "serviceAccountJson": service_account}))
22
+ redactor = Redactor(secret_values({"type": "gcs", "serviceAccountJson": service_account}))
23
23
  error = "PUT https://storage.googleapis.com/acme-prod-exports/a.csv: 403, export@acme-prod.iam.gserviceaccount.com"
24
24
  assert redactor.redact(error) == error
25
25
 
26
26
 
27
27
  def test_an_azure_error_carrying_the_sas_token_is_masked():
28
28
  sas_token = "sv=2024-01-01&ss=b&sig=Zm9vYmFy%3D"
29
- redactor = Redactor(sealed_values({"type": "bucket", "credentials": {"type": "azureBlob", "sasToken": sas_token}}))
29
+ redactor = Redactor(secret_values({"type": "bucket", "credentials": {"type": "azureBlob", "sasToken": sas_token}}))
30
30
  error = (
31
31
  "Generic MicrosoftAzure error: Error performing PUT "
32
32
  f"https://acme.blob.core.windows.net/exports/seg_a/data?{sas_token}&comp=block in 1.2s: "
@@ -516,6 +516,6 @@ def test_a_failure_outside_the_action_fails_the_worker_without_its_message(tmp_p
516
516
  pipe = tmp_path / "pipe.log"
517
517
  pipe.touch()
518
518
  monkeypatch.setenv("DQ_INTERNAL_LOGS_PIPE", str(pipe))
519
- with pytest.raises(runner.WorkerFailed) as raised:
519
+ with pytest.raises(runner.WorkerCrashed) as raised:
520
520
  runner.main(tmp_path / "config.json", tmp_path / "credentials.json", tmp_path, tmp_path / "out")
521
521
  assert raised.value.__cause__ is None
@@ -9,7 +9,7 @@ from obstore.store import S3Store
9
9
 
10
10
  from dq_export_connector._models.export_connector_credentials import BucketExportCredentials
11
11
  from dq_export_connector._models.export_worker_config import BucketConnection
12
- from dq_export_connector.bucket.store import build_store, classify_error, describe
12
+ from dq_export_connector.bucket.store import build_store, classify_error, describe_storage_error
13
13
  from dq_export_connector.errors import ErrorCode, ExportConnectorError
14
14
 
15
15
  if TYPE_CHECKING:
@@ -97,7 +97,7 @@ def _put_error(port, client_options: "ClientConfig"):
97
97
  obstore.put(store, "k", b"x")
98
98
  except obstore.exceptions.BaseError as error:
99
99
  # Leaves out the request's URL and duration.
100
- return classify_error(error), describe(error).split(" - ", 1)[1]
100
+ return classify_error(error), describe_storage_error(error).split(" - ", 1)[1]
101
101
  return None
102
102
 
103
103
 
@@ -122,7 +122,7 @@ def test_a_request_that_couldnt_be_sent_is_unreachable_and_keeps_its_cause():
122
122
 
123
123
  def test_obstores_debug_dump_is_left_out():
124
124
  error = obstore.exceptions.GenericError("Generic S3 error: failed\n\nDebug source:\nGeneric {\n store: \"S3\",\n}")
125
- assert describe(error) == "Generic S3 error: failed"
125
+ assert describe_storage_error(error) == "Generic S3 error: failed"
126
126
 
127
127
 
128
128
  def _denied(key, response):
@@ -90,7 +90,7 @@ wheels = [
90
90
 
91
91
  [[package]]
92
92
  name = "dq-export-connector"
93
- version = "0.1.0.dev22"
93
+ version = "0.1.0.dev23"
94
94
  source = { editable = "." }
95
95
  dependencies = [
96
96
  { name = "pydantic" },