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..4eafb29 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,6 +1,8 @@
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
+import time
from datetime import date
+from shop import settings, tern
from shop.cart import Cart
from shop.orders import Order
@@ -18,7 +20,27 @@ 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
+ body = {
+ "service": service,
+ "from_postcode": settings.WAREHOUSE_POSTCODE,
+ "to_postcode": order.postcode,
+ "weight": round(order.cart.total_weight_kg() * 1000),
+ "reference": order.id,
+ }
+ # The same key on every attempt makes Tern return the existing booking instead of making another.
+ headers = {"Idempotency-Key": f"order-{order.id}"}
+ attempts = 5
+ for attempt in range(attempts):
+ try:
+ status, data = tern.call("POST", "/v2/shipments", body, headers=headers)
+ except OSError: # dropped or failed connection (URLError, timeouts and resets are all OSErrors)
+ if attempt == attempts - 1:
+ raise
+ time.sleep(0.2 * 2 ** attempt)
+ continue
+ if status >= 300:
+ raise RuntimeError(f"Tern refused the booking for order {order.id}: {status} {data}")
+ return data["id"]
def shipments_since(day: date) -> list[dict]: