python-pylan 0.0.2__py3-none-any.whl → 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pylan/core/net.py ADDED
@@ -0,0 +1,88 @@
1
+ """Low-level network adapter inspection and ARP neighbor discovery."""
2
+
3
+ import ipaddress
4
+ import logging
5
+ import os
6
+ import re
7
+ import socket
8
+ import subprocess
9
+
10
+ import psutil
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def get_default_interface_ip() -> str:
16
+ """Find the primary outbound local IPv4 address."""
17
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
18
+ try:
19
+ sock.connect(("8.8.8.8", 80))
20
+ return str(sock.getsockname()[0])
21
+ except OSError:
22
+ return "127.0.0.1"
23
+ finally:
24
+ sock.close()
25
+
26
+
27
+ def get_active_interface_details() -> tuple[str, str]:
28
+ """Retrieve the primary active local IPv4 address and its netmask.
29
+
30
+ Returns:
31
+ A tuple of (ip_address, netmask_str). Falls back to /24 if the netmask
32
+ cannot be determined from psutil interface records.
33
+ """
34
+ default_ip = get_default_interface_ip()
35
+ if default_ip == "127.0.0.1":
36
+ return "127.0.0.1", "255.255.255.0"
37
+
38
+ try:
39
+ interfaces = psutil.net_if_addrs()
40
+ for _iface, addrs in interfaces.items():
41
+ for addr in addrs:
42
+ if (
43
+ addr.family == socket.AF_INET
44
+ and addr.address == default_ip
45
+ ):
46
+ netmask = addr.netmask or "255.255.255.0"
47
+ return addr.address, netmask
48
+ except Exception as exc:
49
+ logger.debug("Failed querying psutil network interfaces: %s", exc)
50
+
51
+ return default_ip, "255.255.255.0"
52
+
53
+
54
+ def get_arp_neighbors() -> set[str]:
55
+ """Extract cached IPv4 addresses from the local OS ARP table."""
56
+ neighbors: set[str] = set()
57
+ ip_pattern = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
58
+
59
+ try:
60
+ if os.name == "nt":
61
+ output = subprocess.check_output(
62
+ ["arp", "-a"], stderr=subprocess.DEVNULL
63
+ ).decode(errors="ignore")
64
+ else:
65
+ try:
66
+ output = subprocess.check_output(
67
+ ["ip", "neighbor", "show"], stderr=subprocess.DEVNULL
68
+ ).decode(errors="ignore")
69
+ except Exception:
70
+ output = subprocess.check_output(
71
+ ["arp", "-an"], stderr=subprocess.DEVNULL
72
+ ).decode(errors="ignore")
73
+
74
+ for match in ip_pattern.findall(output):
75
+ try:
76
+ ip_obj = ipaddress.ip_address(match)
77
+ if not (
78
+ ip_obj.is_multicast
79
+ or ip_obj.is_loopback
80
+ or ip_obj.is_reserved
81
+ ):
82
+ neighbors.add(str(ip_obj))
83
+ except ValueError:
84
+ continue
85
+ except Exception as exc:
86
+ logger.debug("Failed reading system ARP cache: %s", exc)
87
+
88
+ return neighbors
pylan/core/protocol.py ADDED
@@ -0,0 +1,132 @@
1
+ """Module for framing network messages with a binary header and variable
2
+ payload.
3
+
4
+ This module provides utility functions to pack structured message data (either
5
+ JSON-serializable dictionaries or raw bytes) along with a fixed-size binary
6
+ header, and to unpack the header back into its component metadata values.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ import struct
12
+ from typing import Optional
13
+
14
+ from pylan.errors import PayloadTooLargeError
15
+
16
+ # "!BI" translates to:
17
+ # ! = Network byte order (Big-endian)
18
+ # B = 1-byte unsigned char (Message Type)
19
+ # I = 4-byte unsigned int (Payload Length)
20
+ HEADER_FORMAT = "!BI"
21
+ HEADER_SIZE = struct.calcsize(HEADER_FORMAT)
22
+ MAX_FRAME_SIZE: int = 10 * 1024 * 1024 # 10 MB limit for control/chunk frames
23
+
24
+ MSG_TYPE_TRANSFER_REQUEST = 20
25
+ MSG_TYPE_TRANSFER_ACCEPT = 21
26
+ MSG_TYPE_TRANSFER_REJECT = 22
27
+ MSG_TYPE_TRANSFER_CHUNK = 23
28
+ MSG_TYPE_TRANSFER_COMPLETE = 24
29
+
30
+
31
+ def pack_message(msg_type: int, payload: dict | bytes) -> bytes:
32
+ """Serializes a payload and prepends a fixed-size binary header.
33
+
34
+ Args:
35
+ msg_type: An integer representing the application-defined message type.
36
+ payload: The message body, which can be either a Python dictionary
37
+ (will be converted to JSON bytes) or raw bytes.
38
+
39
+ Returns:
40
+ A bytes object containing the packed header immediately followed by
41
+ the serialized payload bytes.
42
+
43
+ Raises:
44
+ TypeError: If the payload is neither a dictionary nor a bytes object.
45
+ """
46
+ if isinstance(payload, dict):
47
+ payload_bytes = json.dumps(payload).encode("utf-8")
48
+ elif isinstance(payload, bytes):
49
+ payload_bytes = payload
50
+ else:
51
+ raise TypeError(f"Unsupported payload type: {type(payload)}")
52
+
53
+ payload_length = len(payload_bytes)
54
+
55
+ header = struct.pack(HEADER_FORMAT, msg_type, payload_length)
56
+
57
+ return header + payload_bytes
58
+
59
+
60
+ def unpack_header(header_bytes: bytes) -> tuple[int, int]:
61
+ """Unpacks a raw byte stream into message metadata values.
62
+
63
+ Args:
64
+ header_bytes: A bytes object of exact length `HEADER_SIZE` (5 bytes).
65
+
66
+ Returns:
67
+ A tuple containing:
68
+ - msg_type (int): The application-defined message identifier.
69
+ - payload_length (int): The length of the upcoming payload in
70
+ bytes.
71
+
72
+ Raises:
73
+ struct.error: If `header_bytes` is not exactly equal to `HEADER_SIZE`.
74
+ """
75
+ msg_type, payload_length = struct.unpack(HEADER_FORMAT, header_bytes)
76
+ return msg_type, payload_length
77
+
78
+
79
+ async def read_frame(
80
+ reader: asyncio.StreamReader,
81
+ *,
82
+ max_frame_size: int = MAX_FRAME_SIZE,
83
+ timeout: Optional[float] = None,
84
+ ) -> tuple[int, bytes]:
85
+ """Read and validate a single length-prefixed frame from an async stream.
86
+
87
+ Validates the declared payload length against ``max_frame_size`` before
88
+ allocating memory or reading the frame body.
89
+
90
+ Args:
91
+ reader: Connected :class:`asyncio.StreamReader` to read from.
92
+ max_frame_size: Maximum allowed payload length in bytes. Defaults to
93
+ :data:`MAX_FRAME_SIZE`.
94
+ timeout: Optional timeout in seconds applied to each stream read.
95
+
96
+ Returns:
97
+ A tuple containing ``(msg_type, body_bytes)``.
98
+
99
+ Raises:
100
+ ValueError: If ``max_frame_size`` is negative.
101
+ PayloadTooLargeError: If the declared payload length exceeds
102
+ ``max_frame_size``.
103
+ asyncio.IncompleteReadError: If EOF is reached before the full frame is
104
+ received.
105
+ asyncio.TimeoutError: If ``timeout`` expires while waiting for data.
106
+ """
107
+ if max_frame_size < 0:
108
+ raise ValueError("max_frame_size must be non-negative.")
109
+
110
+ header_coro = reader.readexactly(HEADER_SIZE)
111
+ header_bytes = (
112
+ await asyncio.wait_for(header_coro, timeout=timeout)
113
+ if timeout is not None
114
+ else await header_coro
115
+ )
116
+ msg_type, payload_length = unpack_header(header_bytes)
117
+
118
+ if payload_length > max_frame_size:
119
+ raise PayloadTooLargeError(
120
+ f"Frame payload length {payload_length} exceeds maximum allowed "
121
+ f"size ({max_frame_size} bytes).",
122
+ payload_length=payload_length,
123
+ max_frame_size=max_frame_size,
124
+ )
125
+
126
+ body_coro = reader.readexactly(payload_length)
127
+ body_bytes = (
128
+ await asyncio.wait_for(body_coro, timeout=timeout)
129
+ if timeout is not None
130
+ else await body_coro
131
+ )
132
+ return msg_type, body_bytes
pylan/core/transfer.py ADDED
@@ -0,0 +1,420 @@
1
+ """Core async file transfer logic with framing, integrity, and cleanup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import dataclass
7
+ import hashlib
8
+ import json
9
+ import logging
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Optional
13
+
14
+ from pylan.core.protocol import (
15
+ MAX_FRAME_SIZE,
16
+ MSG_TYPE_TRANSFER_ACCEPT,
17
+ MSG_TYPE_TRANSFER_CHUNK,
18
+ MSG_TYPE_TRANSFER_COMPLETE,
19
+ MSG_TYPE_TRANSFER_REJECT,
20
+ MSG_TYPE_TRANSFER_REQUEST,
21
+ pack_message,
22
+ read_frame,
23
+ )
24
+ from pylan.errors import ChecksumMismatchError, TransferError
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ DEFAULT_CHUNK_SIZE: int = 64 * 1024
29
+ DEFAULT_TRANSFER_TIMEOUT: float = 10.0
30
+ DEFAULT_HANDSHAKE_TIMEOUT: float = 15.0
31
+
32
+ ProgressCallback = Callable[[int, int], None]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class TransferMetadata:
37
+ """Validated metadata parsed from an incoming transfer request."""
38
+
39
+ file_name: str
40
+ file_size: Optional[int]
41
+ sha256: Optional[str] = None
42
+ sender_alias: Optional[str] = None
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class TransferResult:
47
+ """Outcome summary returned by core send and receive operations."""
48
+
49
+ accepted: bool
50
+ file_name: str
51
+ file_size: int
52
+ bytes_transferred: int
53
+ sha256: str
54
+ file_path: Optional[Path] = None
55
+ rejection_reason: Optional[str] = None
56
+ unexpected_response_type: Optional[int] = None
57
+
58
+
59
+ def compute_file_sha256(
60
+ file_path: str | Path,
61
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
62
+ ) -> str:
63
+ """Compute the lowercase hexadecimal SHA-256 digest of a file."""
64
+ hasher = hashlib.sha256()
65
+ with open(file_path, "rb") as file_obj:
66
+ while chunk := file_obj.read(chunk_size):
67
+ hasher.update(chunk)
68
+ return hasher.hexdigest()
69
+
70
+
71
+ def sanitize_filename(
72
+ raw_name: str,
73
+ default: str = "unnamed_transfer",
74
+ ) -> str:
75
+ """Strip directory traversal components and return a safe base name."""
76
+ cleaned = raw_name.replace("\x00", "").replace("\\", "/")
77
+ candidate = Path(cleaned).name
78
+ if not candidate or candidate in (".", ".."):
79
+ return default
80
+ return candidate
81
+
82
+
83
+ def _part_path_for(target_path: Path) -> Path:
84
+ """Return the temporary ``.part`` path associated with ``target_path``."""
85
+ return target_path.with_suffix(target_path.suffix + ".part")
86
+
87
+
88
+ def resolve_unique_path(directory: str | Path, file_name: str) -> Path:
89
+ """Return a non-colliding path in ``directory`` with ``(1)``, ``(2)``."""
90
+ out_dir = Path(directory)
91
+ safe_name = sanitize_filename(file_name)
92
+ candidate = out_dir / safe_name
93
+ if not candidate.exists() and not _part_path_for(candidate).exists():
94
+ return candidate
95
+
96
+ stem = candidate.stem
97
+ suffix = candidate.suffix
98
+ counter = 1
99
+ while True:
100
+ numbered = out_dir / f"{stem} ({counter}){suffix}"
101
+ if not numbered.exists() and not _part_path_for(numbered).exists():
102
+ return numbered
103
+ counter += 1
104
+
105
+
106
+ def _validate_sha256(raw_digest: Any) -> str:
107
+ """Validate and normalize a hexadecimal SHA-256 digest string."""
108
+ if (
109
+ not isinstance(raw_digest, str)
110
+ or len(raw_digest) != 64
111
+ or not all(ch in "0123456789abcdefABCDEF" for ch in raw_digest)
112
+ ):
113
+ raise ValueError("Invalid sha256 digest in transfer metadata.")
114
+ return raw_digest.lower()
115
+
116
+
117
+ def parse_transfer_request(
118
+ initial_body: bytes,
119
+ default_name: str = "unnamed_transfer",
120
+ ) -> TransferMetadata:
121
+ """Parse and validate a JSON ``MSG_TYPE_TRANSFER_REQUEST`` body.
122
+
123
+ Args:
124
+ initial_body: Raw UTF-8 JSON payload from the transfer request frame.
125
+ default_name: Fallback file name when none is supplied.
126
+
127
+ Returns:
128
+ A validated :class:`TransferMetadata` instance.
129
+
130
+ Raises:
131
+ ValueError: If the payload is not a JSON object or has invalid fields.
132
+ UnicodeDecodeError: If ``initial_body`` is not valid UTF-8.
133
+ json.JSONDecodeError: If ``initial_body`` is not valid JSON.
134
+ """
135
+ meta: Any = json.loads(initial_body.decode("utf-8"))
136
+ if not isinstance(meta, dict):
137
+ raise ValueError("Transfer metadata must be a JSON object.")
138
+
139
+ raw_name = meta.get("file_name")
140
+ file_name = (
141
+ sanitize_filename(raw_name, default=default_name)
142
+ if isinstance(raw_name, str)
143
+ else default_name
144
+ )
145
+
146
+ raw_size = meta.get("file_size")
147
+ file_size: Optional[int] = None
148
+ if raw_size is not None:
149
+ if isinstance(raw_size, bool) or not isinstance(raw_size, int):
150
+ raise ValueError("Invalid file_size in transfer metadata.")
151
+ if raw_size < 0:
152
+ raise ValueError("file_size cannot be negative.")
153
+ file_size = raw_size
154
+
155
+ raw_sha256 = meta.get("sha256")
156
+ sha256 = _validate_sha256(raw_sha256) if raw_sha256 is not None else None
157
+
158
+ raw_alias = meta.get("alias")
159
+ sender_alias = str(raw_alias) if raw_alias is not None else None
160
+
161
+ return TransferMetadata(
162
+ file_name=file_name,
163
+ file_size=file_size,
164
+ sha256=sha256,
165
+ sender_alias=sender_alias,
166
+ )
167
+
168
+
169
+ async def send_file(
170
+ host: str,
171
+ port: int,
172
+ file_path: str | Path,
173
+ *,
174
+ sender_alias: Optional[str] = None,
175
+ timeout: float = DEFAULT_TRANSFER_TIMEOUT,
176
+ handshake_timeout: float = DEFAULT_HANDSHAKE_TIMEOUT,
177
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
178
+ max_frame_size: int = MAX_FRAME_SIZE,
179
+ on_progress: Optional[ProgressCallback] = None,
180
+ ) -> TransferResult:
181
+ """Connect to a remote PyLan receiver and stream a file over TCP.
182
+
183
+ Args:
184
+ host: Destination IPv4 address or hostname.
185
+ port: Destination TCP port.
186
+ file_path: Local path to the regular file to transmit.
187
+ sender_alias: Optional sender display alias sent in request metadata.
188
+ timeout: TCP connection timeout in seconds.
189
+ handshake_timeout: Timeout in seconds for reading the receiver's
190
+ accept/reject response frame.
191
+ chunk_size: Maximum payload bytes per ``MSG_TYPE_TRANSFER_CHUNK``
192
+ frame.
193
+ max_frame_size: Maximum control response frame size accepted.
194
+ on_progress: Optional callback invoked as
195
+ ``(bytes_sent, total_bytes)``.
196
+
197
+ Returns:
198
+ A :class:`TransferResult` describing whether the transfer was accepted
199
+ and the number of bytes transmitted.
200
+
201
+ Raises:
202
+ FileNotFoundError: If ``file_path`` does not point to a regular file.
203
+ ConnectionError: If connecting fails or the peer disconnects
204
+ mid-stream.
205
+ PayloadTooLargeError: If the receiver sends an oversized response
206
+ frame.
207
+ """
208
+ path = Path(file_path)
209
+ if not path.is_file():
210
+ raise FileNotFoundError(f"File not found: {file_path}")
211
+
212
+ file_name = path.name
213
+ file_size = path.stat().st_size
214
+
215
+ try:
216
+ reader, writer = await asyncio.wait_for(
217
+ asyncio.open_connection(host, port),
218
+ timeout=timeout,
219
+ )
220
+ except (OSError, asyncio.TimeoutError) as exc:
221
+ raise ConnectionError(
222
+ f"Could not connect to {host}:{port}: {exc}"
223
+ ) from exc
224
+
225
+ try:
226
+ request_payload: dict[str, Any] = {
227
+ "file_name": file_name,
228
+ "file_size": file_size,
229
+ }
230
+ if sender_alias is not None:
231
+ request_payload["alias"] = sender_alias
232
+
233
+ writer.write(pack_message(MSG_TYPE_TRANSFER_REQUEST, request_payload))
234
+ await writer.drain()
235
+
236
+ msg_type, body = await read_frame(
237
+ reader,
238
+ max_frame_size=max_frame_size,
239
+ timeout=handshake_timeout,
240
+ )
241
+
242
+ if msg_type != MSG_TYPE_TRANSFER_ACCEPT:
243
+ reason: Optional[str] = None
244
+ if msg_type == MSG_TYPE_TRANSFER_REJECT:
245
+ reason = "rejected by receiver"
246
+ try:
247
+ response = json.loads(body.decode("utf-8"))
248
+ if isinstance(response, dict):
249
+ reason = str(response.get("reason", "unknown"))
250
+ except Exception:
251
+ pass
252
+ return TransferResult(
253
+ accepted=False,
254
+ file_name=file_name,
255
+ file_size=file_size,
256
+ bytes_transferred=0,
257
+ sha256="",
258
+ file_path=path,
259
+ rejection_reason=reason,
260
+ unexpected_response_type=(
261
+ None if msg_type == MSG_TYPE_TRANSFER_REJECT else msg_type
262
+ ),
263
+ )
264
+
265
+ sent_bytes = 0
266
+ hasher = hashlib.sha256()
267
+ with open(path, "rb") as file_obj:
268
+ while chunk := file_obj.read(chunk_size):
269
+ hasher.update(chunk)
270
+ writer.write(pack_message(MSG_TYPE_TRANSFER_CHUNK, chunk))
271
+ await writer.drain()
272
+ sent_bytes += len(chunk)
273
+ if on_progress is not None:
274
+ on_progress(sent_bytes, file_size)
275
+
276
+ sha256 = hasher.hexdigest()
277
+ writer.write(
278
+ pack_message(MSG_TYPE_TRANSFER_COMPLETE, {"sha256": sha256})
279
+ )
280
+ await writer.drain()
281
+
282
+ return TransferResult(
283
+ accepted=True,
284
+ file_name=file_name,
285
+ file_size=file_size,
286
+ bytes_transferred=sent_bytes,
287
+ sha256=sha256,
288
+ file_path=path,
289
+ )
290
+ except (asyncio.IncompleteReadError, ConnectionResetError) as exc:
291
+ raise ConnectionError(
292
+ "Peer disconnected prematurely during transfer."
293
+ ) from exc
294
+ finally:
295
+ writer.close()
296
+ try:
297
+ await writer.wait_closed()
298
+ except Exception:
299
+ pass
300
+
301
+
302
+ async def receive_file(
303
+ reader: asyncio.StreamReader,
304
+ writer: asyncio.StreamWriter,
305
+ output_dir: str | Path,
306
+ metadata: TransferMetadata,
307
+ *,
308
+ max_frame_size: int = MAX_FRAME_SIZE,
309
+ on_progress: Optional[ProgressCallback] = None,
310
+ ) -> TransferResult:
311
+ """Accept an incoming file transfer, verify integrity, and save atomically.
312
+
313
+ Writes incoming chunks into a temporary ``.part`` file, cleans it up if any
314
+ framing, I/O, size, or SHA-256 verification error occurs, and atomically
315
+ moves the completed file to a collision-safe target path via
316
+ :func:`os.replace`.
317
+
318
+ Args:
319
+ reader: Stream reader connected to the sending peer.
320
+ writer: Stream writer connected to the sending peer.
321
+ output_dir: Target directory where the received file will be stored.
322
+ metadata: Validated metadata from the initial transfer request.
323
+ max_frame_size: Maximum payload size allowed per incoming frame.
324
+ on_progress: Optional callback invoked as
325
+ ``(bytes_received, expected_total_bytes)``.
326
+
327
+ Returns:
328
+ A :class:`TransferResult` pointing to the saved file and SHA-256
329
+ digest.
330
+
331
+ Raises:
332
+ PayloadTooLargeError: If an incoming frame exceeds ``max_frame_size``.
333
+ ChecksumMismatchError: If the computed SHA-256 digest does not match
334
+ the expected digest.
335
+ TransferError: If an unexpected frame type or size mismatch occurs.
336
+ asyncio.IncompleteReadError: If the sender disconnects prematurely.
337
+ """
338
+ out_dir = Path(output_dir)
339
+ out_dir.mkdir(parents=True, exist_ok=True)
340
+ target_path = resolve_unique_path(out_dir, metadata.file_name)
341
+ part_path = _part_path_for(target_path)
342
+
343
+ writer.write(pack_message(MSG_TYPE_TRANSFER_ACCEPT, {}))
344
+ await writer.drain()
345
+
346
+ hasher = hashlib.sha256()
347
+ received_bytes = 0
348
+ expected_total = metadata.file_size or 0
349
+ complete_sha256: Optional[str] = None
350
+ completed = False
351
+ renamed = False
352
+
353
+ try:
354
+ with open(part_path, "wb") as out_file:
355
+ while True:
356
+ msg_type, body = await read_frame(
357
+ reader,
358
+ max_frame_size=max_frame_size,
359
+ )
360
+ if msg_type == MSG_TYPE_TRANSFER_CHUNK:
361
+ out_file.write(body)
362
+ hasher.update(body)
363
+ received_bytes += len(body)
364
+ if on_progress is not None:
365
+ on_progress(received_bytes, expected_total)
366
+ elif msg_type == MSG_TYPE_TRANSFER_COMPLETE:
367
+ if body:
368
+ try:
369
+ complete_meta = json.loads(body.decode("utf-8"))
370
+ except Exception:
371
+ complete_meta = None
372
+ if isinstance(complete_meta, dict):
373
+ raw_complete_sha = complete_meta.get("sha256")
374
+ if raw_complete_sha is not None:
375
+ complete_sha256 = _validate_sha256(
376
+ raw_complete_sha
377
+ )
378
+ completed = True
379
+ break
380
+ else:
381
+ raise TransferError(
382
+ f"Unexpected transfer message type: {msg_type}"
383
+ )
384
+
385
+ if not completed:
386
+ raise TransferError("Transfer did not complete cleanly.")
387
+
388
+ if (
389
+ metadata.file_size is not None
390
+ and received_bytes != metadata.file_size
391
+ ):
392
+ raise TransferError(
393
+ f"Transfer size mismatch: expected {metadata.file_size} "
394
+ f"bytes, received {received_bytes} bytes."
395
+ )
396
+
397
+ actual_sha256 = hasher.hexdigest()
398
+ for expected_sha in (metadata.sha256, complete_sha256):
399
+ if expected_sha is not None and actual_sha256 != expected_sha:
400
+ raise ChecksumMismatchError(
401
+ f"SHA-256 mismatch for '{metadata.file_name}': "
402
+ f"expected {expected_sha}, got {actual_sha256}."
403
+ )
404
+
405
+ if target_path.exists():
406
+ target_path = resolve_unique_path(out_dir, metadata.file_name)
407
+ os.replace(part_path, target_path)
408
+ renamed = True
409
+
410
+ return TransferResult(
411
+ accepted=True,
412
+ file_name=target_path.name,
413
+ file_size=received_bytes,
414
+ bytes_transferred=received_bytes,
415
+ sha256=actual_sha256,
416
+ file_path=target_path,
417
+ )
418
+ finally:
419
+ if not renamed:
420
+ part_path.unlink(missing_ok=True)
@@ -0,0 +1,28 @@
1
+ """Exception hierarchy for PyLan."""
2
+
3
+ from pylan.errors.base import PylanException
4
+
5
+
6
+ class ProtocolError(PylanException):
7
+ """Base exception for protocol framing and serialization errors."""
8
+
9
+
10
+ class PayloadTooLargeError(ProtocolError, ValueError):
11
+ """Raised when an incoming frame exceeds the maximum allowed size."""
12
+
13
+
14
+ class TransferError(PylanException):
15
+ """Base exception for file transfer errors."""
16
+
17
+
18
+ class ChecksumMismatchError(TransferError, ValueError):
19
+ """Raised when a received file fails integrity verification."""
20
+
21
+
22
+ __all__: list[str] = [
23
+ "ChecksumMismatchError",
24
+ "PayloadTooLargeError",
25
+ "ProtocolError",
26
+ "PylanException",
27
+ "TransferError",
28
+ ]
pylan/errors/base.py ADDED
@@ -0,0 +1,13 @@
1
+ """Exception handling module for pylan"""
2
+
3
+ from typing import Any
4
+
5
+
6
+ class PylanException(Exception):
7
+ """root exception for all pylan related failures."""
8
+
9
+ def __init__(self, message: str, *args: Any, **kwargs: Any) -> None:
10
+ super().__init__(message, *args)
11
+
12
+ for key, value in kwargs.items():
13
+ setattr(self, key, value)
pylan/main.py ADDED
@@ -0,0 +1,6 @@
1
+ """Direct console script entrypoint for PyLan."""
2
+
3
+ from pylan.__main__ import main
4
+
5
+ if __name__ == "__main__":
6
+ main()