dq-export-connector 0.1.0.dev7__tar.gz → 0.1.0.dev9__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 (36) hide show
  1. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/PKG-INFO +7 -3
  2. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/README.md +6 -2
  3. dq_export_connector-0.1.0.dev9/dq_export_connector/_models/bucket_validation_result.py +35 -0
  4. dq_export_connector-0.1.0.dev7/dq_export_connector/_models/export_receipt.py → dq_export_connector-0.1.0.dev9/dq_export_connector/_models/export_report.py +38 -58
  5. dq_export_connector-0.1.0.dev9/dq_export_connector/bucket/export.py +167 -0
  6. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/bucket/paths.py +8 -8
  7. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/bucket/store.py +63 -29
  8. dq_export_connector-0.1.0.dev9/dq_export_connector/bucket/validate.py +57 -0
  9. dq_export_connector-0.1.0.dev9/dq_export_connector/errors.py +58 -0
  10. dq_export_connector-0.1.0.dev9/dq_export_connector/report.py +40 -0
  11. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/runner.py +33 -7
  12. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/pyproject.toml +1 -1
  13. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/scripts/codegen-models.sh +1 -1
  14. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/tests/test_live_buckets.py +8 -9
  15. dq_export_connector-0.1.0.dev9/tests/test_runner.py +295 -0
  16. dq_export_connector-0.1.0.dev9/tests/test_store.py +46 -0
  17. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/uv.lock +1 -1
  18. dq_export_connector-0.1.0.dev7/dq_export_connector/_models/bucket_validation_result.py +0 -63
  19. dq_export_connector-0.1.0.dev7/dq_export_connector/bucket/export.py +0 -236
  20. dq_export_connector-0.1.0.dev7/dq_export_connector/bucket/validate.py +0 -76
  21. dq_export_connector-0.1.0.dev7/tests/test_runner.py +0 -211
  22. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/.gitignore +0 -0
  23. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/.python-version +0 -0
  24. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/__init__.py +0 -0
  25. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/_models/__init__.py +0 -0
  26. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/_models/export_connector_credentials.py +0 -0
  27. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/_models/export_worker_config.py +0 -0
  28. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/bucket/__init__.py +0 -0
  29. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/bucket/datasets.py +0 -0
  30. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/bucket/upload.py +0 -0
  31. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/log.py +0 -0
  32. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/dq_export_connector/redact.py +0 -0
  33. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/tests/test_models_are_current.py +0 -0
  34. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/tests/test_paths.py +0 -0
  35. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/tests/test_redact.py +0 -0
  36. {dq_export_connector-0.1.0.dev7 → dq_export_connector-0.1.0.dev9}/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.dev7
3
+ Version: 0.1.0.dev9
4
4
  Summary: Worker logic for the Export Connector DCR.
5
5
  Author: Decentriq
6
6
  Requires-Python: >=3.10
@@ -21,13 +21,17 @@ published to PyPI, since the compiled graph installs it from there.
21
21
 
22
22
  - `dq_export_connector.runner`: the entry point. Reads `/input/config.json`
23
23
  and `/input/credentials.json`, sets up logging, and dispatches on the
24
- Connector Kind and the action.
24
+ Connector Kind and the action, then writes what the action reports.
25
+ - `dq_export_connector.errors`: the codes the worker reports, and
26
+ `ExportConnectorError`, which stops a run with one.
27
+ - `dq_export_connector.report`: collects a run's error, warnings and receipt
28
+ while it runs, and cuts each message to ddc's 1,000 characters once redacted.
25
29
  - `dq_export_connector.redact`: keeps every value from the sealed half, and
26
30
  URL query strings, out of log lines and result messages.
27
31
  - `dq_export_connector.bucket`: the bucket kind (`ValidateConnection` and
28
32
  `Export`).
29
33
  - `dq_export_connector._models`: pydantic models generated from ddc's JSON
