fsanyoto commited on
Commit
9291c01
·
verified ·
1 Parent(s): 17b5276

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "90f3c38cd0",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "f8e0c1a6b4",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 90f3c38cd0
 
1
+ f8e0c1a6b4
api/routes_pdp_publish.py CHANGED
@@ -12,9 +12,9 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool
12
 
13
  from core import pdp_publish as publish
14
  from core import platform_admin
15
- from connectors import amazon_listing_attributes as attributes
16
- from connectors import amazon_listing_write as listing
17
- from connectors import amazon_aplus_write as aplus_write
18
  from deps import Session, err, require_session
19
 
20
 
 
12
 
13
  from core import pdp_publish as publish
14
  from core import platform_admin
15
+ from core import amazon_listing_attributes as attributes
16
+ from core import amazon_listing_write as listing
17
+ from core import amazon_aplus_write as aplus_write
18
  from deps import Session, err, require_session
19
 
20
 
platform/core/amazon_aplus_write.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build confirmed A+ documents and send their approved operations through the listing transport."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import copy
6
+ import hashlib
7
+ import io
8
+ import json
9
+ import re
10
+ import time
11
+ import urllib.parse
12
+
13
+ from core import amazon_listing_write as listing
14
+
15
+
16
+ BASE = "/aplus/2020-11-01"
17
+ RESOURCE = "aplus/2020-11-01/contentDocuments"
18
+ UPLOAD_PATH = "/uploads/2020-11-01/uploadDestinations/" + RESOURCE
19
+ OPERATIONS = {
20
+ "createUploadDestinationForResource": ("POST", UPLOAD_PATH),
21
+ "validateContentDocumentAsinRelations": ("POST", BASE + "/contentAsinValidations"),
22
+ "createContentDocument": ("POST", BASE + "/contentDocuments"),
23
+ "postContentDocumentAsinRelations": ("POST", BASE + "/contentDocuments/{reference}/asins"),
24
+ "postContentDocumentApprovalSubmission": ("POST", BASE + "/contentDocuments/{reference}/approvalSubmissions"),
25
+ "searchContentPublishRecords": ("GET", BASE + "/contentPublishRecords"),
26
+ "getContentDocument": ("GET", BASE + "/contentDocuments/{reference}"),
27
+ }
28
+ MODULES = {
29
+ "A1": ("Standard", "STANDARD_HEADER_IMAGE_TEXT", "standardHeaderImageText", (970, 600)),
30
+ "A2": ("Standard", "STANDARD_FOUR_IMAGE_TEXT", "standardFourImageText", (220, 220)),
31
+ "A3": ("Standard", "STANDARD_SINGLE_IMAGE_SPECS_DETAIL", "standardSingleImageSpecsDetail", (300, 300)),
32
+ "A4": ("Standard", "STANDARD_COMPARISON_TABLE", "standardComparisonTable", (150, 300)),
33
+ "A5": ("Standard", "STANDARD_COMPANY_LOGO", "standardCompanyLogo", (600, 180)),
34
+ "STORY": ("BrandStory", "BRAND_STORY_IMAGE_WITH_LOGO", "brandStoryImageWithLogo", (1464, 625)),
35
+ }
36
+ SHAPES = {
37
+ "text": ({"value": ("string", 10000)}, {"value"}),
38
+ "paragraph": ({"textList": ("list", "text", 1, 100)}, {"textList"}),
39
+ "image": ({"imageId": ("string", 1024), "altText": ("string", 100)}, {"imageId", "altText"}),
40
+ "imageText": ({"image": "image", "headline": "text", "body": "paragraph"}, set()),
41
+ "textBlock": ({"headline": "text", "body": "paragraph"}, set()),
42
+ "textItem": ({"position": ("integer", 100), "text": "text"}, {"position", "text"}),
43
+ "plainItem": ({"position": ("integer", 100), "value": ("string", 250)}, {"position", "value"}),
44
+ "textList": ({"textList": ("list", "textItem", 0, 8)}, {"textList"}),
45
+ "headerList": ({"headline": "text", "block": "textList"}, set()),
46
+ "product": ({"position": ("integer", 6), "image": "image", "title": ("string", 80),
47
+ "asin": ("asin",), "highlight": ("boolean",), "metrics": ("list", "plainItem", 0, 10)}, {"position"}),
48
+ "standardHeaderImageText": ({"headline": "text", "block": "imageText"}, {"block"}),
49
+ "standardFourImageText": ({"headline": "text", **{"block" + str(i): "imageText" for i in range(1, 5)}},
50
+ {"block" + str(i) for i in range(1, 5)}),
51
+ "standardSingleImageSpecsDetail": ({"headline": "text", "image": "image", "descriptionHeadline": "text",
52
+ "descriptionBlock1": "textBlock", "descriptionBlock2": "textBlock", "specificationHeadline": "text",
53
+ "specificationListBlock": "headerList", "specificationTextBlock": "textBlock"}, {"image"}),
54
+ "standardComparisonTable": ({"productColumns": ("list", "product", 1, 6),
55
+ "metricRowLabels": ("list", "plainItem", 0, 10)}, {"productColumns"}),
56
+ "standardCompanyLogo": ({"companyLogo": "image"}, {"companyLogo"}),
57
+ "brandStoryImageWithLogo": ({"title": "text", "description": "paragraph", "desktopImage": "image",
58
+ "mobileImage": "image"}, {"desktopImage", "mobileImage"}),
59
+ }
60
+ STATUS_TTL = 3600
61
+ Failure = listing.ListingWriteFailure
62
+
63
+
64
+ def _asins(values):
65
+ if (not isinstance(values, (list, tuple)) or not values
66
+ or any(not isinstance(v, str) or not re.fullmatch(r"[A-Z0-9]{10}", v) for v in values)):
67
+ raise Failure("aplus", "InvalidAsinSet")
68
+ return sorted(set(values))
69
+
70
+
71
+ def _check_shape(value, rule):
72
+ if isinstance(rule, str):
73
+ fields, required = SHAPES[rule]
74
+ if not isinstance(value, dict) or set(value) - fields.keys() or not required <= value.keys():
75
+ raise Failure("aplus", "InvalidModuleShape")
76
+ for key, item in value.items():
77
+ _check_shape(item, fields[key])
78
+ return
79
+ kind = rule[0]
80
+ if kind == "list":
81
+ if not isinstance(value, list) or not rule[2] <= len(value) <= rule[3]:
82
+ raise Failure("aplus", "InvalidModuleList")
83
+ for item in value:
84
+ _check_shape(item, rule[1])
85
+ positions = [item["position"] for item in value if isinstance(item, dict) and "position" in item]
86
+ valid = len(positions) == len(set(positions))
87
+ elif kind == "string":
88
+ valid = listing._text(value, rule[1])
89
+ elif kind == "integer":
90
+ valid = type(value) is int and 1 <= value <= rule[1]
91
+ elif kind == "boolean":
92
+ valid = type(value) is bool
93
+ else:
94
+ valid = bool(_asins([value]))
95
+ if not valid:
96
+ raise Failure("aplus", "InvalidModuleValue")
97
+
98
+
99
+ def operation_request(market, operation, reference, asin, page_token, body, asins, content_md5, content_type):
100
+ """Encode only the named model parameters, including token-only search continuations."""
101
+ if operation not in OPERATIONS:
102
+ raise Failure(operation, "OperationRefused")
103
+ method, path = OPERATIONS[operation]
104
+ args = {k: v for k, v in {"reference": reference, "asin": asin, "page_token": page_token,
105
+ "body": body, "asins": asins, "content_md5": content_md5, "content_type": content_type}.items()
106
+ if v is not None}
107
+ params = {"marketplaceId": market}
108
+ expected = set()
109
+ if "{reference}" in path:
110
+ if not listing._text(reference) or reference in {".", ".."}:
111
+ raise Failure(operation, "ReferenceRequired")
112
+ path = path.format(reference=urllib.parse.quote(reference, safe=""))
113
+ expected.add("reference")
114
+ if operation == "createUploadDestinationForResource":
115
+ expected = {"content_md5", "content_type"}
116
+ if (not listing._text(content_md5) or content_type not in {"image/png", "image/jpeg"}
117
+ or not re.fullmatch(r"[A-Za-z0-9+/]{22}==", content_md5)):
118
+ raise Failure(operation, "InvalidImageDigestOrType")
119
+ params = {"marketplaceIds": market, "contentMD5": content_md5, "contentType": content_type}
120
+ elif operation == "searchContentPublishRecords":
121
+ if page_token is not None:
122
+ if not listing._text(page_token, listing._MAX_BYTES):
123
+ raise Failure(operation, "InvalidPageToken")
124
+ params, expected = {"pageToken": page_token}, {"page_token"}
125
+ else:
126
+ params["asin"], expected = _asins([asin])[0], {"asin"}
127
+ elif operation == "getContentDocument":
128
+ params["includedDataSet"] = "CONTENTS,METADATA"
129
+ elif operation in {"createContentDocument", "validateContentDocumentAsinRelations"}:
130
+ if not isinstance(body, dict) or set(body) != {"contentDocument"}:
131
+ raise Failure(operation, "ContentDocumentRequired")
132
+ expected.add("body")
133
+ if operation.startswith("validate"):
134
+ params["asinSet"] = ",".join(_asins(asins))
135
+ expected.add("asins")
136
+ elif operation == "postContentDocumentAsinRelations":
137
+ if not isinstance(body, dict) or set(body) != {"asinSet"} or body["asinSet"] != _asins(body["asinSet"]):
138
+ raise Failure(operation, "InvalidAsinSet")
139
+ expected.add("body")
140
+ if set(args) != expected:
141
+ raise Failure(operation, "ParametersRefused")
142
+ return path, params, method
143
+
144
+
145
+ def _s3_url(value):
146
+ if not listing._text(value, 32768) or "\\" in value or value != value.strip():
147
+ return False
148
+ try:
149
+ p = urllib.parse.urlsplit(value)
150
+ host = p.hostname or ""
151
+ s3 = re.fullmatch(r"(?:[a-z0-9][a-z0-9.-]*\.)?s3(?:[.-][a-z0-9-]+)?\.amazonaws\.com", host)
152
+ return bool(s3 and p.scheme == "https" and p.netloc == host and p.port is None
153
+ and not p.username and not p.password and not p.fragment and p.path not in {"", "/"})
154
+ except ValueError:
155
+ return False
156
+
157
+
158
+ def register_upload(transport, response, digest, mime):
159
+ payload = response.get("payload")
160
+ if (not isinstance(payload, dict) or response.get("errors") or not _s3_url(payload.get("url"))
161
+ or not listing._text(payload.get("uploadDestinationId"))
162
+ or payload["uploadDestinationId"] in transport._uploads):
163
+ raise Failure("createUploadDestinationForResource", "InvalidUploadDestination")
164
+ headers = payload.get("headers", {})
165
+ if (not isinstance(headers, dict) or any(not listing._text(k) or not listing._text(v, 8192)
166
+ or k.lower() not in {"content-md5", "x-amz-server-side-encryption", "x-amz-server-side-encryption-aws-kms-key-id"}
167
+ for k, v in headers.items()) or any(k.lower() == "content-md5" and v != digest for k, v in headers.items())):
168
+ raise Failure("createUploadDestinationForResource", "UploadHeadersRefused")
169
+ transport._uploads[payload["uploadDestinationId"]] = {
170
+ **copy.deepcopy(payload), "digest": digest, "mime": mime, "created_at": time.time(), "used": False}
171
+
172
+
173
+ def upload_request(transport, destination_id, content):
174
+ """Resolve an upload capability from an admitted provider reply without accepting a caller URL."""
175
+ cap = transport._uploads.get(destination_id)
176
+ if (not cap or cap["used"] or not 0 <= time.time() - cap["created_at"] < 900
177
+ or type(content) is not bytes or _md5(content) != cap["digest"] or not _s3_url(cap["url"])):
178
+ raise Failure("uploadAplusImage", "UploadCapabilityRequired")
179
+ parts = urllib.parse.urlsplit(cap["url"])
180
+ fields = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
181
+ boundary = "aplus" + listing._nonce()
182
+ chunks = []
183
+ for key, value in fields:
184
+ if not listing._text(key) or any(c in key for c in '"\\'):
185
+ raise Failure("uploadAplusImage", "InvalidUploadFields")
186
+ chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode())
187
+ chunks.extend([f'--{boundary}\r\nContent-Disposition: form-data; name="FILE"; filename="image"\r\n'
188
+ f'Content-Type: {cap["mime"]}\r\n\r\n'.encode(), content,
189
+ f'\r\n--{boundary}--\r\n'.encode()])
190
+ headers = {"Content-MD5": cap["digest"], **cap.get("headers", {}),
191
+ "Content-Type": "multipart/form-data; boundary=" + boundary}
192
+ cap["used"] = True
193
+ return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, "", "")), b"".join(chunks), headers, cap
194
+
195
+
196
+ def guard_request(transport, operation, request, binding):
197
+ p = urllib.parse.urlsplit(request.full_url)
198
+ params = urllib.parse.parse_qs(p.query, keep_blank_values=True)
199
+ if operation == "uploadAplusImage":
200
+ cap = binding[5]
201
+ destination = urllib.parse.urlsplit(cap["url"]) if cap is not None else None
202
+ expected_url = urllib.parse.urlunsplit((destination.scheme, destination.netloc, destination.path, "", "")) if destination else None
203
+ allowed = (cap is not None and any(cap is v for v in transport._uploads.values())
204
+ and cap["used"] and _s3_url(request.full_url) and request.method == "POST"
205
+ and request.full_url == expected_url and request.get_header("Content-md5") == cap["digest"]
206
+ and request.get_header("Content-type", "").startswith("multipart/form-data; boundary=")
207
+ and not p.query and not request.has_header("X-amz-access-token")
208
+ and not request.has_header("Authorization") and callable(binding[4]))
209
+ else:
210
+ allowed = (p.scheme == "https" and p.netloc == urllib.parse.urlsplit(listing.ENDPOINTS[transport.region]).netloc
211
+ and not p.fragment and p.port is None and request.get_header("X-amz-access-token") == transport.token
212
+ and bool(transport.token) and not request.has_header("Authorization"))
213
+ method, pattern = OPERATIONS[operation]
214
+ path = re.escape(pattern).replace(re.escape("{reference}"), r"[^/]+")
215
+ allowed &= bool(re.fullmatch(path, p.path)) and request.method == method
216
+ if operation == "createUploadDestinationForResource":
217
+ allowed &= (set(params) == {"marketplaceIds", "contentMD5", "contentType"}
218
+ and params["marketplaceIds"] == [transport.marketplace]
219
+ and len(params["contentMD5"]) == 1 and bool(re.fullmatch(r"[A-Za-z0-9+/]{22}==", params["contentMD5"][0]))
220
+ and params["contentType"] in (["image/png"], ["image/jpeg"]))
221
+ elif operation == "searchContentPublishRecords" and set(params) == {"pageToken"}:
222
+ allowed &= len(params["pageToken"]) == 1 and listing._text(params["pageToken"][0], listing._MAX_BYTES)
223
+ else:
224
+ extra = {"getContentDocument": "includedDataSet", "searchContentPublishRecords": "asin",
225
+ "validateContentDocumentAsinRelations": "asinSet"}.get(operation)
226
+ allowed &= params.get("marketplaceId") == [transport.marketplace]
227
+ allowed &= set(params) == ({"marketplaceId", extra} if extra else {"marketplaceId"})
228
+ if extra == "includedDataSet":
229
+ allowed &= params.get(extra) == ["CONTENTS,METADATA"]
230
+ elif extra in {"asin", "asinSet"}:
231
+ values = params.get(extra, [])
232
+ allowed &= len(values) == 1 and bool(_asins(values[0].split(",")))
233
+ if method == "POST":
234
+ allowed &= callable(binding[4])
235
+ if operation in {"getContentDocument", "searchContentPublishRecords", "createUploadDestinationForResource",
236
+ "postContentDocumentApprovalSubmission"}:
237
+ allowed &= request.data is None
238
+ else:
239
+ body = json.loads(request.data)
240
+ expected = "asinSet" if operation == "postContentDocumentAsinRelations" else "contentDocument"
241
+ allowed &= isinstance(body, dict) and set(body) == {expected}
242
+ if not allowed:
243
+ raise Failure(operation, "RequestRefused")
244
+
245
+
246
+ def _md5(content):
247
+ return base64.b64encode(hashlib.md5(content, usedforsecurity=False).digest()).decode("ascii")
248
+
249
+
250
+ def _image_info(content):
251
+ from PIL import Image, UnidentifiedImageError
252
+
253
+ if type(content) is not bytes or not content or len(content) > listing._MAX_BYTES:
254
+ raise Failure("aplus", "InvalidImage")
255
+ try:
256
+ with Image.open(io.BytesIO(content)) as image:
257
+ width, height = image.size
258
+ mime = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format)
259
+ image.verify()
260
+ except (OSError, ValueError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError):
261
+ raise Failure("aplus", "InvalidImage") from None
262
+ if mime is None:
263
+ raise Failure("aplus", "ImageTypeRefused")
264
+ return {"sha256": hashlib.sha256(content).hexdigest(), "width": width, "height": height, "mime": mime}
265
+
266
+
267
+ def _image_slots(key, payload):
268
+ if key == "A1":
269
+ return [payload.get("block", {}).get("image")]
270
+ if key == "A2":
271
+ return [payload.get("block" + str(i), {}).get("image") for i in range(1, 5)]
272
+ if key == "A3":
273
+ return [payload.get("image")]
274
+ if key == "A4":
275
+ columns = payload.get("productColumns")
276
+ if not isinstance(columns, list) or not 1 <= len(columns) <= 6:
277
+ raise Failure("aplus", "InvalidComparisonColumns")
278
+ return [column.get("image") for column in columns]
279
+ if key == "A5":
280
+ return [payload.get("companyLogo")]
281
+ return [payload.get("desktopImage"), payload.get("mobileImage")]
282
+
283
+
284
+ def build_documents(parts, images, *, name, locale):
285
+ """Map confirmed prototype parts to Standard EBC and BrandStory provider documents."""
286
+ if (not isinstance(parts, list) or not parts or not isinstance(images, dict)
287
+ or not listing._text(name, 100) or not re.fullmatch(r"[a-z]{2}-[A-Z]{2}", str(locale))):
288
+ raise Failure("aplus", "InvalidDocument")
289
+ documents, manifest, seen = {}, {}, set()
290
+ for part in parts:
291
+ if not isinstance(part, dict) or set(part) != {"key", "confirmed", "module"}:
292
+ raise Failure("aplus", "InvalidPart")
293
+ key = part["key"]
294
+ if not isinstance(key, str) or key not in MODULES or key in seen or part["confirmed"] is not True:
295
+ raise Failure("aplus", "ConfirmedPartRequired")
296
+ seen.add(key)
297
+ kind, module_type, field, minimum = MODULES[key]
298
+ if len(name + " " + kind) > 100:
299
+ raise Failure("aplus", "DocumentNameTooLong")
300
+ module = copy.deepcopy(part["module"])
301
+ if (not isinstance(module, dict) or set(module) != {"contentModuleType", field}
302
+ or module["contentModuleType"] != module_type or not isinstance(module[field], dict)):
303
+ raise Failure("aplus", "ModuleTypeRefused")
304
+ _check_shape(module[field], field)
305
+ slots = _image_slots(key, module[field])
306
+ for index, slot in enumerate(slots):
307
+ if (not isinstance(slot, dict) or set(slot) != {"imageId", "altText"}
308
+ or not listing._text(slot["altText"], 100) or not listing._text(slot["imageId"])
309
+ or slot["imageId"] not in images):
310
+ raise Failure("aplus", "ImageReferenceRequired")
311
+ image_id = slot["imageId"]
312
+ info = manifest.setdefault(image_id, _image_info(images[image_id]))
313
+ width, height = (463, 625) if key == "STORY" and index == 1 else minimum
314
+ if info["width"] < width or info["height"] < height:
315
+ raise Failure("aplus", "ImageBelowModuleMinimum")
316
+ if key == "STORY" and len(module[field].get("title", {}).get("value", "")) > 30:
317
+ raise Failure("aplus", "StoryTitleTooLong")
318
+ document = documents.setdefault(kind, {"name": name + " " + kind,
319
+ "contentType": "EBC" if kind == "Standard" else "BrandStory", "locale": locale, "contentModuleList": []})
320
+ document["contentModuleList"].append(module)
321
+ if set(images) != set(manifest):
322
+ raise Failure("aplus", "UnboundImage")
323
+ return documents, manifest
324
+
325
+
326
+ def _state(document):
327
+ value = document.setdefault("aplus", {"receipts": {}, "status": {}})
328
+ if not isinstance(value, dict) or any(not isinstance(value.get(k), dict) for k in ("receipts", "status")):
329
+ raise Failure("aplus", "InvalidTenantState")
330
+ return value
331
+
332
+
333
+ def _materialize(value, destinations, manifest):
334
+ if isinstance(value, list):
335
+ return [_materialize(v, destinations, manifest) for v in value]
336
+ if not isinstance(value, dict):
337
+ return value
338
+ if set(value) == {"imageId", "altText"}:
339
+ image_id = value["imageId"]
340
+ dimensions = {k: {"value": manifest[image_id][k], "units": "pixels"} for k in ("width", "height")}
341
+ return {"uploadDestinationId": destinations[image_id], "altText": value["altText"],
342
+ "imageCropSpecification": {"size": dimensions}}
343
+ return {k: _materialize(v, destinations, manifest) for k, v in value.items()}
344
+
345
+
346
+ class APlusPublisher:
347
+ """Own A+ plans, receipts and hourly memo state within one tenant runtime."""
348
+
349
+ def __init__(self, rt, approval_reader, *, connection_id=None, timeout=30):
350
+ self.rt, self.tenant_key, self.approval_reader = rt, listing._tenant(rt), approval_reader
351
+ self.transport = listing._Transport(rt, connection_id=connection_id, timeout=timeout)
352
+
353
+ def _scope(self):
354
+ t = self.transport
355
+ if listing._tenant(self.rt) != self.tenant_key:
356
+ raise Failure("aplus", "TenantChanged")
357
+ return {"tenant_key": self.tenant_key, "connection_id": t.connection_id, "region": t.region,
358
+ "marketplace_id": t.marketplace, "seller_id": t.fields["seller_id"]}
359
+
360
+ def _receipt(self, receipt_id):
361
+ return _state(listing._read(self.rt))["receipts"].get(receipt_id)
362
+
363
+ def _save(self, receipt, previous):
364
+ def save(document):
365
+ rows = _state(document)["receipts"]
366
+ if rows.get(receipt["id"]) != previous:
367
+ raise Failure("aplus", "ReceiptChanged")
368
+ if previous is None and any(row["binding"]["workflow"] == receipt["binding"]["workflow"]
369
+ and row["state"] in {"pending", "unknown"} for row in rows.values()):
370
+ raise Failure("aplus", "ReconciliationRequired")
371
+ rows[receipt["id"]] = copy.deepcopy(receipt)
372
+
373
+ stored = listing._change(self.rt, save)
374
+ if _state(stored)["receipts"].get(receipt["id"]) != receipt:
375
+ raise Failure("aplus", "PersistenceUnproven")
376
+
377
+ def _authorize(self, binding, approval_id, receipt=None):
378
+ if any(binding.get(k) != v for k, v in self._scope().items()):
379
+ raise Failure("aplus", "ScopeChanged")
380
+ approved = listing.read_approval(self.rt, self.approval_reader, approval_id, binding)
381
+ if receipt is not None and self._receipt(receipt["id"]) != receipt:
382
+ raise Failure("aplus", "PendingReceiptRequired")
383
+ if not listing.writes_enabled(self.rt):
384
+ raise Failure("aplus", "WritesDisabled")
385
+ return approved
386
+
387
+ def _write(self, receipt, operation, **arguments):
388
+ previous = copy.deepcopy(receipt)
389
+ receipt["operations"].append({"operation": operation, "request": {
390
+ k: hashlib.sha256(v).hexdigest() if type(v) is bytes else copy.deepcopy(v)
391
+ for k, v in arguments.items()}, "state": "pending"})
392
+ self._save(receipt, previous)
393
+ boundary = lambda: self._authorize(receipt["binding"], receipt["approval_id"], receipt)
394
+ if operation == "uploadAplusImage":
395
+ response = self.transport.upload_aplus_image(boundary=boundary, **arguments)
396
+ else:
397
+ response = self.transport.aplus(operation, boundary=boundary, **arguments)
398
+ if response.get("errors") and operation != "validateContentDocumentAsinRelations":
399
+ raise Failure(operation, "ProviderErrors")
400
+ previous = copy.deepcopy(receipt)
401
+ receipt["operations"][-1].update(state="complete", response=copy.deepcopy(response))
402
+ self._save(receipt, previous)
403
+ return response
404
+
405
+ def _content(self, reference):
406
+ scope = {**self._scope(), "contentReferenceKey": reference}
407
+ key, token, now = listing._hash(scope), listing._nonce(), time.time()
408
+
409
+ def reserve(document):
410
+ rows = _state(document)["status"]
411
+ cached = rows.get(key)
412
+ if cached is None or not 0 <= now - cached["at"] < STATUS_TTL:
413
+ rows[key] = {"scope": scope, "at": now, "token": token, "state": "pending"}
414
+
415
+ stored = listing._change(self.rt, reserve)
416
+ row = _state(stored)["status"][key]
417
+ if row["scope"] != scope:
418
+ raise Failure("getContentDocument", "ScopeChanged")
419
+ if row["token"] != token:
420
+ if row["state"] != "complete":
421
+ raise Failure("getContentDocument", "HourlyReadPendingOrUnknown")
422
+ return copy.deepcopy(row["response"])
423
+ response = self.transport.aplus("getContentDocument", reference=reference)
424
+ record = response.get("contentRecord", {})
425
+ if (response.get("errors") or record.get("contentReferenceKey") != reference
426
+ or record.get("contentMetadata", {}).get("marketplaceId") != self.transport.marketplace):
427
+ raise Failure("getContentDocument", "InvalidContentRecord")
428
+
429
+ def finish(document):
430
+ rows = _state(document)["status"]
431
+ if rows.get(key) != row:
432
+ raise Failure("getContentDocument", "MemoChanged")
433
+ rows[key] = {**row, "state": "complete", "response": response}
434
+
435
+ saved = listing._change(self.rt, finish)
436
+ if _state(saved)["status"].get(key) != {**row, "state": "complete", "response": response}:
437
+ raise Failure("getContentDocument", "PersistenceUnproven")
438
+ return copy.deepcopy(response)
439
+
440
+ def aplus_status(self, reference):
441
+ if not listing._text(reference):
442
+ raise Failure("getContentDocument", "ReferenceRequired")
443
+ if not listing.writes_enabled(self.rt):
444
+ return {"state": "disabled", "contentReferenceKey": reference}
445
+ response = self._content(reference)
446
+ status = response["contentRecord"]["contentMetadata"].get("status")
447
+ if status not in {"DRAFT", "SUBMITTED", "APPROVED", "REJECTED"}:
448
+ raise Failure("getContentDocument", "UnknownContentStatus")
449
+ return {"state": status, "contentReferenceKey": reference, "reasons": copy.deepcopy(response.get("warnings", []))}
450
+
451
+ def _records(self, asin):
452
+ records, token, seen = [], None, set()
453
+ while True:
454
+ arguments = {"page_token": token} if token else {"asin": asin}
455
+ response = self.transport.aplus("searchContentPublishRecords", **arguments)
456
+ rows = response.get("publishRecordList")
457
+ if (response.get("errors") or not isinstance(rows, list) or any(not isinstance(r, dict)
458
+ or r.get("asin") != asin or r.get("marketplaceId") != self.transport.marketplace
459
+ or not listing._text(r.get("contentReferenceKey")) for r in rows)):
460
+ raise Failure("searchContentPublishRecords", "InvalidPublishRecords")
461
+ records.extend(rows)
462
+ token = response.get("nextPageToken")
463
+ if token is None:
464
+ return records
465
+ if not listing._text(token, listing._MAX_BYTES) or token in seen:
466
+ raise Failure("searchContentPublishRecords", "InvalidPagination")
467
+ seen.add(token)
468
+
469
+ def _snapshot(self, binding):
470
+ records = [r for asin in sorted(set(binding["asins"] + (binding["prior_asins"] or [])))
471
+ for r in self._records(asin)]
472
+ records = [r for r in records if r.get("locale") == binding["locale"] and
473
+ r.get("contentType") in {d["contentType"] for d in binding["documents"].values()}]
474
+ if records and binding["prior_asins"] is None:
475
+ raise Failure("aplus", "PriorAsinInventoryRequired")
476
+ workflow_refs = {r["contentReferenceKey"] for r in records if r["asin"] in binding["asins"]}
477
+ if any(not any(r["asin"] == asin and r["contentReferenceKey"] in workflow_refs for r in records)
478
+ for asin in binding["prior_asins"] or []):
479
+ raise Failure("aplus", "PriorAsinRelationUnproven")
480
+ snapshots = {ref: self._content(ref) for ref in sorted({r["contentReferenceKey"] for r in records})}
481
+ return {"publishRecordList": records, "documents": snapshots}
482
+
483
+ def _publish_documents(self, receipt, images):
484
+ binding, destinations = receipt["binding"], {}
485
+ for image_id, info in binding["images"].items():
486
+ response = self._write(receipt, "createUploadDestinationForResource",
487
+ content_md5=_md5(images[image_id]), content_type=info["mime"])
488
+ destination = response["payload"]["uploadDestinationId"]
489
+ self._write(receipt, "uploadAplusImage", destination_id=destination, content=images[image_id])
490
+ destinations[image_id] = destination
491
+ bodies = {kind: {"contentDocument": _materialize(document, destinations, binding["images"])}
492
+ for kind, document in binding["documents"].items()}
493
+ asins = sorted(set(binding["asins"] + (binding["prior_asins"] or [])))
494
+ for body in bodies.values():
495
+ result = self._write(receipt, "validateContentDocumentAsinRelations", body=body, asins=asins)
496
+ if not isinstance(result.get("errors"), list) or result["errors"]:
497
+ return "invalid"
498
+ for kind, body in bodies.items():
499
+ result = self._write(receipt, "createContentDocument", body=body)
500
+ reference = result.get("contentReferenceKey")
501
+ if not listing._text(reference) or reference in receipt["snapshot"]["documents"]:
502
+ raise Failure("createContentDocument", "NewReferenceRequired")
503
+ previous = copy.deepcopy(receipt)
504
+ receipt["documents"][kind] = reference
505
+ self._save(receipt, previous)
506
+ self._write(receipt, "postContentDocumentAsinRelations", reference=reference, body={"asinSet": asins})
507
+ self._write(receipt, "postContentDocumentApprovalSubmission", reference=reference)
508
+ return "submitted"
509
+
510
+ def publish_aplus(self, workflow, asins, parts, images, *, name, locale, approval_id, prior_asins=None):
511
+ if isinstance(images, dict):
512
+ images = images.copy()
513
+ documents, manifest = build_documents(parts, images, name=name, locale=locale)
514
+ if not listing._text(workflow):
515
+ raise Failure("aplus", "WorkflowRequired")
516
+ binding = {**self._scope(), "workflow": workflow, "asins": _asins(asins), "locale": locale,
517
+ "prior_asins": None if prior_asins is None else _asins(prior_asins),
518
+ "documents": documents, "images": manifest}
519
+ if not listing.writes_enabled(self.rt):
520
+ return {"state": "disabled", "sent": False, "binding": binding}
521
+ approved = self._authorize(binding, approval_id)
522
+ key = listing._hash({**self._scope(), "workflow": workflow, "approval_id": approval_id})
523
+ previous = self._receipt(key)
524
+ if previous is not None:
525
+ if previous["binding"] != binding:
526
+ raise Failure("aplus", "ReservedApprovalMismatch")
527
+ return copy.deepcopy(previous)
528
+ snapshot = self._snapshot(binding)
529
+ self._authorize(binding, approval_id)
530
+ receipt = {"id": key, "binding": binding, "approval_id": approval_id, "approved_by": approved["approved_by"],
531
+ "snapshot": snapshot, "state": "pending", "documents": {}, "operations": [], "at": time.time()}
532
+ self._save(receipt, None)
533
+ try:
534
+ state = self._publish_documents(receipt, images)
535
+ except Failure as exc:
536
+ stored = self._receipt(key)
537
+ if stored is not None:
538
+ self._save({**stored, "state": "unknown", "failure_class": exc.failure_class}, stored)
539
+ raise
540
+ previous = copy.deepcopy(receipt)
541
+ receipt.update(state=state, sent=state == "submitted", finished_at=time.time())
542
+ self._save(receipt, previous)
543
+ return copy.deepcopy(receipt)
544
+
545
+
546
+ def publish_aplus(rt, workflow, asins, parts, images, *, name, locale, approval_id, approval_reader,
547
+ prior_asins=None, connection_id=None):
548
+ publisher = APlusPublisher(rt, approval_reader, connection_id=connection_id)
549
+ return publisher.publish_aplus(workflow, asins, parts, images, name=name, locale=locale,
550
+ approval_id=approval_id, prior_asins=prior_asins)
551
+
552
+
553
+ def aplus_status(rt, reference, *, connection_id=None):
554
+ return APlusPublisher(rt, None, connection_id=connection_id).aplus_status(reference)
platform/core/amazon_listing_attributes.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Translate the twelve details editor fields using one product type's supplied schema."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ from decimal import Decimal
6
+ from fractions import Fraction
7
+ import math
8
+ import re
9
+
10
+
11
+ FIELDS = (
12
+ ("item_dimensions", "dimensions", ("item_dimensions",)),
13
+ ("item_weight", "weight", ("item_weight",)),
14
+ ("package_dimensions", "dimensions", ("item_package_dimensions", "package_dimensions")),
15
+ ("package_weight", "weight", ("item_package_weight", "package_weight")),
16
+ ("number_of_items", "integer", ("number_of_items",)),
17
+ ("number_of_pieces", "integer", ("number_of_pieces",)),
18
+ ("unit_count", "count", ("unit_count",)),
19
+ ("material", "text", ("material",)),
20
+ ("color", "text", ("color",)),
21
+ ("size", "text", ("size",)),
22
+ ("shape", "text", ("shape",)),
23
+ ("uses", "text", ("recommended_uses_for_product", "recommended_uses")),
24
+ )
25
+ EDITOR_KEYS = frozenset(row[0] for row in FIELDS)
26
+ DETAIL_ATTRIBUTES = frozenset(name for _, _, names in FIELDS for name in names)
27
+ _UNITS = {
28
+ "in": ("in", "inch", "inches"), "ft": ("ft", "foot", "feet"),
29
+ "cm": ("cm", "centimeter", "centimeters"), "mm": ("mm", "millimeter", "millimeters"),
30
+ "m": ("m", "meter", "meters"), "lb": ("lb", "lbs", "pound", "pounds"),
31
+ "oz": ("oz", "ounce", "ounces"), "kg": ("kg", "kilogram", "kilograms"),
32
+ "g": ("g", "gram", "grams"),
33
+ }
34
+ _INCHES = {"in": Fraction(1), "ft": Fraction(12), "cm": Fraction(50, 127),
35
+ "mm": Fraction(5, 127), "m": Fraction(5000, 127)}
36
+ _NUMBER = r"(?:\d+(?:\.\d*)?|\.\d+)"
37
+ _MEASURE = re.compile(rf"\s*({_NUMBER})\s*([A-Za-z]+)\s*\Z")
38
+ _DIMENSIONS = re.compile(rf"\s*({_NUMBER})\s*[xX×]\s*({_NUMBER})\s*[xX×]\s*({_NUMBER})\s*([A-Za-z]+)\s*\Z")
39
+
40
+
41
+ class DetailFailure(ValueError):
42
+ """Carry a fixed reason and the schema's units without disclosing provider payloads."""
43
+
44
+ def __init__(self, reason, field=None, allowed_units=()):
45
+ self.reason, self.field, self.allowed_units = reason, field, list(allowed_units)
46
+ super().__init__(reason + (": " + field if field else ""))
47
+
48
+
49
+ def _local_schema(value, root, trail=()):
50
+ if isinstance(value, list):
51
+ return [_local_schema(item, root, trail) for item in value]
52
+ if not isinstance(value, dict):
53
+ return value
54
+ if "$dynamicRef" in value or "$recursiveRef" in value:
55
+ raise DetailFailure("UnsupportedSchemaReference")
56
+ ref = value.get("$ref")
57
+ result = {}
58
+ if ref is not None:
59
+ if not isinstance(ref, str) or not ref.startswith("#/") or ref in trail:
60
+ raise DetailFailure("LocalSchemaReferenceRequired")
61
+ target = root
62
+ try:
63
+ for key in ref[2:].split("/"):
64
+ key = key.replace("~1", "/").replace("~0", "~")
65
+ target = target[int(key)] if isinstance(target, list) else target[key]
66
+ except (KeyError, TypeError, ValueError, IndexError):
67
+ raise DetailFailure("SchemaReferenceMissing") from None
68
+ result = _local_schema(target, root, (*trail, ref))
69
+ if not isinstance(result, dict):
70
+ raise DetailFailure("InvalidSchemaReference")
71
+ own = {key: _local_schema(item, root, trail) for key, item in value.items()
72
+ if key not in {"$ref", "$id", "$schema"}}
73
+ return {"allOf": [result, own]} if ref is not None and own else (result if ref is not None else own)
74
+
75
+
76
+ def _properties(schema):
77
+ result = dict(schema.get("properties", {}))
78
+ for part in schema.get("allOf", []):
79
+ for name, rule in _properties(part).items():
80
+ result[name] = {"allOf": [result[name], rule]} if name in result else rule
81
+ return result
82
+
83
+
84
+ def _enum(schema):
85
+ values = schema.get("enum", [schema["const"]] if "const" in schema else None)
86
+ for part in schema.get("allOf", []):
87
+ other = _enum(part)
88
+ if other is not None:
89
+ values = other if values is None else [v for v in values if v in other]
90
+ return values
91
+
92
+
93
+ def _keyword(schema, key):
94
+ if key in schema:
95
+ return schema[key]
96
+ return next((value for part in schema.get("allOf", [])
97
+ if (value := _keyword(part, key)) is not None), None)
98
+
99
+
100
+ def _unit_key(value):
101
+ value = str(value).lower()
102
+ return next((key for key, names in _UNITS.items() if value in names), value)
103
+
104
+
105
+ def _number(value, field):
106
+ number = float(value)
107
+ if not math.isfinite(number):
108
+ raise DetailFailure("InvalidNumber", field)
109
+ return int(number) if number.is_integer() else number
110
+
111
+
112
+ def _format(value, factor=None):
113
+ if type(value) not in (int, float) or not math.isfinite(value):
114
+ raise DetailFailure("InvalidLiveNumber")
115
+ number = Decimal(str(value))
116
+ if factor is not None:
117
+ try:
118
+ converted = Fraction(number) * factor
119
+ number = float(converted)
120
+ # Keep exact fractional sides distinct from integers at the JSON-number boundary.
121
+ if number.is_integer() and converted.denominator != 1:
122
+ number = math.nextafter(number, math.inf if converted > number else -math.inf)
123
+ number = Decimal(str(_number(number, None)))
124
+ except OverflowError:
125
+ raise DetailFailure("InvalidLiveNumber") from None
126
+ text = format(number, "f")
127
+ return text.rstrip("0").rstrip(".") if "." in text else text
128
+
129
+
130
+ def _validator(schema):
131
+ try:
132
+ from jsonschema import Draft201909Validator
133
+ except ImportError:
134
+ raise DetailFailure("SchemaValidatorUnavailable") from None
135
+ return Draft201909Validator(schema)
136
+
137
+
138
+ class DetailsSchema:
139
+ """Bind field names, shapes and units to one marketplace and product type."""
140
+
141
+ def __init__(self, product_type, marketplace, schema, *, language="en_US"):
142
+ if not all(isinstance(v, str) and re.fullmatch(r"[A-Za-z0-9_.:-]+", v)
143
+ for v in (product_type, marketplace, language)):
144
+ raise DetailFailure("InvalidSchemaIdentity")
145
+ if not isinstance(schema, dict) or not isinstance(schema.get("properties"), dict):
146
+ raise DetailFailure("ProductTypeSchemaRequired")
147
+ self.product_type, self.marketplace, self.language = product_type, marketplace, language
148
+ self.schema = _local_schema(copy.deepcopy(schema), schema)
149
+ props = _properties(self.schema)
150
+ self.fields, self.unsupported = {}, []
151
+ for key, kind, names in FIELDS:
152
+ attribute = next((name for name in names if name in props), None)
153
+ if attribute is None:
154
+ self.unsupported.append(key)
155
+ continue
156
+ rule = props[attribute]
157
+ item = _keyword(rule, "items")
158
+ if _keyword(rule, "type") != "array" or not isinstance(item, dict):
159
+ raise DetailFailure("UnsupportedAttributeShape", key)
160
+ self.fields[key] = {"attribute": attribute, "kind": kind, "rule": rule,
161
+ "item": item, "properties": _properties(item)}
162
+
163
+ def _field(self, key):
164
+ if key not in self.fields:
165
+ raise DetailFailure("AttributeUnavailable", key)
166
+ return self.fields[key]
167
+
168
+ def _unit(self, key, rule, supplied):
169
+ allowed = _enum(rule)
170
+ if not allowed or not all(isinstance(unit, str) for unit in allowed):
171
+ raise DetailFailure("SchemaUnitsRequired", key)
172
+ unit = next((unit for unit in allowed if _unit_key(unit) == _unit_key(supplied)), None)
173
+ if unit is None:
174
+ raise DetailFailure("UnitRefused", key, allowed)
175
+ if self.fields[key]["kind"] == "dimensions" and _unit_key(unit) not in _INCHES:
176
+ raise DetailFailure("UnsupportedPhysicalUnit", key, allowed)
177
+ return unit
178
+
179
+ def _base(self, properties):
180
+ result = {}
181
+ if "marketplace_id" in properties:
182
+ result["marketplace_id"] = self.marketplace
183
+ if "language_tag" in properties:
184
+ result["language_tag"] = self.language
185
+ return result
186
+
187
+ def _count(self, key, text, properties):
188
+ match = re.fullmatch(rf"\s*({_NUMBER})(?:\s+(.+?))?\s*", text)
189
+ if not match:
190
+ raise DetailFailure("InvalidCount", key)
191
+ result = {"value": _number(match[1], key)}
192
+ if "type" in properties:
193
+ nested = _properties(properties["type"])
194
+ rule = nested.get("value", {})
195
+ allowed = _enum(rule) or []
196
+ supplied = match[2] or "count"
197
+ unit = next((v for v in allowed if isinstance(v, str) and v.lower() == supplied.lower()), None)
198
+ if unit is None:
199
+ raise DetailFailure("UnitRefused", key, allowed)
200
+ result["type"] = {**self._base(nested), "value": unit}
201
+ elif match[2]:
202
+ raise DetailFailure("UnitRefused", key)
203
+ return result
204
+
205
+ def parse(self, key, text):
206
+ """Return attribute array values without substituting units absent from the schema."""
207
+ field = self._field(key)
208
+ if not isinstance(text, str) or not text.strip() or any(ord(c) < 32 for c in text):
209
+ raise DetailFailure("DetailTextRequired", key)
210
+ if "; " in text:
211
+ values = [value for part in text.split("; ") for value in self.parse(key, part)]
212
+ self.validate(key, values)
213
+ return values
214
+ props, kind = field["properties"], field["kind"]
215
+ result = self._base(props)
216
+ if kind == "dimensions":
217
+ match = _DIMENSIONS.fullmatch(text)
218
+ if not match:
219
+ raise DetailFailure("InvalidDimensions", key)
220
+ for axis, value in zip(("length", "width", "height"), match.groups()[:3]):
221
+ rule = _properties(props.get(axis, {}))
222
+ result[axis] = {"value": _number(value, key), "unit": self._unit(key, rule.get("unit", {}), match[4])}
223
+ elif kind == "weight":
224
+ match = _MEASURE.fullmatch(text)
225
+ if not match:
226
+ raise DetailFailure("InvalidWeight", key)
227
+ result.update(value=_number(match[1], key), unit=self._unit(key, props.get("unit", {}), match[2]))
228
+ elif kind == "count":
229
+ result.update(self._count(key, text, props))
230
+ elif kind == "integer":
231
+ if not re.fullmatch(r"\d+", text.strip()):
232
+ raise DetailFailure("InvalidCount", key)
233
+ result["value"] = int(text)
234
+ else:
235
+ result["value"] = text
236
+ values = [result]
237
+ self.validate(key, values)
238
+ return values
239
+
240
+ def validate(self, key, values):
241
+ field = self._field(key)
242
+ if not isinstance(values, list) or not values:
243
+ raise DetailFailure("InvalidAttributeValue", key)
244
+ for value in values:
245
+ if not isinstance(value, dict) or value.get("marketplace_id") != self.marketplace:
246
+ raise DetailFailure("AttributeMarketplaceMismatch", key)
247
+ self._validate_units(key, value, field["properties"])
248
+ if not _validator(field["rule"]).is_valid(values):
249
+ raise DetailFailure("SchemaValueRefused", key)
250
+
251
+ def _validate_units(self, key, value, properties):
252
+ for name, rule in properties.items():
253
+ if name == "unit" and name in value:
254
+ allowed = _enum(rule) or []
255
+ if value[name] not in allowed:
256
+ raise DetailFailure("UnitRefused", key, allowed)
257
+ elif isinstance(value.get(name), dict):
258
+ self._validate_units(key, value[name], _properties(rule))
259
+
260
+ def validate_attribute(self, attribute, values):
261
+ key = next((key for key, field in self.fields.items() if field["attribute"] == attribute), None)
262
+ if key is None:
263
+ raise DetailFailure("AttributeUnavailable", attribute)
264
+ self.validate(key, values)
265
+
266
+ def render(self, key, values):
267
+ """Render every marketplace value in the editor's canonical physical units."""
268
+ field = self._field(key)
269
+ if not isinstance(values, list) or any(not isinstance(v, dict) for v in values):
270
+ raise DetailFailure("InvalidLiveAttribute", key)
271
+ selected = [v for v in values if v.get("marketplace_id") == self.marketplace]
272
+ if not selected:
273
+ return ""
274
+ parts = []
275
+ try:
276
+ for value in selected:
277
+ kind = field["kind"]
278
+ if kind == "dimensions":
279
+ axes = [value[axis] for axis in ("length", "width", "height")]
280
+ units = [_unit_key(axis["unit"]) for axis in axes]
281
+ if any(unit not in _INCHES for unit in units):
282
+ raise DetailFailure("UnsupportedPhysicalUnit", key)
283
+ unit = units[0]
284
+ sides = [_format(axis["value"], _INCHES[u] / _INCHES[unit])
285
+ for axis, u in zip(axes, units)]
286
+ parts.append(" x ".join(sides) + " " + unit)
287
+ elif kind == "weight":
288
+ parts.append(_format(value["value"]) + " " + _unit_key(value["unit"]))
289
+ elif kind == "count":
290
+ unit = value.get("type", {}).get("value", "count")
291
+ parts.append(_format(value["value"]) + ("" if unit.lower() == "count" else " " + unit))
292
+ elif kind == "integer":
293
+ parts.append(_format(value["value"]))
294
+ else:
295
+ if not isinstance(value["value"], str):
296
+ raise DetailFailure("InvalidLiveAttribute", key)
297
+ parts.append(value["value"])
298
+ except (KeyError, TypeError, AttributeError):
299
+ raise DetailFailure("InvalidLiveAttribute", key) from None
300
+ return "; ".join(parts)
301
+
302
+ def render_all(self, attributes):
303
+ if not isinstance(attributes, dict):
304
+ raise DetailFailure("LiveAttributesRequired")
305
+ return {key: self.render(key, attributes.get(field["attribute"], [])) for key, field in self.fields.items()}
306
+
307
+ def patch(self, draft):
308
+ """Reject an unsupported or empty draft field before producing any patch body."""
309
+ if not isinstance(draft, dict) or not draft or set(draft) - EDITOR_KEYS:
310
+ raise DetailFailure("InvalidDetailsDraft")
311
+ patches = [{"op": "replace", "path": "/attributes/" + self._field(key)["attribute"],
312
+ "value": self.parse(key, value)} for key, value in draft.items()]
313
+ return {"productType": self.product_type, "patches": patches}
314
+
315
+
316
+ def _sides_in_inches(text):
317
+ sides = []
318
+ for part in str(text or "").split("; "):
319
+ match = _DIMENSIONS.fullmatch(part)
320
+ if not match or _unit_key(match[4]) not in _INCHES:
321
+ return []
322
+ sides.extend(float(value) * _INCHES[_unit_key(match[4])] for value in match.groups()[:3])
323
+ return sides
324
+
325
+
326
+ def pd_flags(title, values):
327
+ """Apply v51's exact messages after converting physical sides to inches."""
328
+ match = re.search(r"(\d+)\s*(?:pack|pk|pcs|pieces|count)\b", title or "", re.I)
329
+ match = match or re.search(r"pack of\s*(\d+)", title or "", re.I)
330
+ pack, flags = int(match[1]) if match else 0, {}
331
+ if not values.get("item_dimensions"):
332
+ flags["item_dimensions"] = "Missing. Shoppers see no product size"
333
+ if any(0 < side < 0.05 for side in _sides_in_inches(values.get("item_dimensions"))):
334
+ flags["item_dimensions"] = "A side under 0.05 in looks wrong"
335
+ package = values.get("package_dimensions")
336
+ sides = _sides_in_inches(package)
337
+ if sides and all(side <= 1 for side in sides) and pack > 1:
338
+ flags["package_dimensions"] = f"{package} cannot hold {pack} pieces"
339
+ items = values.get("number_of_items")
340
+ try:
341
+ count = float(items) if items else 0
342
+ except (TypeError, ValueError):
343
+ count = None
344
+ conflict = pack > 1 and items and count != pack and not values.get("number_of_pieces")
345
+ if items == "0" or conflict:
346
+ flags["number_of_items"] = f"The title says {pack}" if pack > 1 else "Zero items"
347
+ if pack > 1 and re.match(r"^1\b", values.get("unit_count") or ""):
348
+ flags["unit_count"] = f"The title says {pack}"
349
+ if not values.get("item_weight"):
350
+ flags["item_weight"] = "Missing"
351
+ return flags
platform/core/amazon_listing_write.py ADDED
@@ -0,0 +1,877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Publish exact approved listing patches through a tenant-bound, non-retrying transport."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import copy
6
+ import hashlib
7
+ import json
8
+ import re
9
+ import time
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+
14
+ from core import amazon_listing_attributes as details
15
+
16
+
17
+ ENDPOINTS = {
18
+ "na": "https://sellingpartnerapi-na.amazon.com",
19
+ "eu": "https://sellingpartnerapi-eu.amazon.com",
20
+ "fe": "https://sellingpartnerapi-fe.amazon.com",
21
+ }
22
+ PUBLIC_MEDIA_HOST = "fsanyoto-loopable.hf.space"
23
+ MEDIA_HOSTS = frozenset({PUBLIC_MEDIA_HOST, "m.media-amazon.com"})
24
+ IMAGE_ATTRIBUTES = frozenset({"main_product_image_locator"} | {
25
+ f"other_product_image_locator_{index}" for index in range(1, 9)})
26
+ COPY_ATTRIBUTES = frozenset({
27
+ "item_name", "title_differentiation", "bullet_point", "product_description", "generic_keyword"})
28
+ DETAIL_ATTRIBUTES = details.DETAIL_ATTRIBUTES
29
+ REPLACE_ATTRIBUTES = COPY_ATTRIBUTES | IMAGE_ATTRIBUTES | DETAIL_ATTRIBUTES
30
+ SCHEMA_HOSTS = frozenset({
31
+ "selling-partner-definitions-prod-iad.s3.amazonaws.com",
32
+ "selling-partner-definitions-prod-iad.s3.us-east-1.amazonaws.com",
33
+ "selling-partner-definitions-prod-dub.s3.amazonaws.com",
34
+ "selling-partner-definitions-prod-dub.s3.eu-west-1.amazonaws.com",
35
+ "selling-partner-definitions-prod-pdx.s3.amazonaws.com",
36
+ "selling-partner-definitions-prod-pdx.s3.us-west-2.amazonaws.com",
37
+ })
38
+ STATE_KEY = "amazon_listing_writes"
39
+ PREVIEW_TTL = 15 * 60
40
+ _MAX_BYTES = 16 * 1024 * 1024
41
+ _NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.:-]{0,255}\Z")
42
+
43
+
44
+ class ListingWriteFailure(RuntimeError):
45
+ """Expose fixed failure metadata without provider URLs, payloads or credentials."""
46
+
47
+ def __init__(self, operation, failure_class="Refused", status=None, *, field=None, allowed_units=()):
48
+ self.operation = operation
49
+ self.failure_class = failure_class
50
+ self.status = status if type(status) is int else None
51
+ self.field, self.allowed_units = field, list(allowed_units)
52
+ super().__init__(f"{operation}: {self.status}: {failure_class}")
53
+
54
+
55
+ def _text(value, maximum=1024):
56
+ return (isinstance(value, str) and 0 < len(value) <= maximum and bool(value.strip())
57
+ and not any(ord(char) < 32 for char in value))
58
+
59
+
60
+ def _copy_text(value):
61
+ return (isinstance(value, str) and 0 < len(value) <= _MAX_BYTES and bool(value.strip())
62
+ and not any(ord(char) < 32 and char not in "\n\r\t" for char in value))
63
+
64
+
65
+ def _name(value):
66
+ if not isinstance(value, str) or not _NAME.fullmatch(value):
67
+ raise ListingWriteFailure("validate", "InvalidIdentifier")
68
+ return value
69
+
70
+
71
+ def _json(value):
72
+ try:
73
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
74
+ except (TypeError, ValueError, UnicodeError):
75
+ raise ListingWriteFailure("validate", "InvalidJSON") from None
76
+
77
+
78
+ def _hash(value):
79
+ return hashlib.sha256(_json(value)).hexdigest()
80
+
81
+
82
+ def _tenant(rt):
83
+ key = getattr(rt, "key", None)
84
+ if not isinstance(key, str) or not key or key != key.strip().lower():
85
+ raise ListingWriteFailure("authorize", "TenantRequired")
86
+ return key
87
+
88
+
89
+ def _document(value, tenant):
90
+ if value is None or value == {}:
91
+ return {"tenant_key": tenant, "writes_enabled": False, "switch_history": [],
92
+ "previews": {}, "receipts": {}}
93
+ if (not isinstance(value, dict) or value.get("tenant_key") != tenant
94
+ or type(value.get("writes_enabled")) is not bool
95
+ or not isinstance(value.get("switch_history"), list)
96
+ or any(not isinstance(value.get(key), dict) for key in ("previews", "receipts"))):
97
+ raise ListingWriteFailure("store", "InvalidTenantState")
98
+ return copy.deepcopy(value)
99
+
100
+
101
+ def _read(rt):
102
+ try:
103
+ return _document(rt.get(STATE_KEY, fresh=True), _tenant(rt))
104
+ except ListingWriteFailure:
105
+ raise
106
+ except Exception:
107
+ raise ListingWriteFailure("store", "StateUnreadable") from None
108
+
109
+
110
+ def _change(rt, mutate):
111
+ tenant = _tenant(rt)
112
+
113
+ def change(value):
114
+ document = _document(value, tenant)
115
+ mutate(document)
116
+ return document
117
+
118
+ try:
119
+ rt.update(STATE_KEY, change, flush="sync")
120
+ return _read(rt)
121
+ except ListingWriteFailure:
122
+ raise
123
+ except Exception:
124
+ # Persistence uncertainty never grants permission to send.
125
+ raise ListingWriteFailure("store", "PersistenceUnproven") from None
126
+
127
+
128
+ def writes_enabled(rt):
129
+ """Read the tenant's current switch without a cache and fail closed on any read fault."""
130
+ try:
131
+ return _read(rt)["writes_enabled"] is True
132
+ except Exception:
133
+ return False
134
+
135
+
136
+ def set_writes_enabled(rt, enabled, by, words):
137
+ """Record a platform administrator's switch setting and exact instruction atomically."""
138
+ from core import platform_admin
139
+
140
+ if (type(enabled) is not bool or not platform_admin.is_platform_admin(by)
141
+ or not _text(by.get("username")) or not _text(words, 16384)):
142
+ raise ListingWriteFailure("switch", "PlatformAdminAndWordsRequired")
143
+ event = {"id": _nonce(), "tenant_key": _tenant(rt), "enabled": enabled,
144
+ "by": by["username"], "words": words, "at": time.time()}
145
+
146
+ def flip(document):
147
+ document["writes_enabled"] = enabled
148
+ document["switch_history"].append(event)
149
+
150
+ stored = _change(rt, flip)
151
+ if stored["writes_enabled"] is not enabled or event not in stored["switch_history"]:
152
+ raise ListingWriteFailure("switch", "PersistenceUnproven")
153
+ return copy.deepcopy(event)
154
+
155
+
156
+ def _nonce():
157
+ import uuid
158
+
159
+ return uuid.uuid4().hex
160
+
161
+
162
+ def allowed_media_url(value):
163
+ """Admit only HTTPS images on the published Space or Amazon's exact image host."""
164
+ if not _text(value, 8192) or value != value.strip() or "\\" in value:
165
+ return False
166
+ try:
167
+ parts = urllib.parse.urlsplit(value)
168
+ return (parts.scheme == "https" and parts.netloc in MEDIA_HOSTS
169
+ and parts.port is None and not parts.username and not parts.password
170
+ and not parts.fragment and parts.path.startswith("/") and parts.path != "/")
171
+ except ValueError:
172
+ return False
173
+
174
+
175
+ def validate_patch(body, marketplace, *, schema=None):
176
+ """Return detached JSON containing only admitted attribute operations and value shapes."""
177
+ body = json.loads(_json(body))
178
+ _name(marketplace)
179
+ if not isinstance(body, dict) or set(body) != {"productType", "patches"}:
180
+ raise ListingWriteFailure("patchListingsItem", "InvalidPatch")
181
+ _name(body["productType"])
182
+ patches, seen = body["patches"], set()
183
+ if not isinstance(patches, list) or not patches:
184
+ raise ListingWriteFailure("patchListingsItem", "InvalidPatch")
185
+ for patch in patches:
186
+ if not isinstance(patch, dict):
187
+ raise ListingWriteFailure("patchListingsItem", "InvalidPatch")
188
+ attribute = str(patch.get("path", "")).removeprefix("/attributes/")
189
+ op = patch.get("op")
190
+ if (patch.get("path") != "/attributes/" + attribute or attribute in seen
191
+ or attribute not in REPLACE_ATTRIBUTES or not isinstance(op, str) or op not in {"replace", "delete"}
192
+ or (op == "delete" and attribute not in IMAGE_ATTRIBUTES)
193
+ or set(patch) not in ({"op", "path", "value"}, {"op", "path"})
194
+ or (op == "replace" and "value" not in patch)):
195
+ raise ListingWriteFailure("patchListingsItem", "AttributeOrOperationRefused")
196
+ seen.add(attribute)
197
+ if "value" in patch:
198
+ if attribute in DETAIL_ATTRIBUTES:
199
+ if not isinstance(schema, details.DetailsSchema):
200
+ raise ListingWriteFailure("patchListingsItem", "ProductTypeSchemaRequired")
201
+ if schema.product_type != body["productType"] or schema.marketplace != marketplace:
202
+ raise ListingWriteFailure("patchListingsItem", "ProductTypeSchemaMismatch")
203
+ try:
204
+ schema.validate_attribute(attribute, patch["value"])
205
+ except details.DetailFailure as exc:
206
+ raise ListingWriteFailure("patchListingsItem", exc.reason, field=exc.field,
207
+ allowed_units=exc.allowed_units) from None
208
+ else:
209
+ _attribute_values(attribute, patch["value"], marketplace, deleting=op == "delete")
210
+ return body
211
+
212
+
213
+ def _attribute_values(attribute, values, marketplace, *, deleting):
214
+ if not isinstance(values, list) or not values:
215
+ raise ListingWriteFailure("patchListingsItem", "InvalidAttributeValue")
216
+ for value in values:
217
+ if not isinstance(value, dict) or value.get("marketplace_id") != marketplace:
218
+ raise ListingWriteFailure("patchListingsItem", "AttributeMarketplaceMismatch")
219
+ if attribute in IMAGE_ATTRIBUTES:
220
+ expected = {"marketplace_id"} if deleting else {"marketplace_id", "media_location"}
221
+ if set(value) != expected or (not deleting and not allowed_media_url(value.get("media_location"))):
222
+ raise ListingWriteFailure("patchListingsItem", "MediaLocationRefused")
223
+ elif (set(value) - {"marketplace_id", "language_tag", "value"}
224
+ or not _copy_text(value.get("value"))
225
+ or ("language_tag" in value and not _text(value["language_tag"], 32))):
226
+ raise ListingWriteFailure("patchListingsItem", "InvalidAttributeValue")
227
+
228
+
229
+ def read_approval(rt, reader, approval_id, binding):
230
+ """Require a trusted reader's approved record to contain every exact binding field."""
231
+ if not callable(reader) or not _text(approval_id) or binding.get("tenant_key") != _tenant(rt):
232
+ raise ListingWriteFailure("approve", "ApprovalRequired")
233
+ try:
234
+ record = reader(_tenant(rt), approval_id)
235
+ matches = (isinstance(record, dict) and record.get("decision") == "approved"
236
+ and _text(record.get("approved_by"))
237
+ and all(key in record and _json(record[key]) == _json(value)
238
+ for key, value in binding.items()))
239
+ except Exception:
240
+ raise ListingWriteFailure("approve", "ApprovalUnreadable") from None
241
+ if not matches:
242
+ raise ListingWriteFailure("approve", "ExactApprovalRequired")
243
+ return copy.deepcopy(record)
244
+
245
+
246
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
247
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
248
+ return None
249
+
250
+
251
+ def _schema_capability(definition):
252
+ if not isinstance(definition, dict) or not isinstance(definition.get("schema"), dict):
253
+ raise ListingWriteFailure("downloadSchema", "SchemaDefinitionRequired")
254
+ descriptor = definition["schema"]
255
+ link = descriptor.get("link")
256
+ url = link.get("resource") if isinstance(link, dict) else None
257
+ try:
258
+ parts = urllib.parse.urlsplit(url)
259
+ allowed = (_text(url, 32768) and url == url.strip() and "\\" not in url
260
+ and parts.scheme == "https" and parts.hostname in SCHEMA_HOSTS
261
+ and parts.netloc == parts.hostname and parts.port is None
262
+ and not parts.username and not parts.password and not parts.fragment
263
+ and parts.path.startswith("/") and parts.path != "/")
264
+ except (TypeError, ValueError):
265
+ allowed = False
266
+ if not allowed or link.get("verb") != "GET":
267
+ raise ListingWriteFailure("downloadSchema", "SchemaHostRefused")
268
+ checksum = descriptor.get("checksum")
269
+ try:
270
+ valid = isinstance(checksum, str) and len(base64.b64decode(checksum, validate=True)) == 16
271
+ except ValueError:
272
+ valid = False
273
+ if not valid:
274
+ raise ListingWriteFailure("downloadSchema", "SchemaChecksumRequired")
275
+ return {"url": url, "checksum": checksum}
276
+
277
+
278
+ class _KeychainSnapshot:
279
+ def __init__(self, rt, keychain):
280
+ self.key = _tenant(rt)
281
+ self.rows = {name: rt.get(name, fresh=True) or {} for name in (keychain.KEY, keychain.SCOPE_KEY)}
282
+ if any(not isinstance(value, dict) for value in self.rows.values()):
283
+ raise ListingWriteFailure("keychain", "InvalidCredentialStore")
284
+
285
+ def get(self, name, fresh=False):
286
+ return self.rows[name]
287
+
288
+
289
+ class _Transport:
290
+ def __init__(self, rt, *, connection_id=None, timeout=30):
291
+ from core import keychain
292
+ from harness import amazon_client
293
+
294
+ self.rt, self.tenant_key = rt, _tenant(rt)
295
+ self.keychain, self.client = keychain, amazon_client
296
+ if connection_id is not None and not _text(connection_id):
297
+ raise ListingWriteFailure("keychain", "ConnectionRequired")
298
+ self.requested_connection = connection_id
299
+ self.connection_id, self.fields = self._credential()
300
+ self.fields = copy.deepcopy(self.fields)
301
+ self.region = self.fields.get("region", "na")
302
+ self.marketplace = _name(self.fields.get("marketplace_id"))
303
+ if self.region not in ENDPOINTS or amazon_client.is_sandbox(self.fields):
304
+ raise ListingWriteFailure("keychain", "ProductionRegionRequired")
305
+ self.seller = urllib.parse.quote(self.fields["seller_id"], safe="")
306
+ self.timeout, self.token, self.issued = timeout, None, 0.0
307
+ self.urlopen = urllib.request.build_opener(_NoRedirect()).open
308
+ self._binding = None
309
+ self._uploads = {}
310
+ self._schemas = {}
311
+
312
+ def _credential(self):
313
+ if _tenant(self.rt) != self.tenant_key:
314
+ raise ListingWriteFailure("keychain", "TenantChanged")
315
+ try:
316
+ snapshot = _KeychainSnapshot(self.rt, self.keychain)
317
+ connection = self.requested_connection
318
+ if connection is None:
319
+ connection = self.keychain.default_connection_id(snapshot, "amazon_sp")
320
+ fields = self.keychain.amazon_creds(snapshot, connection_id=connection) if connection else None
321
+ if not isinstance(fields, dict) or not all(_text(fields.get(key)) for key in (
322
+ "seller_id", "marketplace_id", "client_id", "client_secret", "refresh_token")):
323
+ raise ListingWriteFailure("keychain", "CredentialMissing")
324
+ return connection, fields
325
+ except ListingWriteFailure:
326
+ raise
327
+ except Exception:
328
+ raise ListingWriteFailure("keychain", "CredentialUnreadable") from None
329
+
330
+ def _current(self):
331
+ connection, fields = self._credential()
332
+ if connection != self.connection_id or fields != self.fields:
333
+ raise ListingWriteFailure("keychain", "CredentialChangedOrRevoked")
334
+
335
+ def _access_token(self):
336
+ self._current()
337
+ if self.token is None or time.monotonic() - self.issued >= 2700:
338
+ try:
339
+ self.token = self.client.access_token(self.fields, timeout=self.timeout)
340
+ except Exception:
341
+ raise ListingWriteFailure("accessToken", "TokenUnavailable") from None
342
+ self.issued = time.monotonic()
343
+ if not _text(self.token, 16384):
344
+ raise ListingWriteFailure("accessToken", "TokenUnavailable")
345
+ return self.token
346
+
347
+ def _guard_request(self, operation, request):
348
+ binding = self._binding
349
+ if (not binding or request is not binding[0] or operation != binding[1]
350
+ or request.full_url != binding[2] or request.data != binding[3]):
351
+ raise ListingWriteFailure(operation, "FreshRequestBindingRequired")
352
+ from core import amazon_aplus_write as aplus
353
+
354
+ if operation in aplus.OPERATIONS or operation == "uploadAplusImage":
355
+ aplus.guard_request(self, operation, request, binding)
356
+ return
357
+ if operation == "downloadSchema":
358
+ cap = binding[5]
359
+ if (not isinstance(cap, dict) or cap != _schema_capability({"schema": {
360
+ "link": {"verb": "GET", "resource": request.full_url}, "checksum": cap.get("checksum")}})
361
+ or request.method != "GET" or request.data is not None or binding[4] is not None
362
+ or request.has_header("X-amz-access-token") or request.has_header("Authorization")):
363
+ raise ListingWriteFailure(operation, "RequestRefused")
364
+ return
365
+ parts = urllib.parse.urlsplit(request.full_url)
366
+ params = urllib.parse.parse_qs(parts.query, keep_blank_values=True)
367
+ allowed = (parts.scheme == "https" and parts.netloc == urllib.parse.urlsplit(ENDPOINTS[self.region]).netloc
368
+ and not parts.username and not parts.password and not parts.fragment and parts.port is None
369
+ and request.get_header("X-amz-access-token") == self.token and bool(self.token)
370
+ and not request.has_header("Authorization")
371
+ and params.get("marketplaceIds") == [self.marketplace])
372
+ prefix = "/listings/2021-08-01/items/" + self.seller + "/"
373
+ suffix = parts.path.removeprefix(prefix)
374
+ listing = (parts.path.startswith(prefix) and bool(suffix) and "/" not in suffix
375
+ and urllib.parse.unquote(suffix) not in {".", ".."})
376
+ if operation == "getListingsItem":
377
+ allowed &= (listing and request.method == "GET" and request.data is None
378
+ and set(params) == {"marketplaceIds", "includedData"}
379
+ and params["includedData"] == ["attributes,productTypes,summaries"])
380
+ elif operation == "getDefinitionsProductType":
381
+ definition = parts.path.removeprefix("/definitions/2020-09-01/productTypes/")
382
+ allowed &= (parts.path.startswith("/definitions/2020-09-01/productTypes/")
383
+ and bool(_NAME.fullmatch(definition)) and request.method == "GET" and request.data is None
384
+ and params == {"marketplaceIds": [self.marketplace], "sellerId": [self.fields["seller_id"]],
385
+ "requirements": ["LISTING"], "requirementsEnforced": ["ENFORCED"],
386
+ "productTypeVersion": ["LATEST"]})
387
+ elif operation == "patchListingsItem":
388
+ expected = {"marketplaceIds": [self.marketplace]}
389
+ if binding[4] is None:
390
+ expected["mode"] = ["VALIDATION_PREVIEW"]
391
+ elif not callable(binding[4]):
392
+ allowed = False
393
+ allowed &= listing and request.method == "PATCH" and params == expected
394
+ self._validate_patch(json.loads(request.data))
395
+ else:
396
+ allowed = False
397
+ if not allowed:
398
+ raise ListingWriteFailure(operation, "RequestRefused")
399
+
400
+ def _perform(self, operation, request):
401
+ try:
402
+ self._guard_request(operation, request)
403
+ except ListingWriteFailure:
404
+ self._binding = None
405
+ raise
406
+ except Exception:
407
+ self._binding = None
408
+ raise ListingWriteFailure(operation, "RequestRefused") from None
409
+ boundary, cap, self._binding = self._binding[4], self._binding[5], None
410
+ self._current()
411
+ from core import amazon_aplus_write as aplus
412
+
413
+ if (operation in aplus.OPERATIONS or operation == "uploadAplusImage") and not writes_enabled(self.rt):
414
+ raise ListingWriteFailure(operation, "WritesDisabled")
415
+ if boundary is not None:
416
+ boundary()
417
+ status = None
418
+ try:
419
+ # This is the only wire owner and its opener refuses redirects and retries.
420
+ with self.urlopen(request, timeout=self.timeout) as response:
421
+ status = response.status
422
+ raw = response.read(_MAX_BYTES + 1)
423
+ if len(raw) > _MAX_BYTES or not 200 <= status < 300:
424
+ raise ListingWriteFailure(operation, "InvalidHTTPResponse", status)
425
+ if (operation == "downloadSchema"
426
+ and base64.b64encode(hashlib.md5(raw).digest()).decode("ascii") != cap["checksum"]):
427
+ raise ListingWriteFailure(operation, "SchemaChecksumMismatch", status)
428
+ got = {"uploaded": True} if operation == "uploadAplusImage" else json.loads(raw)
429
+ if not isinstance(got, dict):
430
+ raise ListingWriteFailure(operation, "InvalidResponse", status)
431
+ return got
432
+ except ListingWriteFailure:
433
+ raise
434
+ except urllib.error.HTTPError as exc:
435
+ exc.close()
436
+ raise ListingWriteFailure(operation, "HTTPError", exc.code) from None
437
+ except Exception:
438
+ raise ListingWriteFailure(operation, "OutcomeUnknown", status) from None
439
+
440
+ def _request(self, operation, path, params, *, body=None, boundary=None, method=None, image=None, schema=None):
441
+ from core import amazon_aplus_write as aplus
442
+
443
+ method = method or ("GET" if body is None else "PATCH")
444
+ cap = None
445
+ if operation == "uploadAplusImage":
446
+ url, raw, headers, cap = aplus.upload_request(self, path, image)
447
+ elif operation == "downloadSchema":
448
+ url, raw, headers, cap = path, None, {"Accept": "application/json"}, schema
449
+ else:
450
+ raw = None if body is None else _json(body)
451
+ url = ENDPOINTS[self.region] + path + "?" + urllib.parse.urlencode(params)
452
+ headers = {"x-amz-access-token": self._access_token(), "Content-Type": "application/json",
453
+ "Accept": "application/json"}
454
+ request = urllib.request.Request(url, data=raw, method=method, headers=headers)
455
+ self._binding = (request, operation, url, raw, boundary, cap)
456
+ return self._perform(operation, request)
457
+
458
+ def aplus(self, operation, *, reference=None, asin=None, page_token=None, body=None,
459
+ asins=None, content_md5=None, content_type=None, boundary=None):
460
+ from core import amazon_aplus_write as aplus
461
+
462
+ if not writes_enabled(self.rt):
463
+ raise ListingWriteFailure(operation, "WritesDisabled")
464
+ path, params, method = aplus.operation_request(
465
+ self.marketplace, operation, reference, asin, page_token, body, asins, content_md5, content_type)
466
+ response = self._request(operation, path, params, body=body, boundary=boundary, method=method)
467
+ if operation == "createUploadDestinationForResource":
468
+ aplus.register_upload(self, response, content_md5, content_type)
469
+ return response
470
+
471
+ def upload_aplus_image(self, destination_id, content, *, boundary):
472
+ return self._request("uploadAplusImage", destination_id, {}, method="POST",
473
+ boundary=boundary, image=content)
474
+
475
+ def read(self, operation, *, sku=None, product_type=None):
476
+ params = {"marketplaceIds": self.marketplace}
477
+ if operation == "getListingsItem" and _text(sku) and sku not in {".", ".."} and product_type is None:
478
+ path = "/listings/2021-08-01/items/" + self.seller + "/" + urllib.parse.quote(sku, safe="")
479
+ params["includedData"] = "attributes,productTypes,summaries"
480
+ elif operation == "getDefinitionsProductType" and sku is None:
481
+ path = "/definitions/2020-09-01/productTypes/" + _name(product_type)
482
+ params.update(sellerId=self.fields["seller_id"], requirements="LISTING",
483
+ requirementsEnforced="ENFORCED", productTypeVersion="LATEST")
484
+ else:
485
+ raise ListingWriteFailure("read", "OperationRefused")
486
+ return self._request(operation, path, params)
487
+
488
+ def _patch(self, sku, body, *, boundary=None):
489
+ if not _text(sku) or sku in {".", ".."}:
490
+ raise ListingWriteFailure("patchListingsItem", "InvalidSKU")
491
+ body = self._validate_patch(body)
492
+ path = "/listings/2021-08-01/items/" + self.seller + "/" + urllib.parse.quote(sku, safe="")
493
+ params = {"marketplaceIds": self.marketplace}
494
+ if boundary is None:
495
+ params["mode"] = "VALIDATION_PREVIEW"
496
+ return self._request("patchListingsItem", path, params, body=body, boundary=boundary)
497
+
498
+ def _validate_patch(self, body):
499
+ return validate_patch(body, self.marketplace, schema=self._schemas.get(
500
+ body.get("productType") if isinstance(body, dict) else None))
501
+
502
+ def schema(self, definition):
503
+ cap = _schema_capability(definition)
504
+ return self._request("downloadSchema", cap["url"], {}, schema=cap)
505
+
506
+ def product_schema(self, product_type):
507
+ product_type = _name(product_type)
508
+ self._current()
509
+ if product_type not in self._schemas:
510
+ definition = self.read("getDefinitionsProductType", product_type=product_type)
511
+ if (definition.get("productType") != product_type
512
+ or definition.get("marketplaceIds") != [self.marketplace]):
513
+ raise ListingWriteFailure("getDefinitionsProductType", "DefinitionScopeMismatch")
514
+ raw = self.schema(definition)
515
+ self._schemas[product_type] = details.DetailsSchema(product_type, self.marketplace, raw)
516
+ return self._schemas[product_type]
517
+
518
+
519
+ class ListingPublisher:
520
+ """Use a trusted tenant runtime and a server-owned reader of exact per-listing approvals."""
521
+
522
+ def __init__(self, rt, approval_reader, *, connection_id=None, timeout=30):
523
+ self.rt, self.tenant_key, self.approval_reader = rt, _tenant(rt), approval_reader
524
+ self.transport = _Transport(rt, connection_id=connection_id, timeout=timeout)
525
+
526
+ def read_item(self, sku):
527
+ return self.transport.read("getListingsItem", sku=sku)
528
+
529
+ def read_definition(self, product_type):
530
+ return self.transport.read("getDefinitionsProductType", product_type=product_type)
531
+
532
+ def read_schema(self, product_type):
533
+ return self.transport.product_schema(product_type)
534
+
535
+ def _binding(self, workflow, asin, sku, body):
536
+ if _tenant(self.rt) != self.tenant_key or not _text(workflow) or not _text(asin) or not _text(sku):
537
+ raise ListingWriteFailure("publish", "ListingIdentityRequired")
538
+ body = json.loads(_json(body))
539
+ # Refuse unknown paths before a details patch may fetch its named product type schema.
540
+ paths = {"/attributes/" + name for name in REPLACE_ATTRIBUTES}
541
+ if (isinstance(body, dict) and isinstance(body.get("patches"), list)
542
+ and all(isinstance(p, dict) and p.get("path") in paths for p in body["patches"])
543
+ and any(p.get("path", "").removeprefix("/attributes/") in DETAIL_ATTRIBUTES for p in body["patches"])):
544
+ self.read_schema(body.get("productType"))
545
+ return {"tenant_key": self.tenant_key, "workflow": workflow, "asin": asin, "sku": sku,
546
+ "body": self.transport._validate_patch(body)}
547
+
548
+ def _scope(self, binding):
549
+ return {**binding, "connection_id": self.transport.connection_id, "region": self.transport.region,
550
+ "marketplace_id": self.transport.marketplace, "seller_id": self.transport.fields["seller_id"]}
551
+
552
+ def preview(self, workflow, asin, sku, body):
553
+ """Persist the exact body's observed preview result without requiring the LIVE switch."""
554
+ binding = self._binding(workflow, asin, sku, body)
555
+ scope = self._scope(binding)
556
+ key = _hash(scope)
557
+ _change(self.rt, lambda document: document["previews"].pop(key, None))
558
+ response = self.transport._patch(sku, binding["body"])
559
+ result = {"binding": scope, "body_sha256": _hash(binding["body"]),
560
+ "status": response.get("status"), "at": time.time(), "response": response}
561
+ stored = _change(self.rt, lambda document: document["previews"].update({key: result}))
562
+ if stored["previews"].get(key) != result:
563
+ raise ListingWriteFailure("preview", "PersistenceUnproven")
564
+ return copy.deepcopy(result)
565
+
566
+ def _valid_preview(self, document, binding):
567
+ scope = self._scope(binding)
568
+ preview = document["previews"].get(_hash(scope))
569
+ now = time.time()
570
+ if (not isinstance(preview, dict) or preview.get("binding") != scope
571
+ or preview.get("body_sha256") != _hash(binding["body"]) or preview.get("status") != "VALID"
572
+ or type(preview.get("at")) not in (int, float) or not 0 <= now - preview["at"] <= PREVIEW_TTL):
573
+ raise ListingWriteFailure("publish", "RecentIdenticalValidPreviewRequired")
574
+
575
+ def _live_boundary(self, binding, approval_id, receipt=None):
576
+ approved = read_approval(self.rt, self.approval_reader, approval_id, binding)
577
+ document = _read(self.rt)
578
+ self._valid_preview(document, binding)
579
+ if receipt is not None and document["receipts"].get(receipt["id"]) != receipt:
580
+ raise ListingWriteFailure("publish", "PendingReceiptRequired")
581
+ if not writes_enabled(self.rt):
582
+ raise ListingWriteFailure("publish", "WritesDisabled")
583
+ return approved
584
+
585
+ def _snapshot(self, binding):
586
+ item = self.read_item(binding["sku"])
587
+ market = self.transport.marketplace
588
+ summaries, types, attributes = item.get("summaries"), item.get("productTypes"), item.get("attributes")
589
+ if (not isinstance(attributes, dict) or not isinstance(summaries, list) or not isinstance(types, list)
590
+ or not any(isinstance(row, dict) and row.get("marketplaceId") == market
591
+ and row.get("asin") == binding["asin"] for row in summaries)
592
+ or not any(isinstance(row, dict) and row.get("marketplaceId") == market
593
+ and row.get("productType") == binding["body"]["productType"] for row in types)):
594
+ raise ListingWriteFailure("publish", "FreshListingIdentityRequired")
595
+ return copy.deepcopy(attributes)
596
+
597
+ def _reserve(self, receipt, binding):
598
+ def reserve(document):
599
+ if receipt["id"] in document["receipts"]:
600
+ raise ListingWriteFailure("publish", "AlreadyReserved")
601
+ identity = ("tenant_key", "workflow", "asin", "sku")
602
+ if any(row.get("state") in {"pending", "unknown"}
603
+ and all(row.get("binding", {}).get(key) == binding[key] for key in identity)
604
+ for row in document["receipts"].values()):
605
+ raise ListingWriteFailure("publish", "ReconciliationRequired")
606
+ if document["writes_enabled"] is not True:
607
+ raise ListingWriteFailure("publish", "WritesDisabled")
608
+ self._valid_preview(document, binding)
609
+ document["receipts"][receipt["id"]] = receipt
610
+
611
+ stored = _change(self.rt, reserve)
612
+ if stored["receipts"].get(receipt["id"]) != receipt:
613
+ raise ListingWriteFailure("publish", "PersistenceUnproven")
614
+
615
+ def _finish(self, pending, **outcome):
616
+ receipt = {**pending, **outcome, "finished_at": time.time()}
617
+
618
+ def finish(document):
619
+ if document["receipts"].get(pending["id"]) != pending:
620
+ raise ListingWriteFailure("publish", "ReceiptChanged")
621
+ document["receipts"][pending["id"]] = receipt
622
+
623
+ stored = _change(self.rt, finish)
624
+ if stored["receipts"].get(pending["id"]) != receipt:
625
+ raise ListingWriteFailure("publish", "PersistenceUnproven")
626
+ return copy.deepcopy(receipt)
627
+
628
+ def publish(self, workflow, asin, sku, body, *, approval_id):
629
+ """Send once after a valid preview, returning an existing receipt on any later invocation."""
630
+ binding = self._binding(workflow, asin, sku, body)
631
+ if not _text(approval_id):
632
+ raise ListingWriteFailure("approve", "ApprovalRequired")
633
+ identity = {key: value for key, value in binding.items() if key != "body"}
634
+ key = _hash({**identity, "approval_id": approval_id})
635
+ previous = _read(self.rt)["receipts"].get(key)
636
+ if previous is not None:
637
+ if previous.get("binding") != self._scope(binding):
638
+ raise ListingWriteFailure("publish", "ReservedApprovalMismatch")
639
+ return copy.deepcopy(previous)
640
+ approved = self._live_boundary(binding, approval_id)
641
+ snapshot = self._snapshot(binding)
642
+ pending = {"id": key, "binding": self._scope(binding), "approval_id": approval_id,
643
+ "approved_by": approved["approved_by"], "body_sha256": _hash(binding["body"]),
644
+ "prior_attributes": snapshot, "state": "pending", "sent": False, "at": time.time()}
645
+ self._reserve(pending, binding)
646
+ try:
647
+ response = self.transport._patch(sku, binding["body"], boundary=lambda:
648
+ self._live_boundary(binding, approval_id, pending))
649
+ except ListingWriteFailure as exc:
650
+ self._finish(pending, state="unknown", failure_class=exc.failure_class)
651
+ raise
652
+ status = response.get("status")
653
+ state = {"ACCEPTED": "accepted", "INVALID": "rejected"}.get(status, "unknown")
654
+ return self._finish(pending, state=state, sent=state == "accepted", response=response)
655
+
656
+
657
+ def publish_listing(rt, workflow, asin, sku, body, *, approval_id, approval_reader, connection_id=None):
658
+ """Preview first, report disabled sending, or publish the identical approved patch once."""
659
+ publisher = ListingPublisher(rt, approval_reader, connection_id=connection_id)
660
+ preview = publisher.preview(workflow, asin, sku, body)
661
+ if preview["status"] != "VALID":
662
+ return {"sent": False, "state": "invalid", "preview": preview}
663
+ if not writes_enabled(rt):
664
+ return {"sent": False, "state": "disabled", "preview": preview}
665
+ return publisher.publish(workflow, asin, sku, body, approval_id=approval_id)
666
+
667
+
668
+ class _OfflineFixture:
669
+ def __init__(self):
670
+ from types import SimpleNamespace
671
+
672
+ self.key = "listing-fixture"
673
+ self.data, self.requests, self.reads = {}, [], []
674
+ self.fail_read = self.fail_write = self.unclear = self.redirect = False
675
+ self.preview_status = "VALID"
676
+ self.before_live = None
677
+ self.fields = {"seller_id": "fixture-seller", "marketplace_id": "MARKET1", "region": "na",
678
+ "client_id": "fixture-client", "client_secret": "fixture-secret", "refresh_token": "fixture-refresh"}
679
+ self.body = {"productType": "VASE", "patches": [{"op": "replace", "path": "/attributes/item_name",
680
+ "value": [{"value": "fixture title", "language_tag": "en_US", "marketplace_id": "MARKET1"}]}]}
681
+ self.approval = {"tenant_key": self.key, "workflow": "workflow-1", "asin": "ASIN1", "sku": "sku-1",
682
+ "body": copy.deepcopy(self.body), "decision": "approved", "approved_by": "fixture-person"}
683
+ self.admin = {"tenant": "loopable", "platform_admin": True, "username": "fixture-operator"}
684
+ self.original = {"item_name": [{"value": "original", "marketplace_id": "MARKET1"}], "color": [{"value": "blue"}]}
685
+ self.rt = SimpleNamespace(key=self.key, get=self.get, update=self.update)
686
+
687
+ def get(self, name, fresh=False):
688
+ self.reads.append((name, fresh))
689
+ if self.fail_read and name == STATE_KEY:
690
+ raise OSError("fixture store unavailable")
691
+ return copy.deepcopy(self.data.get(name))
692
+
693
+ def update(self, name, fn, flush):
694
+ if self.fail_write:
695
+ raise OSError("fixture persistence unavailable")
696
+ if flush != "sync":
697
+ raise AssertionError("synchronous persistence required")
698
+ self.data[name] = copy.deepcopy(fn(copy.deepcopy(self.data.get(name))))
699
+
700
+ def reader(self, tenant, approval_id):
701
+ if tenant != self.key or not approval_id:
702
+ raise AssertionError("tenant approval reader")
703
+ return copy.deepcopy(self.approval)
704
+
705
+ def __enter__(self):
706
+ from contextlib import ExitStack
707
+ from types import SimpleNamespace
708
+ from unittest.mock import patch
709
+ from core import keychain
710
+ from harness import amazon_client
711
+
712
+ self.stack = ExitStack()
713
+ self.stack.enter_context(patch.object(keychain, "default_connection_id", return_value="fixture-connection"))
714
+ self.stack.enter_context(patch.object(keychain, "amazon_creds", side_effect=lambda *a, **k: copy.deepcopy(self.fields)))
715
+ self.stack.enter_context(patch.object(amazon_client, "access_token", return_value="fixture-token"))
716
+ self.stack.enter_context(patch.object(urllib.request, "build_opener", return_value=SimpleNamespace(open=self.wire)))
717
+ self.stack.enter_context(patch.object(urllib.request, "urlopen", side_effect=AssertionError("real network forbidden")))
718
+ self.publisher = ListingPublisher(self.rt, self.reader)
719
+ return self
720
+
721
+ def __exit__(self, *args):
722
+ return self.stack.__exit__(*args)
723
+
724
+ def wire(self, request, timeout):
725
+ import io
726
+
727
+ self.requests.append(request)
728
+ params = urllib.parse.parse_qs(urllib.parse.urlsplit(request.full_url).query, keep_blank_values=True)
729
+ if "mode" in params and params["mode"] != ["VALIDATION_PREVIEW"]:
730
+ raise AssertionError("unsupported listing PATCH mode")
731
+ if self.redirect:
732
+ raise urllib.error.HTTPError(request.full_url, 302, "fixture redirect", {}, io.BytesIO())
733
+ if request.method == "PATCH":
734
+ if "mode" not in params:
735
+ pending = list(self.data[STATE_KEY]["receipts"].values())
736
+ if not pending or pending[-1]["prior_attributes"] != self.original or pending[-1]["state"] != "pending":
737
+ raise AssertionError("durable snapshot and pending receipt before wire")
738
+ if self.unclear:
739
+ raise TimeoutError("fixture unclear response")
740
+ got = {"status": "ACCEPTED"}
741
+ else:
742
+ got = {"status": self.preview_status, "issues": []}
743
+ elif "/definitions/" in request.full_url:
744
+ got = {"productType": "VASE", "marketplaceIds": ["MARKET1"]}
745
+ else:
746
+ got = {"attributes": self.original, "summaries": [{"marketplaceId": "MARKET1", "asin": "ASIN1"}],
747
+ "productTypes": [{"marketplaceId": "MARKET1", "productType": "VASE"}]}
748
+ if self.before_live:
749
+ self.before_live()
750
+ response = io.BytesIO(_json(got))
751
+ response.status = 200
752
+ return response
753
+
754
+ def preview(self):
755
+ return self.publisher.preview("workflow-1", "ASIN1", "sku-1", self.body)
756
+
757
+ def publish(self, approval_id="approval-1"):
758
+ return self.publisher.publish("workflow-1", "ASIN1", "sku-1", self.body, approval_id=approval_id)
759
+
760
+ def enable(self):
761
+ return set_writes_enabled(self.rt, True, self.admin, "fixture approved switch instruction")
762
+
763
+ def live_count(self):
764
+ return sum(request.method == "PATCH"
765
+ and "mode" not in urllib.parse.parse_qs(urllib.parse.urlsplit(request.full_url).query,
766
+ keep_blank_values=True)
767
+ for request in self.requests)
768
+
769
+
770
+ def _refused(call):
771
+ try:
772
+ call()
773
+ except ListingWriteFailure:
774
+ return True
775
+ return False
776
+
777
+
778
+ def _selftest_refusals():
779
+ checks = {}
780
+ with _OfflineFixture() as fixture:
781
+ fixture.preview()
782
+ checks["switch_off"] = _refused(fixture.publish) and fixture.live_count() == 0
783
+ checks["preview_with_switch_off"] = len(fixture.requests) == 1
784
+ for operation in ("putListingsItem", "deleteListingsItem", "createFeed"):
785
+ before = len(fixture.requests)
786
+ checks[operation] = (_refused(lambda: fixture.publisher.transport.read(operation))
787
+ and len(fixture.requests) == before)
788
+ fixture.enable()
789
+ fixture.body["patches"][0]["path"] = "/attributes/price"
790
+ before = len(fixture.requests)
791
+ checks["attribute_allowlist"] = _refused(fixture.preview) and len(fixture.requests) == before
792
+ for case in ("no_preview", "stale_preview", "different_body", "different_approval", "media_host", "invalid_preview"):
793
+ with _OfflineFixture() as fixture:
794
+ fixture.enable()
795
+ if case != "no_preview":
796
+ fixture.preview()
797
+ if case == "stale_preview":
798
+ for row in fixture.data[STATE_KEY]["previews"].values():
799
+ row["at"] = time.time() - PREVIEW_TTL - 1
800
+ elif case == "different_body":
801
+ fixture.body["patches"][0]["value"][0]["value"] = "changed"
802
+ fixture.approval["body"] = copy.deepcopy(fixture.body)
803
+ elif case == "different_approval":
804
+ fixture.approval["body"]["patches"][0]["value"][0]["value"] = "not approved"
805
+ elif case == "media_host":
806
+ fixture.body["patches"] = [{"op": "replace", "path": "/attributes/main_product_image_locator",
807
+ "value": [{"marketplace_id": "MARKET1", "media_location": "https://evil.example/image.jpg"}]}]
808
+ elif case == "invalid_preview":
809
+ fixture.preview_status = "INVALID"
810
+ fixture.preview()
811
+ before = len(fixture.requests)
812
+ checks[case] = _refused(fixture.publish) and len(fixture.requests) == before
813
+ return checks
814
+
815
+
816
+ def _selftest_persistence():
817
+ checks = {}
818
+ with _OfflineFixture() as fixture:
819
+ flip = fixture.enable()
820
+ checks["switch_audit"] = flip in fixture.data[STATE_KEY]["switch_history"] and bool(flip["words"])
821
+ fixture.preview()
822
+ first = fixture.publish()
823
+ checks["accepted_snapshot"] = (first["state"] == "accepted" and first["sent"] is True
824
+ and first["prior_attributes"] == fixture.original and fixture.live_count() == 1)
825
+ checks["accepted_no_resend"] = fixture.publish() == first and fixture.live_count() == 1
826
+ checks["fresh_reads"] = bool(fixture.reads) and all(fresh for _, fresh in fixture.reads)
827
+ with _OfflineFixture() as fixture:
828
+ fixture.enable()
829
+ fixture.preview()
830
+ fixture.unclear = True
831
+ checks["unknown_failure"] = _refused(fixture.publish) and fixture.live_count() == 1
832
+ recovered = fixture.publish()
833
+ checks["unknown_no_resend"] = recovered["state"] == "unknown" and fixture.live_count() == 1
834
+ checks["unknown_new_approval"] = _refused(lambda: fixture.publish("approval-2")) and fixture.live_count() == 1
835
+ for fault in ("fail_read", "fail_write"):
836
+ with _OfflineFixture() as fixture:
837
+ fixture.enable()
838
+ fixture.preview()
839
+ setattr(fixture, fault, True)
840
+ checks[fault] = _refused(fixture.publish) and fixture.live_count() == 0
841
+ if fault == "fail_read":
842
+ checks["switch_read_failure"] = writes_enabled(fixture.rt) is False
843
+ with _OfflineFixture() as fixture:
844
+ fixture.enable()
845
+ fixture.preview()
846
+ fixture.before_live = lambda: set_writes_enabled(fixture.rt, False, fixture.admin, "fixture revocation")
847
+ checks["switch_boundary"] = _refused(fixture.publish) and fixture.live_count() == 0
848
+ return checks
849
+
850
+
851
+ def selftest():
852
+ """Return focused offline behavior controls using in-memory stores and a provider double."""
853
+ checks = {**_selftest_refusals(), **_selftest_persistence()}
854
+ with _OfflineFixture() as fixture:
855
+ fixture.redirect = True
856
+ checks["redirect_response"] = _refused(fixture.preview) and len(fixture.requests) == 1
857
+ checks["redirect_handler"] = _NoRedirect().redirect_request(None, None, 302, "", {}, "https://evil.example") is None
858
+ before = len(fixture.requests)
859
+ forged = urllib.request.Request(ENDPOINTS["na"] + "/unbound", method="PATCH", data=b"{}")
860
+ checks["unbound_request"] = (_refused(lambda: fixture.publisher.transport._perform("patchListingsItem", forged))
861
+ and len(fixture.requests) == before)
862
+ by = {"username": "tenant-admin", "role": "admin", "tenant": fixture.key}
863
+ checks["platform_admin_only"] = _refused(lambda: set_writes_enabled(fixture.rt, True, by, "fixture instruction"))
864
+ return {"selftest": "PASS" if all(checks.values()) else "FAIL", "checks": checks,
865
+ "network": False, "store_writes": False}
866
+
867
+
868
+ if __name__ == "__main__":
869
+ import sys
870
+ from pathlib import Path
871
+
872
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
873
+ if sys.argv[1:] != ["--selftest"]:
874
+ raise SystemExit("Only --selftest is supported. Use ListingPublisher from the trusted runtime.")
875
+ result = selftest()
876
+ print(json.dumps(result))
877
+ raise SystemExit(0 if result["selftest"] == "PASS" else 1)
platform/core/amazon_pdp.py CHANGED
@@ -464,9 +464,9 @@ def save_draft(rt, workflow_id, asin, slot, value, *, option_id=None, by):
464
 
465
  def _details_provider():
466
  try:
467
- return import_module('connectors.amazon_listing_attributes')
468
  except ModuleNotFoundError as exc:
469
- if exc.name != 'connectors.amazon_listing_attributes':
470
  raise
471
  raise Refused('details_provider_unavailable', 'Product details are unavailable. Try again later.') from None
472
 
 
464
 
465
  def _details_provider():
466
  try:
467
+ return import_module('core.amazon_listing_attributes')
468
  except ModuleNotFoundError as exc:
469
+ if exc.name != 'core.amazon_listing_attributes':
470
  raise
471
  raise Refused('details_provider_unavailable', 'Product details are unavailable. Try again later.') from None
472
 
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 09d975f8a03aad3544ef2c67d6b5a023b197c17fc6cec0090818dd49bec671d0
 
1
+ b9152b3ed160cd56ea48b4bdba008e2742242b08e862dfaab6c4b3209d62c4ed