panpath 0.4.5__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: panpath
3
- Version: 0.4.5
3
+ Version: 0.4.6
4
4
  Summary: Universal sync/async local/cloud path library with pathlib-compatible interface
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -56,7 +56,7 @@ except ImportError:
56
56
  # Azure dependencies not installed
57
57
  pass
58
58
 
59
- __version__ = "0.4.5"
59
+ __version__ = "0.4.6"
60
60
 
61
61
  __all__ = [
62
62
  "PanPath",
@@ -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, "_panpath_cleanup_registered"):
132
+ if not hasattr(loop, "_panpath_az_cleanup_registered"):
133
133
  _register_loop_cleanup(loop)
134
- loop._panpath_cleanup_registered = True # type: ignore
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 _stream_read_all(self) -> Union[str, bytes]:
792
- """Read all remaining data from stream."""
793
- download_stream = await self._client.get_blob_client( # type: ignore[union-attr]
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
- ).download_blob()
796
- data = await download_stream.readall()
797
- if self._is_binary:
798
- return data # type: ignore[no-any-return]
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
- return data.decode(self._encoding) # type: ignore[no-any-return]
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
- async def _upload(self, data: Union[str, bytes]) -> None:
803
- """Flush write buffer to Azure blob."""
804
- await self._client.get_blob_client( # type: ignore[union-attr]
805
- self._bucket,
806
- self._blob,
807
- ).upload_blob(data, overwrite=True)
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 _stream_read_all(self) -> Union[str, bytes]:
641
- """Read all remaining data from stream."""
642
- download_stream = self._client.get_blob_client(self._bucket, self._blob).download_blob()
643
- data = download_stream.readall()
644
- if self._is_binary:
645
- return data # type: ignore[no-any-return]
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
- return data.decode(self._encoding) # type: ignore[no-any-return]
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
- def _upload(self, data: Union[str, bytes]) -> None:
650
- """Flush write buffer to Azure blob."""
651
- self._client.get_blob_client(self._bucket, self._blob).upload_blob(data, overwrite=True)
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)
@@ -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,34 +432,12 @@ 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 (optional, default implementation is no-op).
436
+ """Flush write buffer to cloud storage.
453
437
 
454
- Note latter flush will overwrite previous data in cloud storage.
455
- Incremental flush is not supported in this base implementation.
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.
456
441
  """
457
442
  if self._closed: # pragma: no cover
458
443
  raise ValueError("I/O operation on closed file")
@@ -460,6 +445,9 @@ class AsyncFileHandle(ABC):
460
445
  if not self._is_write: # pragma: no cover
461
446
  return
462
447
 
448
+ if not self._write_buffer and not self._first_write:
449
+ return
450
+
463
451
  if self._is_binary:
464
452
  data: Union[bytes, str] = bytes(self._write_buffer) # type: ignore
465
453
  else:
@@ -468,6 +456,18 @@ class AsyncFileHandle(ABC):
468
456
  await self._upload(data)
469
457
  self._write_buffer = bytearray() if self._is_binary else []
470
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
+
471
471
  async def reset_stream(self) -> None:
472
472
  """Reset the underlying stream to the beginning."""
473
473
  self._stream = await self._create_stream()
@@ -489,20 +489,10 @@ class AsyncFileHandle(ABC):
489
489
  ) from None
490
490
  else: # pragma: no cover
491
491
  raise
492
- elif self._is_append:
493
- try:
494
- self._stream = await self._create_stream()
495
- existing = await self._stream_read_all()
496
- if self._is_binary:
497
- self._write_buffer = bytearray(existing) # type: ignore
498
- else:
499
- self._write_buffer = [existing] # type: ignore
500
- except Exception as e:
501
- if self.__class__._expception_as_filenotfound(e):
502
- # File does not exist, start with empty buffer
503
- pass
504
- else: # pragma: no cover
505
- 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
506
496
  return self
507
497
 
508
498
  async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
@@ -530,7 +520,7 @@ class AsyncFileHandle(ABC):
530
520
  # Return all buffered data plus rest of stream
