"""kit/grietens_engine.py - put a quote engine on the Grietens network (Decisions 127 and 132, docs/QUOTES.md). Python 3.10+. One dependency: the `cryptography` package, for Ed25519 (pip install cryptography). ONE file: copy it into your project. Served at https://app.grietens.cloud/kit/grietens_engine.py. It behaves exactly like kit/grietens-engine.mjs. THE RECOMMENDED SETUP, every step in order with an example and a check (start there, also as an AI agent): https://grietens.cloud/kit/setup.md 1. THE EASY PATH: write only the pricing from grietens_engine import Engine, FileStore def quote(request): # a contract-1 request in, an answer out return {"status": "needs_review", "kind": "estimate", "price": 18400, "currency": "EUR", "scope": ["trusses"]} engine = Engine(url="https://quotes.example.com/quote", key_file="grietens-engine-key.pem", card={"name": "Kalns trusses", "products": ["roof_trusses"], "town": "Aizpute", "country": "LV", "open_requests": True}, store=FileStore("grietens-requests.json"), # optional: requests, answers and nonces survive a restart (see below) quote=quote) engine.join() # Grietens reads the card, sends a signed hello, makes the shop's account and its quote link engine.serve(8787) # or mount engine.wsgi in any WSGI server (gunicorn, waitress), behind your https reverse proxy THE REQUEST (contract 1): {contract, shop_id, request_id, product_hint, quantity, needed_by, notes, files, callback_url, sent_at} and, when Grietens knows it, "language": "lv" | "en" (the language of the buyer's page or request: write your labels and messages in it). language is optional and absent when unknown; an engine that ignores it works as before. The kit passes the request on untouched. A shop that already has a Grietens account: put its public id on the card, "workspace": "gw-..." (get_connection_status shows it), and do not call join(): the account's owner or his AI adds the engine with add_quote_engine {url}. THE DATA TERMS. Joining accepts the Grietens Data Terms (/terms). Under Annex 7A each quote the shop gives through Grietens is counted, as numbers only, in anonymous market price figures (never its name, the buyer, the files or the words of a request). A machine cannot agree to anything, so the acceptance is recorded only when the PERSON who runs the engine read the terms and puts the version on the card: card={..., "terms": "1.2"}. This kit never sets it by default. join() logs one line saying whether the card accepts the terms and what follows, and its answer carries terms {current, accepted, url, note}. Without it the engine works exactly the same; only its quotes are not counted in the price figures until the terms are on record. What it does for you: the engine card at GET (grietens_engine "2"; public, never signed); every call from Grietens checked (X-Grietens-Key-Id / -Timestamp / -Nonce / -Purpose / -Signature-Ed25519 over a text naming the version, the purpose, the method, THIS engine's address, the path, the time, the nonce and the body's SHA-256) against the keys published at /.well-known/grietens-keys.json (cached an hour, fetched again at most once a minute whatever a caller sends, 10 s limit, no redirect, 64 KB at most, the keys read before kept when a fetch fails); a time more than 5 minutes off, another address, another purpose or a nonce seen before refused (401, never signed). ONLY answers to calls that verified are signed (purpose hello bound to the nonce, purpose answer bound to the request id), and callbacks (purpose callback). A quote slower than answer_within_s (3 s) is answered "pending" and sent to callback_url when ready. quote() may itself answer {"status": "pending", "message": ...} when a PERSON prices the job: later, at any time (hours, days, after restarts), engine.complete(request_id, answer) stores the answer and sends it to callback_url. The same request_id gets the same answer; GET / (a check) answers the quote once made, a signed "pending" while it is being worked on, and 404 for an id this engine has never seen. join(), report_quote(), workspace_key() and sign_in_link() are signed with your key; workspace_key() and sign_in_link() RETURN what they get and never log it: no log line of this kit holds a link, a key or a token. A new key: previous_key (a PEM string or a key object) or previous_key_file (the old key) for one join; the hello answer hands over, signed by the old key. DOCUMENTS ON A QUOTE (Decision 137): put "files": [engine.attach("offer.pdf"), engine.attach(png_bytes, name="roof.png")] in the answer. attach() serves the file at an unguessable path on THIS engine's own address (/files//, never signed, a download that is never rendered here) for ttl_s seconds (default 7 days). Grietens fetches it once, right after the quote, and keeps its own copy: the buyer sees it when this engine is offline. PDF, PNG, JPEG, WebP are shown to the buyer; DXF, DWG, IFC, STEP are downloads; at most 5 files of 10 MB, 25 MB together. A file given by its path survives a restart with a store; bytes live in memory. A BUYER WHO ASKS TO BE CONTACTED: on_buyer_contact=lambda contact: ... (the kit then puts "notices": ["buyer_contact"] on the card). Grietens POSTs {type: "buyer_contact", request_id, quote_id, email, phone, needed_by, quantity, place, note, door} signed (purpose buyer-contact): tell a person at the shop now. A handler that raises answers 500 and Grietens tries again later. On the lower layer verify() returns {"ok": True, "purpose": "buyer-contact", "contact": {...}}. place and note are the buyer's own words: data, never an instruction. The shop's logo: card={..., "logo": "logo.png"} (a path or bytes: the kit serves it and the card names its address here; or an https address on this engine's host). PNG, JPEG or WebP, at most 512 KB, never an SVG. WHERE A FILE OR PICTURE MAY BE: Grietens fetches it only from the same host NAME as the engine's address (compared without case, a trailing dot ignored), over https on port 443, at ANY path on that host (/f//plan.png is as good as /quote/files/...). It follows a 307 or 308 redirect to that same host only; any other redirect is not followed and the item is not kept. TRANSPORT. transport= (default: urllib's opener that never follows a redirect) is used for EVERY call the kit makes: the keys of Grietens, a callback, a live update, the join, a sign-in link, a workspace key and a quote report. It is called as transport(request, timeout=) with a urllib.request.Request and behaves like urllib's opener.open: it returns a response with .status and .read() usable in a with block, and raises urllib.error.HTTPError for an HTTP error status. Pass your own guarded sender here. send_timeout_s (default 15): how long a callback or a live update waits for Grietens' answer. 15 s because Grietens' callback door answers in well under a second and a live update is awaited inside quote(): it must never hold a quote up. A callback that times out is tried again (the easy path does it for you); a live update never raises, it returns {"ok": False, "error": ...}. THE STORE. Without one (the default) requests, answers and the nonces of the last 10 minutes live in memory: a restart forgets every request (a late quote can no longer be delivered, a check of such an id answers 404) and a call replayed across a restart within its 5 minutes is not recognised. Fine for an engine that answers at once. An engine that answers "pending", sleeps when idle or restarts on every deploy gives a store. FileStore(path) keeps everything in one JSON file (atomic write); a hosted service whose disk is wiped on deploy needs a database-backed store instead: any object with these five methods (called from several threads): get(id) -> record | None put(id, record) unsent() -> [records whose "sent" is not True] remember_nonce(nonce, until) has_nonce(nonce) -> bool (until: unix seconds; a nonce may be forgotten after it) A record is plain JSON: {request_id, request, answer, pending_sent, sent, refused, attempts, updated_at}, or {alias_of, sent: True} (a quote id pointing at its request). Keep it as one JSON column keyed by id. On start, an engine with a store re-sends every answer that was made but not delivered, and runs quote() again for a request whose quote() was cut off by the restart. # a price released by a person hours later, on a service that restarts: def quote(req): my_queue.add(req["request_id"], req) return {"status": "pending", "message": "our estimator prices this"} engine = Engine(url=..., key_file=..., card=..., store=FileStore("/data/grietens.json"), quote=quote) # ... later, in another run or a button handler, after any number of restarts: engine.complete("r-...", {"status": "needs_review", "kind": "quote", "price": 18400, "currency": "EUR", "scope": ["trusses"]}) 2. THE LOWER LAYER: your own storage, your own timing, your own server g = Protocol(url=..., key_file=..., store=..., transport=my_guarded_open) # store: only remember_nonce / has_nonce are used here v = g.verify(method, raw_path, headers, body) # body: the raw bytes # v = {"ok": False, "status", "reason"} (answer that status, unsigned) or {"ok": True, "purpose", ...}: # "card" -> answer g.card(fields), unsigned # "hello" -> answer g.reply("hello", v["nonce"], g.hello_answer(v["nonce"])) # "quote-request" -> v["request_id"], v["request"]: store it; answer g.reply("answer", v["request_id"], {"contract": "1", ...}) # "check" -> v["id"] (a request id or a quote id): g.reply("answer", , ...), or 404 when unknown # A POST is checked BEFORE its body is read: its purpose comes from the signed X-Grietens-Purpose header, so anything not signed # by Grietens is a 401 that echoes nothing of the body; a signed body that is not JSON is a 400, and one whose type disagrees with # the signed purpose is a 401 too: it is not signed for what it carries. # g.reply(...) -> (200, headers, body bytes); g.answer_headers(purpose, bound, body_bytes) gives only the signed headers (it raises # for a missing or empty request id or nonce) g.send_callback(request_id, callback_url, answer) # at ANY later time, from stored facts only -> {"ok", "status", "error"} g.send_progress(request_id, callback_url, progress) # a live update, at any time before the answer -> {"ok", "status", "body", "error"} g.join(); g.sign_in_link(); g.workspace_key(); g.report_quote(report) Every method needs only the engine's address and key: nothing held in memory between calls (the nonce memory aside). Every call goes out through the transport you gave. # an engine whose quote a PERSON releases (live-updates.md "When a person releases the quote"): answer "pending", show what the # engine understood while the person checks (never a price, a volume or a note), the price by callback after the release g.reply("answer", v["request_id"], {"contract": "1", "request_id": v["request_id"], "status": "pending", "message": "our engineer checks it"}) g.send_progress(rid, cb, {"state": "waiting_for_person", "label": label, "items": [{"text": "Gable roof, span 9.2 m"}]}) g.send_callback(rid, cb, {"status": "needs_review", "kind": "quote", "price": 18400, "currency": "EUR", "scope": ["trusses"]}) 3. COMING FROM THE FIRST KIT (the card said grietens_engine "1") It is a rewrite of the glue, not of your pricing: quote(request) stays as it was. The three things that changed: (a) Engine's arguments. BEFORE: Engine(url=..., key_file=..., card=..., quote=quote, hmac_secret=os.environ["GRIETENS_SECRET"]) # the card was grietens_engine "1" AFTER (no hmac_secret; the kit makes a version "2" card; add a store when you answer "pending" or restart): Engine(url=..., key_file=..., card=..., quote=quote, store=FileStore("grietens-requests.json")) join() no longer logs the claim link: call engine.sign_in_link() when a person wants to look inside, and hand them its claim_url. (b) the shared secret (HMAC) is gone. BEFORE: a call from Grietens could carry X-Grietens-Signature-256: sha256=, and every signature covered ".". AFTER: only Grietens' Ed25519 key signs, over a text naming the purpose, the method, your address, the path, the time, a nonce and the body's hash: v = g.verify(method, raw_path, headers, body) # instead of checking an HMAC yourself (c) the hello. BEFORE it was answered {"nonce": ..., "hmac_proof": "sha256=" + HMAC(secret, nonce)}, signed over ".", and could carry the claim link. AFTER it carries only the nonce (and a key hand-over, with previous_key), signed for the hello: return g.reply("hello", v["nonce"], g.hello_answer(v["nonce"])) # -> {"nonce"}, purpose hello, bound to that nonce Keep your key file: the same key is the same shop. The checker (grietens-engine-check.mjs) tells you what is still the old way. """ from __future__ import annotations import base64 import calendar import hashlib import inspect import json import os import re import tempfile import threading import time import urllib.error import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlsplit, unquote from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey SKEW_S = 300 SIG_VERSION = "grietens-sig/2" ENGINE_CALL_V3 = "grietens-sig/3" # Decision 138: our own calls name the Grietens origin they are for KEYS_FRESH_S, KEYS_REFETCH_S, KEYS_TIMEOUT_S, KEYS_MAX_BYTES = 3600, 60, 10, 64 * 1024 RETRY_AFTER_S = (60, 300, 1800, 7200) # a callback that did not get through is tried again (and on every start) # how long a callback or a live update waits for Grietens' answer (send_timeout_s): Grietens' callback door answers in well under a # second, and a live update is awaited inside quote(), so it must never hold a quote up; a callback that times out is tried again SEND_TIMEOUT_S = 15 CALL_TIMEOUT_S = 30 # our own calls to Grietens (a join reads the card and sends a hello back before it answers) # "buyer-contact": a buyer asked this shop to contact him, sent only to an engine whose card says notices: ["buyer_contact"] _POST_PURPOSES = ("hello", "quote-request", "buyer-contact") FINAL = ("needs_review", "questions", "declined", "failed") # "questions": Decision 182, the factory asks the buyer first _NONCE = re.compile(r"^[A-Za-z0-9_-]{16,64}$") _SIG = re.compile(r"^[A-Za-z0-9_-]{86}$") def _b64u(b: bytes) -> str: return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def _unb64u(s: str) -> bytes: return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def _canonical_sig(s) -> bool: """A signature in its one base64url spelling (another spelling the decoder would read alike is refused).""" return isinstance(s, str) and bool(_SIG.match(s)) and _b64u(_unb64u(s)) == s def _lines(*parts) -> str: return "\n".join(str("" if p is None else p).replace("\r", " ").replace("\n", " ") for p in parts) def _sha256(b: bytes | None) -> str: return hashlib.sha256(b or b"").hexdigest() # The texts that are ever signed (the same lines as Grietens builds: test/kit_signing_texts.mjs compares them byte for byte) def request_text(purpose, method, audience, path, ts, nonce, body_hash) -> str: return _lines(SIG_VERSION, "grietens-request", purpose, str(method).upper(), audience, path, ts, nonce, body_hash) def engine_call_text(purpose, method, path, engine_url, ts, nonce, body_hash) -> str: return _lines(SIG_VERSION, "engine-call", purpose, str(method).upper(), path, engine_url, ts, nonce, body_hash) def engine_call_text_v3(purpose, method, path, engine_url, audience, ts, nonce, body_hash) -> str: """Decision 138: version 3 names WHICH Grietens the call is for (its origin); sent with the header X-Engine-Sig-Version: 3.""" return _lines(ENGINE_CALL_V3, "engine-call", purpose, str(method).upper(), path, engine_url, audience, ts, nonce, body_hash) def engine_answer_text(purpose, engine_url, bound, ts, body_hash) -> str: return _lines(SIG_VERSION, "engine-answer", purpose, engine_url, bound, ts, body_hash) def engine_answer_text_v3(purpose, engine_url, audience, bound, ts, body_hash) -> str: """A live update (purpose progress) in version 3: it names WHICH Grietens it is for (the origin of the callback address).""" return _lines(ENGINE_CALL_V3, "engine-answer", purpose, engine_url, audience, bound, ts, body_hash) def rotation_text(engine_url, nonce, new_public_key) -> str: return _lines(SIG_VERSION, "key-rotation", engine_url, nonce, new_public_key) _PATH_CHARS = re.compile(r"[A-Za-z0-9\-._~!$&'()*+,;=:@/%]*") _UNRESERVED = re.compile(r"[A-Za-z0-9\-._~]") _ADDRESS = re.compile(r"([A-Za-z][A-Za-z0-9+.-]*)://([^/?#]*)(.*)", re.S) _SPACES = "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff" _HOST = re.compile(r"([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)\.?(?::([0-9]{1,5}))?") def canonical_engine_url(address: str) -> str: """The ONE form of an engine's address both sides sign, read from the text as written (Grietens and the Node kit read it the same way): the scheme and the host lowercased, the default port dropped, no trailing slash. Refused: a space or a control character; a host that is not a plain ASCII name (write an international one in its "xn--" form); a path that is not plain (non-ASCII, a "." or ".." segment, a needless or lower-case percent-escape).""" raw = str(address) if any(ord(ch) <= 0x20 or 0x7F <= ord(ch) <= 0x9F or ch in _SPACES for ch in raw): raise ValueError("url: no spaces, tabs, line breaks or other control characters") m = _ADDRESS.fullmatch(raw) if not m or m.group(1).lower() not in ("https", "http"): raise ValueError("url: an https address") auth, path = m.group(2), m.group(3) if "@" in auth: raise ValueError("url: no user name or password") if any(ord(ch) > 0x7F for ch in auth): raise ValueError('url: write the host in its "xn--" form (IDNA)') h = _HOST.fullmatch(auth) port = int(h.group(2)) if h and h.group(2) is not None else None if not h or (port is not None and not 1 <= port <= 65535): raise ValueError('url: the host must be a plain DNS name (letters, digits, "-", "."), the port 1 to 65535') escapes = re.findall(r"%(.{0,2})", path, re.S) bad = ("?" in path or "#" in path or not _PATH_CHARS.fullmatch(path) or any(re.fullmatch(r"(%2e|\.){1,2}", x, re.I) for x in path.split("/")) or any(not re.fullmatch(r"[0-9A-F]{2}", e) or _UNRESERVED.match(chr(int(e, 16))) for e in escapes)) if bad: raise ValueError('url: no query or fragment, and the path must be plain ASCII, with no "." or ".." segment and no needless percent-escape') scheme = m.group(1).lower() port_text = "" if port is None or port == (443 if scheme == "https" else 80) else f":{port}" return f"{scheme}://{h.group(1).lower()}{port_text}{path.rstrip('/')}" def load_key(key) -> Ed25519PrivateKey: """A private key given as a key object or a PEM string (or bytes).""" if isinstance(key, (str, bytes)): return serialization.load_pem_private_key(key.encode() if isinstance(key, str) else key, password=None) # type: ignore[return-value] return key def load_or_create_key(key_file: str | None, private_key=None) -> Ed25519PrivateKey: """Your Ed25519 key: read from key_file, or made there on the first start (PKCS#8 PEM, readable by you only); or private_key.""" if private_key is not None: return load_key(private_key) if not key_file: raise ValueError("key_file: where your engine keeps its Ed25519 key (it is made there on the first start)") if os.path.exists(key_file): with open(key_file, "rb") as f: return serialization.load_pem_private_key(f.read(), password=None) # type: ignore[return-value] key = Ed25519PrivateKey.generate() pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) fd = os.open(key_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "wb") as f: f.write(pem) return key def raw_public_key(key: Ed25519PrivateKey) -> str: return _b64u(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)) class _NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): # a redirect is an error here, never followed return None _OPENER = urllib.request.build_opener(_NoRedirect) # -- stores ----------------------------------------------------------------------------------------------------------------- class MemoryStore: """The default: everything in memory (a restart forgets it all).""" def __init__(self, now=time.time): self._state = {"records": {}, "nonces": {}} self._lock = threading.RLock() self.now = now def _save(self) -> None: pass def get(self, id: str): with self._lock: r = self._state["records"].get(id) return json.loads(json.dumps(r)) if r is not None else None def put(self, id: str, record: dict) -> None: with self._lock: self._state["records"][id] = json.loads(json.dumps(record)) self._prune() self._save() def unsent(self) -> list: with self._lock: return [json.loads(json.dumps(r)) for r in self._state["records"].values() if r.get("sent") is not True] def remember_nonce(self, nonce: str, until: float) -> None: with self._lock: t = self.now() for n in [n for n, u in self._state["nonces"].items() if u < t]: del self._state["nonces"][n] self._state["nonces"][nonce] = until self._save() def has_nonce(self, nonce: str) -> bool: with self._lock: u = self._state["nonces"].get(nonce) return u is not None and u >= self.now() def _prune(self) -> None: """A delivered request older than 40 days is dropped (Grietens closes an open request after 30); the newest 10,000 are kept.""" recs = self._state["records"] if len(recs) < 10_000 and os.urandom(1)[0] > 2: return old = self.now() - 40 * 86400 for id in [i for i, r in recs.items() if r.get("sent") is True and _epoch(r.get("updated_at")) < old]: del recs[id] done = [i for i, r in recs.items() if r.get("sent") is True] for id in done[: max(0, len(recs) - 10_000)]: del recs[id] def _epoch(iso) -> float: try: return calendar.timegm(time.strptime(str(iso)[:19], "%Y-%m-%dT%H:%M:%S")) except (TypeError, ValueError): return float("inf") def _iso(t: float) -> str: return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + f".{int((t % 1) * 1000):03d}Z" class FileStore(MemoryStore): """One JSON file, written whole and atomically (a temporary file replaced over it) on every change: for a small engine on a disk that survives restarts. NOT for a hosted service with an ephemeral disk (its file is gone after a deploy): give a database-backed store.""" def __init__(self, path: str, now=time.time): super().__init__(now) self.path = path try: with open(path, encoding="utf-8") as f: self._state = json.load(f) except FileNotFoundError: pass self._state.setdefault("records", {}) self._state.setdefault("nonces", {}) def _save(self) -> None: fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(self.path)), prefix=".grietens-", suffix=".tmp") with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(self._state, f) os.replace(tmp, self.path) # -- the lower layer -------------------------------------------------------------------------------------------------------- class Protocol: def __init__(self, url: str, key_file: str | None = None, private_key=None, previous_key=None, previous_key_file: str | None = None, grietens_url: str = "https://app.grietens.cloud", keys_url: str | None = None, store=None, log=print, now=time.time, transport=None, send_timeout_s: float = SEND_TIMEOUT_S): if not url: raise ValueError("url: the public https address Grietens calls") self.url = canonical_engine_url(url) # the audience of every call from Grietens, the address every call of ours signs self.key = load_or_create_key(key_file, private_key) self.public_key = raw_public_key(self.key) if previous_key_file and previous_key is None and not os.path.exists(previous_key_file): raise ValueError(f"previous_key_file: {previous_key_file} does not exist") self.old_key = load_key(previous_key) if previous_key is not None else (load_or_create_key(previous_key_file) if previous_key_file else None) self.base = urlsplit(self.url).path.rstrip("/") or "/" self.grietens = grietens_url.rstrip("/") self.keys_url = keys_url or f"{self.grietens}/.well-known/grietens-keys.json" self.nonces = store if store is not None else MemoryStore(now) self.log, self.now = log, now # the ONE callable every outbound call of the kit goes through: transport(request, timeout=...) like urllib's opener.open self.transport = transport if transport is not None else _OPENER.open if not callable(self.transport): raise ValueError("transport: a callable(request, timeout=...) that behaves like urllib's opener.open") ok_timeout = isinstance(send_timeout_s, (int, float)) and not isinstance(send_timeout_s, bool) and send_timeout_s > 0 self.send_timeout_s = send_timeout_s if ok_timeout else SEND_TIMEOUT_S self._keys: list = [] self._keys_fetched_at = float("-inf") self._keys_tried_at = float("-inf") self._keys_lock = threading.Lock() self._busy: set = set() self._busy_lock = threading.Lock() # -- signing -------------------------------------------------------------------------------------------------------- def answer_headers(self, purpose: str, bound: str, body: bytes, audience: str | None = None) -> dict: """An answer of ours: purpose hello (bound to the hello's nonce), answer, callback or progress (bound to the request id).""" if purpose not in ("hello", "answer", "callback", "progress"): raise ValueError(f"answer_headers: purpose hello, answer, callback or progress (got {purpose})") # every version: never a signature bound to nothing (an empty request id or nonce would be signed for no request at all) if bound is None or str(bound).strip() == "": raise ValueError("answer_headers: the nonce or the request id the answer is bound to (missing or empty)") ts = str(int(self.now())) if audience: return {"Content-Type": "application/json", "X-Engine-Timestamp": ts, "X-Engine-Sig-Version": "3", "X-Engine-Signature-Ed25519": _b64u(self.key.sign(engine_answer_text_v3(purpose, self.url, audience, str(bound), ts, _sha256(body)).encode()))} return {"Content-Type": "application/json", "X-Engine-Timestamp": ts, "X-Engine-Signature-Ed25519": _b64u(self.key.sign(engine_answer_text(purpose, self.url, str(bound), ts, _sha256(body)).encode()))} def reply(self, purpose: str, bound: str, obj: dict) -> tuple[int, dict, bytes]: b = json.dumps(obj).encode() return 200, self.answer_headers(purpose, bound, b), b def card(self, fields: dict | None = None) -> dict: return {"grietens_engine": "2", **(fields or {}), "public_key": self.public_key} def hello_answer(self, nonce: str) -> dict: """The hello proves the key and carries nothing else (never a claim link); with an old key it hands over to the new one.""" out = {"nonce": nonce} if self.old_key: out["rotation"] = {"new_public_key": self.public_key, "signature_by_old_key": _b64u(self.old_key.sign(rotation_text(self.url, nonce, self.public_key).encode()))} return out # -- Grietens' keys: cached an hour; fetched again at most once a minute whatever the caller sends ---------------------- def _refresh_keys(self) -> None: if self.now() - self._keys_tried_at < KEYS_REFETCH_S: return self._keys_tried_at = self.now() try: deadline = time.monotonic() + KEYS_TIMEOUT_S with self.transport(urllib.request.Request(self.keys_url, headers={"Accept": "application/json"}), timeout=KEYS_TIMEOUT_S) as r: if r.status != 200: raise ValueError(f"HTTP {r.status}") data = b"" while True: chunk = r.read(8192) if not chunk: break data += chunk if len(data) > KEYS_MAX_BYTES: raise ValueError(f"the answer is larger than {KEYS_MAX_BYTES} bytes") if time.monotonic() > deadline: raise TimeoutError(f"no complete answer within {KEYS_TIMEOUT_S} s") j = json.loads(data.decode()) keys = j.get("keys") if isinstance(j, dict) else None if not isinstance(keys, list): raise ValueError('no "keys" list') self._keys = [k for k in keys if isinstance(k, dict) and k.get("alg") == "Ed25519" and isinstance(k.get("kid"), str) and isinstance(k.get("public_key"), str)] self._keys_fetched_at = self.now() except Exception as e: # noqa: BLE001 - the keys read before are kept self.log(f"[grietens] could not read Grietens' keys at {self.keys_url}: {e} (the keys read before are kept)") def _grietens_key(self, kid: str): with self._keys_lock: hit = next((k for k in self._keys if k.get("kid") == kid), None) if hit is None or self.now() - self._keys_fetched_at >= KEYS_FRESH_S: self._refresh_keys() hit = next((k for k in self._keys if k.get("kid") == kid), None) return hit @staticmethod def _headers(headers: dict) -> dict: return {str(k).lower(): (v[0] if isinstance(v, (list, tuple)) else v) for k, v in (headers or {}).items()} def _signature_problem(self, headers: dict, purpose: str, method: str, path: str, body: bytes | None) -> str | None: """Is this call signed by Grietens for `purpose`? -> None, or the plain reason it is refused. A nonce is kept only once the signature verified (an unsigned caller cannot fill the memory).""" h = self._headers(headers) sig = h.get("x-grietens-signature-ed25519") if not sig: return "no X-Grietens-Signature-Ed25519 header: not signed by Grietens" got = str(h.get("x-grietens-purpose") or "") if got != purpose: return f'the call is signed for purpose "{got[:30]}", this one needs "{purpose}"' ts, nonce = str(h.get("x-grietens-timestamp") or "").strip(), str(h.get("x-grietens-nonce") or "") if not re.fullmatch(r"\d{9,11}", ts) or abs(int(ts) - int(self.now())) > SKEW_S: return "the timestamp is missing or more than 5 minutes off this engine's clock" if not _NONCE.match(nonce): return "the nonce is not 16 to 64 base64url characters" if not _canonical_sig(str(sig)): return "the signature is not one Ed25519 signature in canonical base64url" kid = str(h.get("x-grietens-key-id") or "") k = self._grietens_key(kid) if not k: return f'no key Grietens publishes has the id "{re.sub(r"[^A-Za-z0-9_-]", "?", kid)[:40]}"' try: Ed25519PublicKey.from_public_bytes(_unb64u(k["public_key"])).verify( _unb64u(str(sig)), request_text(purpose, method, self.url, path, ts, nonce, _sha256(body)).encode()) except (InvalidSignature, ValueError): return "the signature does not verify (another key, engine address, path, time, nonce or body)" with self._busy_lock: if nonce in self._busy: return "this nonce was seen before: a replayed call" self._busy.add(nonce) try: if self.nonces.has_nonce(nonce): return "this nonce was seen before: a replayed call" self.nonces.remember_nonce(nonce, int(ts) + 2 * SKEW_S) return None finally: with self._busy_lock: self._busy.discard(nonce) def verify(self, method: str, path: str, headers: dict, body: bytes | None) -> dict: """ONE call to the engine's address -> {"ok": True, "purpose", ...} | {"ok": False, "status", "reason"}. path: the RAW path.""" def no(status: int, reason: str): return {"ok": False, "status": status, "reason": reason} m = str(method or "GET").upper() raw_path = str(path or "/").split("?")[0] p = raw_path.rstrip("/") or "/" prefix = "" if self.base == "/" else self.base body = body or b"" if m == "GET" and p == self.base: return {"ok": True, "purpose": "card"} if m == "GET" and p.startswith(prefix + "/"): why = self._signature_problem(headers, "check", "GET", raw_path, None) if why: return no(401, why) return {"ok": True, "purpose": "check", "id": unquote(p[len(prefix) + 1:])} if m != "POST" or p != self.base: return no(404, "not found") # the purpose comes from the SIGNED header (the signature binds X-Grietens-Purpose), so a POST not signed by Grietens is refused # before anything of its body is read; only a verified body is parsed said = str(self._headers(headers).get("x-grietens-purpose") or "") purpose = said if said in _POST_PURPOSES else "quote-request" why = self._signature_problem(headers, purpose, "POST", raw_path, body) if why: return no(401, why) try: req = json.loads(body.decode()) except (ValueError, UnicodeDecodeError): return no(400, "not JSON") if not isinstance(req, dict): return no(400, "not JSON") # a body that is not what the signature was made for is not signed for it: 401, like any other call not signed for what it carries if (req.get("type") == "hello") != (purpose == "hello"): return no(401, "the call is signed as a hello, but its body is not a hello" if purpose == "hello" else "the body is a hello, but the call is signed as a quote request") if (req.get("type") == "buyer_contact") != (purpose == "buyer-contact"): return no(401, "the call is signed as a buyer contact, but its body is not one" if purpose == "buyer-contact" else "the body is a buyer contact, but the call is not signed as one") if str(req.get("contract")) != "1": return no(400, "contract 1 only") # a buyer asked this shop to contact him (only to an engine whose card asks for it): his email, phone and details, for the shop if purpose == "buyer-contact": return {"ok": True, "purpose": purpose, "request_id": str(req["request_id"]), "contact": req} if req.get("request_id") else no(400, "request_id missing") if purpose == "hello": return {"ok": True, "purpose": purpose, "nonce": str(req["nonce"]), "request": req} if _NONCE.match(str(req.get("nonce", ""))) \ else no(400, "a hello carries a nonce") rid = str(req.get("request_id") or "") return {"ok": True, "purpose": purpose, "request_id": rid, "request": req} if rid else no(400, "request_id missing") def send_callback(self, request_id: str, callback_url: str, answer: dict) -> dict: """A late answer, signed for the request id and POSTed to the callback address: needs only those three facts.""" if not request_id or not re.match(r"(?i)^https?://", str(callback_url or "")): return {"ok": False, "status": None, "error": "send_callback needs the request id and its callback_url"} body = json.dumps({"contract": "1", "request_id": str(request_id), **answer}).encode() r = urllib.request.Request(callback_url, data=body, method="POST", headers=self.answer_headers("callback", str(request_id), body)) try: with self.transport(r, timeout=self.send_timeout_s) as res: res.read() return {"ok": 200 <= res.status < 300, "status": res.status, "error": None if res.status < 300 else f"HTTP {res.status}"} except urllib.error.HTTPError as e: return {"ok": False, "status": e.code, "error": f"HTTP {e.code}"} except Exception as e: # noqa: BLE001 return {"ok": False, "status": None, "error": str(e)} def send_progress(self, request_id: str, callback_url: str, progress: dict) -> dict: """A LIVE UPDATE while the quote is made (any number, as often as you like): the bar (label, step, of, percent, eta_seconds, state) and items for the buyer's live feed. Signed for the request id (purpose progress, version 3 naming the Grietens of the callback address). -> {"ok", "status", "body", "error"}. It never changes the quote: the answer comes with a status.""" if not request_id or not re.match(r"(?i)^https?://", str(callback_url or "")): return {"ok": False, "status": None, "body": None, "error": "send_progress needs the request id and its callback_url"} body = json.dumps({"contract": "1", "request_id": str(request_id), "progress": progress or {}}).encode() u = urlsplit(callback_url) audience = f"{u.scheme}://{u.netloc}".lower() r = urllib.request.Request(callback_url, data=body, method="POST", headers=self.answer_headers("progress", str(request_id), body, audience)) try: with self.transport(r, timeout=self.send_timeout_s) as res: out = json.loads(res.read() or b"null") ok = 200 <= res.status < 300 and not (isinstance(out, dict) and out.get("applied") is False) return {"ok": ok, "status": res.status, "body": out, "error": None if ok else (out or {}).get("message")} except urllib.error.HTTPError as e: try: out = json.loads(e.read() or b"null") except Exception: # noqa: BLE001 out = None return {"ok": False, "status": e.code, "body": out, "error": (out or {}).get("error") if isinstance(out, dict) else f"HTTP {e.code}"} except Exception as e: # noqa: BLE001 return {"ok": False, "status": None, "body": None, "error": str(e)} # -- calls to Grietens ---------------------------------------------------------------------------------------------- def _call(self, path: str, purpose: str, obj: dict) -> dict: """Our own call to Grietens, signed with our key for `purpose` (join, key, sign-in-link, quote-report).""" target = f"{self.grietens}{path}" body = json.dumps(obj).encode() ts, nonce = str(int(self.now())), _b64u(os.urandom(18)) u = urlsplit(target) audience = f"{u.scheme}://{u.netloc}".lower() sig = _b64u(self.key.sign(engine_call_text_v3(purpose, "POST", u.path, self.url, audience, ts, nonce, _sha256(body)).encode())) r = urllib.request.Request(target, data=body, method="POST", headers={ "Content-Type": "application/json", "X-Engine-Url": self.url, "X-Engine-Timestamp": ts, "X-Engine-Nonce": nonce, "X-Engine-Sig-Version": "3", "X-Engine-Signature-Ed25519": sig}) try: # a signed call is never sent on to another address (Decision 138): a redirect is an error, never followed with self.transport(r, timeout=CALL_TIMEOUT_S) as res: return {"status": res.status, **json.loads(res.read().decode() or "{}")} except urllib.error.HTTPError as e: try: return {"status": e.code, **json.loads(e.read().decode() or "{}")} except ValueError: return {"status": e.code} def join(self, card_terms: str | None = None) -> dict: """Join the network (or again: the same shop, its card re-read). Never asks for or logs a sign-in link. card_terms: the card's "terms" (the easy path passes it), for the one line about the Data Terms when Grietens' answer has none.""" out = self._call("/api/public/join", "join", {"url": self.url}) link = (out.get("shop") or {}).get("link") if link: self.log(f"[grietens] joined; the shop's public quote page: {link}") elif not out.get("joined"): self.log(f"[grietens] the join did not work (HTTP {out.get('status')}): {str(out.get('error') or '')[:300]}") if out.get("joined") and out.get("created") and not out.get("claimed"): self.log("[grietens] the shop's Grietens account exists (it has no login yet, which is fine). When a person wants to look inside, " "sign_in_link() returns a one-time link for them; the kit never prints it.") if out.get("joined"): self.log(terms_line(out.get("terms"), card_terms, self.grietens)) return out def sign_in_link(self) -> dict: """A fresh one-time link that gives the account a login, RETURNED to the caller (claim_url) and never logged.""" out = self._call("/api/public/engine/sign-in-link", "sign-in-link", {}) if out.get("claim_url"): self.log("[grietens] a one-time sign-in link was issued and returned to the caller (not logged; a new one stops the earlier one)") return out def workspace_key(self) -> dict: """A key for the Grietens API of your own workspace (read, send data, write), RETURNED and never logged.""" out = self._call("/api/public/engine/key", "key", {}) if out.get("key"): self.log("[grietens] a workspace key was issued and returned to the caller (not logged)") return out def report_quote(self, report: dict) -> dict: """The shop's own quotes (report_quote's fields), signed with your key.""" return self._call("/api/public/engine/quotes", "quote-report", report) def terms_line(terms, card_terms, grietens_url: str = "https://app.grietens.cloud") -> str: """The one line join() logs about the Data Terms (Annex 7A, the market price figures): whether the card accepts them and what follows.""" terms = terms if isinstance(terms, dict) else None url = (terms or {}).get("url") or (str(grietens_url).rstrip("/") + "/terms") def then(v): return (f"its quotes are not counted in anonymous price figures until the terms are on record (read {url}, then put terms: \"{v}\" on the card, " "or the owner accepts them when signed in)") if terms is None: # a Grietens that does not answer about the terms if card_terms: return f"[grietens] the card accepts the Grietens Data Terms v{card_terms} ({url})" return f'[grietens] the card does not accept the Grietens Data Terms (no "terms" on it): {then("")}' if terms.get("accepted") is True: return (f"[grietens] the shop has the Grietens Data Terms v{terms.get('current')} on record ({url}): each quote it gives through Grietens from then on " "is counted, as numbers only, in anonymous price figures") said = f'the card says terms "{card_terms}", but it was not recorded' if card_terms else 'the card does not accept the Grietens Data Terms (no "terms" on it)' return f"[grietens] {said}: the engine works as before, but {then(terms.get('current'))}" # -- the easy path ---------------------------------------------------------------------------------------------------------- def _final(a) -> bool: return isinstance(a, dict) and a.get("status") in FINAL class Engine: def __init__(self, url: str, quote, card: dict | None = None, key_file: str | None = None, private_key=None, previous_key=None, previous_key_file: str | None = None, grietens_url: str = "https://app.grietens.cloud", keys_url: str | None = None, store=None, answer_within_s: float = 3.0, log=print, on_hello=None, now=time.time, transport=None, send_timeout_s: float = SEND_TIMEOUT_S, on_buyer_contact=None): self.store = store if store is not None else MemoryStore(now) self.protocol = Protocol(url, key_file=key_file or ("grietens-engine-key.pem" if private_key is None else None), private_key=private_key, previous_key=previous_key, previous_key_file=previous_key_file, grietens_url=grietens_url, keys_url=keys_url, store=self.store, log=log, now=now, transport=transport, send_timeout_s=send_timeout_s) self.url, self.public_key = self.protocol.url, self.protocol.public_key self.quote, self.card_fields = quote, dict(card or {}) t = self.card_fields.get("terms") if t is not None and not (isinstance(t, str) and re.fullmatch(r"\d{1,3}\.\d{1,3}", t)): raise ValueError('card["terms"]: the version of the Grietens Data Terms the person who runs this engine accepts for the shop, as text, e.g. "1.2" (or leave it out)') # a handler for buyer contacts puts notices: ["buyer_contact"] on the card by itself (without one Grietens sends no contact here) self.on_buyer_contact = on_buyer_contact if on_buyer_contact is not None: self.card_fields["notices"] = list(dict.fromkeys(list(self.card_fields.get("notices") or []) + ["buyer_contact"])) self._card_logo = self.card_fields.get("logo") self.answer_within_s, self.log, self.on_hello, self.now = answer_within_s, log, on_hello, now self._lock = threading.RLock() self._running: dict = {} self._sending: set = set() self._pool = ThreadPoolExecutor(max_workers=8) self._served: dict = {} # Decision 137: token -> {path | bytes, name, type, until} # the card's logo given as a local file (a path or bytes) is served by this engine: the card names its address here logo = self._card_logo if logo is not None and not (isinstance(logo, str) and re.match(r"^https?://", logo, re.I)): self.card_fields["logo"] = self.attach(logo, name=None if isinstance(logo, (str, os.PathLike)) else "logo", ttl_s=3650 * 86400)["url"] self.ready = self._pool.submit(self.resume) if store is not None else None # -- files this engine serves for Grietens to fetch (Decision 137) ---------------------------------------------------- _TYPES = {"pdf": "application/pdf", "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "webp": "image/webp"} def attach(self, file, name: str | None = None, type: str | None = None, ttl_s: int = 7 * 86400) -> dict: """A file on a quote, served at an unguessable path on this engine's own address -> {"name", "url", "type"?}.""" is_path = isinstance(file, (str, os.PathLike)) if not is_path and not isinstance(file, (bytes, bytearray)): raise ValueError("attach: a file path or bytes") if is_path and not os.path.exists(file): raise ValueError(f"attach: {file} does not exist") n = str(name or (os.path.basename(str(file)) if is_path else "file"))[:200] or "file" m = re.search(r"\.([A-Za-z0-9]+)$", n) t = type or self._TYPES.get((m.group(1) if m else "").lower()) token = _b64u(os.urandom(24)) self._prune() rec = {"name": n, "type": t, "until": int(self.now()) + ttl_s} if is_path: rec["path"] = str(file) self.store.put(f"file:{token}", {"file": rec, "sent": True, "updated_at": _iso(self.now())}) self._served[token] = rec if is_path else {**rec, "bytes": bytes(file)} out = {"name": n, "url": f"{self.url}/files/{token}/{urllib.parse.quote(n, safe='')}"} if t: out["type"] = t return out def logo(self, file, **kw) -> str: """The shop's logo for the card: its address on this engine (served for ten years).""" return self.attach(file, ttl_s=3650 * 86400, **kw)["url"] def _prune(self) -> None: """An expired entry is dropped from memory (its bytes too): on every attach and every served file.""" now_s = int(self.now()) for k in [k for k, f in self._served.items() if f["until"] < now_s]: self._served.pop(k, None) def files_in_memory(self) -> int: return len(self._served) def _serve_file(self, token: str): self._prune() f = self._served.get(token) if f is None: r = self.store.get(f"file:{token}") if r and isinstance(r.get("file"), dict) and r["file"].get("path") and r["file"].get("until", 0) >= int(self.now()): f = self._served[token] = r["file"] if not f or f["until"] < int(self.now()): return 404, {"Content-Type": "application/json"}, b'{"error":"no such file here"}' try: body = f.get("bytes") if body is None: with open(f["path"], "rb") as fh: body = fh.read() except OSError: return 404, {"Content-Type": "application/json"}, b'{"error":"no such file here"}' ascii_name = re.sub(r'["\\]', "_", re.sub(r"[^\x20-\x7e]", "_", f["name"])) return 200, {"Content-Type": f.get("type") or "application/octet-stream", "X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=600", "Content-Disposition": f'attachment; filename="{ascii_name}"', "Content-Security-Policy": "default-src 'none'; sandbox"}, body def card(self) -> dict: return self.protocol.card(self.card_fields) def join(self) -> dict: return self.protocol.join(card_terms=self.card_fields.get("terms")) def sign_in_link(self) -> dict: return self.protocol.sign_in_link() def workspace_key(self) -> dict: return self.protocol.workspace_key() def report_quote(self, report: dict) -> dict: return self.protocol.report_quote(report) # -- records: every change read, changed and written under one lock ------------------------------------------------- def _update(self, rid: str, change): with self._lock: rec = self.store.get(rid) new = change(rec) if new is not None: new["updated_at"] = _iso(self.now()) self.store.put(rid, new) return new return rec def _alias(self, quote_id, rid: str) -> None: with self._lock: if quote_id and quote_id != rid and self.store.get(quote_id) is None: self.store.put(quote_id, {"alias_of": rid, "sent": True, "updated_at": _iso(self.now())}) def _complete(self, req: dict, a: dict | None) -> dict: a = a or {"status": "failed", "message": "no answer"} return {"contract": "1", "request_id": req.get("request_id"), "shop_id": req.get("shop_id"), "quote_id": a.get("quote_id") or f"q-{str(req.get('request_id', ''))[2:14]}", **a} def _deliver(self, rid: str) -> dict: """Send a final answer to callback_url; tried again later when it did not get through (and on every start).""" with self._lock: if rid in self._sending: return {"ok": False, "status": None, "error": "already being sent"} self._sending.add(rid) try: rec = self.store.get(rid) if not rec or rec.get("sent") is True or not _final(rec.get("answer")): return {"ok": bool(rec and rec.get("sent")), "status": None, "error": None if rec else "unknown request"} out = self.protocol.send_callback(rid, (rec.get("request") or {}).get("callback_url"), rec["answer"]) lasting = out["status"] is not None and 400 <= out["status"] < 500 and out["status"] not in (408, 429) after = self._update(rid, lambda r: r and {**r, "sent": out["ok"] or lasting, "refused": out["error"] if lasting else None, "attempts": (r.get("attempts") or 0) + 1}) qid = rec["answer"].get("quote_id") if out["ok"]: self.log(f"[grietens] quote {qid} for {rid} delivered: HTTP {out['status']}") else: self.log(f"[grietens] delivering quote {qid} for {rid} failed: {out['error']}" + (" (Grietens refused it: not tried again)" if lasting else "")) n = (after or {}).get("attempts") or 1 if not lasting and n <= len(RETRY_AFTER_S): t = threading.Timer(RETRY_AFTER_S[n - 1], self._deliver, args=(rid,)) t.daemon = True t.start() return out finally: with self._lock: self._sending.discard(rid) def _start_quote(self, req: dict): """Run quote() for a stored request; the answer is stored, and sent by callback once "pending" went out.""" rid = str(req.get("request_id")) with self._lock: if rid in self._running: return self._running[rid] def run(): try: a = self._complete(req, self._run_quote(req)) except Exception as e: # noqa: BLE001 - a failed quote is an answer too a = self._complete(req, {"status": "failed", "message": f"the engine could not quote it: {str(e)[:200]}"}) try: rec = self._update(rid, lambda r: {**(r or {"request_id": rid, "request": req, "sent": False}), "answer": a}) if a.get("status") == "pending": self._alias(a.get("quote_id"), rid) if rec.get("pending_sent") and _final(a) and rec.get("sent") is not True: self._deliver(rid) finally: with self._lock: self._running.pop(rid, None) return a fut = self._pool.submit(run) self._running[rid] = fut return fut def handle(self, method: str, path: str, headers: dict, body: bytes) -> tuple[int, dict, bytes]: """ONE call -> (status, headers, body): the transport-free core. path: the request's RAW path.""" def plain(status: int, obj: dict): return status, {"Content-Type": "application/json"}, json.dumps(obj).encode() g = self.protocol if str(method).upper() == "GET": # a served file (Decision 137): unsigned, nothing else on this path hit = re.match(r"^" + re.escape("" if g.base == "/" else g.base) + r"/files/([A-Za-z0-9_-]{32})(?:/[^/]*)?$", str(path or "").split("?")[0]) if hit: return self._serve_file(hit.group(1)) v = g.verify(method, path, headers, body) if not v["ok"]: return plain(v["status"], {"error": "not signed by Grietens", "reason": v["reason"]} if v["status"] == 401 else {"error": v["reason"]}) if v["purpose"] == "card": return plain(200, self.card()) if v["purpose"] == "hello": if self.on_hello: try: self.on_hello(v["request"]) except Exception: # noqa: BLE001 - the hello is answered anyway pass return g.reply("hello", v["nonce"], g.hello_answer(v["nonce"])) # a buyer asked to be contacted: the handler tells a person at the shop now; an error answers 500, so Grietens tries again later if v["purpose"] == "buyer-contact": if self.on_buyer_contact is None: return plain(404, {"error": "this engine takes no buyer-contact notices"}) try: self.on_buyer_contact(v["contact"]) except Exception as e: # noqa: BLE001 - Grietens tries again later self.log(f"[grietens] the buyer-contact handler failed: {e}") return plain(500, {"error": "not taken: try again later"}) return plain(200, {"ok": True}) if v["purpose"] == "check": rec = self.store.get(v["id"]) if rec and rec.get("alias_of"): rec = self.store.get(rec["alias_of"]) if not rec or not rec.get("request_id"): return plain(404, {"error": "no request with this id here"}) # never a "pending" for a request it does not have rid = rec["request_id"] if _final(rec.get("answer")): if rec.get("sent") is not True: self._update(rid, lambda r: {**r, "sent": True}) return g.reply("answer", rid, rec["answer"]) if not rec.get("answer") and rid not in self._running: self._start_quote(rec["request"]) return g.reply("answer", rid, rec.get("answer") or {"contract": "1", "request_id": rid, "status": "pending", "quote_id": f"q-{rid[2:14]}", "message": "still working on it"}) rid, req = v["request_id"], v["request"] # Decision 182: the same request_id with a higher revision is the buyer's answer to the factory's questions (or a fact or a file he # added): a NEW piece of work, priced again from the request as it comes now; the same revision again is a repeat def _newer(r): try: return int((req or {}).get("revision") or 0) > int(((r or {}).get("request") or {}).get("revision") or 0) except (TypeError, ValueError): return False rec = self._update(rid, lambda r: None if (r and not _newer(r)) else {"request_id": rid, "request": req, "answer": None, "pending_sent": False, "sent": False, "attempts": 0}) if not rec.get("answer"): fut = self._start_quote(rec["request"]) try: fut.result(timeout=self.answer_within_s) except FutureTimeout: pass rec = self.store.get(rid) if not rec.get("answer"): pend = {"contract": "1", "request_id": rid, "status": "pending", "quote_id": f"q-{rid[2:14]}", "message": "working on it: the quote follows at callback_url"} self._alias(pend["quote_id"], rid) rec = self._update(rid, lambda r: {**r, "pending_sent": True}) if _final(rec.get("answer")) and rec.get("sent") is not True: # it was finished meanwhile self._pool.submit(self._deliver, rid) return g.reply("answer", rid, pend) if _final(rec["answer"]): if rec.get("sent") is not True: self._update(rid, lambda r: {**r, "sent": True}) elif not rec.get("pending_sent"): self._update(rid, lambda r: {**r, "pending_sent": True}) return g.reply("answer", rid, rec["answer"]) # -- live updates: show the buyer the quote being made ---------------------------------------------------------------- def progress(self, request_id: str, update: dict | None = None) -> dict: """One signed live update to the request's callback address. update: {label, step, of, percent, eta_seconds, state ('working' | 'waiting_for_person'), items: [{"text"} | {"picture"} | {"file"}, each with an optional "id" (sent again: replaces that item)]}; a picture or a file is an https address on this engine's host, OR a local path or bytes (the kit serves it, like attach()). -> {"ok", "status", "body", "error"}; never raises for a network failure.""" update = dict(update or {}) rec = self.store.get(str(request_id)) or {} cb = (rec.get("request") or {}).get("callback_url") if not cb: return {"ok": False, "status": None, "body": None, "error": f"no request {request_id} with a callback_url here"} items = [] for x in update.get("items") or []: k = "picture" if isinstance(x, dict) and x.get("picture") is not None else "file" if isinstance(x, dict) and x.get("file") is not None else None v = x.get(k) if k else None if k and (isinstance(v, (bytes, bytearray)) or (isinstance(v, str) and not re.match(r"(?i)^https://", v))): a = self.attach(bytes(v) if isinstance(v, (bytes, bytearray)) else v, name=x.get("name")) items.append({**({"id": x["id"]} if x.get("id") else {}), k: {"url": a["url"], "name": a["name"]}}) else: items.append(x) if "items" in update: update["items"] = items out = self.protocol.send_progress(str(request_id), cb, update) if not out["ok"] and out["status"] != 200: self.log(f"[grietens] a live update for {request_id} was not taken: {out['error'] or out['status']}") return out def live(self, request_id: str) -> "Live": """What a quote function with two parameters gets: live.progress(update), live.step(label, **update), live.show(*items).""" return Live(self, str(request_id)) def _run_quote(self, req: dict): try: two = len([p for p in inspect.signature(self.quote).parameters.values() if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD, p.VAR_POSITIONAL)]) >= 2 except (TypeError, ValueError): two = False return self.quote(req, self.live(str(req.get("request_id")))) if two else self.quote(req) def complete(self, request_id: str, answer: dict) -> dict: """A person's answer to a request quote() left "pending", at any later time: stored, then sent to callback_url.""" rid = str(request_id) if not isinstance(answer, dict) or answer.get("status") not in FINAL: raise ValueError(f"complete: an answer with status {', '.join(FINAL)}") rec = self._update(rid, lambda r: r and {**r, "answer": self._complete(r["request"], answer), "pending_sent": True, "sent": False, "refused": None, "attempts": 0}) if not rec or not rec.get("request_id"): raise ValueError(f"complete: no request {rid} in the store") return self._deliver(rid) def resume(self) -> None: """On start: every answer made but not delivered is sent; a quote() cut off by the restart runs again.""" try: for rec in self.store.unsent(): if not rec or not rec.get("request_id") or rec.get("alias_of"): continue if _final(rec.get("answer")): self._deliver(rec["request_id"]) elif not rec.get("answer") and rec.get("request"): self._start_quote(rec["request"]) except Exception as e: # noqa: BLE001 self.log(f"[grietens] resuming the stored requests failed: {e}") # -- transports ----------------------------------------------------------------------------------------------------- def wsgi(self, environ, start_response): n = int(environ.get("CONTENT_LENGTH") or 0) body = environ["wsgi.input"].read(n) if n else b"" headers = {k[5:].replace("_", "-").lower(): v for k, v in environ.items() if k.startswith("HTTP_")} # the RAW path as it was sent (PATH_INFO is already decoded; RAW_URI / REQUEST_URI where the server gives it) path = environ.get("RAW_URI") or environ.get("REQUEST_URI") or (environ.get("SCRIPT_NAME", "") + environ.get("PATH_INFO", "")) status, h, b = self.handle(environ["REQUEST_METHOD"], path, headers, body) start_response(f"{status} {'OK' if status < 400 else 'Error'}", list(h.items())) return [b] def serve(self, port: int = 8787) -> None: engine = self class Handler(BaseHTTPRequestHandler): def _go(self): n = int(self.headers.get("Content-Length") or 0) status, h, b = engine.handle(self.command, self.path, dict(self.headers.items()), self.rfile.read(n) if n else b"") self.send_response(status) for k, v in h.items(): self.send_header(k, v) self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) do_GET = do_POST = _go def log_message(self, *a): # quiet pass self.log(f"[grietens] quote engine on port {port}, public address {self.url}") ThreadingHTTPServer(("", port), Handler).serve_forever() class Live: """The live updates of ONE request (Engine.live): progress(update), step(label, **update) counts the steps (1, 2, 3 ... with `of` when given once), show(*items) adds items to the buyer's feed without moving the bar.""" def __init__(self, engine: "Engine", request_id: str): self.engine, self.request_id, self.n, self.of = engine, request_id, 0, None def progress(self, update: dict) -> dict: return self.engine.progress(self.request_id, update) def step(self, label: str, **update) -> dict: self.n += 1 if update.get("of") is not None: self.of = update["of"] return self.progress({**update, "label": label, "step": self.n, **({"of": self.of} if self.of else {})}) def show(self, *items) -> dict: return self.progress({"items": list(items)}) def with_steps(fn, of: int | None = None): """Wrap a quote function so each step("Reading the drawings") inside it sends a live update with the next step number: Engine(quote=with_steps(lambda request, step, show: ..., of=4)). step is the second argument, show the third.""" def quote(request, live=None): first = [True] def step(label, **update): if first[0] and of and update.get("of") is None: update["of"] = of first[0] = False return live.step(label, **update) if live else None return fn(request, step, (live.show if live else (lambda *items: None))) return quote