panpath 0.4.4__tar.gz → 0.4.6__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.
- {panpath-0.4.4 → panpath-0.4.6}/PKG-INFO +1 -1
- {panpath-0.4.4 → panpath-0.4.6}/panpath/__init__.py +1 -1
- {panpath-0.4.4 → panpath-0.4.6}/panpath/azure_async_client.py +56 -16
- {panpath-0.4.4 → panpath-0.4.6}/panpath/azure_client.py +53 -10
- {panpath-0.4.4 → panpath-0.4.6}/panpath/base.py +1 -1
- {panpath-0.4.4 → panpath-0.4.6}/panpath/clients.py +73 -85
- {panpath-0.4.4 → panpath-0.4.6}/panpath/cloud.py +20 -4
- {panpath-0.4.4 → panpath-0.4.6}/panpath/gs_async_client.py +51 -4
- {panpath-0.4.4 → panpath-0.4.6}/panpath/gs_client.py +44 -3
- {panpath-0.4.4 → panpath-0.4.6}/panpath/local_path.py +5 -2
- {panpath-0.4.4 → panpath-0.4.6}/panpath/s3_async_client.py +48 -9
- {panpath-0.4.4 → panpath-0.4.6}/panpath/s3_client.py +44 -2
- {panpath-0.4.4 → panpath-0.4.6}/pyproject.toml +1 -1
- {panpath-0.4.4 → panpath-0.4.6}/LICENSE +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/README.md +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/azure_path.py +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/exceptions.py +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/gs_path.py +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/py.typed +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/registry.py +0 -0
- {panpath-0.4.4 → panpath-0.4.6}/panpath/s3_path.py +0 -0
|
@@ -129,9 +129,9 @@ class AsyncAzureBlobClient(AsyncClient):
|
|
|
129
129
|
try:
|
|
130
130
|
loop = asyncio.get_running_loop()
|
|
131
131
|
# Check if we've already patched this loop
|
|
132
|
-
if not hasattr(loop, "
|
|
132
|
+
if not hasattr(loop, "_panpath_az_cleanup_registered"):
|
|
133
133
|
_register_loop_cleanup(loop)
|
|
134
|
-
loop.
|
|
134
|
+
loop._panpath_az_cleanup_registered = True # type: ignore
|
|
135
135
|
except RuntimeError: # pragma: no cover
|
|
136
136
|
# No running loop, cleanup will be handled by explicit close
|
|
137
137
|
pass
|
|
@@ -788,20 +788,60 @@ class AzureAsyncFileHandle(AsyncFileHandle):
|
|
|
788
788
|
self._read_residue = self._read_residue[size:]
|
|
789
789
|
return result # type: ignore[no-any-return]
|
|
790
790
|
|
|
791
|
-
async def
|
|
792
|
-
"""
|
|
793
|
-
|
|
791
|
+
async def _upload(self, data: Union[str, bytes]) -> None:
|
|
792
|
+
"""Upload data to Azure blob using append semantics.
|
|
793
|
+
|
|
794
|
+
This method uses Azure append blobs for efficient appending.
|
|
795
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
796
|
+
For 'a' mode, it always appends.
|
|
797
|
+
|
|
798
|
+
Args:
|
|
799
|
+
data: Data to upload
|
|
800
|
+
(will be appended to existing content after first write)
|
|
801
|
+
"""
|
|
802
|
+
if isinstance(data, str):
|
|
803
|
+
data = data.encode(self._encoding)
|
|
804
|
+
|
|
805
|
+
blob_client = self._client.get_blob_client( # type: ignore[union-attr]
|
|
794
806
|
self._bucket, self._blob
|
|
795
|
-
)
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
# For 'w' mode on first write, overwrite existing content
|
|
810
|
+
if self._first_write and not self._is_append:
|
|
811
|
+
self._first_write = False
|
|
812
|
+
# Simple overwrite
|
|
813
|
+
await blob_client.upload_blob(data, overwrite=True)
|
|
814
|
+
return
|
|
815
|
+
|
|
816
|
+
from azure.storage.blob import BlobType # type: ignore[import-not-found]
|
|
817
|
+
|
|
818
|
+
self._first_write = False
|
|
819
|
+
|
|
820
|
+
# For subsequent writes or 'a' mode, use append semantics
|
|
821
|
+
# Check if blob exists and its type
|
|
822
|
+
try:
|
|
823
|
+
properties = await blob_client.get_blob_properties()
|
|
824
|
+
blob_exists = True
|
|
825
|
+
blob_type = properties.blob_type
|
|
826
|
+
except ResourceNotFoundError:
|
|
827
|
+
blob_exists = False
|
|
828
|
+
blob_type = None
|
|
829
|
+
|
|
830
|
+
if not blob_exists:
|
|
831
|
+
# Create new append blob
|
|
832
|
+
await blob_client.upload_blob(data, blob_type=BlobType.AppendBlob)
|
|
833
|
+
elif blob_type == "AppendBlob":
|
|
834
|
+
# Append to existing append blob
|
|
835
|
+
await blob_client.append_block(data)
|
|
799
836
|
else:
|
|
800
|
-
|
|
837
|
+
# Convert block blob to append blob by reading, then creating append blob
|
|
838
|
+
existing_data = await blob_client.download_blob()
|
|
839
|
+
existing_content = await existing_data.readall()
|
|
801
840
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
841
|
+
# Delete the old block blob
|
|
842
|
+
await blob_client.delete_blob()
|
|
843
|
+
|
|
844
|
+
# Create new append blob with combined content
|
|
845
|
+
await blob_client.upload_blob(
|
|
846
|
+
existing_content + data, blob_type=BlobType.AppendBlob
|
|
847
|
+
)
|
|
@@ -637,15 +637,58 @@ class AzureSyncFileHandle(SyncFileHandle):
|
|
|
637
637
|
self._read_residue = self._read_residue[size:]
|
|
638
638
|
return result # type: ignore[no-any-return]
|
|
639
639
|
|
|
640
|
-
def
|
|
641
|
-
"""
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
640
|
+
def _upload(self, data: Union[str, bytes]) -> None:
|
|
641
|
+
"""Upload data to Azure blob using append semantics.
|
|
642
|
+
|
|
643
|
+
This method uses Azure append blobs for efficient appending.
|
|
644
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
645
|
+
For 'a' mode, it always appends.
|
|
646
|
+
|
|
647
|
+
Args:
|
|
648
|
+
data: Data to upload
|
|
649
|
+
(will be appended to existing content after first write)
|
|
650
|
+
"""
|
|
651
|
+
if isinstance(data, str):
|
|
652
|
+
data = data.encode(self._encoding)
|
|
653
|
+
|
|
654
|
+
blob_client = self._client.get_blob_client(self._bucket, self._blob)
|
|
655
|
+
|
|
656
|
+
# For 'w' mode on first write, overwrite existing content
|
|
657
|
+
if self._first_write and not self._is_append:
|
|
658
|
+
self._first_write = False
|
|
659
|
+
# Simple overwrite
|
|
660
|
+
blob_client.upload_blob(data, overwrite=True)
|
|
661
|
+
return
|
|
662
|
+
|
|
663
|
+
self._first_write = False
|
|
664
|
+
|
|
665
|
+
# For subsequent writes or 'a' mode, use append semantics
|
|
666
|
+
# Check if blob exists and its type
|
|
667
|
+
try:
|
|
668
|
+
properties = blob_client.get_blob_properties()
|
|
669
|
+
blob_exists = True
|
|
670
|
+
blob_type = properties.blob_type
|
|
671
|
+
except ResourceNotFoundError:
|
|
672
|
+
blob_exists = False
|
|
673
|
+
blob_type = None
|
|
674
|
+
|
|
675
|
+
if not blob_exists:
|
|
676
|
+
# Create new append blob
|
|
677
|
+
from azure.storage.blob import BlobType
|
|
678
|
+
|
|
679
|
+
blob_client.upload_blob(data, blob_type=BlobType.AppendBlob)
|
|
680
|
+
elif blob_type == "AppendBlob":
|
|
681
|
+
# Append to existing append blob
|
|
682
|
+
blob_client.append_block(data)
|
|
646
683
|
else:
|
|
647
|
-
|
|
684
|
+
# Convert block blob to append blob by reading, then creating append blob
|
|
685
|
+
existing_data = blob_client.download_blob()
|
|
686
|
+
existing_content = existing_data.readall()
|
|
648
687
|
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
688
|
+
# Delete the old block blob
|
|
689
|
+
blob_client.delete_blob()
|
|
690
|
+
|
|
691
|
+
# Create new append blob with combined content
|
|
692
|
+
from azure.storage.blob import BlobType
|
|
693
|
+
|
|
694
|
+
blob_client.upload_blob(existing_content + data, blob_type=BlobType.AppendBlob)
|
|
@@ -214,7 +214,7 @@ class PanPath(PathlibPath):
|
|
|
214
214
|
"""
|
|
215
215
|
|
|
216
216
|
@abstractmethod
|
|
217
|
-
async def a_stat(self) -> os.stat_result:
|
|
217
|
+
async def a_stat(self, follow_symlinks: bool = True) -> os.stat_result:
|
|
218
218
|
"""Asynchronously get the file or directory's status information.
|
|
219
219
|
|
|
220
220
|
Returns:
|
|
@@ -14,6 +14,7 @@ from typing import (
|
|
|
14
14
|
)
|
|
15
15
|
|
|
16
16
|
import re
|
|
17
|
+
import warnings
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class Client(ABC):
|
|
@@ -366,6 +367,7 @@ class AsyncFileHandle(ABC):
|
|
|
366
367
|
mode: str = "r",
|
|
367
368
|
encoding: Optional[str] = None,
|
|
368
369
|
chunk_size: int = 4096,
|
|
370
|
+
upload_warning_threshold: int = 100,
|
|
369
371
|
):
|
|
370
372
|
"""Initialize async file handle.
|
|
371
373
|
|
|
@@ -377,6 +379,8 @@ class AsyncFileHandle(ABC):
|
|
|
377
379
|
mode: File mode ('r', 'w', 'rb', 'wb', etc.)
|
|
378
380
|
encoding: Text encoding (for text modes)
|
|
379
381
|
chunk_size: Size of chunks to read
|
|
382
|
+
upload_warning_threshold: Number of chunk uploads before warning (default: 100)
|
|
383
|
+
-1 to disable warning
|
|
380
384
|
"""
|
|
381
385
|
self._client_factory = client_factory
|
|
382
386
|
self._client: Optional[AsyncClient] = None
|
|
@@ -387,6 +391,9 @@ class AsyncFileHandle(ABC):
|
|
|
387
391
|
self._encoding = encoding or "utf-8"
|
|
388
392
|
self._chunk_size = chunk_size
|
|
389
393
|
self._closed = False
|
|
394
|
+
self._upload_warning_threshold = upload_warning_threshold
|
|
395
|
+
self._upload_count = 0
|
|
396
|
+
self._first_write = True # Track if this is the first write (for 'w' mode clearing)
|
|
390
397
|
|
|
391
398
|
# For write modes
|
|
392
399
|
self._write_buffer: Union[bytearray, List[str]] = bytearray() if "b" in mode else []
|
|
@@ -425,37 +432,22 @@ class AsyncFileHandle(ABC):
|
|
|
425
432
|
else:
|
|
426
433
|
return chunk.decode(self._encoding) # type: ignore
|
|
427
434
|
|
|
428
|
-
async def _stream_read_all(self) -> Union[str, bytes]:
|
|
429
|
-
"""Read all data from stream (used internally)."""
|
|
430
|
-
if self._stream is None: # pragma: no cover
|
|
431
|
-
raise ValueError("Stream not initialized")
|
|
432
|
-
chunk = await self._stream.read()
|
|
433
|
-
if self._is_binary:
|
|
434
|
-
return chunk # type: ignore
|
|
435
|
-
else:
|
|
436
|
-
return chunk.decode(self._encoding) # type: ignore
|
|
437
|
-
|
|
438
|
-
# async def _stream_read_all(self) -> Union[str, bytes]:
|
|
439
|
-
# """Read all remaining data from the underlying stream."""
|
|
440
|
-
# chunks = []
|
|
441
|
-
# while True:
|
|
442
|
-
# chunk = await self._stream_read(self._chunk_size)
|
|
443
|
-
# if not chunk:
|
|
444
|
-
# break
|
|
445
|
-
# chunks.append(chunk)
|
|
446
|
-
# if self._is_binary:
|
|
447
|
-
# return b"".join(chunks)
|
|
448
|
-
# else:
|
|
449
|
-
# return "".join(chunks)
|
|
450
|
-
|
|
451
435
|
async def flush(self) -> None:
|
|
452
|
-
"""Flush write buffer
|
|
436
|
+
"""Flush write buffer to cloud storage.
|
|
437
|
+
|
|
438
|
+
After open, all flushes append to existing content using provider-native
|
|
439
|
+
append operations. The difference between 'w' and 'a' modes is that 'w'
|
|
440
|
+
clears existing content on open, while 'a' preserves it.
|
|
441
|
+
"""
|
|
453
442
|
if self._closed: # pragma: no cover
|
|
454
443
|
raise ValueError("I/O operation on closed file")
|
|
455
444
|
|
|
456
445
|
if not self._is_write: # pragma: no cover
|
|
457
446
|
return
|
|
458
447
|
|
|
448
|
+
if not self._write_buffer and not self._first_write:
|
|
449
|
+
return
|
|
450
|
+
|
|
459
451
|
if self._is_binary:
|
|
460
452
|
data: Union[bytes, str] = bytes(self._write_buffer) # type: ignore
|
|
461
453
|
else:
|
|
@@ -464,6 +456,18 @@ class AsyncFileHandle(ABC):
|
|
|
464
456
|
await self._upload(data)
|
|
465
457
|
self._write_buffer = bytearray() if self._is_binary else []
|
|
466
458
|
|
|
459
|
+
# Track upload count and warn if threshold exceeded
|
|
460
|
+
self._upload_count += 1
|
|
461
|
+
if self._upload_count == self._upload_warning_threshold:
|
|
462
|
+
warnings.warn(
|
|
463
|
+
f"File handle has flushed {self._upload_count} times. "
|
|
464
|
+
"Consider using larger chunk_size or buffering writes to reduce "
|
|
465
|
+
"cloud API calls. Set upload_warning_threshold=-1 to suppress "
|
|
466
|
+
"this warning.",
|
|
467
|
+
ResourceWarning,
|
|
468
|
+
stacklevel=2,
|
|
469
|
+
)
|
|
470
|
+
|
|
467
471
|
async def reset_stream(self) -> None:
|
|
468
472
|
"""Reset the underlying stream to the beginning."""
|
|
469
473
|
self._stream = await self._create_stream()
|
|
@@ -485,20 +489,10 @@ class AsyncFileHandle(ABC):
|
|
|
485
489
|
) from None
|
|
486
490
|
else: # pragma: no cover
|
|
487
491
|
raise
|
|
488
|
-
elif self._is_append:
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
if self._is_binary:
|
|
493
|
-
self._write_buffer = bytearray(existing) # type: ignore
|
|
494
|
-
else:
|
|
495
|
-
self._write_buffer = [existing] # type: ignore
|
|
496
|
-
except Exception as e:
|
|
497
|
-
if self.__class__._expception_as_filenotfound(e):
|
|
498
|
-
# File does not exist, start with empty buffer
|
|
499
|
-
pass
|
|
500
|
-
else: # pragma: no cover
|
|
501
|
-
raise
|
|
492
|
+
elif self._is_write and not self._is_append:
|
|
493
|
+
# 'w' mode: clear existing content - do nothing here, will create on first write
|
|
494
|
+
# The difference is that subsequent flushes will append
|
|
495
|
+
pass
|
|
502
496
|
return self
|
|
503
497
|
|
|
504
498
|
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
@@ -526,7 +520,7 @@ class AsyncFileHandle(ABC):
|
|
|
526
520
|
# Return all buffered data plus rest of stream
|
|
527
521
|
buffered = self._read_buffer
|
|
528
522
|
self._read_buffer = b"" if self._is_binary else ""
|
|
529
|
-
rest = await self._stream_read(-1)
|
|
523
|
+
rest = await self._stream_read(-1)
|
|
530
524
|
self._read_pos += len(rest)
|
|
531
525
|
self._eof = True
|
|
532
526
|
result: Union[str, bytes] = buffered + rest # type: ignore
|
|
@@ -552,7 +546,6 @@ class AsyncFileHandle(ABC):
|
|
|
552
546
|
|
|
553
547
|
# No buffered data, read from stream
|
|
554
548
|
if size == -1:
|
|
555
|
-
# Use _stream_read with -1, not _stream_read_all
|
|
556
549
|
result_stream = await self._stream_read(-1)
|
|
557
550
|
self._read_pos += len(result_stream)
|
|
558
551
|
self._eof = True
|
|
@@ -633,6 +626,9 @@ class AsyncFileHandle(ABC):
|
|
|
633
626
|
data = data.decode(self._encoding)
|
|
634
627
|
self._write_buffer.append(data) # type: ignore
|
|
635
628
|
|
|
629
|
+
if len(self._write_buffer) >= self._chunk_size:
|
|
630
|
+
await self.flush()
|
|
631
|
+
|
|
636
632
|
return len(data)
|
|
637
633
|
|
|
638
634
|
async def writelines(self, lines: List[Union[str, bytes]]) -> None:
|
|
@@ -766,17 +762,19 @@ class SyncFileHandle(ABC):
|
|
|
766
762
|
mode: str = "r",
|
|
767
763
|
encoding: Optional[str] = None,
|
|
768
764
|
chunk_size: int = 4096,
|
|
765
|
+
upload_warning_threshold: int = 100,
|
|
769
766
|
):
|
|
770
|
-
"""Initialize
|
|
767
|
+
"""Initialize sync file handle.
|
|
771
768
|
|
|
772
769
|
Args:
|
|
773
|
-
|
|
770
|
+
client: Sync client for cloud operations
|
|
774
771
|
bucket: Cloud storage bucket name or container
|
|
775
772
|
blob: Cloud storage blob name or object key
|
|
776
773
|
prefix: Cloud storage path prefix
|
|
777
774
|
mode: File mode ('r', 'w', 'rb', 'wb', etc.)
|
|
778
775
|
encoding: Text encoding (for text modes)
|
|
779
776
|
chunk_size: Size of chunks to read
|
|
777
|
+
upload_warning_threshold: Number of chunk uploads before warning (default: 100)
|
|
780
778
|
"""
|
|
781
779
|
self._client = client
|
|
782
780
|
self._bucket = bucket
|
|
@@ -786,6 +784,9 @@ class SyncFileHandle(ABC):
|
|
|
786
784
|
self._encoding = encoding or "utf-8"
|
|
787
785
|
self._chunk_size = chunk_size
|
|
788
786
|
self._closed = False
|
|
787
|
+
self._upload_warning_threshold = upload_warning_threshold
|
|
788
|
+
self._upload_count = 0
|
|
789
|
+
self._first_write = True # Track if this is the first write (for 'w' mode clearing)
|
|
789
790
|
|
|
790
791
|
# For write modes
|
|
791
792
|
self._write_buffer: Union[bytearray, List[str]] = bytearray() if "b" in mode else []
|
|
@@ -815,13 +816,21 @@ class SyncFileHandle(ABC):
|
|
|
815
816
|
"""Upload data to cloud storage (used internally)."""
|
|
816
817
|
|
|
817
818
|
def flush(self) -> None:
|
|
818
|
-
"""Flush write buffer
|
|
819
|
+
"""Flush write buffer to cloud storage.
|
|
820
|
+
|
|
821
|
+
After open, all flushes append to existing content using provider-native
|
|
822
|
+
append operations. The difference between 'w' and 'a' modes is that 'w'
|
|
823
|
+
clears existing content on open, while 'a' preserves it.
|
|
824
|
+
"""
|
|
819
825
|
if self._closed: # pragma: no cover
|
|
820
826
|
raise ValueError("I/O operation on closed file")
|
|
821
827
|
|
|
822
828
|
if not self._is_write: # pragma: no cover
|
|
823
829
|
return
|
|
824
830
|
|
|
831
|
+
if not self._write_buffer and not self._first_write:
|
|
832
|
+
return
|
|
833
|
+
|
|
825
834
|
if self._is_binary:
|
|
826
835
|
data = bytes(self._write_buffer) # type: ignore
|
|
827
836
|
else:
|
|
@@ -830,6 +839,17 @@ class SyncFileHandle(ABC):
|
|
|
830
839
|
self._upload(data)
|
|
831
840
|
self._write_buffer = bytearray() if self._is_binary else []
|
|
832
841
|
|
|
842
|
+
# Track upload count and warn if threshold exceeded
|
|
843
|
+
self._upload_count += 1
|
|
844
|
+
if self._upload_count == self._upload_warning_threshold:
|
|
845
|
+
warnings.warn(
|
|
846
|
+
f"File handle has flushed {self._upload_count} times. Consider using larger "
|
|
847
|
+
f"chunk_size or buffering writes to reduce cloud API calls. "
|
|
848
|
+
f"Set upload_warning_threshold=-1 to suppress this warning.",
|
|
849
|
+
ResourceWarning,
|
|
850
|
+
stacklevel=2,
|
|
851
|
+
)
|
|
852
|
+
|
|
833
853
|
def _stream_read(self, size: int = -1) -> Union[str, bytes]:
|
|
834
854
|
"""Read from stream (used internally)."""
|
|
835
855
|
# Python 3.9 compatibility: http.client.HTTPResponse.read() doesn't accept -1
|
|
@@ -850,32 +870,6 @@ class SyncFileHandle(ABC):
|
|
|
850
870
|
else:
|
|
851
871
|
return chunk.decode(self._encoding) # type: ignore
|
|
852
872
|
|
|
853
|
-
def _stream_read_all(self) -> Union[str, bytes]:
|
|
854
|
-
"""Read all data from stream (used internally).
|
|
855
|
-
Suppose self._stream.read() reads all remaining data.
|
|
856
|
-
If not, this method should be overridden in subclasses.
|
|
857
|
-
"""
|
|
858
|
-
if self._stream is None: # pragma: no cover
|
|
859
|
-
raise ValueError("Stream not initialized")
|
|
860
|
-
chunk = self._stream.read()
|
|
861
|
-
if self._is_binary:
|
|
862
|
-
return chunk # type: ignore
|
|
863
|
-
else:
|
|
864
|
-
return chunk.decode(self._encoding) # type: ignore
|
|
865
|
-
|
|
866
|
-
# def _stream_read_all(self) -> Union[str, bytes]:
|
|
867
|
-
# """Read all remaining data from the underlying stream."""
|
|
868
|
-
# chunks = []
|
|
869
|
-
# while True:
|
|
870
|
-
# chunk = self._stream_read(self._chunk_size)
|
|
871
|
-
# if not chunk:
|
|
872
|
-
# break
|
|
873
|
-
# chunks.append(chunk)
|
|
874
|
-
# if self._is_binary:
|
|
875
|
-
# return b"".join(chunks)
|
|
876
|
-
# else:
|
|
877
|
-
# return "".join(chunks)
|
|
878
|
-
|
|
879
873
|
def reset_stream(self) -> None:
|
|
880
874
|
"""Reset the underlying stream to the beginning."""
|
|
881
875
|
self._stream = self._create_stream()
|
|
@@ -884,7 +878,7 @@ class SyncFileHandle(ABC):
|
|
|
884
878
|
self._eof = False
|
|
885
879
|
|
|
886
880
|
def __enter__(self) -> "SyncFileHandle":
|
|
887
|
-
"""Enter
|
|
881
|
+
"""Enter context manager."""
|
|
888
882
|
if self._is_read:
|
|
889
883
|
try:
|
|
890
884
|
self._stream = self._create_stream()
|
|
@@ -895,20 +889,11 @@ class SyncFileHandle(ABC):
|
|
|
895
889
|
) from None
|
|
896
890
|
else: # pragma: no cover
|
|
897
891
|
raise
|
|
898
|
-
elif self._is_append:
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
self._write_buffer = bytearray(existing) # type: ignore
|
|
904
|
-
else:
|
|
905
|
-
self._write_buffer = [existing] # type: ignore
|
|
906
|
-
except Exception as e:
|
|
907
|
-
if self.__class__._expception_as_filenotfound(e):
|
|
908
|
-
# File does not exist, start with empty buffer
|
|
909
|
-
pass
|
|
910
|
-
else: # pragma: no cover
|
|
911
|
-
raise
|
|
892
|
+
elif self._is_write and not self._is_append:
|
|
893
|
+
# 'w' mode: clear existing content - do nothing here, will create on
|
|
894
|
+
# first write
|
|
895
|
+
# The difference is that subsequent flushes will append
|
|
896
|
+
pass
|
|
912
897
|
return self
|
|
913
898
|
|
|
914
899
|
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
@@ -932,7 +917,7 @@ class SyncFileHandle(ABC):
|
|
|
932
917
|
|
|
933
918
|
# No buffered data, read from stream
|
|
934
919
|
if size == -1:
|
|
935
|
-
result = self._stream_read(-1)
|
|
920
|
+
result = self._stream_read(-1)
|
|
936
921
|
self._read_pos += len(result)
|
|
937
922
|
self._eof = True
|
|
938
923
|
return result
|
|
@@ -1012,6 +997,9 @@ class SyncFileHandle(ABC):
|
|
|
1012
997
|
data = data.decode(self._encoding)
|
|
1013
998
|
self._write_buffer.append(data) # type: ignore
|
|
1014
999
|
|
|
1000
|
+
if len(self._write_buffer) >= self._chunk_size:
|
|
1001
|
+
self.flush()
|
|
1002
|
+
|
|
1015
1003
|
return len(data)
|
|
1016
1004
|
|
|
1017
1005
|
def writelines(self, lines: List[Union[str, bytes]]) -> None:
|
|
@@ -191,8 +191,12 @@ class CloudPath(PanPath, PurePosixPath, ABC):
|
|
|
191
191
|
"""Check if path is a file."""
|
|
192
192
|
return self.client.is_file(str(self))
|
|
193
193
|
|
|
194
|
-
def stat(self) -> Any:
|
|
194
|
+
def stat(self, follow_symlinks: bool = True) -> Any:
|
|
195
195
|
"""Get file stats."""
|
|
196
|
+
if follow_symlinks and self.is_symlink():
|
|
197
|
+
target = self.readlink()
|
|
198
|
+
return target.stat()
|
|
199
|
+
|
|
196
200
|
return self.client.stat(str(self))
|
|
197
201
|
|
|
198
202
|
def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
|
|
@@ -378,7 +382,11 @@ class CloudPath(PanPath, PurePosixPath, ABC):
|
|
|
378
382
|
"""
|
|
379
383
|
target = self.client.readlink(str(self))
|
|
380
384
|
|
|
381
|
-
return PanPath(
|
|
385
|
+
return PanPath( # type: ignore
|
|
386
|
+
target,
|
|
387
|
+
client=self._client,
|
|
388
|
+
async_client=self._async_client,
|
|
389
|
+
)
|
|
382
390
|
|
|
383
391
|
def symlink_to(self, target: Union[str, "CloudPath"]) -> None: # type: ignore[override]
|
|
384
392
|
"""Create symlink pointing to target (via metadata).
|
|
@@ -558,8 +566,12 @@ class CloudPath(PanPath, PurePosixPath, ABC):
|
|
|
558
566
|
"""Check if path is a file."""
|
|
559
567
|
return await self.async_client.is_file(str(self))
|
|
560
568
|
|
|
561
|
-
async def a_stat(self) -> Any:
|
|
569
|
+
async def a_stat(self, follow_symlinks: bool = True) -> Any:
|
|
562
570
|
"""Get file stats."""
|
|
571
|
+
if follow_symlinks and await self.a_is_symlink():
|
|
572
|
+
target = await self.a_readlink()
|
|
573
|
+
return await target.a_stat()
|
|
574
|
+
|
|
563
575
|
return await self.async_client.stat(str(self))
|
|
564
576
|
|
|
565
577
|
async def a_mkdir(
|
|
@@ -735,7 +747,11 @@ class CloudPath(PanPath, PurePosixPath, ABC):
|
|
|
735
747
|
"""
|
|
736
748
|
target = await self.async_client.readlink(str(self))
|
|
737
749
|
|
|
738
|
-
return PanPath(
|
|
750
|
+
return PanPath( # type: ignore
|
|
751
|
+
target,
|
|
752
|
+
client=self._client,
|
|
753
|
+
async_client=self._async_client,
|
|
754
|
+
)
|
|
739
755
|
|
|
740
756
|
async def a_symlink_to( # type: ignore[override]
|
|
741
757
|
self,
|
|
@@ -124,9 +124,9 @@ class AsyncGSClient(AsyncClient):
|
|
|
124
124
|
try:
|
|
125
125
|
loop = asyncio.get_running_loop()
|
|
126
126
|
# Check if we've already patched this loop
|
|
127
|
-
if not hasattr(loop, "
|
|
127
|
+
if not hasattr(loop, "_panpath_gs_cleanup_registered"):
|
|
128
128
|
_register_loop_cleanup(loop)
|
|
129
|
-
loop.
|
|
129
|
+
loop._panpath_gs_cleanup_registered = True # type: ignore
|
|
130
130
|
except RuntimeError: # pragma: no cover
|
|
131
131
|
# No running loop, cleanup will be handled by explicit close
|
|
132
132
|
pass
|
|
@@ -776,9 +776,56 @@ class GSAsyncFileHandle(AsyncFileHandle):
|
|
|
776
776
|
return True
|
|
777
777
|
|
|
778
778
|
async def _upload(self, data: Union[str, bytes]) -> None:
|
|
779
|
-
"""Upload data to GCS blob.
|
|
779
|
+
"""Upload data to GCS blob using append semantics.
|
|
780
|
+
|
|
781
|
+
This method appends data using GCS compose.
|
|
782
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
783
|
+
For 'a' mode, it always appends.
|
|
780
784
|
|
|
781
785
|
Args:
|
|
782
786
|
data: Data to upload
|
|
787
|
+
(will be appended to existing content after first write)
|
|
783
788
|
"""
|
|
784
|
-
|
|
789
|
+
if isinstance(data, str):
|
|
790
|
+
data = data.encode(self._encoding)
|
|
791
|
+
|
|
792
|
+
storage: Storage = self._client # type: ignore[assignment]
|
|
793
|
+
|
|
794
|
+
# For 'w' mode on first write, overwrite existing content
|
|
795
|
+
if self._first_write and not self._is_append:
|
|
796
|
+
self._first_write = False
|
|
797
|
+
# Simple overwrite
|
|
798
|
+
await storage.upload(self._bucket, self._blob, data)
|
|
799
|
+
return
|
|
800
|
+
|
|
801
|
+
self._first_write = False
|
|
802
|
+
|
|
803
|
+
# For subsequent writes or append mode, use compose to append
|
|
804
|
+
# Check if the original blob exists
|
|
805
|
+
try:
|
|
806
|
+
await storage.download_metadata(self._bucket, self._blob)
|
|
807
|
+
blob_exists = True
|
|
808
|
+
except Exception:
|
|
809
|
+
blob_exists = False
|
|
810
|
+
|
|
811
|
+
if not blob_exists:
|
|
812
|
+
# If blob doesn't exist, just upload the new data
|
|
813
|
+
await storage.upload(self._bucket, self._blob, data)
|
|
814
|
+
else:
|
|
815
|
+
# Upload new data to a temporary blob
|
|
816
|
+
temp_blob = f"{self._blob}.tmp.{os.getpid()}"
|
|
817
|
+
await storage.upload(
|
|
818
|
+
self._bucket,
|
|
819
|
+
temp_blob,
|
|
820
|
+
data,
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
# Use compose API to concatenate original + new data
|
|
824
|
+
await storage.compose(
|
|
825
|
+
bucket=self._bucket,
|
|
826
|
+
object_name=self._blob,
|
|
827
|
+
source_object_names=[self._blob, temp_blob],
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
# Clean up the temporary blob
|
|
831
|
+
await storage.delete(self._bucket, temp_blob)
|
|
@@ -590,8 +590,9 @@ class GSSyncFileHandle(SyncFileHandle):
|
|
|
590
590
|
raise FileNotFoundError(f"GCS blob not found: {self._bucket}/{self._blob}")
|
|
591
591
|
|
|
592
592
|
@classmethod
|
|
593
|
-
def _expception_as_filenotfound(cls, exception: Exception) -> bool:
|
|
593
|
+
def _expception_as_filenotfound(cls, exception: Exception) -> bool: # pragma: no cover
|
|
594
594
|
"""Check if exception is GCS NotFound and convert to FileNotFoundError."""
|
|
595
|
+
# FileNotFoundError already raised in __init__
|
|
595
596
|
return isinstance(exception, NotFound)
|
|
596
597
|
|
|
597
598
|
def reset_stream(self) -> None:
|
|
@@ -616,5 +617,45 @@ class GSSyncFileHandle(SyncFileHandle):
|
|
|
616
617
|
return self._blob.open("rb") # type: ignore[no-any-return]
|
|
617
618
|
|
|
618
619
|
def _upload(self, data: Union[bytes, str]) -> None:
|
|
619
|
-
"""
|
|
620
|
-
|
|
620
|
+
"""Upload data to GCS blob using append semantics.
|
|
621
|
+
|
|
622
|
+
This method appends data using GCS compose API.
|
|
623
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
624
|
+
For 'a' mode, it always appends.
|
|
625
|
+
|
|
626
|
+
Args:
|
|
627
|
+
data: Data to upload
|
|
628
|
+
(will be appended to existing content after first write)
|
|
629
|
+
"""
|
|
630
|
+
if isinstance(data, str):
|
|
631
|
+
data = data.encode(self._encoding)
|
|
632
|
+
|
|
633
|
+
# For 'w' mode on first write, overwrite existing content
|
|
634
|
+
if self._first_write and not self._is_append:
|
|
635
|
+
self._first_write = False
|
|
636
|
+
# Simple overwrite
|
|
637
|
+
self._blob.upload_from_string(data)
|
|
638
|
+
return
|
|
639
|
+
|
|
640
|
+
self._first_write = False
|
|
641
|
+
|
|
642
|
+
# For subsequent writes or append mode, use compose to append
|
|
643
|
+
# Check if the original blob exists
|
|
644
|
+
blob_exists = self._blob.exists()
|
|
645
|
+
|
|
646
|
+
if not blob_exists:
|
|
647
|
+
# If blob doesn't exist, just upload the new data
|
|
648
|
+
self._blob.upload_from_string(data)
|
|
649
|
+
else:
|
|
650
|
+
bucket = self._blob.bucket
|
|
651
|
+
temp_blob_name = f"{self._blob.name}.tmp.{os.getpid()}"
|
|
652
|
+
temp_blob = bucket.blob(temp_blob_name)
|
|
653
|
+
|
|
654
|
+
# Upload new data to temp blob
|
|
655
|
+
temp_blob.upload_from_string(data)
|
|
656
|
+
|
|
657
|
+
# Compose: original + temp = original
|
|
658
|
+
self._blob.compose([self._blob, temp_blob])
|
|
659
|
+
|
|
660
|
+
# Clean up temp blob
|
|
661
|
+
temp_blob.delete()
|
|
@@ -470,7 +470,7 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
|
|
|
470
470
|
for item in await aiofiles.os.listdir(str(self)):
|
|
471
471
|
yield self / item
|
|
472
472
|
|
|
473
|
-
async def a_stat(self) -> os.stat_result:
|
|
473
|
+
async def a_stat(self, follow_symlinks: bool = True) -> os.stat_result:
|
|
474
474
|
"""Get file stats (async)."""
|
|
475
475
|
if not HAS_AIOFILES:
|
|
476
476
|
raise MissingDependencyError(
|
|
@@ -479,7 +479,10 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
|
|
|
479
479
|
extra="all-async",
|
|
480
480
|
)
|
|
481
481
|
|
|
482
|
-
return await aiofiles.os.stat(
|
|
482
|
+
return await aiofiles.os.stat( # type: ignore[no-any-return]
|
|
483
|
+
str(self),
|
|
484
|
+
follow_symlinks=follow_symlinks,
|
|
485
|
+
)
|
|
483
486
|
|
|
484
487
|
def a_open( # type: ignore[override]
|
|
485
488
|
self,
|
|
@@ -116,9 +116,9 @@ class AsyncS3Client(AsyncClient):
|
|
|
116
116
|
try:
|
|
117
117
|
loop = asyncio.get_running_loop()
|
|
118
118
|
# Check if we've already patched this loop
|
|
119
|
-
if not hasattr(loop, "
|
|
119
|
+
if not hasattr(loop, "_panpath_s3_cleanup_registered"):
|
|
120
120
|
_register_loop_cleanup(loop)
|
|
121
|
-
loop.
|
|
121
|
+
loop._panpath_s3_cleanup_registered = True # type: ignore
|
|
122
122
|
except RuntimeError: # pragma: no cover
|
|
123
123
|
# No running loop, cleanup will be handled by explicit close
|
|
124
124
|
pass
|
|
@@ -758,7 +758,7 @@ class S3AsyncFileHandle(AsyncFileHandle):
|
|
|
758
758
|
|
|
759
759
|
async def _create_stream(self) -> None:
|
|
760
760
|
"""Create the underlying stream for reading or writing."""
|
|
761
|
-
client = await self._client_factory()
|
|
761
|
+
client: AioBaseClient = await self._client_factory()
|
|
762
762
|
response = await client.get_object(Bucket=self._bucket, Key=self._blob)
|
|
763
763
|
return response["Body"] # type: ignore[no-any-return]
|
|
764
764
|
|
|
@@ -774,9 +774,48 @@ class S3AsyncFileHandle(AsyncFileHandle):
|
|
|
774
774
|
)
|
|
775
775
|
|
|
776
776
|
async def _upload(self, data: Union[str, bytes]) -> None:
|
|
777
|
-
"""
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
777
|
+
"""Upload data to S3 using append semantics.
|
|
778
|
+
|
|
779
|
+
This method appends data using multipart upload.
|
|
780
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
781
|
+
For 'a' mode, it always appends.
|
|
782
|
+
|
|
783
|
+
Args:
|
|
784
|
+
data: Data to upload (will be appended to existing content after first write)
|
|
785
|
+
"""
|
|
786
|
+
if isinstance(data, str):
|
|
787
|
+
data = data.encode(self._encoding)
|
|
788
|
+
|
|
789
|
+
client: AioBaseClient = self._client
|
|
790
|
+
|
|
791
|
+
# For 'w' mode on first write, overwrite existing content
|
|
792
|
+
if self._first_write and not self._is_append:
|
|
793
|
+
self._first_write = False
|
|
794
|
+
# Simple overwrite
|
|
795
|
+
await client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
|
|
796
|
+
return
|
|
797
|
+
|
|
798
|
+
self._first_write = False
|
|
799
|
+
|
|
800
|
+
# For subsequent writes or append mode, use read-modify-write
|
|
801
|
+
# Check if object exists
|
|
802
|
+
try:
|
|
803
|
+
await client.head_object(Bucket=self._bucket, Key=self._blob)
|
|
804
|
+
object_exists = True
|
|
805
|
+
except ClientError as e:
|
|
806
|
+
if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
|
|
807
|
+
object_exists = False
|
|
808
|
+
else: # pragma: no cover
|
|
809
|
+
raise
|
|
810
|
+
|
|
811
|
+
if not object_exists:
|
|
812
|
+
# Simple upload for new objects
|
|
813
|
+
await client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
|
|
814
|
+
else:
|
|
815
|
+
# For existing objects, download, concatenate, and re-upload
|
|
816
|
+
response = await client.get_object(Bucket=self._bucket, Key=self._blob)
|
|
817
|
+
existing_data = await response["Body"].read()
|
|
818
|
+
combined_data = existing_data + data
|
|
819
|
+
await client.put_object(
|
|
820
|
+
Bucket=self._bucket, Key=self._blob, Body=combined_data
|
|
821
|
+
)
|
|
@@ -632,5 +632,47 @@ class S3SyncFileHandle(SyncFileHandle):
|
|
|
632
632
|
return False # pragma: no cover
|
|
633
633
|
|
|
634
634
|
def _upload(self, data: Union[str, bytes]) -> None:
|
|
635
|
-
"""
|
|
636
|
-
|
|
635
|
+
"""Upload data to S3 using append semantics.
|
|
636
|
+
|
|
637
|
+
This method appends data using multipart upload.
|
|
638
|
+
For 'w' mode on first write, it overwrites. Subsequently it appends.
|
|
639
|
+
For 'a' mode, it always appends.
|
|
640
|
+
|
|
641
|
+
Args:
|
|
642
|
+
data: Data to upload
|
|
643
|
+
(will be appended to existing content after first write)
|
|
644
|
+
"""
|
|
645
|
+
if isinstance(data, str):
|
|
646
|
+
data = data.encode(self._encoding)
|
|
647
|
+
|
|
648
|
+
# For 'w' mode on first write, overwrite existing content
|
|
649
|
+
if self._first_write and not self._is_append:
|
|
650
|
+
self._first_write = False
|
|
651
|
+
# Simple overwrite
|
|
652
|
+
self._client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
|
|
653
|
+
return
|
|
654
|
+
|
|
655
|
+
self._first_write = False
|
|
656
|
+
|
|
657
|
+
# For subsequent writes or append mode, use read-modify-write
|
|
658
|
+
# Check if object exists
|
|
659
|
+
try:
|
|
660
|
+
self._client.head_object(Bucket=self._bucket, Key=self._blob)
|
|
661
|
+
object_exists = True
|
|
662
|
+
except ClientError as e:
|
|
663
|
+
if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
|
|
664
|
+
object_exists = False
|
|
665
|
+
else: # pragma: no cover
|
|
666
|
+
raise
|
|
667
|
+
|
|
668
|
+
if not object_exists:
|
|
669
|
+
# Simple upload for new objects
|
|
670
|
+
self._client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
|
|
671
|
+
else:
|
|
672
|
+
# For existing objects, download, concatenate, and re-upload
|
|
673
|
+
response = self._client.get_object(Bucket=self._bucket, Key=self._blob)
|
|
674
|
+
existing_data = response["Body"].read()
|
|
675
|
+
combined_data = existing_data + data
|
|
676
|
+
self._client.put_object(
|
|
677
|
+
Bucket=self._bucket, Key=self._blob, Body=combined_data
|
|
678
|
+
)
|
|
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
|
|
|
4
4
|
|
|
5
5
|
[tool.poetry]
|
|
6
6
|
name = "panpath"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.6"
|
|
8
8
|
description = "Universal sync/async local/cloud path library with pathlib-compatible interface"
|
|
9
9
|
authors = ["panpath contributors"]
|
|
10
10
|
readme = "README.md"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|