panpath 0.4.5__tar.gz → 0.4.7__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.7
4
4
  Summary: Universal sync/async local/cloud path library with pathlib-compatible interface
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -32,7 +32,7 @@ Requires-Dist: aioboto3 (>=11.0.0) ; extra == "async-s3" or extra == "all-async"
32
32
  Requires-Dist: aiofiles (>=23.0.0) ; extra == "async-s3" or extra == "async-gs" or extra == "async-azure" or extra == "all-async" or extra == "all"
33
33
  Requires-Dist: azure-storage-blob (>=12.0.0) ; extra == "azure" or extra == "async-azure" or extra == "all-sync" or extra == "all-async" or extra == "all"
34
34
  Requires-Dist: boto3 (>=1.20.0) ; extra == "s3" or extra == "all-sync" or extra == "all"
35
- Requires-Dist: gcloud-aio-storage (>=8.0.0) ; extra == "async-gs" or extra == "all-async" or extra == "all"
35
+ Requires-Dist: gcloud-aio-storage (>=9.5) ; extra == "async-gs" or extra == "all-async" or extra == "all"
36
36
  Requires-Dist: google-cloud-storage (>=2.0.0) ; extra == "gs" or extra == "all-sync" or extra == "all"
37
37
  Requires-Dist: typing-extensions (>=4.0.0)
38
38
  Project-URL: Documentation, https://github.com/pwwang/panpath#readme
@@ -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.7"
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
@@ -301,6 +301,13 @@ class AsyncAzureBlobClient(AsyncClient):
301
301
 
302
302
  Note: For better streaming support, use a_open() instead.
303
303
  This method returns a file-like object that supports the standard file API.
304
+
305
+ Args:
306
+ path: Azure path
307
+ mode: File mode
308
+ encoding: Text encoding
309
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
310
+ upload_interval supported)
304
311
  """
305
312
  if mode not in ("r", "rb", "w", "wb", "a", "ab"):
306
313
  raise ValueError(f"Unsupported mode '{mode}'. Use 'r', 'rb', 'w', 'wb', 'a', or 'ab'.")
@@ -788,20 +795,60 @@ class AzureAsyncFileHandle(AsyncFileHandle):
788
795
  self._read_residue = self._read_residue[size:]
789
796
  return result # type: ignore[no-any-return]
790
797
 
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]
798
+ async def _upload(self, data: Union[str, bytes]) -> None:
799
+ """Upload data to Azure blob using append semantics.
800
+
801
+ This method uses Azure append blobs for efficient appending.
802
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
803
+ For 'a' mode, it always appends.
804
+
805
+ Args:
806
+ data: Data to upload
807
+ (will be appended to existing content after first write)
808
+ """
809
+ if isinstance(data, str):
810
+ data = data.encode(self._encoding)
811
+
812
+ blob_client = self._client.get_blob_client( # type: ignore[union-attr]
794
813
  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]
814
+ )
815
+
816
+ # For 'w' mode on first write, overwrite existing content
817
+ if self._first_write and not self._is_append:
818
+ self._first_write = False
819
+ # Simple overwrite
820
+ await blob_client.upload_blob(data, overwrite=True)
821
+ return
822
+
823
+ from azure.storage.blob import BlobType # type: ignore[import-not-found]
824
+
825
+ self._first_write = False
826
+
827
+ # For subsequent writes or 'a' mode, use append semantics
828
+ # Check if blob exists and its type
829
+ try:
830
+ properties = await blob_client.get_blob_properties()
831
+ blob_exists = True
832
+ blob_type = properties.blob_type
833
+ except ResourceNotFoundError:
834
+ blob_exists = False
835
+ blob_type = None
836
+
837
+ if not blob_exists:
838
+ # Create new append blob
839
+ await blob_client.upload_blob(data, blob_type=BlobType.AppendBlob)
840
+ elif blob_type == "AppendBlob":
841
+ # Append to existing append blob
842
+ await blob_client.append_block(data)
799
843
  else:
800
- return data.decode(self._encoding) # type: ignore[no-any-return]
844
+ # Convert block blob to append blob by reading, then creating append blob
845
+ existing_data = await blob_client.download_blob()
846
+ existing_content = await existing_data.readall()
801
847
 
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)
848
+ # Delete the old block blob
849
+ await blob_client.delete_blob()
850
+
851
+ # Create new append blob with combined content
852
+ await blob_client.upload_blob(
853
+ existing_content + data, blob_type=BlobType.AppendBlob
854
+ )
@@ -180,7 +180,15 @@ class AzureBlobClient(SyncClient):
180
180
  encoding: Optional[str] = None,
181
181
  **kwargs: Any,
182
182
  ) -> SyncFileHandle:
183
- """Open Azure blob for reading/writing."""
183
+ """Open Azure blob for reading/writing.
184
+
185
+ Args:
186
+ path: Azure path
187
+ mode: File mode
188
+ encoding: Text encoding
189
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
190
+ upload_interval supported)
191
+ """
184
192
  if mode not in ("r", "rb", "w", "wb", "a", "ab"):
185
193
  raise ValueError(f"Unsupported mode '{mode}'. Use 'r', 'rb', 'w', 'wb', 'a', or 'ab'.")
186
194
 
@@ -637,15 +645,58 @@ class AzureSyncFileHandle(SyncFileHandle):
637
645
  self._read_residue = self._read_residue[size:]
638
646
  return result # type: ignore[no-any-return]
639
647
 
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]
648
+ def _upload(self, data: Union[str, bytes]) -> None:
649
+ """Upload data to Azure blob using append semantics.
650
+
651
+ This method uses Azure append blobs for efficient appending.
652
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
653
+ For 'a' mode, it always appends.
654
+
655
+ Args:
656
+ data: Data to upload
657
+ (will be appended to existing content after first write)
658
+ """
659
+ if isinstance(data, str):
660
+ data = data.encode(self._encoding)
661
+
662
+ blob_client = self._client.get_blob_client(self._bucket, self._blob)
663
+
664
+ # For 'w' mode on first write, overwrite existing content
665
+ if self._first_write and not self._is_append:
666
+ self._first_write = False
667
+ # Simple overwrite
668
+ blob_client.upload_blob(data, overwrite=True)
669
+ return
670
+
671
+ self._first_write = False
672
+
673
+ # For subsequent writes or 'a' mode, use append semantics
674
+ # Check if blob exists and its type
675
+ try:
676
+ properties = blob_client.get_blob_properties()
677
+ blob_exists = True
678
+ blob_type = properties.blob_type
679
+ except ResourceNotFoundError:
680
+ blob_exists = False
681
+ blob_type = None
682
+
683
+ if not blob_exists:
684
+ # Create new append blob
685
+ from azure.storage.blob import BlobType
686
+
687
+ blob_client.upload_blob(data, blob_type=BlobType.AppendBlob)
688
+ elif blob_type == "AppendBlob":
689
+ # Append to existing append blob
690
+ blob_client.append_block(data)
646
691
  else:
647
- return data.decode(self._encoding) # type: ignore[no-any-return]
692
+ # Convert block blob to append blob by reading, then creating append blob
693
+ existing_data = blob_client.download_blob()
694
+ existing_content = existing_data.readall()
648
695
 
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)
696
+ # Delete the old block blob
697
+ blob_client.delete_blob()
698
+
699
+ # Create new append blob with combined content
700
+ from azure.storage.blob import BlobType
701
+
702
+ blob_client.upload_blob(existing_content + data, blob_type=BlobType.AppendBlob)
@@ -3,7 +3,6 @@
3
3
  import os
4
4
  import re
5
5
  import sys
6
- from abc import abstractmethod
7
6
  from pathlib import Path as PathlibPath, PurePosixPath
8
7
  from typing import TYPE_CHECKING, Any, AsyncGenerator, List, Union
9
8
 
@@ -123,32 +122,31 @@ class PanPath(PathlibPath):
123
122
  except KeyError:
124
123
  raise ValueError(f"Unsupported URI scheme: {scheme!r}")
125
124
 
126
- @abstractmethod
127
- async def a_resolve(self) -> "PanPath":
125
+ # These methods are used for IDE type hinting and documentation generation.
126
+ # Actual implementations are in LocalPath and CloudPath subclasses and
127
+ # are routed via __new__.
128
+ async def a_resolve(self) -> "PanPath": # type: ignore[empty-body]
128
129
  """Resolve to absolute path (no-op for cloud paths).
