dq-export-connector 0.1.0.dev6__tar.gz → 0.1.0.dev8__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 (35) hide show
  1. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/PKG-INFO +7 -3
  2. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/README.md +6 -2
  3. dq_export_connector-0.1.0.dev8/dq_export_connector/_models/bucket_validation_result.py +34 -0
  4. dq_export_connector-0.1.0.dev6/dq_export_connector/_models/export_receipt.py → dq_export_connector-0.1.0.dev8/dq_export_connector/_models/export_report.py +36 -57
  5. dq_export_connector-0.1.0.dev8/dq_export_connector/bucket/export.py +163 -0
  6. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/bucket/paths.py +8 -8
  7. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/bucket/store.py +43 -29
  8. dq_export_connector-0.1.0.dev8/dq_export_connector/bucket/validate.py +57 -0
  9. dq_export_connector-0.1.0.dev8/dq_export_connector/errors.py +50 -0
  10. dq_export_connector-0.1.0.dev8/dq_export_connector/report.py +39 -0
  11. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/runner.py +33 -7
  12. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/pyproject.toml +1 -1
  13. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/scripts/codegen-models.sh +1 -1
  14. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/tests/test_live_buckets.py +8 -9
  15. dq_export_connector-0.1.0.dev8/tests/test_runner.py +255 -0
  16. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/uv.lock +1 -1
  17. dq_export_connector-0.1.0.dev6/dq_export_connector/_models/bucket_validation_result.py +0 -63
  18. dq_export_connector-0.1.0.dev6/dq_export_connector/bucket/export.py +0 -225
  19. dq_export_connector-0.1.0.dev6/dq_export_connector/bucket/validate.py +0 -76
  20. dq_export_connector-0.1.0.dev6/tests/test_runner.py +0 -195
  21. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/.gitignore +0 -0
  22. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/.python-version +0 -0
  23. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/__init__.py +0 -0
  24. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/_models/__init__.py +0 -0
  25. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/_models/export_connector_credentials.py +0 -0
  26. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/_models/export_worker_config.py +0 -0
  27. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/bucket/__init__.py +0 -0
  28. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/bucket/datasets.py +0 -0
  29. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/bucket/upload.py +0 -0
  30. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/log.py +0 -0
  31. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/dq_export_connector/redact.py +0 -0
  32. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/tests/test_models_are_current.py +0 -0
  33. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/tests/test_paths.py +0 -0
  34. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/tests/test_redact.py +0 -0
  35. {dq_export_connector-0.1.0.dev6 → dq_export_connector-0.1.0.dev8}/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.dev6
3
+ Version: 0.1.0.dev8
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.
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.
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,34 @@
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.'
25
+ ),
26
+ ]
27
+
28
+
29
+ class BucketValidationResult(BaseModel):
30
+ model_config = ConfigDict(
31
+ populate_by_name=True,
32
+ )
33
+ error: ExportMessage | None = None
34
+ 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
@@ -81,32 +80,18 @@ class ExportTotals(BaseModel):
81
80
  ] = None
82
81
 
83
82
 
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
83
  class BucketInputReceipt(BaseModel):
101
84
  model_config = ConfigDict(
102
85
  populate_by_name=True,
103
86
  )
104
- errors: list[ExportMessage]
105
- files: list[ExportedFile]
87
+ destination_directory: Annotated[str, Field(alias='destinationDirectory')]
106
88
  leaf_id: Annotated[str, Field(alias='leafId')]
107
- status: InputStatus
108
- totals: ExportTotals
109
- warnings: list[ExportMessage]
89
+ totals: Annotated[
90
+ ExportTotals,
91
+ Field(
92
+ description='What reached the bucket, also from an Input that failed partway.'
93
+ ),
94
+ ]
110
95
 
111
96
 
112
97
  class ExportReceiptV01(BaseModel):
