dq-export-connector 0.1.0.dev10__tar.gz → 0.1.0.dev12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/PKG-INFO +8 -6
  2. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/README.md +5 -4
  3. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/_models/export_connector_credentials.py +20 -34
  4. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/datasets.py +28 -13
  5. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/export.py +22 -7
  6. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/paths.py +13 -3
  7. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/store.py +55 -91
  8. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/upload.py +6 -2
  9. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/validate.py +3 -3
  10. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/errors.py +2 -1
  11. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/redact.py +5 -4
  12. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/runner.py +18 -8
  13. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/pyproject.toml +9 -2
  14. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/tests/test_live_buckets.py +60 -4
  15. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/tests/test_paths.py +6 -0
  16. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/tests/test_redact.py +2 -2
  17. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/tests/test_runner.py +110 -6
  18. dq_export_connector-0.1.0.dev12/tests/test_store.py +164 -0
  19. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/uv.lock +10 -3
  20. dq_export_connector-0.1.0.dev10/tests/test_store.py +0 -110
  21. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/.gitignore +0 -0
  22. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/.python-version +0 -0
  23. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/__init__.py +0 -0
  24. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/_models/__init__.py +0 -0
  25. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/_models/bucket_validation_result.py +0 -0
  26. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/_models/export_report.py +0 -0
  27. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/_models/export_worker_config.py +0 -0
  28. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/bucket/__init__.py +0 -0
  29. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/log.py +0 -0
  30. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/dq_export_connector/report.py +0 -0
  31. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/scripts/codegen-models.sh +0 -0
  32. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/tests/test_models_are_current.py +0 -0
  33. {dq_export_connector-0.1.0.dev10 → dq_export_connector-0.1.0.dev12}/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.dev10
3
+ Version: 0.1.0.dev12
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. The **bucket** kind uploads each
15
- Input's dataset to S3, Azure Blob or GCS through
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 `export_connector/v0/worker/<version>/`.
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. The **bucket** kind uploads each
5
- Input's dataset to S3, Azure Blob or GCS through
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 `export_connector/v0/worker/<version>/`.
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`.
@@ -3,28 +3,21 @@
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
- from typing import Annotated
6
+ from typing import Annotated, Literal
7
7
 
8
8
  from pydantic import BaseModel, ConfigDict, Field, RootModel
9
9
 
10
10
 
11
- class S3(BaseModel):
11
+ class BucketExportCredentials1(BaseModel):
12
12
  model_config = ConfigDict(
13
13
  populate_by_name=True,
14
14
  )
15
15
  access_key: Annotated[str, Field(alias='accessKey')]
16
16
  secret_key: Annotated[str, Field(alias='secretKey')]
17
+ type: Literal['s3']
17
18
 
18
19
 
19
- class BucketCredentials1(BaseModel):
20
- model_config = ConfigDict(
21
- extra='forbid',
22
- populate_by_name=True,
23
- )
24
- s3: S3
25
-
26
-
27
- class AzureBlob(BaseModel):
20
+ class BucketExportCredentials2(BaseModel):
28
21
  model_config = ConfigDict(
29
22
  populate_by_name=True,
30
23
  )
@@ -32,46 +25,39 @@ class AzureBlob(BaseModel):
32
25
  str,
33
26
  Field(
34
27
  alias='sasToken',
35
- description='A container SAS token — the scoped, expiring grant Azure recommends\nover an account key. Only the grant: the account and container it\napplies to are pinned by the signed `BucketConnection`, so rotating\nthe token can never repoint the connector.',
28
+ description='A container SAS token. Only the grant: the account and container\nit applies to are pinned by the signed `BucketConnection`.',
36
29
  ),
37
30
  ]
31
+ type: Literal['azureBlob']
38
32
 
39
33
 
40
- class BucketCredentials2(BaseModel):
41
- model_config = ConfigDict(
42
- extra='forbid',
43
- populate_by_name=True,
44
- )
45
- azure_blob: Annotated[AzureBlob, Field(alias='azureBlob')]
46
-
47
-
48
- class Gcs(BaseModel):
34
+ class BucketExportCredentials3(BaseModel):
49
35
  model_config = ConfigDict(
50
36
  populate_by_name=True,
51
37
  )
52
38
  service_account_json: Annotated[str, Field(alias='serviceAccountJson')]
39
+ type: Literal['gcs']
53
40
 
54
41
 
55
- class BucketCredentials3(BaseModel):
56
- model_config = ConfigDict(
57
- extra='forbid',
58
- populate_by_name=True,
59
- )
60
- gcs: Gcs
61
-
62
-
63
- class BucketCredentials(
64
- RootModel[BucketCredentials1 | BucketCredentials2 | BucketCredentials3]
42
+ class BucketExportCredentials(
43
+ RootModel[
44
+ BucketExportCredentials1 | BucketExportCredentials2 | BucketExportCredentials3
45
+ ]
65
46
  ):
66
- root: BucketCredentials1 | BucketCredentials2 | BucketCredentials3
47
+ root: Annotated[
48
+ BucketExportCredentials1 | BucketExportCredentials2 | BucketExportCredentials3,
49
+ Field(
50
+ description='The credentials of a Bucket connection, keyed by Bucket Provider like\n[`BucketConnection`]. Secret leaf fields are `Secret`-wrapped so they mask\nin a `redacted()` view but serialize transparently everywhere else.'
51
+ ),
52
+ ]
67
53
 
68
54
 
69
55
  class ExportConnectorCredentials1(BaseModel):
70
56
  model_config = ConfigDict(
71
- extra='forbid',
72
57
  populate_by_name=True,
73
58
  )
74
- bucket: BucketCredentials
59
+ credentials: BucketExportCredentials
60
+ type: Literal['bucket']
75
61
 
76
62
 
77
63
  class ExportConnectorCredentials(RootModel[ExportConnectorCredentials1]):
@@ -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 `data`. A
4
- stored ZIP with an encrypted entry can't be read."""
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 flag of an encrypted entry.
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
- encrypted = [entry.filename for entry in entries if entry.flag_bits & _ENCRYPTED]
57
- if encrypted:
58
- raise UnreadableDatasetError(f"its ZIP entry '{encrypted[0]}' is encrypted")
59
- files = [DatasetFile(entry.filename, entry.file_size) for entry in entries if not entry.is_dir()]
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
- return self._archive.open(file.path) # type: ignore[return-value]
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]
@@ -12,7 +12,7 @@ from datetime import datetime
12
12
  from pathlib import Path
13
13
  from typing import Any
14
14
 
15
- from dq_export_connector._models.export_connector_credentials import BucketCredentials
15
+ from dq_export_connector._models.export_connector_credentials import BucketExportCredentials
16
16
  from dq_export_connector._models.export_report import BucketConnection as ReceiptConnection
17
17
  from dq_export_connector._models.export_report import (
18
18
  BucketInputReceipt,
@@ -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, UnreadableDatasetError, open_dataset
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
@@ -33,10 +33,10 @@ from dq_export_connector.report import ReportBuilder
33
33
  def export(
34
34
  connector: ExportConnectorKind1,
35
35
  policies: list[ProvisionedPolicy],
36
- credentials: BucketCredentials,
36
+ credentials: BucketExportCredentials,
37
37
  inputs_dir: Path,
38
38
  now: datetime,
39
- build_store: Callable[[Any, BucketCredentials], Any],
39
+ build_store: Callable[[Any, BucketExportCredentials], Any],
40
40
  report: ReportBuilder,
41
41
  ) -> None:
42
42
  export_prefix = fill_date_tokens(connector.export_prefix, now) if connector.export_prefix else None
@@ -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(bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals])
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, UnreadableDatasetError) as error:
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"the object key {key!r} is longer than {PROVIDER_MAX_KEY_BYTES} bytes")
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(f"the object key {key!r} is longer than {AZURE_MAX_KEY_CHARACTERS} characters")
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(f"the object key {key!r} has more than {AZURE_MAX_KEY_SEGMENTS} segments")
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:
@@ -12,10 +12,10 @@ import obstore.exceptions
12
12
  from obstore.store import AzureStore, GCSStore, S3Store
13
13
 
14
14
  from dq_export_connector._models.export_connector_credentials import (
15
- BucketCredentials,
16
- BucketCredentials1,
17
- BucketCredentials2,
18
- BucketCredentials3,
15
+ BucketExportCredentials,
16
+ BucketExportCredentials1,
17
+ BucketExportCredentials2,
18
+ BucketExportCredentials3,
19
19
  )
20
20
  from dq_export_connector._models.export_worker_config import (
21
21
  BucketConnection,
@@ -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; `read_timeout` resets
52
- # on every read and is what detects a stalled connection.
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(seconds=60),
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
- # Provider error codes that mean bad credentials. They are checked before the
105
- # error's type: S3's SignatureDoesNotMatch and InvalidAccessKeyId arrive as a
106
- # 403, which object_store raises as permission denied.
107
- _CREDENTIAL_CODES: tuple[str, ...] = (
108
- # S3
109
- "SignatureDoesNotMatch",
110
- "InvalidAccessKeyId",
111
- "InvalidSecurityToken",
112
- "ExpiredToken",
113
- # Azure
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
- # Provider error codes recognised in an error's message, checked in order.
121
- # object_store wraps many non-2xx responses in a generic error, so the
122
- # provider's code in the message is often the only signal.
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
- message = str(error)
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
- for code, needles in _MESSAGE_CLASSIFIERS:
187
- if any(needle in message for needle in needles):
188
- return code
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,
@@ -228,7 +181,7 @@ _CREDENTIAL_PARSE_ERRORS = (
228
181
  _ECHOED_VALUE = re.compile(r'"(?:[^"\\]|\\.)*"|`(?![A-Za-z_][A-Za-z0-9_]*`)[^`]*`')
229
182
 
230
183
 
231
- def build_store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
184
+ def build_store(connection: BucketConnection, credentials: BucketExportCredentials) -> Any:
232
185
  """obstore parses the credentials here, so a malformed GCS key or Azure SAS
233
186
  token fails before any request, as does an address no URL can hold, such as
234
187
  an Azure account name with a space."""
@@ -246,36 +199,47 @@ def build_store(connection: BucketConnection, credentials: BucketCredentials) ->
246
199
  ) from error
247
200
 
248
201
 
249
- def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
202
+ def _store(connection: BucketConnection, credentials: BucketExportCredentials) -> Any:
250
203
  """ddc pins the provider pairing, so a mismatch here is a bug."""
251
204
  match (connection.root, credentials.root):
252
- case (BucketConnection1() as s3, BucketCredentials1() as s3_credentials):
205
+ case (BucketConnection1() as s3, BucketExportCredentials1() as s3_credentials):
253
206
  return S3Store(
254
207
  bucket=s3.bucket,
255
208
  region=s3.region,
256
- access_key_id=s3_credentials.s3.access_key,
257
- secret_access_key=s3_credentials.s3.secret_key,
209
+ access_key_id=_checked_s3_access_key(s3_credentials.access_key),
210
+ secret_access_key=s3_credentials.secret_key,
258
211
  retry_config=RETRY_CONFIG,
259
212
  client_options=CLIENT_CONFIG,
260
213
  )
261
- case (BucketConnection2() as azure, BucketCredentials2() as azure_credentials):
214
+ case (BucketConnection2() as azure, BucketExportCredentials2() as azure_credentials):
262
215
  return AzureStore(
263
216
  container_name=azure.container,
264
217
  account_name=azure.account_name,
265
- sas_key=_normalize_azure_sas_token(azure_credentials.azure_blob.sas_token),
218
+ sas_key=_normalize_azure_sas_token(azure_credentials.sas_token),
266
219
  retry_config=RETRY_CONFIG,
267
220
  client_options=CLIENT_CONFIG,
268
221
  )
269
- case (BucketConnection3() as gcs, BucketCredentials3() as gcs_credentials):
222
+ case (BucketConnection3() as gcs, BucketExportCredentials3() as gcs_credentials):
270
223
  return GCSStore(
271
224
  bucket=gcs.bucket,
272
- service_account_key=gcs_credentials.gcs.service_account_json,
225
+ service_account_key=gcs_credentials.service_account_json,
273
226
  retry_config=RETRY_CONFIG,
274
227
  client_options=CLIENT_CONFIG,
275
228
  )
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. obstore aborts a
6
- multipart upload that fails.
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
@@ -10,7 +10,7 @@ from typing import Any
10
10
 
11
11
  import obstore
12
12
 
13
- from dq_export_connector._models.export_connector_credentials import BucketCredentials
13
+ from dq_export_connector._models.export_connector_credentials import BucketExportCredentials
14
14
  from dq_export_connector._models.export_worker_config import BucketConnection
15
15
  from dq_export_connector.bucket.paths import join_key
16
16
  from dq_export_connector.bucket.store import StorageError, classify_error, failure_sentence, location, storage_call
@@ -27,8 +27,8 @@ def probe_key(path_prefix: str | None) -> str:
27
27
 
28
28
  def validate_connection(
29
29
  connection: BucketConnection,
30
- credentials: BucketCredentials,
31
- build_store: Callable[[BucketConnection, BucketCredentials], Any],
30
+ credentials: BucketExportCredentials,
31
+ build_store: Callable[[BucketConnection, BucketExportCredentials], Any],
32
32
  report: ReportBuilder,
33
33
  ) -> None:
34
34
  logger.info("Connection test started: provider %s", connection.root.type)
@@ -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: Exception, activity: str) -> str:
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)
@@ -1,8 +1,8 @@
1
1
  """Keeps the sealed half out of everything the worker writes.
2
2
 
3
3
  Log lines reach Decentriq-readable platform logs, and result messages reach
4
- api-platform in plaintext. Every string value of the credentials is masked, so a
5
- new credential field needs no change here. URL query strings are masked too,
4
+ api-platform in plaintext. Every string value of the credentials but the `type`
5
+ tags is masked, so a new credential field needs no change here. URL query strings are masked too,
6
6
  since storage clients put tokens there, such as an Azure SAS token.
7
7
  """
8
8
 
@@ -20,9 +20,10 @@ _URL_QUERY = re.compile(r"(?P<url>[a-zA-Z][a-zA-Z0-9+.-]*://[^\s?#\"'<>]+)\?[^\s
20
20
 
21
21
  def sealed_values(value: Any) -> list[str]:
22
22
  """Every string in a JSON value, including those inside strings that are
23
- themselves JSON, such as a GCS service account key."""
23
+ themselves JSON, such as a GCS service account key. The `type` tags of
24
+ the credentials, such as `s3`, are not secret."""
24
25
  if isinstance(value, dict):
25
- return [found for item in value.values() for found in sealed_values(item)]
26
+ return [found for key, item in value.items() if key != "type" for found in sealed_values(item)]
26
27
  if isinstance(value, list):
27
28
  return [found for item in value for found in sealed_values(item)]
28
29
  if isinstance(value, str):