129
130
 
130
131
  Returns:
131
132
  Self (cloud paths are already absolute)
132
133
  """
133
134
 
134
- @abstractmethod
135
- async def a_exists(self) -> bool:
135
+ async def a_exists(self) -> bool: # type: ignore[empty-body]
136
136
  """Asynchronously check if the path exists.
137
137
 
138
138
  Returns:
139
139
  True if the path exists, False otherwise.
140
140
  """
141
141
 
142
- @abstractmethod
143
- async def a_read_bytes(self) -> bytes:
142
+ async def a_read_bytes(self) -> bytes: # type: ignore[empty-body]
144
143
  """Asynchronously read the file's bytes.
145
144
 
146
145
  Returns:
147
146
  File content as bytes.
148
147
  """
149
148
 
150
- @abstractmethod
151
- async def a_read_text(self, encoding: str = "utf-8") -> str:
149
+ async def a_read_text(self, encoding: str = "utf-8") -> str: # type: ignore[empty-body]
152
150
  """Asynchronously read the file's text content.
153
151
 
154
152
  Args:
@@ -158,7 +156,6 @@ class PanPath(PathlibPath):
158
156
  File content as string.
159
157
  """
160
158
 
161
- @abstractmethod
162
159
  async def a_write_bytes(self, data: bytes) -> Union[int, None]:
163
160
  """Asynchronously write bytes to the file.
164
161
 
@@ -169,8 +166,11 @@ class PanPath(PathlibPath):
169
166
  Number of bytes written. For some cloud paths, may return None.
170
167
  """
171
168
 
172
- @abstractmethod
173
- async def a_write_text(self, data: str, encoding: str = "utf-8") -> int:
169
+ async def a_write_text( # type: ignore[empty-body]
170
+ self,
171
+ data: str,
172
+ encoding: str = "utf-8",
173
+ ) -> int:
174
174
  """Asynchronously write text to the file.
175
175
 
176
176
  Args:
@@ -181,7 +181,6 @@ class PanPath(PathlibPath):
181
181
  Number of characters written.
182
182
  """
183
183
 
184
- @abstractmethod
185
184
  async def a_unlink(self, missing_ok: bool = False) -> None:
186
185
  """Asynchronously remove (delete) the file or empty directory.
187
186
 
@@ -189,39 +188,37 @@ class PanPath(PathlibPath):
189
188
  missing_ok: If True, does not raise an error if the file does not exist.
190
189
  """
191
190
 
192
- @abstractmethod
193
- async def a_iterdir(self) -> AsyncGenerator["PanPath", None]:
191
+ async def a_iterdir(self) -> AsyncGenerator["PanPath", None]: # type: ignore[empty-body]
194
192
  """Asynchronously iterate over directory contents.
195
193
 
196
194
  Yields:
197
195
  PanPath instances for each item in the directory.
198
196
  """
199
197
 
200
- @abstractmethod
201
- async def a_is_dir(self) -> bool:
198
+ async def a_is_dir(self) -> bool: # type: ignore[empty-body]
202
199
  """Asynchronously check if the path is a directory.
203
200
 
204
201
  Returns:
205
202
  True if the path is a directory, False otherwise.
206
203
  """
207
204
 
208
- @abstractmethod
209
- async def a_is_file(self) -> bool:
205
+ async def a_is_file(self) -> bool: # type: ignore[empty-body]
210
206
  """Asynchronously check if the path is a file.
211
207
 
212
208
  Returns:
213
209
  True if the path is a file, False otherwise.