@@ -116,12 +101,6 @@ class ExportReceiptV01(BaseModel):
116
101
  connection: Annotated[
117
102
  BucketConnection, Field(description='Where the run exported to.')
118
103
  ]
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
104
  export_prefix: Annotated[
126
105
  str | None,
127
106
  Field(
@@ -131,7 +110,6 @@ class ExportReceiptV01(BaseModel):
131
110
  ] = None
132
111
  inputs: list[BucketInputReceipt]
133
112
  totals: ExportTotals
134
- warnings: list[ExportMessage]
135
113
  type: Literal['BUCKET']
136
114
 
137
115
 
@@ -139,39 +117,47 @@ class ExportReceiptV0(RootModel[ExportReceiptV01]):
139
117
  root: ExportReceiptV01
140
118
 
141
119
 
142
- class ExportReceipt1(BaseModel):
120
+ class ExportReportV0(BaseModel):
143
121
  model_config = ConfigDict(
144
122
  populate_by_name=True,
145
123
  )
146
- version: Literal['V0']
147
- connection: Annotated[
148
- BucketConnection, Field(description='Where the run exported to.')
149
- ]
150
- errors: Annotated[
151
- list[ExportMessage],
124
+ error: Annotated[
125
+ ExportMessage | None,
152
126
  Field(
153
- description='Problems tied to no single Input, such as credentials rejected before\nany upload.'
127
+ description="What stopped the run; the run failed exactly when it's set."
154
128
  ),
155
- ]
156
- export_prefix: Annotated[
157
- str | None,
129
+ ] = None
130
+ receipt: Annotated[
131
+ ExportReceiptV0 | None,
132
+ Field(description='Absent when the run failed before its worker could report.'),
133
+ ] = None
134
+ warnings: list[ExportMessage]
135
+
136
+
137
+ class ExportReport1(BaseModel):
138
+ model_config = ConfigDict(
139
+ populate_by_name=True,
140
+ )
141
+ error: Annotated[
142
+ ExportMessage | None,
158
143
  Field(
159
- alias='exportPrefix',
160
- description='The export prefix with its date tokens filled; `None` without one.',
144
+ description="What stopped the run; the run failed exactly when it's set."
161
145
  ),
162
146
  ] = None
163
- inputs: list[BucketInputReceipt]
164
- totals: ExportTotals
147
+ receipt: Annotated[
148
+ ExportReceiptV0 | None,
149
+ Field(description='Absent when the run failed before its worker could report.'),
150
+ ] = None
165
151
  warnings: list[ExportMessage]
166
- type: Literal['BUCKET']
152
+ version: Literal['V0']
167
153
 
168
154
 
169
- class ExportReceipt(RootModel[ExportReceipt1]):
155
+ class ExportReport(RootModel[ExportReport1]):
170
156
  root: Annotated[
171
- ExportReceipt1,
157
+ ExportReport1,
172
158
  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',
159
+ 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.',
160
+ title='ExportReport',
175
161
  ),
176
162
  ]
177
163
 
@@ -183,12 +169,6 @@ class BucketExportReceiptV0(BaseModel):
183
169
  connection: Annotated[
184
170
  BucketConnection, Field(description='Where the run exported to.')
185
171
  ]
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
172
  export_prefix: Annotated[
193
173
  str | None,
194
174
  Field(
@@ -198,4 +178,3 @@ class BucketExportReceiptV0(BaseModel):
198
178
  ] = None
199
179
  inputs: list[BucketInputReceipt]
200
180
  totals: ExportTotals
201
- warnings: list[ExportMessage]
@@ -0,0 +1,163 @@
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
+ from collections.abc import Callable, Iterator
9
+ from contextlib import contextmanager
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from dq_export_connector._models.export_connector_credentials import BucketCredentials
15
+ from dq_export_connector._models.export_report import BucketConnection as ReceiptConnection
16
+ from dq_export_connector._models.export_report import (
17
+ BucketInputReceipt,
18
+ ExportReceiptV0,
19
+ ExportReceiptV01,
20
+ ExportTotals,
21
+ )
22
+ from dq_export_connector._models.export_worker_config import BucketInput, ExportConnectorKind1, ProvisionedPolicy
23
+ from dq_export_connector.bucket.datasets import DatasetFile, open_dataset
24
+ from dq_export_connector.bucket.paths import InvalidPathError, check_dataset_path, check_key, fill_date_tokens, join_key
25
+ from dq_export_connector.bucket.store import StorageError, classify_error, failure_sentence, location
26
+ from dq_export_connector.bucket.upload import plan_upload, upload
27
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError
28
+ from dq_export_connector.log import logger
29
+ from dq_export_connector.report import ReportBuilder
30
+
31
+
32
+ def export(
33
+ connector: ExportConnectorKind1,
34
+ policies: list[ProvisionedPolicy],
35
+ credentials: BucketCredentials,
36
+ inputs_dir: Path,
37
+ now: datetime,
38
+ build_store: Callable[[Any, BucketCredentials], Any],
39
+ report: ReportBuilder,
40
+ ) -> None:
41
+ export_prefix = fill_date_tokens(connector.export_prefix, now) if connector.export_prefix else None
42
+ policy_ids = {policy.leaf_id: policy.policy_id for policy in policies}
43
+ connection = connector.connection.root
44
+ logger.info(
45
+ "Export started: provider %s, %s, path prefix %r, export prefix %r resolved to %r, Inputs %s",
46
+ connection.type,
47
+ location(connection),
48
+ connection.path_prefix,
49
+ connector.export_prefix,
50
+ export_prefix,
51
+ ", ".join(f"{leaf.leaf_id} (policy {policy_ids.get(leaf.leaf_id)})" for leaf in connector.inputs),
52
+ )
53
+ receipt = ExportReceiptV01(
54
+ type="BUCKET",
55
+ connection=ReceiptConnection.model_validate(connector.connection.model_dump(by_alias=True)),
56
+ export_prefix=export_prefix,
57
+ totals=_no_totals(),
58
+ inputs=[
59
+ BucketInputReceipt(
60
+ leaf_id=bucket_input.leaf_id,
61
+ destination_directory=bucket_input.destination_directory,
62
+ totals=_no_totals(),
63
+ )
64
+ for bucket_input in connector.inputs
65
+ ],
66
+ )
67
+ report.receipt = ExportReceiptV0(root=receipt)
68
+ store = build_store(connector.connection, credentials)
69
+ for bucket_input in connector.inputs:
70
+ _check_input(bucket_input, connection, export_prefix, inputs_dir, report)
71
+ for bucket_input, receipt_input in zip(connector.inputs, receipt.inputs):
72
+ _export_input(bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals])
73
+ logger.info(
74
+ "Export finished: %d Inputs, %d files, %d bytes",
75
+ len(receipt.inputs),
76
+ receipt.totals.files,
77
+ receipt.totals.bytes,
78
+ )
79
+
80
+
81
+ def _check_input(
82
+ bucket_input: BucketInput,
83
+ connection: Any,
84
+ export_prefix: str | None,
85
+ inputs_dir: Path,
86
+ report: ReportBuilder,
87
+ ) -> None:
88
+ destination = bucket_input.destination_directory
89
+ with _reading(destination), open_dataset(inputs_dir / bucket_input.leaf_id) as (layout, _):
90
+ if layout.raw_reason is None:
91
+ logger.info("Input %s is a stored ZIP with %d files", bucket_input.leaf_id, len(layout.files))
92
+ else:
93
+ logger.info("Input %s is written as one raw file: it is %s", bucket_input.leaf_id, layout.raw_reason)
94
+ try:
95
+ for file in layout.files:
96
+ check_dataset_path(file.path)
97
+ check_key(_key(connection, export_prefix, destination, file), connection)
98
+ except InvalidPathError as error:
99
+ raise ExportConnectorError(
100
+ ErrorCode.BUCKET_INVALID_PATH, f"Nothing was exported: in the dataset for '{destination}/', {error}"
101
+ ) from error
102
+ if not layout.files:
103
+ report.warn(
104
+ ErrorCode.EMPTY_DATASET, f"The dataset for '{destination}/' has no files, so nothing was written there"
105
+ )
106
+
107
+
108
+ def _export_input(
109
+ bucket_input: BucketInput,
110
+ connection: Any,
111
+ export_prefix: str | None,
112
+ inputs_dir: Path,
113
+ store: Any,
114
+ totals: list[ExportTotals],
115
+ ) -> None:
116
+ leaf_id = bucket_input.leaf_id
117
+ destination = bucket_input.destination_directory
118
+ started = time.monotonic()
119
+ logger.info("Input %s started, destination directory %r", leaf_id, destination)
120
+ with _reading(destination), open_dataset(inputs_dir / leaf_id) as (layout, reader):
121
+ for uploaded, file in enumerate(layout.files):
122
+ key = _key(connection, export_prefix, destination, file)
123
+ plan = plan_upload(file.size)
124
+ logger.info(
125
+ "Upload of %r started: %d bytes, %s",
126
+ key,
127
+ file.size,
128
+ f"multipart with {plan.part_size}-byte parts" if plan.multipart else "single request",
129
+ )
130
+ file_started = time.monotonic()
131
+ with reader.open(file) as source:
132
+ try:
133
+ upload(store, key, source, plan)
134
+ except StorageError as error:
135
+ code = classify_error(error.cause)
136
+ raise ExportConnectorError(
137
+ code,
138
+ f"{failure_sentence(code, location(connection))}, so writing '{key}' failed after"
139
+ f" {uploaded} of {len(layout.files)} files for '{destination}/': {error}",
140
+ ) from error
141
+ logger.info("Upload of %r finished in %.1fs", key, time.monotonic() - file_started)
142
+ for total in totals:
143
+ total.files += 1
144
+ total.bytes += file.size
145
+ logger.info("Input %s exported: %d files in %.1fs", leaf_id, len(layout.files), time.monotonic() - started)
146
+
147
+
148
+ @contextmanager
149
+ def _reading(destination: str) -> Iterator[None]:
150
+ try:
151
+ yield
152
+ except OSError as error:
153
+ raise ExportConnectorError(
154
+ ErrorCode.READ_FAILED, f"The dataset for '{destination}/' couldn't be read: {error}"
155
+ ) from error
156
+
157
+
158
+ def _key(connection: Any, export_prefix: str | None, destination: str, file: DatasetFile) -> str:
159
+ return join_key(connection.path_prefix, export_prefix, destination, file.path)
160
+
161
+
162
+ def _no_totals() -> ExportTotals:
163
+ 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,14 +54,6 @@ 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"
61
-
62
-
63
57
  T = TypeVar("T")
64
58
 
65
59
 
@@ -86,11 +80,6 @@ def storage_call(call: Callable[[], T]) -> T:
86
80
  raise StorageError(error) from error
87
81
 
88
82
 
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
83
  # Provider error codes that mean bad credentials. They are checked before the
95
84
  # error's type: S3's SignatureDoesNotMatch and InvalidAccessKeyId arrive as a
96
85
  # 403, which object_store raises as permission denied.
@@ -110,9 +99,9 @@ _CREDENTIAL_CODES: tuple[str, ...] = (
110
99
  # Provider error codes recognised in an error's message, checked in order.
111
100
  # object_store wraps many non-2xx responses in a generic error, so the
112
101
  # provider's code in the message is often the only signal.
113
- _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
102
+ _MESSAGE_CLASSIFIERS: list[tuple[ErrorCode, tuple[str, ...]]] = [
114
103
  (
115
- UNAUTHENTICATED,
104
+ ErrorCode.UNAUTHENTICATED,
116
105
  (
117
106
  # S3
118
107
  "SignatureDoesNotMatch",
@@ -128,7 +117,7 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
128
117
  ),
129
118
  ),
130
119
  (
131
- ACCESS_DENIED,
120
+ ErrorCode.ACCESS_DENIED,
132
121
  (
133
122
  "AccessDenied", # S3
134
123
  "AuthorizationFailure", # Azure
@@ -138,7 +127,7 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
138
127
  ),
139
128
  ),
140
129
  (
141
- NOT_FOUND,
130
+ ErrorCode.DESTINATION_NOT_FOUND,
142
131
  (
143
132
  "NoSuchBucket", # S3
144
133
  "ContainerNotFound", # Azure
@@ -147,7 +136,7 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
147
136
  ),
148
137
  ),
149
138
  (
150
- UNREACHABLE,
139
+ ErrorCode.UNREACHABLE,
151
140
  (
152
141
  "error sending request",
153
142
  "dns error",
@@ -159,23 +148,46 @@ _MESSAGE_CLASSIFIERS: list[tuple[str, tuple[str, ...]]] = [
159
148
  ]
160
149
 
161
150
 
162
- def classify_error(error: Exception) -> str:
151
+ def classify_error(error: Exception) -> ErrorCode:
163
152
  """Maps a storage error to a code, the same for every Bucket Provider."""
164
153
  message = str(error)
165
- if isinstance(error, InvalidCredentialsError):
166
- return INVALID_CREDENTIALS
167
154
  if any(code in message for code in _CREDENTIAL_CODES):
168
- return UNAUTHENTICATED
155
+ return ErrorCode.UNAUTHENTICATED
169
156
  if isinstance(error, obstore.exceptions.UnauthenticatedError):
170
- return UNAUTHENTICATED
157
+ return ErrorCode.UNAUTHENTICATED
171
158
  if isinstance(error, obstore.exceptions.PermissionDeniedError):
172
- return ACCESS_DENIED
159
+ return ErrorCode.ACCESS_DENIED
173
160
  if isinstance(error, FileNotFoundError):
174
- return NOT_FOUND
161
+ return ErrorCode.DESTINATION_NOT_FOUND
175
162
  for code, needles in _MESSAGE_CLASSIFIERS:
176
163
  if any(needle in message for needle in needles):
177
164
  return code
178
- return UNKNOWN
165
+ return ErrorCode.UNKNOWN
166
+
167
+
168
+ def location(connection: BucketConnection1 | BucketConnection2 | BucketConnection3) -> str:
169
+ match connection:
170
+ case BucketConnection1():
171
+ return f"bucket '{connection.bucket}' in {connection.region}"
172
+ case BucketConnection2():
173
+ return f"container '{connection.container}' of account '{connection.account_name}'"
174
+ case BucketConnection3():
175
+ return f"bucket '{connection.bucket}'"
176
+
177
+
178
+ def failure_sentence(code: ErrorCode, where: str) -> str:
179
+ """What a storage error with `code` means, as the start of a message."""
180
+ match code:
181
+ case ErrorCode.UNAUTHENTICATED:
182
+ return f"The {where} rejected the credentials"
183
+ case ErrorCode.ACCESS_DENIED:
184
+ return f"The credentials may not write to the {where}"
185
+ case ErrorCode.DESTINATION_NOT_FOUND:
186
+ return f"The {where} doesn't exist"
187
+ case ErrorCode.UNREACHABLE:
188
+ return f"The {where} couldn't be reached"
189
+ case _:
190
+ return f"The {where} returned an error"
179
191
 
180
192
 
181
193
  def build_store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
@@ -214,9 +226,11 @@ def _normalize_azure_sas_token(sas_token: str) -> str:
214
226
  hiding a paste error."""
215
227
  token = sas_token.strip().lstrip("?")
216
228
  if "://" in token:
217
- raise InvalidCredentialsError(
218
- "Expected an Azure SAS token (the query-string part, `sv=...&sig=...`), not a SAS URL"
229
+ raise ExportConnectorError(
230
+ ErrorCode.INVALID_CREDENTIALS,
231
+ "The credentials hold an Azure SAS URL where the SAS token belongs:"
232
+ " paste only its query-string part, `sv=...&sig=...`",
219
233
  )
220
234
  if not token:
221
- raise InvalidCredentialsError("The Azure SAS token is empty")
235
+ raise ExportConnectorError(ErrorCode.INVALID_CREDENTIALS, "The Azure SAS token in the credentials is empty")
222
236
  return token
@@ -0,0 +1,57 @@
1
+ """The Bucket `ValidateConnection`: writes a probe object under the path prefix
2
+ and deletes it again. Connection problems are reported in the result, and the
3
+ task still succeeds."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import uuid
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ import obstore
12
+
13
+ from dq_export_connector._models.export_connector_credentials import BucketCredentials
14
+ from dq_export_connector._models.export_worker_config import BucketConnection
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
17
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError
18
+ from dq_export_connector.log import logger
19
+ from dq_export_connector.report import ReportBuilder
20
+
21
+ PROBE_CONTENT = b"Written by a Decentriq connection test; safe to delete."
22
+
23
+
24
+ def probe_key(path_prefix: str | None) -> str:
25
+ return join_key(path_prefix, f"_decentriq_connection_test_{uuid.uuid4().hex}")
26
+
27
+
28
+ def validate_connection(
29
+ connection: BucketConnection,
30
+ credentials: BucketCredentials,
31
+ build_store: Callable[[BucketConnection, BucketCredentials], Any],
32
+ report: ReportBuilder,
33
+ ) -> None:
34
+ logger.info("Connection test started: provider %s", connection.root.type)
35
+ store = build_store(connection, credentials)
36
+ key = probe_key(connection.root.path_prefix)
37
+ try:
38
+ storage_call(lambda: obstore.put(store, key, PROBE_CONTENT))
39
+ except StorageError as error:
40
+ code = classify_error(error.cause)
41
+ raise ExportConnectorError(
42
+ code,
43
+ f"{failure_sentence(code, location(connection.root))}, so the connection test couldn't write"
44
+ f" its test object '{key}': {error}",
45
+ ) from error
46
+ logger.info("Wrote the probe %r", key)
47
+
48
+ try:
49
+ storage_call(lambda: obstore.delete(store, key))
50
+ except StorageError as error:
51
+ logger.warning("Deleting the probe %r failed: %s", key, error)
52
+ report.warn(
53
+ ErrorCode.BUCKET_PROBE_NOT_DELETED,
54
+ f"The connection test wrote its test object '{key}' but couldn't delete it; it's safe to delete: {error}",
55
+ )
56
+ return
57
+ logger.info("Deleted the probe %r; the connection works", key)