asanypath 2.7.0__tar.gz → 2.7.2__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.
Files changed (85) hide show
  1. {asanypath-2.7.0 → asanypath-2.7.2}/PKG-INFO +27 -10
  2. {asanypath-2.7.0 → asanypath-2.7.2}/README.md +25 -8
  3. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_version.py +2 -2
  4. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/asanypath.py +52 -14
  5. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/click.py +5 -1
  6. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/cloud.py +6 -2
  7. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/http.py +85 -4
  8. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/ssh.py +4 -7
  9. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/sync.py +2 -1
  10. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_asanypath.py +196 -0
  11. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_backend_options.py +51 -0
  12. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_http.py +197 -0
  13. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_ssh.py +49 -0
  14. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_sync.py +23 -0
  15. {asanypath-2.7.0 → asanypath-2.7.2}/.copilot/skills/async-python-lib/SKILL.md +0 -0
  16. {asanypath-2.7.0 → asanypath-2.7.2}/.copilot/skills/gitguro/SKILL.md +0 -0
  17. {asanypath-2.7.0 → asanypath-2.7.2}/.github/CODEOWNERS +0 -0
  18. {asanypath-2.7.0 → asanypath-2.7.2}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  19. {asanypath-2.7.0 → asanypath-2.7.2}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  20. {asanypath-2.7.0 → asanypath-2.7.2}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  21. {asanypath-2.7.0 → asanypath-2.7.2}/.github/dependabot.yml +0 -0
  22. {asanypath-2.7.0 → asanypath-2.7.2}/.github/workflows/publish.yml +0 -0
  23. {asanypath-2.7.0 → asanypath-2.7.2}/.github/workflows/unittests.yml +0 -0
  24. {asanypath-2.7.0 → asanypath-2.7.2}/.gitignore +0 -0
  25. {asanypath-2.7.0 → asanypath-2.7.2}/.pre-commit-config.yaml +0 -0
  26. {asanypath-2.7.0 → asanypath-2.7.2}/CODE_OF_CONDUCT.md +0 -0
  27. {asanypath-2.7.0 → asanypath-2.7.2}/CONTRIBUTING.md +0 -0
  28. {asanypath-2.7.0 → asanypath-2.7.2}/LICENSE +0 -0
  29. {asanypath-2.7.0 → asanypath-2.7.2}/asanypath.png +0 -0
  30. {asanypath-2.7.0 → asanypath-2.7.2}/compose.yml +0 -0
  31. {asanypath-2.7.0 → asanypath-2.7.2}/hatch_build.py +0 -0
  32. {asanypath-2.7.0 → asanypath-2.7.2}/pyproject.toml +0 -0
  33. {asanypath-2.7.0 → asanypath-2.7.2}/scripts/bench.py +0 -0
  34. {asanypath-2.7.0 → asanypath-2.7.2}/scripts/bench_rmtree.py +0 -0
  35. {asanypath-2.7.0 → asanypath-2.7.2}/scripts/bench_upload.py +0 -0
  36. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/__init__.py +0 -0
  37. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/__init__.pyi +0 -0
  38. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_backend_opts.py +0 -0
  39. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_credstore.py +0 -0
  40. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_prompt.py +0 -0
  41. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_resume.py +0 -0
  42. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/_transfer.py +0 -0
  43. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/artifactory.py +0 -0
  44. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/asanypath.pyi +0 -0
  45. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/azure.py +0 -0
  46. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/batcher.py +0 -0
  47. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/cache.py +0 -0
  48. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/cli.py +0 -0
  49. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/common.py +0 -0
  50. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/exceptions.py +0 -0
  51. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/ftp.py +0 -0
  52. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/gcs.py +0 -0
  53. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/local.py +0 -0
  54. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/options.py +0 -0
  55. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/py.typed +0 -0
  56. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/s3.py +0 -0
  57. {asanypath-2.7.0 → asanypath-2.7.2}/src/asanypath/unsupported.py +0 -0
  58. {asanypath-2.7.0 → asanypath-2.7.2}/tests/__init__.py +0 -0
  59. {asanypath-2.7.0 → asanypath-2.7.2}/tests/conftest.py +0 -0
  60. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_artifactory.py +0 -0
  61. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_auth_errors.py +0 -0
  62. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_azure.py +0 -0
  63. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_batcher.py +0 -0
  64. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_cache.py +0 -0
  65. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_cli.py +0 -0
  66. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_click.py +0 -0
  67. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_cloudpathmixin.py +0 -0
  68. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_commonpathmixin.py +0 -0
  69. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_credstore.py +0 -0
  70. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_endpoints.py +0 -0
  71. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_ftp.py +0 -0
  72. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_gcs.py +0 -0
  73. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_http_auth.py +0 -0
  74. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_isolation.py +0 -0
  75. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_local.py +0 -0
  76. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_options.py +0 -0
  77. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_py_typed.py +0 -0
  78. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_resume.py +0 -0
  79. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_s3.py +0 -0
  80. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_scandir.py +0 -0
  81. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_ssh_hostkeys.py +0 -0
  82. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_syncpath.py +0 -0
  83. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_transport_hardening.py +0 -0
  84. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_unsupported_path.py +0 -0
  85. {asanypath-2.7.0 → asanypath-2.7.2}/tests/test_upload.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: asanypath
3
- Version: 2.7.0
3
+ Version: 2.7.2
4
4
  Summary: Async pathlib for local and cloud storage
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -20,7 +20,7 @@ Classifier: Programming Language :: Python :: 3.15
20
20
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
21
  Requires-Python: >=3.10
22
22
  Requires-Dist: anyio>=4
23
- Requires-Dist: asanypath-native~=2.7.0
23
+ Requires-Dist: asanypath-native~=2.7.2
24
24
  Requires-Dist: msgspec>=0.22.0
25
25
  Requires-Dist: yarl>=1.2
26
26
  Provides-Extra: all
@@ -136,15 +136,15 @@ with path.open("rb") as f:
136
136
  chunk = f.read(512)
137
137
  ```
138
138
 
139
- Files smaller than the buffer size are fetched in one shot automatically.
140
- Supported on S3, GCS, Azure, and Artifactory.
139
+ The buffer size controls prefetch; smaller files may be fetched in one shot.
140
+ Supported on S3, GCS, Azure, Artifactory, and HTTP/HTTPS.
141
141
 
142
- HTTP and HTTPS paths also support read-only `open("rb")` and `open("r")`
143
- with both context-manager styles. These download the entire response on entry
144
- and return a seekable in-memory handle, so servers do not need to support HEAD
145
- or range requests. Text mode accepts `encoding`, `errors`, and `newline`.
146
- Existing HTTP authentication and read-cache settings apply; anonymous URLs
147
- require no token.
142
+ HTTP and HTTPS paths support read-only `open("rb")` and `open("r")` with both
143
+ context-manager styles. They use lazy range reads when a HEAD response supplies
144
+ the size, falling back to a full download when HEAD or ranges are unavailable.
145
+ If the download cache is enabled, `open()` uses it instead of range reads.
146
+ Text mode accepts `encoding`, `errors`, and `newline`. Existing HTTP
147
+ authentication settings apply; anonymous URLs require no token.
148
148
 
149
149
  ### Service endpoints
150
150
 
@@ -292,6 +292,9 @@ workers.
292
292
 
293
293
  Cloud paths share a background event loop per process. After `fork`, the child
294
294
  resets the inherited runner and starts its own loop lazily on the next sync call.
295
+ An S3 sync path passed to a spawned worker retains its backend configuration,
296
+ including any credentials stored on the path. Don't share or store its pickle
297
+ as if it were just a URL.
295
298
 
296
299
  ### Large uploads stream automatically
297
300
 
@@ -609,6 +612,20 @@ syntax. Transport-managed headers such as `Host` and
609
612
  visible in shell history or process listings, so use the HTTP auth environment
610
613
  variables for secrets.
611
614
 
615
+ For SSH copies, config aliases can be used as `alias:path` (relative to the
616
+ remote home) or `ssh://alias/absolute/path`. Source overrides use constructor
617
+ option names, not OpenSSH directive names, and each requires a separate flag:
618
+
619
+ ```sh
620
+ asanypath cp alias:logs/output.txt ./output.txt \
621
+ --src-option ssh.username=deploy \
622
+ --src-option ssh.port=2222 \
623
+ --src-option ssh.client_keys=/path/to/private-key
624
+ ```
625
+
626
+ These override the corresponding config values. Passwords and other secrets
627
+ passed on the command line may be visible in shell history or process listings.
628
+
612
629
  ### Shell Completions (Beta)
613
630
 
614
631
  Path completions are available for all subcommands that take cloud paths: `ls`, `cp`, `mv`, `rm`, `stat`, `cat`, `exists`, `touch`, `checksums`, `mkdir`, `presign`, and `sync`.
@@ -79,15 +79,15 @@ with path.open("rb") as f:
79
79
  chunk = f.read(512)
80
80
  ```
81
81
 
82
- Files smaller than the buffer size are fetched in one shot automatically.
83
- Supported on S3, GCS, Azure, and Artifactory.
82
+ The buffer size controls prefetch; smaller files may be fetched in one shot.
83
+ Supported on S3, GCS, Azure, Artifactory, and HTTP/HTTPS.
84
84
 
85
- HTTP and HTTPS paths also support read-only `open("rb")` and `open("r")`
86
- with both context-manager styles. These download the entire response on entry
87
- and return a seekable in-memory handle, so servers do not need to support HEAD
88
- or range requests. Text mode accepts `encoding`, `errors`, and `newline`.
89
- Existing HTTP authentication and read-cache settings apply; anonymous URLs
90
- require no token.
85
+ HTTP and HTTPS paths support read-only `open("rb")` and `open("r")` with both
86
+ context-manager styles. They use lazy range reads when a HEAD response supplies
87
+ the size, falling back to a full download when HEAD or ranges are unavailable.
88
+ If the download cache is enabled, `open()` uses it instead of range reads.
89
+ Text mode accepts `encoding`, `errors`, and `newline`. Existing HTTP
90
+ authentication settings apply; anonymous URLs require no token.
91
91
 
92
92
  ### Service endpoints
93
93
 
@@ -235,6 +235,9 @@ workers.
235
235
 
236
236
  Cloud paths share a background event loop per process. After `fork`, the child
237
237
  resets the inherited runner and starts its own loop lazily on the next sync call.
238
+ An S3 sync path passed to a spawned worker retains its backend configuration,
239
+ including any credentials stored on the path. Don't share or store its pickle
240
+ as if it were just a URL.
238
241
 
239
242
  ### Large uploads stream automatically
240
243
 
@@ -552,6 +555,20 @@ syntax. Transport-managed headers such as `Host` and
552
555
  visible in shell history or process listings, so use the HTTP auth environment
553
556
  variables for secrets.
554
557
 
558
+ For SSH copies, config aliases can be used as `alias:path` (relative to the
559
+ remote home) or `ssh://alias/absolute/path`. Source overrides use constructor
560
+ option names, not OpenSSH directive names, and each requires a separate flag:
561
+
562
+ ```sh
563
+ asanypath cp alias:logs/output.txt ./output.txt \
564
+ --src-option ssh.username=deploy \
565
+ --src-option ssh.port=2222 \
566
+ --src-option ssh.client_keys=/path/to/private-key
567
+ ```
568
+
569
+ These override the corresponding config values. Passwords and other secrets
570
+ passed on the command line may be visible in shell history or process listings.
571
+
555
572
  ### Shell Completions (Beta)
556
573
 
557
574
  Path completions are available for all subcommands that take cloud paths: `ls`, `cp`, `mv`, `rm`, `stat`, `cat`, `exists`, `touch`, `checksums`, `mkdir`, `presign`, and `sync`.
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '2.7.0'
22
- __version_tuple__ = version_tuple = (2, 7, 0)
21
+ __version__ = version = '2.7.2'
22
+ __version_tuple__ = version_tuple = (2, 7, 2)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -6,11 +6,13 @@
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import os
9
10
  from abc import ABC, abstractmethod
10
11
  from collections.abc import AsyncIterator, Callable
11
12
  from importlib import import_module
12
13
  from os import PathLike, stat_result
13
14
  from pathlib import Path, PurePosixPath
15
+ from threading import Lock
14
16
  from typing import TYPE_CHECKING, Any, TypeVar
15
17
  from urllib.parse import urlsplit
16
18
 
@@ -48,25 +50,60 @@ class _LazyDict(dict):
48
50
  def __init__(self) -> None:
49
51
  super().__init__()
50
52
  self._pending = dict(_BUILTIN_PROTOCOLS)
53
+ self._lock = Lock()
54
+ self._loading: dict[str, int] = {}
55
+ self._generation = 0
56
+
57
+ def _after_fork(self):
58
+ self._lock = Lock()
59
+ self._loading.clear()
60
+ self._generation += 1
51
61
 
52
62
  def _load(self, key) -> bool:
53
- spec = self._pending.pop(key, None)
54
- if spec is None:
55
- return False
63
+ with self._lock:
64
+ if super().__contains__(key):
65
+ self._pending.pop(key, None)
66
+ return True
67
+ spec = self._pending.get(key)
68
+ if spec is None:
69
+ return False
70
+ self._loading[key] = self._loading.get(key, 0) + 1
71
+ generation = self._generation
72
+
73
+ unavailable = False
56
74
  try:
57
- klass = getattr(import_module(spec[0]), spec[1])
58
- except ImportError: # optional backend dependency not installed
59
- return False
60
- self.setdefault(key, klass)
61
- return True
75
+ # Do not hold the registry lock while Python's import locks are held.
76
+ try:
77
+ klass = getattr(import_module(spec[0]), spec[1])
78
+ except ImportError: # optional backend dependency not installed
79
+ unavailable = True
80
+ return False
81
+ with self._lock:
82
+ self.setdefault(key, klass)
83
+ if self._pending.get(key) == spec:
84
+ self._pending.pop(key)
85
+ return True
86
+ finally:
87
+ with self._lock:
88
+ if self._generation == generation:
89
+ remaining = self._loading[key] - 1
90
+ if remaining:
91
+ self._loading[key] = remaining
92
+ else:
93
+ del self._loading[key]
94
+ if unavailable and self._pending.get(key) == spec:
95
+ self._pending.pop(key)
62
96
 
63
97
  def _ensure(self):
64
- for key in list(self._pending):
98
+ with self._lock:
99
+ pending = list(self._pending)
100
+ for key in pending:
65
101
  self._load(key)
66
102
 
67
103
  def __setitem__(self, key, value):
68
- self._pending.pop(key, None)
69
- super().__setitem__(key, value)
104
+ with self._lock:
105
+ super().__setitem__(key, value)
106
+ self._pending.pop(key, None)
70
107
 
71
108
  def items(self):
72
109
  self._ensure()
@@ -97,12 +134,13 @@ class _LazyDict(dict):
97
134
  return super().get(key, default)
98
135
 
99
136
  def __missing__(self, key):
100
- if self._load(key):
101
- return self[key]
102
- return UnsupportedProtocolPath
137
+ self._load(key)
138
+ return super().get(key, UnsupportedProtocolPath)
103
139
 
104
140
 
105
141
  PROTOCOL_MAP = _LazyDict()
142
+ if hasattr(os, "register_at_fork"):
143
+ os.register_at_fork(after_in_child=PROTOCOL_MAP._after_fork)
106
144
 
107
145
  # Flavors whose abstract-method implementation has been validated once.
108
146
  _VALIDATED_FLAVORS: set[type] = set()
@@ -171,7 +171,11 @@ def _maybe_rewrite_scp_style(value: str) -> str:
171
171
  return value
172
172
  if not _discover_ssh_config():
173
173
  return value
174
- if _resolve_alias(host, None, None)[0] == host:
174
+ try:
175
+ resolved_host = _resolve_alias(host, None, None)[0]
176
+ except RuntimeError as exc:
177
+ raise click.ClickException(str(exc)) from exc
178
+ if resolved_host == host:
175
179
  # No Host block matched — leave alone (don't probe DNS).
176
180
  return value
177
181
  prefix = f"{user}@" if user else ""
@@ -1381,7 +1381,7 @@ class _CloudFile:
1381
1381
  self._range_read = range_read
1382
1382
  self._buf: IO[bytes] | None = None
1383
1383
  self._text_wrapper: io.TextIOWrapper | None = None
1384
- self._reader: io.BufferedReader | None = None
1384
+ self._reader: io.BufferedReader | io.RawIOBase | None = None
1385
1385
  self._closed = False
1386
1386
  self._sync = False
1387
1387
 
@@ -1415,11 +1415,12 @@ class _CloudFile:
1415
1415
 
1416
1416
  def _make_reader(self, size: int) -> io.IOBase:
1417
1417
  """Create a lazily-filled reader backed by range reads."""
1418
- raw = _CloudRawIO(self._path, size)
1418
+ raw = self._make_raw_reader(size)
1419
1419
  if self._buffering == 0:
1420
1420
  # Unbuffered: return raw directly (binary only)
1421
1421
  if "b" not in self._mode:
1422
1422
  raise ValueError("can't have unbuffered text I/O")
1423
+ self._reader = raw
1423
1424
  return raw
1424
1425
  reader = io.BufferedReader(raw, buffer_size=self._chunk_size)
1425
1426
  self._reader = reader
@@ -1432,6 +1433,9 @@ class _CloudFile:
1432
1433
  )
1433
1434
  return reader
1434
1435
 
1436
+ def _make_raw_reader(self, size: int) -> _CloudRawIO:
1437
+ return _CloudRawIO(self._path, size)
1438
+
1435
1439
  def _spool_for_upload(self) -> tuple[IO[bytes], int]:
1436
1440
  """Flush any text layer and rewind the spool; return ``(buffer, size)``."""
1437
1441
  if self._text_wrapper is not None:
@@ -29,7 +29,7 @@ from asanypath_native import (
29
29
  from yarl import URL
30
30
 
31
31
  from asanypath._transfer import RangeNotSupportedError
32
- from asanypath.cloud import CloudPathMixin, _CloudFile, _service_origin
32
+ from asanypath.cloud import CloudPathMixin, _CloudFile, _CloudRawIO, _service_origin
33
33
 
34
34
  logger = logging.getLogger(__name__)
35
35
 
@@ -483,8 +483,8 @@ class HTTPPath(CloudPathMixin):
483
483
  def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None):
484
484
  """Open a seekable read-only handle with sync or async context management.
485
485
 
486
- Downloads the response on context entry using read_bytes(), including
487
- its authentication and cache settings. No HEAD or range support is required.
486
+ Read ranges lazily when the server provides a usable size. Servers that
487
+ do not support HEAD or ranges fall back to a full download.
488
488
  """
489
489
  if mode not in ("r", "rt", "tr", "rb", "br"):
490
490
  raise ValueError("HTTPPath.open() supports only read modes ('r', 'rt', 'rb')")
@@ -492,7 +492,7 @@ class HTTPPath(CloudPathMixin):
492
492
  raise ValueError("binary mode doesn't take an encoding, errors or newline argument")
493
493
  if buffering == 0 and "b" not in mode:
494
494
  raise ValueError("can't have unbuffered text I/O")
495
- return _CloudFile(self, mode, buffering, encoding, errors, newline, range_read=False)
495
+ return _HTTPCloudFile(self, mode, buffering, encoding, errors, newline)
496
496
 
497
497
  async def _read_bytes_uncached(self) -> bytes:
498
498
  return await http_get(str(self), headers=self._merge_headers(None))
@@ -666,3 +666,84 @@ class HTTPSPath(HTTPPath):
666
666
  """Async path implementation for HTTPS."""
667
667
 
668
668
  protocol: str = "https"
669
+
670
+
671
+ class _HTTPRawIO(_CloudRawIO):
672
+ def __init__(self, path, size: int, etag: str | None, last_modified: str | None):
673
+ super().__init__(path, size)
674
+ self._etag = etag
675
+ self._last_modified = last_modified
676
+ self._whole_response: bytes | None = None
677
+
678
+ def readinto(self, b):
679
+ if self._pos >= self._size or not b:
680
+ return 0
681
+ end = min(self._pos + len(b), self._size)
682
+ if self._whole_response is None:
683
+ from asanypath.sync import _SyncRunner
684
+
685
+ try:
686
+ data = _SyncRunner.get().run(
687
+ self._path._range_read(
688
+ self._pos,
689
+ end - 1,
690
+ etag=self._etag,
691
+ last_modified=self._last_modified,
692
+ total_size=self._size,
693
+ )
694
+ )
695
+ except RangeNotSupportedError as error:
696
+ if len(error.data) != self._size:
697
+ raise OSError("Source changed during ranged read") from error
698
+ self._whole_response = error.data
699
+ data = error.data[self._pos : end]
700
+ else:
701
+ data = self._whole_response[self._pos : end]
702
+ b[: len(data)] = data
703
+ self._pos += len(data)
704
+ return len(data)
705
+
706
+
707
+ class _HTTPCloudFile(_CloudFile):
708
+ async def _range_metadata(self):
709
+ from asanypath.cache import cache_enabled
710
+
711
+ if cache_enabled(None) or http_request is None:
712
+ return None
713
+ response = await self._path.request("HEAD", headers={"accept-encoding": "identity"})
714
+ if response.status_code in (400, 401, 403, 404, 405, 501):
715
+ logger.debug("HTTP HEAD unavailable; falling back to a full read")
716
+ return None
717
+ if not response.ok:
718
+ raise RuntimeError(f"HTTP {response.status_code} during HEAD request")
719
+ headers = {key.lower(): value for key, value in response.headers.items()}
720
+ if headers.get("accept-ranges", "").lower() == "none":
721
+ return None
722
+ if headers.get("content-encoding", "identity").lower() != "identity":
723
+ return None
724
+ size = self._get_size(headers)
725
+ if size is None or size <= 0:
726
+ return None
727
+ return size, headers.get("etag"), headers.get("last-modified")
728
+
729
+ def _make_raw_reader(self, size: int) -> _CloudRawIO:
730
+ return _HTTPRawIO(self._path, size, self._etag, self._last_modified)
731
+
732
+ def __enter__(self):
733
+ from asanypath.sync import _SyncRunner
734
+
735
+ self._sync = True
736
+ runner = _SyncRunner.get()
737
+ metadata = runner.run(self._range_metadata())
738
+ if metadata is not None:
739
+ size, self._etag, self._last_modified = metadata
740
+ return self._make_reader(size)
741
+ return self._make_buffer(runner.run(self._path.read_bytes()))
742
+
743
+ async def __aenter__(self):
744
+ self._sync = False
745
+ metadata = await self._range_metadata()
746
+ if metadata is not None:
747
+ size, self._etag, self._last_modified = metadata
748
+ return self._make_reader(size)
749
+ return self._make_buffer(await self._path.read_bytes())
@@ -179,12 +179,9 @@ def _resolve_alias(
179
179
  cfg_paths = _discover_ssh_config()
180
180
  if not host or not cfg_paths:
181
181
  return host, port, user, None, None, None
182
- try:
183
- cfg_host, cfg_port, cfg_user, cfg_identity, cfg_strict, cfg_known = ssh_resolve_config(
184
- host, cfg_paths
185
- )
186
- except Exception: # noqa: BLE001
187
- return host, port, user, None, None, None
182
+ cfg_host, cfg_port, cfg_user, cfg_identity, cfg_strict, cfg_known = ssh_resolve_config(
183
+ host, cfg_paths
184
+ )
188
185
  resolved_host = cfg_host or host
189
186
  resolved_port = port or cfg_port
190
187
  resolved_user = user or cfg_user
@@ -356,7 +353,7 @@ class SSHPath(CloudPathMixin):
356
353
  # Auth precedence mirrors ssh: explicit password, then key file
357
354
  # (explicit kwarg/env, else ssh_config IdentityFile), else agent.
358
355
  keys = self._client_keys or ()
359
- key_path = keys[0] if keys else getattr(self, "_config_identity", None)
356
+ key_path = keys[0] if keys else self._expand_ssh_tokens(self._config_identity)
360
357
  if key_path is not None:
361
358
  key_path = str(Path(key_path).expanduser())
362
359
  if self._password is not None:
@@ -140,7 +140,8 @@ class _SyncProxy:
140
140
  # (every cloud path method call triggers these branches), but edge cases
141
141
  # like "non-callable attributes that are collections" are hard to trigger
142
142
  # directly without synthetic mocking.
143
- attr = getattr(self._async, name)
143
+ # Pickle probes __setstate__ before restoring the _async slot.
144
+ attr = getattr(object.__getattribute__(self, "_async"), name)
144
145
 
145
146
  # Properties and plain values
146
147
  if not callable(attr): # pragma: no cover
@@ -4,6 +4,7 @@
4
4
  # license that can be found in the LICENSE file or at
5
5
  # https://opensource.org/licenses/MIT.
6
6
 
7
+ import os
7
8
  import re
8
9
  from urllib.parse import urlparse
9
10
 
@@ -225,6 +226,201 @@ def test_register_overrides_builtin():
225
226
  assert out == "True"
226
227
 
227
228
 
229
+ def test_concurrent_https_and_local_dispatch_during_lazy_import(monkeypatch):
230
+ from concurrent.futures import ThreadPoolExecutor
231
+ from threading import Event
232
+
233
+ import asanypath.asanypath as factory
234
+ from asanypath.http import HTTPSPath
235
+ from asanypath.local import AsyncPath
236
+
237
+ registry = factory._LazyDict()
238
+ monkeypatch.setattr(factory, "PROTOCOL_MAP", registry)
239
+ original_import = factory.import_module
240
+ importing = Event()
241
+ resume = Event()
242
+
243
+ def blocked_import(name):
244
+ if name == "asanypath.local" and not importing.is_set():
245
+ importing.set()
246
+ if not resume.wait(5):
247
+ raise TimeoutError("local backend import was not released")
248
+ return original_import(name)
249
+
250
+ monkeypatch.setattr(factory, "import_module", blocked_import)
251
+ with ThreadPoolExecutor(max_workers=1) as executor:
252
+ https = executor.submit(AsAnyPath, "https://example.com/file")
253
+ try:
254
+ assert importing.wait(5)
255
+ local = AsAnyPath("/tmp/cfg.yaml")
256
+ finally:
257
+ resume.set()
258
+ assert isinstance(https.result(timeout=10), HTTPSPath)
259
+ assert isinstance(local, AsyncPath)
260
+ assert str(local) == "/tmp/cfg.yaml"
261
+
262
+
263
+ @pytest.mark.parametrize("import_fails", [False, True])
264
+ def test_register_while_lazy_import_is_in_progress(monkeypatch, import_fails):
265
+ from concurrent.futures import ThreadPoolExecutor
266
+ from threading import Event
267
+ from types import SimpleNamespace
268
+
269
+ import asanypath.asanypath as factory
270
+
271
+ class Builtin:
272
+ pass
273
+
274
+ class Override:
275
+ pass
276
+
277
+ registry = factory._LazyDict()
278
+ registry._pending = {"file": ("backend", "Builtin")}
279
+ importing = Event()
280
+ resume = Event()
281
+
282
+ def blocked_import(name):
283
+ importing.set()
284
+ if not resume.wait(5):
285
+ raise TimeoutError("backend import was not released")
286
+ if import_fails:
287
+ raise ImportError("optional backend unavailable")
288
+ return SimpleNamespace(Builtin=Builtin)
289
+
290
+ monkeypatch.setattr(factory, "import_module", blocked_import)
291
+ with ThreadPoolExecutor(max_workers=1) as executor:
292
+ lookup = executor.submit(registry.__getitem__, "file")
293
+ try:
294
+ assert importing.wait(5)
295
+ registry["file"] = Override
296
+ finally:
297
+ resume.set()
298
+ assert lookup.result(timeout=5) is Override
299
+ assert registry["file"] is Override
300
+
301
+
302
+ def test_failed_import_does_not_hide_another_import_in_progress(monkeypatch):
303
+ from concurrent.futures import ThreadPoolExecutor
304
+ from threading import Event
305
+ from types import SimpleNamespace
306
+
307
+ import asanypath.asanypath as factory
308
+
309
+ class Builtin:
310
+ pass
311
+
312
+ registry = factory._LazyDict()
313
+ registry._pending = {"file": ("backend", "Builtin")}
314
+ first_started, second_started = Event(), Event()
315
+ fail_first, finish_second = Event(), Event()
316
+
317
+ def blocked_import(name):
318
+ if not first_started.is_set():
319
+ first_started.set()
320
+ if not fail_first.wait(5):
321
+ raise TimeoutError("first import was not released")
322
+ raise ImportError("temporarily unavailable")
323
+ if not second_started.is_set():
324
+ second_started.set()
325
+ if not finish_second.wait(5):
326
+ raise TimeoutError("second import was not released")
327
+ return SimpleNamespace(Builtin=Builtin)
328
+
329
+ monkeypatch.setattr(factory, "import_module", blocked_import)
330
+ with ThreadPoolExecutor(max_workers=2) as executor:
331
+ first = executor.submit(registry.__getitem__, "file")
332
+ try:
333
+ assert first_started.wait(5)
334
+ second = executor.submit(registry.__getitem__, "file")
335
+ assert second_started.wait(5)
336
+ fail_first.set()
337
+ assert first.result(timeout=5) is UnsupportedProtocolPath
338
+ assert registry["file"] is Builtin
339
+ finally:
340
+ fail_first.set()
341
+ finish_second.set()
342
+ assert second.result(timeout=5) is Builtin
343
+
344
+
345
+ def test_missing_backend_is_not_reimported(monkeypatch):
346
+ import asanypath.asanypath as factory
347
+
348
+ registry = factory._LazyDict()
349
+ registry._pending = {"file": ("backend", "Builtin")}
350
+ attempts = []
351
+
352
+ def missing_import(name):
353
+ attempts.append(name)
354
+ raise ImportError("backend unavailable")
355
+
356
+ monkeypatch.setattr(factory, "import_module", missing_import)
357
+ assert registry["file"] is UnsupportedProtocolPath
358
+ assert registry["file"] is UnsupportedProtocolPath
359
+ assert attempts == ["backend"]
360
+
361
+
362
+ def test_in_progress_import_can_finish_after_fork_reset(monkeypatch):
363
+ from types import SimpleNamespace
364
+
365
+ import asanypath.asanypath as factory
366
+
367
+ class Builtin:
368
+ pass
369
+
370
+ registry = factory._LazyDict()
371
+ registry._pending = {"file": ("backend", "Builtin")}
372
+
373
+ def import_after_fork(name):
374
+ registry._after_fork()
375
+ return SimpleNamespace(Builtin=Builtin)
376
+
377
+ monkeypatch.setattr(factory, "import_module", import_after_fork)
378
+ assert registry["file"] is Builtin
379
+ assert registry["file"] is Builtin
380
+
381
+
382
+ @pytest.mark.skipif(not hasattr(os, "fork"), reason="requires fork")
383
+ def test_registry_lock_is_reinitialized_after_fork():
384
+ import multiprocessing
385
+ from concurrent.futures import ThreadPoolExecutor
386
+ from threading import Event
387
+
388
+ import asanypath.asanypath as factory
389
+ from asanypath.local import AsyncPath
390
+
391
+ ctx = multiprocessing.get_context("fork")
392
+ parent, child = ctx.Pipe(duplex=False)
393
+ locked, release = Event(), Event()
394
+
395
+ def hold_lock():
396
+ with factory.PROTOCOL_MAP._lock:
397
+ locked.set()
398
+ release.wait(10)
399
+
400
+ def child_lookup():
401
+ child.send(factory.PROTOCOL_MAP.get("file") is AsyncPath)
402
+ child.close()
403
+
404
+ with ThreadPoolExecutor(max_workers=1) as executor:
405
+ holder = executor.submit(hold_lock)
406
+ process = ctx.Process(target=child_lookup)
407
+ try:
408
+ assert locked.wait(5)
409
+ process.start()
410
+ assert parent.poll(5), "child blocked on the inherited registry lock"
411
+ assert parent.recv()
412
+ process.join(5)
413
+ assert process.exitcode == 0
414
+ finally:
415
+ release.set()
416
+ if process.pid is not None and process.is_alive():
417
+ process.terminate()
418
+ process.join()
419
+ holder.result(timeout=5)
420
+ parent.close()
421
+ child.close()
422
+
423
+
228
424
  def test_lazy_exports_and_dir():
229
425
  import asanypath
230
426