214
210
  """
215
211
 
216
- @abstractmethod
217
- async def a_stat(self, follow_symlinks: bool = True) -> os.stat_result:
212
+ async def a_stat( # type: ignore[empty-body]
213
+ self,
214
+ follow_symlinks: bool = True,
215
+ ) -> os.stat_result:
218
216
  """Asynchronously get the file or directory's status information.
219
217
 
220
218
  Returns:
221
219
  An object containing file status information (platform-dependent).
222
220
  """
223
221
 
224
- @abstractmethod
225
222
  async def a_mkdir(
226
223
  self,
227
224
  mode: int = 0o777,
@@ -236,8 +233,10 @@ class PanPath(PathlibPath):
236
233
  exist_ok: If True, does not raise an error if the directory already exists.
237
234
  """
238
235
 
239
- @abstractmethod
240
- async def a_glob(self, pattern: str) -> AsyncGenerator["PanPath", None]:
236
+ async def a_glob( # type: ignore[empty-body]
237
+ self,
238
+ pattern: str,
239
+ ) -> AsyncGenerator["PanPath", None]:
241
240
  """Asynchronously yield paths matching a glob pattern.
242
241
 
243
242
  Args:
@@ -247,8 +246,10 @@ class PanPath(PathlibPath):
247
246
  List of PanPath instances matching the pattern.
248
247
  """
249
248
 
250
- @abstractmethod
251
- async def a_rglob(self, pattern: str) -> AsyncGenerator["PanPath", None]:
249
+ async def a_rglob( # type: ignore[empty-body]
250
+ self,
251
+ pattern: str,
252
+ ) -> AsyncGenerator["PanPath", None]:
252
253
  """Asynchronously yield paths matching a recursive glob pattern.
253
254
 
254
255
  Args:
@@ -258,16 +259,20 @@ class PanPath(PathlibPath):
258
259
  List of PanPath instances matching the pattern.
259
260
  """
260
261
 
261
- @abstractmethod
262
- async def a_walk(self) -> AsyncGenerator[tuple["PanPath", List[str], List[str]], None]:
262
+ async def a_walk( # type: ignore[empty-body]
263
+ self,
264
+ ) -> AsyncGenerator[tuple["PanPath", List[str], List[str]], None]:
263
265
  """Asynchronously walk the directory tree.
264
266
 
265
267
  Yields:
266
268
  Tuples of (current_path, dirnames, filenames) at each level.
267
269
  """
268
270
 
269
- @abstractmethod
270
- async def a_touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
271
+ async def a_touch(
272
+ self,
273
+ mode: int = 0o666,
274
+ exist_ok: bool = True,
275
+ ) -> None:
271
276
  """Asynchronously create the file if it does not exist.
272
277
 
273
278
  Args:
@@ -275,8 +280,10 @@ class PanPath(PathlibPath):
275
280
  exist_ok: If False, raises an error if the file already exists.
276
281
  """
277
282
 
278
- @abstractmethod
279
- async def a_rename(self, target: Union[str, "PathlibPath"]) -> "PanPath":
283
+ async def a_rename( # type: ignore[empty-body]
284
+ self,
285
+ target: Union[str, "PathlibPath"],
286
+ ) -> "PanPath":
280
287
  """Asynchronously rename this path to the target path.
281
288
 
282
289
  Args:
@@ -286,8 +293,10 @@ class PanPath(PathlibPath):
286
293
  The renamed PanPath instance.
287
294
  """
288
295
 
289
- @abstractmethod
290
- async def a_replace(self, target: Union[str, "PathlibPath"]) -> "PanPath":
296
+ async def a_replace( # type: ignore[empty-body]
297
+ self,
298
+ target: Union[str, "PathlibPath"],
299
+ ) -> "PanPath":
291
300
  """Asynchronously replace this path with the target path.
292
301
 
293
302
  Args:
@@ -297,12 +306,10 @@ class PanPath(PathlibPath):
297
306
  The replaced PanPath instance.
298
307
  """
299
308
 
300
- @abstractmethod
301
309
  async def a_rmdir(self) -> None:
302
310
  """Asynchronously remove the directory and its contents recursively."""
303
311
 
304
- @abstractmethod
305
- async def a_is_symlink(self) -> bool:
312
+ async def a_is_symlink(self) -> bool: # type: ignore[empty-body]
306
313
  """Asynchronously check if the path is a symbolic link.
307
314
 
308
315
  For local path, this checks if the path is a symlink.
@@ -314,8 +321,7 @@ class PanPath(PathlibPath):
314
321
  True if the path is a symlink, False otherwise.
315
322
  """
316
323
 
317
- @abstractmethod
318
- async def a_readlink(self) -> "PanPath":
324
+ async def a_readlink(self) -> "PanPath": # type: ignore[empty-body]
319
325
  """Asynchronously read the target of the symbolic link.
320
326
 
321
327
  For local path, this reads the symlink target.
@@ -325,7 +331,6 @@ class PanPath(PathlibPath):
325
331
  The target PanPath of the symlink.
326
332
  """
327
333
 
328
- @abstractmethod
329
334
  async def a_symlink_to(
330
335
  self,
331
336
  target: Union[str, "PathlibPath"],
@@ -341,7 +346,6 @@ class PanPath(PathlibPath):
341
346
  target_is_directory: Whether the target is a directory (ignored for cloud paths).
342
347
  """
343
348
 
344
- @abstractmethod
345
349
  async def a_rmtree(self, ignore_errors: bool = False, onerror: Any = None) -> None:
346
350
  """Asynchronously remove the directory and all its contents recursively.
347
351
 
@@ -350,8 +354,10 @@ class PanPath(PathlibPath):
350
354
  onerror: Optional function to call on errors.
351
355
  """
352
356
 
353
- @abstractmethod
354
- async def a_copy(self, target: Union[str, "PathlibPath"]) -> "PanPath":
357
+ async def a_copy( # type: ignore[empty-body]
358
+ self,
359
+ target: Union[str, "PathlibPath"],
360
+ ) -> "PanPath":
355
361
  """Asynchronously copy this path to the target path.
356
362
 
357
363
  Args:
@@ -361,8 +367,7 @@ class PanPath(PathlibPath):
361
367
  The copied PanPath instance.
362
368
  """
363
369
 
364
- @abstractmethod
365
- async def a_copytree(
370
+ async def a_copytree( # type: ignore[empty-body]
366
371
  self,
367
372
  target: Union[str, "PathlibPath"],
368
373
  follow_symlinks: bool = True,
@@ -377,8 +382,12 @@ class PanPath(PathlibPath):
377
382
  The copied PanPath instance.
378
383
  """
379
384
 
380
- @abstractmethod
381
- def a_open(self, mode: str = "r", encoding: str = "utf-8", **kwargs: Any) -> "AsyncFileHandle":
385
+ def a_open( # type: ignore[empty-body]
386
+ self,
387
+ mode: str = "r",
388
+ encoding: str = "utf-8",
389
+ **kwargs: Any,
390
+ ) -> "AsyncFileHandle":
382
391
  """Asynchronously open the file and return an async file handle.
383
392
 
384
393
  Args:
@@ -1,6 +1,8 @@
1
1
  """Base client classes for sync and async cloud storage operations."""
2
2
 
3
3
  from abc import ABC, abstractmethod
4
+ import asyncio
5
+ import time
4
6
  from typing import (
5
7
  Any,
6
8
  AsyncGenerator,
@@ -14,6 +16,7 @@ from typing import (
14
16
  )
15
17
 
16
18
  import re
19
+ import warnings
17
20
 
18
21
 
19
22
  class Client(ABC):
@@ -366,6 +369,8 @@ class AsyncFileHandle(ABC):
366
369
  mode: str = "r",
367
370
  encoding: Optional[str] = None,
368
371
  chunk_size: int = 4096,
372
+ upload_warning_threshold: int = 100,
373
+ upload_interval: float = 1.0,
369
374
  ):
370
375
  """Initialize async file handle.
371
376
 
@@ -377,6 +382,10 @@ class AsyncFileHandle(ABC):
377
382
  mode: File mode ('r', 'w', 'rb', 'wb', etc.)
378
383
  encoding: Text encoding (for text modes)
379
384
  chunk_size: Size of chunks to read
385
+ upload_warning_threshold: Number of chunk uploads before warning (default: 100)
386
+ -1 to disable warning
387
+ upload_interval: Minimum interval (in seconds) between uploads to avoid
388
+ rate limits (default: 1.0)
380
389
  """
381
390
  self._client_factory = client_factory
382
391
  self._client: Optional[AsyncClient] = None
@@ -387,6 +396,11 @@ class AsyncFileHandle(ABC):
387
396
  self._encoding = encoding or "utf-8"
388
397
  self._chunk_size = chunk_size
389
398
  self._closed = False
399
+ self._upload_warning_threshold = upload_warning_threshold
400
+ self._upload_count = 0
401
+ self._first_write = True # Track if this is the first write (for 'w' mode clearing)
402
+ self._upload_interval = upload_interval
403
+ self._last_upload_time: Optional[float] = None
390
404
 
391
405
  # For write modes
392
406
  self._write_buffer: Union[bytearray, List[str]] = bytearray() if "b" in mode else []
@@ -425,34 +439,12 @@ class AsyncFileHandle(ABC):
425
439
  else:
426
440
  return chunk.decode(self._encoding) # type: ignore
427
441
 
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
442
  async def flush(self) -> None:
452
- """Flush write buffer (optional, default implementation is no-op).
443
+ """Flush write buffer to cloud storage.
453
444
 
454
- Note latter flush will overwrite previous data in cloud storage.
455
- Incremental flush is not supported in this base implementation.
445
+ After open, all flushes append to existing content using provider-native
446
+ append operations. The difference between 'w' and 'a' modes is that 'w'
447
+ clears existing content on open, while 'a' preserves it.
456
448
  """
457
449
  if self._closed: # pragma: no cover
458
450
  raise ValueError("I/O operation on closed file")
@@ -460,14 +452,36 @@ class AsyncFileHandle(ABC):
460
452
  if not self._is_write: # pragma: no cover
461
453
  return
462
454
 
455
+ if not self._write_buffer and not self._first_write:
456
+ return
457
+
463
458
  if self._is_binary:
464
459
  data: Union[bytes, str] = bytes(self._write_buffer) # type: ignore
465
460
  else:
466
461
  data = "".join(self._write_buffer) # type: ignore
467
462
 
463
+ # Rate limiting: wait if needed to respect upload_interval
464
+ if self._upload_interval > 0 and self._last_upload_time is not None:
465
+ elapsed = time.time() - self._last_upload_time
466
+ if elapsed < self._upload_interval:
467
+ await asyncio.sleep(self._upload_interval - elapsed)
468
+
468
469
  await self._upload(data)
470
+ self._last_upload_time = time.time()
469
471
  self._write_buffer = bytearray() if self._is_binary else []
470
472
 
473
+ # Track upload count and warn if threshold exceeded
474
+ self._upload_count += 1
475
+ if self._upload_count == self._upload_warning_threshold:
476
+ warnings.warn(
477
+ f"File handle has flushed {self._upload_count} times. "
478
+ "Consider using larger chunk_size or buffering writes to reduce "
479
+ "cloud API calls. Set upload_warning_threshold=-1 to suppress "
480
+ "this warning.",
481
+ ResourceWarning,
482
+ stacklevel=2,
483
+ )
484
+
471
485
  async def reset_stream(self) -> None:
472
486
  """Reset the underlying stream to the beginning."""
473
487
  self._stream = await self._create_stream()
@@ -489,20 +503,10 @@ class AsyncFileHandle(ABC):
489
503
  ) from None
490
504
  else: # pragma: no cover
491
505
  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
506
+ elif self._is_write and not self._is_append:
507
+ # 'w' mode: clear existing content - do nothing here, will create on first write
508
+ # The difference is that subsequent flushes will append
509
+ pass
506
510
  return self
507
511
 
508
512
  async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
@@ -530,7 +534,7 @@ class AsyncFileHandle(ABC):
530
534
  # Return all buffered data plus rest of stream
531
535
  buffered = self._read_buffer
532
536
  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
537
+ rest = await self._stream_read(-1)
534
538
  self._read_pos += len(rest)
535
539
  self._eof = True
536
540
  result: Union[str, bytes] = buffered + rest # type: ignore
@@ -556,7 +560,6 @@ class AsyncFileHandle(ABC):
556
560
 
557
561
  # No buffered data, read from stream
558
562
  if size == -1:
559
- # Use _stream_read with -1, not _stream_read_all
560
563
  result_stream = await self._stream_read(-1)
561
564
  self._read_pos += len(result_stream)
562
565
  self._eof = True
@@ -637,6 +640,9 @@ class AsyncFileHandle(ABC):
637
640
  data = data.decode(self._encoding)
638
641
  self._write_buffer.append(data) # type: ignore
639
642
 
643
+ if len(self._write_buffer) >= self._chunk_size:
644
+ await self.flush()
645
+
640
646
  return len(data)
641
647
 
642
648
  async def writelines(self, lines: List[Union[str, bytes]]) -> None:
@@ -770,17 +776,22 @@ class SyncFileHandle(ABC):
770
776
  mode: str = "r",
771
777
  encoding: Optional[str] = None,
772
778
  chunk_size: int = 4096,
779
+ upload_warning_threshold: int = 100,
780
+ upload_interval: float = 1.0,
773
781
  ):
774
- """Initialize async file handle.
782
+ """Initialize sync file handle.
775
783
 
776
784
  Args:
777
- client_factor: Async client factory for cloud operations
785
+ client: Sync client for cloud operations
778
786
  bucket: Cloud storage bucket name or container
779
787
  blob: Cloud storage blob name or object key
780
788
  prefix: Cloud storage path prefix
781
789
  mode: File mode ('r', 'w', 'rb', 'wb', etc.)
782
790
  encoding: Text encoding (for text modes)
783
791
  chunk_size: Size of chunks to read
