brewsorted-cli 0.8.4__py3-none-any.whl

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.
@@ -0,0 +1,482 @@
1
+ """Small HTTP transport used by the CLI."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ import re
6
+ from typing import Any, Callable, Literal
7
+ from urllib.parse import urlsplit, urlunsplit
8
+ from uuid import UUID, uuid4
9
+
10
+ import httpx
11
+
12
+ from . import USER_AGENT, __version__
13
+ from .http import http_client
14
+
15
+ ResponseKind = Literal[
16
+ "item", "image", "list", "system_list", "health", "comparison", "context", "preview",
17
+ "strategy_list", "suggestion", "suggestion_list", "attempt", "feedback",
18
+ "feedback_list", "capabilities",
19
+ ]
20
+
21
+ QUALIFIED_ID = re.compile(r"^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]/[1-9][0-9]*$")
22
+ USERNAME = re.compile(r"^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$")
23
+ TOKEN = re.compile(r"^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$")
24
+ SECRET_TEXT = re.compile(
25
+ r"(?i)(?:bearer\s+[^\s,;]+|"
26
+ r"(?:authorization|cookie|action[_ -]?link)\s*[:=]\s*[^\s,;]+)"
27
+ )
28
+ ACTION_URL = re.compile(
29
+ r"(?i)https?://[^\s]+[?&](?:token|code|action|rid)=[^\s]+"
30
+ )
31
+ QUALIFIED_REFERENCE_FIELDS = {
32
+ "attempt_id", "brew_device_id", "brew_id", "brew_method_id", "brewer_id",
33
+ "coffee_bag_id", "coffee_id", "drink_type_id", "equipment_id", "filter_id",
34
+ "grinder_id", "kettle_id", "legacy_id", "recipe_id", "roastery_id",
35
+ "scale_id", "server_id", "source_recipe_id", "suggestion_id", "tasting_id",
36
+ "water_profile_id",
37
+ }
38
+
39
+
40
+ def _record_id(value: Any) -> bool:
41
+ return isinstance(value, str) and QUALIFIED_ID.fullmatch(value) is not None
42
+
43
+
44
+ def _api_origin(value: str) -> str:
45
+ if not value or value != value.strip():
46
+ raise ValueError("API URL must be an exact HTTPS origin")
47
+ parsed = urlsplit(value)
48
+ try:
49
+ parsed.port
50
+ except ValueError as error:
51
+ raise ValueError("API URL must be an exact HTTPS origin") from error
52
+ loopback = parsed.hostname in {"127.0.0.1", "::1", "localhost"}
53
+ if (
54
+ parsed.hostname is None
55
+ or parsed.username is not None
56
+ or parsed.password is not None
57
+ or parsed.path not in {"", "/"}
58
+ or parsed.query
59
+ or parsed.fragment
60
+ or parsed.scheme not in ({"http", "https"} if loopback else {"https"})
61
+ ):
62
+ raise ValueError(
63
+ "API URL must be an exact HTTPS origin; HTTP is allowed only for loopback"
64
+ )
65
+ return urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))
66
+
67
+
68
+ def _redact(value: Any, token: str | None) -> Any:
69
+ if isinstance(value, dict):
70
+ safe: dict[str, Any] = {}
71
+ for key, item in value.items():
72
+ folded = key.casefold().replace("-", "_")
73
+ if (
74
+ "authorization" in folded
75
+ or "cookie" in folded
76
+ or "token" in folded
77
+ or folded in {"action_link", "action_url", "actionlink", "actionurl"}
78
+ ):
79
+ safe[key] = "[redacted]"
80
+ else:
81
+ safe[key] = _redact(item, token)
82
+ return safe
83
+ if isinstance(value, list):
84
+ return [_redact(item, token) for item in value]
85
+ if isinstance(value, str):
86
+ if token:
87
+ value = value.replace(token, "[redacted]")
88
+ return SECRET_TEXT.sub("[redacted]", ACTION_URL.sub("[redacted]", value))
89
+ return value
90
+
91
+
92
+ def _safe_problem(status: int, body: dict[str, Any], token: str | None) -> dict[str, Any]:
93
+ generic = {
94
+ 401: ("Authentication Required", "authentication_required", "Authentication failed."),
95
+ 403: ("Capability Denied", "capability_denied", "This credential cannot perform that operation."),
96
+ 404: ("Not Found", "not_found", "The requested record was not found."),
97
+ }.get(status)
98
+ if generic is None and status == 422 and body.get("code") == "invalid_reference":
99
+ generic = (
100
+ "Invalid Reference", "invalid_reference",
101
+ "A referenced record is invalid.",
102
+ )
103
+ if generic is not None:
104
+ title, code, detail = generic
105
+ return {
106
+ "type": "about:blank", "title": title, "status": status,
107
+ "detail": detail, "code": code,
108
+ }
109
+ return _redact(body, token)
110
+
111
+
112
+ class BackendUnavailable(Exception):
113
+ pass
114
+
115
+
116
+ class ApiError(Exception):
117
+ def __init__(self, status: int, body: dict[str, Any]):
118
+ self.status = status
119
+ self.body = body
120
+ super().__init__(body["detail"])
121
+
122
+
123
+ class InvalidServerResponse(Exception):
124
+ def __init__(self, status: int, detail: str):
125
+ self.body = {
126
+ "type": "about:blank", "title": "Invalid Server Response",
127
+ "status": status, "detail": detail, "code": "invalid_server_response",
128
+ }
129
+ super().__init__(detail)
130
+
131
+
132
+ def _page_error(payload: Any) -> str | None:
133
+ if not isinstance(payload, dict):
134
+ return "expected a JSON object"
135
+ items, page = payload.get("items"), payload.get("page")
136
+ if not isinstance(items, list) or not all(isinstance(item, dict) for item in items):
137
+ return "expected items to be an array of objects"
138
+ if not isinstance(page, dict) or any(
139
+ type(page.get(field)) is not int or page[field] < 0
140
+ for field in ("limit", "offset", "total")
141
+ ):
142
+ return "expected page limit, offset, and total to be nonnegative integers"
143
+ return None
144
+
145
+
146
+ def _strategy_error(payload: Any) -> str | None:
147
+ if not isinstance(payload, dict):
148
+ return "expected a strategy object"
149
+ if not isinstance(payload.get("id"), str) or not payload["id"]:
150
+ return "expected a nonempty strategy id"
151
+ if not isinstance(payload.get("version"), str):
152
+ return "expected a string strategy version"
153
+ if payload.get("kind") not in {"rules", "statistical", "llm"}:
154
+ return "expected a supported strategy kind"
155
+ if not isinstance(payload.get("description"), str):
156
+ return "expected a string strategy description"
157
+ if type(payload.get("requires_external_processing")) is not bool:
158
+ return "expected requires_external_processing to be a boolean"
159
+ return None
160
+
161
+
162
+ def _qualified_references_error(payload: Any) -> str | None:
163
+ if isinstance(payload, list):
164
+ for item in payload:
165
+ detail = _qualified_references_error(item)
166
+ if detail:
167
+ return detail
168
+ return None
169
+ if not isinstance(payload, dict):
170
+ return None
171
+ for key, value in payload.items():
172
+ if key in QUALIFIED_REFERENCE_FIELDS:
173
+ if value is not None and not _record_id(value):
174
+ return f"expected {key} to be a Qualified ID or null"
175
+ elif key == "additional_equipment_ids":
176
+ if not isinstance(value, list) or any(not _record_id(item) for item in value):
177
+ return "expected additional_equipment_ids to contain Qualified IDs"
178
+ detail = _qualified_references_error(value)
179
+ if detail:
180
+ return detail
181
+ return None
182
+
183
+
184
+ def _feedback_error(payload: Any) -> str | None:
185
+ if not isinstance(payload, dict):
186
+ return "expected a Feedback object"
187
+ if any(not _record_id(payload.get(field)) for field in (
188
+ "id", "attempt_id", "suggestion_id"
189
+ )):
190
+ return "expected qualified Feedback, Attempt, and Suggestion ids"
191
+ if payload.get("outcome") not in {"yes", "no", "unclear"}:
192
+ return "expected Feedback outcome yes, no, or unclear"
193
+ if "notes" not in payload or not (
194
+ payload["notes"] is None or isinstance(payload["notes"], str)
195
+ ):
196
+ return "expected Feedback notes to be a string or null"
197
+ if not isinstance(payload.get("created_at"), str):
198
+ return "expected Feedback created_at to be a string"
199
+ return None
200
+
201
+
202
+ def _attempt_error(payload: Any) -> str | None:
203
+ if not isinstance(payload, dict):
204
+ return "expected an Attempt object"
205
+ if any(not _record_id(payload.get(field)) for field in (
206
+ "id", "suggestion_id", "brew_id"
207
+ )):
208
+ return "expected qualified Attempt, Suggestion, and Brew ids"
209
+ if not isinstance(payload.get("setup_snapshot"), dict):
210
+ return "expected Attempt setup_snapshot to be an object"
211
+ if not isinstance(payload.get("created_at"), str):
212
+ return "expected Attempt created_at to be a string"
213
+ if "latest_feedback" not in payload:
214
+ return "expected Attempt latest_feedback"
215
+ latest = payload.get("latest_feedback")
216
+ if latest is not None:
217
+ return _feedback_error(latest)
218
+ return None
219
+
220
+
221
+ def _suggestion_error(payload: Any) -> str | None:
222
+ if not isinstance(payload, dict):
223
+ return "expected a Suggestion object"
224
+ if any(not _record_id(payload.get(field)) for field in ("id", "brew_id")):
225
+ return "expected qualified Suggestion and Brew ids"
226
+ outcome = payload.get("outcome")
227
+ if outcome not in {"proposed", "insufficient_evidence"}:
228
+ return "expected a supported Suggestion outcome"
229
+ if _strategy_error(payload.get("strategy")):
230
+ return "expected Suggestion strategy metadata"
231
+ if not isinstance(payload.get("text"), str):
232
+ return "expected Suggestion text to be a string"
233
+ if not all(
234
+ isinstance(payload.get(field), str)
235
+ for field in (
236
+ "engine_version", "template_version", "corpus_version",
237
+ "corpus_digest", "created_at",
238
+ )
239
+ ):
240
+ return "expected Suggestion version, corpus, digest, and timestamp strings"
241
+ for field in ("analysis_runs", "evidence", "knowledge_cards"):
242
+ if not isinstance(payload.get(field), list) or not all(
243
+ isinstance(item, dict) for item in payload[field]
244
+ ):
245
+ return f"expected Suggestion {field} to be an array of objects"
246
+ proposed_change = payload.get("proposed_change")
247
+ if outcome == "proposed" and not isinstance(proposed_change, dict):
248
+ return "expected a proposed Suggestion change object"
249
+ if outcome == "proposed" and payload.get("insufficient_reason") is not None:
250
+ return "expected a proposed Suggestion without an insufficient reason"
251
+ if outcome == "insufficient_evidence" and proposed_change is not None:
252
+ return "expected an insufficient Suggestion without a proposed change"
253
+ if outcome == "insufficient_evidence" and not isinstance(
254
+ payload.get("insufficient_reason"), str
255
+ ):
256
+ return "expected an insufficient Suggestion reason"
257
+ if "attempt" not in payload:
258
+ return "expected Suggestion attempt"
259
+ attempt = payload["attempt"]
260
+ if attempt is not None:
261
+ return _attempt_error(attempt)
262
+ return None
263
+
264
+
265
+ def _success_error(payload: Any, kind: ResponseKind) -> str | None:
266
+ if not isinstance(payload, dict):
267
+ return "expected a JSON object"
268
+ if kind == "item":
269
+ if not _record_id(payload.get("id")):
270
+ return "expected a qualified item id"
271
+ elif kind == "image":
272
+ try:
273
+ UUID(payload.get("id"))
274
+ except (AttributeError, TypeError, ValueError):
275
+ return "expected a UUID image id"
276
+ if not isinstance(payload.get("user"), str) or not USERNAME.fullmatch(
277
+ payload["user"]
278
+ ):
279
+ return "expected an image owner Username"
280
+ elif kind in {
281
+ "list", "system_list", "strategy_list", "suggestion_list", "feedback_list",
282
+ }:
283
+ detail = _page_error(payload)
284
+ if detail:
285
+ return detail
286
+ validator = {
287
+ "strategy_list": _strategy_error,
288
+ "suggestion_list": _suggestion_error,
289
+ "feedback_list": _feedback_error,
290
+ }.get(kind)
291
+ if validator is not None:
292
+ for item in payload["items"]:
293
+ detail = validator(item)
294
+ if detail:
295
+ return detail
296
+ elif kind == "list" and any(
297
+ not _record_id(item.get("id")) for item in payload["items"]
298
+ ):
299
+ return "expected list items with qualified ids"
300
+ elif kind == "health":
301
+ if payload != {"status": "healthy"}:
302
+ return "expected the minimal healthy status"
303
+ elif kind == "capabilities":
304
+ if payload.get("schema_version") != 1 or type(payload.get("schema_version")) is not int:
305
+ return "expected capability schema version 1"
306
+ if payload.get("supported_api_versions") != ["v1"]:
307
+ return "expected supported API version v1"
308
+ available = payload.get("capabilities")
309
+ if not isinstance(available, dict) or any(
310
+ not isinstance(key, str) or type(value) is not bool
311
+ for key, value in available.items()
312
+ ):
313
+ return "expected capability availability flags"
314
+ if not isinstance(payload.get("recommended_client_bundle_version"), str):
315
+ return "expected a recommended client bundle version"
316
+ elif kind == "comparison":
317
+ if any(not _record_id(payload.get(field)) for field in ("left_id", "right_id")):
318
+ return "expected qualified comparison left_id and right_id"
319
+ changed = payload.get("changed")
320
+ if not isinstance(changed, dict) or not all(
321
+ isinstance(value, dict) and "left" in value and "right" in value
322
+ for value in changed.values()
323
+ ):
324
+ return "expected changed to contain objects with left and right values"
325
+ elif kind == "context":
326
+ for field in (
327
+ "equipment", "devices", "grinders", "brew_methods", "drink_types",
328
+ "recipes", "brews",
329
+ ):
330
+ items = payload.get(field)
331
+ if not isinstance(items, list) or not all(
332
+ isinstance(item, dict) and _record_id(item.get("id"))
333
+ for item in items
334
+ ):
335
+ return f"expected {field} to be an array of objects with qualified ids"
336
+ elif kind == "preview":
337
+ if not _record_id(payload.get("recipe_id")):
338
+ return "expected a qualified recipe_id"
339
+ if not isinstance(payload.get("draft"), dict):
340
+ return "expected draft to be an object"
341
+ if not isinstance(payload.get("issues"), list):
342
+ return "expected issues to be an array"
343
+ if type(payload.get("can_create")) is not bool:
344
+ return "expected can_create to be a boolean"
345
+ elif kind == "suggestion":
346
+ detail = _suggestion_error(payload)
347
+ if detail:
348
+ return detail
349
+ elif kind == "attempt":
350
+ detail = _attempt_error(payload)
351
+ if detail:
352
+ return detail
353
+ elif kind == "feedback":
354
+ detail = _feedback_error(payload)
355
+ if detail:
356
+ return detail
357
+ if kind not in {"health", "image", "system_list", "strategy_list"}:
358
+ return _qualified_references_error(payload)
359
+ return None
360
+
361
+
362
+ def _reject_json_constant(value: str) -> None:
363
+ raise ValueError(f"invalid JSON constant: {value}")
364
+
365
+
366
+ class ApiClient:
367
+ def __init__(
368
+ self, base_url: str, *, token: str | None = None,
369
+ token_provider: Callable[[], str] | None = None,
370
+ timeout: float = 5.0, transport=None, proxy: str | None = None,
371
+ ):
372
+ self.base_url = _api_origin(base_url)
373
+ if token is not None and not TOKEN.fullmatch(token):
374
+ raise ValueError("API access token is invalid")
375
+ if token is not None and token_provider is not None:
376
+ raise ValueError("Only one API credential source is allowed")
377
+ self.token = token
378
+ self.token_provider = token_provider
379
+ self.timeout = timeout
380
+ self.transport = transport
381
+ self.proxy = proxy
382
+
383
+ def submit_product_feedback(self, body):
384
+ from .product_feedback import decode_response, failure, validate_submission
385
+ validate_submission(body)
386
+ # Refresh before the one POST; no response-triggered authentication replay.
387
+ token = self.token_provider() if self.token_provider is not None else self.token
388
+ if token is None or not TOKEN.fullmatch(token):
389
+ raise ValueError("OAuth access token is required for authenticated commands")
390
+ try:
391
+ with http_client(timeout=self.timeout, transport=self.transport,
392
+ proxy=self.proxy) as client:
393
+ with client.stream("POST", self.base_url + "/api/v1/product-feedback",
394
+ json=body, headers={"Authorization": f"Bearer {token}",
395
+ "User-Agent": USER_AGENT, "Accept-Encoding": "identity"}) as response:
396
+ raw = bytearray()
397
+ if response.headers.get("content-encoding", "identity") != "identity":
398
+ raise failure()
399
+ for chunk in response.iter_bytes():
400
+ if len(raw) + len(chunk) > 8192:
401
+ raise failure()
402
+ raw.extend(chunk)
403
+ return decode_response(response.status_code, response.headers, raw)
404
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout):
405
+ raise failure(503, "feedback_unavailable") from None
406
+ except (httpx.HTTPError, httpx.StreamError):
407
+ raise failure() from None
408
+
409
+ def request(
410
+ self, method: str, path: str, *, params: dict[str, Any] | None = None,
411
+ body: dict[str, Any] | None = None, file_path: str | Path | None = None,
412
+ response_kind: ResponseKind = "item",
413
+ expected_status: int | None = None,
414
+ authenticate: bool = True,
415
+ ) -> Any:
416
+ token = (self.token_provider() if self.token_provider is not None else self.token) if authenticate else None
417
+ if authenticate and token is None:
418
+ raise ValueError("OAuth access token is required for authenticated commands")
419
+ if token is not None and not TOKEN.fullmatch(token):
420
+ raise ValueError("API access token is invalid")
421
+ if expected_status is None:
422
+ expected_status = {
423
+ "GET": 200, "POST": 201, "PATCH": 200, "DELETE": 204
424
+ }[method]
425
+ request_path = f"/api{path}" if path.startswith("/v1/") else path
426
+ filtered = {key: value for key, value in (params or {}).items() if value is not None}
427
+ stream = None
428
+ try:
429
+ files = None
430
+ if file_path is not None:
431
+ selected = Path(file_path)
432
+ stream = selected.open("rb")
433
+ files = {"file": (selected.name, stream, "application/octet-stream")}
434
+ with http_client(
435
+ timeout=self.timeout, transport=self.transport, proxy=self.proxy,
436
+ headers={"User-Agent": USER_AGENT, "X-BrewSorted-Client": "cli",
437
+ "X-BrewSorted-Client-Version": __version__,
438
+ "X-BrewSorted-Operation-Id": str(uuid4())},
439
+ ) as client:
440
+ response = client.request(
441
+ method, f"{self.base_url}{request_path}", params=filtered, json=body,
442
+ files=files,
443
+ headers=(
444
+ {"Authorization": f"Bearer {token}"}
445
+ if authenticate else {}
446
+ ),
447
+ )
448
+ except httpx.RequestError as exc:
449
+ raise BackendUnavailable(
450
+ "could not connect to the configured API origin"
451
+ ) from exc
452
+ finally:
453
+ if stream is not None:
454
+ stream.close()
455
+ status = response.status_code
456
+ if not response.is_error and status != expected_status:
457
+ raise InvalidServerResponse(status, f"expected HTTP {expected_status}, received {status}")
458
+ if status == 204:
459
+ if response.content:
460
+ raise InvalidServerResponse(status, "expected an empty body for HTTP 204")
461
+ return None
462
+ media_type = response.headers.get("content-type", "").split(";", 1)[0].strip().lower()
463
+ expected_media_type = "application/problem+json" if response.is_error else "application/json"
464
+ if media_type != expected_media_type:
465
+ raise InvalidServerResponse(status, f"expected Content-Type {expected_media_type}")
466
+ try:
467
+ payload = response.json(parse_constant=_reject_json_constant)
468
+ except ValueError as exc:
469
+ raise InvalidServerResponse(status, "response body is not valid JSON") from exc
470
+ if response.is_error:
471
+ if not isinstance(payload, dict) or any(
472
+ not isinstance(payload.get(field), str) for field in ("code", "title", "detail")
473
+ ) or type(payload.get("status")) is not int or payload["status"] != status:
474
+ raise InvalidServerResponse(
475
+ status, "expected a problem object with string code, title, detail "
476
+ "and matching integer status",
477
+ )
478
+ raise ApiError(status, _safe_problem(status, payload, token))
479
+ detail = _success_error(payload, response_kind)
480
+ if detail:
481
+ raise InvalidServerResponse(status, detail)
482
+ return payload
brewsorted_cli/http.py ADDED
@@ -0,0 +1,29 @@
1
+ """Shared outbound HTTP configuration for API and OAuth traffic."""
2
+ from __future__ import annotations
3
+
4
+ import httpx
5
+
6
+
7
+ def proxy_url(value: str) -> str:
8
+ """Validate without including potentially secret proxy credentials in errors."""
9
+ try:
10
+ url = httpx.URL(value)
11
+ if (url.scheme not in {"http", "https"} or not url.host
12
+ or url.path not in {"", "/"} or url.query or url.fragment):
13
+ raise ValueError
14
+ except (ValueError, httpx.InvalidURL):
15
+ raise ValueError("Proxy must be an absolute HTTP(S) URL without a path, query or fragment") from None
16
+ return value
17
+
18
+
19
+ def http_client(*, proxy: str | None = None, timeout: float = 5.0,
20
+ transport=None, headers=None) -> httpx.Client:
21
+ if proxy is not None:
22
+ proxy_url(proxy)
23
+ try:
24
+ return httpx.Client(
25
+ proxy=proxy, timeout=timeout, transport=transport, headers=headers,
26
+ follow_redirects=False, trust_env=True,
27
+ )
28
+ except (ValueError, httpx.InvalidURL, ImportError):
29
+ raise ValueError("Invalid HTTP proxy or TLS environment configuration") from None