Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
buy_label.py · 21.4 KB · 459 lines
1"""action_buy_label -- put a tracking number and a label on a parcel,
2whichever way this shop actually gets one.
3
4POST {shipment_id, tracking_number?, carrier?, label_base64?,
5 label_content_type?, label_filename?}
6
7ONE VERB, BOTH DIRECTIONS. A return label is this action against an INBOUND
8shipment; there is deliberately no action_buy_return_label. A return label
9is the same purchase with the addresses the other way round, and a second
10verb would be a second place for the credentials, the refusals, the file
11handling and the stamping to drift -- which in practice means the return
12half quietly rots, because it is used a tenth as often as the outbound half.
13
14UNCONFIGURED IS A 409 THAT NAMES THE SETTING, never a broken button and
15never a fake success. Same posture as action_stripe_checkout, and for the
16same reason: the shop can see the button, so the button owes them a sentence
17they can act on. `missing_settings` carries the same fact as a list, for a
18client that wants to render the fix rather than the prose.
19
20The whole flow works with no carrier at all -- that is the design, not a
21consolation. With carrier.provider=manual the operator walks to the counter,
22buys the postage, and brings back a tracking number (and, if they were
23handed one, the label PDF). This action records both. It buys nothing and
24says it bought nothing. What it gets in exchange for going through the
25connector interface anyway is that the day a real adapter is installed, the
26tracking number arrives on the same field, the label lands in the same file,
27the manifest prints the same row and nothing downstream is rewritten.
28
29THE LABEL FILE IS EVIDENCE (docs/logic-decisions.md #8), stored exactly the
30way a scanned receipt is: bytes through object_user_files, a `files` row so
31it can actually be opened at /api/files/{id}, and the id stamped on the
32shipment. A re-bought label gets a NEW file id rather than overwriting the
33old bytes -- the first label was really printed and may really be on a box,
34and evidence is not edited to agree with the current plan.
35
36A PAID LABEL IS BOUGHT ONCE. With any carrier but `manual`, a shipment that
37already has a label is refused unless the request says `replace: true`,
38and the purchase is CLAIMED on the shipment (shipments.label_purchase, a
39compare-and-set) before the carrier is called, so two clicks that both read
40a label-less shipment cannot both buy. A connector that raises (or answers
41nonsense) after a paid call may already have been charged, so that outcome
42is recorded as `unknown` on the shipment and answered with a 502 that says
43to check with the carrier; the next click is refused until somebody passes
44`replace`. Nothing retries a paid call on its own (AGENTS.md). A connector
45that answers ok=false or skip said no, so its claim is simply released.
46
47A failure to store the FILE does not lose the TRACKING NUMBER. The number is
48the thing a customer will be given and the thing the poll needs; the PDF is
49a convenience the operator can re-upload. Refusing the whole action because
50a file write failed would be the paperwork throwing away the fact to protect
51the attachment.
52"""
53
54import base64
55import os
56from datetime import datetime, timezone
57from pathlib import Path
58
59import object_access
60import object_connectors
61import object_ids
62import object_packages
63import object_records
64import object_user_files
65
66ACTOR = "action_buy_label"
67
68# A shipping label is a few hundred kilobytes of PDF. The cap is here to
69# refuse an accident, not to price a service.
70MAX_BYTES = 10 * 1024 * 1024
71
72# Journeys that are over. Buying a label for one of these is somebody on the
73# wrong record, and stamping a new tracking number onto a delivered parcel
74# would rewrite what the customer was told last week.
75FINISHED = {"delivered", "returned_to_sender", "lost", "received",
76 "dispositioned", "expired"}
77
78
79def _base_dir():
80 return os.environ.get("DBBASIC_DATA_DIR", "data")
81
82
83def _text(value):
84 return str(value if value is not None else "").strip()
85
86
87def _setting(base, key, default=""):
88 """Duplicated on purpose, same as every other package that reads
89 app_settings (docs/logic-decisions.md #4)."""
90 try:
91 # access: box configuration
92 for row in object_records.read_collection_records("app_settings",
93 base_dir=base):
94 if row.get("key") == key and _text(row.get("value")):
95 return _text(row["value"])
96 except Exception:
97 pass
98 return default
99
100
101# --- the carrier boundary -----------------------------------------------------
102#
103# A deliberate second copy of the pair in system_tracking_poll, named in both
104# files: objects on this platform cannot import one another (a sibling is
105# executed, not imported), and #4 says the third occurrence is the one that
106# earns the extraction.
107
108def _carrier_declaration():
109 """The connector declaration that owns `shipments` on this box, resolved
110 through object_packages.iter_connectors -- the existing mechanism, which
111 escape-checks the module path and lets a private overlay win."""
112 packages = os.environ.get("DBBASIC_PACKAGES_DIR", object_packages.PACKAGES_DIR)
113 private = (os.environ.get("DBBASIC_PRIVATE_PACKAGES_DIR")
114 or str(Path(packages).parent / "packages-private"))
115 roots = ([private] if Path(private).is_dir() else []) + [packages]
116 for root in roots:
117 for declaration in object_packages.iter_connectors(root=root):
118 if declaration["collection"] == "shipments":
119 return declaration
120 return None
121
122
123def _carrier(base, entry):
124 """(function, provider, problem, missing) -- the configured carrier's
125 `entry`, or the honest reason there is not one plus the settings whose
126 absence caused it."""
127 provider = _setting(base, "carrier.provider", "none").lower() or "none"
128 if provider == "none":
129 return None, provider, (
130 "No carrier is configured on this server, so there is no label to "
131 "buy. Set app_settings carrier.provider to `manual` and pass the "
132 "tracking number from the post office counter (with the label PDF "
133 "if you were handed one), or set it to an installed carrier "
134 "adapter's name. Until then the shipment still works: type the "
135 "tracking number on it and print the packing slip."
136 ), ["carrier.provider"]
137
138 declaration = _carrier_declaration()
139 if declaration is None:
140 return None, provider, (
141 f"app_settings carrier.provider is {provider!r}, but no installed "
142 f"package declares a connector for the shipments collection. "
143 f"Install the carrier adapter package, or set carrier.provider to "
144 f"`manual`."
145 ), ["carrier.provider"]
146 try:
147 function = object_connectors.load_connector(declaration["module"], entry)
148 except object_connectors.ConnectorLoadError as exc:
149 return None, provider, (
150 f"The carrier connector for {provider!r} could not be loaded: "
151 f"{str(exc)[:200]}"
152 ), []
153
154 # The module's own name for itself, read off the loaded function's
155 # globals: load_connector deliberately keeps the module out of
156 # sys.modules, and a second loader to read one constant would be a
157 # second loader.
158 declared = _text(function.__globals__.get("PROVIDER"))
159 if declared and declared.lower() != provider:
160 return None, provider, (
161 f"app_settings carrier.provider is {provider!r}, but the connector "
162 f"installed for shipments answers to {declared!r}. Nothing was "
163 f"bought: using a carrier the shop did not configure is worse than "
164 f"a refusal."
165 ), ["carrier.provider"]
166 return function, provider, "", []
167
168
169def _store_label(base, shipment, outcome):
170 """Bytes to disk, a `files` row so somebody can open them, and the id.
171
172 Returns (file_id, url, error). The `files` row is best-effort: a
173 deployment without app-files installed still gets the bytes and the
174 stamp, and says so, because a label held and unopenable beats a label
175 refused.
176 """
177 content = outcome.get("label_bytes")
178 if not content:
179 return "", "", ""
180 if not isinstance(content, (bytes, bytearray)):
181 return "", "", "the carrier returned a label that was not bytes"
182
183 owner = _text(shipment.get("owner_id")) or "shipping"
184 # A NEW id per label, never a rewrite of the last one: the previous label
185 # may be on a box somewhere, and evidence is not edited (#8).
186 file_id = f"label-{object_ids.new_uuid4()}"
187 try:
188 size = object_user_files.save_file(owner, file_id, bytes(content),
189 base_dir=base)
190 except Exception as exc: # noqa: BLE001
191 return "", "", f"the label could not be stored: {str(exc)[:160]}"
192
193 try:
194 # access: label file stored for the shipment read through Access above
195 object_records.create_collection_record(
196 "files",
197 {
198 "id": file_id,
199 "filename": (_text(outcome.get("label_filename"))
200 or f"label-{shipment['id'][:8]}.pdf"),
201 "content_type": (_text(outcome.get("label_content_type"))
202 or "application/pdf"),
203 "size": str(size),
204 "description": (f"Shipping label for shipment "
205 f"{shipment['id']}"),
206 "parent_collection": "shipments",
207 "parent_id": shipment["id"],
208 "owner_id": owner,
209 },
210 base_dir=base, actor=ACTOR)
211 except Exception as exc: # noqa: BLE001
212 return file_id, "", (f"the label bytes were stored but no files record "
213 f"could be written ({str(exc)[:120]}), so it will "
214 f"not open at /api/files")
215 return file_id, f"/api/files/{file_id}", ""
216
217
218MANUAL_PROVIDER = "manual"
219PURCHASE_PENDING = "pending"
220PURCHASE_UNKNOWN = "unknown"
221
222
223def _truthy(value):
224 return _text(value).lower() in ("true", "1", "yes", "on")
225
226
227def _claim_tail(claim):
228 """`<attempt id> <started at>` of a `pending ...` claim."""
229 return claim.split(" ", 1)[1] if " " in claim else claim
230
231
232def _claim_the_purchase(base, shipment, provider, *, replace):
233 """Before a PAID carrier is called: refuse a shipment that already has a
234 label, or whose last purchase is pending or of unknown outcome, unless
235 the caller says `replace`; then claim the purchase on the shipment as a
236 compare-and-set. Returns (claim, None) or ("", refusal).
237
238 buy_label used to have no guard at all, so a double click bought (and
239 the shop was billed for) a second label. A guard on the stored label
240 alone is not enough: two clicks that read the shipment before either
241 label lands both pass it. So the claim -- shipments.label_purchase set
242 to `pending <attempt> <time>` with expected_rev -- is what lets exactly
243 one of them call the carrier. The manual carrier buys nothing, and its
244 re-buy is deliberate (an operator retyping a number), so it is never
245 guarded.
246 """
247 shipment_id = _text(shipment.get("id"))
248 state = _text(shipment.get("label_purchase"))
249 has_label = bool(_text(shipment.get("tracking_number"))
250 or _text(shipment.get("label_file_id")))
251 if not replace:
252 if state.startswith(PURCHASE_PENDING):
253 return "", {"status": 409, "provider": provider,
254 "label_purchase": state,
255 "error": ("A label purchase for this shipment is "
256 "already in progress (or was interrupted). "
257 "Check with the carrier whether it went "
258 "through; pass replace=true to buy another "
259 "anyway.")}
260 if state.startswith(PURCHASE_UNKNOWN):
261 return "", {"status": 409, "provider": provider,
262 "label_purchase": state,
263 "error": (f"The last label purchase for this shipment "
264 f"ended with an unknown outcome and may have "
265 f"been charged. Check with the carrier "
266 f"({provider}) first; pass replace=true to buy "
267 f"another anyway.")}
268 if has_label:
269 return "", {"status": 409, "provider": provider,
270 "tracking_number": _text(shipment.get("tracking_number")),
271 "label_file_id": _text(shipment.get("label_file_id")),
272 "error": ("This shipment already has a label from a paid "
273 "carrier, so another would be a second "
274 "purchase. Pass replace=true if the first one "
275 "really has to be replaced (and void it with "
276 "the carrier).")}
277 claim = (f"{PURCHASE_PENDING} {object_ids.new_uuid4()} "
278 f"{datetime.now(timezone.utc).isoformat(timespec='seconds')}")
279 try:
280 object_records.update_collection_record(
281 "shipments", shipment_id, {"label_purchase": claim},
282 base_dir=base, actor=ACTOR, preserve_read_only=True,
283 expected_rev=object_records.compute_record_rev(shipment))
284 except object_records.VersionConflictError:
285 return "", {"status": 409, "provider": provider,
286 "error": ("This shipment changed while the label was being "
287 "bought -- most likely another click is buying "
288 "it right now. Reload it before buying again.")}
289 return claim, None
290
291
292def _settle_the_claim(base, shipment_id, claim, value):
293 """Replace our own claim with `value` ("" releases it). Only if the
294 shipment still carries OUR claim; anything else is somebody else's
295 attempt and is left alone."""
296 if not claim:
297 return
298 try:
299 current = object_records.get_collection_record("shipments", shipment_id,
300 base_dir=base)
301 if _text(current.get("label_purchase")) != claim:
302 return
303 object_records.update_collection_record(
304 "shipments", shipment_id, {"label_purchase": value},
305 base_dir=base, actor=ACTOR, preserve_read_only=True,
306 expected_rev=object_records.compute_record_rev(current))
307 except Exception: # noqa: BLE001
308 pass
309
310
311def POST(request):
312 base = _base_dir()
313 shipment_id = _text(request.get("shipment_id"))
314 if not shipment_id:
315 return {"status": 400, "error": "shipment_id is required"}
316
317 # Only someone the shipments API would let UPDATE this parcel may put a
318 # label on it. The stamp below is a trusted server-side write, so this
319 # object is the only gate: it used to let any signed-in user overwrite
320 # the tracking number on anybody's parcel, and -- with a paid carrier
321 # configured -- spend the shop's postage account on it. Refused reads
322 # exactly like missing.
323 access = object_access.Access(request.get("_identity"), base_dir=base)
324 try:
325 shipment = access.get("shipments", shipment_id, action="update")
326 except Exception:
327 shipment = None
328 if not shipment:
329 return {"status": 404, "error": f"No such shipment: {shipment_id}"}
330
331 status = _text(shipment.get("status"))
332 if status in FINISHED:
333 return {"status": 409,
334 "error": (f"This shipment is {status}: its journey is over, so "
335 f"a new label would only overwrite what the customer "
336 f"was already told. Raise a new shipment if goods "
337 f"have to move again.")}
338
339 inbound = _text(shipment.get("direction")) == "inbound"
340
341 label_bytes = None
342 raw = request.get("label_base64")
343 if raw:
344 try:
345 label_bytes = base64.b64decode(_text(raw), validate=True)
346 except Exception:
347 return {"status": 400, "error": "label_base64 is not valid base64."}
348 if len(label_bytes) > MAX_BYTES:
349 return {"status": 413,
350 "error": (f"That label is larger than the "
351 f"{MAX_BYTES // (1024 * 1024)}MB cap.")}
352
353 buy, provider, problem, missing = _carrier(base, "buy_label")
354 if problem:
355 return {"status": 409, "error": problem, "provider": provider,
356 "missing_settings": missing,
357 "note": ("the manual path still works with no carrier at all: "
358 "type the tracking number onto the shipment and print "
359 "the packing slip")}
360
361 paid = provider != MANUAL_PROVIDER
362 claim = ""
363 if paid:
364 claim, refusal = _claim_the_purchase(base, shipment, provider,
365 replace=_truthy(request.get("replace")))
366 if refusal:
367 return refusal
368
369 unknown = ""
370 try:
371 outcome = buy(shipment, base_dir=base,
372 tracking_number=_text(request.get("tracking_number")),
373 label_bytes=label_bytes,
374 label_content_type=_text(request.get("label_content_type")),
375 label_filename=_text(request.get("label_filename")))
376 if not isinstance(outcome, dict):
377 unknown = (f"the carrier connector returned "
378 f"{type(outcome).__name__}, expected a dict")
379 except Exception as exc: # noqa: BLE001
380 unknown = f"the carrier connector raised: {str(exc)[:200]}"
381
382 if unknown:
383 if paid:
384 # The paid call may have gone through before the failure: an
385 # exception after the carrier accepted the order looks exactly
386 # like one before it. So the attempt is RECORDED on the
387 # shipment and the next click is refused until somebody has
388 # checked with the carrier (AGENTS.md: never auto-retry a paid,
389 # non-idempotent call -- a retry is a person's decision).
390 _settle_the_claim(base, shipment_id, claim,
391 f"{PURCHASE_UNKNOWN} {_claim_tail(claim)}")
392 return {"status": 502, "provider": provider,
393 "outcome": "unknown",
394 "error": (f"{unknown}. The label purchase may have gone "
395 f"through and been charged: check with the "
396 f"carrier ({provider}) before buying again. Do "
397 f"not retry blindly -- this shipment now refuses "
398 f"another purchase until you pass replace=true.")}
399 outcome = {"ok": False, "error": unknown}
400
401 if outcome.get("skip"):
402 # The connector declined rather than failed -- the host is not ready.
403 _settle_the_claim(base, shipment_id, claim, "")
404 return {"status": 409, "provider": provider,
405 "error": _text(outcome.get("reason")) or
406 "the carrier connector declined to sell a label."}
407 if not outcome.get("ok"):
408 # `permanent` means the request as posed can never work (a missing
409 # tracking number, an address the carrier will not accept), which is
410 # the caller's to fix -- 400. Anything else is the provider having a
411 # bad minute, which is 502 and worth retrying, the same split
412 # action_stripe_checkout makes. Either way the CONNECTOR said no, so
413 # nothing was bought and the claim is released.
414 _settle_the_claim(base, shipment_id, claim, "")
415 return {"status": 400 if outcome.get("permanent") else 502,
416 "provider": provider,
417 "error": _text(outcome.get("error")) or
418 "the carrier could not produce a label."}
419
420 tracking_number = _text(outcome.get("tracking_number"))
421 file_id, url, file_error = _store_label(base, shipment, outcome)
422
423 update = {}
424 if tracking_number:
425 update["tracking_number"] = tracking_number
426 if file_id:
427 update["label_file_id"] = file_id
428 carrier = _text(outcome.get("carrier")) or _text(request.get("carrier"))
429 if carrier:
430 update["carrier"] = carrier
431 if claim:
432 # Bought: the label on the shipment is now what refuses a second
433 # purchase, so the claim is cleared with the same write.
434 update["label_purchase"] = ""
435 if update:
436 object_records.update_collection_record(
437 "shipments", shipment_id, update, base_dir=base, actor=ACTOR,
438 preserve_read_only=True)
439
440 return {
441 "ok": True,
442 "shipment_id": shipment_id,
443 "direction": "inbound" if inbound else "outbound",
444 "kind": "return label" if inbound else "shipping label",
445 "provider": provider,
446 "tracking_number": tracking_number,
447 "label_file_id": file_id,
448 "label_url": url,
449 "carrier": carrier or _text(shipment.get("carrier")),
450 "status_of_shipment": status,
451 "bought_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
452 "slip_path": f"/shipments/{shipment_id}/slip",
453 # The status ladder is not this action's business: a label on the
454 # bench is not a parcel out of the door, and moving it would let a
455 # printer jam look like a handover.
456 "note": (_text(outcome.get("note"))
457 or "label recorded; the shipment's status is unchanged"),
458 **({"label_error": file_error} if file_error else {}),
459 }