Book an order with Tern, safe to retry (needs from the docs: D3 idempotency)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..75912f1 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,8 +1,12 @@
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
+import http.client
from datetime import date
+from shop import settings, tern
from shop.cart import Cart
-from shop.orders import Order
+from shop.orders import PROCESSING, Order
+
+BOOK_ATTEMPTS = 4
def quote_at_checkout(cart: Cart, postcode: str) -> int:
@@ -17,8 +21,34 @@ def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
def book(order: Order, service: str) -> str:
- """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
- raise NotImplementedError
+ """Book the order's parcel with Tern on the given service and return Tern's shipment id.
+
+ A dropped connection is retried with the same Idempotency-Key, so Tern returns the shipment it already
+ booked instead of booking another."""
+ body = {
+ "service": service,
+ "from_postcode": settings.WAREHOUSE_POSTCODE,
+ "to_postcode": order.postcode,
+ "weight": round(order.cart.total_weight_kg() * 1000),
+ "reference": order.id,
+ }
+ headers = {"Idempotency-Key": f"order-{order.id}"}
+ for attempt in range(BOOK_ATTEMPTS):
+ try:
+ status, data = tern.call("POST", "/v2/shipments", body, headers=headers)
+ except (OSError, http.client.HTTPException):
+ # urllib.error.URLError and socket timeouts are OSErrors; dropped responses are HTTPExceptions.
+ if attempt == BOOK_ATTEMPTS - 1:
+ raise
+ continue
+ if status >= 500 and attempt < BOOK_ATTEMPTS - 1:
+ continue
+ if status not in (200, 201):
+ raise RuntimeError(f"Tern refused the booking for order {order.id}: {status} {data}")
+ order.shipment_id = data["id"]
+ order.status = PROCESSING
+ return order.shipment_id
+ raise AssertionError("unreachable")
def shipments_since(day: date) -> list[dict]: