sandloom-s3 0.7.0a13__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.
@@ -0,0 +1,4 @@
1
+ # Build artifacts from `uv build` — not committed.
2
+ dist/
3
+ build/
4
+ *.egg-info/
@@ -0,0 +1,6 @@
1
+ # Changelog — sandloom-s3
2
+
3
+ ## [0.7.0a13]
4
+
5
+ - Add an optional S3-compatible object store driver with signed GET URLs and user metadata.
6
+ - Run object store conformance on MinIO and SeaweedFS.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Sandloom
2
+ Copyright 2026 Vasyl Cherniavskyi
3
+
4
+ The original Sandloom framework code, documentation and examples are licensed
5
+ under the Apache License, Version 2.0. See LICENSE for the full terms.
6
+
7
+ Third-party components and assets retain their own copyright notices and
8
+ licenses. This notice does not replace or modify those terms.
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.5
2
+ Name: sandloom-s3
3
+ Version: 0.7.0a13
4
+ Summary: S3-compatible object store driver for Sandloom
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: anyio<5,>=4
10
+ Requires-Dist: boto3<2,>=1.36
11
+ Requires-Dist: botocore<2,>=1.36
12
+ Requires-Dist: pydantic<3,>=2
13
+ Requires-Dist: sandloom<0.8,>=0.7.0a13
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Sandloom S3 driver
17
+
18
+ Install this package alongside the matching Sandloom release. For a checkout,
19
+ run `uv pip install -e packages/sandloom -e packages/sandloom-s3` from the
20
+ repository root. Sandloom discovers `objectstore.s3` through the
21
+ `sandloom.drivers` entry-point group.
22
+
23
+ For an existing AWS S3 general-purpose bucket, set:
24
+
25
+ ```sh
26
+ INFRA='{"objectstore":{"default":{"driver":"s3","bucket":"app-objects","region":"eu-west-1"}}}'
27
+ ```
28
+
29
+ The driver uses the AWS credential chain by default. For MinIO or another
30
+ S3-compatible endpoint, add `endpoint_url` and, if needed, set
31
+ `addressing_style` to `path`. Supply credentials through the SDK environment
32
+ or through both `access_key_id` and `secret_access_key` in the instance
33
+ configuration. Use an HTTPS endpoint in production.
34
+
35
+ The credentials need PutObject, GetObject and DeleteObject permissions on the
36
+ object keys. Readiness probes use HeadBucket, which requires ListBucket on AWS.
37
+ The bucket must already exist. `url()` signs a GET for 300 seconds by default.
38
+ The endpoint used for signing must be reachable by the URL recipient. Treat
39
+ the signed URL as a credential until it expires.
40
+
41
+ Uploads accept bytes or a stream with an async `read(size)` method. Stream
42
+ uploads spool to temporary storage before one PutObject call.
43
+ `max_upload_size_bytes` defaults to 50 MiB and also limits downloads, which
44
+ return bytes in memory. Zero removes the configured limit. Single PUTs are
45
+ still capped at 5 GiB. Delete follows S3 semantics and succeeds for absent keys.
46
+
47
+ AWS S3 general-purpose buckets, MinIO and SeaweedFS use the same driver. Other
48
+ S3-compatible services can be exercised with the same endpoint test using a
49
+ dedicated test bucket and `SANDLOOM_S3_TEST_ENDPOINT`. Compatibility depends
50
+ on the service's support for SigV4, HeadBucket, PutObject, GetObject,
51
+ DeleteObject and signed GETs.
52
+
53
+ ## Backend compatibility
54
+
55
+ | Backend | Configuration | Verification |
56
+ | --- | --- | --- |
57
+ | Amazon S3 general-purpose buckets | Bucket and AWS region, SDK credential chain | Targeted by the driver. The endpoint suite can run against a dedicated AWS test bucket. [AWS S3 API](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html) |
58
+ | MinIO | Endpoint URL, region, path-style addressing | Passed the endpoint suite on RELEASE.2025-04-22T22-12-26Z. The MinIO integration job uses that release. [MinIO and boto3](https://support.hpe.com/hpesc/public/docDisplay?docId=a00aie17hen_us&docLocale=en_US&page=Notebooks%2Fusing-boto3.html) |
59
+ | SeaweedFS | Endpoint URL, region, path-style addressing | Passed the endpoint suite on 4.53. The SeaweedFS integration job uses that release. [SeaweedFS S3 quick start](https://github.com/seaweedfs/seaweedfs#quick-start) |
60
+ | Cloudflare R2 | Account S3 endpoint, region `auto`, R2 API credentials | Candidate for endpoint testing. [R2 S3 compatibility](https://developers.cloudflare.com/r2/api/s3/api/) |
61
+ | Ceph RGW | Gateway endpoint, region and credentials for that gateway | Candidate for endpoint testing. [Ceph S3 API compliance](https://docs.ceph.com/en/latest/dev/radosgw/s3_compliance/) |
62
+
63
+ SeaweedFS 3.97 failed the endpoint suite during reads with `NoSuchBucket` after successful writes.
64
+
65
+ Run the endpoint suite from the repository root. It writes and removes objects
66
+ under unique `conformance/` keys in the selected bucket.
67
+
68
+ ```sh
69
+ SANDLOOM_S3_TEST_BUCKET=sandloom-conformance \
70
+ SANDLOOM_S3_TEST_ENDPOINT=http://127.0.0.1:9000 \
71
+ uv run --no-sync pytest -n 2 --dist loadfile packages/sandloom-s3/tests
72
+ ```
73
+
74
+ The MinIO CI job runs the endpoint suite as a service user with
75
+ `s3:ListBucket` on the test bucket and object permissions under
76
+ `conformance/*`. To run its access check on an existing test endpoint, seed
77
+ an object outside the permitted prefix as an administrator and set
78
+ `SANDLOOM_S3_TEST_DENIED_KEY` to that key. Run pytest with the service user's
79
+ credentials. The check expects a missing key under the permitted prefix to
80
+ raise `FileNotFoundError` and reads of the seeded object to return HTTP 403,
81
+ including through a signed GET URL.
@@ -0,0 +1,66 @@
1
+ # Sandloom S3 driver
2
+
3
+ Install this package alongside the matching Sandloom release. For a checkout,
4
+ run `uv pip install -e packages/sandloom -e packages/sandloom-s3` from the
5
+ repository root. Sandloom discovers `objectstore.s3` through the
6
+ `sandloom.drivers` entry-point group.
7
+
8
+ For an existing AWS S3 general-purpose bucket, set:
9
+
10
+ ```sh
11
+ INFRA='{"objectstore":{"default":{"driver":"s3","bucket":"app-objects","region":"eu-west-1"}}}'
12
+ ```
13
+
14
+ The driver uses the AWS credential chain by default. For MinIO or another
15
+ S3-compatible endpoint, add `endpoint_url` and, if needed, set
16
+ `addressing_style` to `path`. Supply credentials through the SDK environment
17
+ or through both `access_key_id` and `secret_access_key` in the instance
18
+ configuration. Use an HTTPS endpoint in production.
19
+
20
+ The credentials need PutObject, GetObject and DeleteObject permissions on the
21
+ object keys. Readiness probes use HeadBucket, which requires ListBucket on AWS.
22
+ The bucket must already exist. `url()` signs a GET for 300 seconds by default.
23
+ The endpoint used for signing must be reachable by the URL recipient. Treat
24
+ the signed URL as a credential until it expires.
25
+
26
+ Uploads accept bytes or a stream with an async `read(size)` method. Stream
27
+ uploads spool to temporary storage before one PutObject call.
28
+ `max_upload_size_bytes` defaults to 50 MiB and also limits downloads, which
29
+ return bytes in memory. Zero removes the configured limit. Single PUTs are
30
+ still capped at 5 GiB. Delete follows S3 semantics and succeeds for absent keys.
31
+
32
+ AWS S3 general-purpose buckets, MinIO and SeaweedFS use the same driver. Other
33
+ S3-compatible services can be exercised with the same endpoint test using a
34
+ dedicated test bucket and `SANDLOOM_S3_TEST_ENDPOINT`. Compatibility depends
35
+ on the service's support for SigV4, HeadBucket, PutObject, GetObject,
36
+ DeleteObject and signed GETs.
37
+
38
+ ## Backend compatibility
39
+
40
+ | Backend | Configuration | Verification |
41
+ | --- | --- | --- |
42
+ | Amazon S3 general-purpose buckets | Bucket and AWS region, SDK credential chain | Targeted by the driver. The endpoint suite can run against a dedicated AWS test bucket. [AWS S3 API](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html) |
43
+ | MinIO | Endpoint URL, region, path-style addressing | Passed the endpoint suite on RELEASE.2025-04-22T22-12-26Z. The MinIO integration job uses that release. [MinIO and boto3](https://support.hpe.com/hpesc/public/docDisplay?docId=a00aie17hen_us&docLocale=en_US&page=Notebooks%2Fusing-boto3.html) |
44
+ | SeaweedFS | Endpoint URL, region, path-style addressing | Passed the endpoint suite on 4.53. The SeaweedFS integration job uses that release. [SeaweedFS S3 quick start](https://github.com/seaweedfs/seaweedfs#quick-start) |
45
+ | Cloudflare R2 | Account S3 endpoint, region `auto`, R2 API credentials | Candidate for endpoint testing. [R2 S3 compatibility](https://developers.cloudflare.com/r2/api/s3/api/) |
46
+ | Ceph RGW | Gateway endpoint, region and credentials for that gateway | Candidate for endpoint testing. [Ceph S3 API compliance](https://docs.ceph.com/en/latest/dev/radosgw/s3_compliance/) |
47
+
48
+ SeaweedFS 3.97 failed the endpoint suite during reads with `NoSuchBucket` after successful writes.
49
+
50
+ Run the endpoint suite from the repository root. It writes and removes objects
51
+ under unique `conformance/` keys in the selected bucket.
52
+
53
+ ```sh
54
+ SANDLOOM_S3_TEST_BUCKET=sandloom-conformance \
55
+ SANDLOOM_S3_TEST_ENDPOINT=http://127.0.0.1:9000 \
56
+ uv run --no-sync pytest -n 2 --dist loadfile packages/sandloom-s3/tests
57
+ ```
58
+
59
+ The MinIO CI job runs the endpoint suite as a service user with
60
+ `s3:ListBucket` on the test bucket and object permissions under
61
+ `conformance/*`. To run its access check on an existing test endpoint, seed
62
+ an object outside the permitted prefix as an administrator and set
63
+ `SANDLOOM_S3_TEST_DENIED_KEY` to that key. Run pytest with the service user's
64
+ credentials. The check expects a missing key under the permitted prefix to
65
+ raise `FileNotFoundError` and reads of the seeded object to return HTTP 403,
66
+ including through a signed GET URL.
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "sandloom-s3"
3
+ version = "0.7.0a13"
4
+ description = "S3-compatible object store driver for Sandloom"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ dependencies = [
10
+ "sandloom>=0.7.0a13,<0.8",
11
+ "anyio>=4,<5",
12
+ "boto3>=1.36,<2",
13
+ "botocore>=1.36,<2",
14
+ "pydantic>=2,<3",
15
+ ]
16
+
17
+ [project.entry-points."sandloom.drivers"]
18
+ "objectstore.s3" = "sandloom_s3:S3ObjectStore"
19
+
20
+ [build-system]
21
+ requires = ["hatchling>=1.27"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/sandloom_s3"]
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ include = ["/src", "/LICENSE", "/NOTICE", "/README.md", "/CHANGELOG.md", "/pyproject.toml"]
@@ -0,0 +1,207 @@
1
+ """An object store for AWS S3 and S3-compatible endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from functools import partial
7
+ from tempfile import SpooledTemporaryFile
8
+ from typing import Any, Literal, cast
9
+
10
+ import boto3
11
+ from anyio import Lock, to_thread
12
+ from botocore.config import Config
13
+ from botocore.exceptions import BotoCoreError, ClientError
14
+ from pydantic import (
15
+ AnyHttpUrl,
16
+ BaseModel,
17
+ ConfigDict,
18
+ Field,
19
+ SecretStr,
20
+ model_validator,
21
+ )
22
+
23
+ from sandloom.driverkit import (
24
+ HealthResult,
25
+ ObjectContent,
26
+ ObjectStoreProvider,
27
+ ObjectTooLargeError,
28
+ UploadTooLargeError,
29
+ iter_object_chunks,
30
+ validate_object_key,
31
+ )
32
+
33
+ _CHUNK_SIZE = 1024 * 1024
34
+ _MAX_SINGLE_PUT = 5 * 1024**3
35
+
36
+
37
+ class S3Options(BaseModel):
38
+ model_config = ConfigDict(extra="forbid", hide_input_in_errors=True)
39
+
40
+ bucket: str = Field(min_length=1)
41
+ region: str | None = None
42
+ endpoint_url: AnyHttpUrl | None = None
43
+ addressing_style: Literal["auto", "path", "virtual"] = "auto"
44
+ access_key_id: SecretStr | None = None
45
+ secret_access_key: SecretStr | None = None
46
+ presign_seconds: int = Field(default=300, ge=1, le=604800)
47
+ max_upload_size_bytes: int = Field(default=50 * 1024**2, ge=0)
48
+
49
+ @model_validator(mode="after")
50
+ def validate_connection(self) -> S3Options:
51
+ if bool(self.access_key_id) != bool(self.secret_access_key):
52
+ raise ValueError(
53
+ "Provide both S3 credential fields or use the AWS credential chain"
54
+ )
55
+ endpoint = self.endpoint_url
56
+ if endpoint and (
57
+ endpoint.username
58
+ or endpoint.password
59
+ or endpoint.query
60
+ or endpoint.fragment
61
+ ):
62
+ raise ValueError(
63
+ "S3 endpoint cannot include user info, a query or a fragment"
64
+ )
65
+ return self
66
+
67
+
68
+ class S3ObjectStore(ObjectStoreProvider):
69
+ contract_version = "v1"
70
+ supported_features = frozenset({"metadata", "presigned_get"})
71
+ options_schema = S3Options
72
+
73
+ def __init__(self, *, name: str, driver: str, options: Mapping[str, Any]) -> None:
74
+ super().__init__(name=name, driver=driver, options=options)
75
+ self._config = S3Options.model_validate(options)
76
+ self._client: Any = None
77
+ self._client_lock = Lock()
78
+
79
+ def _connect(self) -> Any:
80
+ options = self._config
81
+ return boto3.session.Session().client(
82
+ "s3",
83
+ region_name=options.region,
84
+ endpoint_url=str(options.endpoint_url) if options.endpoint_url else None,
85
+ aws_access_key_id=options.access_key_id.get_secret_value()
86
+ if options.access_key_id
87
+ else None,
88
+ aws_secret_access_key=options.secret_access_key.get_secret_value()
89
+ if options.secret_access_key
90
+ else None,
91
+ config=Config(
92
+ signature_version="s3v4",
93
+ connect_timeout=2,
94
+ read_timeout=10,
95
+ retries={"mode": "standard", "total_max_attempts": 2},
96
+ s3={"addressing_style": options.addressing_style},
97
+ ),
98
+ )
99
+
100
+ async def aopen(self) -> None:
101
+ # Client creation (credential resolution included) can block. Serialize
102
+ # the first open with the same lock used by direct SDK calls.
103
+ async with self._client_lock:
104
+ if self._client is None:
105
+ self._client = await to_thread.run_sync(self._connect)
106
+
107
+ async def aclose(self) -> None:
108
+ async with self._client_lock:
109
+ if self._client is not None:
110
+ client, self._client = self._client, None
111
+ await to_thread.run_sync(client.close)
112
+
113
+ async def _backend(self) -> Any:
114
+ await self.aopen()
115
+ return self._client
116
+
117
+ async def put(
118
+ self,
119
+ key: str,
120
+ data: ObjectContent,
121
+ *,
122
+ content_type: str | None = None,
123
+ metadata: Mapping[str, str] | None = None,
124
+ ) -> str:
125
+ validate_object_key(key)
126
+ limit = min(
127
+ self._config.max_upload_size_bytes or _MAX_SINGLE_PUT, _MAX_SINGLE_PUT
128
+ )
129
+ params: dict[str, Any] = {"Bucket": self._config.bucket, "Key": key}
130
+ if content_type is not None:
131
+ params["ContentType"] = content_type
132
+ if metadata is not None:
133
+ params["Metadata"] = dict(metadata)
134
+ client = await self._backend()
135
+ if isinstance(data, (bytes, bytearray)):
136
+ if len(data) > limit:
137
+ raise UploadTooLargeError(f"Upload exceeds {limit} bytes")
138
+ await to_thread.run_sync(
139
+ partial(client.put_object, Body=bytes(data), **params)
140
+ )
141
+ else:
142
+ # A seekable body allows the SDK to sign and retry the request.
143
+ # Spill larger inputs to disk and publish only after the whole
144
+ # source has been read within its size limit.
145
+ with SpooledTemporaryFile(max_size=_CHUNK_SIZE) as body:
146
+ written = 0
147
+ async for chunk in iter_object_chunks(data, _CHUNK_SIZE):
148
+ written += len(chunk)
149
+ if written > limit:
150
+ raise UploadTooLargeError(f"Upload exceeds {limit} bytes")
151
+ await to_thread.run_sync(body.write, chunk)
152
+ await to_thread.run_sync(body.seek, 0)
153
+ await to_thread.run_sync(
154
+ partial(client.put_object, Body=body, **params)
155
+ )
156
+ return key
157
+
158
+ async def get(self, key: str) -> bytes:
159
+ validate_object_key(key)
160
+ client = await self._backend()
161
+
162
+ def read() -> bytes:
163
+ try:
164
+ result = client.get_object(Bucket=self._config.bucket, Key=key)
165
+ except ClientError as exc:
166
+ if exc.response["Error"]["Code"] == "NoSuchKey":
167
+ raise FileNotFoundError(key) from exc
168
+ raise
169
+ body = result["Body"]
170
+ try:
171
+ limit = self._config.max_upload_size_bytes
172
+ if limit and result["ContentLength"] > limit:
173
+ raise ObjectTooLargeError(f"Stored object exceeds {limit} bytes")
174
+ return cast(bytes, body.read())
175
+ finally:
176
+ body.close()
177
+
178
+ return await to_thread.run_sync(read)
179
+
180
+ async def delete(self, key: str) -> None:
181
+ validate_object_key(key)
182
+ client = await self._backend()
183
+ await to_thread.run_sync(
184
+ partial(client.delete_object, Bucket=self._config.bucket, Key=key)
185
+ )
186
+
187
+ async def url(self, key: str) -> str:
188
+ validate_object_key(key)
189
+ client = await self._backend()
190
+ return await to_thread.run_sync(
191
+ partial(
192
+ client.generate_presigned_url,
193
+ "get_object",
194
+ Params={"Bucket": self._config.bucket, "Key": key},
195
+ ExpiresIn=self._config.presign_seconds,
196
+ )
197
+ )
198
+
199
+ async def health(self) -> HealthResult:
200
+ try:
201
+ client = await self._backend()
202
+ await to_thread.run_sync(
203
+ partial(client.head_bucket, Bucket=self._config.bucket)
204
+ )
205
+ except (BotoCoreError, ClientError) as exc:
206
+ return HealthResult(status="fail", details={"error": type(exc).__name__})
207
+ return HealthResult(status="ok")