792
+ upload_warning_threshold: Number of chunk uploads before warning (default: 100)
793
+ upload_interval: Minimum interval (in seconds) between uploads to avoid
794
+ rate limits (default: 1.0)
784
795
  """
785
796
  self._client = client
786
797
  self._bucket = bucket
@@ -790,6 +801,11 @@ class SyncFileHandle(ABC):
790
801
  self._encoding = encoding or "utf-8"
791
802
  self._chunk_size = chunk_size
792
803
  self._closed = False
804
+ self._upload_warning_threshold = upload_warning_threshold
805
+ self._upload_count = 0
806
+ self._first_write = True # Track if this is the first write (for 'w' mode clearing)
807
+ self._upload_interval = upload_interval
808
+ self._last_upload_time: Optional[float] = None
793
809
 
794
810
  # For write modes
795
811
  self._write_buffer: Union[bytearray, List[str]] = bytearray() if "b" in mode else []
@@ -819,21 +835,47 @@ class SyncFileHandle(ABC):
819
835
  """Upload data to cloud storage (used internally)."""
820
836
 
821
837
  def flush(self) -> None:
822
- """Flush write buffer (optional, default implementation is no-op)."""
838
+ """Flush write buffer to cloud storage.
839
+
840
+ After open, all flushes append to existing content using provider-native
841
+ append operations. The difference between 'w' and 'a' modes is that 'w'
842
+ clears existing content on open, while 'a' preserves it.
843
+ """
823
844
  if self._closed: # pragma: no cover
824
845
  raise ValueError("I/O operation on closed file")
825
846
 
826
847
  if not self._is_write: # pragma: no cover
827
848
  return
828
849
 
850
+ if not self._write_buffer and not self._first_write:
851
+ return
852
+
829
853
  if self._is_binary:
830
854
  data = bytes(self._write_buffer) # type: ignore
831
855
  else:
832
856
  data = "".join(self._write_buffer) # type: ignore
833
857
 
858
+ # Rate limiting: wait if needed to respect upload_interval
859
+ if self._upload_interval > 0 and self._last_upload_time is not None:
860
+ elapsed = time.time() - self._last_upload_time
861
+ if elapsed < self._upload_interval:
862
+ time.sleep(self._upload_interval - elapsed)
863
+
834
864
  self._upload(data)
865
+ self._last_upload_time = time.time()
835
866
  self._write_buffer = bytearray() if self._is_binary else []
836
867
 
868
+ # Track upload count and warn if threshold exceeded
869
+ self._upload_count += 1
870
+ if self._upload_count == self._upload_warning_threshold:
871
+ warnings.warn(
872
+ f"File handle has flushed {self._upload_count} times. Consider using larger "
873
+ f"chunk_size or buffering writes to reduce cloud API calls. "
874
+ f"Set upload_warning_threshold=-1 to suppress this warning.",
875
+ ResourceWarning,
876
+ stacklevel=2,
877
+ )
878
+
837
879
  def _stream_read(self, size: int = -1) -> Union[str, bytes]:
838
880
  """Read from stream (used internally)."""
839
881
  # Python 3.9 compatibility: http.client.HTTPResponse.read() doesn't accept -1
@@ -854,32 +896,6 @@ class SyncFileHandle(ABC):
854
896
  else:
855
897
  return chunk.decode(self._encoding) # type: ignore
856
898
 
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
899
  def reset_stream(self) -> None:
884
900
  """Reset the underlying stream to the beginning."""
885
901
  self._stream = self._create_stream()
@@ -888,7 +904,7 @@ class SyncFileHandle(ABC):
888
904
  self._eof = False
889
905
 
890
906
  def __enter__(self) -> "SyncFileHandle":
891
- """Enter async context manager."""
907
+ """Enter context manager."""
892
908
  if self._is_read:
893
909
  try:
894
910
  self._stream = self._create_stream()
@@ -899,20 +915,11 @@ class SyncFileHandle(ABC):
899
915
  ) from None
900
916
  else: # pragma: no cover
901
917
  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
918
+ elif self._is_write and not self._is_append:
919
+ # 'w' mode: clear existing content - do nothing here, will create on
920
+ # first write
921
+ # The difference is that subsequent flushes will append
922
+ pass
916
923
  return self
917
924
 
918
925
  def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
@@ -936,7 +943,7 @@ class SyncFileHandle(ABC):
936
943
 
937
944
  # No buffered data, read from stream
938
945
  if size == -1:
939
- result = self._stream_read(-1) # Use _stream_read with -1, not _stream_read_all
946
+ result = self._stream_read(-1)
940
947
  self._read_pos += len(result)
941
948
  self._eof = True
942
949
  return result
@@ -1016,6 +1023,9 @@ class SyncFileHandle(ABC):
1016
1023
  data = data.decode(self._encoding)
1017
1024
  self._write_buffer.append(data) # type: ignore
1018
1025
 
1026
+ if len(self._write_buffer) >= self._chunk_size:
1027
+ self.flush()
1028
+
1019
1029
  return len(data)
1020
1030
 
1021
1031
  def writelines(self, lines: List[Union[str, bytes]]) -> None:
@@ -472,8 +472,8 @@ class CloudPath(PanPath, PurePosixPath, ABC):
472
472
  src: str, dst: str, follow_symlinks: bool = True
473
473
  ) -> None: # pragma: no cover
474
474
  """Copy file across storage boundaries."""
475
- src_path = PanPath(src) # type: ignore[abstract]
476
- dst_path = PanPath(dst) # type: ignore[abstract]
475
+ src_path = PanPath(src)
476
+ dst_path = PanPath(dst)
477
477
 
478
478
  # Handle symlinks
479
479
  if not follow_symlinks and src_path.is_symlink():
@@ -490,8 +490,8 @@ class CloudPath(PanPath, PurePosixPath, ABC):
490
490
  src: str, dst: str, follow_symlinks: bool = True
491
491
  ) -> None: # pragma: no cover
492
492
  """Copy directory tree across storage boundaries."""
493
- src_path = PanPath(src) # type: ignore[abstract]
494
- dst_path = PanPath(dst) # type: ignore[abstract]
493
+ src_path = PanPath(src)
494
+ dst_path = PanPath(dst)
495
495
 
496
496
  # Create destination directory
497
497
  dst_path.mkdir(parents=True, exist_ok=True)
@@ -508,7 +508,7 @@ class CloudPath(PanPath, PurePosixPath, ABC):
508
508
 
509
509
  # Copy files
510
510
  for filename in filenames:
511
- src_file = PanPath(dirpath) / filename # type: ignore[abstract]
511
+ src_file = PanPath(dirpath) / filename
512
512
  dst_file = dst_path / rel_dir / filename if rel_dir else dst_path / filename
513
513
  # Handle symlinks
514
514
  if not follow_symlinks and src_file.is_symlink():
@@ -666,7 +666,7 @@ class CloudPath(PanPath, PurePosixPath, ABC):
666
666
 
667
667
  target_str = str(target)
668
668
  if not isinstance(target, PanPath): # pragma: no cover
669
- target = PanPath(target_str) # type: ignore[abstract, assignment]
669
+ target = PanPath(target_str) # type: ignore[assignment]
670
670
 
671
671
  source_is_dir = await self.a_is_dir()
672
672
  target_is_dir = await target.a_is_dir() # type: ignore[union-attr]
@@ -799,7 +799,7 @@ class CloudPath(PanPath, PurePosixPath, ABC):
799
799
  # Same storage, use native copy
800
800
  await self.async_client.copy(str(self), target_str, follow_symlinks=follow_symlinks)
801
801
 
802
- return PanPath(target_str) # type: ignore[abstract]
802
+ return PanPath(target_str)
803
803
 
804
804
  async def a_copytree(
805
805
  self,
@@ -834,8 +834,8 @@ class CloudPath(PanPath, PurePosixPath, ABC):
834
834
  src: str, dst: str, follow_symlinks: bool = True
835
835
  ) -> None: # pragma: no cover
836
836
  """Copy file across storage boundaries (async)."""
837
- src_path = PanPath(src) # type: ignore[abstract]
838
- dst_path = PanPath(dst) # type: ignore[abstract]
837
+ src_path = PanPath(src)
838
+ dst_path = PanPath(dst)
839
839
 
840
840
  # Handle symlinks
841
841
  if not follow_symlinks and await src_path.a_is_symlink():
@@ -852,8 +852,8 @@ class CloudPath(PanPath, PurePosixPath, ABC):
852
852
  src: str, dst: str, follow_symlinks: bool = True
853
853
  ) -> None: # pragma: no cover
854
854
  """Copy directory tree across storage boundaries (async)."""
855
- src_path = PanPath(src) # type: ignore[abstract]
856
- dst_path = PanPath(dst) # type: ignore[abstract]
855
+ src_path = PanPath(src)
856
+ dst_path = PanPath(dst)
857
857
 
858
858
  # Create destination directory
859
859
  await dst_path.a_mkdir(parents=True, exist_ok=True)
@@ -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
@@ -322,7 +322,8 @@ class AsyncGSClient(AsyncClient):
322
322
  path: GCS path (gs://bucket/blob)
323
323
  mode: File mode ('r', 'w', 'rb', 'wb', 'a', 'ab')
324
324
  encoding: Text encoding (for text modes)
325
- **kwargs: Additional arguments (unused for GCS)
325
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
326
+ upload_interval supported)
326
327
 
327
328
  Returns:
328
329
  GSAsyncFileHandle with streaming support
@@ -776,9 +777,60 @@ class GSAsyncFileHandle(AsyncFileHandle):
776
777
  return True
777
778
 
778
779
  async def _upload(self, data: Union[str, bytes]) -> None:
779
- """Upload data to GCS blob.
780
+ """Upload data to GCS blob using append semantics.
781
+
782
+ This method appends data using GCS compose.
783
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
784
+ For 'a' mode, it always appends.
780
785
 
781
786
  Args:
782
787
  data: Data to upload
788
+ (will be appended to existing content after first write)
783
789
  """