30
- schemas, so the config the worker reads and the receipt and validation
34
+ schemas, so the config the worker reads and the report and validation
31
35
  result it writes match ddc's Rust types. Regenerate them with
32
36
  `scripts/codegen-models.sh` after the types change and
33
37
  `decentriq_dcr_compiler` has been rebuilt; a test fails while they are
@@ -11,13 +11,17 @@ published to PyPI, since the compiled graph installs it from there.
11
11
 
12
12
  - `dq_export_connector.runner`: the entry point. Reads `/input/config.json`
13
13
  and `/input/credentials.json`, sets up logging, and dispatches on the
14
- Connector Kind and the action.
14
+ Connector Kind and the action, then writes what the action reports.
15
+ - `dq_export_connector.errors`: the codes the worker reports, and
16
+ `ExportConnectorError`, which stops a run with one.
17
+ - `dq_export_connector.report`: collects a run's error, warnings and receipt
18
+ while it runs, and cuts each message to ddc's 1,000 characters once redacted.
15
19
  - `dq_export_connector.redact`: keeps every value from the sealed half, and
16
20
  URL query strings, out of log lines and result messages.
17
21
  - `dq_export_connector.bucket`: the bucket kind (`ValidateConnection` and
18
22
  `Export`).
19
23
  - `dq_export_connector._models`: pydantic models generated from ddc's JSON
20
- schemas, so the config the worker reads and the receipt and validation
24
+ schemas, so the config the worker reads and the report and validation
21
25
  result it writes match ddc's Rust types. Regenerate them with
22
26
  `scripts/codegen-models.sh` after the types change and
23
27
  `decentriq_dcr_compiler` has been rebuilt; a test fails while they are
@@ -0,0 +1,35 @@
1
+ # generated by datamodel-codegen:
2
+ # filename: bucket_validation_result.json
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Annotated
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class ExportMessage(BaseModel):
12
+ model_config = ConfigDict(
13
+ populate_by_name=True,
14
+ )
15
+ code: Annotated[
16
+ str,
17
+ Field(
18
+ description='SCREAMING_SNAKE_CASE, such as `ACCESS_DENIED`. A string rather than an\nenum, so a worker release can add codes that readers built against an\nolder ddc still accept.'
19
+ ),
20
+ ]
21
+ message: Annotated[
22
+ str,
23
+ Field(
24
+ description='Safe to show to the user: no credentials and no dataset values. A\nlonger one is cut, ending in `…`.',
25
+ max_length=1000,
26
+ ),
27
+ ]
28
+
29
+
30
+ class BucketValidationResult(BaseModel):
31
+ model_config = ConfigDict(
32
+ populate_by_name=True,
33
+ )
34
+ error: ExportMessage | None = None
35
+ warnings: list[ExportMessage]
@@ -1,9 +1,8 @@
1
1
  # generated by datamodel-codegen:
2
- # filename: export_receipt.json
2
+ # filename: export_report.json
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
- from enum import Enum
7
6
  from typing import Annotated, Literal
8
7
 
9
8
  from pydantic import BaseModel, ConfigDict, Field, RootModel
@@ -62,7 +61,8 @@ class ExportMessage(BaseModel):
62
61
  message: Annotated[
63
62
  str,
64
63
  Field(
65
- description='Safe to show to the user: no credentials and no dataset values.'
64
+ description='Safe to show to the user: no credentials and no dataset values. A\nlonger one is cut, ending in `…`.',
65
+ max_length=1000,
66
66
  ),
67
67
  ]
68
68
 
@@ -81,32 +81,18 @@ class ExportTotals(BaseModel):
81
81
  ] = None
82
82
 
83
83
 
84
- class ExportedFile(BaseModel):
85
- model_config = ConfigDict(
86
- populate_by_name=True,
87
- )
88
- bytes: Annotated[int, Field(ge=0)]
89
- path: Annotated[str, Field(description='The object key in the bucket.')]
90
- rows: Annotated[
91
- int | None, Field(description="`None` where the worker can't count rows.", ge=0)
92
- ] = None
93
-
94
-
95
- class InputStatus(Enum):
96
- success = 'SUCCESS'
97
- failed = 'FAILED'
98
-
99
-
100
84
  class BucketInputReceipt(BaseModel):
