Package not found. Please check the package name and try again.
dq-export-connector 0.1.0.dev10__tar.gz → 0.1.0.dev11__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.
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/PKG-INFO +8 -6
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/README.md +5 -4
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/datasets.py +28 -13
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/export.py +19 -4
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/paths.py +13 -3
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/store.py +43 -79
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/upload.py +6 -2
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/errors.py +2 -1
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/runner.py +17 -7
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/pyproject.toml +9 -2
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_live_buckets.py +56 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_paths.py +6 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_runner.py +109 -5
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_store.py +61 -7
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/uv.lock +10 -3
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/.gitignore +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/.python-version +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/__init__.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/__init__.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/bucket_validation_result.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_connector_credentials.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_report.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_worker_config.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/__init__.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/validate.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/log.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/redact.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/report.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/scripts/codegen-models.sh +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_models_are_current.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_redact.py +0 -0
- {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_upload.py +0 -0
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: dq-export-connector
|
|
3
|
-
Version: 0.1.0.
|
|
3
|
+
Version: 0.1.0.dev11
|
|
4
4
|
Summary: Worker logic for the Export Connector DCR.
|
|
5
5
|
Author: Decentriq
|
|
6
6
|
Requires-Python: >=3.10
|
|
7
|
-
Requires-Dist: obstore<0.12,>=0.11.1
|
|
8
7
|
Requires-Dist: pydantic<2.8,>=2.7
|
|
8
|
+
Provides-Extra: bucket
|
|
9
|
+
Requires-Dist: obstore<0.12,>=0.11.1; extra == 'bucket'
|
|
9
10
|
Description-Content-Type: text/markdown
|
|
10
11
|
|
|
11
12
|
# dq-export-connector
|
|
12
13
|
|
|
13
14
|
Worker logic for the **Export Connector DCR**: one package for every
|
|
14
|
-
Connector Kind, each in its own sub-package
|
|
15
|
-
Input's dataset to S3, Azure
|
|
16
|
-
[`obstore`](https://developmentseed.org/obstore/).
|
|
15
|
+
Connector Kind, each in its own sub-package with an extra of the same name for
|
|
16
|
+
its dependencies. The **bucket** kind uploads each Input's dataset to S3, Azure
|
|
17
|
+
Blob or GCS through [`obstore`](https://developmentseed.org/obstore/).
|
|
17
18
|
|
|
18
19
|
ddc pins this package by hash in a fully locked `requirements.txt` and runs
|
|
19
20
|
`dq_export_connector.runner.main` in the task's Python environment. It is
|
|
@@ -48,4 +49,5 @@ uv run mypy dq_export_connector tests
|
|
|
48
49
|
Bump `version` in `pyproject.toml`, then push a `dq-export-connector-v<version>`
|
|
49
50
|
tag; the `Publish dq-export-connector to PyPI` workflow tests, builds and uploads
|
|
50
51
|
it. Use `.devN` versions while developing; PyPI releases can't be replaced.
|
|
51
|
-
ddc then pins the new version in a new
|
|
52
|
+
ddc then pins the new version for each kind that should run it, in a new
|
|
53
|
+
`export_connector/v0/worker/<version>/<kind>/`, written by `worker/lock.sh`.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# dq-export-connector
|
|
2
2
|
|
|
3
3
|
Worker logic for the **Export Connector DCR**: one package for every
|
|
4
|
-
Connector Kind, each in its own sub-package
|
|
5
|
-
Input's dataset to S3, Azure
|
|
6
|
-
[`obstore`](https://developmentseed.org/obstore/).
|
|
4
|
+
Connector Kind, each in its own sub-package with an extra of the same name for
|
|
5
|
+
its dependencies. The **bucket** kind uploads each Input's dataset to S3, Azure
|
|
6
|
+
Blob or GCS through [`obstore`](https://developmentseed.org/obstore/).
|
|
7
7
|
|
|
8
8
|
ddc pins this package by hash in a fully locked `requirements.txt` and runs
|
|
9
9
|
`dq_export_connector.runner.main` in the task's Python environment. It is
|
|
@@ -38,4 +38,5 @@ uv run mypy dq_export_connector tests
|
|
|
38
38
|
Bump `version` in `pyproject.toml`, then push a `dq-export-connector-v<version>`
|
|
39
39
|
tag; the `Publish dq-export-connector to PyPI` workflow tests, builds and uploads
|
|
40
40
|
it. Use `.devN` versions while developing; PyPI releases can't be replaced.
|
|
41
|
-
ddc then pins the new version in a new
|
|
41
|
+
ddc then pins the new version for each kind that should run it, in a new
|
|
42
|
+
`export_connector/v0/worker/<version>/<kind>/`, written by `worker/lock.sh`.
|
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
"""How an Input's dataset maps to files. A ZIP whose entries are all stored
|
|
2
2
|
without compression is unpacked, each entry keeping its path. Anything else,
|
|
3
|
-
including a ZIP with a compressed entry, is one raw file named
|
|
4
|
-
|
|
3
|
+
including a ZIP with a compressed or an encrypted entry, is one raw file named
|
|
4
|
+
`data`."""
|
|
5
5
|
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
8
|
import zipfile
|
|
9
9
|
from collections.abc import Iterator
|
|
10
10
|
from contextlib import contextmanager
|
|
11
|
-
from dataclasses import dataclass
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
from typing import BinaryIO
|
|
14
14
|
|
|
15
15
|
RAW_FILE_NAME = "data"
|
|
16
|
-
# The ZIP general purpose
|
|
16
|
+
# The ZIP general purpose flags of an encrypted entry and of a UTF-8 name.
|
|
17
17
|
_ENCRYPTED = 0x1
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class UnreadableDatasetError(Exception):
|
|
21
|
-
pass
|
|
18
|
+
_UTF8_NAME = 0x800
|
|
22
19
|
|
|
23
20
|
|
|
24
21
|
@dataclass(frozen=True)
|
|
@@ -27,6 +24,7 @@ class DatasetFile:
|
|
|
27
24
|
|
|
28
25
|
path: str
|
|
29
26
|
size: int
|
|
27
|
+
zip_entry: zipfile.ZipInfo | None = field(default=None, compare=False)
|
|
30
28
|
|
|
31
29
|
|
|
32
30
|
@dataclass(frozen=True)
|
|
@@ -53,13 +51,28 @@ def open_dataset(dataset_path: Path) -> Iterator[tuple[Layout, _Reader]]:
|
|
|
53
51
|
size = dataset_path.stat().st_size
|
|
54
52
|
yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with compressed entries"), _RawReader(dataset_path)
|
|
55
53
|
return
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
if any(entry.flag_bits & _ENCRYPTED for entry in entries):
|
|
55
|
+
size = dataset_path.stat().st_size
|
|
56
|
+
yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with encrypted entries"), _RawReader(dataset_path)
|
|
57
|
+
return
|
|
58
|
+
named = [(_name(entry), entry) for entry in entries]
|
|
59
|
+
# An entry is a directory by its name alone, whatever its attributes say.
|
|
60
|
+
files = [DatasetFile(name, entry.file_size, entry) for name, entry in named if not name.endswith("/")]
|
|
60
61
|
yield Layout(files, None), _ZipReader(archive)
|
|
61
62
|
|
|
62
63
|
|
|
64
|
+
def _name(entry: zipfile.ZipInfo) -> str:
|
|
65
|
+
"""`zipfile` decodes a name without the UTF-8 flag as CP437. Many tools
|
|
66
|
+
write UTF-8 without setting the flag, so such a name is read as UTF-8 when
|
|
67
|
+
it is valid UTF-8."""
|
|
68
|
+
if entry.flag_bits & _UTF8_NAME:
|
|
69
|
+
return entry.filename
|
|
70
|
+
try:
|
|
71
|
+
return entry.filename.encode("cp437").decode("utf-8")
|
|
72
|
+
except UnicodeDecodeError:
|
|
73
|
+
return entry.filename
|
|
74
|
+
|
|
75
|
+
|
|
63
76
|
class _Reader:
|
|
64
77
|
def open(self, file: DatasetFile) -> BinaryIO:
|
|
65
78
|
raise NotImplementedError
|
|
@@ -78,4 +91,6 @@ class _ZipReader(_Reader):
|
|
|
78
91
|
self._archive = archive
|
|
79
92
|
|
|
80
93
|
def open(self, file: DatasetFile) -> BinaryIO:
|
|
81
|
-
|
|
94
|
+
if file.zip_entry is None:
|
|
95
|
+
raise ValueError(f"{file.path!r} isn't an entry of the ZIP")
|
|
96
|
+
return self._archive.open(file.zip_entry) # type: ignore[return-value]
|
|
@@ -21,7 +21,7 @@ from dq_export_connector._models.export_report import (
|
|
|
21
21
|
ExportTotals,
|
|
22
22
|
)
|
|
23
23
|
from dq_export_connector._models.export_worker_config import BucketInput, ExportConnectorKind1, ProvisionedPolicy
|
|
24
|
-
from dq_export_connector.bucket.datasets import DatasetFile,
|
|
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
26
|
from dq_export_connector.bucket.store import StorageError, classify_error, failure_sentence, location
|
|
27
27
|
from dq_export_connector.bucket.upload import plan_upload, upload
|
|
@@ -70,7 +70,9 @@ def export(
|
|
|
70
70
|
for bucket_input in connector.inputs:
|
|
71
71
|
_check_input(bucket_input, connection, export_prefix, inputs_dir, report)
|
|
72
72
|
for bucket_input, receipt_input in zip(connector.inputs, receipt.inputs):
|
|
73
|
-
_export_input(
|
|
73
|
+
_export_input(
|
|
74
|
+
bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals], report
|
|
75
|
+
)
|
|
74
76
|
logger.info(
|
|
75
77
|
"Export finished: %d Inputs, %d files, %d bytes",
|
|
76
78
|
len(receipt.inputs),
|
|
@@ -93,9 +95,14 @@ def _check_input(
|
|
|
93
95
|
else:
|
|
94
96
|
logger.info("Input %s is written as one raw file: it is %s", bucket_input.leaf_id, layout.raw_reason)
|
|
95
97
|
try:
|
|
98
|
+
paths: set[str] = set()
|
|
96
99
|
for file in layout.files:
|
|
97
100
|
check_dataset_path(file.path)
|
|
98
101
|
check_key(_key(connection, export_prefix, destination, file), connection)
|
|
102
|
+
# Two entries of one name would be written to one key.
|
|
103
|
+
if file.path in paths:
|
|
104
|
+
raise InvalidPathError(f"the path '{file.path}' appears more than once")
|
|
105
|
+
paths.add(file.path)
|
|
99
106
|
except InvalidPathError as error:
|
|
100
107
|
raise ExportConnectorError(
|
|
101
108
|
ErrorCode.BUCKET_INVALID_PATH, f"Nothing was exported: in the dataset for '{destination}/', {error}"
|
|
@@ -113,6 +120,7 @@ def _export_input(
|
|
|
113
120
|
inputs_dir: Path,
|
|
114
121
|
store: Any,
|
|
115
122
|
totals: list[ExportTotals],
|
|
123
|
+
report: ReportBuilder,
|
|
116
124
|
) -> None:
|
|
117
125
|
leaf_id = bucket_input.leaf_id
|
|
118
126
|
destination = bucket_input.destination_directory
|
|
@@ -133,6 +141,12 @@ def _export_input(
|
|
|
133
141
|
try:
|
|
134
142
|
upload(store, key, source, plan)
|
|
135
143
|
except StorageError as error:
|
|
144
|
+
if plan.multipart:
|
|
145
|
+
report.warn(
|
|
146
|
+
ErrorCode.BUCKET_PARTS_MAY_REMAIN,
|
|
147
|
+
f"Parts of the unfinished upload of '{key}' may remain in the {location(connection)}. They"
|
|
148
|
+
" don't show up as files, and a lifecycle rule for incomplete uploads removes them",
|
|
149
|
+
)
|
|
136
150
|
code = classify_error(error.cause)
|
|
137
151
|
raise ExportConnectorError(
|
|
138
152
|
code,
|
|
@@ -149,10 +163,11 @@ def _export_input(
|
|
|
149
163
|
@contextmanager
|
|
150
164
|
def _reading(destination: str) -> Iterator[None]:
|
|
151
165
|
"""A stored ZIP that is corrupt raises `BadZipFile`, or `EOFError` for an
|
|
152
|
-
entry cut short, when its entry is read.
|
|
166
|
+
entry cut short, when its entry is read. One that needs a newer ZIP version
|
|
167
|
+
than `zipfile` supports raises `NotImplementedError`."""
|
|
153
168
|
try:
|
|
154
169
|
yield
|
|
155
|
-
except (OSError, EOFError, zipfile.BadZipFile
|
|
170
|
+
except (OSError, EOFError, NotImplementedError, zipfile.BadZipFile) as error:
|
|
156
171
|
raise ExportConnectorError(
|
|
157
172
|
ErrorCode.READ_FAILED,
|
|
158
173
|
f"The dataset for '{destination}/' couldn't be read: {str(error) or type(error).__name__}",
|
|
@@ -19,6 +19,7 @@ AZURE_MAX_KEY_CHARACTERS = 1024
|
|
|
19
19
|
AZURE_MAX_KEY_SEGMENTS = 254
|
|
20
20
|
|
|
21
21
|
_RESERVED_GCS_PREFIX = ".well-known/acme-challenge/"
|
|
22
|
+
_QUOTED_KEY_END = 200
|
|
22
23
|
|
|
23
24
|
|
|
24
25
|
class InvalidPathError(ValueError):
|
|
@@ -64,12 +65,21 @@ def check_key(key: str, connection: BucketConnection1 | BucketConnection2 | Buck
|
|
|
64
65
|
match connection:
|
|
65
66
|
case BucketConnection1() | BucketConnection3():
|
|
66
67
|
if len(key.encode("utf-8")) > PROVIDER_MAX_KEY_BYTES:
|
|
67
|
-
raise InvalidPathError(f"
|
|
68
|
+
raise InvalidPathError(f"an object key is longer than {PROVIDER_MAX_KEY_BYTES} bytes: {_shortened(key)!r}")
|
|
68
69
|
case BucketConnection2():
|
|
69
70
|
if len(key) > AZURE_MAX_KEY_CHARACTERS:
|
|
70
|
-
raise InvalidPathError(
|
|
71
|
+
raise InvalidPathError(
|
|
72
|
+
f"an object key is longer than {AZURE_MAX_KEY_CHARACTERS} characters: {_shortened(key)!r}"
|
|
73
|
+
)
|
|
71
74
|
if key.count("/") + 1 > AZURE_MAX_KEY_SEGMENTS:
|
|
72
|
-
raise InvalidPathError(
|
|
75
|
+
raise InvalidPathError(
|
|
76
|
+
f"an object key has more than {AZURE_MAX_KEY_SEGMENTS} segments: {_shortened(key)!r}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _shortened(key: str) -> str:
|
|
81
|
+
"""Both ends of a key too long to quote whole in a report message."""
|
|
82
|
+
return key if len(key) <= 2 * _QUOTED_KEY_END else f"{key[:_QUOTED_KEY_END]}…{key[-_QUOTED_KEY_END:]}"
|
|
73
83
|
|
|
74
84
|
|
|
75
85
|
def _is_control(character: str) -> bool:
|
|
@@ -48,12 +48,14 @@ RETRY_CONFIG: RetryConfig = {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
# object_store's whole-request `timeout` (30s by default) would abort any part
|
|
51
|
-
# upload that takes longer, so it is pushed out of reach
|
|
52
|
-
#
|
|
51
|
+
# upload that takes longer, so it is pushed out of reach, and `read_timeout`
|
|
52
|
+
# is what detects a stalled connection. For an upload it runs while the part
|
|
53
|
+
# is sent, so it has to cover a whole part, and parts grow with the file: at
|
|
54
|
+
# 60s, a part of a very large file would time out on a healthy connection.
|
|
53
55
|
CLIENT_CONFIG: ClientConfig = {
|
|
54
56
|
"connect_timeout": timedelta(seconds=30),
|
|
55
57
|
"timeout": _NEVER_IN_PRACTICE,
|
|
56
|
-
"read_timeout": timedelta(
|
|
58
|
+
"read_timeout": timedelta(minutes=10),
|
|
57
59
|
}
|
|
58
60
|
|
|
59
61
|
T = TypeVar("T")
|
|
@@ -101,91 +103,40 @@ def storage_call(call: Callable[[], T]) -> T:
|
|
|
101
103
|
raise StorageError(error) from error
|
|
102
104
|
|
|
103
105
|
|
|
104
|
-
#
|
|
105
|
-
#
|
|
106
|
-
#
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
"AuthenticationFailed",
|
|
115
|
-
# GCS
|
|
116
|
-
"invalid_grant",
|
|
117
|
-
"Invalid JWT",
|
|
118
|
-
)
|
|
106
|
+
# S3 and Azure answer a credential they reject with a 403, which obstore
|
|
107
|
+
# raises as permission denied, so the code in the response body is what tells
|
|
108
|
+
# it from a missing permission. Azure also answers this way for a container
|
|
109
|
+
# that doesn't exist.
|
|
110
|
+
_REJECTED_CREDENTIAL_CODES = frozenset({"SignatureDoesNotMatch", "InvalidAccessKeyId", "AuthenticationFailed"})
|
|
111
|
+
|
|
112
|
+
# The response follows this in obstore's message. The object key comes before
|
|
113
|
+
# it, so nothing in a key can pass for a provider's code.
|
|
114
|
+
_RESPONSE_START = " - Server returned non-2xx status code: "
|
|
115
|
+
_RESPONSE_CODE = re.compile(r"<Code>(\w+)</Code>")
|
|
119
116
|
|
|
120
|
-
#
|
|
121
|
-
#
|
|
122
|
-
|
|
123
|
-
_MESSAGE_CLASSIFIERS: list[tuple[ErrorCode, tuple[str, ...]]] = [
|
|
124
|
-
(
|
|
125
|
-
ErrorCode.UNAUTHENTICATED,
|
|
126
|
-
(
|
|
127
|
-
# S3
|
|
128
|
-
"SignatureDoesNotMatch",
|
|
129
|
-
"InvalidAccessKeyId",
|
|
130
|
-
"InvalidSecurityToken",
|
|
131
|
-
"ExpiredToken",
|
|
132
|
-
# Azure
|
|
133
|
-
"AuthenticationFailed",
|
|
134
|
-
# GCS
|
|
135
|
-
"invalid_grant",
|
|
136
|
-
"Invalid JWT",
|
|
137
|
-
"status code: 401",
|
|
138
|
-
),
|
|
139
|
-
),
|
|
140
|
-
(
|
|
141
|
-
ErrorCode.ACCESS_DENIED,
|
|
142
|
-
(
|
|
143
|
-
"AccessDenied", # S3
|
|
144
|
-
"AuthorizationFailure", # Azure
|
|
145
|
-
"AuthorizationPermissionMismatch", # Azure
|
|
146
|
-
"PERMISSION_DENIED", # GCS
|
|
147
|
-
"status code: 403",
|
|
148
|
-
),
|
|
149
|
-
),
|
|
150
|
-
(
|
|
151
|
-
ErrorCode.DESTINATION_NOT_FOUND,
|
|
152
|
-
(
|
|
153
|
-
"NoSuchBucket", # S3
|
|
154
|
-
# S3, for a bucket in another region than the connection's
|
|
155
|
-
"PermanentRedirect",
|
|
156
|
-
"incorrectly configured region",
|
|
157
|
-
"ContainerNotFound", # Azure
|
|
158
|
-
"bucket does not exist", # GCS
|
|
159
|
-
"status code: 404",
|
|
160
|
-
),
|
|
161
|
-
),
|
|
162
|
-
(
|
|
163
|
-
ErrorCode.UNREACHABLE,
|
|
164
|
-
(
|
|
165
|
-
"error sending request",
|
|
166
|
-
"dns error",
|
|
167
|
-
"Connection refused",
|
|
168
|
-
"connection refused",
|
|
169
|
-
"operation timed out",
|
|
170
|
-
),
|
|
171
|
-
),
|
|
172
|
-
]
|
|
117
|
+
# How object_store reports S3's redirect for a bucket in another region than
|
|
118
|
+
# the connection's.
|
|
119
|
+
_OTHER_REGION = "this normally indicates an incorrectly configured region"
|
|
173
120
|
|
|
174
121
|
|
|
175
122
|
def classify_error(error: Exception) -> ErrorCode:
|
|
176
|
-
"""Maps a storage error to a code, the same for every Bucket Provider.
|
|
177
|
-
|
|
178
|
-
if any(code in message for code in _CREDENTIAL_CODES):
|
|
179
|
-
return ErrorCode.UNAUTHENTICATED
|
|
123
|
+
"""Maps a storage error to a code, the same for every Bucket Provider. Each
|
|
124
|
+
rule is one a real provider's response was seen to need."""
|
|
180
125
|
if isinstance(error, obstore.exceptions.UnauthenticatedError):
|
|
181
126
|
return ErrorCode.UNAUTHENTICATED
|
|
182
127
|
if isinstance(error, obstore.exceptions.PermissionDeniedError):
|
|
128
|
+
response_code = _RESPONSE_CODE.search(str(error).rpartition(_RESPONSE_START)[2])
|
|
129
|
+
if response_code is not None and response_code[1] in _REJECTED_CREDENTIAL_CODES:
|
|
130
|
+
return ErrorCode.UNAUTHENTICATED
|
|
183
131
|
return ErrorCode.ACCESS_DENIED
|
|
184
132
|
if isinstance(error, FileNotFoundError):
|
|
185
133
|
return ErrorCode.DESTINATION_NOT_FOUND
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
134
|
+
message, _, dump = str(error).partition("\n\nDebug source:")
|
|
135
|
+
if message.endswith(_OTHER_REGION):
|
|
136
|
+
return ErrorCode.DESTINATION_NOT_FOUND
|
|
137
|
+
# The request got no response: it couldn't connect, timed out or was cut off.
|
|
138
|
+
if _HTTP_ERROR.search(dump) is not None:
|
|
139
|
+
return ErrorCode.UNREACHABLE
|
|
189
140
|
return ErrorCode.UNKNOWN
|
|
190
141
|
|
|
191
142
|
|
|
@@ -220,6 +171,8 @@ _CREDENTIAL_PARSE_ERRORS = (
|
|
|
220
171
|
"Generic MicrosoftAzure error: Missing component in SAS query pair",
|
|
221
172
|
"Generic MicrosoftAzure error: Failed parsing an SAS key",
|
|
222
173
|
"Generic GCS error: GCP credential error:",
|
|
174
|
+
"Generic AwsLcCryptoProvider error: Error reading pem file",
|
|
175
|
+
"Generic AwsLcCryptoProvider error: Invalid RSA key",
|
|
223
176
|
)
|
|
224
177
|
|
|
225
178
|
# A value serde rejects, echoed in quotes or backticks with Rust's escaping,
|
|
@@ -253,7 +206,7 @@ def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
|
|
|
253
206
|
return S3Store(
|
|
254
207
|
bucket=s3.bucket,
|
|
255
208
|
region=s3.region,
|
|
256
|
-
access_key_id=s3_credentials.s3.access_key,
|
|
209
|
+
access_key_id=_checked_s3_access_key(s3_credentials.s3.access_key),
|
|
257
210
|
secret_access_key=s3_credentials.s3.secret_key,
|
|
258
211
|
retry_config=RETRY_CONFIG,
|
|
259
212
|
client_options=CLIENT_CONFIG,
|
|
@@ -276,6 +229,17 @@ def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
|
|
|
276
229
|
raise ValueError(f"Credentials for {type(credentials.root).__name__} don't match {type(connection.root).__name__}")
|
|
277
230
|
|
|
278
231
|
|
|
232
|
+
def _checked_s3_access_key(access_key: str) -> str:
|
|
233
|
+
"""The access key is sent in a header, and object_store panics on one no
|
|
234
|
+
header can hold."""
|
|
235
|
+
if not access_key.isprintable() or " " in access_key:
|
|
236
|
+
raise ExportConnectorError(
|
|
237
|
+
ErrorCode.INVALID_CREDENTIALS,
|
|
238
|
+
"The S3 access key in the credentials contains whitespace or a control character",
|
|
239
|
+
)
|
|
240
|
+
return access_key
|
|
241
|
+
|
|
242
|
+
|
|
279
243
|
def _normalize_azure_sas_token(sas_token: str) -> str:
|
|
280
244
|
"""The portal's "Blob SAS token" includes a leading `?`. A SAS URL is
|
|
281
245
|
rejected rather than parsed: its account and container would be ignored,
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
S3 and GCS allow at most 10,000 parts per upload (Azure 50,000 blocks), so the
|
|
4
4
|
part size grows with the file: at the 8 MiB default of the AWS SDKs and CLI, a
|
|
5
|
-
file larger than about 78 GiB would run out of parts.
|
|
6
|
-
|
|
5
|
+
file larger than about 78 GiB would run out of parts.
|
|
6
|
+
|
|
7
|
+
obstore aborts a multipart upload that fails while the source is still being
|
|
8
|
+
read. It sends no abort when a part fails once the source is exhausted, and it
|
|
9
|
+
exposes no call to abort one, so the parts of such an upload stay at the
|
|
10
|
+
destination until its lifecycle rules remove them.
|
|
7
11
|
"""
|
|
8
12
|
|
|
9
13
|
from __future__ import annotations
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/errors.py
RENAMED
|
@@ -21,6 +21,7 @@ class ErrorCode(str, Enum):
|
|
|
21
21
|
# Warnings
|
|
22
22
|
EMPTY_DATASET = "EMPTY_DATASET"
|
|
23
23
|
BUCKET_PROBE_NOT_DELETED = "BUCKET_PROBE_NOT_DELETED"
|
|
24
|
+
BUCKET_PARTS_MAY_REMAIN = "BUCKET_PARTS_MAY_REMAIN"
|
|
24
25
|
|
|
25
26
|
|
|
26
27
|
# ddc's limit on a report message, in characters.
|
|
@@ -41,7 +42,7 @@ class ExportConnectorError(Exception):
|
|
|
41
42
|
self.message = message
|
|
42
43
|
|
|
43
44
|
|
|
44
|
-
def internal_error_message(error:
|
|
45
|
+
def internal_error_message(error: BaseException, activity: str) -> str:
|
|
45
46
|
"""Names the error's type and where it was raised, but not its message,
|
|
46
47
|
which could hold dataset values."""
|
|
47
48
|
error_type = type(error)
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/runner.py
RENAMED
|
@@ -18,9 +18,6 @@ from dq_export_connector._models.export_worker_config import (
|
|
|
18
18
|
ExportConnectorDcrComputeAction2,
|
|
19
19
|
ExportWorkerConfig,
|
|
20
20
|
)
|
|
21
|
-
from dq_export_connector.bucket import store
|
|
22
|
-
from dq_export_connector.bucket.export import export
|
|
23
|
-
from dq_export_connector.bucket.validate import validate_connection
|
|
24
21
|
from dq_export_connector.errors import ErrorCode, ExportConnectorError, internal_error_message
|
|
25
22
|
from dq_export_connector.log import configure, logger
|
|
26
23
|
from dq_export_connector.redact import Redactor, sealed_values
|
|
@@ -45,7 +42,7 @@ def main(
|
|
|
45
42
|
credentials_path: Path = CREDENTIALS_PATH,
|
|
46
43
|
inputs_dir: Path = INPUTS_DIR,
|
|
47
44
|
output_dir: Path = OUTPUT_DIR,
|
|
48
|
-
build_store: Callable[[Any, Any], Any] =
|
|
45
|
+
build_store: Callable[[Any, Any], Any] | None = None,
|
|
49
46
|
) -> None:
|
|
50
47
|
credentials_json = json.loads(credentials_path.read_text())
|
|
51
48
|
redactor = Redactor(sealed_values(credentials_json))
|
|
@@ -59,7 +56,10 @@ def main(
|
|
|
59
56
|
build_store,
|
|
60
57
|
redactor,
|
|
61
58
|
)
|
|
62
|
-
except
|
|
59
|
+
except (KeyboardInterrupt, SystemExit):
|
|
60
|
+
raise
|
|
61
|
+
# A panic in obstore's Rust code is a `BaseException`.
|
|
62
|
+
except BaseException:
|
|
63
63
|
logger.exception("The export worker failed")
|
|
64
64
|
raise WorkerFailed("The export worker failed; its redacted error is in the platform logs") from None
|
|
65
65
|
|
|
@@ -69,9 +69,16 @@ def run(
|
|
|
69
69
|
credentials: ExportConnectorCredentials,
|
|
70
70
|
inputs_dir: Path,
|
|
71
71
|
output_dir: Path,
|
|
72
|
-
build_store: Callable[[Any, Any], Any],
|
|
72
|
+
build_store: Callable[[Any, Any], Any] | None,
|
|
73
73
|
redactor: Redactor,
|
|
74
74
|
) -> None:
|
|
75
|
+
# A kind's modules import what its extra installs, so they load only for
|
|
76
|
+
# a run of that kind.
|
|
77
|
+
from dq_export_connector.bucket import store
|
|
78
|
+
from dq_export_connector.bucket.export import export
|
|
79
|
+
from dq_export_connector.bucket.validate import validate_connection
|
|
80
|
+
|
|
81
|
+
build_store = build_store or store.build_store
|
|
75
82
|
logger.info("dq-export-connector %s", version("dq-export-connector"))
|
|
76
83
|
connector = config.connector.root
|
|
77
84
|
bucket_credentials = credentials.root.bucket
|
|
@@ -100,10 +107,13 @@ def _reporting(report: ReportBuilder, activity: str, action: Callable[[], None])
|
|
|
100
107
|
did before it."""
|
|
101
108
|
try:
|
|
102
109
|
action()
|
|
110
|
+
except (KeyboardInterrupt, SystemExit):
|
|
111
|
+
raise
|
|
103
112
|
except ExportConnectorError as error:
|
|
104
113
|
logger.error("The %s failed with %s: %s", activity, error.code.value, error.message)
|
|
105
114
|
report.fail(error.code, error.message)
|
|
106
|
-
|
|
115
|
+
# A panic in obstore's Rust code is a `BaseException`.
|
|
116
|
+
except BaseException as error:
|
|
107
117
|
logger.exception("An internal error stopped the %s", activity)
|
|
108
118
|
report.fail(ErrorCode.INTERNAL_ERROR, internal_error_message(error, activity))
|
|
109
119
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "dq-export-connector"
|
|
3
|
-
version = "0.1.0.
|
|
3
|
+
version = "0.1.0.dev11"
|
|
4
4
|
description = "Worker logic for the Export Connector DCR."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [{ name = "Decentriq" }]
|
|
@@ -10,12 +10,19 @@ requires-python = ">=3.10"
|
|
|
10
10
|
# locked one. pydantic stays at the version dq_validation runs in that image;
|
|
11
11
|
# newer ones need a newer typing_extensions.
|
|
12
12
|
dependencies = [
|
|
13
|
-
"obstore>=0.11.1,<0.12",
|
|
14
13
|
"pydantic>=2.7,<2.8",
|
|
15
14
|
]
|
|
16
15
|
|
|
16
|
+
# One extra per Connector Kind, holding what only that kind needs: ddc locks
|
|
17
|
+
# `dq-export-connector[<kind>]`, so a run installs no other kind's packages.
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
bucket = [
|
|
20
|
+
"obstore>=0.11.1,<0.12",
|
|
21
|
+
]
|
|
22
|
+
|
|
17
23
|
[dependency-groups]
|
|
18
24
|
dev = [
|
|
25
|
+
"dq-export-connector[bucket]",
|
|
19
26
|
"mypy>=1.13",
|
|
20
27
|
"pytest>=8.3",
|
|
21
28
|
]
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_live_buckets.py
RENAMED
|
@@ -132,3 +132,59 @@ def test_an_export_lands_in_the_bucket(tmp_path: Path, provider: tuple[dict[str,
|
|
|
132
132
|
None,
|
|
133
133
|
{f"{prefix}/zipped/dir with space/part #1.csv": b"a,b\n", f"{prefix}/raw/data": b"raw bytes"},
|
|
134
134
|
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _write_error_code(tmp_path: Path, name: str, connection: dict[str, Any], credentials: dict[str, Any]) -> Any:
|
|
138
|
+
output = _main(tmp_path / name, VALIDATE, connection, credentials, {})
|
|
139
|
+
return json.loads((output / runner.VALIDATION_RESULT_FILE).read_text())["error"]["code"]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_s3_failures_are_classified(tmp_path: Path) -> None:
|
|
143
|
+
connection, credentials = _s3("dq-export-connector-live-tests")
|
|
144
|
+
keys = credentials["bucket"]["s3"]
|
|
145
|
+
cases = {
|
|
146
|
+
"secret": (connection, {"bucket": {"s3": {**keys, "secretKey": "x" * 40}}}),
|
|
147
|
+
"access": (connection, {"bucket": {"s3": {**keys, "accessKey": "AKIAAAAAAAAAAAAAAAAA"}}}),
|
|
148
|
+
"bucket": ({**connection, "bucket": f"dq-no-such-bucket-{uuid.uuid4().hex}"}, credentials),
|
|
149
|
+
"region": ({**connection, "region": "eu-central-1"}, credentials),
|
|
150
|
+
}
|
|
151
|
+
for name in cases:
|
|
152
|
+
(tmp_path / name).mkdir()
|
|
153
|
+
assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
|
|
154
|
+
"secret": "UNAUTHENTICATED",
|
|
155
|
+
"access": "UNAUTHENTICATED",
|
|
156
|
+
"bucket": "DESTINATION_NOT_FOUND",
|
|
157
|
+
"region": "DESTINATION_NOT_FOUND",
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_azure_failures_are_classified(tmp_path: Path) -> None:
|
|
162
|
+
connection, credentials = _azure("dq-export-connector-live-tests")
|
|
163
|
+
token = credentials["bucket"]["azureBlob"]["sasToken"]
|
|
164
|
+
signature = token[token.index("sig=") :].split("&")[0]
|
|
165
|
+
cases = {
|
|
166
|
+
"signature": (connection, {"bucket": {"azureBlob": {"sasToken": token.replace(signature, "sig=AAAA")}}}),
|
|
167
|
+
"container": ({**connection, "container": f"no-such-{uuid.uuid4().hex[:12]}"}, credentials),
|
|
168
|
+
}
|
|
169
|
+
for name in cases:
|
|
170
|
+
(tmp_path / name).mkdir()
|
|
171
|
+
assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
|
|
172
|
+
"signature": "UNAUTHENTICATED",
|
|
173
|
+
"container": "UNAUTHENTICATED",
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_gcs_failures_are_classified(tmp_path: Path) -> None:
|
|
178
|
+
connection, credentials = _gcs("dq-export-connector-live-tests")
|
|
179
|
+
account = json.loads(credentials["bucket"]["gcs"]["serviceAccountJson"])
|
|
180
|
+
unknown = {**account, "client_email": "nobody@" + account["client_email"].split("@")[1]}
|
|
181
|
+
cases = {
|
|
182
|
+
"account": (connection, {"bucket": {"gcs": {"serviceAccountJson": json.dumps(unknown)}}}),
|
|
183
|
+
"bucket": ({**connection, "bucket": f"dq-no-such-bucket-{uuid.uuid4().hex}"}, credentials),
|
|
184
|
+
}
|
|
185
|
+
for name in cases:
|
|
186
|
+
(tmp_path / name).mkdir()
|
|
187
|
+
assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
|
|
188
|
+
"account": "UNAUTHENTICATED",
|
|
189
|
+
"bucket": "DESTINATION_NOT_FOUND",
|
|
190
|
+
}
|
|
@@ -48,6 +48,12 @@ def test_key_limits_follow_the_provider():
|
|
|
48
48
|
]] == [True, False, False, True, True, False]
|
|
49
49
|
|
|
50
50
|
|
|
51
|
+
def test_a_key_that_is_too_long_is_quoted_by_its_ends_after_the_reason():
|
|
52
|
+
with pytest.raises(InvalidPathError) as raised:
|
|
53
|
+
check_key("a" * 600 + "b" * 600, S3)
|
|
54
|
+
assert str(raised.value) == f"an object key is longer than 1024 bytes: '{'a' * 200}…{'b' * 200}'"
|
|
55
|
+
|
|
56
|
+
|
|
51
57
|
def test_the_gcs_reserved_prefix_is_rejected_for_every_provider():
|
|
52
58
|
assert [_accepted(".well-known/acme-challenge/x", connection) for connection in [S3, AZURE, GCS]] == [False] * 3
|
|
53
59
|
|
|
@@ -5,6 +5,7 @@ import io
|
|
|
5
5
|
import json
|
|
6
6
|
import os
|
|
7
7
|
import re
|
|
8
|
+
import warnings
|
|
8
9
|
import zipfile
|
|
9
10
|
from pathlib import Path
|
|
10
11
|
|
|
@@ -15,6 +16,7 @@ from obstore.store import LocalStore, MemoryStore
|
|
|
15
16
|
from dq_export_connector import runner
|
|
16
17
|
from dq_export_connector.bucket import export
|
|
17
18
|
from dq_export_connector.bucket.store import StorageError
|
|
19
|
+
from dq_export_connector.bucket.upload import MIN_PART_SIZE
|
|
18
20
|
from dq_export_connector.errors import MAX_MESSAGE_LENGTH
|
|
19
21
|
|
|
20
22
|
SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
|
@@ -102,22 +104,56 @@ def test_stored_zips_are_unpacked_and_other_datasets_written_raw(tmp_path, monke
|
|
|
102
104
|
"segA": _zip({"part-0.csv": b"a,b\n", "sub/": b"", "sub/part-1.csv": b"c,d\n"}),
|
|
103
105
|
"segB": b"raw bytes",
|
|
104
106
|
"segC": _zip({"x.csv": b"compressed"}, compression=zipfile.ZIP_DEFLATED),
|
|
107
|
+
"segD": _encrypted(_zip({"y.csv": b"encrypted"})),
|
|
105
108
|
}
|
|
106
|
-
config = _config(EXPORT, [("segA", "seg_a"), ("segB", "seg_b"), ("segC", "seg_c")])
|
|
109
|
+
config = _config(EXPORT, [("segA", "seg_a"), ("segB", "seg_b"), ("segC", "seg_c"), ("segD", "seg_d")])
|
|
107
110
|
_run(tmp_path, config, datasets, store, monkeypatch)
|
|
108
111
|
seg_c_size = len(datasets["segC"])
|
|
112
|
+
seg_d_size = len(datasets["segD"])
|
|
109
113
|
assert (_objects(store), _report(tmp_path)) == (
|
|
110
114
|
{
|
|
111
115
|
"decentriq/seg_a/part-0.csv": b"a,b\n",
|
|
112
116
|
"decentriq/seg_a/sub/part-1.csv": b"c,d\n",
|
|
113
117
|
"decentriq/seg_b/data": b"raw bytes",
|
|
114
118
|
"decentriq/seg_c/data": datasets["segC"],
|
|
119
|
+
"decentriq/seg_d/data": datasets["segD"],
|
|
115
120
|
},
|
|
116
121
|
{
|
|
117
122
|
"version": "V0",
|
|
118
123
|
"warnings": [],
|
|
119
|
-
"receipt": _receipt(
|
|
124
|
+
"receipt": _receipt(
|
|
125
|
+
[
|
|
126
|
+
("segA", "seg_a", 2, 8),
|
|
127
|
+
("segB", "seg_b", 1, 9),
|
|
128
|
+
("segC", "seg_c", 1, seg_c_size),
|
|
129
|
+
("segD", "seg_d", 1, seg_d_size),
|
|
130
|
+
]
|
|
131
|
+
),
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_names_and_directories_are_read_as_the_dataset_preview_reads_them(tmp_path, monkeypatch):
|
|
137
|
+
buffer = io.BytesIO()
|
|
138
|
+
with zipfile.ZipFile(buffer, "w") as archive:
|
|
139
|
+
archive.writestr("über.csv", b"utf-8")
|
|
140
|
+
archive.writestr("cafX.csv", b"cp437")
|
|
141
|
+
flagged_as_directory = zipfile.ZipInfo("report.csv")
|
|
142
|
+
flagged_as_directory.external_attr = 0x10
|
|
143
|
+
archive.writestr(flagged_as_directory, b"content")
|
|
144
|
+
dataset = bytearray(buffer.getvalue().replace(b"cafX.csv", b"caf\x82.csv"))
|
|
145
|
+
# Clears the UTF-8 flag of the first entry in its local and its central header.
|
|
146
|
+
for signature, flags_offset in ((b"PK\x03\x04", 7), (b"PK\x01\x02", 9)):
|
|
147
|
+
dataset[dataset.index(signature) + flags_offset] &= ~0x08
|
|
148
|
+
store = MemoryStore()
|
|
149
|
+
_run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": bytes(dataset)}, store, monkeypatch)
|
|
150
|
+
assert (_objects(store), _report(tmp_path)["receipt"]) == (
|
|
151
|
+
{
|
|
152
|
+
"decentriq/seg_a/über.csv": b"utf-8",
|
|
153
|
+
"decentriq/seg_a/café.csv": b"cp437",
|
|
154
|
+
"decentriq/seg_a/report.csv": b"content",
|
|
120
155
|
},
|
|
156
|
+
_receipt([("segA", "seg_a", 3, 17)]),
|
|
121
157
|
)
|
|
122
158
|
|
|
123
159
|
|
|
@@ -145,12 +181,34 @@ def test_a_bad_path_fails_the_run_before_anything_is_written(tmp_path, monkeypat
|
|
|
145
181
|
)
|
|
146
182
|
|
|
147
183
|
|
|
184
|
+
def test_a_zip_with_one_name_twice_fails_the_run_before_anything_is_written(tmp_path, monkeypatch):
|
|
185
|
+
store = MemoryStore()
|
|
186
|
+
buffer = io.BytesIO()
|
|
187
|
+
with zipfile.ZipFile(buffer, "w") as archive, warnings.catch_warnings():
|
|
188
|
+
warnings.simplefilter("ignore", UserWarning)
|
|
189
|
+
archive.writestr("x.csv", b"1")
|
|
190
|
+
archive.writestr("x.csv", b"22")
|
|
191
|
+
_run(tmp_path, _config(EXPORT, [("twice", "twice")]), {"twice": buffer.getvalue()}, store, monkeypatch)
|
|
192
|
+
assert (_objects(store), _report(tmp_path)) == (
|
|
193
|
+
{},
|
|
194
|
+
{
|
|
195
|
+
"version": "V0",
|
|
196
|
+
"error": {
|
|
197
|
+
"code": "BUCKET_INVALID_PATH",
|
|
198
|
+
"message": "Nothing was exported: in the dataset for 'twice/', the path 'x.csv' appears more than once",
|
|
199
|
+
},
|
|
200
|
+
"warnings": [],
|
|
201
|
+
"receipt": _receipt([("twice", "twice", 0, 0)]),
|
|
202
|
+
},
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
148
206
|
def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monkeypatch):
|
|
149
207
|
upload = export.upload
|
|
150
208
|
|
|
151
209
|
def denied_for_seg_b(store, key, source, plan):
|
|
152
210
|
if "/seg_b/" in key:
|
|
153
|
-
raise StorageError(
|
|
211
|
+
raise StorageError(obstore.exceptions.PermissionDeniedError("Access Denied"))
|
|
154
212
|
upload(store, key, source, plan)
|
|
155
213
|
|
|
156
214
|
monkeypatch.setattr(export, "upload", denied_for_seg_b)
|
|
@@ -164,7 +222,7 @@ def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monke
|
|
|
164
222
|
"error": {
|
|
165
223
|
"code": "ACCESS_DENIED",
|
|
166
224
|
"message": "The credentials may not write to the bucket 'acme' in eu-central-1, so writing"
|
|
167
|
-
" 'decentriq/seg_b/data' failed after 0 of 1 files for 'seg_b/':
|
|
225
|
+
" 'decentriq/seg_b/data' failed after 0 of 1 files for 'seg_b/': Access Denied",
|
|
168
226
|
},
|
|
169
227
|
"warnings": [],
|
|
170
228
|
"receipt": _receipt([("segA", "seg_a", 1, 1), ("segB", "seg_b", 0, 0), ("segC", "seg_c", 0, 0)]),
|
|
@@ -172,6 +230,22 @@ def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monke
|
|
|
172
230
|
)
|
|
173
231
|
|
|
174
232
|
|
|
233
|
+
def test_a_failed_multipart_upload_warns_that_its_parts_may_remain(tmp_path, monkeypatch):
|
|
234
|
+
def failing(*_):
|
|
235
|
+
raise StorageError(RuntimeError("AccessDenied: Access Denied"))
|
|
236
|
+
|
|
237
|
+
monkeypatch.setattr(export, "upload", failing)
|
|
238
|
+
dataset = bytes(MIN_PART_SIZE + 1)
|
|
239
|
+
_run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": dataset}, MemoryStore(), monkeypatch)
|
|
240
|
+
assert _report(tmp_path)["warnings"] == [
|
|
241
|
+
{
|
|
242
|
+
"code": "BUCKET_PARTS_MAY_REMAIN",
|
|
243
|
+
"message": "Parts of the unfinished upload of 'decentriq/seg_a/data' may remain in the bucket 'acme' in"
|
|
244
|
+
" eu-central-1. They don't show up as files, and a lifecycle rule for incomplete uploads removes them",
|
|
245
|
+
}
|
|
246
|
+
]
|
|
247
|
+
|
|
248
|
+
|
|
175
249
|
def _encrypted(data):
|
|
176
250
|
"""Sets the encryption flag in the local and the central header."""
|
|
177
251
|
data = bytearray(data)
|
|
@@ -180,12 +254,19 @@ def _encrypted(data):
|
|
|
180
254
|
return bytes(data)
|
|
181
255
|
|
|
182
256
|
|
|
257
|
+
def _needing_version_25_5(data):
|
|
258
|
+
"""Sets the version needed to extract in the central header."""
|
|
259
|
+
data = bytearray(data)
|
|
260
|
+
data[data.index(b"PK\x01\x02") + 6] = 0xFF
|
|
261
|
+
return bytes(data)
|
|
262
|
+
|
|
263
|
+
|
|
183
264
|
@pytest.mark.parametrize(
|
|
184
265
|
("entries", "corrupt", "reason"),
|
|
185
266
|
[
|
|
186
267
|
({"a.csv": b"hello world"}, lambda data: data.replace(b"hello world", b"hellO world"), "Bad CRC-32 for file 'a.csv'"),
|
|
187
268
|
({"a.csv": b"hello world"}, lambda data: data.replace(b"PK\x03\x04", b"PK\x00\x00", 1), "Bad magic number for file header"),
|
|
188
|
-
({"a.csv": b"hello world"},
|
|
269
|
+
({"a.csv": b"hello world"}, _needing_version_25_5, "zip file version 25.5"),
|
|
189
270
|
# Over 8 MiB, so the entry is read inside obstore's multipart upload.
|
|
190
271
|
({"big.csv": b"x" * 8 * 1024 * 1024 + b"y"}, lambda data: data.replace(b"xy", b"xz"), "Bad CRC-32 for file 'big.csv'"),
|
|
191
272
|
],
|
|
@@ -266,6 +347,29 @@ def test_an_internal_error_is_reported_without_its_message(tmp_path, monkeypatch
|
|
|
266
347
|
}
|
|
267
348
|
|
|
268
349
|
|
|
350
|
+
def test_a_panic_is_reported_as_an_internal_error(tmp_path, monkeypatch):
|
|
351
|
+
class PanicException(BaseException):
|
|
352
|
+
pass
|
|
353
|
+
|
|
354
|
+
def panicking(*_):
|
|
355
|
+
raise PanicException("a dataset value")
|
|
356
|
+
|
|
357
|
+
line = panicking.__code__.co_firstlineno + 1
|
|
358
|
+
monkeypatch.setattr(export, "upload", panicking)
|
|
359
|
+
_run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": b"x"}, MemoryStore(), monkeypatch)
|
|
360
|
+
assert _report(tmp_path) == {
|
|
361
|
+
"version": "V0",
|
|
362
|
+
"error": {
|
|
363
|
+
"code": "INTERNAL_ERROR",
|
|
364
|
+
"message": "An internal error stopped the export:"
|
|
365
|
+
f" {__name__}.test_a_panic_is_reported_as_an_internal_error.<locals>.PanicException at {__name__}:{line}"
|
|
366
|
+
" (error message removed due to data privacy)",
|
|
367
|
+
},
|
|
368
|
+
"warnings": [],
|
|
369
|
+
"receipt": _receipt([("segA", "seg_a", 0, 0)]),
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
|
|
269
373
|
def test_the_connection_test_writes_and_deletes_its_probe(tmp_path, monkeypatch):
|
|
270
374
|
store = MemoryStore()
|
|
271
375
|
logs = _run(tmp_path, _config(VALIDATE, []), {}, store, monkeypatch)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import socket
|
|
3
3
|
from datetime import timedelta
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
4
5
|
|
|
5
6
|
import obstore
|
|
6
7
|
import obstore.exceptions
|
|
@@ -11,6 +12,9 @@ from dq_export_connector._models.export_worker_config import BucketConnection
|
|
|
11
12
|
from dq_export_connector.bucket.store import build_store, classify_error, describe
|
|
12
13
|
from dq_export_connector.errors import ErrorCode, ExportConnectorError
|
|
13
14
|
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from obstore.store import ClientConfig
|
|
17
|
+
|
|
14
18
|
|
|
15
19
|
def _build_error(connection, credentials):
|
|
16
20
|
try:
|
|
@@ -23,6 +27,8 @@ def _build_error(connection, credentials):
|
|
|
23
27
|
def test_malformed_credentials_are_invalid_before_any_request():
|
|
24
28
|
gcs = {"type": "gcs", "bucket": "b", "pathPrefix": None}
|
|
25
29
|
azure = {"type": "azureBlob", "accountName": "a", "container": "c", "pathPrefix": None}
|
|
30
|
+
service_account = {"private_key_id": "i", "client_email": "a@b.iam.gserviceaccount.com"}
|
|
31
|
+
bad_key = "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n"
|
|
26
32
|
decode_error = (
|
|
27
33
|
"The credentials couldn't be read: Generic GCS error: GCP credential error: Unable to decode service account"
|
|
28
34
|
" file: "
|
|
@@ -32,6 +38,8 @@ def test_malformed_credentials_are_invalid_before_any_request():
|
|
|
32
38
|
_build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({"private_key": 5})}}),
|
|
33
39
|
_build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({"client_email": "a@b"})}}),
|
|
34
40
|
_build_error(azure, {"azureBlob": {"sasToken": "garbage"}}),
|
|
41
|
+
_build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({**service_account, "private_key": "not a pem"})}}),
|
|
42
|
+
_build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({**service_account, "private_key": bad_key})}}),
|
|
35
43
|
] == [
|
|
36
44
|
(ErrorCode.INVALID_CREDENTIALS, decode_error + "expected ident at line 1 column 2"),
|
|
37
45
|
(ErrorCode.INVALID_CREDENTIALS, decode_error + "invalid type: integer `***`, expected a string at line 1 column 17"),
|
|
@@ -40,9 +48,29 @@ def test_malformed_credentials_are_invalid_before_any_request():
|
|
|
40
48
|
ErrorCode.INVALID_CREDENTIALS,
|
|
41
49
|
"The credentials couldn't be read: Generic MicrosoftAzure error: Missing component in SAS query pair",
|
|
42
50
|
),
|
|
51
|
+
(
|
|
52
|
+
ErrorCode.INVALID_CREDENTIALS,
|
|
53
|
+
"The credentials couldn't be read: Generic AwsLcCryptoProvider error: Error reading pem file: no items found",
|
|
54
|
+
),
|
|
55
|
+
(
|
|
56
|
+
ErrorCode.INVALID_CREDENTIALS,
|
|
57
|
+
"The credentials couldn't be read: Generic AwsLcCryptoProvider error: Invalid RSA key: InvalidEncoding",
|
|
58
|
+
),
|
|
43
59
|
]
|
|
44
60
|
|
|
45
61
|
|
|
62
|
+
def test_an_s3_access_key_no_header_can_hold_is_invalid():
|
|
63
|
+
s3 = {"type": "s3", "region": "eu-central-1", "bucket": "b", "pathPrefix": None}
|
|
64
|
+
error = (
|
|
65
|
+
ErrorCode.INVALID_CREDENTIALS,
|
|
66
|
+
"The S3 access key in the credentials contains whitespace or a control character",
|
|
67
|
+
)
|
|
68
|
+
assert [
|
|
69
|
+
_build_error(s3, {"s3": {"accessKey": access_key, "secretKey": "s"}})
|
|
70
|
+
for access_key in ["AKIA\n", " AKIA", "AK\u0001IA", "AKIA"]
|
|
71
|
+
] == [error, error, error, None]
|
|
72
|
+
|
|
73
|
+
|
|
46
74
|
def test_a_rejected_credential_is_masked_however_rust_escapes_it():
|
|
47
75
|
gcs = {"type": "gcs", "bucket": "b", "pathPrefix": None}
|
|
48
76
|
# serde quotes a rejected string as Rust's Debug does, with \u{1} for the
|
|
@@ -63,7 +91,7 @@ def test_an_address_no_url_can_hold_is_unreachable():
|
|
|
63
91
|
)
|
|
64
92
|
|
|
65
93
|
|
|
66
|
-
def _put_error(port,
|
|
94
|
+
def _put_error(port, client_options: "ClientConfig"):
|
|
67
95
|
store = S3Store(
|
|
68
96
|
bucket="b",
|
|
69
97
|
region="eu-west-1",
|
|
@@ -71,17 +99,17 @@ def _put_error(port, **client_options):
|
|
|
71
99
|
secret_access_key="s",
|
|
72
100
|
endpoint=f"http://127.0.0.1:{port}",
|
|
73
101
|
retry_config={"max_retries": 0},
|
|
74
|
-
client_options=
|
|
102
|
+
client_options=client_options,
|
|
75
103
|
)
|
|
76
104
|
try:
|
|
77
105
|
obstore.put(store, "k", b"x")
|
|
78
106
|
except obstore.exceptions.BaseError as error:
|
|
79
107
|
# Leaves out the request's URL and duration.
|
|
80
|
-
return describe(error).split(" - ", 1)[1]
|
|
108
|
+
return classify_error(error), describe(error).split(" - ", 1)[1]
|
|
81
109
|
return None
|
|
82
110
|
|
|
83
111
|
|
|
84
|
-
def
|
|
112
|
+
def test_a_request_that_couldnt_be_sent_is_unreachable_and_keeps_its_cause():
|
|
85
113
|
with socket.socket() as closed:
|
|
86
114
|
closed.bind(("127.0.0.1", 0))
|
|
87
115
|
closed_port = closed.getsockname()[1]
|
|
@@ -90,10 +118,13 @@ def test_a_request_that_couldnt_be_sent_keeps_its_cause():
|
|
|
90
118
|
with socket.socket() as silent:
|
|
91
119
|
silent.bind(("127.0.0.1", 0))
|
|
92
120
|
silent.listen()
|
|
93
|
-
errors = [
|
|
121
|
+
errors = [
|
|
122
|
+
_put_error(closed_port, {"allow_http": True}),
|
|
123
|
+
_put_error(silent.getsockname()[1], {"allow_http": True, "read_timeout": timedelta(milliseconds=200)}),
|
|
124
|
+
]
|
|
94
125
|
assert errors == [
|
|
95
|
-
"HTTP error: error sending request: tcp connect error: Connection refused",
|
|
96
|
-
"HTTP error: error sending request: timed out",
|
|
126
|
+
(ErrorCode.UNREACHABLE, "HTTP error: error sending request: tcp connect error: Connection refused"),
|
|
127
|
+
(ErrorCode.UNREACHABLE, "HTTP error: error sending request: timed out"),
|
|
97
128
|
]
|
|
98
129
|
|
|
99
130
|
|
|
@@ -102,6 +133,29 @@ def test_obstores_debug_dump_is_left_out():
|
|
|
102
133
|
assert describe(error) == "Generic S3 error: failed"
|
|
103
134
|
|
|
104
135
|
|
|
136
|
+
def _denied(key, response):
|
|
137
|
+
return obstore.exceptions.PermissionDeniedError(
|
|
138
|
+
f"The operation lacked the necessary privileges to complete for path {key}: Error performing PUT"
|
|
139
|
+
f" https://s3.eu-west-3.amazonaws.com/b/k in 110ms - Server returned non-2xx status code: 403 Forbidden:"
|
|
140
|
+
f" {response}"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def test_a_403_is_a_rejected_credential_only_by_the_code_in_its_response():
|
|
145
|
+
assert [
|
|
146
|
+
classify_error(_denied("k", "<Error><Code>SignatureDoesNotMatch</Code><Message>m</Message></Error>")),
|
|
147
|
+
classify_error(_denied("k", "<Error><Code>InvalidAccessKeyId</Code><Message>m</Message></Error>")),
|
|
148
|
+
classify_error(_denied("k", '\ufeff<?xml version="1.0"?><Error><Code>AuthenticationFailed</Code></Error>')),
|
|
149
|
+
classify_error(_denied("k", "<Error><Code>AccessDenied</Code><Message>m</Message></Error>")),
|
|
150
|
+
classify_error(_denied("<Code>SignatureDoesNotMatch</Code>", "<Error><Code>AccessDenied</Code></Error>")),
|
|
151
|
+
] == [ErrorCode.UNAUTHENTICATED] * 3 + [ErrorCode.ACCESS_DENIED] * 2
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_an_error_obstore_gives_no_type_and_no_cause_is_unknown():
|
|
155
|
+
error = obstore.exceptions.GenericError("Generic S3 error: AccessDenied, status code: 403, dns error")
|
|
156
|
+
assert classify_error(error) == ErrorCode.UNKNOWN
|
|
157
|
+
|
|
158
|
+
|
|
105
159
|
def test_a_bucket_in_another_region_is_not_found_there():
|
|
106
160
|
error = obstore.exceptions.GenericError(
|
|
107
161
|
"Generic S3 error: Error performing PUT https://s3.us-east-1.amazonaws.com/b/k in 482ms - Received redirect"
|
|
@@ -96,27 +96,34 @@ wheels = [
|
|
|
96
96
|
|
|
97
97
|
[[package]]
|
|
98
98
|
name = "dq-export-connector"
|
|
99
|
-
version = "0.1.0.
|
|
99
|
+
version = "0.1.0.dev11"
|
|
100
100
|
source = { editable = "." }
|
|
101
101
|
dependencies = [
|
|
102
|
-
{ name = "obstore" },
|
|
103
102
|
{ name = "pydantic" },
|
|
104
103
|
]
|
|
105
104
|
|
|
105
|
+
[package.optional-dependencies]
|
|
106
|
+
bucket = [
|
|
107
|
+
{ name = "obstore" },
|
|
108
|
+
]
|
|
109
|
+
|
|
106
110
|
[package.dev-dependencies]
|
|
107
111
|
dev = [
|
|
112
|
+
{ name = "dq-export-connector", extra = ["bucket"] },
|
|
108
113
|
{ name = "mypy" },
|
|
109
114
|
{ name = "pytest" },
|
|
110
115
|
]
|
|
111
116
|
|
|
112
117
|
[package.metadata]
|
|
113
118
|
requires-dist = [
|
|
114
|
-
{ name = "obstore", specifier = ">=0.11.1,<0.12" },
|
|
119
|
+
{ name = "obstore", marker = "extra == 'bucket'", specifier = ">=0.11.1,<0.12" },
|
|
115
120
|
{ name = "pydantic", specifier = ">=2.7,<2.8" },
|
|
116
121
|
]
|
|
122
|
+
provides-extras = ["bucket"]
|
|
117
123
|
|
|
118
124
|
[package.metadata.requires-dev]
|
|
119
125
|
dev = [
|
|
126
|
+
{ name = "dq-export-connector", extras = ["bucket"] },
|
|
120
127
|
{ name = "mypy", specifier = ">=1.13" },
|
|
121
128
|
{ name = "pytest", specifier = ">=8.3" },
|
|
122
129
|
]
|
|
File without changes
|
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/log.py
RENAMED
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/redact.py
RENAMED
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/dq_export_connector/report.py
RENAMED
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/scripts/codegen-models.sh
RENAMED
|
File without changes
|
{dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev11}/tests/test_models_are_current.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|