784
- await self._client.upload(self._bucket, self._blob, data) # type: ignore[union-attr]
790
+ if isinstance(data, str):
791
+ data = data.encode(self._encoding)
792
+
793
+ storage: Storage = self._client # type: ignore[assignment]
794
+
795
+ # For 'w' mode on first write, overwrite existing content
796
+ if self._first_write and not self._is_append:
797
+ self._first_write = False
798
+ # Simple overwrite
799
+ await storage.upload(self._bucket, self._blob, data)
800
+ return
801
+
802
+ self._first_write = False
803
+
804
+ # For subsequent writes or append mode, use compose to append
805
+ # Check if the original blob exists
806
+ try:
807
+ await storage.download_metadata(self._bucket, self._blob)
808
+ blob_exists = True
809
+ except Exception:
810
+ blob_exists = False
811
+
812
+ if not blob_exists:
813
+ # If blob doesn't exist, just upload the new data
814
+ await storage.upload(self._bucket, self._blob, data)
815
+ else:
816
+ # Upload new data to a temporary blob
817
+ # Use upload count to ensure unique temp blob names across multiple flushes
818
+ temp_blob = f"{self._blob}.tmp.{os.getpid()}.{self._upload_count}"
819
+ await storage.upload(
820
+ self._bucket,
821
+ temp_blob,
822
+ data,
823
+ )
824
+
825
+ try:
826
+ # Use compose API to concatenate original + new data
827
+ await storage.compose(
828
+ bucket=self._bucket,
829
+ object_name=self._blob,
830
+ source_object_names=[self._blob, temp_blob],
831
+ )
832
+ except Exception as e: # pragma: no cover
833
+ raise IOError(f"Failed to append data to GCS blob: {self._blob}") from e
834
+ finally:
835
+ # Clean up the temporary blob
836
+ await storage.delete(self._bucket, temp_blob)
@@ -176,7 +176,8 @@ class GSClient(SyncClient):
176
176
  path: GCS path (gs://bucket/blob)
177
177
  mode: File mode ('r', 'w', 'rb', 'wb', 'a', 'ab')
178
178
  encoding: Text encoding (for text modes)
179
- **kwargs: Additional arguments (chunk_size supported)
179
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
180
+ upload_interval supported)
180
181
 
181
182
  Returns:
182
183
  GSSyncFileHandle with streaming support
@@ -590,8 +591,9 @@ class GSSyncFileHandle(SyncFileHandle):
590
591
  raise FileNotFoundError(f"GCS blob not found: {self._bucket}/{self._blob}")
591
592
 
592
593
  @classmethod
593
- def _expception_as_filenotfound(cls, exception: Exception) -> bool:
594
+ def _expception_as_filenotfound(cls, exception: Exception) -> bool: # pragma: no cover
594
595
  """Check if exception is GCS NotFound and convert to FileNotFoundError."""
596
+ # FileNotFoundError already raised in __init__
595
597
  return isinstance(exception, NotFound)
596
598
 
597
599
  def reset_stream(self) -> None:
@@ -616,5 +618,49 @@ class GSSyncFileHandle(SyncFileHandle):
616
618
  return self._blob.open("rb") # type: ignore[no-any-return]
617
619
 
618
620
  def _upload(self, data: Union[bytes, str]) -> None:
619
- """Flush buffered writes to GCS."""
620
- self._blob.upload_from_string(data)
621
+ """Upload data to GCS blob using append semantics.
622
+
623
+ This method appends data using GCS compose API.
624
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
625
+ For 'a' mode, it always appends.
626
+
627
+ Args:
628
+ data: Data to upload
629
+ (will be appended to existing content after first write)
630
+ """
631
+ if isinstance(data, str):
632
+ data = data.encode(self._encoding)
633
+
634
+ # For 'w' mode on first write, overwrite existing content
635
+ if self._first_write and not self._is_append:
636
+ self._first_write = False
637
+ # Simple overwrite
638
+ self._blob.upload_from_string(data)
639
+ return
640
+
641
+ self._first_write = False
642
+
643
+ # For subsequent writes or append mode, use compose to append
644
+ # Check if the original blob exists
645
+ blob_exists = self._blob.exists()
646
+
647
+ if not blob_exists:
648
+ # If blob doesn't exist, just upload the new data
649
+ self._blob.upload_from_string(data)
650
+ else:
651
+ bucket = self._blob.bucket
652
+ # Use upload count to ensure unique temp blob names across multiple flushes
653
+ temp_blob_name = f"{self._blob.name}.tmp.{os.getpid()}.{self._upload_count}"
654
+ temp_blob = bucket.blob(temp_blob_name)
655
+
656
+ # Upload new data to temp blob
657
+ temp_blob.upload_from_string(data)
658
+
659
+ try:
660
+ # Compose: original + temp = original
661
+ self._blob.compose([self._blob, temp_blob])
662
+ except Exception as e: # pragma: no cover
663
+ raise IOError(f"Failed to append data to GCS blob: {self._blob}") from e
664
+ finally:
665
+ # Clean up temp blob
666
+ temp_blob.delete()
@@ -79,7 +79,7 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
79
79
 
80
80
  target_str = str(target)
81
81
  await aiofiles.os.rename(str(self), target_str)
82
- return PanPath(target_str) # type: ignore[abstract]
82
+ return PanPath(target_str)
83
83
 
84
84
  async def a_replace(self, target: Union[str, "Path"]) -> "PanPath":