531
521
  buffered = self._read_buffer
532
522
  self._read_buffer = b"" if self._is_binary else ""
533
- rest = await self._stream_read(-1) # Use _stream_read with -1, not _stream_read_all
523
+ rest = await self._stream_read(-1)
534
524
  self._read_pos += len(rest)
535
525
  self._eof = True
536
526
  result: Union[str, bytes] = buffered + rest # type: ignore
@@ -556,7 +546,6 @@ class AsyncFileHandle(ABC):
556
546
 
557
547
  # No buffered data, read from stream
558
548
  if size == -1:
559
- # Use _stream_read with -1, not _stream_read_all
560
549
  result_stream = await self._stream_read(-1)
561
550
  self._read_pos += len(result_stream)
562
551
  self._eof = True
@@ -637,6 +626,9 @@ class AsyncFileHandle(ABC):
637
626
  data = data.decode(self._encoding)
638
627
  self._write_buffer.append(data) # type: ignore
639
628
 
629
+ if len(self._write_buffer) >= self._chunk_size:
630
+ await self.flush()
631
+
640
632
  return len(data)
641
633
 
642
634
  async def writelines(self, lines: List[Union[str, bytes]]) -> None:
@@ -770,17 +762,19 @@ class SyncFileHandle(ABC):
770
762
  mode: str = "r",
771
763
  encoding: Optional[str] = None,
772
764
  chunk_size: int = 4096,
765
+ upload_warning_threshold: int = 100,
773
766
  ):
774
- """Initialize async file handle.
767
+ """Initialize sync file handle.
775
768
 
776
769
  Args:
777
- client_factor: Async client factory for cloud operations
770
+ client: Sync client for cloud operations
778
771
  bucket: Cloud storage bucket name or container
779
772
  blob: Cloud storage blob name or object key
780
773
  prefix: Cloud storage path prefix
781
774
  mode: File mode ('r', 'w', 'rb', 'wb', etc.)
782
775
  encoding: Text encoding (for text modes)
783
776
  chunk_size: Size of chunks to read
777
+ upload_warning_threshold: Number of chunk uploads before warning (default: 100)
784
778
  """
785
779
  self._client = client
786
780
  self._bucket = bucket
@@ -790,6 +784,9 @@ class SyncFileHandle(ABC):
790
784
  self._encoding = encoding or "utf-8"
791
785
  self._chunk_size = chunk_size
792
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)
793
790
 
794
791
  # For write modes
795
792
  self._write_buffer: Union[bytearray, List[str]] = bytearray() if "b" in mode else []
@@ -819,13 +816,21 @@ class SyncFileHandle(ABC):
819
816
  """Upload data to cloud storage (used internally)."""
820
817
 
821
818
  def flush(self) -> None:
822
- """Flush write buffer (optional, default implementation is no-op)."""
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
+ """
823
825
  if self._closed: # pragma: no cover
824
826
  raise ValueError("I/O operation on closed file")
825
827
 
826
828
  if not self._is_write: # pragma: no cover
827
829
  return
828
830
 
831
+ if not self._write_buffer and not self._first_write:
832
+ return
833
+
829
834
  if self._is_binary:
830
835
  data = bytes(self._write_buffer) # type: ignore
831
836
  else:
@@ -834,6 +839,17 @@ class SyncFileHandle(ABC):
834
839
  self._upload(data)
835
840
  self._write_buffer = bytearray() if self._is_binary else []
836
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
+
837
853
  def _stream_read(self, size: int = -1) -> Union[str, bytes]:
838
854
  """Read from stream (used internally)."""
839
855
  # Python 3.9 compatibility: http.client.HTTPResponse.read() doesn't accept -1
@@ -854,32 +870,6 @@ class SyncFileHandle(ABC):
854
870
  else:
855
871
  return chunk.decode(self._encoding) # type: ignore
856
872
 