101
85
  model_config = ConfigDict(
102
86
  populate_by_name=True,
103
87
  )
104
- errors: list[ExportMessage]
105
- files: list[ExportedFile]
88
+ destination_directory: Annotated[str, Field(alias='destinationDirectory')]
106
89
  leaf_id: Annotated[str, Field(alias='leafId')]
107
- status: InputStatus
108
- totals: ExportTotals
109
- warnings: list[ExportMessage]
90
+ totals: Annotated[
91
+ ExportTotals,
92
+ Field(
93
+ description='What reached the bucket, also from an Input that failed partway.'
94
+ ),
95
+ ]
110
96
 
111
97
 
112
98
  class ExportReceiptV01(BaseModel):
@@ -116,12 +102,6 @@ class ExportReceiptV01(BaseModel):
116
102
  connection: Annotated[
117
103
  BucketConnection, Field(description='Where the run exported to.')
118
104
  ]
119
- errors: Annotated[
120
- list[ExportMessage],
121
- Field(
122
- description='Problems tied to no single Input, such as credentials rejected before\nany upload.'
123
- ),
124
- ]
125
105
  export_prefix: Annotated[
126
106
  str | None,
127
107
  Field(
@@ -131,7 +111,6 @@ class ExportReceiptV01(BaseModel):
131
111
  ] = None
132
112
  inputs: list[BucketInputReceipt]
133
113
  totals: ExportTotals
134
- warnings: list[ExportMessage]
135
114
  type: Literal['BUCKET']
136
115
 
137
116
 
@@ -139,39 +118,47 @@ class ExportReceiptV0(RootModel[ExportReceiptV01]):
139
118
  root: ExportReceiptV01
140
119
 
141
120
 
142
- class ExportReceipt1(BaseModel):
121
+ class ExportReportV0(BaseModel):
143
122
  model_config = ConfigDict(
144
123
  populate_by_name=True,
145
124
  )
146
- version: Literal['V0']
147
- connection: Annotated[
148
- BucketConnection, Field(description='Where the run exported to.')
149
- ]
150
- errors: Annotated[
151
- list[ExportMessage],
125
+ error: Annotated[
126
+ ExportMessage | None,
152
127
  Field(
153
- description='Problems tied to no single Input, such as credentials rejected before\nany upload.'
128
+ description="What stopped the run; the run failed exactly when it's set."
154
129
  ),
155
- ]
156
- export_prefix: Annotated[
157
- str | None,
130
+ ] = None
131
+ receipt: Annotated[
132
+ ExportReceiptV0 | None,
133
+ Field(description='Absent when the run failed before its worker could report.'),
134
+ ] = None
135
+ warnings: list[ExportMessage]
136
+
137
+
138
+ class ExportReport1(BaseModel):
139
+ model_config = ConfigDict(
140
+ populate_by_name=True,
141
+ )
142
+ error: Annotated[
143
+ ExportMessage | None,
158
144
  Field(
159
- alias='exportPrefix',
160
- description='The export prefix with its date tokens filled; `None` without one.',
145
+ description="What stopped the run; the run failed exactly when it's set."
161
146
  ),
162
147
  ] = None
163
- inputs: list[BucketInputReceipt]
164
- totals: ExportTotals
148
+ receipt: Annotated[
149
+ ExportReceiptV0 | None,
150
+ Field(description='Absent when the run failed before its worker could report.'),
151
+ ] = None
165
152
  warnings: list[ExportMessage]
166
- type: Literal['BUCKET']
153
+ version: Literal['V0']
167
154
 
168
155
 
169
- class ExportReceipt(RootModel[ExportReceipt1]):
156
+ class ExportReport(RootModel[ExportReport1]):
170
157
  root: Annotated[
171
- ExportReceipt1,
158
+ ExportReport1,
172
159
  Field(
173
- description='A released version never changes: a change is a new version, and readers\nkeep reading every version ever written.',
174
- title='ExportReceipt',
160
+ description='What an Export Connector Run reports when it ends. A released version never\nchanges: a change is a new version, and readers keep reading every version\never written.',
161
+ title='ExportReport',
175
162
  ),
176
163
  ]
177
164
 
@@ -183,12 +170,6 @@ class BucketExportReceiptV0(BaseModel):
183
170
  connection: Annotated[
184
171
  BucketConnection, Field(description='Where the run exported to.')
185
172
  ]
186
- errors: Annotated[
187
- list[ExportMessage],
188
- Field(
189
- description='Problems tied to no single Input, such as credentials rejected before\nany upload.'
190
- ),
191
- ]
192
173
  export_prefix: Annotated[
193
174
  str | None,
194
175
  Field(
@@ -198,4 +179,3 @@ class BucketExportReceiptV0(BaseModel):
198
179
  ] = None
199
180
  inputs: list[BucketInputReceipt]
200
181
  totals: ExportTotals
201
- warnings: list[ExportMessage]
@@ -0,0 +1,167 @@
1
+ """The Bucket `Export`: checks every Input's object keys, then uploads the Inputs
2
+ in turn and stops at the first that fails. Files already written stay where
3
+ they are, and the receipt counts them."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import time
8
+ import zipfile
9
+ from collections.abc import Callable, Iterator
10
+ from contextlib import contextmanager
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from dq_export_connector._models.export_connector_credentials import BucketCredentials
16
+ from dq_export_connector._models.export_report import BucketConnection as ReceiptConnection
17
+ from dq_export_connector._models.export_report import (
18
+ BucketInputReceipt,
19
+ ExportReceiptV0,
20
+ ExportReceiptV01,
21
+ ExportTotals,
22
+ )
23
+ from dq_export_connector._models.export_worker_config import BucketInput, ExportConnectorKind1, ProvisionedPolicy
24
+ from dq_export_connector.bucket.datasets import DatasetFile, open_dataset
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
27
+ from dq_export_connector.bucket.upload import plan_upload, upload
28
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError
29
+ from dq_export_connector.log import logger
30
+ from dq_export_connector.report import ReportBuilder
31
+
32
+
33
+ def export(
34
+ connector: ExportConnectorKind1,
35
+ policies: list[ProvisionedPolicy],
36
+ credentials: BucketCredentials,
37
+ inputs_dir: Path,
38
+ now: datetime,
39
+ build_store: Callable[[Any, BucketCredentials], Any],
40
+ report: ReportBuilder,
41
+ ) -> None:
42
+ export_prefix = fill_date_tokens(connector.export_prefix, now) if connector.export_prefix else None
43
+ policy_ids = {policy.leaf_id: policy.policy_id for policy in policies}
44
+ connection = connector.connection.root
45
+ logger.info(
46
+ "Export started: provider %s, %s, path prefix %r, export prefix %r resolved to %r, Inputs %s",
47
+ connection.type,
48
+ location(connection),
49
+ connection.path_prefix,
50
+ connector.export_prefix,
51
+ export_prefix,
52
+ ", ".join(f"{leaf.leaf_id} (policy {policy_ids.get(leaf.leaf_id)})" for leaf in connector.inputs),
53
+ )
54
+ receipt = ExportReceiptV01(
55
+ type="BUCKET",
56
+ connection=ReceiptConnection.model_validate(connector.connection.model_dump(by_alias=True)),
57
+ export_prefix=export_prefix,
58
+ totals=_no_totals(),
59
+ inputs=[
60
+ BucketInputReceipt(
61
+ leaf_id=bucket_input.leaf_id,
62
+ destination_directory=bucket_input.destination_directory,
63
+ totals=_no_totals(),
64
+ )
65
+ for bucket_input in connector.inputs
66
+ ],
67
+ )
68
+ report.receipt = ExportReceiptV0(root=receipt)
69
+ store = build_store(connector.connection, credentials)
70
+ for bucket_input in connector.inputs:
71
+ _check_input(bucket_input, connection, export_prefix, inputs_dir, report)
72
+ for bucket_input, receipt_input in zip(connector.inputs, receipt.inputs):
73
+ _export_input(bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals])
74
+ logger.info(
75
+ "Export finished: %d Inputs, %d files, %d bytes",
76
+ len(receipt.inputs),
77
+ receipt.totals.files,
78
+ receipt.totals.bytes,
79
+ )
80
+
81
+
82
+ def _check_input(
83
+ bucket_input: BucketInput,
84
+ connection: Any,
85
+ export_prefix: str | None,
86
+ inputs_dir: Path,
87
+ report: ReportBuilder,
88
+ ) -> None:
89
+ destination = bucket_input.destination_directory
90
+ with _reading(destination), open_dataset(inputs_dir / bucket_input.leaf_id) as (layout, _):
91
+ if layout.raw_reason is None:
92
+ logger.info("Input %s is a stored ZIP with %d files", bucket_input.leaf_id, len(layout.files))
93
+ else:
94
+ logger.info("Input %s is written as one raw file: it is %s", bucket_input.leaf_id, layout.raw_reason)
95
+ try:
96
+ for file in layout.files:
97
+ check_dataset_path(file.path)
98
+ check_key(_key(connection, export_prefix, destination, file), connection)
99
+ except InvalidPathError as error:
100
+ raise ExportConnectorError(
101
+ ErrorCode.BUCKET_INVALID_PATH, f"Nothing was exported: in the dataset for '{destination}/', {error}"
102
+ ) from error
103
+ if not layout.files:
104
+ report.warn(
105
+ ErrorCode.EMPTY_DATASET, f"The dataset for '{destination}/' has no files, so nothing was written there"
106
+ )
107
+
108
+
109
+ def _export_input(
110
+ bucket_input: BucketInput,
111
+ connection: Any,
112
+ export_prefix: str | None,
113
+ inputs_dir: Path,
114
+ store: Any,
115
+ totals: list[ExportTotals],
116
+ ) -> None:
117
+ leaf_id = bucket_input.leaf_id
118
+ destination = bucket_input.destination_directory
119
+ started = time.monotonic()
120
+ logger.info("Input %s started, destination directory %r", leaf_id, destination)
121
+ with _reading(destination), open_dataset(inputs_dir / leaf_id) as (layout, reader):
122
+ for uploaded, file in enumerate(layout.files):
123
+ key = _key(connection, export_prefix, destination, file)
124
+ plan = plan_upload(file.size)
125
+ logger.info(
126
+ "Upload of %r started: %d bytes, %s",
127
+ key,
128
+ file.size,
129
+ f"multipart with {plan.part_size}-byte parts" if plan.multipart else "single request",
130
+ )
131
+ file_started = time.monotonic()
132
+ with reader.open(file) as source:
133
+ try:
134
+ upload(store, key, source, plan)
135
+ except StorageError as error:
136
+ code = classify_error(error.cause)
137
+ raise ExportConnectorError(
138
+ code,
139
+ f"{failure_sentence(code, location(connection))}, so writing '{key}' failed after"
140
+ f" {uploaded} of {len(layout.files)} files for '{destination}/': {error}",
141
+ ) from error
142
+ logger.info("Upload of %r finished in %.1fs", key, time.monotonic() - file_started)
143
+ for total in totals:
144
+ total.files += 1
145
+ total.bytes += file.size
146
+ logger.info("Input %s exported: %d files in %.1fs", leaf_id, len(layout.files), time.monotonic() - started)
147
+
148
+
149
+ @contextmanager
150
+ def _reading(destination: str) -> Iterator[None]:
151
+ """A stored ZIP that is corrupt raises `BadZipFile`, or `EOFError` for an
152
+ entry cut short, when its entry is read."""
153
+ try:
154
+ yield
155
+ except (OSError, EOFError, zipfile.BadZipFile) as error:
156
+ raise ExportConnectorError(
157
+ ErrorCode.READ_FAILED,
158
+ f"The dataset for '{destination}/' couldn't be read: {str(error) or type(error).__name__}",
159
+ ) from error
160
+
161
+
162
+ def _key(connection: Any, export_prefix: str | None, destination: str, file: DatasetFile) -> str:
163
+ return join_key(connection.path_prefix, export_prefix, destination, file.path)
164
+
165
+
166
+ def _no_totals() -> ExportTotals:
167
+ return ExportTotals(files=0, bytes=0, rows=None)
@@ -22,7 +22,7 @@ _RESERVED_GCS_PREFIX = ".well-known/acme-challenge/"
22
22
 
23
23
 
24
24
  class InvalidPathError(ValueError):
25
- pass
25
+ """Its message completes a sentence about the dataset the path is in."""
26
26
 
27
27
 
28
28
  def fill_date_tokens(export_prefix: str, now: datetime) -> str:
@@ -49,27 +49,27 @@ def check_dataset_path(path: str) -> None:
49
49
  """A path inside a dataset, which lands below its Input's destination
50
50
  directory and must stay there."""
51
51
  if path.startswith("/"):
52
- raise InvalidPathError(f"The path {path!r} in the dataset is absolute")
52
+ raise InvalidPathError(f"the path {path!r} is absolute")
53
53
  segments = path.split("/")
54
54
  if any(segment in ("", ".", "..") for segment in segments):
55
- raise InvalidPathError(f"The path {path!r} in the dataset has an empty, '.' or '..' segment")
55
+ raise InvalidPathError(f"the path {path!r} has an empty, '.' or '..' segment")
56
56
  for character in path:
57
57
  if _is_control(character) or _is_noncharacter(character) or character == "\\":
58
- raise InvalidPathError(f"The path {path!r} in the dataset contains {character!r}")
58
+ raise InvalidPathError(f"the path {path!r} contains {character!r}")
59
59
 
60
60
 
61
61
  def check_key(key: str, connection: BucketConnection1 | BucketConnection2 | BucketConnection3) -> None:
62
62
  if f"{key}/".startswith(_RESERVED_GCS_PREFIX):
63
- raise InvalidPathError(f"The key {key!r} is under {_RESERVED_GCS_PREFIX!r}, which GCS reserves")
63
+ raise InvalidPathError(f"the object key {key!r} is under {_RESERVED_GCS_PREFIX!r}, which GCS reserves")
64
64
  match connection:
65
65
  case BucketConnection1() | BucketConnection3():
66
66
  if len(key.encode("utf-8")) > PROVIDER_MAX_KEY_BYTES:
67
- raise InvalidPathError(f"The key {key!r} is longer than {PROVIDER_MAX_KEY_BYTES} bytes")
67
+ raise InvalidPathError(f"the object key {key!r} is longer than {PROVIDER_MAX_KEY_BYTES} bytes")
68
68
  case BucketConnection2():
69
69
  if len(key) > AZURE_MAX_KEY_CHARACTERS:
70
- raise InvalidPathError(f"The key {key!r} is longer than {AZURE_MAX_KEY_CHARACTERS} characters")
70
+ raise InvalidPathError(f"the object key {key!r} is longer than {AZURE_MAX_KEY_CHARACTERS} characters")
71
71
  if key.count("/") + 1 > AZURE_MAX_KEY_SEGMENTS:
72
- raise InvalidPathError(f"The key {key!r} has more than {AZURE_MAX_KEY_SEGMENTS} segments")
72
+ raise InvalidPathError(f"the object key {key!r} has more than {AZURE_MAX_KEY_SEGMENTS} segments")
73
73
 
74
74
 
75
75
  def _is_control(character: str) -> bool:
@@ -23,6 +23,8 @@ from dq_export_connector._models.export_worker_config import (
23
23
  BucketConnection3,
24
24
  )
25
25
 
26
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError
27
+
26
28
  if TYPE_CHECKING:
27
29
  from obstore.store import ClientConfig, RetryConfig
28
30
 
@@ -52,22 +54,20 @@ CLIENT_CONFIG: ClientConfig = {
52
54
  "read_timeout": timedelta(seconds=60),
53
55
  }
54
56
 
55
- INVALID_CREDENTIALS = "INVALID_CREDENTIALS"
56
- UNAUTHENTICATED = "UNAUTHENTICATED"
57
- ACCESS_DENIED = "ACCESS_DENIED"
58
- NOT_FOUND = "NOT_FOUND"
59
- UNREACHABLE = "UNREACHABLE"
60
- UNKNOWN = "UNKNOWN"
57
+ T = TypeVar("T")
61
58
 
62
59
 
63
- T = TypeVar("T")
60
+ def describe(error: Exception) -> str:
61
+ """obstore's message without the `Debug source:` dump it appends, which
62
+ repeats the error."""
63
+ return str(error).split("\n\nDebug source:", 1)[0]
64
64
 
65
65
 
66
66
  class StorageError(Exception):
67
67
  """A request to the Bucket Provider failed; `cause` is obstore's error."""
68
68
 
69
69
  def __init__(self, cause: Exception) -> None:
70
- super().__init__(str(cause))
70
+ super().__init__(describe(cause))
71
71
  self.cause = cause
72
72
 
73
73
 
@@ -86,11 +86,6 @@ def storage_call(call: Callable[[], T]) -> T:
86
86
  raise StorageError(error) from error
87
87
 
88
88
 
89
- class InvalidCredentialsError(ValueError):
90
- """Credentials that can't be used as given, such as an empty Azure SAS token
91
- or a SAS URL pasted where the token belongs."""
92
-
93
-
94
89
  # Provider error codes that mean bad credentials. They are checked before the
95
90
  # error's type: S3's SignatureDoesNotMatch and InvalidAccessKeyId arrive as a
96
91
  # 403, which object_store raises as permission denied.
@@ -110,9 +105,9 @@ _CREDENTIAL_CODES: tuple[str, ...] = (
110
105
  # Provider error codes recognised in an error's message, checked in order.
111
106
  # object_store wraps many non-2xx responses in a generic error, so the
112
107
  # provider's code in the message is often the only signal.
113
- _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
108
+ _MESSAGE_CLASSIFIERS: list[tuple[ErrorCode, tuple[str, ...]]] = [
114
109
  (
115
- UNAUTHENTICATED,
110
+ ErrorCode.UNAUTHENTICATED,
116
111
  (
117
112
  # S3
118
113
  "SignatureDoesNotMatch",
@@ -128,7 +123,7 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
128
123
  ),
129
124
  ),
130
125
  (
131
- ACCESS_DENIED,
126
+ ErrorCode.ACCESS_DENIED,
132
127
  (
133
128
  "AccessDenied", # S3
134
129
  "AuthorizationFailure", # Azure
@@ -138,16 +133,19 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
138
133
  ),
139
134
  ),
140
135
  (
141
- NOT_FOUND,
136
+ ErrorCode.DESTINATION_NOT_FOUND,
142
137
  (
143
138
  "NoSuchBucket", # S3
139
+ # S3, for a bucket in another region than the connection's
140
+ "PermanentRedirect",
141
+ "incorrectly configured region",
144
142
  "ContainerNotFound", # Azure
145
143
  "bucket does not exist", # GCS
146
144
  "status code: 404",
147
145
  ),
148
146
  ),
149
147
  (
150
- UNREACHABLE,
148
+ ErrorCode.UNREACHABLE,
151
149
  (
152
150
  "error sending request",
153
151
  "dns error",
@@ -159,26 +157,60 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
159
157
  ]
160
158
 
161
159
 
162
- def classify_error(error: Exception) -> str:
160
+ def classify_error(error: Exception) -> ErrorCode:
163
161
  """Maps a storage error to a code, the same for every Bucket Provider."""
164
162
  message = str(error)
165
- if isinstance(error, InvalidCredentialsError):
166
- return INVALID_CREDENTIALS
167
163
  if any(code in message for code in _CREDENTIAL_CODES):
168
- return UNAUTHENTICATED
164
+ return ErrorCode.UNAUTHENTICATED
169
165
  if isinstance(error, obstore.exceptions.UnauthenticatedError):
170
- return UNAUTHENTICATED
166
+ return ErrorCode.UNAUTHENTICATED
171
167
  if isinstance(error, obstore.exceptions.PermissionDeniedError):
172
- return ACCESS_DENIED
168
+ return ErrorCode.ACCESS_DENIED
173
169
  if isinstance(error, FileNotFoundError):
174
- return NOT_FOUND
170
+ return ErrorCode.DESTINATION_NOT_FOUND
175
171
  for code, needles in _MESSAGE_CLASSIFIERS:
176
172
  if any(needle in message for needle in needles):
177
173
  return code
178
- return UNKNOWN
174
+ return ErrorCode.UNKNOWN
175
+
176
+
177
+ def location(connection: BucketConnection1 | BucketConnection2 | BucketConnection3) -> str:
178
+ match connection:
179
+ case BucketConnection1():
180
+ return f"bucket '{connection.bucket}' in {connection.region}"
181
+ case BucketConnection2():
182
+ return f"container '{connection.container}' of account '{connection.account_name}'"
183
+ case BucketConnection3():
184
+ return f"bucket '{connection.bucket}'"
185
+
186
+
187
+ def failure_sentence(code: ErrorCode, where: str) -> str:
188
+ """What a storage error with `code` means, as the start of a message."""
189
+ match code:
190
+ case ErrorCode.UNAUTHENTICATED:
191
+ return f"The {where} rejected the credentials"
192
+ case ErrorCode.ACCESS_DENIED:
193
+ return f"The credentials may not write to the {where}"
194
+ case ErrorCode.DESTINATION_NOT_FOUND:
195
+ return f"The {where} doesn't exist"
196
+ case ErrorCode.UNREACHABLE:
197
+ return f"The {where} couldn't be reached"
198
+ case _:
199
+ return f"The {where} returned an error"
179
200
 
180
201
 
181
202
  def build_store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
203
+ """obstore parses the credentials here, so a malformed GCS key or Azure SAS
204
+ token fails before any request."""
205
+ try:
206
+ return _store(connection, credentials)
207
+ except obstore.exceptions.BaseError as error:
208
+ raise ExportConnectorError(
209
+ ErrorCode.INVALID_CREDENTIALS, f"The credentials couldn't be read: {describe(error)}"
210
+ ) from error
211
+
212
+
213
+ def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
182
214
  """ddc pins the provider pairing, so a mismatch here is a bug."""
183
215
  match (connection.root, credentials.root):
184
216
  case (BucketConnection1() as s3, BucketCredentials1() as s3_credentials):
@@ -214,9 +246,11 @@ def _normalize_azure_sas_token(sas_token: str) -> str:
214
246
  hiding a paste error."""
215
247
  token = sas_token.strip().lstrip("?")
216
248
  if "://" in token:
217
- raise InvalidCredentialsError(
218
- "Expected an Azure SAS token (the query-string part, `sv=...&sig=...`), not a SAS URL"
249
+ raise ExportConnectorError(
250
+ ErrorCode.INVALID_CREDENTIALS,
251
+ "The credentials hold an Azure SAS URL where the SAS token belongs:"
252
+ " paste only its query-string part, `sv=...&sig=...`",
219
253
  )
220
254
  if not token:
221
- raise InvalidCredentialsError("The Azure SAS token is empty")
255
+ raise ExportConnectorError(ErrorCode.INVALID_CREDENTIALS, "The Azure SAS token in the credentials is empty")
222
256
  return token