85
85
  """Rename the file or directory to target, overwriting if target exists.
@@ -131,7 +131,7 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
131
131
  break
132
132
  await df.write(chunk)
133
133
 
134
- return PanPath(target_str) # type: ignore[abstract]
134
+ return PanPath(target_str)
135
135
 
136
136
  async def a_copytree(
137
137
  self,
@@ -154,7 +154,7 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
154
154
  extra="all-async",
155
155
  )
156
156
 
157
- target = PanPath(target) # type: ignore[abstract]
157
+ target = PanPath(target)
158
158
  await target.a_mkdir(parents=True, exist_ok=True)
159
159
 
160
160
  async for entry in self.a_iterdir():
@@ -207,7 +207,7 @@ class LocalPath(_ConcretePath, PanPath): # type: ignore[valid-type, misc]
207
207
  extra="all-async",
208
208
  )
209
209
 
210
- return PanPath( # type: ignore[return-value, abstract]
210
+ return PanPath( # type: ignore[return-value]
211
211
  await aiofiles.os.readlink(str(self))
212
212
  )
213
213
 
@@ -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
@@ -298,7 +298,8 @@ class AsyncS3Client(AsyncClient):
298
298
  path: S3 path (s3://bucket/key)
299
299
  mode: File mode ('r', 'w', 'rb', 'wb', 'a', 'ab')
300
300
  encoding: Text encoding (for text modes)
301
- **kwargs: Additional arguments (unused for S3)
301
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
302
+ upload_interval supported)
302
303
 
303
304
  Returns:
304
305
  S3AsyncFileHandle with streaming support
@@ -758,7 +759,7 @@ class S3AsyncFileHandle(AsyncFileHandle):
758
759
 
759
760
  async def _create_stream(self) -> None:
760
761
  """Create the underlying stream for reading or writing."""
761
- client = await self._client_factory()
762
+ client: AioBaseClient = await self._client_factory()
762
763
  response = await client.get_object(Bucket=self._bucket, Key=self._blob)
763
764
  return response["Body"] # type: ignore[no-any-return]
764
765
 
@@ -774,9 +775,48 @@ class S3AsyncFileHandle(AsyncFileHandle):
774
775
  )
775
776
 
776
777
  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
- )
778
+ """Upload data to S3 using append semantics.
779
+
780
+ This method appends data using multipart upload.
781
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
782
+ For 'a' mode, it always appends.
783
+
784
+ Args:
785
+ data: Data to upload (will be appended to existing content after first write)
786
+ """
787
+ if isinstance(data, str):
788
+ data = data.encode(self._encoding)
789
+
790
+ client: AioBaseClient = self._client
791
+
792
+ # For 'w' mode on first write, overwrite existing content
793
+ if self._first_write and not self._is_append:
794
+ self._first_write = False
795
+ # Simple overwrite
796
+ await client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
797
+ return
798
+
799
+ self._first_write = False
800
+
801
+ # For subsequent writes or append mode, use read-modify-write
802
+ # Check if object exists
803
+ try:
804
+ await client.head_object(Bucket=self._bucket, Key=self._blob)
805
+ object_exists = True
806
+ except ClientError as e:
807
+ if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
808
+ object_exists = False
809
+ else: # pragma: no cover
810
+ raise
811
+
812
+ if not object_exists:
813
+ # Simple upload for new objects
814
+ await client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
815
+ else:
816
+ # For existing objects, download, concatenate, and re-upload
817
+ response = await client.get_object(Bucket=self._bucket, Key=self._blob)
818
+ existing_data = await response["Body"].read()
819
+ combined_data = existing_data + data
820
+ await client.put_object(
821
+ Bucket=self._bucket, Key=self._blob, Body=combined_data
822
+ )
@@ -188,7 +188,8 @@ class S3Client(SyncClient):
188
188
  path: S3 path (s3://bucket/key)
189
189
  mode: File mode ('r', 'w', 'rb', 'wb', 'a', 'ab')
190
190
  encoding: Text encoding (for text modes)
191
- **kwargs: Additional arguments (chunk_size supported)
191
+ **kwargs: Additional arguments (chunk_size, upload_warning_threshold,
192
+ upload_interval supported)
192
193
 
193
194
  Returns:
194
195
  S3SyncFileHandle with streaming support
@@ -632,5 +633,47 @@ class S3SyncFileHandle(SyncFileHandle):
632
633
  return False # pragma: no cover
633
634
 
634
635
  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)
636
+ """Upload data to S3 using append semantics.
637
+
638
+ This method appends data using multipart upload.
639
+ For 'w' mode on first write, it overwrites. Subsequently it appends.
640
+ For 'a' mode, it always appends.
641
+
642
+ Args:
643
+ data: Data to upload
644
+ (will be appended to existing content after first write)
645
+ """
646
+ if isinstance(data, str):
647
+ data = data.encode(self._encoding)
648
+
649
+ # For 'w' mode on first write, overwrite existing content
650
+ if self._first_write and not self._is_append:
651
+ self._first_write = False
652
+ # Simple overwrite
653
+ self._client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
654
+ return
655
+
656
+ self._first_write = False
657
+
658
+ # For subsequent writes or append mode, use read-modify-write
659
+ # Check if object exists
660
+ try:
661
+ self._client.head_object(Bucket=self._bucket, Key=self._blob)
662
+ object_exists = True
663
+ except ClientError as e:
664
+ if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
665
+ object_exists = False
666
+ else: # pragma: no cover
667
+ raise
668
+
669
+ if not object_exists:
670
+ # Simple upload for new objects
671
+ self._client.put_object(Bucket=self._bucket, Key=self._blob, Body=data)
672
+ else:
673
+ # For existing objects, download, concatenate, and re-upload
674
+ response = self._client.get_object(Bucket=self._bucket, Key=self._blob)
675
+ existing_data = response["Body"].read()
676
+ combined_data = existing_data + data
677
+ self._client.put_object(
678
+ Bucket=self._bucket, Key=self._blob, Body=combined_data
679
+ )
@@ -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.7"
8
8
  description = "Universal sync/async local/cloud path library with pathlib-compatible interface"
9
9
  authors = ["panpath contributors"]
10
10
  readme = "README.md"
@@ -40,7 +40,7 @@ azure-storage-blob = {version = ">=12.0.0", optional = true}
40
40
  # Async cloud storage backends
41
41
  aioboto3 = {version = ">=11.0.0", optional = true}
42
42
  aiofiles = {version = ">=23.0.0", optional = true}
43
- gcloud-aio-storage = {version = ">=8.0.0", optional = true}
43
+ gcloud-aio-storage = {version = ">=9.5", optional = true}
44
44
 
45
45
  [tool.poetry.extras]
46
46
  s3 = ["boto3"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes