python-sendparcel 0.1.1__tar.gz → 0.2.0__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.
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/PKG-INFO +5 -14
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/pyproject.toml +13 -14
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/__init__.py +10 -1
- python_sendparcel-0.2.0/src/sendparcel/batch.py +303 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/enums.py +1 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/flow.py +123 -22
- python_sendparcel-0.2.0/src/sendparcel/fsm.py +106 -0
- python_sendparcel-0.2.0/src/sendparcel/logging.py +155 -0
- python_sendparcel-0.2.0/src/sendparcel/protocols.py +75 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/registry.py +60 -28
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/conftest.py +54 -1
- python_sendparcel-0.2.0/tests/test_batch.py +446 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_enums.py +21 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_flow.py +68 -3
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_fsm.py +1 -3
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_integration.py +2 -1
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_protocols.py +32 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_public_api.py +6 -0
- python_sendparcel-0.1.1/src/sendparcel/fsm.py +0 -99
- python_sendparcel-0.1.1/src/sendparcel/protocols.py +0 -26
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/.github/workflows/ci.yml +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/.github/workflows/ecosystem-smoke.yml +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/.github/workflows/release.yml +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/.gitignore +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/.pre-commit-config.yaml +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/CHANGELOG.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/CONTRIBUTING.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/LICENSE +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/README.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/Makefile +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/compatibility-matrix.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/conf.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/getting-started.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/index.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/installation-matrix.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/plans/2026-02-17-order-optional.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/provider-authoring.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/release-policy.md +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/docs/requirements.txt +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/exceptions.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/provider.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/providers/__init__.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/providers/dummy.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/py.typed +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/types.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/src/sendparcel/validators.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_builtin_dummy_provider.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_exceptions.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_provider.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_registry.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_types.py +0 -0
- {python_sendparcel-0.1.1 → python_sendparcel-0.2.0}/tests/test_validators.py +0 -0
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-sendparcel
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Framework-agnostic parcel shipping core for Python.
|
|
5
|
-
Project-URL: Homepage, https://github.com/sendparcel/python-sendparcel
|
|
6
|
-
Project-URL:
|
|
7
|
-
Project-URL:
|
|
8
|
-
Project-URL:
|
|
9
|
-
Project-URL: Issue Tracker, https://github.com/sendparcel/python-sendparcel/issues
|
|
5
|
+
Project-URL: Homepage, https://github.com/python-sendparcel/python-sendparcel
|
|
6
|
+
Project-URL: Repository, https://github.com/python-sendparcel/python-sendparcel
|
|
7
|
+
Project-URL: Changelog, https://github.com/python-sendparcel/python-sendparcel/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issue Tracker, https://github.com/python-sendparcel/python-sendparcel/issues
|
|
10
9
|
Author-email: Dominik Kozaczko <dominik@kozaczko.info>
|
|
11
10
|
License: MIT
|
|
12
11
|
License-File: LICENSE
|
|
@@ -25,8 +24,6 @@ Requires-Dist: anyio>=4.0
|
|
|
25
24
|
Requires-Dist: httpx>=0.27.0
|
|
26
25
|
Provides-Extra: all
|
|
27
26
|
Requires-Dist: django-sendparcel>=0.1.0; extra == 'all'
|
|
28
|
-
Requires-Dist: fastapi-sendparcel>=0.1.0; extra == 'all'
|
|
29
|
-
Requires-Dist: litestar-sendparcel>=0.1.0; extra == 'all'
|
|
30
27
|
Requires-Dist: python-sendparcel-cli>=0.1.0; extra == 'all'
|
|
31
28
|
Requires-Dist: python-sendparcel-dpdpl>=0.1.0; extra == 'all'
|
|
32
29
|
Requires-Dist: python-sendparcel-inpost>=0.1.0; extra == 'all'
|
|
@@ -45,16 +42,10 @@ Requires-Dist: django-sendparcel>=0.1.0; extra == 'django'
|
|
|
45
42
|
Provides-Extra: dpdpl
|
|
46
43
|
Requires-Dist: python-sendparcel-dpdpl>=0.1.0; extra == 'dpdpl'
|
|
47
44
|
Provides-Extra: dummy
|
|
48
|
-
Provides-Extra: fastapi
|
|
49
|
-
Requires-Dist: fastapi-sendparcel>=0.1.0; extra == 'fastapi'
|
|
50
45
|
Provides-Extra: frameworks
|
|
51
46
|
Requires-Dist: django-sendparcel>=0.1.0; extra == 'frameworks'
|
|
52
|
-
Requires-Dist: fastapi-sendparcel>=0.1.0; extra == 'frameworks'
|
|
53
|
-
Requires-Dist: litestar-sendparcel>=0.1.0; extra == 'frameworks'
|
|
54
47
|
Provides-Extra: inpost
|
|
55
48
|
Requires-Dist: python-sendparcel-inpost>=0.1.0; extra == 'inpost'
|
|
56
|
-
Provides-Extra: litestar
|
|
57
|
-
Requires-Dist: litestar-sendparcel>=0.1.0; extra == 'litestar'
|
|
58
49
|
Provides-Extra: providers
|
|
59
50
|
Requires-Dist: python-sendparcel-dpdpl>=0.1.0; extra == 'providers'
|
|
60
51
|
Requires-Dist: python-sendparcel-inpost>=0.1.0; extra == 'providers'
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "python-sendparcel"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
description = "Framework-agnostic parcel shipping core for Python."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = { text = "MIT" }
|
|
@@ -32,32 +32,32 @@ dev = [
|
|
|
32
32
|
]
|
|
33
33
|
dummy = []
|
|
34
34
|
django = ["django-sendparcel>=0.1.0"]
|
|
35
|
-
fastapi = ["fastapi-sendparcel>=0.1.0"]
|
|
36
|
-
litestar = ["litestar-sendparcel>=0.1.0"]
|
|
35
|
+
# fastapi = ["fastapi-sendparcel>=0.1.0"]
|
|
36
|
+
# litestar = ["litestar-sendparcel>=0.1.0"]
|
|
37
37
|
inpost = ["python-sendparcel-inpost>=0.1.0"]
|
|
38
38
|
dpdpl = ["python-sendparcel-dpdpl>=0.1.0"]
|
|
39
39
|
cli = ["python-sendparcel-cli>=0.1.0"]
|
|
40
40
|
providers = ["python-sendparcel-inpost>=0.1.0", "python-sendparcel-dpdpl>=0.1.0"]
|
|
41
41
|
frameworks = [
|
|
42
42
|
"django-sendparcel>=0.1.0",
|
|
43
|
-
"fastapi-sendparcel>=0.1.0",
|
|
44
|
-
"litestar-sendparcel>=0.1.0",
|
|
43
|
+
# "fastapi-sendparcel>=0.1.0",
|
|
44
|
+
# "litestar-sendparcel>=0.1.0",
|
|
45
45
|
]
|
|
46
46
|
all = [
|
|
47
47
|
"django-sendparcel>=0.1.0",
|
|
48
|
-
"fastapi-sendparcel>=0.1.0",
|
|
49
|
-
"litestar-sendparcel>=0.1.0",
|
|
48
|
+
# "fastapi-sendparcel>=0.1.0",
|
|
49
|
+
# "litestar-sendparcel>=0.1.0",
|
|
50
50
|
"python-sendparcel-inpost>=0.1.0",
|
|
51
51
|
"python-sendparcel-dpdpl>=0.1.0",
|
|
52
52
|
"python-sendparcel-cli>=0.1.0",
|
|
53
53
|
]
|
|
54
54
|
|
|
55
55
|
[project.urls]
|
|
56
|
-
Homepage = "https://github.com/sendparcel/python-sendparcel"
|
|
57
|
-
Documentation = "https://python-sendparcel.readthedocs.io/"
|
|
58
|
-
Repository = "https://github.com/sendparcel/python-sendparcel"
|
|
59
|
-
Changelog = "https://github.com/sendparcel/python-sendparcel/blob/main/CHANGELOG.md"
|
|
60
|
-
"Issue Tracker" = "https://github.com/sendparcel/python-sendparcel/issues"
|
|
56
|
+
Homepage = "https://github.com/python-sendparcel/python-sendparcel"
|
|
57
|
+
# Documentation = "https://python-sendparcel.readthedocs.io/"
|
|
58
|
+
Repository = "https://github.com/python-sendparcel/python-sendparcel"
|
|
59
|
+
Changelog = "https://github.com/python-sendparcel/python-sendparcel/blob/main/CHANGELOG.md"
|
|
60
|
+
"Issue Tracker" = "https://github.com/python-sendparcel/python-sendparcel/issues"
|
|
61
61
|
|
|
62
62
|
[build-system]
|
|
63
63
|
requires = ["hatchling"]
|
|
@@ -82,6 +82,7 @@ ignore = ["N818", "B027"]
|
|
|
82
82
|
|
|
83
83
|
[tool.ruff.lint.per-file-ignores]
|
|
84
84
|
"tests/**" = ["RUF012"]
|
|
85
|
+
"docs/**" = ["A001"]
|
|
85
86
|
|
|
86
87
|
[tool.ty.environment]
|
|
87
88
|
python-version = "3.12"
|
|
@@ -98,8 +99,6 @@ invalid-return-type = "ignore"
|
|
|
98
99
|
|
|
99
100
|
[tool.uv.sources]
|
|
100
101
|
django-sendparcel = { path = "../django-sendparcel", editable = true }
|
|
101
|
-
fastapi-sendparcel = { path = "../fastapi-sendparcel", editable = true }
|
|
102
|
-
litestar-sendparcel = { path = "../litestar-sendparcel", editable = true }
|
|
103
102
|
python-sendparcel-inpost = { path = "../python-sendparcel-inpost", editable = true }
|
|
104
103
|
python-sendparcel-dpdpl = { path = "../python-sendparcel-dpdpl", editable = true }
|
|
105
104
|
python-sendparcel-cli = { path = "../python-sendparcel-cli", editable = true }
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""sendparcel core package."""
|
|
2
2
|
|
|
3
|
-
__version__ = "0.
|
|
3
|
+
__version__ = "0.2.0"
|
|
4
4
|
|
|
5
|
+
from sendparcel.batch import BatchCreateResult, BatchResult, ShipmentBatch
|
|
5
6
|
from sendparcel.enums import ConfirmationMethod, LabelFormat, ShipmentStatus
|
|
6
7
|
from sendparcel.exceptions import (
|
|
7
8
|
CommunicationError,
|
|
@@ -13,6 +14,7 @@ from sendparcel.exceptions import (
|
|
|
13
14
|
ShipmentNotFoundError,
|
|
14
15
|
)
|
|
15
16
|
from sendparcel.flow import ShipmentFlow
|
|
17
|
+
from sendparcel.logging import configure_logging, get_logger
|
|
16
18
|
from sendparcel.provider import (
|
|
17
19
|
BaseProvider,
|
|
18
20
|
CancellableProvider,
|
|
@@ -26,10 +28,13 @@ from sendparcel.types import (
|
|
|
26
28
|
CreateLabelOutcome,
|
|
27
29
|
CreateShipmentOutcome,
|
|
28
30
|
ShipmentUpdateOutcome,
|
|
31
|
+
ShipmentUpdateResult,
|
|
29
32
|
)
|
|
30
33
|
|
|
31
34
|
__all__ = [
|
|
32
35
|
"BaseProvider",
|
|
36
|
+
"BatchCreateResult",
|
|
37
|
+
"BatchResult",
|
|
33
38
|
"CancellableProvider",
|
|
34
39
|
"CommunicationError",
|
|
35
40
|
"ConfirmationMethod",
|
|
@@ -45,10 +50,14 @@ __all__ = [
|
|
|
45
50
|
"PullStatusProvider",
|
|
46
51
|
"PushCallbackProvider",
|
|
47
52
|
"SendParcelException",
|
|
53
|
+
"ShipmentBatch",
|
|
48
54
|
"ShipmentFlow",
|
|
49
55
|
"ShipmentNotFoundError",
|
|
50
56
|
"ShipmentStatus",
|
|
51
57
|
"ShipmentUpdateOutcome",
|
|
58
|
+
"ShipmentUpdateResult",
|
|
52
59
|
"__version__",
|
|
60
|
+
"configure_logging",
|
|
61
|
+
"get_logger",
|
|
53
62
|
"registry",
|
|
54
63
|
]
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Batch shipment operations for sendparcel.
|
|
2
|
+
|
|
3
|
+
Provides batch creation, status fetching, and cancellation of shipments.
|
|
4
|
+
Designed for efficiency when processing multiple shipments at once.
|
|
5
|
+
|
|
6
|
+
Usage::
|
|
7
|
+
|
|
8
|
+
from sendparcel.batch import ShipmentBatch
|
|
9
|
+
|
|
10
|
+
batch = ShipmentBatch(repository=repo, config=config)
|
|
11
|
+
results = await batch.create_shipments(
|
|
12
|
+
[
|
|
13
|
+
{
|
|
14
|
+
"provider_slug": "inpost-courier",
|
|
15
|
+
"sender_address": {...},
|
|
16
|
+
"receiver_address": {...},
|
|
17
|
+
"parcels": [...],
|
|
18
|
+
},
|
|
19
|
+
# ... more shipments
|
|
20
|
+
]
|
|
21
|
+
)
|
|
22
|
+
for result in results:
|
|
23
|
+
if result.success:
|
|
24
|
+
print(f"Created {result.shipment.tracking_number}")
|
|
25
|
+
else:
|
|
26
|
+
print(f"Failed: {result.error}")
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import asyncio
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from sendparcel.flow import ShipmentFlow
|
|
36
|
+
from sendparcel.logging import get_logger
|
|
37
|
+
from sendparcel.protocols import ShipmentRepository
|
|
38
|
+
from sendparcel.registry import PluginRegistry
|
|
39
|
+
|
|
40
|
+
logger = get_logger(__name__)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class BatchResult:
|
|
45
|
+
"""Result of a single batch operation."""
|
|
46
|
+
|
|
47
|
+
index: int
|
|
48
|
+
success: bool
|
|
49
|
+
shipment: Any | None = None
|
|
50
|
+
error: str | None = None
|
|
51
|
+
outcome: Any | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class BatchCreateResult:
|
|
56
|
+
"""Result of a batch create operation."""
|
|
57
|
+
|
|
58
|
+
total: int
|
|
59
|
+
successful: int
|
|
60
|
+
failed: int
|
|
61
|
+
results: list[BatchResult] = field(default_factory=list)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def success(self) -> bool:
|
|
65
|
+
"""True if all shipments were created successfully."""
|
|
66
|
+
return self.failed == 0
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def summary(self) -> dict[str, Any]:
|
|
70
|
+
"""Return a summary of the batch operation."""
|
|
71
|
+
return {
|
|
72
|
+
"total": self.total,
|
|
73
|
+
"successful": self.successful,
|
|
74
|
+
"failed": self.failed,
|
|
75
|
+
"success_rate": (
|
|
76
|
+
round(self.successful / self.total * 100, 2)
|
|
77
|
+
if self.total > 0
|
|
78
|
+
else 0.0
|
|
79
|
+
),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ShipmentBatch:
|
|
84
|
+
"""Batch shipment operations.
|
|
85
|
+
|
|
86
|
+
Provides efficient batch creation, status fetching, and cancellation
|
|
87
|
+
of shipments. All operations are atomic within the batch — if one
|
|
88
|
+
shipment fails, the others are still processed.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
repository: Shipment repository for persisting results.
|
|
92
|
+
config: Provider configuration.
|
|
93
|
+
registry: Provider registry (defaults to module-level singleton).
|
|
94
|
+
max_concurrent: Maximum number of concurrent provider calls
|
|
95
|
+
(default: 5).
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
repository: ShipmentRepository,
|
|
101
|
+
config: dict[str, Any] | None = None,
|
|
102
|
+
registry: PluginRegistry | None = None,
|
|
103
|
+
max_concurrent: int = 5,
|
|
104
|
+
) -> None:
|
|
105
|
+
self.repository = repository
|
|
106
|
+
self.config = config or {}
|
|
107
|
+
self.registry = registry or PluginRegistry()
|
|
108
|
+
self.max_concurrent = max_concurrent
|
|
109
|
+
|
|
110
|
+
async def create_shipments(
|
|
111
|
+
self,
|
|
112
|
+
shipments: list[dict[str, Any]],
|
|
113
|
+
) -> BatchCreateResult:
|
|
114
|
+
"""Create multiple shipments in a batch.
|
|
115
|
+
|
|
116
|
+
Each shipment dict must contain:
|
|
117
|
+
- provider_slug: Provider identifier
|
|
118
|
+
- sender_address: Sender address info
|
|
119
|
+
- receiver_address: Receiver address info
|
|
120
|
+
- parcels: List of parcel definitions
|
|
121
|
+
- Optional: idempotency_key, reference_id, and other kwargs
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
shipments: List of shipment dicts to create.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
BatchCreateResult with per-shipment results.
|
|
128
|
+
"""
|
|
129
|
+
semaphore = asyncio.Semaphore(self.max_concurrent)
|
|
130
|
+
|
|
131
|
+
async def _create_one(
|
|
132
|
+
index: int, shipment_data: dict[str, Any]
|
|
133
|
+
) -> BatchResult:
|
|
134
|
+
async with semaphore:
|
|
135
|
+
return await self._create_single_shipment(index, shipment_data)
|
|
136
|
+
|
|
137
|
+
results = await asyncio.gather(
|
|
138
|
+
*(_create_one(i, d) for i, d in enumerate(shipments))
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
successful = sum(1 for r in results if r.success)
|
|
142
|
+
failed = sum(1 for r in results if not r.success)
|
|
143
|
+
|
|
144
|
+
# Sort by original index to preserve input order.
|
|
145
|
+
results.sort(key=lambda r: r.index)
|
|
146
|
+
|
|
147
|
+
return BatchCreateResult(
|
|
148
|
+
total=len(shipments),
|
|
149
|
+
successful=successful,
|
|
150
|
+
failed=failed,
|
|
151
|
+
results=results,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
async def _create_single_shipment(
|
|
155
|
+
self, index: int, shipment_data: dict[str, Any]
|
|
156
|
+
) -> BatchResult:
|
|
157
|
+
provider_slug = shipment_data.get("provider_slug")
|
|
158
|
+
if not provider_slug:
|
|
159
|
+
return BatchResult(
|
|
160
|
+
index=index,
|
|
161
|
+
success=False,
|
|
162
|
+
error="Missing provider_slug",
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
self.registry.get_by_slug(provider_slug)
|
|
167
|
+
|
|
168
|
+
flow = ShipmentFlow(
|
|
169
|
+
repository=self.repository,
|
|
170
|
+
config=self.config,
|
|
171
|
+
registry=self.registry,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
outcome = await flow.create_shipment(
|
|
175
|
+
provider_slug=provider_slug,
|
|
176
|
+
sender_address=shipment_data["sender_address"],
|
|
177
|
+
receiver_address=shipment_data["receiver_address"],
|
|
178
|
+
parcels=shipment_data["parcels"],
|
|
179
|
+
**{
|
|
180
|
+
k: v
|
|
181
|
+
for k, v in shipment_data.items()
|
|
182
|
+
if k
|
|
183
|
+
not in (
|
|
184
|
+
"provider_slug",
|
|
185
|
+
"sender_address",
|
|
186
|
+
"receiver_address",
|
|
187
|
+
"parcels",
|
|
188
|
+
)
|
|
189
|
+
},
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
logger.info(
|
|
193
|
+
"Batch create: shipment %d created successfully "
|
|
194
|
+
"(provider=%s, tracking=%s)",
|
|
195
|
+
index,
|
|
196
|
+
provider_slug,
|
|
197
|
+
outcome.shipment.tracking_number,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
return BatchResult(
|
|
201
|
+
index=index,
|
|
202
|
+
success=True,
|
|
203
|
+
shipment=outcome.shipment,
|
|
204
|
+
outcome=outcome,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
except Exception as exc:
|
|
208
|
+
logger.warning(
|
|
209
|
+
"Batch create: shipment %d failed: %s",
|
|
210
|
+
index,
|
|
211
|
+
exc,
|
|
212
|
+
)
|
|
213
|
+
return BatchResult(
|
|
214
|
+
index=index,
|
|
215
|
+
success=False,
|
|
216
|
+
error=str(exc),
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
async def fetch_statuses(
|
|
220
|
+
self,
|
|
221
|
+
shipment_ids: list[str],
|
|
222
|
+
) -> list[BatchResult]:
|
|
223
|
+
"""Fetch statuses for multiple shipments.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
shipment_ids: List of shipment IDs to fetch.
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
List of BatchResult with per-shipment status updates.
|
|
230
|
+
"""
|
|
231
|
+
semaphore = asyncio.Semaphore(self.max_concurrent)
|
|
232
|
+
|
|
233
|
+
async def _fetch_one(index: int, sid: str) -> BatchResult:
|
|
234
|
+
async with semaphore:
|
|
235
|
+
try:
|
|
236
|
+
shipment = await self.repository.get_by_id(sid)
|
|
237
|
+
flow = ShipmentFlow(
|
|
238
|
+
repository=self.repository,
|
|
239
|
+
config=self.config,
|
|
240
|
+
registry=self.registry,
|
|
241
|
+
)
|
|
242
|
+
outcome = await flow.fetch_and_update_status(shipment)
|
|
243
|
+
return BatchResult(
|
|
244
|
+
index=index,
|
|
245
|
+
success=True,
|
|
246
|
+
shipment=outcome.shipment,
|
|
247
|
+
outcome=outcome,
|
|
248
|
+
)
|
|
249
|
+
except Exception as exc:
|
|
250
|
+
return BatchResult(
|
|
251
|
+
index=index,
|
|
252
|
+
success=False,
|
|
253
|
+
error=str(exc),
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
results = await asyncio.gather(
|
|
257
|
+
*(_fetch_one(i, sid) for i, sid in enumerate(shipment_ids))
|
|
258
|
+
)
|
|
259
|
+
results.sort(key=lambda r: r.index)
|
|
260
|
+
return results
|
|
261
|
+
|
|
262
|
+
async def cancel_shipments(
|
|
263
|
+
self,
|
|
264
|
+
shipment_ids: list[str],
|
|
265
|
+
) -> list[BatchResult]:
|
|
266
|
+
"""Cancel multiple shipments.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
shipment_ids: List of shipment IDs to cancel.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
List of BatchResult with per-shipment cancellation results.
|
|
273
|
+
"""
|
|
274
|
+
semaphore = asyncio.Semaphore(self.max_concurrent)
|
|
275
|
+
|
|
276
|
+
async def _cancel_one(index: int, sid: str) -> BatchResult:
|
|
277
|
+
async with semaphore:
|
|
278
|
+
try:
|
|
279
|
+
shipment = await self.repository.get_by_id(sid)
|
|
280
|
+
flow = ShipmentFlow(
|
|
281
|
+
repository=self.repository,
|
|
282
|
+
config=self.config,
|
|
283
|
+
registry=self.registry,
|
|
284
|
+
)
|
|
285
|
+
cancelled = await flow.cancel_shipment(shipment)
|
|
286
|
+
return BatchResult(
|
|
287
|
+
index=index,
|
|
288
|
+
success=True,
|
|
289
|
+
shipment=shipment,
|
|
290
|
+
outcome={"cancelled": cancelled},
|
|
291
|
+
)
|
|
292
|
+
except Exception as exc:
|
|
293
|
+
return BatchResult(
|
|
294
|
+
index=index,
|
|
295
|
+
success=False,
|
|
296
|
+
error=str(exc),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
results = await asyncio.gather(
|
|
300
|
+
*(_cancel_one(i, sid) for i, sid in enumerate(shipment_ids))
|
|
301
|
+
)
|
|
302
|
+
results.sort(key=lambda r: r.index)
|
|
303
|
+
return results
|
|
@@ -21,6 +21,8 @@ from sendparcel.provider import (
|
|
|
21
21
|
PullStatusProvider,
|
|
22
22
|
PushCallbackProvider,
|
|
23
23
|
)
|
|
24
|
+
from sendparcel.registry import PluginRegistry
|
|
25
|
+
from sendparcel.registry import registry as default_registry
|
|
24
26
|
from sendparcel.types import (
|
|
25
27
|
AddressInfo,
|
|
26
28
|
CreateLabelOutcome,
|
|
@@ -40,13 +42,11 @@ class ShipmentFlow:
|
|
|
40
42
|
repository: ShipmentRepository,
|
|
41
43
|
config: dict[str, Any] | None = None,
|
|
42
44
|
validators: list[Any] | None = None,
|
|
43
|
-
registry:
|
|
45
|
+
registry: PluginRegistry | None = None,
|
|
44
46
|
) -> None:
|
|
45
47
|
self.repository = repository
|
|
46
48
|
self.config = config or {}
|
|
47
49
|
self.validators = validators or []
|
|
48
|
-
from sendparcel.registry import registry as default_registry
|
|
49
|
-
|
|
50
50
|
self.registry = registry or default_registry
|
|
51
51
|
|
|
52
52
|
async def create_shipment(
|
|
@@ -56,25 +56,98 @@ class ShipmentFlow:
|
|
|
56
56
|
sender_address: AddressInfo,
|
|
57
57
|
receiver_address: AddressInfo,
|
|
58
58
|
parcels: list[ParcelInfo],
|
|
59
|
+
idempotency_key: str | None = None,
|
|
59
60
|
**kwargs: Any,
|
|
60
61
|
) -> CreateShipmentOutcome:
|
|
61
|
-
"""Create a shipment record with explicit address and parcel data.
|
|
62
|
+
"""Create a shipment record with explicit address and parcel data.
|
|
63
|
+
|
|
64
|
+
Uses persistence-enforced idempotency: if a shipment with the same
|
|
65
|
+
provider + idempotency_key already exists, it is returned without
|
|
66
|
+
calling the provider again.
|
|
67
|
+
|
|
68
|
+
On provider failure:
|
|
69
|
+
- CommunicationError (timeout, network): marks shipment as
|
|
70
|
+
``SUBMITTED`` (ambiguous — provider may have accepted).
|
|
71
|
+
The caller should reconcile via polling or callback.
|
|
72
|
+
- Other errors: marks shipment as ``FAILED`` and re-raises.
|
|
73
|
+
|
|
74
|
+
The shipment record is never deleted on failure, ensuring that
|
|
75
|
+
retries and reconciliation always have a record to work with.
|
|
62
76
|
|
|
77
|
+
Args:
|
|
78
|
+
provider_slug: Provider identifier.
|
|
79
|
+
sender_address: Sender address info.
|
|
80
|
+
receiver_address: Receiver address info.
|
|
81
|
+
parcels: List of parcel definitions.
|
|
82
|
+
idempotency_key: Optional key for retry safety. Stored in the
|
|
83
|
+
``reference_id`` field of the shipment record.
|
|
84
|
+
**kwargs: Passed to the provider (after repo-only fields
|
|
85
|
+
are stripped).
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
CreateShipmentOutcome with the persisted shipment and
|
|
89
|
+
optional label payload.
|
|
90
|
+
"""
|
|
63
91
|
self.registry.get_by_slug(provider_slug)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
92
|
+
|
|
93
|
+
# Separate repository kwargs from provider kwargs.
|
|
94
|
+
repo_kwargs: dict[str, Any] = {}
|
|
95
|
+
for key in ("reference_id",):
|
|
96
|
+
if key in kwargs:
|
|
97
|
+
repo_kwargs[key] = kwargs.pop(key)
|
|
98
|
+
|
|
99
|
+
# Apply idempotency key to reference_id if provided.
|
|
100
|
+
if idempotency_key is not None:
|
|
101
|
+
repo_kwargs.setdefault("reference_id", idempotency_key)
|
|
102
|
+
|
|
103
|
+
# Create shipment — use atomic idempotency if key provided.
|
|
104
|
+
if idempotency_key is not None:
|
|
105
|
+
(
|
|
106
|
+
existing,
|
|
107
|
+
created,
|
|
108
|
+
) = await self.repository.create_with_idempotency_key(
|
|
109
|
+
provider=provider_slug,
|
|
110
|
+
status=ShipmentStatus.NEW.value,
|
|
111
|
+
**repo_kwargs,
|
|
112
|
+
)
|
|
113
|
+
if existing is not None:
|
|
114
|
+
return CreateShipmentOutcome(shipment=existing, label=None)
|
|
115
|
+
if created is None:
|
|
116
|
+
raise RuntimeError(
|
|
117
|
+
"create_with_idempotency_key returned (None, None) "
|
|
118
|
+
"— repository contract violated"
|
|
119
|
+
)
|
|
120
|
+
shipment = created
|
|
121
|
+
else:
|
|
122
|
+
shipment = await self.repository.create(
|
|
123
|
+
provider=provider_slug,
|
|
124
|
+
status=ShipmentStatus.NEW.value,
|
|
125
|
+
**repo_kwargs,
|
|
126
|
+
)
|
|
127
|
+
|
|
69
128
|
provider = self._get_provider(shipment)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
129
|
+
try:
|
|
130
|
+
result = await self._call_provider(
|
|
131
|
+
provider.create_shipment(
|
|
132
|
+
sender_address=sender_address,
|
|
133
|
+
receiver_address=receiver_address,
|
|
134
|
+
parcels=parcels,
|
|
135
|
+
**kwargs,
|
|
136
|
+
)
|
|
76
137
|
)
|
|
77
|
-
|
|
138
|
+
except CommunicationError:
|
|
139
|
+
# Ambiguous: provider may have accepted the shipment
|
|
140
|
+
# (e.g. timeout after acceptance). Mark as SUBMITTED for
|
|
141
|
+
# reconciliation via polling or callback.
|
|
142
|
+
transition_shipment(shipment, ShipmentStatus.SUBMITTED)
|
|
143
|
+
await self.repository.save(shipment)
|
|
144
|
+
return CreateShipmentOutcome(shipment=shipment, label=None)
|
|
145
|
+
except Exception:
|
|
146
|
+
# Non-communication error: mark as FAILED, never delete.
|
|
147
|
+
transition_shipment(shipment, ShipmentStatus.FAILED)
|
|
148
|
+
await self.repository.save(shipment)
|
|
149
|
+
raise
|
|
150
|
+
|
|
78
151
|
shipment.external_id = str(result.get("external_id", ""))
|
|
79
152
|
shipment.tracking_number = str(result.get("tracking_number", ""))
|
|
80
153
|
transition_shipment(shipment, ShipmentStatus.CREATED)
|
|
@@ -98,7 +171,9 @@ class ShipmentFlow:
|
|
|
98
171
|
)
|
|
99
172
|
label = await self._call_provider(provider.create_label(**kwargs))
|
|
100
173
|
transition_shipment(shipment, ShipmentStatus.LABEL_READY)
|
|
101
|
-
saved = await self.repository.
|
|
174
|
+
saved = await self.repository.update_fields(
|
|
175
|
+
shipment_id=shipment.id, status=shipment.status
|
|
176
|
+
)
|
|
102
177
|
return CreateLabelOutcome(shipment=saved, label=label)
|
|
103
178
|
|
|
104
179
|
async def handle_callback(
|
|
@@ -155,7 +230,9 @@ class ShipmentFlow:
|
|
|
155
230
|
)
|
|
156
231
|
if cancelled:
|
|
157
232
|
transition_shipment(shipment, ShipmentStatus.CANCELLED)
|
|
158
|
-
await self.repository.
|
|
233
|
+
await self.repository.update_fields(
|
|
234
|
+
shipment_id=shipment.id, status=shipment.status
|
|
235
|
+
)
|
|
159
236
|
return bool(cancelled)
|
|
160
237
|
|
|
161
238
|
def _get_provider(self, shipment: Shipment) -> BaseProvider:
|
|
@@ -166,16 +243,29 @@ class ShipmentFlow:
|
|
|
166
243
|
async def _apply_update(
|
|
167
244
|
self, shipment: Shipment, update: ShipmentUpdateResult
|
|
168
245
|
) -> Shipment:
|
|
246
|
+
"""Apply a normalized update to a shipment atomically.
|
|
247
|
+
|
|
248
|
+
Uses the atomic ``update_fields`` persistence primitive to
|
|
249
|
+
prevent concurrent read-modify-save races.
|
|
250
|
+
"""
|
|
251
|
+
fields: dict[str, Any] = {}
|
|
169
252
|
tracking_number = update.get("tracking_number")
|
|
170
253
|
if tracking_number:
|
|
171
|
-
|
|
254
|
+
fields["tracking_number"] = str(tracking_number)
|
|
172
255
|
status = update.get("status")
|
|
173
256
|
if status is not None:
|
|
174
257
|
transition_shipment(shipment, status)
|
|
175
|
-
|
|
258
|
+
fields["status"] = shipment.status
|
|
259
|
+
return await self.repository.update_fields(
|
|
260
|
+
shipment_id=shipment.id, **fields
|
|
261
|
+
)
|
|
176
262
|
|
|
177
263
|
async def _call_provider(self, coro: Any) -> Any:
|
|
178
|
-
"""Call a provider coroutine, wrapping
|
|
264
|
+
"""Call a provider coroutine, wrapping only network errors.
|
|
265
|
+
|
|
266
|
+
Domain errors (ValueError, KeyError, TypeError, etc.) are re-raised
|
|
267
|
+
as-is so they are distinguishable from communication failures.
|
|
268
|
+
"""
|
|
179
269
|
|
|
180
270
|
try:
|
|
181
271
|
return await coro
|
|
@@ -186,7 +276,18 @@ class ShipmentFlow:
|
|
|
186
276
|
str(exc),
|
|
187
277
|
context={"original_error": type(exc).__name__},
|
|
188
278
|
) from exc
|
|
189
|
-
except
|
|
279
|
+
except TimeoutError as exc:
|
|
280
|
+
raise CommunicationError(
|
|
281
|
+
str(exc),
|
|
282
|
+
context={"original_error": type(exc).__name__},
|
|
283
|
+
) from exc
|
|
284
|
+
except ExceptionGroup as exc:
|
|
285
|
+
# Preserve typed inner exceptions: if any inner exception is a
|
|
286
|
+
# SendParcelException, re-raise it directly. Otherwise wrap the
|
|
287
|
+
# entire group in a CommunicationError.
|
|
288
|
+
for e in exc.exceptions:
|
|
289
|
+
if isinstance(e, SendParcelException):
|
|
290
|
+
raise e from exc
|
|
190
291
|
raise CommunicationError(
|
|
191
292
|
str(exc),
|
|
192
293
|
context={"original_error": type(exc).__name__},
|