multids 0.1.0__py3-none-any.whl

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,375 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Tuple
9
+
10
+ from ..interfaces import Connector, Readable, Writable
11
+
12
+ ProgressCallback = Callable[[int, int], Any]
13
+ OverallProgressCallback = Callable[[int, Optional[int]], Any]
14
+
15
+
16
+ class S3Connector(Connector, Readable, Writable):
17
+ """
18
+ Async S3 connector with streaming reads and multipart uploads.
19
+
20
+ Features:
21
+ - Streaming reads via `read_stream`/`read_bytes`.
22
+ - Multipart uploads with concurrent part uploads.
23
+ - Disk-backed staging for very large parts.
24
+ - Checkpointing to resume multipart uploads.
25
+ - Part-level and overall progress callbacks.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ aws_region: Optional[str] = None,
31
+ part_size: int = 8 * 1024 * 1024,
32
+ max_concurrency: int = 4,
33
+ spill_to_disk_threshold: int = 32 * 1024 * 1024,
34
+ enforce_min_part_size: bool = False,
35
+ min_multipart_upload_size: int = 5 * 1024 * 1024,
36
+ ):
37
+ self._region = aws_region
38
+ # Lazy-import aioboto3 to avoid import-time dependency issues during tests.
39
+ try:
40
+ import aioboto3 as _aioboto3
41
+
42
+ self._aioboto3 = _aioboto3
43
+ self._session = _aioboto3.Session()
44
+ except Exception:
45
+ self._aioboto3 = None
46
+ self._session = None
47
+ if enforce_min_part_size:
48
+ self.part_size = max(part_size, 5 * 1024 * 1024)
49
+ else:
50
+ self.part_size = part_size
51
+ self.max_concurrency = max(1, max_concurrency)
52
+ self.spill_to_disk_threshold = max(spill_to_disk_threshold, self.part_size)
53
+ # threshold before switching from single PUT to multipart upload
54
+ self.min_multipart_upload_size = max(0, int(min_multipart_upload_size))
55
+
56
+ async def read_stream(
57
+ self, bucket: Optional[str] = None, key: Optional[str] = None, *args: Any, **kwargs: Any
58
+ ) -> AsyncIterator[bytes]:
59
+ if not bucket or not key:
60
+ raise ValueError("bucket and key are required for S3Connector")
61
+ if self._session is None:
62
+ raise RuntimeError("aioboto3 is not available; install aioboto3 to use S3Connector")
63
+ async with self._session.client("s3", region_name=self._region) as client:
64
+ obj = await client.get_object(Bucket=bucket, Key=key)
65
+ stream = obj["Body"]
66
+ try:
67
+ while True:
68
+ chunk = await stream.read(self.part_size)
69
+ if not chunk:
70
+ break
71
+ yield chunk
72
+ finally:
73
+ await stream.close()
74
+
75
+ async def read_bytes(
76
+ self, bucket: Optional[str] = None, key: Optional[str] = None, *args: Any, **kwargs: Any
77
+ ) -> bytes:
78
+ if not bucket or not key:
79
+ raise ValueError("bucket and key are required for S3Connector")
80
+ buf = bytearray()
81
+ async for chunk in self.read_stream(bucket, key, *args, **kwargs):
82
+ buf.extend(chunk)
83
+ return bytes(buf)
84
+
85
+ async def read_json(self, bucket: Optional[str] = None, key: Optional[str] = None) -> Any:
86
+ """Read a JSON object from S3."""
87
+ if not bucket or not key:
88
+ raise ValueError("bucket and key are required for S3Connector")
89
+ data = await self.read_bytes(bucket, key)
90
+ return json.loads(data.decode("utf-8"))
91
+
92
+ async def write_json(
93
+ self, data: Any, bucket: Optional[str] = None, key: Optional[str] = None, indent: int = 2
94
+ ) -> None:
95
+ """Write a JSON object to S3."""
96
+ if not bucket or not key:
97
+ raise ValueError("bucket and key are required for S3Connector")
98
+ content = json.dumps(data, indent=indent, ensure_ascii=False)
99
+ await self.write_bytes(content.encode("utf-8"), bucket, key)
100
+
101
+ def _save_checkpoint(self, checkpoint_file: Path, data: dict) -> None:
102
+ if checkpoint_file is None:
103
+ return
104
+ checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
105
+ with open(checkpoint_file, "w", encoding="utf-8") as f:
106
+ json.dump(data, f)
107
+
108
+ def _load_checkpoint(self, checkpoint_file: Path) -> Optional[dict]:
109
+ if checkpoint_file is None or not checkpoint_file.exists():
110
+ return None
111
+ try:
112
+ return json.loads(checkpoint_file.read_text(encoding="utf-8"))
113
+ except Exception:
114
+ return None
115
+
116
+ async def _resume_upload(
117
+ self, client: Any, bucket: str, key: str, checkpoint_file: Optional[Path]
118
+ ) -> Tuple[Optional[str], List[Dict[str, Any]], int, int]:
119
+ upload_id = None
120
+ parts: List[Dict[str, Any]] = []
121
+ part_no = 1
122
+ uploaded_bytes = 0
123
+
124
+ if not checkpoint_file or not checkpoint_file.exists():
125
+ return upload_id, parts, part_no, uploaded_bytes
126
+
127
+ chk = self._load_checkpoint(checkpoint_file)
128
+ if chk and chk.get("bucket") == bucket and chk.get("key") == key and chk.get("upload_id"):
129
+ upload_id = chk["upload_id"]
130
+ try:
131
+ listed = await client.list_parts(Bucket=bucket, Key=key, UploadId=upload_id)
132
+ existing = {int(p["PartNumber"]): p for p in listed.get("Parts", [])}
133
+ for partnum, info in existing.items():
134
+ parts.append({"ETag": info["ETag"], "PartNumber": partnum, "size": int(info.get("Size", 0) or 0)})
135
+ uploaded_bytes += int(info.get("Size", 0) or 0)
136
+ except Exception:
137
+ for p in chk.get("parts", []):
138
+ parts.append(p)
139
+ uploaded_bytes += int(p.get("size", 0) or 0)
140
+ if parts:
141
+ part_no = max(int(p["PartNumber"]) for p in parts) + 1
142
+
143
+ return upload_id, parts, part_no, uploaded_bytes
144
+
145
+ async def _upload_part_from_bytes(
146
+ self,
147
+ client: Any,
148
+ bucket: str,
149
+ key: str,
150
+ upload_id: str,
151
+ part_number: int,
152
+ data: bytes,
153
+ semaphore: asyncio.Semaphore,
154
+ progress_callback: Optional[ProgressCallback],
155
+ ) -> Dict[str, Any]:
156
+ async with semaphore:
157
+ resp = await client.upload_part(
158
+ Bucket=bucket, Key=key, PartNumber=part_number, UploadId=upload_id, Body=data
159
+ )
160
+ if progress_callback:
161
+ progress_callback(part_number, len(data))
162
+ return {"ETag": resp["ETag"], "PartNumber": part_number, "size": len(data)}
163
+
164
+ async def _upload_part_from_file(
165
+ self,
166
+ client: Any,
167
+ bucket: str,
168
+ key: str,
169
+ upload_id: str,
170
+ part_number: int,
171
+ path: str,
172
+ semaphore: asyncio.Semaphore,
173
+ progress_callback: Optional[ProgressCallback],
174
+ ) -> Dict[str, Any]:
175
+ async with semaphore:
176
+ with open(path, "rb") as fh:
177
+ resp = await client.upload_part(
178
+ Bucket=bucket, Key=key, PartNumber=part_number, UploadId=upload_id, Body=fh
179
+ )
180
+ size = os.path.getsize(path)
181
+ if progress_callback:
182
+ progress_callback(part_number, size)
183
+ return {"ETag": resp["ETag"], "PartNumber": part_number, "size": size}
184
+
185
+ async def write_stream( # noqa: C901
186
+ self,
187
+ stream: AsyncIterator[bytes],
188
+ bucket: Optional[str] = None,
189
+ key: Optional[str] = None,
190
+ *args: Any,
191
+ progress_callback: Optional[ProgressCallback] = None,
192
+ overall_progress: Optional[OverallProgressCallback] = None,
193
+ resume: bool = False,
194
+ checkpoint_path: Optional[str] = None,
195
+ force_multipart: bool = False,
196
+ **kwargs: Any,
197
+ ) -> None:
198
+ """Write an async byte stream to S3 with resumable multipart support.
199
+
200
+ If `resume` is True and `checkpoint_path` points to a valid checkpoint file,
201
+ the upload will attempt to resume from the recorded `upload_id` and parts.
202
+ """
203
+ if not bucket or not key:
204
+ raise ValueError("bucket and key are required for S3Connector")
205
+ if self._session is None:
206
+ raise RuntimeError("aioboto3 is not available; install aioboto3 to use S3Connector")
207
+ async with self._session.client("s3", region_name=self._region) as client:
208
+ part_no = 1
209
+ upload_id: Optional[str] = None
210
+ parts: List[Dict[str, Any]] = []
211
+ tasks: List[asyncio.Task] = []
212
+ tmp_files: List[str] = []
213
+
214
+ uploaded_bytes = 0
215
+ checkpoint_file: Optional[Path] = Path(checkpoint_path) if checkpoint_path else None
216
+
217
+ if resume:
218
+ upload_id, parts, part_no, uploaded_bytes = await self._resume_upload(
219
+ client, bucket, key, checkpoint_file
220
+ )
221
+
222
+ semaphore = asyncio.Semaphore(self.max_concurrency)
223
+ buffer = bytearray()
224
+ try:
225
+ async for chunk in stream:
226
+ buffer.extend(chunk)
227
+ if upload_id is None:
228
+ if force_multipart:
229
+ mpu = await client.create_multipart_upload(Bucket=bucket, Key=key)
230
+ upload_id = mpu["UploadId"]
231
+ else:
232
+ if uploaded_bytes + len(buffer) < self.min_multipart_upload_size:
233
+ continue
234
+ mpu = await client.create_multipart_upload(Bucket=bucket, Key=key)
235
+ upload_id = mpu["UploadId"]
236
+
237
+ if len(buffer) >= self.part_size:
238
+ if len(buffer) >= self.spill_to_disk_threshold:
239
+ tf = tempfile.NamedTemporaryFile(delete=False)
240
+ tf.write(bytes(buffer))
241
+ tf.close()
242
+ tmp_files.append(tf.name)
243
+ task = asyncio.create_task(
244
+ self._upload_part_from_file(
245
+ client, bucket, key, upload_id, part_no, tf.name, semaphore, progress_callback
246
+ )
247
+ )
248
+ else:
249
+ task = asyncio.create_task(
250
+ self._upload_part_from_bytes(
251
+ client,
252
+ bucket,
253
+ key,
254
+ upload_id,
255
+ part_no,
256
+ bytes(buffer),
257
+ semaphore,
258
+ progress_callback,
259
+ )
260
+ )
261
+
262
+ tasks.append(task)
263
+ part_no += 1
264
+ buffer.clear()
265
+
266
+ if len(tasks) >= self.max_concurrency:
267
+ done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
268
+ for d in done:
269
+ res = d.result()
270
+ parts.append(res)
271
+ uploaded_bytes += int(res.get("size", 0) or 0)
272
+ if checkpoint_file is not None and upload_id is not None:
273
+ self._save_checkpoint(
274
+ checkpoint_file,
275
+ {"bucket": bucket, "key": key, "upload_id": upload_id, "parts": parts},
276
+ )
277
+ if overall_progress:
278
+ overall_progress(uploaded_bytes, None)
279
+ tasks = list(pending)
280
+
281
+ if upload_id is None:
282
+ await client.put_object(Bucket=bucket, Key=key, Body=bytes(buffer))
283
+ if overall_progress:
284
+ overall_progress(len(buffer), len(buffer))
285
+ return
286
+
287
+ if buffer:
288
+ if len(buffer) >= self.spill_to_disk_threshold:
289
+ tf = tempfile.NamedTemporaryFile(delete=False)
290
+ tf.write(bytes(buffer))
291
+ tf.close()
292
+ tmp_files.append(tf.name)
293
+ task = asyncio.create_task(
294
+ self._upload_part_from_file(
295
+ client, bucket, key, upload_id, part_no, tf.name, semaphore, progress_callback
296
+ )
297
+ )
298
+ else:
299
+ task = asyncio.create_task(
300
+ self._upload_part_from_bytes(
301
+ client, bucket, key, upload_id, part_no, bytes(buffer), semaphore, progress_callback
302
+ )
303
+ )
304
+ tasks.append(task)
305
+
306
+ if tasks:
307
+ for t in asyncio.as_completed(tasks):
308
+ res = await t
309
+ parts.append(res)
310
+ uploaded_bytes += int(res.get("size", 0) or 0)
311
+ if checkpoint_file is not None and upload_id is not None:
312
+ self._save_checkpoint(
313
+ checkpoint_file,
314
+ {"bucket": bucket, "key": key, "upload_id": upload_id, "parts": parts},
315
+ )
316
+ if overall_progress:
317
+ overall_progress(uploaded_bytes, None)
318
+
319
+ parts_sorted = sorted(parts, key=lambda p: int(p["PartNumber"]))
320
+ await client.complete_multipart_upload(
321
+ Bucket=bucket,
322
+ Key=key,
323
+ UploadId=upload_id,
324
+ MultipartUpload={"Parts": parts_sorted},
325
+ )
326
+
327
+ if checkpoint_file is not None and checkpoint_file.exists():
328
+ try:
329
+ checkpoint_file.unlink()
330
+ except Exception:
331
+ pass
332
+ except Exception:
333
+ if upload_id is not None and checkpoint_file is not None:
334
+ try:
335
+ self._save_checkpoint(
336
+ checkpoint_file,
337
+ {"bucket": bucket, "key": key, "upload_id": upload_id, "parts": parts},
338
+ )
339
+ except Exception:
340
+ pass
341
+ else:
342
+ if upload_id is not None:
343
+ try:
344
+ await client.abort_multipart_upload(Bucket=bucket, Key=key, UploadId=upload_id)
345
+ except Exception:
346
+ pass
347
+ raise
348
+ finally:
349
+ for p in tmp_files:
350
+ try:
351
+ os.unlink(p)
352
+ except Exception:
353
+ pass
354
+
355
+ async def write_bytes(
356
+ self, data: bytes, bucket: Optional[str] = None, key: Optional[str] = None, *args: Any, **kwargs: Any
357
+ ) -> None:
358
+ async def gen() -> AsyncIterator[bytes]:
359
+ yield data
360
+
361
+ await self.write_stream(gen(), bucket, key, *args, **kwargs)
362
+
363
+ async def close(self) -> None:
364
+ return
365
+
366
+ async def ping(self) -> bool:
367
+ """Check AWS connectivity by listing buckets."""
368
+ try:
369
+ if self._session is None:
370
+ return False
371
+ async with self._session.client("s3", region_name=self._region) as client:
372
+ await client.list_buckets()
373
+ return True
374
+ except Exception:
375
+ return False
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, AsyncIterator, Iterable
4
+
5
+ from sqlalchemy import text
6
+ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
7
+
8
+ from ..interfaces import Connector
9
+
10
+
11
+ class SQLConnectorBase(Connector):
12
+ """
13
+ Base SQL connector using SQLAlchemy async engine.
14
+
15
+ The `url` should be an async-enabled SQLAlchemy URL (for MySQL: `mysql+asyncmy://...`).
16
+ """
17
+
18
+ def __init__(self, url: str):
19
+ self._url = url
20
+ self._engine: AsyncEngine = create_async_engine(self._url, future=True)
21
+
22
+ async def fetch_rows(self, query: str, /, **params: Any) -> AsyncIterator[dict]:
23
+ """Stream rows from a query as dictionaries (uses SQLAlchemy streaming API)."""
24
+ async with self._engine.connect() as conn:
25
+ result = await conn.stream(text(query), params)
26
+ async for row in result.mappings():
27
+ yield dict(row)
28
+
29
+ async def execute(self, statement: str, /, **params: Any) -> None:
30
+ """Execute a statement (INSERT/UPDATE/DELETE)."""
31
+ async with self._engine.begin() as conn:
32
+ await conn.execute(text(statement), params)
33
+
34
+ async def execute_many(self, statement: str, params_iter: Iterable[dict]) -> None:
35
+ """
36
+ Execute the same statement multiple times with different parameters.
37
+
38
+ This implementation iterates and executes repeatedly inside a transaction.
39
+ Drivers or more advanced techniques (COPY, bulk insert) may be added for performance.
40
+ """
41
+ async with self._engine.begin() as conn:
42
+ for params in params_iter:
43
+ await conn.execute(text(statement), params)
44
+
45
+ async def close(self) -> None:
46
+ await self._engine.dispose()
47
+
48
+ async def ping(self) -> bool:
49
+ """Check connection by running a simple query."""
50
+ try:
51
+ async with self._engine.connect() as conn:
52
+ await conn.execute(text("SELECT 1"))
53
+ return True
54
+ except Exception:
55
+ return False
56
+
57
+
58
+ class MySQLConnector(SQLConnectorBase):
59
+ """
60
+ MySQL connector convenience wrapper.
61
+
62
+ Example URL: `mysql+asyncmy://user:password@host:3306/dbname`
63
+ """
64
+
65
+ def __init__(self, url: str):
66
+ super().__init__(url)
67
+
68
+ async def bulk_insert(
69
+ self,
70
+ table: str,
71
+ rows: Iterable[dict],
72
+ chunk_size: int = 1000,
73
+ ) -> None:
74
+ """
75
+ Optimized bulk insert using SQLAlchemy's batch execution.
76
+
77
+ Args:
78
+ table: Name of the table to insert into.
79
+ rows: Iterable of dictionaries, where keys match column names.
80
+ chunk_size: Number of rows to insert in a single batch.
81
+ """
82
+ # Convert to iterator to handle both lists and generators
83
+ rows_iter = iter(rows)
84
+
85
+ # Peek at the first row to determine columns without consuming it
86
+ try:
87
+ first_row = next(rows_iter)
88
+ except StopIteration:
89
+ return # Empty iterable
90
+
91
+ cols = list(first_row.keys())
92
+ # Reconstruct the iterable with the first row back in front
93
+ # (This is a simple way; for very large iterables, using itertools.chain is cleaner)
94
+ from itertools import chain, islice
95
+
96
+ rows_iter = chain([first_row], rows_iter)
97
+
98
+ col_list = ", ".join([f"`{c}`" for c in cols])
99
+ placeholders = ", ".join([f":{c}" for c in cols])
100
+ stmt = text(f"INSERT INTO {table} ({col_list}) VALUES ({placeholders})")
101
+
102
+ async with self._engine.begin() as conn:
103
+ while True:
104
+ chunk = list(islice(rows_iter, chunk_size))
105
+ if not chunk:
106
+ break
107
+ await conn.execute(stmt, chunk)
multids/interfaces.py ADDED
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import abstractmethod
4
+ from dataclasses import dataclass
5
+ from typing import Any, AsyncIterator, Optional, Protocol, TypedDict, runtime_checkable
6
+
7
+ DataChunk = bytes
8
+ AsyncByteIterator = AsyncIterator[DataChunk]
9
+
10
+
11
+ class Readable(Protocol):
12
+ """Protocol for objects that can stream bytes out of a data source."""
13
+
14
+ def read_stream(self, *args: Any, **kwargs: Any) -> AsyncByteIterator:
15
+ """Yield chunks of bytes from the source."""
16
+ ...
17
+
18
+ async def read_bytes(self, *args: Any, **kwargs: Any) -> bytes:
19
+ """Convenience: read the entire payload into memory."""
20
+ ...
21
+
22
+
23
+ class Writable(Protocol):
24
+ """Protocol for objects that can consume async byte streams to write to a destination."""
25
+
26
+ async def write_stream(self, stream: AsyncByteIterator, *args: Any, **kwargs: Any) -> None:
27
+ """Consume the stream and store the content."""
28
+ ...
29
+
30
+ async def write_bytes(self, data: bytes, *args: Any, **kwargs: Any) -> None:
31
+ """Convenience: write a single bytes object."""
32
+ ...
33
+
34
+
35
+ @runtime_checkable
36
+ class Connector(Protocol):
37
+ """
38
+ Base connector interface.
39
+
40
+ Connectors SHOULD implement `close()` and may provide any combination of
41
+ the read/write convenience methods above.
42
+ """
43
+
44
+ @abstractmethod
45
+ async def close(self) -> None: # pragma: no cover - interface only
46
+ """Release any held resources (sessions, clients)."""
47
+ ...
48
+
49
+ async def ping(self) -> bool:
50
+ """Optional quick health check; return True if the connector is responsive."""
51
+ ...
52
+
53
+
54
+ class S3Location(TypedDict):
55
+ bucket: str
56
+ key: str
57
+
58
+
59
+ class SQLLocation(TypedDict, total=False):
60
+ table: str
61
+ schema: Optional[str]
62
+
63
+
64
+ @dataclass
65
+ class RangeSpec:
66
+ offset: Optional[int] = None
67
+ length: Optional[int] = None