857
- def _stream_read_all(self) -> Union[str, bytes]:
858
- """Read all data from stream (used internally).
859
- Suppose self._stream.read() reads all remaining data.
860
- If not, this method should be overridden in subclasses.
861
- """
862
- if self._stream is None: # pragma: no cover
863
- raise ValueError("Stream not initialized")
864
- chunk = self._stream.read()
865
- if self._is_binary:
866
- return chunk # type: ignore
867
- else:
868
- return chunk.decode(self._encoding) # type: ignore
869
-
870
- # def _stream_read_all(self) -> Union[str, bytes]:
871
- # """Read all remaining data from the underlying stream."""
872
- # chunks = []
873
- # while True:
874
- # chunk = self._stream_read(self._chunk_size)
875
- # if not chunk:
876
- # break
877
- # chunks.append(chunk)
878
- # if self._is_binary:
879
- # return b"".join(chunks)
880
- # else:
881
- # return "".join(chunks)
882
-
883
873
  def reset_stream(self) -> None:
884
874
  """Reset the underlying stream to the beginning."""
885
875
  self._stream = self._create_stream()
@@ -888,7 +878,7 @@ class SyncFileHandle(ABC):
888
878
  self._eof = False
889
879
 
890
880
  def __enter__(self) -> "SyncFileHandle":
891
- """Enter async context manager."""
881
+ """Enter context manager."""
892
882
  if self._is_read:
893
883
  try:
894
884
  self._stream = self._create_stream()
@@ -899,20 +889,11 @@ class SyncFileHandle(ABC):
899
889
  ) from None
900
890
  else: # pragma: no cover
901
891
  raise
902
- elif self._is_append:
903
- try:
904
- self._stream = self._create_stream()
905
- existing = self._stream_read_all()
906
- if self._is_binary:
907
- self._write_buffer = bytearray(existing) # type: ignore
908
- else:
909
- self._write_buffer = [existing] # type: ignore
910
- except Exception as e:
911
- if self.__class__._expception_as_filenotfound(e):
912
- # File does not exist, start with empty buffer
913
- pass
914
- else: # pragma: no cover
915
- 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
916
897
  return self
917
898
 
918
899
  def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
@@ -936,7 +917,7 @@ class SyncFileHandle(ABC):
936
917
 
937
918
  # No buffered data, read from stream
938
919
  if size == -1:
939
- result = self._stream_read(-1) # Use _stream_read with -1, not _stream_read_all
920
+ result = self._stream_read(-1)
940
921
  self._read_pos += len(result)
941
922
  self._eof = True
942
923
  return result
@@ -1016,6 +997,9 @@ class SyncFileHandle(ABC):
1016
997
  data = data.decode(self._encoding)
1017
998
  self._write_buffer.append(data) # type: ignore
1018
999
 
1000
+ if len(self._write_buffer) >= self._chunk_size:
1001
+ self.flush()
1002
+
1019
1003
  return len(data)
1020
1004
 
1021
1005
  def writelines(self, lines: List[Union[str, bytes]]) -> None:
@@ -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, "_panpath_cleanup_registered"):
127
+ if not hasattr(loop, "_panpath_gs_cleanup_registered"):
128
128
  _register_loop_cleanup(loop)
129
- loop._panpath_cleanup_registered = True # type: ignore
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
- await self._client.upload(self._bucket, self._blob, data) # type: ignore[union-attr]
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
- """Flush buffered writes to GCS."""
620
- self._blob.upload_from_string(data)
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()
@@ -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, "_panpath_cleanup_registered"):
119
+ if not hasattr(loop, "_panpath_s3_cleanup_registered"):
120
120
  _register_loop_cleanup(loop)
121
- loop._panpath_cleanup_registered = True # type: ignore
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
- """Flush write buffer to S3 (no-op for S3)."""
778
- await self._client.put_object( # type: ignore[union-attr]
779
- Bucket=self._bucket,
780
- Key=self._blob,
781
- Body=data,
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
- """Flush write buffer to S3 (no-op for S3)."""
636
- self._client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
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.5"
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
File without changes
File without changes
File without changes