Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download platform/harness/amazon_client.py from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 228 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/platform/harness/amazon_client.py
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/platform/harness/amazon_client.py
-
curl -L -o amazon_client.py https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/platform/harness/amazon_client.py
228 kB
"""amazon_client.py — the SP-API transport, in the DATA LAYER where the loaders can reach it.
⛔⛔ **WHY THIS FILE MOVED DOWN OUT OF `aios-web/api/`, AND THE GATE THAT MADE IT.** The transport
started life inside `connectors_amazon.py`, and `harness/amazon_store.py` reached UP to import it.
`verify_meta`'s architecture leg caught it in one line -- `amazon_store.py -> connectors_amazon` --
and it was right: layers point ONE way (`modules -> core`, `api -> modules`), and nothing under
`platform/core` or `platform/harness` may import an API-layer module. That check exists because the
same shortcut was taken once before, with `sys.path.insert` plus an import from inside `core`.
⭐ **THE ALTERNATIVE WAS WORSE, WHICH IS WHY THIS AND NOT A SECOND READER.** `meta_store` avoids the
inversion by bringing its own reader, and Graph is simple enough that a second one costs little.
SP-API is not: the LWA token exchange, the read-only guard, the report request-poll-download loop
and the rate-limit reporting would all have existed twice, and "which stored credential serves this
connector" having two answers is a defect class this codebase already names. So the TRANSPORT lives
here, in the layer both callers can see, and `connectors_amazon.py` stays the API-layer face that
registers the liveness probe.
⭐ **WHY THIS FILE IS SMALL, AND THE STALE ASSUMPTION IT KILLS.** Since 2 October 2023 SP-API
disregards AWS SigV4 entirely and authorizes on the LWA access token alone: a plain
`Authorization: Bearer` header. Any library, blog post or memory that has us minting IAM users and
signing requests is describing a dead API.
· https://developer-docs.amazon.com/sp-api/changelog/sp-api-will-no-longer-require-aws-iam-or-aws-signature-version-4
⛔ **SELLER DATA IS READ-ONLY.** `_request` refuses any method but
GET before it builds a request. The separate `send_named_write` door admits C3's exact approved
inbound and removal batches. Sync and plain read routes cannot opt out of `_request`'s guard.
The approved POST wrappers read reports, pricing, fees, replenishment and Data Kiosk results.
`_notifications_post` creates only an EventBridge destination or one approved subscription.
These fixed paths cannot alter seller records or send buyer messages.
⛔ **REPORTS AND DATA KIOSK ARE THE BULK PATHS; FINANCES FOLLOWS EVERY PAGE.** SP-API is token-bucket rate limited per
operation per selling-partner/application pair, and Amazon treats throttling as evidence of a wrong
call pattern rather than a wrong ceiling. Standing rule 1 forbids a silent cap on a connector's
records, and its second half is what applies: a limit that genuinely cannot be removed must be
REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down.
· https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits
Ideation record, with every owner ruling: `AutoWiki/research/ideation/amazon-connector.md`
"""
from __future__ import annotations
import contextvars
from contextlib import contextmanager
import csv
import gzip
import hashlib
import importlib
import io
import json
import logging
import math
import os
import random
import re
import shutil
import sys
import tempfile
import threading
import time
from datetime import date, datetime, timezone, timedelta
import urllib.error
import urllib.parse
import urllib.request
KEY = "amazon_sp"
LABEL = "Amazon"
#: W57-T38/C13: five total attempts, including the first, bound one throttled operation.
RETRY_MAX_ATTEMPTS = 5
#: W57-T38/C13: exponential backoff starts at one second after the first 429.
RETRY_BASE_SECONDS = 1.0
#: W57-T38/C13: no individual retry sleep exceeds one minute, including Retry-After/jitter.
RETRY_MAX_SECONDS = 60.0
#: W57-T38/C13: randomize each wait by up to half its value to separate competing clients.
RETRY_JITTER = 0.5
#: W57-T38/C13: separate consecutive table report creations by at least five seconds.
REPORT_STAGGER_SECONDS = 5.0
#: Amazon createReport usage plan: 15 initial tokens, shared by callers in this process.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_BURST = 15
#: Amazon createReport usage plan: 0.0167 requests/second, approximately one token/minute.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_SUSTAINED_SECONDS = 60.0
#: Product Pricing v2022-05-01 `getCompetitiveSummary`, official default usage plan.
#: https://developer-docs.amazon.com/sp-api/reference/getcompetitivesummary
COMPETITIVE_SUMMARY_RATE = 0.033
COMPETITIVE_SUMMARY_INTERVAL = 1.0 / COMPETITIVE_SUMMARY_RATE
COMPETITIVE_SUMMARY_BATCH_SIZE = 20
#: AWD v2024-05-09 `listInventory`, official default usage plan and maximum page size.
#: https://developer-docs.amazon.com/sp-api/reference/listinventory
AWD_INVENTORY_RATE = 2.0
AWD_INVENTORY_INTERVAL = 1.0 / AWD_INVENTORY_RATE
AWD_INVENTORY_PAGE_SIZE = 200
# Unscoped callers retain the legacy bucket. Transport calls use credential-scoped state.
# The contextual wait belongs to the current report_document logger.
_report_pacer = {
"tokens": float(REPORT_BURST),
"updated": None,
"last_create": None,
"lock": threading.Lock(),
"waited": contextvars.ContextVar("amazon_report_create_waited", default=0.0),
}
# Unscoped pacer defaults remain available to callers without an access token.
_entity_pacers = {
"competitive_summary": {"last": None, "lock": threading.Lock()},
"getItemOffersBatch": {"last": None, "lock": threading.Lock()},
"awd_inventory": {"last": None, "lock": threading.Lock()},
"transactions": {"last": None, "lock": threading.Lock()},
"getOrderMetrics": {"last": None, "lock": threading.Lock()},
"getInventorySummaries": {"last": None, "lock": threading.Lock()},
"searchListingsItems": {"last": None, "lock": threading.Lock()},
"searchCatalogItems": {"last": None, "lock": threading.Lock()},
"getItemReviewTopics": {"last": None, "lock": threading.Lock()},
"getItemReviewTrends": {"last": None, "lock": threading.Lock()},
"getItemBrowseNode": {"last": None, "lock": threading.Lock()},
"getBrowseNodeReviewTopics": {"last": None, "lock": threading.Lock()},
"getMyFeesEstimates": {"last": None, "lock": threading.Lock()},
"listAllFulfillmentOrders": {"last": None, "lock": threading.Lock()},
"getFulfillmentOrder": {"last": None, "lock": threading.Lock()},
"listInboundPlans": {"last": None, "lock": threading.Lock()},
"getInboundPlan": {"last": None, "lock": threading.Lock()},
"listShipmentItems": {"last": None, "lock": threading.Lock()},
"getShipment": {"last": None, "lock": threading.Lock()},
"getShipmentItemsByShipmentId": {"last": None, "lock": threading.Lock()},
"getShipmentItems": {"last": None, "lock": threading.Lock()},
"getSellingPartnerMetrics": {"last": None, "lock": threading.Lock()},
"listOfferMetrics": {"last": None, "lock": threading.Lock()},
}
# Data Kiosk has its own quota, independent of createReport.
QUERY_BURST = 15
QUERY_SUSTAINED_SECONDS = 60.0
_query_pacer = {"tokens": float(QUERY_BURST), "updated": None, "lock": threading.Lock()}
_rate_lock = threading.Lock()
_rate_states = {}
_token_scopes = {}
_client_scope = contextvars.ContextVar("amazon_client_scope", default=None)
_tenant_scope = contextvars.ContextVar("amazon_tenant_scope", default="")
_reservation = contextvars.ContextVar("amazon_operation_reservation", default=None)
#: S82-T14: documents the first-load job already downloaded, keyed by `prefetch_key`. `None` outside a job write.
_prefetch = contextvars.ContextVar("amazon_report_prefetch", default=None)
#: S82-T14: the store's per-seller createReport ledger. A callable taking `fields`; it raises AmazonThrottled to defer.
_report_ledger = contextvars.ContextVar("amazon_report_ledger", default=None)
_QUERIES_CREATE_PATH = "dataKiosk/2023-11-15/queries"
_TRANSACTIONS_PATH = "finances/2024-06-19/transactions"
TRANSACTIONS_INTERVAL = 2.0
# Selection pinned to Amazon's published analytics_economics_2024_03_15.graphql,
# read 2026-09-25. RANGE avoids MONTH's automatic rounding of partial months.
# Only dates, a validated marketplace ID and one of two fixed grains are substituted.
_ECONOMICS_QUERY = '''query {
analytics_economics_2024_03_15 {
economics(startDate: "__START__", endDate: "__END__",
marketplaceIds: ["__MARKETPLACE__"], aggregateBy: {date: __DATE__, productId: __PRODUCT__}) {
startDate endDate marketplaceId msku fnsku childAsin parentAsin
sales {
orderedProductSales { amount currencyCode } unitsOrdered
refundedProductSales { amount currencyCode } unitsRefunded
netProductSales { amount currencyCode } netUnitsSold
averageSellingPrice { amount currencyCode }
}
fees { feeTypeName charges { startDate endDate identifier aggregatedDetail {
amount { amount currencyCode } totalAmount { amount currencyCode }
amountPerUnit { amount currencyCode } amountPerUnitDelta { amount currencyCode }
promotionAmount { amount currencyCode } taxAmount { amount currencyCode } quantity
} } }
ads { adTypeName charge {
amount { amount currencyCode } totalAmount { amount currencyCode }
amountPerUnit { amount currencyCode } promotionAmount { amount currencyCode }
taxAmount { amount currencyCode } quantity
} }
netProceeds { total { amount currencyCode } perUnit { amount currencyCode } }
cost {
costOfGoodsSold { amount currencyCode } miscellaneousCost { amount currencyCode }
fbaCost { shippingToAmazonCost { amount currencyCode } }
mfnCost { fulfillmentCost { amount currencyCode } storageCost { amount currencyCode } }
}
}
}
}'''
_ECONOMICS_TEMPLATES = {
False: _ECONOMICS_QUERY.replace("__DATE__", "DAY").replace("__PRODUCT__", "MSKU"),
# S66-T40 (lead, measured live 2026-09-25, window 2026-09-20..24): RANGE x MSKU equals the
# sum of our DAY x MSKU rows to the cent (fees 38,009.94, net 38,474.335), while ANY
# PARENT_ASIN grain carries 37.75 of fees Amazon attributes to no MSKU. The reconciliation
# checks OUR date roll-up at the SAME product grain; comparing across grains refused a
# correct transform.
True: _ECONOMICS_QUERY.replace("__DATE__", "RANGE").replace("__PRODUCT__", "MSKU"),
}
#: ⚠ MUST MATCH `core.keychain.ENTRY_TYPES` OR `add_entry` 400s with a message about our data
#: structure on a screen about their Amazon account. That was the wave-31 Meta defect and the
#: comments in `keychain.py` warn about it in as many words.
ENTRY_TYPE = "amazon_sp"
#: Login With Amazon: the ONLY place a refresh token is exchanged. Not a regional endpoint.
LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"
#: Regional SP-API hosts. Royal Imports is US, so North America is the default.
ENDPOINTS = {
"na": "https://sellingpartnerapi-na.amazon.com",
"eu": "https://sellingpartnerapi-eu.amazon.com",
"fe": "https://sellingpartnerapi-fe.amazon.com",
}
#: ⭐ THE SANDBOX HOSTS, so the `Loopable Sandbox` app that ALREADY EXISTS is usable today.
#:
#: Owner ruling R9 created that app precisely so the connector could be built and proven while
#: identity verification is pending. Without these hosts its credentials would be sent to the
#: PRODUCTION endpoint and fail with an authorization error that looks like a bad credential rather
#: than a wrong host -- the most expensive kind of wrong answer.
#:
#: ⛔⛔ A SANDBOX CREDENTIAL IS FENCED OUT OF `sync`, AND THAT FENCE IS THE POINT. The sandbox
#: returns STATIC MOCK responses. Standing rule 8 forbids an unverifiable aggregate on a screen and
#: R3 requires reconciliation to Amazon's own summary; a mock figure satisfies neither, and mock
#: rows written into `ut_amzn_*` would be indistinguishable from real ones once they are in a grid.
#: So sandbox is allowed for the LIVENESS PROBE and for `--check`, and `amazon_store.sync` REFUSES
#: it by name. That is what makes the sandbox app useful without making it dangerous.
SANDBOX_ENDPOINTS = {
"na": "https://sandbox.sellingpartnerapi-na.amazon.com",
"eu": "https://sandbox.sellingpartnerapi-eu.amazon.com",
"fe": "https://sandbox.sellingpartnerapi-fe.amazon.com",
}
DEFAULT_REGION = "na"
#: These paths are constants, not caller input. The outer Product Pricing request is POST, but
#: every request inside its batch is a fixed GET to the read-only item URI.
_COMPETITIVE_SUMMARY_BATCH_PATH = (
"batches/products/pricing/2022-05-01/items/competitiveSummary")
_COMPETITIVE_SUMMARY_ITEM_URI = "/products/pricing/2022-05-01/items/competitiveSummary"
_COMPETITIVE_SUMMARY_INCLUDED = ("featuredBuyingOptions", "referencePrices")
_AWD_INVENTORY_PATH = "awd/2024-05-09/inventory"
_REPLENISHMENT_PATHS = {
"getSellingPartnerMetrics": "replenishment/2022-11-07/sellingPartners/metrics/search",
"listOfferMetrics": "replenishment/2022-11-07/offers/metrics/search",
}
REPLENISHMENT_EMPTY = "Amazon reports no Subscribe and Save offers for this seller"
def is_sandbox(fields):
"""Does this stored credential belong to a SANDBOX app? -> bool.
⚠ ONE READING, IN ONE PLACE. The probe, the request builder and the loader's refusal all ask
this function rather than each testing the field themselves, because three spellings of
"is this sandbox" is three chances for one of them to answer differently -- and the one that
matters is the refusal.
"""
v = (fields or {}).get("sandbox")
return str(v).strip().lower() in ("1", "true", "yes", "on") if v is not None else False
def base_for(fields, region=None):
"""The SP-API host this credential should talk to. Sandbox or production, never a guess."""
r = str(region or (fields or {}).get("region") or DEFAULT_REGION).lower()
table = SANDBOX_ENDPOINTS if is_sandbox(fields) else ENDPOINTS
return table.get(r)
#: US marketplace. Stored per credential; this is only the fallback for a probe.
US_MARKETPLACE_ID = "ATVPDKIKX0DER"
#: The five values an admin pastes. `refresh_token` is the secret; the other four are identifiers.
#: ⚠ `refresh_token` MUST also join `keychain._PREVIEW_FIELDS`, or the entry stores correctly and
#: renders a BLANK preview: nothing raises, and the only symptom is an empty cell on the screen the
#: feature exists for. Exactly the wave-31 `access_token` defect.
CREDENTIAL_FIELDS = ("client_id", "client_secret", "refresh_token", "seller_id", "marketplace_id")
#: ⚠ OPTIONAL, AND NOT ONE OF THE FIVE. `sandbox` is a DECLARATION about which app minted the
#: credential, not a secret and not something an admin must supply. Absent means production, which
#: is the safe default: a sandbox credential mistakenly left undeclared fails loudly against the
#: production host, whereas a production credential wrongly marked sandbox would quietly read mocks.
OPTIONAL_FIELDS = ("sandbox", "region")
SQP_ASIN_OPTION_MAX_CHARS = 200
SQP_PERIOD = ("MONTH", "WEEK")
#: ⭐ THE SCHEMA SPINE (owner rulings R4 + R14: seven tables, and NOTHING ELSE). Each row names
#: the table, the bulk report
#: type that fills it, and the summary aggregate its `validate()` reconciles against.
#:
#: ⭐⭐ R3 — `validate()` RECONCILES TO AMAZON'S OWN SUMMARY, not to Odoo. Standing rule 8 says a
#: number that does not tie to Odoo does not ship; settlements, FBA inventory and Brand Analytics
#: have no Odoo counterpart at all. The owner ruled the reconciliation is source-internal
#: (summary vs detail), because the bug class rule 8 exists to catch is OUR transformation, not
#: Amazon's arithmetic. That answer governs every API-only connector, not just this one.
#:
#: ⛔⛔ R12 — THESE ARE STANDALONE DATABASES. Owner, verbatim: *"We're not building a cross
#: source integration. Its all different. Assume that its a whole new databases which they
#: are."* So NOTHING here joins to Odoo: `listings` is not a bridge to `product_data`'s
#: `default_code`, no seller-SKU mapping table is built, and the hand-maintained ASIN
#: mastersheet is NOT retired by this connector. Amazon numbers are read, reconciled and
#: presented on Amazon's own terms.
#: ⭐ The consequence worth stating: this REMOVES the whole class of defect that
#: [[amazon-conversion-k-is-inverted]] describes, because no unit conversion between an Odoo
#: unit and an Amazon unit is ever performed.
#:
#: ⛔⛔ R14 — NO DASHBOARD, AND NO MODULE. Owner: *"this is just database from Amazon, all
#: its fields mapped into our app so it can be seen under Data module and later be pulled
#: into Sheet. All database connector has this exact flow."* We ship the data, not the
#: conclusion. ⭐ `sheet/BindingEditor.tsx:61` binds on `database.startsWith("ut_")`, so
#: `ut_amzn_*` is Sheet-bindable the moment it exists; that path needs no work.
#:
#: ⚠ `report` is `None` where no bulk report flavor is confirmed. That is O5 of the ideation
#: record and it is NOT a licence to page an entity endpoint quietly: an unconfirmed row must
#: either find its report or REPORT the limit with cause, per standing rule 1.
#:
#: `history` is Amazon's own history floor for a dated table, one of:
#: {"rolling_days": N, "edge": "start"|"end", "evidence": str}: Amazon refuses a window whose
#: start (or end) is older than now minus N days. The floor moves with the clock.
#: {"from": "YYYY-MM-DD", "evidence": str}: Amazon serves nothing older than this date.
#: {"seller_floor": False, "evidence": str}: brand-level data; the seller's first month does not
#: bound it, so history walks back until Amazon refuses an older period.
#: A `from` rule also replaces the seller month, even when older. A rolling rule is max(seller, rule).
#: No `history` key: Amazon serves back to the seller's first data (`amazon_store.history_floor`).
REPORT_TYPES = {
# ⭐⭐ R13 — BOTH ORDER REPORTS, BY ROLE. `report` seeds the one-time historical
# backfill because BY_ORDER_DATE is stable and pages cleanly by period; `report_incremental`
# drives every sync after, because BY_LAST_UPDATE is the ONLY one that returns orders whose
# status changed after they were placed. ⛔ Refunds, cancellations and settlement
# restatements all arrive as updates to OLD orders, so an order-date-only sync drifts away
# from Amazon in the direction that flatters us, and standing rule 8 would only catch it later
# against the settlement summary.
"orders": {
"report": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
"report_incremental": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL",
"validates_against": "order report totals vs our order rows",
"role": "Inventory and Order Tracking",
},
"order_items": {
"report": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
"report_incremental": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL",
"validates_against": "order report line totals vs our item rows",
"role": "Inventory and Order Tracking",
},
"listings": {
"report": "GET_MERCHANT_LISTINGS_ALL_DATA",
"snapshot": True,
"validates_against": "listing report row count vs our listing rows",
"role": "Product Listing",
},
# ⛔⛔ THE REPORT THIS ROW ORIGINALLY NAMED IS BEING **REMOVED ON 2026-11-11**.
# `GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE` and `GET_V2_SETTLEMENT_REPORT_DATA_XML` are both
# deprecated and deleted on that date; Amazon's named replacement is
# `GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2`, which "offers the same information in fewer
# columns and streamlined formatting" and is available NOW.
# ⭐ CAUGHT BEFORE THE FIRST SYNC, WHICH IS THE ONLY REASON IT COST NOTHING: had we shipped on
# the deprecated report, settlements would have worked, been reconciled, been trusted, and then
# gone dark in November with no code change on our side to explain it.
# ⚠ FEWER COLUMNS MEANS A DIFFERENT HEADER. This table is `measured_at_sync`, so the parser
# reads whatever V2 actually sends and nothing here needs to know the column list -- which is
# exactly the property that makes swapping the report type a one-line change.
# · https://developer-docs.amazon.com/sp-api/docs/report-type-values-settlement
# Amazon creates settlements on its own schedule and refuses createReport for them.
# This type is a getReports discovery filter, never a requestable report flavor.
"settlements": {
"report_discover": "GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2",
"validates_against": "settlement summary vs settlement lines",
"role": "Finance and Accounting",
},
"inventory": {
"report": "GET_LEDGER_SUMMARY_VIEW_DATA",
"snapshot": True,
"dated_snapshot": True,
"options": {"aggregateByTimePeriod": "DAILY", "aggregateByLocation": "COUNTRY"},
"entity_read": "AWD v2024-05-09 listInventory (all 200-row pages)",
"validates_against": "FBA ledger summary vs detail and AWD API items vs stored AWD rows",
"role": "Amazon Fulfillment / Amazon Warehousing and Distribution",
},
# ⛔⛔ O5 IS CLOSED AND THE ANSWER IS NO (researched 2026-09-04). All 101 report types were
# enumerated and ZERO contain BUYBOX, PRICING, PRICE or COMPETITIVE. So this table SPLITS:
# Buy Box SHARE -> GET_SALES_AND_TRAFFIC_REPORT.salesAndTrafficByAsin.buyBoxPercentage,
# which IS bulk. ⚠ needs the Brand Analytics role, the same one R5 marks
# UNPROVEN, so this row inherits that risk.
# Buy Box PRICE -> Product Pricing entity endpoints ONLY. No bulk path exists.
# ⛔ STANDING RULE 1'S SECOND HALF: the ceiling is Amazon's and cannot be removed, so it is
# REPORTED here with its cause and its fix. Best path is Product Pricing v2022-05-01
# `getCompetitiveSummary` (featured buying options + competitive price threshold): batch 20,
# rate 0.033/sec, burst 1 — about 40 ASINs per minute.
# ⭐ So the ticket ships SHARE from the bulk report as this table's spine, and PRICE as an
# explicitly rate-limited enrichment that names its own ceiling on screen. A silent per-ASIN
# page loop over a full catalogue is precisely what rule 1 forbids.
"pricing": {
"report": "GET_SALES_AND_TRAFFIC_REPORT",
"history": {"rolling_days": 730, "edge": "start",
"evidence": "CANCELLED, Amazon's no data answer, for 2021-09, 2023-01 and 2024-11 (start 743 days "
"back, 17,584 orders that month); DONE with rows 2024-12 (start 713 days back), 2025-05, "
"2025-11 (2026-11-14)"},
"json_root": "salesAndTrafficByAsin",
"report_covers": "buy box SHARE only; PRICE has no bulk path",
"price_path": "Product Pricing v2022-05-01 getCompetitiveSummary (batch 20, 0.033/sec)",
"validates_against": "sales and traffic report totals and competitive ASIN responses",
"role": "Pricing + Brand Analytics",
},
"brand_analytics": {
# ⚠ Returns data only for Brand Registry brand owners (owner ruling R5). Carried as the
# wave's one UNPROVEN ticket with its exit condition written in advance: returns >0 rows
# for any registered brand, else demote to a declared-but-unsynced stub.
# R18 (SDLC 78): one completed Sunday to Saturday WEEK per window. A first load takes the
# latest week only; older weeks keep watched terms only (amazon_store.write_week).
"report": "GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT",
"weekly": True, "period": "WEEK",
"history": {"from": "2025-08-10",
"evidence": "Weekly FATAL, the period may fall outside the available data range, for the weeks "
"of 2021-09-05, 2023-11-05, 2024-11-03, 2025-03-30, 2025-06-29 and 2025-08-03; DONE with "
"rows 2025-10-05, 2026-04-05 and 2026-07-05 (2026-11-14). The weeks between stop at "
"Amazon's first refusal. Search terms cover the marketplace, not the seller"},
"json_root": "dataByDepartmentAndSearchTerm",
"validates_against": "report period totals vs our search-term rows",
"role": "Brand Analytics",
},
"economics": {
"api": "createQuery",
"validates_against": "DAY x MSKU sales, fees and net proceeds vs Amazon RANGE x MSKU totals per currency",
"role": "Selling Partner Insights",
"history": {"rolling_days": 730, "edge": "start",
"evidence": "Data Kiosk FATAL: Start date must be no more than two years ago (2026-11-14)"},
},
"transactions": {
"api": "listTransactions",
"validates_against": "Amazon transaction count and totalAmount per currency vs stored items, and breakdowns vs transaction totals",
"role": "Finance and Accounting",
"history": {"rolling_days": 730, "edge": "start",
"evidence": "listTransactions 400: Start date cannot be before 2 years from now (2026-11-14)"},
},
# snapshot forbids dataStartTime/dataEndTime; min_interval_s is a successful
# refresh floor (also enforced on manual sync). Monthly history is separate.
"fba_fee_estimates": {
"report": "GET_FBA_ESTIMATED_FBA_FEES_TXT_DATA", "snapshot": True,
"min_interval_s": 86400,
"validates_against": "Amazon document data-row count vs stored rows for its latest snapshot date",
"role": "Amazon Fulfillment",
},
"referral_fees": {
"report": "GET_REFERRAL_FEE_PREVIEW_REPORT", "snapshot": True,
"min_interval_s": 86400,
"validates_against": "Amazon document data-row count vs stored rows for its latest snapshot date",
"role": "Finance and Accounting",
},
"storage_fees": {
"report": "GET_FBA_STORAGE_FEE_CHARGES_DATA", "monthly": True,
"min_interval_s": 86400,
"validates_against": "Amazon document data-row count vs stored rows for its latest calendar month",
"role": "Amazon Fulfillment",
},
"search_query_performance": {
"report": "GET_BRAND_ANALYTICS_SEARCH_QUERY_PERFORMANCE_REPORT",
"history": {"from": "2025-04-01",
"evidence": "Monthly FATAL, the period may fall outside the available data range, for 2021-09, "
"2024-10, 2024-11, 2025-01 and 2025-03; 2025-04 onward landed (2026-11-14)",
"periods": {"WEEK": {"from": "2025-07-13", "provisional": True,
"evidence": "2026-11-14 probe refused 2025-07-06 and served 2025-10-05. "
"The intervening twelve weeks are unasked. 2025-07-13 is the "
"first unasked Sunday, not a proved earliest served floor"}}},
"role": "Brand Analytics",
"validates_against": "Amazon dataByAsin row count and ASIN purchases per batch vs stored rows for the latest month",
"json_root": "dataByAsin", "monthly": True,
"period": "MONTH", "periods": SQP_PERIOD,
"asin_option_max_chars": SQP_ASIN_OPTION_MAX_CHARS,
},
}
# S66-T42: inventory sections 2.2 and 2.3. Fields are measured at sync, including
# JSON documents. Row roots were read from amzn/selling-partner-api-models/schemas/reports
# on 2026-09-25 at commit 713565ff394d136629a342120872e65cb073d162.
# json_schema names the public source, without changing the pinned proto.
GROUP_A_TABLES = {
"long_term_storage_fees": {
"label": "Amazon long term storage fees",
"report": "GET_FBA_FULFILLMENT_LONGTERM_STORAGE_FEE_CHARGES_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Complete calendar months; refresh no sooner than 14400 seconds.",
"monthly": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"storage_overage_fees": {
"label": "Amazon storage overage fees",
"report": "GET_FBA_OVERAGE_FEE_CHARGES_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Complete calendar months; refresh no sooner than 14400 seconds.",
"monthly": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"reimbursements": {
"label": "Amazon reimbursements",
"report": "GET_FBA_REIMBURSEMENTS_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"restatement_keys": ("reimbursement_id",),
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"fba_customer_returns": {
"label": "Amazon FBA customer returns",
"report": "GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"restatement_keys": ("order_id", "sku", "fnsku", "asin", "return_date"),
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"replacements": {
"label": "Amazon replacements",
"report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_REPLACEMENT_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"fba_shipped_sales": {
"label": "Amazon FBA shipped sales",
"report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_SALES_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"fba_shipment_promotions": {
"label": "Amazon FBA shipment promotions",
"report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_PROMOTION_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"inventory_ledger_detail": {
"label": "Amazon inventory ledger detail",
"report": "GET_LEDGER_DETAIL_VIEW_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"inventory_planning": {
"label": "Amazon inventory planning",
"report": "GET_FBA_INVENTORY_PLANNING_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"manage_inventory": {
"label": "Amazon manage inventory",
"report": "GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"reserved_inventory": {
"label": "Amazon reserved inventory",
"report": "GET_RESERVED_INVENTORY_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"restock_recommendations": {
"label": "Amazon restock recommendations",
"report": "GET_RESTOCK_INVENTORY_RECOMMENDATIONS_REPORT",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"stranded_inventory": {
"label": "Amazon stranded inventory",
"report": "GET_STRANDED_INVENTORY_UI_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"inbound_noncompliance": {
"label": "Amazon inbound noncompliance",
"report": "GET_FBA_FULFILLMENT_INBOUND_NONCOMPLIANCE_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"inventory_expiration_dates": {
"label": "Amazon inventory expiration dates",
"report": "GET_FBA_FULFILLMENT_INVENTORY_EXPIRATION_DATE_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"recommended_removals": {
"label": "Amazon recommended removals",
"report": "GET_FBA_RECOMMENDED_REMOVAL_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"removal_orders": {
"label": "Amazon removal orders",
"report": "GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"removal_shipments": {
"label": "Amazon removal shipments",
"report": "GET_FBA_FULFILLMENT_REMOVAL_SHIPMENT_DETAIL_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"subscribe_save_forecast": {
"label": "Amazon Subscribe and Save forecast",
"report": "GET_FBA_SNS_FORECAST_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"subscribe_save_performance": {
"label": "Amazon Subscribe and Save performance",
"report": "GET_FBA_SNS_PERFORMANCE_DATA",
"role": "Amazon Fulfillment",
"min_interval_s": 14400,
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"remote_fulfillment_eligibility": {
"label": "Amazon remote fulfillment eligibility",
"report": "GET_REMOTE_FULFILLMENT_ELIGIBILITY",
"role": "Amazon Fulfillment",
"min_interval_s": 86400,
"cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"search_catalog_performance": {
"label": "Amazon search catalog performance",
"report": "GET_BRAND_ANALYTICS_SEARCH_CATALOG_PERFORMANCE_REPORT",
"role": "Brand Analytics",
"history": {"rolling_days": 730, "edge": "end",
"evidence": "FATAL, the period may fall outside the available data range, for 2024-10 (end 744 "
"days back) and every month probed back to 2021-09; DONE with rows 2024-11 (end 714 days "
"back), 2025-03, 2025-04 (2026-11-14)"},
"min_interval_s": 86400,
"cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
"monthly": True,
"json_root": "dataByAsin",
"json_schema": "sellingPartnerSearchCatalogPerformanceReport.json",
"period": "MONTH",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"market_basket": {
"label": "Amazon market basket",
"report": "GET_BRAND_ANALYTICS_MARKET_BASKET_REPORT",
"role": "Brand Analytics",
"history": {"from": "2019-08-01",
"evidence": "DONE with rows 2020-01, 2020-07 and 2021-07 (before the seller's first order "
"2021-08); DONE empty 2019-07 (2026-11-14)"},
"min_interval_s": 86400,
"cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
"monthly": True,
"json_root": "dataByAsin",
"json_schema": "sellingPartnerMarketBasketAnalysisReport.json",
"period": "MONTH",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"repeat_purchase": {
"label": "Amazon repeat purchase",
"report": "GET_BRAND_ANALYTICS_REPEAT_PURCHASE_REPORT",
"role": "Brand Analytics",
"history": {"from": "2023-02-01",
"evidence": "FATAL, the period may fall outside the available data range, for 2021-09 and 2023-01; "
"DONE with rows 2024-10, 2024-11, 2025-03, 2025-04 (2026-11-14). The months between "
"stop at Amazon's first refusal"},
"min_interval_s": 86400,
"cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
"monthly": True,
"json_root": "dataByAsin",
"json_schema": "sellingPartnerRepeatPurchaseReport.json",
"period": "MONTH",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"promotion_performance": {
"label": "Amazon promotion performance",
"report": "GET_PROMOTION_PERFORMANCE_REPORT",
"role": "Selling Partner Insights",
"history": {"rolling_days": 730, "edge": "start",
"evidence": "FATAL: Requests with a promotionStartDateFrom of more than two years ago are not "
"supported (2021-09 window, 2026-11-14)"},
"min_interval_s": 86400,
"cadence_note": "Date windows; refresh no sooner than 86400 seconds.",
"json_root": "promotions",
"json_schema": "promotionReport.json",
"date_options": ["promotionStartDateFrom","promotionStartDateTo"],
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"coupon_performance": {
"label": "Amazon coupon performance",
"report": "GET_COUPON_PERFORMANCE_REPORT",
"role": "Brand Analytics",
"history": {"rolling_days": 730, "edge": "start",
"evidence": "FATAL: Requests with a couponStartDateFrom of more than two years ago are not "
"supported (2021-09 window, 2026-11-14)"},
"min_interval_s": 86400,
"cadence_note": "Date windows; refresh no sooner than 86400 seconds.",
"json_root": "coupons",
"json_schema": "sellerCouponReport.json",
"date_options": ["couponStartDateFrom","couponStartDateTo"],
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"account_health": {
"label": "Amazon account health",
"report": "GET_V2_SELLER_PERFORMANCE_REPORT",
"role": "Selling Partner Insights",
"min_interval_s": 43200,
"cadence_note": "Current snapshot; refresh no sooner than 43200 seconds.",
"snapshot": True,
"json_root": "performanceMetrics",
"json_schema": "accountHealthReport-2020-11-18.json",
"json_extra_roots": ["accountStatuses"],
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"inactive_listings": {
"label": "Amazon inactive listings",
"report": "GET_MERCHANT_LISTINGS_INACTIVE_DATA",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"cancelled_listings": {
"label": "Amazon cancelled listings",
"report": "GET_MERCHANT_CANCELLED_LISTINGS_DATA",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"suppressed_listings": {
"label": "Amazon suppressed listings",
"report": "GET_MERCHANTS_LISTINGS_FYP_REPORT",
"role": "Product Listing",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"listing_defects": {
"label": "Amazon listing defects",
"report": "GET_MERCHANT_LISTINGS_DEFECT_DATA",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"sold_listings": {
"label": "Amazon sold listings",
"report": "GET_CONVERGED_FLAT_FILE_SOLD_LISTINGS_DATA",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"mfn_returns": {
"label": "Amazon MFN returns",
"report": "GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"restatement_keys": ("order_id", "sku", "return_request_date"),
"cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
"max_window_days": 60,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"b2b_recommended": {
"label": "Amazon B2B product opportunities",
"report": "GET_B2B_PRODUCT_OPPORTUNITIES_RECOMMENDED_FOR_YOU",
"role": "Product Listing",
"min_interval_s": 604800,
"cadence_note": "Current snapshot; refresh no sooner than 604800 seconds.",
"snapshot": True,
"json_root": "recommendations",
"json_schema": "b2bProductOpportunitiesRecommendedForYouReport-2020-11-19.json",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"b2b_not_yet_on_amazon": {
"label": "Amazon B2B products not yet on Amazon",
"report": "GET_B2B_PRODUCT_OPPORTUNITIES_NOT_YET_ON_AMAZON",
"role": "Product Listing",
"min_interval_s": 604800,
"cadence_note": "Current snapshot; refresh no sooner than 604800 seconds.",
"snapshot": True,
"json_root": "recommendations",
"json_schema": "b2bProductOpportunitiesNotYetOnAmazonReport-2020-11-19.json",
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"geo_opportunities": {
"label": "Amazon geo opportunities",
"report": "GET_FLAT_FILE_GEO_OPPORTUNITIES",
"role": "Inventory and Order Tracking",
"min_interval_s": 86400,
"cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"out_of_stock_mfn": {
"label": "Amazon out of stock MFN listings",
"report": "GET_OUT_OF_STOCK_MFN_INFORMATION",
"role": "Inventory and Order Tracking",
"min_interval_s": 14400,
"cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"b2b_quotes": {
"label": "Amazon B2B quantity discounts",
"report": "RFQD_BULK_DOWNLOAD",
"role": "Product Listing",
"min_interval_s": 86400,
"cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"fee_discounts": {
"label": "Amazon fee discounts",
"report": "FEE_DISCOUNTS_REPORT",
"role": "Product Listing",
"min_interval_s": 86400,
"cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"order_metrics": {
"label": "Amazon order metrics",
"api": "getOrderMetrics",
"role": "Inventory and Order Tracking",
"min_interval_s": 1800,
"cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
"validates_against": "Amazon daily order, unit and sales totals vs stored metrics; order counts independently reconcile orders",
},
"fba_inventory": {
"label": "Amazon FBA inventory summaries",
"api": "getInventorySummaries",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"listing_items": {
"label": "Amazon listing status and issues",
"api": "searchListingsItems",
"role": "Product Listing",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"catalog_items": {
"label": "Amazon catalog attributes",
"api": "searchCatalogItems",
"role": "Product Listing",
"min_interval_s": 1800,
"cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
"snapshot": True,
"validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
},
"fee_estimates_api": {
"label": "Amazon per-price fee estimates",
"api": "getMyFeesEstimates",
"role": "Pricing",
"min_interval_s": 1800,
"cadence_note": "Per-price snapshot; batches of 20 at 0.5 requests per second with a burst of one.",
"snapshot": True,
"validates_against": "Amazon returned estimate count vs stored distinct estimates for the latest batch",
},
"outbound_fulfillment": {
"label": "Amazon outbound fulfillment orders",
"api": "listAllFulfillmentOrders",
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current multi-channel order snapshot; every page and order's items are read at two requests per second.",
"snapshot": True,
"validates_against": "Amazon returned order item count and quantities vs stored outbound fulfillment items",
},
"inbound_shipments": {
"label": "Amazon inbound shipments",
"api": "listInboundPlans",
"operations": ("listInboundPlans", "getInboundPlan", "listShipmentItems"),
"role": "Amazon Fulfillment",
"min_interval_s": 1800,
"cadence_note": "Current FBA shipment item snapshot; every plan and item page at two requests per second per operation.",
"snapshot": True,
"validates_against": "Independently counted Amazon shipment items and quantities vs stored items for every latest plan and shipment",
},
"replenishment": {
"label": "Amazon replenishment metrics",
"api": "getSellingPartnerMetrics",
"operations": ("getSellingPartnerMetrics", "listOfferMetrics"),
"role": "Brand Analytics",
"min_interval_s": 86400,
"cadence_note": "Latest complete month snapshot; every offer page at one request per second per operation.",
"snapshot": True,
"validates_against": "Amazon raw seller metric count and total offer metrics vs stored replenishment rows",
},
"review_topics": {
"label": "Amazon review topics",
"api": "getItemReviewTopics",
"role": "Brand Analytics / Selling Partner Insights",
"role_match": "any",
"min_interval_s": 7 * 86400,
"cadence_note": "Amazon refreshes English review topics weekly in US, UK, France, Italy, Germany, Spain and Japan. Every listing ASIN is requested.",
"snapshot": True,
"validates_against": "Amazon returned positive and negative topic counts per ASIN vs stored topics for the same pass",
},
"review_trends": {
"label": "Amazon review trends",
"api": "getItemReviewTrends",
"role": "Brand Analytics / Selling Partner Insights",
"role_match": "any",
"min_interval_s": 7 * 86400,
"cadence_note": "Amazon refreshes six months of English review trends weekly in US, UK, France, Italy, Germany, Spain and Japan. Every listing ASIN is requested.",
"snapshot": True,
"validates_against": "Amazon raw trend point counts and occurrence percentages per ASIN, sentiment, topic and month vs stored rows for the same pass",
},
"browse_node_review_topics": {
"label": "Amazon category review topics",
"api": "getBrowseNodeReviewTopics",
"role": "Brand Analytics / Selling Partner Insights",
"role_match": "any",
"min_interval_s": 7 * 86400,
"cadence_note": "Amazon refreshes the top 10 positive and negative category topics weekly. Every browse node of every active child ASIN is requested, sorted by mentions and by star rating impact.",
"snapshot": True,
"validates_against": "Amazon raw positive and negative topic counts and metrics per browse node and sort vs stored topics for the same pass",
},
}
REPORT_TYPES.update(GROUP_A_TABLES)
# These are visible declarations, never enablement keys or request allow-list entries.
DECLARED_DATASETS = {
"browse_node_return_topics": {
"label": "Amazon browse node return topics",
"operations": ["getBrowseNodeReturnTopics", "getBrowseNodeReturnTrends"],
"role": "Brand Analytics / Selling Partner Insights",
"role_match": "any",
"cadence_note": "Not requested by this connector.",
"reason": "Browse node return topics and trends describe category returns, not item review trends. Their readers are not built in this release.",
},
"manage_inventory_variants": {
"label": "Amazon manage inventory alternatives",
"report_types": ["GET_FBA_MYI_ALL_INVENTORY_DATA","GET_AFN_INVENTORY_DATA"],
"role": "Amazon Fulfillment",
"cadence_note": "Not requested by this connector.",
"reason": "The connector uses the unsuppressed manage inventory report for this dataset.",
},
"stranded_inventory_loader": {
"label": "Amazon stranded inventory loader",
"report_types": ["GET_STRANDED_INVENTORY_LOADER_DATA"],
"role": "Amazon Fulfillment",
"cadence_note": "Not requested by this connector.",
"reason": "The connector uses the stranded inventory UI report for this dataset.",
},
"listing_variants": {
"label": "Amazon listing report variants",
"report_types": ["GET_MERCHANT_LISTINGS_DATA","GET_MERCHANT_LISTINGS_DATA_BACK_COMPAT","GET_MERCHANT_LISTINGS_DATA_LITE","GET_MERCHANT_LISTINGS_DATA_LITER","GET_FLAT_FILE_OPEN_LISTINGS_DATA"],
"role": "Product Listing",
"cadence_note": "Not requested by this connector.",
"reason": "These listing variants overlap Amazon listings, which reads the all listings report.",
},
"pending_orders": {
"label": "Amazon pending order reports",
"report_types": ["GET_FLAT_FILE_PENDING_ORDERS_DATA","GET_PENDING_ORDERS_DATA","GET_CONVERGED_FLAT_FILE_PENDING_ORDERS_DATA"],
"role": "Inventory and Order Tracking",
"cadence_note": "Not requested by this connector.",
"reason": "Pending orders are covered by Amazon orders.",
},
"archived_orders": {
"label": "Amazon archived orders",
"report_types": ["GET_FLAT_FILE_ARCHIVED_ORDERS_DATA_BY_ORDER_DATE"],
"role": "Inventory and Order Tracking",
"cadence_note": "Not requested by this connector.",
"reason": "Archived orders before the normal history window are not built in this release.",
},
"xml_orders": {
"label": "Amazon XML order reports",
"report_types": ["GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL","GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL"],
"role": "Inventory and Order Tracking",
"cadence_note": "Not requested by this connector.",
"reason": "The XML order reports duplicate the flat file reports used by Amazon orders.",
},
"mfn_return_variants": {
"label": "Amazon MFN return report variants",
"report_types": ["GET_CSV_MFN_PRIME_RETURNS_REPORT","GET_XML_MFN_PRIME_RETURNS_REPORT","GET_FLAT_FILE_MFN_SKU_RETURN_ATTRIBUTES_REPORT","GET_XML_MFN_SKU_RETURN_ATTRIBUTES_REPORT"],
"role": "Inventory and Order Tracking",
"cadence_note": "Not requested by this connector.",
"reason": "Prime return, return attribute and attribute feed record variants are not built; Amazon MFN returns reads returns by return date.",
},
"browse_tree": {
"label": "Amazon browse tree",
"report_types": ["GET_XML_BROWSE_TREE_DATA"],
"role": "Product Listing",
"cadence_note": "Not requested by this connector.",
"reason": "The XML browse tree is category reference data and is not built in this release.",
},
"sales_traffic_kiosk": {
"label": "Amazon sales and traffic query",
"operations": ["analytics_salesAndTraffic_2024_04_24"],
"role": "Brand Analytics",
"cadence_note": "Not requested by this connector.",
"reason": "Same rows as Amazon pricing and Buy Box, which reads the report twin.",
},
"financial_events": {
"label": "Amazon legacy financial events",
"operations": ["listFinancialEvents","listFinancialEventGroups"],
"role": "Finance and Accounting",
"cadence_note": "Not requested by this connector.",
"reason": "Superseded by Amazon financial transactions.",
},
"payouts": {
"label": "Amazon payouts",
"operations": ["listPayouts","listExpectedPayouts"],
"role": "Finance and Accounting",
"cadence_note": "Not requested by this connector.",
"reason": "Payout timing from the Transfers API is not built in this release.",
},
# C7: the daily rival job reads offers outside the sync pass, so the sync requests nothing here.
"offer_prices": {
"label": "Amazon offer prices",
"operations": ["getItemOffersBatch"],
"role": "Pricing",
"cadence_note": "Read once a day by the rival job, outside the sync pass.",
"reason": "The daily rival job reads offer prices through getItemOffersBatch. The sync does not request them.",
},
"promotions": {
"label": "Amazon promotion calendar",
"operations": ["searchPromotions","getPromotion"],
"role": "Pricing",
"cadence_note": "Not requested by this connector.",
"reason": "The Promotions API calendar is not built in this release; promotion results are in Amazon promotion performance.",
},
"aplus_content": {
"label": "Amazon A plus content",
"operations": ["searchContentDocuments"],
"role": "Brand Analytics",
"cadence_note": "Not requested by this connector.",
"reason": "A plus content reference data is not built in this release.",
},
"listing_restrictions": {
"label": "Amazon listing restrictions",
"operations": ["getListingsRestrictions"],
"role": "Product Listing",
"cadence_note": "Not requested by this connector.",
"reason": "Listing restriction reference data is not built in this release.",
},
"product_types": {
"label": "Amazon product type definitions",
"operations": ["searchDefinitionsProductTypes","getDefinitionsProductType"],
"role": "Product Listing",
"cadence_note": "Not requested by this connector.",
"reason": "Product type definition reference data is not built in this release.",
},
"supply_sources": {
"label": "Amazon supply sources",
"operations": ["getSupplySources"],
"role": "Selling Partner Insights",
"cadence_note": "Not requested by this connector.",
"reason": "Supply source reference data is not built in this release.",
},
}
# Include the existing seven base tables and T40/T41 datasets in the same inventory.
GROUP_A = {
key: {"key": key, "label": spec.get("label") or "Amazon " + key.replace("_", " "),
"report_types": tuple(spec[k] for k in ("report", "report_incremental", "report_discover") if spec.get(k)),
"operation": spec.get("api"), "role": spec["role"],
**({"operations": tuple(spec["operations"])} if spec.get("operations") else {}),
"cadence_note": spec.get("cadence_note") or "Uses the existing connector cadence."}
for key, spec in REPORT_TYPES.items()
}
GROUP_A.update({key: {"key": key, **spec} for key, spec in DECLARED_DATASETS.items()})
# Source: AutoWiki/research/datadoe-sync-cadence.md. Unlisted tables keep the daily default.
CADENCE = {
table: {"perDay": 1, "lookbackDays": 1, "intradayLookbackDays": 1, "period": "day"}
for table in GROUP_A
}
for _table, _spec in REPORT_TYPES.items():
if _spec.get("monthly") or _spec.get("period") == "MONTH":
CADENCE[_table].update(period="month", lookbackDays=60, intradayLookbackDays=60)
elif _spec.get("weekly") or _spec.get("min_interval_s", 0) >= 7 * 86400:
CADENCE[_table].update(period="week", lookbackDays=14, intradayLookbackDays=14)
for _tables, _passes, _daily, _intraday in (
(("orders", "order_items"), 6, 8, 1),
(("settlements", "transactions"), 3, 8, 2),
(("listings", "inventory_planning"), 4, 1, 1),
(("account_health", "manage_inventory", "restock_recommendations"), 2, 1, 1),
(("pricing", "fba_fee_estimates", "referral_fees"), 1, 4, 4),
(("reimbursements", "long_term_storage_fees"), 1, 30, 30),
(("fba_customer_returns", "mfn_returns"), 1, 60, 60),
(("storage_fees",), 1, 1, 1),
):
for _table in _tables:
CADENCE[_table].update(perDay=_passes, lookbackDays=_daily,
intradayLookbackDays=_intraday, period="day")
# Ads uses namespaced mirror marker names, so its tables cannot collide with SP-API tables.
from harness import amazon_ads_schema as _ads_schema
CADENCE.update({
"ads_" + table: {"perDay": 4, "lookbackDays": 60, "intradayLookbackDays": 5, "period": "day"}
for table in _ads_schema.TABLE_SPECS
})
del _table, _tables, _spec, _passes, _daily, _intraday, _ads_schema
# Inventory section 2.5: immutable refusal even if a future report roster admits one.
EXCLUDED_REPORT_TYPES = frozenset({
"GET_ORDER_REPORT_DATA_SHIPPING", "GET_ORDER_REPORT_DATA_TAX", "GET_ORDER_REPORT_DATA_ALL",
"GET_FLAT_FILE_ORDER_REPORT_DATA_SHIPPING", "GET_FLAT_FILE_ORDER_REPORT_DATA_TAX",
"GET_FLAT_FILE_ORDERS_RECONCILIATION_DATA_SHIPPING", "GET_FLAT_FILE_ORDERS_RECONCILIATION_DATA_TAX",
"GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_SHIPPING", "GET_ORDERS_DATA",
"GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_ALL", "GET_AMAZON_FULFILLED_SHIPMENTS_DATA_TAX",
"GET_FLAT_FILE_SALES_TAX_DATA", "GET_FLAT_FILE_VAT_INVOICE_DATA_REPORT",
"GET_XML_VAT_INVOICE_DATA_REPORT", "GET_VAT_TRANSACTION_DATA",
"GET_GST_MTR_B2B_CUSTOM", "GET_GST_MTR_B2C_CUSTOM", "GET_EASYSHIP_DOCUMENTS",
"GET_EASYSHIP_DOCUMENTS_PICKEDUP", "GET_EASYSHIP_DOCUMENTS_WAITING_FOR_PICKUP",
"GET_MONTHLY_WARRANTIES", "WARRANTY_BASE_ITEM_INFO",
"GET_AMAZON_FULFILLED_SHIPMENTS_DATA_GENERAL", "GET_SELLER_FEEDBACK_DATA",
})
#: Eight of the ten roles Amazon approved on 2026-07-22. Buyer Communication and Buyer Solicitation
#: are REFUSED (owner ruling R7): both are write-shaped and PII-bearing, and it is precisely those
#: restricted roles that trigger Phase 1 verification, a Phase 2 data-security assessment and an
#: architecture review over screen share at developer registration.
#: · https://developer-docs.amazon.com/sp-api/docs/register-as-a-public-developer
ROLES_TAKEN = (
"Inventory and Order Tracking", "Amazon Fulfillment",
"Amazon Warehousing and Distribution", "Finance and Accounting",
"Pricing", "Product Listing", "Brand Analytics", "Selling Partner Insights",
)
ROLES_REFUSED = ("Buyer Communication", "Buyer Solicitation")
NOTIFICATIONS_SCOPE = "sellingpartnerapi::notifications"
# Destination support: https://developer-docs.amazon.com/sp-api/docs/notification-type-values
NOTIFICATION_TYPES = {
# The report example uses 2020-09-04 despite the page's schema prose saying 1.0.
"REPORT_PROCESSING_FINISHED": {
"roles": ROLES_TAKEN, "payload_version": "2020-09-04", "destinations": ("SQS",)},
"FBA_INVENTORY_AVAILABILITY_CHANGES": {
"roles": ("Amazon Fulfillment",), "payload_version": "1.0", "table": "inventory",
"destinations": ("SQS",)},
"LISTINGS_ITEM_STATUS_CHANGE": {
"roles": ("Product Listing",), "payload_version": "1.0", "table": "listings",
"destinations": ("EventBridge",)},
"BRANDED_ITEM_CONTENT_CHANGE": {
"roles": ("Product Listing",), "payload_version": "1.0", "table": "listings",
"destinations": ("EventBridge",), "requires_brand_owner": True},
"ANY_OFFER_CHANGED": {
"roles": ("Pricing",), "payload_version": "1.0", "table": "pricing",
"destinations": ("SQS",)},
}
_NOTIFICATION_DESTINATIONS_PATH = "notifications/v1/destinations"
_NOTIFICATION_SUBSCRIPTIONS_PATH = "notifications/v1/subscriptions"
#: W59-T39: the connector's approved operation scope, not Amazon's entire role catalogue.
#: Join the report roster rather than maintaining another copy of its role labels. A compound
#: label describes TWO data legs: inventory uses Fulfillment for its report and AWD for its
#: entity read; pricing uses Brand Analytics for its report and Pricing for its entity read.
#: Keep those source labels intact and expose both roles, without granting either entity role
#: the other role's report access.
REPORT_ROLES = {
table: tuple(spec["role"].replace(" / ", " + ").split(" + "))
for table, spec in REPORT_TYPES.items()
}
_REPORT_ROLE_INDEX = {"inventory": 0, "pricing": 1}
_BULK_REPORT_ROLES = tuple(dict.fromkeys(
roles[_REPORT_ROLE_INDEX.get(table, 0)] for table, roles in REPORT_ROLES.items()
if REPORT_TYPES[table].get("report") or REPORT_TYPES[table].get("report_discover")))
_APPROVED_REPORT_TYPES = tuple(dict.fromkeys(
spec[key] for spec in REPORT_TYPES.values() for key in ("report", "report_incremental")
if spec.get(key)))
#: Exact method/path pairs. Braced ids match ONE opaque path segment, never a suffix, query,
#: escaped slash or traversal. POSTs generate reports, queries or fees, or wrap fixed read-only GETs.
#: LWA, presigned documents and the schema module's public GitHub refresh are not SP-API
#: operations. The gate enumerates those transports separately; they confer no operation scope.
OPERATIONS = {
"createReport": {
"name": "createReport", "roles": _BULK_REPORT_ROLES, "method": "POST",
"path": "reports/2021-06-30/reports", "report_types": _APPROVED_REPORT_TYPES,
},
# Discovery is approved only for Amazon-issued settlements and their finance role.
# Sharing the Reports path grants neither the other bulk types nor their roles.
"getReports": {
"name": "getReports", "roles": ("Finance and Accounting",), "method": "GET",
"path": "reports/2021-06-30/reports",
"report_types": (REPORT_TYPES["settlements"]["report_discover"],),
},
"getReport": {
"name": "getReport", "roles": _BULK_REPORT_ROLES, "method": "GET",
"path": "reports/2021-06-30/reports/{reportId}",
},
"getReportDocument": {
"name": "getReportDocument", "roles": _BULK_REPORT_ROLES, "method": "GET",
"path": "reports/2021-06-30/documents/{documentId}",
},
"getMarketplaceParticipations": {
"name": "getMarketplaceParticipations", "roles": ("Selling Partner Insights",),
"method": "GET", "path": "sellers/v1/marketplaceParticipations",
},
"getCompetitiveSummary": {
"name": "getCompetitiveSummary", "roles": ("Pricing",), "method": "POST",
"path": "batches/products/pricing/2022-05-01/items/competitiveSummary",
},
"getItemOffersBatch": {
"name": "getItemOffersBatch", "roles": ("Pricing",), "method": "POST",
"path": "batches/products/pricing/v0/itemOffers",
},
"getMyFeesEstimates": {
"name": "getMyFeesEstimates", "roles": ("Pricing",), "method": "POST",
"path": "products/fees/v0/feesEstimate",
},
"listInventory": {
"name": "listInventory", "roles": ("Amazon Warehousing and Distribution",),
"method": "GET", "path": "awd/2024-05-09/inventory",
},
"createQuery": {"name": "createQuery", "roles": ("Selling Partner Insights",),
"method": "POST", "path": _QUERIES_CREATE_PATH},
"getQuery": {"name": "getQuery", "roles": ("Selling Partner Insights",),
"method": "GET", "path": "dataKiosk/2023-11-15/queries/{queryId}"},
"getDocument": {"name": "getDocument", "roles": ("Selling Partner Insights",),
"method": "GET", "path": "dataKiosk/2023-11-15/documents/{documentId}"},
"listTransactions": {"name": "listTransactions", "roles": ("Finance and Accounting",),
"method": "GET", "path": _TRANSACTIONS_PATH},
"getOrderMetrics": {"name": "getOrderMetrics", "roles": ("Inventory and Order Tracking",),
"method": "GET", "path": "sales/v1/orderMetrics"},
"getInventorySummaries": {"name": "getInventorySummaries", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "fba/inventory/v1/summaries"},
"searchListingsItems": {"name": "searchListingsItems", "roles": ("Product Listing",),
"method": "GET", "path": "listings/2021-08-01/items/{sellerId}"},
"searchCatalogItems": {"name": "searchCatalogItems", "roles": ("Product Listing",),
"method": "GET", "path": "catalog/2022-04-01/items"},
"getItemReviewTopics": {"name": "getItemReviewTopics",
"roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
"method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/reviews/topics"},
"getItemReviewTrends": {"name": "getItemReviewTrends",
"roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
"method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/reviews/trends"},
"getItemBrowseNode": {"name": "getItemBrowseNode",
"roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
"method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/browseNode"},
"getBrowseNodeReviewTopics": {"name": "getBrowseNodeReviewTopics",
"roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
"method": "GET",
"path": "customerFeedback/2024-06-01/browseNodes/{browseNodeId}/reviews/topics"},
"listAllFulfillmentOrders": {"name": "listAllFulfillmentOrders", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "fulfillmentOutbound/2020-07-01/fulfillmentOrders"},
"getFulfillmentOrder": {"name": "getFulfillmentOrder", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "fulfillmentOutbound/2020-07-01/fulfillmentOrders/{sellerFulfillmentOrderId}"},
"listInboundPlans": {"name": "listInboundPlans", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans"},
"getInboundPlan": {"name": "getInboundPlan", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}"},
"listPrepDetails": {"name": "listPrepDetails", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/items/prepDetails"},
"getInboundOperationStatus": {"name": "getInboundOperationStatus", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/operations/{operationId}"},
"listShipmentItems": {"name": "listShipmentItems", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/shipments/{shipmentId}/items"},
# The 2024 Item carries no received units: the legacy v0 item read joins them by confirmation ID and SKU.
"getShipment": {"name": "getShipment", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/shipments/{shipmentId}"},
"getShipmentItemsByShipmentId": {"name": "getShipmentItemsByShipmentId", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "fba/inbound/v0/shipments/{shipmentId}/items"},
"getShipmentItems": {"name": "getShipmentItems", "roles": ("Amazon Fulfillment",),
"method": "GET", "path": "fba/inbound/v0/shipmentItems"},
"getSellingPartnerMetrics": {"name": "getSellingPartnerMetrics", "roles": ("Brand Analytics",),
"method": "POST", "path": "replenishment/2022-11-07/sellingPartners/metrics/search"},
"listOfferMetrics": {"name": "listOfferMetrics", "roles": ("Brand Analytics",),
"method": "POST", "path": "replenishment/2022-11-07/offers/metrics/search"},
"createDestination": {"name": "createDestination", "roles": (), "method": "POST",
"path": _NOTIFICATION_DESTINATIONS_PATH, "scope": NOTIFICATIONS_SCOPE},
"getDestinations": {"name": "getDestinations", "roles": (), "method": "GET",
"path": _NOTIFICATION_DESTINATIONS_PATH, "scope": NOTIFICATIONS_SCOPE},
"createSubscription": {"name": "createSubscription", "roles": ROLES_TAKEN, "method": "POST",
"path": "notifications/v1/subscriptions/{notificationType}"},
"getSubscription": {"name": "getSubscription", "roles": ROLES_TAKEN, "method": "GET",
"path": "notifications/v1/subscriptions/{notificationType}"},
}
#: Answer "what does this approved role let this connector read?" directly from data.
#: The report-side roles above are derived from REPORT_TYPES, including its compound labels.
ROLE_OPERATIONS = {
role: tuple(name for name, operation in OPERATIONS.items() if role in operation["roles"])
for role in ROLES_TAKEN
}
# Containment record for the Amazon approval-control series, measured 2026-09-13.
# Git ancestry is not the record here: a packed wave container carries no source
# history. The laptop ancestry check lives in intake finding F23 in
# AutoWiki/research/ideation/wave59-intake.md.
# Each entry claims what exists, never that the control is correct. `contained`
# records full containment; False preserves a documented partial contribution.
# `checkable` means the module can be imported from platform/ without reaching up.
# False is an honest ownership boundary, not a gap to paper over: platform must
# not import the web API, and a Dockerfile is not an importable Python module.
# This is data only; resolving symbols belongs to the checker (W59-T39).
APPROVAL_CONTROLS = {
"f1d803d": {
"carries": "shared persistent login-attempt lockout",
"module": "platform/core/users.py",
"symbol": "LOGIN_LOCKOUT_BUCKET",
"contained": True,
"checkable": True,
},
"be68048": {
"carries": "password minimum age in the password policy",
"module": "platform/core/users.py",
"symbol": "PASSWORD_MIN_AGE_DAYS",
"contained": True,
"checkable": True,
},
"83bfed7": {
"carries": "the audited lockfile is the dependency boundary",
"module": "aios-web/Dockerfile",
"symbol": None,
"contained": False,
"checkable": False,
"note": (
"The lockfile COPY at aios-web/Dockerfile:37 stands; the npm ci half "
"does not: :38 is npm install --no-audit --no-fund --ignore-scripts. "
"The cause is a Windows-resolved lockfile, booked as HARNESS W-170. "
"Dockerfile and the lockfile belong to lane F in Wave 59. "
"This web build control cannot be resolved here because Dockerfile "
"is not an importable Python module."
),
},
"849067e": {
"carries": "Pricing and AWD read operations, and the eight approved roles",
"module": "platform/harness/amazon_client.py",
"symbol": "ROLES_TAKEN",
"contained": True,
"checkable": True,
},
"7e556f8": {
"carries": "exact-tenant raw-mirror purge",
"module": "platform/harness/amazon_store.py",
"symbol": "purge",
"contained": True,
"checkable": True,
},
"9c9454b": {
"carries": "origin attribution on materialised Amazon tables",
"module": "aios-web/api/amazon_relational.py",
"symbol": "source_attribution",
"contained": True,
"checkable": False,
"note": (
"Owned by the web API layer, which platform may not import; "
"source_attribution cannot be resolved from this layer."
),
},
"df1252b": {
"carries": "origin attribution on Sheet workbooks and the scope cache",
"module": "platform/core/sheets.py",
"symbol": "AMAZON_DATA_ORIGIN_NAME",
"contained": True,
"checkable": True,
},
}
_UA = "AIOS-Loopable/1.0 (+read-only)"
_TIMEOUT = 20
class AmazonError(RuntimeError):
"""Any refusal from LWA or SP-API, already stripped of anything secret."""
class AmazonReportError(AmazonError):
"""Vendor report refusal, with its complete reason available to the batch coordinator."""
def __init__(self, message, reason, status):
self.vendor_reason = str(reason).replace("\u2014", "; ").replace("\u2013", " to ")
self.status = status
super().__init__(f"{message}: {self.vendor_reason}")
class AmazonReportPending(AmazonError):
"""A bounded poll ended before the report, which must be resumed by ID."""
def __init__(self, report_id, status):
self.report_id, self.status = str(report_id), str(status or "pending")
super().__init__(f"Report {self.report_id} is still {self.status}; resume its saved ID next pass")
def sqp_refused_asins(error, asins):
"""Only Amazon's named brand refusals permit removing an ASIN from one retry."""
if not isinstance(error, AmazonReportError) or error.status not in (400, "FATAL"):
return []
reason = error.vendor_reason
if not re.search(r"not\s+(?:part|associated|owned|eligible|authorized|belong|registered)|invalid\s+asin|outside.*brand", reason, re.I):
return []
named = set(re.findall(r"\b[A-Z0-9]{10}\b", reason.upper()))
return [asin for asin in asins if asin in named]
class AmazonOperationRefused(AmazonError):
"""A local scope refusal, never a throttle and never eligible for throttling retries."""
def __init__(self, operation):
super().__init__(
f"Refused {_safe(operation)}: this connector is limited to the approved read-only set")
class AmazonThrottled(AmazonError):
"""An operation deferred until resume_at, with metadata safe for a pass summary."""
def __init__(self, message, retry_after=None, *, operation=None, resume_at=None, report_id=None):
super().__init__(message)
self.operation = operation if operation in OPERATIONS else None
self.report_id = report_id
try:
delay = float(retry_after)
self.retry_after = max(0.0, delay) if math.isfinite(delay) else None
except (TypeError, ValueError):
try:
# Retry-After also admits an IMF-fixdate, always expressed in GMT.
stamp = datetime.strptime(str(retry_after).strip(), "%a, %d %b %Y %H:%M:%S GMT").replace(tzinfo=timezone.utc)
self.retry_after = max(0.0, (stamp - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError, OverflowError):
self.retry_after = None
try:
deadline = (datetime.now(timezone.utc) + timedelta(seconds=self.retry_after or 0.0)).isoformat()
except OverflowError:
deadline = datetime.max.replace(tzinfo=timezone.utc).isoformat()
self.resume_at = resume_at or deadline
def as_resume(self):
"""Return the continuation contract consumed by amazon_store without failing a pass."""
row = {"state": "throttled", "operation": self.operation,
"retry_after": self.retry_after, "resume_at": self.resume_at}
if self.report_id is not None:
row["report_id"] = str(self.report_id)
return row
def seller_key(fields):
"""The createReport quota's owner: one seller and region, never a secret."""
fields = fields or {}
ident = [str(fields.get("seller_id") or fields.get("client_id") or ""),
str(fields.get("region") or DEFAULT_REGION).lower(), bool(is_sandbox(fields))]
return hashlib.sha256(json.dumps(ident).encode()).hexdigest()[:16]
def prefetch_key(fields, report_type, start=None, end=None, options=None):
"""One report request's identity: seller, type, window and options. Two tables sharing one report share it."""
return json.dumps([seller_key(fields), str(report_type), start, end, dict(options) if options else None],
sort_keys=True)
@contextmanager
def prefetch_scope(documents, *, only=True):
"""S82-T14: serve `{prefetch_key: (text, meta)}` without a vendor call. `only` defers any other report.
Yields the set of keys served, so the job marks only the windows a write consumed.
"""
served = set()
token = _prefetch.set({"documents": dict(documents), "only": bool(only), "served": served})
try:
yield served
finally:
_prefetch.reset(token)
@contextmanager
def report_ledger_scope(take):
"""S82-T14: every new createReport in this context first draws from `take(fields)`."""
token = _report_ledger.set(take)
try:
yield
finally:
_report_ledger.reset(token)
def prefetch_active():
"""True inside a first-load job's write, where the job owns report pacing."""
return _prefetch.get() is not None
def _prefetched(fields, report_type, start, end, options):
held = _prefetch.get()
if held is None:
return None
key = prefetch_key(fields, report_type, start, end, options)
if key in held["documents"]:
held["served"].add(key)
return held["documents"][key]
if held["only"]:
# The job polls its own reports together; a write it runs never starts another.
raise AmazonThrottled(f"The first-load job requests the {report_type} report for this window itself. "
"It resumes in a later generation.", retry_after=0, operation="createReport")
return None
def _draw_report_token(fields):
take = _report_ledger.get()
if take is not None:
take(fields)
@contextmanager
def rate_limit_scope(tenant, client="amazon_sp"):
"""Isolate one tenant and connection's operation quotas, including refreshed access tokens."""
tenant_token = _tenant_scope.set((str(tenant), str(client)))
client_token = _client_scope.set(None)
reserved = _reservation.set(None)
try:
yield
finally:
_reservation.reset(reserved)
_client_scope.reset(client_token)
_tenant_scope.reset(tenant_token)
def _scope_for(token, region, sandbox):
digest = hashlib.sha256(str(token).encode()).hexdigest()
with _rate_lock:
client = _token_scopes.get((_tenant_scope.get(), digest), digest)
return (_tenant_scope.get(), client, str(region or DEFAULT_REGION).lower(), bool(sandbox))
def _remember_token(fields, token):
client = hashlib.sha256(json.dumps(
[_tenant_scope.get(), str(fields.get("tenant") or ""), str(fields.get("client_id") or ""),
str(fields.get("seller_id") or ""), str(fields.get("refresh_token") or "")],
separators=(",", ":")).encode()).hexdigest()
with _rate_lock:
_token_scopes[(_tenant_scope.get(), hashlib.sha256(token.encode()).hexdigest())] = client
_client_scope.set(_scope_for(token, fields.get("region"), is_sandbox(fields)))
@contextmanager
def _pacing_scope(scope):
previous = _client_scope.set(scope)
try:
yield
finally:
_client_scope.reset(previous)
def _rate_state(operation, scope):
with _rate_lock:
return _rate_states.setdefault((scope, operation),
{"last": None, "interval": None, "until": 0.0, "lock": threading.Lock()})
def _default_interval(operation):
return {"createReport": REPORT_SUSTAINED_SECONDS, "createQuery": QUERY_SUSTAINED_SECONDS,
"getReport": 0.5, "getReports": 1 / 0.0222, "getReportDocument": 1 / 0.0167,
"getQuery": 0.5, "getDocument": 0.5, "getQueries": 0.5,
"getCompetitiveSummary": COMPETITIVE_SUMMARY_INTERVAL,
"getItemOffersBatch": ITEM_OFFERS_INTERVAL, "listPrepDetails": 1.0,
"getInboundOperationStatus": 0.5,
"listInventory": AWD_INVENTORY_INTERVAL, "listTransactions": TRANSACTIONS_INTERVAL,
"listAllFulfillmentOrders": 0.5, "getFulfillmentOrder": 0.5,
"getSellingPartnerMetrics": 1.0, "listOfferMetrics": 1.0,
**ENTITY_INTERVALS, **INBOUND_INTERVALS, **FEEDBACK_INTERVALS}.get(operation, 1.0)
def _observe_rate(operation, scope, headers):
try:
rate = float(next((v for k, v in (headers or {}).items()
if str(k).lower() == "x-amzn-ratelimit-limit"), 0))
except (ValueError, TypeError, AttributeError):
return
if math.isfinite(rate) and rate > 0 and math.isfinite(1 / rate):
state = _rate_state(operation, scope)
with state["lock"]:
state["interval"] = 1 / rate
def _pace_operation(operation, scope, interval, *, sleep, now):
state = _rate_state(operation, scope)
with state["lock"]:
stamp, last = now(), state["last"]
gap = state["interval"] if state["interval"] is not None else interval
wait = max(0.0, state["until"] - stamp,
last + gap - stamp if last is not None else 0.0)
if wait > RETRY_MAX_SECONDS:
raise AmazonThrottled(f"Amazon throttled (429). Operation: {operation}. "
"Resume next pass after the operation's rate limit delay.",
retry_after=wait, operation=operation)
if wait:
sleep(wait)
state["last"] = max(stamp + wait, now())
return wait
def _safe(url):
"""A URL fit to appear in an error message: query string dropped entirely.
Same idiom as `connectors_meta._safe`. SP-API puts marketplace ids, seller ids and date
windows in query parameters, and an error string is the one place a caller reliably copies
into a ticket or a screenshot.
"""
try:
p = urllib.parse.urlsplit(str(url))
return urllib.parse.urlunsplit((p.scheme, p.netloc, p.path, "", ""))
except Exception: # noqa: BLE001
return "<url>"
def operation_for(method, path):
"""Resolve an exact approved operation, or None. Query parameters belong in **params."""
parts = str(path).lstrip("/").split("/")
for operation in OPERATIONS.values():
template = operation["path"].split("/")
if str(method).upper() != operation["method"] or len(parts) != len(template):
continue
if all(
(bool(part) and part not in (".", "..")
and all(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."
for c in part))
if segment.startswith("{") and segment.endswith("}") else part == segment
for part, segment in zip(parts, template)
):
return operation
return None
def require_operation(method, path, *, report_type=None):
"""Fail closed before constructing any URL or touching a transport."""
if report_type in EXCLUDED_REPORT_TYPES:
raise AmazonOperationRefused(f"excluded report {report_type}")
operation = operation_for(method, path)
if operation is None:
raise AmazonOperationRefused(f"{str(method).upper()} {_safe(path)}")
if (operation["name"] in ("getSubscription", "createSubscription")
and str(path).rsplit("/", 1)[-1] not in NOTIFICATION_TYPES):
raise AmazonOperationRefused("Notifications type")
# A Reports URL alone is insufficient: restricted report families use this same POST.
# Admit only the bulk flavors joined from the seven declared tables, including incrementals.
if report_type is not None and str(report_type) not in operation.get("report_types", ()):
raise AmazonOperationRefused(f"{operation['name']} report {report_type}")
return operation
def _retry(attempt_fn, what, *, sleep=time.sleep, rand=random.random, exhausted_fix=None,
operation=None, scope=None, now=time.monotonic):
"""Retry only SP-API throttling; return successes and propagate other refusals unchanged."""
reserved = _reservation.get()
_reservation.set(None)
prepaid = bool(scope is not None and reserved and reserved[0] == operation
and reserved[1] in (None, scope))
if prepaid:
sleep, now = reserved[2:4]
state = _rate_state(operation, scope)
with state["lock"]:
state["last"] = reserved[4]
for n in range(1, RETRY_MAX_ATTEMPTS + 1):
try:
if scope is not None and not (n == 1 and prepaid):
wait = _pace_operation(operation, scope, _default_interval(operation), sleep=sleep, now=now)
if operation == "createReport":
_report_pacer["waited"].set(wait)
return attempt_fn()
except AmazonThrottled as e:
operation = operation or e.operation or (what if what in OPERATIONS else None)
floor = e.retry_after or 0.0
wait = max(floor, min(RETRY_MAX_SECONDS, RETRY_BASE_SECONDS * 2 ** (n - 1)))
wait = max(floor, min(RETRY_MAX_SECONDS,
wait * (1 - RETRY_JITTER + RETRY_JITTER * rand() * 2)))
if scope is not None:
state = _rate_state(operation, scope)
with state["lock"]:
state["until"] = max(state["until"], now() + wait)
interval = state["interval"]
if interval is not None and state["last"] is not None:
wait = max(wait, state["last"] + interval - now())
if n == RETRY_MAX_ATTEMPTS or wait > RETRY_MAX_SECONDS:
fix = exhausted_fix or "sync fewer tables at once and widen the report window"
raise AmazonThrottled(
f"Amazon throttled (429). Operation: {operation or 'unknown'}. Cause: SP-API quota. "
f"Fix: resume next pass after retry delay. {n - 1} retries spent. {fix}. "
f"Endpoint: {_safe(what)}", retry_after=wait, operation=operation) from None
if scope is None:
sleep(wait)
def _pace_report_create(*, sleep=time.sleep, now=time.monotonic):
"""Reserve one report creation under the burst, refill rate and minimum gap; return its wait."""
if _client_scope.get() is not None:
return _pace_entity("createReport", REPORT_SUSTAINED_SECONDS, sleep=sleep, now=now)
with _report_pacer["lock"]:
stamp = now()
updated = _report_pacer["updated"]
elapsed = max(0.0, stamp - updated) if updated is not None else 0.0
tokens = min(REPORT_BURST, _report_pacer["tokens"] + elapsed / REPORT_SUSTAINED_SECONDS)
last = _report_pacer["last_create"]
gap = last + REPORT_STAGGER_SECONDS - stamp if last is not None else 0.0
wait = max(0.0, gap, (1.0 - tokens) * REPORT_SUSTAINED_SECONDS)
if wait:
sleep(wait)
# ⭐ Count refill during the wait too. A late wake may refill up to the burst, never more.
issued = max(stamp + wait, now())
_report_pacer.update(
tokens=min(REPORT_BURST, tokens + (issued - stamp) / REPORT_SUSTAINED_SECONDS) - 1.0,
updated=issued, last_create=issued)
return wait
def _pace_entity(name, interval, *, sleep=time.sleep, now=time.monotonic):
"""Reserve one operation using its observed rate within the active client scope."""
operation = {"competitive_summary": "getCompetitiveSummary", "awd_inventory": "listInventory",
"transactions": "listTransactions"}.get(name, name)
scope = _client_scope.get()
if scope is not None:
wait = _pace_operation(operation, scope, interval, sleep=sleep, now=now)
_reservation.set((operation, scope, sleep, now, now()))
return wait
pacer = _entity_pacers[name]
with pacer["lock"]:
stamp = now()
last = pacer["last"]
wait = max(0.0, last + interval - stamp) if last is not None else 0.0
if wait:
sleep(wait)
pacer["last"] = max(stamp + wait, now())
_reservation.set((operation, None, sleep, now, pacer["last"]))
return wait
def _pace_query_create(*, sleep=time.sleep, now=time.monotonic):
"""Reserve from Data Kiosk's independent burst-15, one-per-minute bucket."""
if _client_scope.get() is not None:
return _pace_entity("createQuery", QUERY_SUSTAINED_SECONDS, sleep=sleep, now=now)
with _query_pacer["lock"]:
stamp = now()
updated = _query_pacer["updated"]
elapsed = max(0.0, stamp - updated) if updated is not None else 0.0
tokens = min(QUERY_BURST, _query_pacer["tokens"] + elapsed / QUERY_SUSTAINED_SECONDS)
wait = max(0.0, (1.0 - tokens) * QUERY_SUSTAINED_SECONDS)
if wait:
sleep(wait)
issued = max(stamp + wait, now())
_query_pacer.update(tokens=min(QUERY_BURST, tokens +
(issued - stamp) / QUERY_SUSTAINED_SECONDS) - 1.0, updated=issued)
return wait
def economics_query(start, end, marketplace_id, *, summary=False):
"""Build only the pinned economics query; never accept caller GraphQL."""
for value in (start, end):
if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
raise AmazonError("Economics dates must be YYYY-MM-DD")
try:
date.fromisoformat(value)
except ValueError:
raise AmazonError("Economics dates must be valid YYYY-MM-DD dates") from None
if start > end or type(summary) is not bool:
raise AmazonError("Economics needs an ordered date range and a boolean summary selection")
if not isinstance(marketplace_id, str) or not re.fullmatch(r"[A-Z0-9]+", marketplace_id):
raise AmazonError("Economics needs an alphanumeric marketplace ID")
return (_ECONOMICS_TEMPLATES[summary].replace("__START__", start)
.replace("__END__", end).replace("__MARKETPLACE__", marketplace_id))
def _create_query(token, start, end, marketplace_id, *, summary=False,
region=DEFAULT_REGION, timeout=_TIMEOUT, sandbox=False):
"""The third declared POST wrapper, fixed to a read-only economics query."""
require_operation("POST", _QUERIES_CREATE_PATH)
operation, scope = "createQuery", _scope_for(token, region, sandbox)
body = {"query": economics_query(start, end, marketplace_id, summary=summary)}
def attempt():
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
url = f"{base}/{_QUERIES_CREATE_PATH}"
req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
_observe_rate(operation, scope, getattr(response, "headers", None))
got = json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
_observe_rate(operation, scope, exc.headers)
if exc.code == 429:
raise AmazonThrottled("createQuery throttled (429); Data Kiosk permits a burst of "
"15, then one query per 60 seconds",
retry_after=(exc.headers or {}).get("Retry-After")) from None
if exc.code == 403:
raise AmazonError("createQuery answered 403: needs the Selling Partner Insights role") from None
raise AmazonError(f"createQuery answered {exc.code}") from None
except Exception as exc:
raise AmazonError(f"createQuery unreachable: {type(exc).__name__}") from None
if not got.get("queryId"):
raise AmazonError("createQuery returned no queryId")
return str(got["queryId"])
with _pacing_scope(scope):
_pace_query_create()
return _retry(attempt, _QUERIES_CREATE_PATH,
operation=operation, scope=scope,
exhausted_fix="reduce Data Kiosk query frequency and retry the window")
def _kiosk_document(token, document_id, *, region, sandbox, timeout):
meta = _request(f"dataKiosk/2023-11-15/documents/{document_id}", token,
region=region, sandbox=sandbox, timeout=timeout)
url = str(meta.get("documentUrl") or "")
if not url:
raise AmazonError("Data Kiosk document returned no documentUrl")
text = _download_document(url, str(meta.get("compressionAlgorithm") or ""))
return text
def economics_document(fields, start, end, *, summary=False, max_wait=900,
poll_seconds=15, timeout=_TIMEOUT, sleep=time.sleep):
"""Request, poll and download JSONL, including the vendor error document on failure."""
marketplace = str(fields.get("marketplace_id") or US_MARKETPLACE_ID)
economics_query(start, end, marketplace, summary=summary) # Validate before LWA.
token = access_token(fields, timeout=timeout)
region, sandbox = str(fields.get("region") or DEFAULT_REGION), is_sandbox(fields)
query_id = _create_query(token, start, end, marketplace, summary=summary,
region=region, sandbox=sandbox, timeout=timeout)
waited = 0
while waited <= max_wait:
got = _request(f"dataKiosk/2023-11-15/queries/{query_id}", token,
region=region, sandbox=sandbox, timeout=timeout)
state = got.get("processingStatus")
if got.get("errorDocumentId"):
detail = _kiosk_document(token, got["errorDocumentId"], region=region,
sandbox=sandbox, timeout=timeout)
detail = detail.replace("\u2014", "; ").replace("\u2013", " to ")
raise AmazonError(f"Economics query {query_id} {state}: {detail[:1200]}")
if state == "DONE":
doc_id = got.get("dataDocumentId")
if not doc_id:
raise AmazonError(f"Economics query {query_id} returned no dataDocumentId")
return (_kiosk_document(token, doc_id, region=region, sandbox=sandbox, timeout=timeout),
{"queryId": query_id, "reportDocumentId": doc_id})
if state in ("FATAL", "CANCELLED"):
raise AmazonError(f"Economics query {query_id} ended as {state}")
sleep(poll_seconds)
waited += poll_seconds
if waited and waited % 1800 == 0:
token = access_token(fields, timeout=timeout)
raise AmazonError(f"Economics query {query_id} still pending after {max_wait}s; "
"increase the query wait before retrying the window")
def transactions(fields, start, end, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Follow every Finances page at 0.5/s, including empty pages carrying a nextToken."""
token, issued = access_token(fields, timeout=timeout), now()
following, seen, rows = None, set(), []
while True:
_pace_entity("transactions", TRANSACTIONS_INTERVAL, sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
got = _request(_TRANSACTIONS_PATH, token,
region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout,
postedAfter=start, postedBefore=end,
marketplaceId=fields.get("marketplace_id") or US_MARKETPLACE_ID,
nextToken=following,
throttle_fix="resume the same Finances window at its 0.5 requests/second rate")
payload = got.get("payload") or {}
page = payload.get("transactions")
if not isinstance(page, list):
raise AmazonError("listTransactions returned no transactions list")
rows.extend(page)
following = payload.get("nextToken")
if not following:
return rows
if following in seen:
raise AmazonError("listTransactions repeated a nextToken; cannot prove complete pagination; "
"retry the window after Amazon corrects the cursor")
seen.add(following)
ENTITY_INTERVALS = {"getOrderMetrics": 2.0, "getInventorySummaries": 0.5,
"searchListingsItems": 0.2, "searchCatalogItems": 0.5,
"getMyFeesEstimates": 2.0}
FEEDBACK_INTERVALS = {"getItemReviewTopics": 1.0, "getItemReviewTrends": 1.0,
"getItemBrowseNode": 1.0, "getBrowseNodeReviewTopics": 1.0}
#: getItemReviewTopics and getBrowseNodeReviewTopics accept exactly these sortBy values.
FEEDBACK_SORTS = ("MENTIONS", "STAR_RATING_IMPACT")
INBOUND_INTERVALS = {"listInboundPlans": 0.5, "getInboundPlan": 0.5, "listShipmentItems": 0.5,
"getShipment": 0.5, "getShipmentItemsByShipmentId": 0.5, "getShipmentItems": 0.5}
#: Amazon's 400 text for an Amazon Warehousing and Distribution plan in the FBA inbound list.
AWD_PLAN_REFUSAL = "not supported for Amazon Warehousing and Distribution inbound plans"
#: Amazon's 400 text for a V0 shipment converted to a Send-to-Amazon plan: getInboundPlan never serves it.
CONVERTED_PLAN_REFUSAL = ("not supported for Fulfillment Inbound API V0 shipments that have been converted "
"to Send-to-Amazon inbound plans")
class InboundRecords(list):
"""Inbound shipment records, plus `skipped_plans`: each plan Amazon refused alone, with its reason."""
def __init__(self, records=(), skipped_plans=()):
super().__init__(records)
self.skipped_plans = list(skipped_plans)
def _inbound_plan_refusal(exc):
"""Name a 400 that refuses one plan, or return None when the refusal must drop the snapshot."""
text = str(exc)
# A throttle or a local scope refusal is never one plan's answer.
if isinstance(exc, (AmazonThrottled, AmazonOperationRefused)):
return None
if CONVERTED_PLAN_REFUSAL in text:
return {"refusal": "converted", "reason": "Amazon converted this V0 shipment to a Send-to-Amazon plan "
"and does not serve it through getInboundPlan."}
status = re.search(r"(?:\banswered|\bHTTP) 400\b:?\s*", text)
if status is None:
return None
detail = text[status.end():].replace("\u2014", ". ").replace("\u2013", " to ").strip()
return {"refusal": "unknown", "reason": "Amazon refused this plan with a 400: " + (detail or "no reason given.")}
def _require_replenishment_roles():
"""Admit both fixed metric searches before credentials or transport access."""
for operation, path in _REPLENISHMENT_PATHS.items():
admitted = require_operation("POST", path)
if (admitted["name"] != operation or admitted["roles"] != ("Brand Analytics",)
or "Brand Analytics" not in ROLES_TAKEN):
raise AmazonOperationRefused(operation + " requires the Brand Analytics role")
def _replenishment_request(token, operation, marketplace, start, end, *, offset=0,
region=DEFAULT_REGION, sandbox=False, timeout=_TIMEOUT,
sleep=time.sleep, now=time.monotonic):
"""Search only Subscribe and Save performance metrics through fixed read-only POST bodies."""
require_operation("POST", _REPLENISHMENT_PATHS.get(operation, ""))
scope = _scope_for(token, region, sandbox)
_require_replenishment_roles()
if not isinstance(marketplace, str) or not re.fullmatch(r"[A-Z0-9]+", marketplace):
raise AmazonError("Replenishment metrics need an alphanumeric marketplace ID")
try:
lower, upper = (datetime.fromisoformat(value.replace("Z", "+00:00")) for value in (start, end))
valid = (lower.tzinfo is not None and upper.tzinfo is not None and lower <= upper
and (lower.year, lower.month) == (upper.year, upper.month))
except (ValueError, TypeError, AttributeError):
valid = False
if not valid:
raise AmazonError("Replenishment metrics need one calendar month with UTC date-time bounds")
if type(offset) is not int or not 0 <= offset <= 9000 or (operation == "getSellingPartnerMetrics" and offset):
raise AmazonOperationRefused("noncanonical replenishment pagination")
filters = {"aggregationFrequency": "MONTH", "timeInterval": {"startDate": start, "endDate": end},
"timePeriodType": "PERFORMANCE", "marketplaceId": marketplace,
"programTypes": ["SUBSCRIBE_AND_SAVE"]}
body = (filters if operation == "getSellingPartnerMetrics" else
{"filters": filters, "pagination": {"limit": 500, "offset": offset},
"sort": {"order": "ASC", "key": "TOTAL_SUBSCRIPTIONS_REVENUE"}})
def attempt():
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
req = urllib.request.Request(f"{base}/{_REPLENISHMENT_PATHS[operation]}",
data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
_observe_rate(operation, scope, getattr(response, "headers", None))
got = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
_observe_rate(operation, scope, exc.headers)
try:
errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
reason = "; ".join(str(row.get("message") or row.get("code") or "Amazon gave no reason") for row in errors)
except (ValueError, AttributeError, TypeError):
reason = "Amazon gave no reason"
if exc.code == 429:
raise AmazonThrottled(f"{operation} throttled (429); use one request per second with a burst of one",
retry_after=(exc.headers or {}).get("Retry-After")) from None
raise AmazonReportError(f"{operation} refused ({exc.code}). Amazon reason",
reason or "Amazon gave no reason", exc.code) from None
except (OSError, ValueError) as exc:
raise AmazonError(f"{operation} could not read Amazon's response: {type(exc).__name__}") from None
if not isinstance(got, dict):
raise AmazonError(operation + " returned no metric response object")
return got
with _pacing_scope(scope):
_pace_entity(operation, 1.0, sleep=sleep, now=now)
return _retry(attempt, operation, sleep=sleep, now=now, operation=operation, scope=scope,
exhausted_fix="resume replenishment metric searches at one request per second")
def replenishment_metrics(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Read the complete seller summary and every offer page for the last complete month."""
_require_replenishment_roles()
end = datetime.now(timezone.utc).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
last = end - timedelta(seconds=1)
start = last.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
first, final = (value.strftime("%Y-%m-%dT%H:%M:%SZ") for value in (start, last))
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
token, issued = access_token(fields, timeout=timeout), now()
def read(operation, offset=0):
nonlocal token, issued
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
return _replenishment_request(token, operation, marketplace, first, final, offset=offset,
region=str(fields.get("region") or DEFAULT_REGION), sandbox=is_sandbox(fields),
timeout=timeout, sleep=sleep, now=now)
seller = read("getSellingPartnerMetrics").get("metrics")
if not isinstance(seller, list) or any(not isinstance(row, dict) for row in seller):
raise AmazonError("getSellingPartnerMetrics returned no valid metrics list")
offers, expected, identities = [], None, set()
while True:
offset = len(offers)
if offset > 9000:
raise AmazonError("Amazon listOfferMetrics limits offsets to 9000. No partial snapshot was stored. "
"Ask Amazon for a higher pagination limit or a bulk replenishment export.")
got = read("listOfferMetrics", offset)
page = got.get("offers")
pagination = got.get("pagination")
count = pagination.get("totalResults") if isinstance(pagination, dict) else None
if (not isinstance(page, list) or any(not isinstance(row, dict) for row in page)
or type(count) is not int or count < 0 or len(page) > 500):
raise AmazonError("listOfferMetrics returned incomplete offers or totalResults; no partial snapshot was stored")
if expected is not None and count != expected:
raise AmazonError("listOfferMetrics changed totalResults during pagination; retry the complete snapshot")
expected = count
for row in page:
identity = (row.get("asin"), row.get("sku"), row.get("fulfillmentChannelType"),
json.dumps(row.get("timeInterval"), sort_keys=True))
if identity in identities:
raise AmazonError("listOfferMetrics repeated an offer across pages; no partial snapshot was stored")
identities.add(identity)
offers.extend(page)
if len(offers) == expected:
break
if not page or len(offers) > expected:
raise AmazonError("listOfferMetrics ended before its totalResults matched; no partial snapshot was stored")
return {"sellingPartnerMetrics": seller, "offerMetrics": offers, "offerCount": expected,
"marketplaceId": marketplace, "start": first, "end": final}
def outbound_fulfillment_orders(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Read every multi-channel order and its items through the two fixed Fulfillment GET operations."""
path = "fulfillmentOutbound/2020-07-01/fulfillmentOrders"
for operation, target in (("listAllFulfillmentOrders", path),
("getFulfillmentOrder", path + "/fixture-order")):
admitted = require_operation("GET", target)
if (admitted["name"] != operation or admitted["roles"] != ("Amazon Fulfillment",)
or "Amazon Fulfillment" not in ROLES_TAKEN):
raise AmazonOperationRefused(operation + " requires the Amazon Fulfillment role")
token, issued = access_token(fields, timeout=timeout), now()
params = {"queryStartDateTime": "1970-01-01T00:00:00Z"}
seen, orders = set(), {}
def read(target, operation, query):
nonlocal token, issued
_pace_entity(operation, 0.5, sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
got = _request(target, token, region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout, **query,
throttle_fix="continue all outbound fulfillment pages and items at two requests per second")
payload = got.get("payload")
if not isinstance(payload, dict):
raise AmazonError(operation + " returned no valid payload; no partial outbound snapshot was stored")
return payload
while True:
payload = read(path, "listAllFulfillmentOrders", params)
page = payload.get("fulfillmentOrders")
if not isinstance(page, list) or any(not isinstance(order, dict) for order in page):
raise AmazonError("Amazon outbound fulfillment returned no valid order list")
for order in page:
identity = order.get("sellerFulfillmentOrderId")
if not isinstance(identity, str) or operation_for("GET", path + "/" + identity) is None:
raise AmazonError("Amazon outbound fulfillment omitted a supported order ID; no partial snapshot was stored")
orders[identity] = None
following = payload.get("nextToken")
if not following:
break
if not isinstance(following, str) or following in seen:
raise AmazonError("Amazon outbound fulfillment repeated or returned an invalid nextToken; no partial snapshot was stored")
seen.add(following)
params = {"nextToken": following}
records = []
for identity in orders:
payload = read(path + "/" + identity, "getFulfillmentOrder", {})
order, items = payload.get("fulfillmentOrder"), payload.get("fulfillmentOrderItems")
if (not isinstance(order, dict) or order.get("sellerFulfillmentOrderId") != identity
or not isinstance(items, list) or any(not isinstance(item, dict) for item in items)):
raise AmazonError("Amazon outbound fulfillment returned incomplete order items; no partial snapshot was stored")
records.append({"fulfillmentOrder": order, "fulfillmentOrderItems": items})
return records
def inbound_shipment_items(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Read every FBA plan, its shipment summaries and every shipment-item page."""
path = "inbound/fba/2024-03-20/inboundPlans"
targets = (("listInboundPlans", path), ("getInboundPlan", path + "/fixture-plan"),
("listShipmentItems", path + "/fixture-plan/shipments/fixture-shipment/items"),
("getShipment", path + "/fixture-plan/shipments/fixture-shipment"),
("getShipmentItemsByShipmentId", "fba/inbound/v0/shipments/fixture-shipment/items"),
("getShipmentItems", "fba/inbound/v0/shipmentItems"))
for operation, target in targets:
admitted = require_operation("GET", target)
if (admitted["name"] != operation or admitted["roles"] != ("Amazon Fulfillment",)
or "Amazon Fulfillment" not in ROLES_TAKEN):
raise AmazonOperationRefused(operation + " requires the Amazon Fulfillment role")
token, issued = access_token(fields, timeout=timeout), now()
def read(target, operation, query):
nonlocal token, issued
_pace_entity(operation, INBOUND_INTERVALS[operation], sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
body = _request(target, token, region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout, **query,
throttle_fix="continue every FBA inbound plan and item page at two requests per second per operation")
if not isinstance(body, dict):
raise AmazonError(operation + " returned no valid response; no partial inbound snapshot was stored")
return body
def pages(target, operation, root, size):
query, seen = {"pageSize": size}, set()
while True:
body = read(target, operation, query)
page = body.get(root)
if not isinstance(page, list) or any(not isinstance(row, dict) for row in page):
raise AmazonError(operation + " returned no valid " + root + " list; no partial inbound snapshot was stored")
yield page
pagination = body.get("pagination", {})
if not isinstance(pagination, dict):
raise AmazonError(operation + " returned invalid pagination; no partial inbound snapshot was stored")
following = pagination.get("nextToken")
if following is None:
return
if not isinstance(following, str) or not following or following in seen:
raise AmazonError(operation + " repeated or returned an invalid nextToken; no partial inbound snapshot was stored")
seen.add(following)
query = {"pageSize": size, "paginationToken": following}
def identifier(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9-]{38}", value):
raise AmazonError("Amazon FBA inbound omitted a supported ID; no partial snapshot was stored")
return value
marketplace = str(fields.get("marketplace_id") or US_MARKETPLACE_ID)
def receipt_refused(exc):
# A 4xx leaves this shipment's receipt unknown. A throttle, a 5xx or an unreachable call refuses the snapshot.
return not isinstance(exc, AmazonThrottled) and re.search(r"\banswered 4\d\d\b", str(exc)) is not None
def receipts(plan_id, shipment_id):
"""Return the legacy confirmation ID and received units per SKU. Unknown receipts stay out."""
try:
shipment = read(path + "/" + plan_id + "/shipments/" + shipment_id, "getShipment", {})
except AmazonError as exc:
if receipt_refused(exc):
return None, {}
raise
confirmation = shipment.get("shipmentConfirmationId")
if (shipment.get("shipmentId") not in (None, shipment_id) or not isinstance(confirmation, str)
or not re.fullmatch(r"[A-Za-z0-9]{1,40}", confirmation)):
return None, {}
legacy, seen = [], set()
target, operation, query = ("fba/inbound/v0/shipments/" + confirmation + "/items",
"getShipmentItemsByShipmentId", {"MarketplaceId": marketplace})
try:
while True:
payload = read(target, operation, query).get("payload")
rows = payload.get("ItemData") if isinstance(payload, dict) else None
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
return confirmation, {}
legacy.extend(rows)
following = payload.get("NextToken")
if not following:
break
if not isinstance(following, str) or following in seen:
return confirmation, {}
seen.add(following)
target, operation = "fba/inbound/v0/shipmentItems", "getShipmentItems"
query = {"QueryType": "NEXT_TOKEN", "NextToken": following, "MarketplaceId": marketplace}
except AmazonError as exc:
if receipt_refused(exc):
return confirmation, {}
raise
received, repeated = {}, set()
for row in legacy:
sku, units = row.get("SellerSKU"), row.get("QuantityReceived")
if row.get("ShipmentId") not in (None, confirmation) or not isinstance(sku, str):
continue
if sku in received:
repeated.add(sku)
received[sku] = units if type(units) is int and units >= 0 else None
return confirmation, {sku: units for sku, units in received.items() if sku not in repeated}
plans, records, skipped = {}, [], []
for page in pages(path, "listInboundPlans", "inboundPlans", 30):
for plan in page:
plans[identifier(plan.get("inboundPlanId"))] = None
for plan_id in plans:
target = path + "/" + plan_id
try:
plan = read(target, "getInboundPlan", {})
except AmazonError as exc:
# Amazon lists AWD plans here but answers 400 to getInboundPlan for them: they are not FBA plans.
if AWD_PLAN_REFUSAL in str(exc):
continue
# One plan's 400 skips that plan and names it. A throttle or a 5xx still refuses the snapshot.
refusal = _inbound_plan_refusal(exc)
if refusal is None:
raise
skipped.append({"inboundPlanId": plan_id, **refusal})
continue
if plan.get("inboundPlanId") != plan_id or not isinstance(plan.get("status"), str) or not plan["status"]:
raise AmazonError("getInboundPlan returned an incomplete or mismatched plan; no partial inbound snapshot was stored")
# Unconfirmed plans may omit shipments until a placement option is confirmed.
shipments = plan.get("shipments", [])
if not isinstance(shipments, list) or any(not isinstance(shipment, dict) for shipment in shipments):
raise AmazonError("getInboundPlan returned invalid shipments; no partial inbound snapshot was stored")
seen = set()
for shipment in shipments:
shipment_id = identifier(shipment.get("shipmentId"))
if shipment_id in seen or not isinstance(shipment.get("status"), str) or not shipment["status"]:
raise AmazonError("getInboundPlan repeated or omitted a shipment status; no partial inbound snapshot was stored")
seen.add(shipment_id)
items = []
for page in pages(target + "/shipments/" + shipment_id + "/items", "listShipmentItems", "items", 1000):
items.extend(page)
confirmation, received = receipts(plan_id, shipment_id) if items else (None, {})
lines = {}
for item in items:
lines[item.get("msku")] = lines.get(item.get("msku"), 0) + 1
for item in items:
# Receipt is Amazon's explicit QuantityReceived, never a CLOSED status. A split SKU line keeps None.
item["QuantityReceived"] = received.get(item.get("msku")) if lines[item.get("msku")] == 1 else None
records.append({"inboundPlanId": plan_id, "planStatus": plan["status"],
"shipmentId": shipment_id, "status": shipment["status"],
"shipmentConfirmationId": confirmation, "items": items})
return InboundRecords(records, skipped)
def _feedback_admitted(operation):
"""Refuse an unapproved Customer Feedback operation or a missing role before any transport."""
if operation not in FEEDBACK_INTERVALS:
raise AmazonOperationRefused("unapproved Customer Feedback reader")
if not set(OPERATIONS[operation]["roles"]).intersection(ROLES_TAKEN):
raise AmazonOperationRefused("Customer Feedback needs Brand Analytics or Selling Partner Insights")
def _feedback_child_asins(asins):
identifiers = sorted(set(asins))
if any(not isinstance(asin, str) or not re.fullmatch(r"[A-Z0-9]{10}", asin) for asin in identifiers):
raise AmazonError("Customer Feedback contains an invalid child ASIN. Correct the listings catalogue and retry.")
return identifiers
def _feedback_sort(sort_by):
if sort_by not in FEEDBACK_SORTS:
raise AmazonError("Customer Feedback sortBy must be MENTIONS or STAR_RATING_IMPACT")
return sort_by
def _feedback_reads(fields, keys, reads, *, subject, timeout, sleep, now):
"""Yield `(key, label, body, reason)` per key and read, interleaved so each operation paces its own bucket.
A 204, 400 or 404 answers one key: body None and a reason. A 403, an exhausted 429 or any other refusal raises.
"""
token, issued = access_token(fields, timeout=timeout), now()
for key in keys:
for label, operation, path, params in reads(key):
_pace_entity(operation, FEEDBACK_INTERVALS[operation], sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
try:
body = _request(path, token, region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout,
throttle_fix="continue every child ASIN at the Customer Feedback rate limit",
**params)
except AmazonError as exc:
status = getattr(exc, "status", None)
if isinstance(exc, (AmazonThrottled, AmazonOperationRefused)) or status not in (400, 404):
raise
detail = str(getattr(exc, "vendor_message", "") or "").replace("\u2014", ". ").replace("\u2013", " to ")
detail = re.sub(r"[.\s]+$", "", detail.strip())
yield key, label, None, (f"Amazon {operation} answered {status} for this {subject} and marketplace: "
+ (detail or "no reason given") + ".")
continue
if body is None:
yield key, label, None, f"Amazon {operation} returned 204 No Content for this {subject} and marketplace."
continue
yield key, label, body, None
def _feedback_record(operation, asin, marketplace, body, reason):
"""One validated item response, or its absence record."""
if reason is not None:
return {"asin": asin, "marketplaceId": marketplace, "_no_feedback_reason": reason}
root = "topics" if operation == "getItemReviewTopics" else "reviewTrends"
if (not isinstance(body, dict) or body.get("asin") != asin or body.get("marketplaceId") != marketplace
or not isinstance(body.get(root), dict)):
raise AmazonError(f"Amazon {operation} returned an invalid response for the requested child ASIN and marketplace. Retry after Amazon restores its response.")
for key in ("positiveTopics", "negativeTopics"):
topics = body[root].get(key)
if topics is not None and (not isinstance(topics, list) or any(not isinstance(t, dict) for t in topics)):
raise AmazonError(f"Amazon {operation} returned invalid {key}. No partial snapshot was stored.")
return body
def _browse_node_record(body, reason):
"""`{"browse_node_id", "browse_node_name"}` from getItemBrowseNode, or its absence."""
if reason is not None:
return {"_no_feedback_reason": reason}
node, name = (body.get(k) if isinstance(body, dict) else None for k in ("browseNodeId", "displayName"))
if not isinstance(node, str) or not re.fullmatch(r"\d{1,20}", node) or (name is not None and not isinstance(name, str)):
raise AmazonError("Amazon getItemBrowseNode returned no valid browse node. No partial snapshot was stored.")
return {"browse_node_id": node, "browse_node_name": name}
def item_review_feedback(fields, asins, *, operation="getItemReviewTopics", sort_by="MENTIONS", timeout=_TIMEOUT,
sleep=time.sleep, now=time.monotonic):
"""Read every child ASIN, retaining known absences separately from invalid responses."""
if operation not in ("getItemReviewTopics", "getItemReviewTrends"):
raise AmazonOperationRefused("unapproved Customer Feedback reader")
_feedback_admitted(operation)
params = {"sortBy": _feedback_sort(sort_by)} if operation == "getItemReviewTopics" else {}
identifiers = _feedback_child_asins(asins)
if not identifiers:
return []
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
path = OPERATIONS[operation]["path"]
reads = lambda asin: [(None, operation, path.replace("{asin}", asin), {"marketplaceId": marketplace, **params})]
return [_feedback_record(operation, asin, marketplace, body, reason) for asin, _label, body, reason in
_feedback_reads(fields, identifiers, reads, subject="ASIN", timeout=timeout, sleep=sleep, now=now)]
def item_browse_nodes(fields, asins, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""`{asin: {"browse_node_id", "browse_node_name"}}` for every child ASIN; an absence carries `_no_feedback_reason`."""
_feedback_admitted("getItemBrowseNode")
identifiers = _feedback_child_asins(asins)
if not identifiers:
return {}
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
path = OPERATIONS["getItemBrowseNode"]["path"]
reads = lambda asin: [(None, "getItemBrowseNode", path.replace("{asin}", asin), {"marketplaceId": marketplace})]
return {asin: _browse_node_record(body, reason) for asin, _label, body, reason in
_feedback_reads(fields, identifiers, reads, subject="ASIN", timeout=timeout, sleep=sleep, now=now)}
def item_review_topics(fields, asins, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Per child ASIN: its browse node and its topics by both sorts, interleaved on one token.
Returns `{"MENTIONS": [record], "STAR_RATING_IMPACT": [record], "browse_nodes": {asin: node}}`.
"""
for operation in ("getItemBrowseNode", "getItemReviewTopics"):
_feedback_admitted(operation)
identifiers = _feedback_child_asins(asins)
out = {**{sort: [] for sort in FEEDBACK_SORTS}, "browse_nodes": {}}
if not identifiers:
return out
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
node_path, topic_path = (OPERATIONS[name]["path"] for name in ("getItemBrowseNode", "getItemReviewTopics"))
def reads(asin):
return [("browse_node", "getItemBrowseNode", node_path.replace("{asin}", asin), {"marketplaceId": marketplace}),
*((sort, "getItemReviewTopics", topic_path.replace("{asin}", asin),
{"marketplaceId": marketplace, "sortBy": sort}) for sort in FEEDBACK_SORTS)]
for asin, label, body, reason in _feedback_reads(fields, identifiers, reads, subject="ASIN",
timeout=timeout, sleep=sleep, now=now):
if label == "browse_node":
out["browse_nodes"][asin] = _browse_node_record(body, reason)
else:
out[label].append(_feedback_record("getItemReviewTopics", asin, marketplace, body, reason))
return out
def browse_node_review_topics(fields, node_ids, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Each browse node's top category topics by both sorts: `{sort: [record]}`; an absence carries `_no_feedback_reason`."""
_feedback_admitted("getBrowseNodeReviewTopics")
nodes = sorted(set(node_ids))
# The id becomes a path segment, so only a numeric browse node id is admitted.
if any(not isinstance(node, str) or not re.fullmatch(r"\d{1,20}", node) for node in nodes):
raise AmazonError("Customer Feedback contains an invalid browse node ID. Retry after Amazon returns a numeric browse node.")
out = {sort: [] for sort in FEEDBACK_SORTS}
if not nodes:
return out
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
path = OPERATIONS["getBrowseNodeReviewTopics"]["path"]
reads = lambda node: [(sort, "getBrowseNodeReviewTopics", path.replace("{browseNodeId}", node),
{"marketplaceId": marketplace, "sortBy": sort}) for sort in FEEDBACK_SORTS]
for node, sort, body, reason in _feedback_reads(fields, nodes, reads, subject="browse node",
timeout=timeout, sleep=sleep, now=now):
if reason is not None:
out[sort].append({"browseNodeId": node, "marketplaceId": marketplace, "_no_feedback_reason": reason})
continue
if (not isinstance(body, dict) or str(body.get("browseNodeId")) != node
or body.get("marketplaceId") != marketplace or not isinstance(body.get("topics"), dict)):
raise AmazonError("Amazon getBrowseNodeReviewTopics returned an invalid response for the requested browse node and marketplace. Retry after Amazon restores its response.")
for key in ("positiveTopics", "negativeTopics"):
topics = body["topics"].get(key)
if topics is not None and (not isinstance(topics, list) or any(not isinstance(t, dict) for t in topics)):
raise AmazonError(f"Amazon getBrowseNodeReviewTopics returned invalid {key}. No partial snapshot was stored.")
out[sort].append(body)
return out
def group_a_records(fields, operation, *, start=None, end=None, asins=(),
timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""Fixed GET readers, every page and every own-ASIN batch; no record ceiling."""
if operation not in ENTITY_INTERVALS or operation == "getMyFeesEstimates":
raise AmazonOperationRefused("unapproved group (a) reader")
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
path = OPERATIONS[operation]["path"]
params = {"marketplaceIds": marketplace}
if operation == "getOrderMetrics":
params.update(interval=f"{start}--{end}", granularity="Day", granularityTimeZone="UTC")
root, payload_key, next_key = None, "payload", None
elif operation == "getInventorySummaries":
params.update(details="true", granularityType="Marketplace", granularityId=marketplace)
root, payload_key, next_key = "inventorySummaries", "payload", "nextToken"
elif operation == "searchListingsItems":
seller = str(fields.get("seller_id") or "")
if not re.fullmatch(r"[A-Za-z0-9]+", seller):
raise AmazonError("Listing status needs the seller ID saved with the connection")
path = path.replace("{sellerId}", seller)
params.update(includedData="summaries,issues,offers,fulfillmentAvailability,attributes", pageSize=20)
root, payload_key, next_key = "items", None, "pageToken"
else:
# `relationships` (S67-T29, O23): same Catalog Items endpoint and Product Listing role;
# it carries VARIATION parentAsins so the mirror can map every own ASIN to its parent.
# `images` names each ASIN's listing pictures; `amazon_pictures` stores the MAIN one.
params.update(identifiersType="ASIN",
includedData="summaries,salesRanks,dimensions,attributes,relationships,images",
pageSize=20)
root, payload_key, next_key = "items", None, "pageToken"
batches = [None]
if operation == "searchCatalogItems":
identifiers = sorted(set(asins))
if any(not re.fullmatch(r"[A-Z0-9]{10}", str(a)) for a in identifiers):
raise AmazonError("Catalog contains an invalid ASIN; correct the listings or pricing mirror and retry")
batches = [identifiers[i:i + 20] for i in range(0, len(identifiers), 20)]
if not batches:
raise AmazonError("Catalog attributes are waiting for our ASINs; sync Amazon listings first")
token, issued = access_token(fields, timeout=timeout), now()
rows = []
listing_end = datetime.now(timezone.utc)
# Date partitions bypass Listings search's 1,000-item pagination ceiling.
# Inclusive boundaries are deduplicated by SKU after every partition has finished.
if operation == "searchListingsItems":
batches = [(datetime(1970, 1, 1, tzinfo=timezone.utc), listing_end)]
for batch in batches:
query, seen = dict(params), set()
if operation == "searchListingsItems":
lower, upper = batch
query.update(createdAfter=lower.isoformat(), createdBefore=upper.isoformat())
elif batch is not None:
query["identifiers"] = ",".join(batch)
page_rows, expected = [], None
while True:
_pace_entity(operation, ENTITY_INTERVALS[operation], sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
got = _request(path, token, region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout, **query,
throttle_fix=f"continue every page at Amazon's {1 / ENTITY_INTERVALS[operation]:g} requests per second")
body = got.get(payload_key) if payload_key else got
if operation == "searchListingsItems" and isinstance(body, dict):
count = body.get("numberOfResults")
if isinstance(count, int) and count > 1000:
midpoint = lower + (upper - lower) / 2
if (upper - lower) <= timedelta(milliseconds=1):
raise AmazonError("Amazon Listings search exceeds its 1,000 SKU limit within one millisecond. "
"No partial snapshot was stored. Ask Amazon to raise this search limit or use a SKU-filtered export.")
batches.extend(((lower, midpoint), (midpoint, upper)))
page_rows = []
break
page = body.get(root) if root and isinstance(body, dict) else body
if not isinstance(page, list) or any(not isinstance(row, dict) for row in page):
raise AmazonError(f"{operation} returned no valid row list; retry after Amazon restores its response")
page_rows.extend(page)
if isinstance(body, dict) and type(body.get("numberOfResults")) is int:
expected = max(expected or 0, body["numberOfResults"])
following = (got.get("pagination") or {}).get("nextToken")
if isinstance(body, dict):
following = following or (body.get("pagination") or {}).get("nextToken") or body.get("nextToken")
if not following:
if expected is not None and len(page_rows) != expected:
raise AmazonError(f"{operation} reported {expected} rows but returned {len(page_rows)}. "
"No partial snapshot was stored; retry after Amazon restores complete pagination.")
break
if not next_key or following in seen:
raise AmazonError(f"{operation} repeated or cannot follow its nextToken; retry after Amazon fixes pagination")
seen.add(following)
query[next_key] = following
rows.extend(page_rows)
if operation == "searchListingsItems":
unique = {}
for row in rows:
if not row.get("sku"):
raise AmazonError("Amazon listing search omitted a SKU; cannot reconcile date partition boundaries")
unique[row["sku"]] = row
rows = list(unique.values())
return rows
#: getOrderMetrics refuses a Month interval over about two years ("2130D exceeded limit"); 731 days answers.
ORDER_MONTHS_MAX = 24
def _parse_utc(value):
"""A datetime or ISO string as an aware UTC datetime; a bare date reads as UTC midnight."""
if isinstance(value, str):
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def order_months(fields, start, end, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
"""[(month_start "YYYY-MM-01", orderCount)] for [start, end) from getOrderMetrics granularity Month."""
lower = _parse_utc(start).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
upper = _parse_utc(end).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
months = (upper.year - lower.year) * 12 + upper.month - lower.month
if months <= 0:
return []
if months > ORDER_MONTHS_MAX:
raise AmazonError(f"getOrderMetrics answers at most {ORDER_MONTHS_MAX} months per Month interval")
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
operation = "getOrderMetrics"
token = access_token(fields, timeout=timeout)
_pace_entity(operation, ENTITY_INTERVALS[operation], sleep=sleep, now=now)
got = _request(OPERATIONS[operation]["path"], token, region=str(fields.get("region") or DEFAULT_REGION),
sandbox=is_sandbox(fields), timeout=timeout, marketplaceIds=marketplace,
interval=f"{lower.strftime('%Y-%m-%dT%H:%M:%SZ')}--{upper.strftime('%Y-%m-%dT%H:%M:%SZ')}",
granularity="Month", granularityTimeZone="UTC",
throttle_fix=f"continue at Amazon's {1 / ENTITY_INTERVALS[operation]:g} requests per second")
body = got.get("payload") if isinstance(got, dict) else None
if not isinstance(body, list) or any(not isinstance(row, dict) for row in body):
raise AmazonError("getOrderMetrics returned no valid month list; retry after Amazon restores its response")
out = []
for row in body:
month = str(row.get("interval") or "").split("--", 1)[0][:7]
count = row.get("orderCount")
if not re.fullmatch(r"\d{4}-\d{2}", month) or type(count) is not int or count < 0:
raise AmazonError("getOrderMetrics returned a month without an interval or a nonnegative orderCount")
first = datetime.fromisoformat(month + "-01").replace(tzinfo=timezone.utc)
if lower <= first < upper:
out.append((month + "-01", count))
return sorted(out)
def _post_form(url, data, timeout=_TIMEOUT):
# LWA exchanges credentials at api.amazon.com, not an SP-API operation. Its sole caller fixes
# LWA_TOKEN_URL; the connector-wide gate checks that call separately from OPERATIONS.
body = urllib.parse.urlencode(data).encode("ascii")
req = urllib.request.Request(url, data=body, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as e:
detail = ""
try:
payload = json.loads((e.read() or b"").decode("utf-8") or "{}")
# LWA answers {error, error_description}. Neither echoes the secret.
detail = str(payload.get("error_description") or payload.get("error") or "")[:200]
except Exception: # noqa: BLE001
detail = ""
raise AmazonError(f"{_safe(url)} answered {e.code}"
+ (f": {detail}" if detail else "")) from None
except Exception as e: # noqa: BLE001
raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
def access_token(fields, timeout=_TIMEOUT):
"""Exchange a stored refresh token for a ~1 hour LWA access token.
⛔ The returned value is a live bearer credential. It is never logged, never written to disk,
and never returned to a client: callers hold it for the length of one sync and drop it.
"""
f = fields or {}
missing = [k for k in ("client_id", "client_secret", "refresh_token") if not f.get(k)]
if missing:
raise AmazonError("credential is missing " + ", ".join(f"`{m}`" for m in missing))
got = _post_form(LWA_TOKEN_URL, {
"grant_type": "refresh_token",
"refresh_token": str(f["refresh_token"]),
"client_id": str(f["client_id"]),
"client_secret": str(f["client_secret"]),
}, timeout=timeout)
tok = str(got.get("access_token") or "")
if not tok:
raise AmazonError("LWA returned no access token")
_remember_token(f, tok)
return tok
def notifications_token(fields, timeout=_TIMEOUT):
"""Mint a grantless Notifications token without reading the seller refresh token."""
if not all(fields.get(key) for key in ("client_id", "client_secret")):
raise AmazonError("Notifications requires client_id and client_secret in the keychain.")
try:
got = _post_form(LWA_TOKEN_URL, {
"grant_type": "client_credentials", "scope": NOTIFICATIONS_SCOPE,
"client_id": str(fields["client_id"]), "client_secret": str(fields["client_secret"]),
}, timeout=timeout)
except AmazonError as exc:
reason = str(exc)
for key in ("client_id", "client_secret"):
reason = reason.replace(str(fields[key]), "[redacted]")
raise AmazonError(reason.replace("\u2014", ". ").replace("\u2013", " to ")) from None
if not got.get("access_token"):
raise AmazonError("LWA returned no grantless Notifications access token.")
tok = str(got["access_token"])
_remember_token(fields, tok)
return tok
class AmazonNotificationError(AmazonError):
"""An Amazon Notifications refusal carries its status and safe cause."""
def __init__(self, status, reason):
self.status = status
super().__init__(f"Amazon Notifications answered {status}: {reason}")
def _notifications_post(operation, token, body, *, notification_type=None,
region=DEFAULT_REGION, sandbox=False, timeout=_TIMEOUT):
"""Create only a fixed EventBridge destination or an approved notification subscription."""
if operation == "createDestination":
path = _NOTIFICATION_DESTINATIONS_PATH
bridge = (body.get("resourceSpecification") or {}).get("eventBridge") or {}
if (set(body) != {"name", "resourceSpecification"}
or body["name"] != "Loopable"
or body["resourceSpecification"] != {"eventBridge": bridge}
or set(bridge) != {"accountId", "region"}
or not re.fullmatch(r"[0-9]{12}", str(bridge.get("accountId", "")))
or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]+", str(bridge.get("region", "")))):
raise AmazonError("Notifications destination requires an AWS account and region.")
elif operation == "createSubscription" and notification_type in NOTIFICATION_TYPES:
path = _NOTIFICATION_SUBSCRIPTIONS_PATH + "/" + notification_type
if (set(body) != {"payloadVersion", "destinationId"}
or body["payloadVersion"] != NOTIFICATION_TYPES[notification_type]["payload_version"]
or not re.fullmatch(r"[A-Za-z0-9_.-]+", str(body["destinationId"]))):
raise AmazonError("Notifications subscription requires an approved type and destination.")
else:
raise AmazonOperationRefused("Notifications operation")
require_operation("POST", path)
scope = _scope_for(token, region, sandbox)
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError("Notifications SP-API region is unknown.")
def attempt():
req = urllib.request.Request(f"{base}/{path}", data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
_observe_rate(operation, scope, getattr(response, "headers", None))
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
_observe_rate(operation, scope, exc.headers)
try:
errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
reason = str(errors[0].get("message") or "Amazon refused this notification operation.")
except (ValueError, KeyError, IndexError, TypeError):
reason = "Amazon refused this notification operation."
reason = reason.replace(token, "[redacted]").replace("\u2014", ". ").replace("\u2013", " to ")
if exc.code == 429:
raise AmazonThrottled("Amazon Notifications throttled (429). Retry with fewer setup calls.",
retry_after=(exc.headers or {}).get("Retry-After")) from None
raise AmazonNotificationError(exc.code, reason[:500]) from None
except (OSError, ValueError) as exc:
raise AmazonError(f"Amazon Notifications unavailable: {type(exc).__name__}.") from None
return _retry(attempt, f"{base}/{path}", operation=operation, scope=scope)
def ensure_notifications(fields, aws_account_id, aws_region, *, granted_roles, timeout=_TIMEOUT):
"""Ensure only EventBridge subscriptions, returning their IDs and safe skip causes."""
account, aws_region = str(aws_account_id), str(aws_region)
if (not re.fullmatch(r"[0-9]{12}", account)
or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]+", aws_region)):
raise AmazonError("Notifications destination requires an AWS account and region.")
bridge = {"accountId": account, "region": aws_region}
region, sandbox = fields.get("region") or DEFAULT_REGION, is_sandbox(fields)
grantless = notifications_token(fields, timeout=timeout)
found = _request(_NOTIFICATION_DESTINATIONS_PATH, grantless, region=region,
sandbox=sandbox, timeout=timeout).get("payload") or []
destination = next((row for row in found
if all(((row.get("resource") or {}).get("eventBridge") or {}).get(key) == value
for key, value in bridge.items())), None)
if destination is None:
destination = _notifications_post("createDestination", grantless, {
"name": "Loopable", "resourceSpecification": {"eventBridge": bridge}},
region=region, sandbox=sandbox, timeout=timeout).get("payload") or {}
destination_id = destination.get("destinationId")
if not isinstance(destination_id, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", destination_id):
raise AmazonError("Amazon Notifications returned no valid destination ID.")
# Destination setup remains grantless even when the seller has granted no event roles.
seller_token, states = None, {}
for event_type, spec in NOTIFICATION_TYPES.items():
if "EventBridge" not in spec["destinations"]:
states[event_type] = {"state": "skipped", "reason":
"Amazon delivers this notification only to SQS. "
"Set up an Amazon Simple Queue Service (SQS) queue and subscribe this type to it."}
continue
if not set(spec["roles"]).intersection(granted_roles):
states[event_type] = {"state": "skipped", "reason":
"Amazon requires one of these granted roles for " + event_type + ": "
+ ", ".join(spec["roles"]) + ". This connection has not granted one."}
continue
if seller_token is None:
seller_token = access_token(fields, timeout=timeout)
try:
try:
subscription = _request(_NOTIFICATION_SUBSCRIPTIONS_PATH + "/" + event_type,
seller_token, region=region, sandbox=sandbox, timeout=timeout,
payloadVersion=spec["payload_version"]).get("payload") or {}
except AmazonError as exc:
# Only an absent subscription can be created. Auth and vendor failures stay visible.
if not isinstance(exc, AmazonNotificationError) or exc.status != 404:
raise
subscription = {}
if subscription and subscription.get("destinationId") != destination_id:
raise AmazonError("Amazon already sends this type to another destination. Review its existing subscription.")
if not subscription:
subscription = _notifications_post("createSubscription", seller_token, {
"payloadVersion": spec["payload_version"], "destinationId": destination_id},
notification_type=event_type, region=region, sandbox=sandbox,
timeout=timeout).get("payload") or {}
if not subscription.get("subscriptionId"):
raise AmazonError("Amazon Notifications returned no subscription ID.")
states[event_type] = {"state": "subscribed", "subscriptionId": subscription["subscriptionId"]}
except AmazonError as exc:
reason = str(exc)
for value in (grantless, seller_token, *(str(fields.get(key) or "")
for key in ("client_id", "client_secret", "refresh_token"))):
if value:
reason = reason.replace(value, "[redacted]")
states[event_type] = {"state": "skipped", "reason":
reason.replace("\u2014", ". ").replace("\u2013", " to ")}
return {"destinationId": destination_id, "subscriptions": states}
def _request(path, token, region=DEFAULT_REGION, method="GET", timeout=_TIMEOUT,
sandbox=False, throttle_fix=None, **params):
"""One read-only SP-API call. Returns the decoded JSON body.
⛔ NON-GET IS REFUSED HERE, BEFORE THE REQUEST IS BUILT. There is no flag, no keyword and no
caller that can turn this off, which is the point: the guard sits below every route, payload
and UI, so nothing above it has to be trusted to stay read-only.
"""
if str(method).upper() != "GET":
raise AmazonError("this connector is read-only: only GET is permitted")
require_operation(method, path)
operation = operation_for(method, path)["name"]
scope = _scope_for(token, region, sandbox)
def attempt():
"""One raw read-only SP-API attempt, with no retry or pacing policy."""
# ⚠ AN EXPLICIT FLAG, NOT A `fields` DICT. This function is handed a TOKEN, never the
# credential -- deliberately, so a secret cannot reach the request builder at all -- so the
# sandbox decision is made by the caller that does hold the credential and passed in as one
# boolean. A first draft reached for `fields` here, which does not exist in this scope.
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
clean = {k: v for k, v in (params or {}).items() if v not in (None, "")}
url = f"{base}/{str(path).lstrip('/')}"
if clean:
url += "?" + urllib.parse.urlencode(clean, doseq=True)
req = urllib.request.Request(url, method="GET")
req.add_header("x-amz-access-token", token)
req.add_header("Accept", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
_observe_rate(operation, scope, getattr(r, "headers", None))
if (operation in FEEDBACK_INTERVALS
and getattr(r, "status", None) == 204):
return None
return json.loads(r.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as e:
_observe_rate(operation, scope, e.headers)
detail = ""
try:
payload = json.loads((e.read() or b"").decode("utf-8") or "{}")
errs = payload.get("errors") or []
if errs:
detail = str((errs[0] or {}).get("message") or "")[:200]
except Exception: # noqa: BLE001
detail = ""
# 429 is the rate limiter, and standing rule 1 wants it NAMED rather than swallowed.
if e.code == 429:
fix = throttle_fix or "use the Reports API bulk path instead of a slower page loop"
raise AmazonThrottled(
f"{_safe(url)} was throttled (429). SP-API is token-bucket limited per operation; "
f"the fix is to {fix}",
retry_after=(e.headers or {}).get("Retry-After")) from None
if path.startswith("notifications/v1/"):
reason = (detail or "Amazon refused this notification operation.").replace(token, "[redacted]")
raise AmazonNotificationError(e.code, reason.replace("\u2014", ". ").replace("\u2013", " to ")) from None
refusal = AmazonError(f"{_safe(url)} answered {e.code}" + (f": {detail}" if detail else ""))
# Callers branch on the status attribute, never on the message text.
refusal.status, refusal.vendor_message = e.code, detail
raise refusal from None
except Exception as e: # noqa: BLE001
raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower(), "")
return _retry(
attempt, f"{base}/{str(path).lstrip('/')}",
operation=operation, scope=scope,
exhausted_fix=(throttle_fix
or "use the Reports API bulk path instead of a slower page loop"))
# Amazon models: models/{fulfillment-inbound-api-model,feeds-api-model} in
# https://github.com/amzn/selling-partner-api-models
SP_NAMED_WRITES = {
"inbound_plan": ("createInboundPlan", "POST", "inbound/fba/2024-03-20/inboundPlans"),
"inbound_plan_cancel": ("cancelInboundPlan", "PUT",
"inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/cancellation"),
"removal_order": ("createFeed", "POST", "feeds/2021-06-30/feeds"),
}
APPROVAL_SOURCES = {
"inbound_plan": {"modules.restock_planner": "modules.amazon_operator:app_approval"},
"inbound_plan_cancel": {"modules.restock_planner": "modules.amazon_operator:app_approval"},
"removal_order": {
"modules.returns_refunds": "modules.returns_refunds:removal_approval",
"modules.aged_stock": "modules.aged_stock:removal_approval",
},
}
# Readers return {tenant_key, decision, approved_by, item_ids, writes: [{kind, payload}]}.
# A cancellation reader also returns original_plan, the saved successful create receipt.
# Producers persist the receipt before allowing another send for that approval.
REMOVAL_FEED_TYPE = "POST_FLAT_FILE_FBA_CREATE_REMOVAL"
_REMOVAL_CONTENT_TYPE = "text/tab-separated-values; charset=UTF-8"
class AmazonWriteRefused(AmazonError):
"""A named write failed local validation before credentials or transport access."""
def _sp_text(value, maximum=1024):
return (isinstance(value, str) and 0 < len(value) <= maximum and bool(value.strip())
and not any(ord(c) < 32 for c in value))
def _sp_item_ids(value):
return (isinstance(value, list) and bool(value) and all(_sp_text(v) for v in value)
and len(set(value)) == len(value))
def _removal_rows(content):
"""Parse every metadata and SKU row of Amazon's tab-separated removal template."""
# https://developer-docs.amazon.com/sp-api/docs/fulfillment-by-amazon-feed-type-values
if not isinstance(content, str) or not content or "\x00" in content:
raise AmazonWriteRefused("removal content must be a UTF-8 tab-separated file")
metadata, items, in_items = {}, [], False
allowed = {"MerchantRemovalOrderID", "RemovalDisposition", "AddressName", "AddressFieldOne",
"AddressFieldTwo", "AddressFieldThree", "AddressCity", "AddressCountryCode",
"AddressStateOrRegion", "AddressPostalCode", "ContactPhoneNumber",
"ShippingNotes", "RemoveFromCountryCode"}
try:
for row in csv.reader(io.StringIO(content), delimiter="\t", strict=True):
if not row or not any(row):
continue
if any(any(ord(c) < 32 for c in cell) for cell in row):
raise AmazonWriteRefused("removal cells must not contain embedded control characters")
if row == ["MerchantSKU", "SellableQuantity", "UnsellableQuantity"] and not in_items:
in_items = True
continue
if not in_items:
if (len(row) not in (2, 3) or row[0] not in allowed or row[0] in metadata
or (len(row) == 3 and row[2])):
raise AmazonWriteRefused("removal metadata is unknown, duplicate or malformed")
metadata[row[0]] = row[1]
continue
if (len(row) != 3 or not _sp_text(row[0], 255)
or any(not re.fullmatch(r"[0-9]+", v or "") for v in row[1:])
or sum(int(v) for v in row[1:]) <= 0):
raise AmazonWriteRefused("every removal SKU row needs two quantities and positive total units")
disposition = {"Return": "Return", "RETURN": "Return", "Disposal": "Disposal",
"DISPOSAL": "Disposal"}.get(metadata.get("RemovalDisposition"))
if disposition is None:
raise AmazonWriteRefused("every removal row must be Return or Disposal")
items.append({"msku": row[0], "sellable": int(row[1]), "unsellable": int(row[2]),
"disposition": disposition})
except (csv.Error, ValueError):
raise AmazonWriteRefused("removal file is malformed") from None
if (not items or len({r["msku"] for r in items}) != len(items)
or not _sp_text(metadata.get("MerchantRemovalOrderID"), 40)
or metadata.get("RemovalDisposition") not in ("Return", "RETURN", "Disposal", "DISPOSAL")):
raise AmazonWriteRefused("removal file needs one order, unique SKUs and Return or Disposal")
if metadata["RemovalDisposition"] in ("Return", "RETURN") and any(not _sp_text(metadata.get(k)) for k in (
"AddressName", "AddressFieldOne", "AddressCity", "AddressCountryCode", "AddressPostalCode")):
raise AmazonWriteRefused("a return removal needs its approved ship-to address")
return items
def _prepare_sp_named_write(kind, payload):
"""Validate the complete payload and resolve only a C3 operation."""
rule = SP_NAMED_WRITES.get(kind)
if not rule or not isinstance(payload, dict) or payload.get("operation") != rule[0]:
raise AmazonWriteRefused("the operation is not a named SP-API write")
if not _sp_item_ids(payload.get("item_ids")):
raise AmazonWriteRefused("a named write needs its exact approved item ids")
common = {"operation", "item_ids"}
operation, method, path = rule
if kind == "inbound_plan":
if set(payload) != common | {"body"}:
raise AmazonWriteRefused("inbound plan payload has unknown fields")
body = payload["body"]
if (not isinstance(body, dict)
or set(body) - {"destinationMarketplaces", "items", "sourceAddress", "name"}
or not isinstance(body.get("destinationMarketplaces"), list)
or len(body["destinationMarketplaces"]) != 1
or not _sp_text(body["destinationMarketplaces"][0], 20)
or not isinstance(body.get("items"), list) or not 1 <= len(body["items"]) <= 2000):
raise AmazonWriteRefused("inbound plan needs one marketplace and 1 to 2000 items. Split larger batches explicitly")
if "name" in body and not _sp_text(body["name"], 40):
raise AmazonWriteRefused("inbound plan name is invalid")
seen = set()
for item in body["items"]:
if (not isinstance(item, dict)
or set(item) - {"msku", "quantity", "labelOwner", "prepOwner", "expiration", "manufacturingLotCode"}
or not _sp_text(item.get("msku"), 255) or item["msku"] in seen
or type(item.get("quantity")) is not int or not 1 <= item["quantity"] <= 500000
or item.get("labelOwner") not in ("SELLER", "AMAZON", "NONE")
or item.get("prepOwner") not in ("SELLER", "AMAZON", "NONE")):
raise AmazonWriteRefused("inbound plan item has invalid SKU, quantity, label owner or prep owner")
seen.add(item["msku"])
if body["destinationMarketplaces"] == [US_MARKETPLACE_ID] and item["labelOwner"] == "AMAZON":
raise AmazonWriteRefused("Amazon labeling is unavailable in the US marketplace")
if "expiration" in item:
try:
if date.fromisoformat(item["expiration"]).isoformat() != item["expiration"]:
raise ValueError
except (TypeError, ValueError):
raise AmazonWriteRefused("inbound item expiration must be YYYY-MM-DD") from None
if "manufacturingLotCode" in item and not _sp_text(item["manufacturingLotCode"], 256):
raise AmazonWriteRefused("inbound item lot code is invalid")
address = body.get("sourceAddress")
sizes = {"addressLine1": 180, "addressLine2": 60, "city": 30, "companyName": 50,
"countryCode": 2, "districtOrCounty": 50, "email": 1024, "name": 50,
"phoneNumber": 20, "postalCode": 32, "stateOrProvinceCode": 64}
if (not isinstance(address, dict) or set(address) - sizes.keys()
or not {"addressLine1", "city", "countryCode", "name", "phoneNumber", "postalCode"} <= address.keys()
or any(not _sp_text(v, sizes[k]) for k, v in address.items())
or not re.fullmatch(r"[A-Z]{2}", address["countryCode"])):
raise AmazonWriteRefused("inbound plan needs a valid sourceAddress")
elif kind == "inbound_plan_cancel":
if (set(payload) != common | {"inboundPlanId", "original_approval_id"}
or not isinstance(payload.get("inboundPlanId"), str)
or not re.fullmatch(r"[a-zA-Z0-9-]{38}", payload["inboundPlanId"])
or not _sp_text(payload.get("original_approval_id"))):
raise AmazonWriteRefused("cancel needs the original plan id and original approval id")
path = path.format(inboundPlanId=payload["inboundPlanId"])
body = None
else:
if (set(payload) - (common | {"feedType", "marketplaceIds", "content", "validate_only"})
or payload.get("feedType") != REMOVAL_FEED_TYPE
or not isinstance(payload.get("marketplaceIds"), list)
or not 1 <= len(payload["marketplaceIds"]) <= 25
or any(not _sp_text(v, 20) for v in payload["marketplaceIds"])
or type(payload.get("validate_only", False)) is not bool):
raise AmazonWriteRefused("only POST_FLAT_FILE_FBA_CREATE_REMOVAL is admitted")
_removal_rows(payload.get("content"))
body = {"feedType": payload["feedType"], "marketplaceIds": payload["marketplaceIds"]}
return operation, method, path, body
def _sp_named_approval(tenant_key, approval_id, kind, payload, source):
"""Require an exact batch write and a trusted original sent plan for cancellation."""
module, _, name = source.partition(":")
try:
record = getattr(importlib.import_module(module), name)(tenant_key, approval_id)
except Exception:
raise AmazonWriteRefused("the approval could not be read") from None
if (not isinstance(record, dict) or record.get("tenant_key") != tenant_key
or record.get("decision") != "approved" or not _sp_text(record.get("approved_by"))
or not _sp_item_ids(record.get("item_ids"))
or sorted(record["item_ids"]) != sorted(payload["item_ids"])
or not isinstance(record.get("writes"), list)
or {"kind": kind, "payload": payload} not in record["writes"]):
raise AmazonWriteRefused("the approval does not bind this tenant, batch and exact payload")
if kind == "inbound_plan_cancel":
original = record.get("original_plan")
if (not isinstance(original, dict) or original.get("sent") is not True
or original.get("kind") != "inbound_plan"
or original.get("inboundPlanId") != payload["inboundPlanId"]
or original.get("approval_id") != payload["original_approval_id"]
or original.get("tenant_key") != tenant_key
or not _sp_item_ids(original.get("item_ids"))
or sorted(original["item_ids"]) != sorted(payload["item_ids"])):
raise AmazonWriteRefused("cancel approval does not name its original sent plan")
return record
def _sp_write_fields(tenant_key):
"""Resolve credentials only from the matching tenant runtime and keychain."""
from harness.runtime import get_runtime
from core.keychain import amazon_creds
rt = get_runtime(tenant_key)
if getattr(rt, "key", None) != tenant_key:
raise AmazonWriteRefused("named write runtime does not match its tenant")
fields = amazon_creds(rt)
if not isinstance(fields, dict) or not all(fields.get(k) for k in (
"client_id", "client_secret", "refresh_token", "marketplace_id", "seller_id")):
raise AmazonWriteRefused("the tenant has no complete SP-API credential")
return fields
def send_named_write(tenant_key, kind, payload, *, approval_id):
"""Send one exact approved C3 batch, or validate a removal locally without I/O."""
caller = sys._getframe(1).f_globals.get("__name__", "")
source = APPROVAL_SOURCES.get(kind, {}).get(caller)
if not source:
raise AmazonWriteRefused("this caller may not send the named SP-API write")
key = str(tenant_key or "").strip().lower()
if not key or not _sp_text(approval_id):
raise AmazonWriteRefused("a named write needs its tenant and approval id")
try:
payload = json.loads(json.dumps(payload, allow_nan=False))
except (TypeError, ValueError):
raise AmazonWriteRefused("the approved payload must be JSON data") from None
operation, method, path, body = _prepare_sp_named_write(kind, payload)
receipt = {"sent": False, "kind": kind, "operation": operation, "method": method, "path": path,
"tenant_key": key, "approval_id": approval_id, "item_ids": payload["item_ids"]}
if kind == "removal_order" and payload.get("validate_only") is True:
return {**receipt, "validated": True, "approval_checked": False,
"rows": len(_removal_rows(payload["content"]))}
approved = _sp_named_approval(key, approval_id, kind, payload, source)
receipt["approved_by"] = approved["approved_by"]
fields = _sp_write_fields(key)
marketplaces = (body.get("destinationMarketplaces") if kind == "inbound_plan"
else payload.get("marketplaceIds"))
if marketplaces and any(m != fields["marketplace_id"] for m in marketplaces):
raise AmazonWriteRefused("the approved marketplace does not match the tenant credential")
base = base_for(fields)
with rate_limit_scope(key):
token = access_token(fields)
scope = _scope_for(token, fields.get("region", DEFAULT_REGION), is_sandbox(fields))
logger = logging.getLogger(__name__)
def call(op, verb, target, data, interval):
_pace_operation(op, scope, interval, sleep=time.sleep, now=time.monotonic)
logger.info("amazon_named_write tenant=%s kind=%s operation=%s approval_id=%s approved_by=%s item_ids=%s",
key, kind, op, approval_id, receipt["approved_by"], payload["item_ids"])
req = urllib.request.Request(base + "/" + target, data=data, method=verb,
headers={"x-amz-access-token": token, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=_TIMEOUT) as response:
_observe_rate(op, scope, getattr(response, "headers", None))
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as error:
_observe_rate(op, scope, error.headers)
if error.code == 400:
try:
errors = json.loads(error.read().decode("utf-8")).get("errors", [])
reason = json.dumps(errors, ensure_ascii=True)
for secret in (token, fields.get("client_secret"), fields.get("refresh_token")):
if secret:
reason = reason.replace(secret, "[redacted]")
except Exception:
reason = "Amazon rejected this payload"
raise AmazonReportError(op + " rejected the approved payload", reason, 400) from None
# A write is never replayed after an ambiguous response.
raise AmazonError(f"{op} answered {error.code}. Reconcile this approval before retrying") from None
except Exception:
raise AmazonError(f"{op} outcome is unknown. Reconcile this approval before retrying") from None
if kind == "removal_order":
document = call("createFeedDocument", "POST", "feeds/2021-06-30/documents",
json.dumps({"contentType": _REMOVAL_CONTENT_TYPE}).encode(), 2.0)
url, document_id = document.get("url"), document.get("feedDocumentId")
parsed = urllib.parse.urlsplit(str(url or ""))
if (parsed.scheme != "https" or not (parsed.hostname or "").endswith(".amazonaws.com")
or parsed.username or parsed.password or parsed.port not in (None, 443)
or parsed.fragment or not _sp_text(document_id)):
raise AmazonWriteRefused("Amazon returned an invalid removal upload document")
def upload():
logger.info("amazon_named_write tenant=%s kind=%s operation=%s approval_id=%s approved_by=%s item_ids=%s",
key, kind, "uploadFeedDocument", approval_id, receipt["approved_by"], payload["item_ids"])
req = urllib.request.Request(url, data=payload["content"].encode("utf-8"), method="PUT",
headers={"Content-Type": _REMOVAL_CONTENT_TYPE})
try:
with urllib.request.urlopen(req, timeout=_TIMEOUT):
pass
except Exception:
raise AmazonError("removal document upload failed. No feed was created") from None
upload()
body["inputFeedDocumentId"] = document_id
response = call(operation, method, path, None if body is None else json.dumps(body).encode(),
1 / 0.0083 if kind == "removal_order" else 0.5)
result = {**receipt, "sent": True, "approval_checked": True, "response": response}
if kind == "inbound_plan" and isinstance(response, dict):
result["inboundPlanId"] = response.get("inboundPlanId")
return result
#: ⛔ THE SECOND NON-GET SP-API PATH. `getCompetitiveSummary` is an Amazon-defined POST wrapper,
#: but every item in its body is a GET to `_COMPETITIVE_SUMMARY_ITEM_URI`. The path, item method,
#: item URI, included data and 20-item maximum are all fixed below; no caller can turn this into a
#: write-shaped Product Pricing request.
def _competitive_summary_batch(token, asins, marketplace_id, region=DEFAULT_REGION,
timeout=_TIMEOUT, sandbox=False):
"""Read one fixed `getCompetitiveSummary` batch. -> its response list."""
require_operation("POST", _COMPETITIVE_SUMMARY_BATCH_PATH)
operation, scope = "getCompetitiveSummary", _scope_for(token, region, sandbox)
items = [str(asin or "").strip() for asin in (asins or ()) if str(asin or "").strip()]
if not 1 <= len(items) <= COMPETITIVE_SUMMARY_BATCH_SIZE:
raise AmazonError(
f"competitive summary needs 1 to {COMPETITIVE_SUMMARY_BATCH_SIZE} ASINs per batch")
marketplace = str(marketplace_id or "").strip()
if not marketplace:
raise AmazonError("competitive summary needs a marketplace_id")
body = {"requests": [{
"asin": asin,
"marketplaceId": marketplace,
"includedData": list(_COMPETITIVE_SUMMARY_INCLUDED),
"method": "GET",
"uri": _COMPETITIVE_SUMMARY_ITEM_URI,
} for asin in items]}
def attempt():
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
url = f"{base}/{_COMPETITIVE_SUMMARY_BATCH_PATH}"
req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
_observe_rate(operation, scope, getattr(r, "headers", None))
got = json.loads(r.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as e:
_observe_rate(operation, scope, e.headers)
detail = ""
try:
errs = (json.loads((e.read() or b"").decode("utf-8") or "{}").get("errors") or [])
detail = str((errs[0] or {}).get("message") or "")[:200] if errs else ""
except Exception: # noqa: BLE001
detail = ""
if e.code == 429:
raise AmazonThrottled(
f"{_safe(url)} was throttled (429). getCompetitiveSummary defaults to "
"0.033 requests/second with a burst of 1; keep 20 ASINs per batch",
retry_after=(e.headers or {}).get("Retry-After")) from None
if e.code == 403:
raise AmazonError(
f"{_safe(url)} refused getCompetitiveSummary (403). The application needs "
"the Pricing role") from None
raise AmazonError(f"{_safe(url)} answered {e.code}"
+ (f": {detail}" if detail else "")) from None
except Exception as e: # noqa: BLE001
raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
responses = got.get("responses")
if not isinstance(responses, list):
raise AmazonError("getCompetitiveSummary returned no response list")
return responses
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower(), "")
return _retry(
attempt, f"{base}/{_COMPETITIVE_SUMMARY_BATCH_PATH}",
operation=operation, scope=scope,
exhausted_fix="retain 20 ASINs per batch and lower the batch request rate")
def competitive_summaries(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep,
now=time.monotonic):
"""Read competitive summaries for every distinct ASIN, in complete fixed-size batches."""
unique = []
seen = set()
for raw in asins or ():
asin = str(raw or "").strip()
if asin and asin not in seen:
unique.append(asin)
seen.add(asin)
if not unique:
return []
f = fields or {}
region = str(f.get("region") or DEFAULT_REGION)
marketplace = str(f.get("marketplace_id") or US_MARKETPLACE_ID)
sandbox = is_sandbox(f)
token = access_token(f, timeout=timeout)
token_issued = now()
out = []
for offset in range(0, len(unique), COMPETITIVE_SUMMARY_BATCH_SIZE):
_pace_entity("competitive_summary", COMPETITIVE_SUMMARY_INTERVAL,
sleep=sleep, now=now)
if now() - token_issued >= 3000:
token = access_token(f, timeout=timeout)
token_issued = now()
batch = unique[offset:offset + COMPETITIVE_SUMMARY_BATCH_SIZE]
responses = _competitive_summary_batch(
token, batch, marketplace, region=region, timeout=timeout, sandbox=sandbox)
returned = [str(((r or {}).get("body") or {}).get("asin") or "") for r in responses]
if len(responses) != len(batch) or sorted(returned) != sorted(batch):
raise AmazonError(
"getCompetitiveSummary returned an incomplete or mismatched ASIN batch; refusing "
"to treat a partial response as complete")
out.extend(responses)
return out
_ITEM_OFFERS_BATCH_PATH = "batches/products/pricing/v0/itemOffers"
_ITEM_OFFERS_INNER_METHOD = "GET"
ITEM_OFFERS_BATCH_SIZE = 20
ITEM_OFFERS_INTERVAL = 10.0
def _item_offers_batch(token, asins, marketplace_id, region=DEFAULT_REGION, timeout=_TIMEOUT,
sandbox=False, *, sleep=time.sleep, now=time.monotonic):
"""Read one fixed Product Pricing v0 batch whose inner requests are all GETs."""
require_operation("POST", _ITEM_OFFERS_BATCH_PATH)
# Another approved POST path would carry these inner requests to a different operation.
if _ITEM_OFFERS_BATCH_PATH != OPERATIONS["getItemOffersBatch"]["path"]:
raise AmazonOperationRefused(f"POST {_safe(_ITEM_OFFERS_BATCH_PATH)} is not getItemOffersBatch")
# Amazon's productPricingV0.json fixes this POST wrapper, GET items and 20-item maximum.
items = list(asins)
if (not 1 <= len(items) <= ITEM_OFFERS_BATCH_SIZE
or any(not isinstance(v, str) or not re.fullmatch(r"[A-Z0-9]{10}", v) for v in items)
or len(set(items)) != len(items) or not _sp_text(marketplace_id, 20)):
raise AmazonError("getItemOffersBatch needs 1 to 20 unique ASINs and a marketplace")
body = {"requests": [{"uri": f"/products/pricing/v0/items/{asin}/offers",
"method": _ITEM_OFFERS_INNER_METHOD,
"MarketplaceId": marketplace_id, "ItemCondition": "New",
"CustomerType": "Consumer"} for asin in items]}
# The POST wrapper stays read-only only while every inner request is a GET.
if any(r["method"] != "GET" for r in body["requests"]):
raise AmazonOperationRefused("getItemOffersBatch inner requests must be GET")
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError("unknown region for getItemOffersBatch")
operation, scope = "getItemOffersBatch", _scope_for(token, region, sandbox)
def attempt():
req = urllib.request.Request(base + "/" + _ITEM_OFFERS_BATCH_PATH,
data=json.dumps(body).encode(), method="POST",
headers={"x-amz-access-token": token, "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
_observe_rate(operation, scope, getattr(response, "headers", None))
result = json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as error:
_observe_rate(operation, scope, error.headers)
if error.code == 429:
raise AmazonThrottled("getItemOffersBatch throttled (429)",
retry_after=(error.headers or {}).get("Retry-After"),
operation=operation) from None
raise AmazonError(f"getItemOffersBatch answered {error.code}") from None
except Exception:
raise AmazonError("getItemOffersBatch unreachable") from None
responses = result.get("responses") if isinstance(result, dict) else None
if (not isinstance(responses, list) or len(responses) != len(items)
or any(not isinstance(r, dict) or not isinstance(r.get("body"), dict)
or not isinstance(r.get("status"), dict)
or str(r["status"].get("statusCode")) != "200"
or r["body"].get("errors") for r in responses)):
raise AmazonError("getItemOffersBatch returned failed or incomplete items. No partial snapshot was stored")
returned = [((r["body"].get("payload") or {}).get("ASIN")) for r in responses]
if sorted(str(v) for v in returned) != sorted(items):
raise AmazonError("getItemOffersBatch returned mismatched ASINs. No partial snapshot was stored")
return responses
return _retry(attempt, base + "/" + _ITEM_OFFERS_BATCH_PATH, operation=operation, scope=scope,
sleep=sleep, now=now, exhausted_fix="resume all offer batches at the operation's advertised rate")
def item_offers(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
"""Read every distinct own ASIN in complete batches, without a row cap."""
unique = list(dict.fromkeys(asins))
if any(not isinstance(v, str) or not re.fullmatch(r"[A-Z0-9]{10}", v) for v in unique):
raise AmazonError("item offers needs ASINs of ten uppercase letters or digits")
if not unique:
return []
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
if not _sp_text(marketplace, 20):
raise AmazonError("item offers needs a marketplace")
token, issued = access_token(fields, timeout=timeout), now()
out = []
for offset in range(0, len(unique), ITEM_OFFERS_BATCH_SIZE):
# Own bucket, as competitive_summaries draws competitive_summary; _retry then skips its pace.
_pace_entity("getItemOffersBatch", ITEM_OFFERS_INTERVAL, sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
out.extend(_item_offers_batch(token, unique[offset:offset + ITEM_OFFERS_BATCH_SIZE], marketplace,
region=fields.get("region", DEFAULT_REGION), timeout=timeout,
sandbox=is_sandbox(fields), sleep=sleep, now=now))
return out
def list_prep_details(fields, mskus, *, timeout=_TIMEOUT):
"""Read prep constraints for every MSKU through Amazon's verified GET operation."""
items = list(dict.fromkeys(mskus))
if not items or any(not _sp_text(v, 255) for v in items):
raise AmazonError("listPrepDetails needs nonblank MSKUs")
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
if not _sp_text(marketplace, 20):
raise AmazonError("listPrepDetails needs a marketplace")
token, issued = access_token(fields, timeout=timeout), time.monotonic()
out = []
for offset in range(0, len(items), 100):
if time.monotonic() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), time.monotonic()
# Amazon requires these three characters to be double percent encoded.
batch = [v.replace("%", "%25").replace("+", "%2B").replace(",", "%2C")
for v in items[offset:offset + 100]]
out.append(_request("inbound/fba/2024-03-20/items/prepDetails", token,
region=fields.get("region", DEFAULT_REGION), sandbox=is_sandbox(fields),
timeout=timeout, marketplaceId=marketplace, mskus=batch))
return out
def get_inbound_operation_status(fields, operation_id, *, timeout=_TIMEOUT):
"""Read one asynchronous inbound result through Amazon's verified GET operation."""
if not isinstance(operation_id, str) or not re.fullmatch(r"[a-zA-Z0-9-]{36,38}", operation_id):
raise AmazonError("getInboundOperationStatus needs a valid operation id")
return _request(f"inbound/fba/2024-03-20/operations/{operation_id}",
access_token(fields, timeout=timeout), timeout=timeout,
region=fields.get("region", DEFAULT_REGION), sandbox=is_sandbox(fields))
FEE_ESTIMATES_BATCH_SIZE = 20
_FEE_ESTIMATES_PATH = "products/fees/v0/feesEstimate"
_fee_estimates_interval = 2.0
def fee_estimate_request(estimate, marketplace_id):
"""Fix the seller SKU or ASIN, fulfillment and complete price basis before deriving a stable request identity."""
sku, asin = estimate.get("sku"), estimate.get("asin")
# Product Fees v0 takes SellerSKU or ASIN. It answers "SKU is not a supported IdType" to SKU.
if sku is None and isinstance(asin, str) and asin.strip():
id_type, id_value, label = "ASIN", asin, f"ASIN {asin}"
elif isinstance(sku, str) and sku.strip():
id_type, id_value, label = "SellerSKU", sku, f"SKU {sku}"
else:
raise AmazonError("Fee estimates need a nonempty SKU or ASIN for every requested price")
fulfilled = estimate.get("is_amazon_fulfilled")
if type(fulfilled) is not bool:
raise AmazonError(f"Fee estimates need the fulfillment method for {label}")
def money(value):
if not isinstance(value, dict) or not re.fullmatch(r"[A-Z]{3}", str(value.get("CurrencyCode") or "")):
raise AmazonError(f"Fee estimates need a price currency for {label}")
try:
amount = float(value["Amount"])
except (KeyError, TypeError, ValueError):
raise AmazonError(f"Fee estimates need a numeric price for {label}") from None
if isinstance(value["Amount"], bool) or not math.isfinite(amount) or amount < 0:
raise AmazonError(f"Fee estimates need a finite nonnegative price for {label}")
return {"CurrencyCode": value["CurrencyCode"], "Amount": amount}
basis = {"ListingPrice": money(estimate.get("price"))}
if "shipping" in estimate:
basis["Shipping"] = money(estimate["shipping"])
if basis["Shipping"]["CurrencyCode"] != basis["ListingPrice"]["CurrencyCode"]:
raise AmazonError(f"Fee estimate shipping and price currencies differ for {label}")
if "points" in estimate:
points = estimate["points"]
if not isinstance(points, dict) or type(points.get("PointsNumber")) is not int or points["PointsNumber"] < 0:
raise AmazonError(f"Fee estimates need a valid points basis for {label}")
basis["Points"] = {"PointsNumber": points["PointsNumber"]}
if "PointsMonetaryValue" in points:
basis["Points"]["PointsMonetaryValue"] = money(points["PointsMonetaryValue"])
request = {"MarketplaceId": marketplace_id, "IsAmazonFulfilled": fulfilled,
"PriceToEstimateFees": basis}
if estimate.get("optional_fulfillment_program"):
request["OptionalFulfillmentProgram"] = estimate["optional_fulfillment_program"]
identity = {"IdType": id_type, "IdValue": id_value, "FeesEstimateRequest": request}
request["Identifier"] = hashlib.sha256(json.dumps(
identity, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
return identity
def _fee_estimates_batch(token, requests, region=DEFAULT_REGION, timeout=_TIMEOUT, sandbox=False,
*, sleep=time.sleep, now=time.monotonic):
"""Send only fixed, read-only fee estimate requests at Amazon's operation pace."""
require_operation("POST", _FEE_ESTIMATES_PATH)
operation, scope = "getMyFeesEstimates", _scope_for(token, region, sandbox)
if not 1 <= len(requests) <= FEE_ESTIMATES_BATCH_SIZE:
raise AmazonError("getMyFeesEstimates needs 1 to 20 estimates per batch")
# Rebuild each body to refuse caller-supplied methods, paths or unrelated fee operations.
body = []
for item in requests:
request = item["FeesEstimateRequest"]
price = request["PriceToEstimateFees"]
id_key = "asin" if item.get("IdType") == "ASIN" else "sku"
estimate = {id_key: item["IdValue"], "price": price["ListingPrice"],
"is_amazon_fulfilled": request["IsAmazonFulfilled"]}
for source, target in (("Shipping", "shipping"), ("Points", "points")):
if source in price:
estimate[target] = price[source]
if "OptionalFulfillmentProgram" in request:
estimate["optional_fulfillment_program"] = request["OptionalFulfillmentProgram"]
canonical = fee_estimate_request(estimate, request["MarketplaceId"])
if item != canonical:
raise AmazonOperationRefused("noncanonical fee estimate request")
body.append(canonical)
def observe_rate(headers):
_observe_rate(operation, scope, headers)
def attempt():
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
req = urllib.request.Request(f"{base}/{_FEE_ESTIMATES_PATH}",
data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
observe_rate(getattr(response, "headers", None))
got = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
observe_rate(exc.headers)
try:
errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
reason = "; ".join(str(e.get("message") or e.get("code") or "Amazon gave no reason") for e in errors)
except (ValueError, AttributeError, TypeError):
reason = "Amazon gave no reason"
if exc.code == 429:
raise AmazonThrottled(
"getMyFeesEstimates throttled (429). Keep batches of 20 at 0.5 requests per second with a burst of one.",
retry_after=(exc.headers or {}).get("Retry-After")) from None
raise AmazonReportError(f"getMyFeesEstimates refused ({exc.code}). Amazon reason",
reason or "Amazon gave no reason", exc.code) from None
except (OSError, ValueError) as exc:
raise AmazonError(f"getMyFeesEstimates could not read Amazon's response: {type(exc).__name__}") from None
if not isinstance(got, list) or any(not isinstance(row, dict) for row in got):
raise AmazonError("getMyFeesEstimates returned no valid estimate list")
return got
with _pacing_scope(scope):
_pace_entity("getMyFeesEstimates", _fee_estimates_interval, sleep=sleep, now=now)
return _retry(attempt, _FEE_ESTIMATES_PATH, sleep=sleep, now=now, operation=operation, scope=scope,
exhausted_fix="keep batches of 20 and reduce the fee estimate request rate")
def fee_estimates(fields, estimates, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
"""Batch every requested SKU and price, refusing incomplete or mismatched estimate responses."""
marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
requests = [fee_estimate_request(estimate, marketplace) for estimate in estimates]
identifiers = [item["FeesEstimateRequest"]["Identifier"] for item in requests]
if len(set(identifiers)) != len(identifiers):
raise AmazonError("Fee estimates contain duplicate SKU and price bases; request each basis once")
if not requests:
return []
token, issued = access_token(fields, timeout=timeout), now()
records = []
for offset in range(0, len(requests), FEE_ESTIMATES_BATCH_SIZE):
if now() - issued >= 3000:
token, issued = access_token(fields, timeout=timeout), now()
batch = requests[offset:offset + FEE_ESTIMATES_BATCH_SIZE]
returned = _fee_estimates_batch(token, batch, region=fields.get("region") or DEFAULT_REGION,
timeout=timeout, sandbox=is_sandbox(fields), sleep=sleep, now=now)
expected = {item["FeesEstimateRequest"]["Identifier"]: item for item in batch}
seen = set()
for record in returned:
if record.get("Status") != "Success":
error = record.get("Error") or {}
raise AmazonReportError("getMyFeesEstimates refused an estimate. Amazon reason",
str(error.get("Message") or error.get("Code") or record.get("Status")),
error.get("Code") or record.get("Status"))
echo = record.get("FeesEstimateIdentifier") or {}
identifier = echo.get("SellerInputIdentifier")
if identifier not in expected or identifier in seen:
raise AmazonError("getMyFeesEstimates returned a duplicate or unrequested estimate identity")
seen.add(identifier)
sent = expected[identifier]
request = sent["FeesEstimateRequest"]
if (echo.get("IdType") != sent["IdType"] or echo.get("IdValue") != sent["IdValue"]
or any(echo.get(key) != request.get(key) for key in
("MarketplaceId", "IsAmazonFulfilled", "PriceToEstimateFees", "OptionalFulfillmentProgram"))):
raise AmazonError("getMyFeesEstimates returned a different IdType, SKU, ASIN or price basis; no partial snapshot was stored")
estimate = record.get("FeesEstimate") or {}
if (not isinstance(estimate.get("FeeDetailList"), list)
or any(not isinstance(line, dict) for line in estimate["FeeDetailList"])
or not isinstance(estimate.get("TotalFeesEstimate"), dict)):
raise AmazonError("getMyFeesEstimates omitted its fee lines or total; no partial snapshot was stored")
if seen != set(expected):
raise AmazonError("getMyFeesEstimates returned an incomplete estimate batch; no partial snapshot was stored")
records.extend(returned)
return records
def awd_inventory(fields, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
"""Read every AWD inventory page, including through empty pages. -> inventory summaries."""
f = fields or {}
region = str(f.get("region") or DEFAULT_REGION)
sandbox = is_sandbox(f)
token = access_token(f, timeout=timeout)
token_issued = now()
next_token = None
seen_tokens = set()
rows = []
while True:
_pace_entity("awd_inventory", AWD_INVENTORY_INTERVAL, sleep=sleep, now=now)
if now() - token_issued >= 3000:
token = access_token(f, timeout=timeout)
token_issued = now()
try:
got = _request(
_AWD_INVENTORY_PATH, token, region=region, timeout=timeout, sandbox=sandbox,
throttle_fix="resume the same listInventory pagination later without dropping pages",
details="SHOW", maxResults=AWD_INVENTORY_PAGE_SIZE, nextToken=next_token)
except AmazonError as e:
if "answered 403" in str(e):
raise AmazonError(
f"{_AWD_INVENTORY_PATH} was refused (403). The application needs the Amazon "
"Warehousing and Distribution role") from None
raise
page = got.get("inventory")
if not isinstance(page, list):
raise AmazonError("listInventory returned no inventory list")
rows.extend(page)
following = str(got.get("nextToken") or "").strip()
if not following:
break
if following in seen_tokens:
raise AmazonError(
"listInventory repeated a nextToken; refusing an infinite or duplicate page loop")
seen_tokens.add(following)
next_token = following
return rows
#: ⛔⛔ THE REPORT-JOB NON-GET PATH, AND IT IS A CONSTANT RATHER THAN A PARAMETER.
#:
#: The Reports API bulk path cannot be reached with GET alone: asking Amazon to BUILD a report is
#: `POST /reports/2021-06-30/reports`. Standing rule 1 forbids a silent cap on a connector's
#: records and names the Reports API as the fix, so refusing this one call would mean either no
#: bulk path at all or a quiet page loop over entity endpoints. Both are worse.
#:
#: ⭐ **THE EXCEPTION IS SHAPED LIKE `modules/collections_send.py`'s, deliberately** — that is the
#: codebase's single standing precedent for a connector that writes, and its discipline is: ONE
#: named operation, whitelisted in the data layer where no route, payload or UI can widen it.
#: Here the path is a module constant and `_create_report` takes NO path argument, so there is no
#: caller-supplied value to smuggle another operation through.
#:
#: ⚠ AND THE BLAST RADIUS IS WORTH STATING PLAINLY, because "read-only" is a promise to the owner
#: and this is one of two places the HTTP verb bends: a report request creates a JOB, not seller
#: data. The other is Amazon's POST-wrapped batch of fixed competitive-summary GETs. Neither can
#: alter a listing, a price, an order or an inventory level, and neither can send a buyer anything.
#: The two roles that could do those things were REFUSED at registration (R7).
_REPORTS_CREATE_PATH = "reports/2021-06-30/reports"
def _create_report(token, report_type, marketplace_ids, region=DEFAULT_REGION,
start=None, end=None, options=None, timeout=_TIMEOUT, sandbox=False):
"""Ask Amazon to build one report. -> its `reportId`.
⛔ NO `path` PARAMETER, ON PURPOSE. See `_REPORTS_CREATE_PATH` above: the whole safety argument
is that this function can reach exactly one operation and a caller cannot redirect it.
"""
require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
operation, scope = "createReport", _scope_for(token, region, sandbox)
if any(s.get("snapshot") and not s.get("dated_snapshot") and s.get("report") == report_type
for s in REPORT_TYPES.values()):
if start is not None or end is not None:
raise AmazonError("Snapshot reports cannot take a data window")
def attempt():
"""One raw attempt at the declared report-creation POST."""
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower())
if not base:
raise AmazonError(f"unknown region `{region}`")
body = {"reportType": str(report_type),
"marketplaceIds": list(marketplace_ids or [US_MARKETPLACE_ID])}
if start:
body["dataStartTime"] = str(start)
if end:
body["dataEndTime"] = str(end)
if options:
body["reportOptions"] = dict(options)
url = f"{base}/{_REPORTS_CREATE_PATH}"
req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
req.add_header("x-amz-access-token", token)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
req.add_header("User-Agent", _UA)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
_observe_rate(operation, scope, getattr(r, "headers", None))
got = json.loads(r.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as e:
_observe_rate(operation, scope, e.headers)
detail = ""
try:
detail = (e.read() or b"").decode("utf-8", errors="replace")
errs = json.loads(detail or "{}").get("errors") or []
detail = " ".join(str(err.get(part) or "") for err in errs
for part in ("message", "details") if err.get(part)) or detail
except Exception: # noqa: BLE001
pass
if e.code == 429:
raise AmazonThrottled(
f"{_safe(url)} was throttled (429) creating a {report_type} report. Report "
"creation is limited to about one call every 60 seconds with a burst of 15; the "
"fix is fewer, wider report windows, not more frequent requests",
retry_after=(e.headers or {}).get("Retry-After")) from None
if e.code == 403:
raise AmazonError(
f"{_safe(url)} refused a {report_type} report (403). That is a ROLE answer: this "
"report needs a role the application was not granted") from None
if e.code == 400 and report_type == REPORT_TYPES["search_query_performance"]["report"]:
raise AmazonReportError("Amazon refused Search Query Performance (400)",
detail, 400) from None
raise AmazonError(f"{_safe(url)} answered {e.code}"
+ (f": {detail[:200]}" if detail else "")) from None
except Exception as e: # noqa: BLE001
raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
rid = str(got.get("reportId") or "")
if not rid:
raise AmazonError(f"Amazon accepted the {report_type} request but returned no reportId")
return rid
base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
str(region or DEFAULT_REGION).lower(), "")
# ⭐ Pace once per new report. Retrying that same report pays only the shared backoff.
with _pacing_scope(scope):
_report_pacer["waited"].set(_pace_report_create())
return _retry(
attempt, f"{base}/{_REPORTS_CREATE_PATH}",
operation=operation, scope=scope,
exhausted_fix="create fewer reports with wider report windows")
#: Terminal processing states. `DONE` is the only one that yields a document.
_REPORT_DONE = "DONE"
_REPORT_DEAD = {"CANCELLED", "FATAL"}
def report_document(fields, report_type, start=None, end=None, options=None,
poll_seconds=15, max_wait=900, log=None, timeout=_TIMEOUT, report_id=None, once=False):
"""The whole bulk path for one report: request, poll, resolve the document. -> `(text, meta)`.
⭐ THIS IS STANDING RULE 1'S "RECOMMENDED FIX", IMPLEMENTED RATHER THAN CITED. Amazon's own
guidance is that entity endpoints are for deltas and lookups and the Reports API is for a set:
one report document carries every row for its window, so a backfill costs one rate-limited
request instead of one per page.
⚠ THE WAIT IS BOUNDED AND THE TIMEOUT IS REPORTED, NOT SWALLOWED. A report that is still
`IN_PROGRESS` after `max_wait` raises with the reportId in the message, so the next call can
resume from it rather than paying for the whole build again.
"""
# Refuse an undeclared report even before its LWA exchange; _create_report guards its own door.
require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
held = _prefetched(fields, report_type, start, end, options)
if held is not None:
return held
if not report_id:
_draw_report_token(fields)
say = log or (lambda *_a, **_k: None)
token = access_token(fields, timeout=timeout)
region = str((fields or {}).get("region") or DEFAULT_REGION)
mkts = [str((fields or {}).get("marketplace_id") or US_MARKETPLACE_ID)]
sbx = is_sandbox(fields)
pace_context = _report_pacer["waited"].set(0.0)
try:
rid = report_id or _create_report(token, report_type, mkts, region=region, start=start, end=end,
options=options, timeout=timeout, sandbox=sbx)
finally:
paced = _report_pacer["waited"].get()
_report_pacer["waited"].reset(pace_context)
if paced:
say(f" {report_type}: waited {paced:.2f}s to stagger report creation")
say(f" {report_type}: reportId {rid}")
def read(path):
try:
return _request(path, token, region=region, timeout=timeout, sandbox=sbx)
except AmazonError as exc:
exc.report_id = rid
raise
waited, state, doc_id = 0, "", ""
while waited <= max_wait:
got = read(f"reports/2021-06-30/reports/{rid}")
state = str(got.get("processingStatus") or "")
if state == _REPORT_DONE:
doc_id = str(got.get("reportDocumentId") or "")
break
if state in _REPORT_DEAD:
if state == "FATAL" and report_type == REPORT_TYPES["search_query_performance"]["report"]:
error_id = got.get("reportDocumentId") or got.get("errorDocumentId")
reason = str(got.get("errorMessage") or "No error document was supplied by Amazon")
if error_id:
meta = read(f"reports/2021-06-30/documents/{error_id}")
if meta.get("url"):
reason = _download_document(meta["url"], str(meta.get("compressionAlgorithm") or ""))
error = AmazonReportError(f"Amazon ended Search Query Performance as FATAL (reportId {rid})",
reason, state)
error.report_id = rid
raise error
if state == "CANCELLED" and not (got.get("errorMessage") or got.get("errorDocumentId")
or got.get("reportDocumentId")):
# S66-T42 (lead, observed live 2026-09-25): Amazon documents CANCELLED as also
# meaning "the report had no data to return". Raising turned an empty period into
# a role-shaped refusal on screen and left the window to retry forever. An empty
# document lets the window complete and the connector detail name the empty period.
say(f" {report_type}: Amazon cancelled report {rid}; no data for the requested period")
return "", {"reportId": rid, "reportDocumentId": None, "processingStatus": state,
"cancelled": True,
"dataStartTime": got.get("dataStartTime"),
"dataEndTime": got.get("dataEndTime"),
"createdTime": got.get("createdTime"), "compression": None,
"marketplaceIds": got.get("marketplaceIds")}
# Every FATAL report now carries Amazon's OWN reason when it supplied an error document,
# so the connector detail names why, never only a generic role hint.
detail = ""
error_id = got.get("reportDocumentId") or got.get("errorDocumentId")
if error_id:
try:
meta = read(f"reports/2021-06-30/documents/{error_id}")
if meta.get("url"):
detail = _download_document(meta["url"], str(meta.get("compressionAlgorithm") or ""))
except AmazonError:
detail = ""
detail = " ".join(str(detail).replace("\u2014", "; ").replace("\u2013", " to ").split())[:240]
reason = detail or str(got.get("errorMessage") or "No error document was supplied by Amazon")
error = AmazonReportError(f"Amazon ended the {report_type} report as {state} (reportId {rid})",
reason, state)
error.report_id = rid
error.has_error_document = bool(error_id or got.get("errorMessage"))
raise error
if once:
break
time.sleep(poll_seconds)
waited += poll_seconds
# ⛔ The token is ~1 hour and a long report can outlive it. Re-mint rather than 403.
if waited and waited % 1800 == 0:
token = access_token(fields, timeout=timeout)
if not doc_id:
raise AmazonReportPending(rid, state)
meta = read(f"reports/2021-06-30/documents/{doc_id}")
url = str(meta.get("url") or "")
if not url:
error = AmazonError(f"the {report_type} report document carried no download URL")
error.report_id = rid
raise error
try:
text = _download_document(url, str(meta.get("compressionAlgorithm") or ""), spool=True)
except AmazonError as exc:
exc.report_id = rid
raise
say(f" {report_type}: {len(text):,} chars")
return text, {"reportId": rid, "reportDocumentId": doc_id, "processingStatus": state,
"dataStartTime": got.get("dataStartTime"),
"dataEndTime": got.get("dataEndTime"), "createdTime": got.get("createdTime"),
"compression": meta.get("compressionAlgorithm"), "marketplaceIds": got.get("marketplaceIds")}
def create_report_id(fields, report_type, start=None, end=None, options=None, timeout=_TIMEOUT):
"""S82-T14: request one report and return its reportId. `poll_report` reads it later."""
require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
token = access_token(fields, timeout=timeout)
return _create_report(token, report_type, [str((fields or {}).get("marketplace_id") or US_MARKETPLACE_ID)],
region=str((fields or {}).get("region") or DEFAULT_REGION), start=start, end=end,
options=options, timeout=timeout, sandbox=is_sandbox(fields))
def poll_report(fields, report_type, report_id, *, log=None, timeout=_TIMEOUT):
"""S82-T14: one status read. None while Amazon builds the report, else `(text, meta)` as `report_document`."""
try:
return report_document(fields, report_type, report_id=str(report_id), once=True, log=log,
timeout=timeout)
except AmazonReportPending:
return None
SETTLEMENT_REPORT_PAGE_CAP = 1000
def settlement_reports(fields, *, since=None, timeout=_TIMEOUT, log=None):
"""List settlements Amazon has already created, oldest first.
Amazon issues these on its own fortnightly cycle, so this lists rather than requests.
Only safe, named metadata leaves this function; vendor extras and tokens stay here.
"""
require_operation("GET", _REPORTS_CREATE_PATH,
report_type=REPORT_TYPES["settlements"]["report_discover"])
import re
rtype = REPORT_TYPES["settlements"]["report_discover"]
token = access_token(fields, timeout=timeout)
region = str((fields or {}).get("region") or DEFAULT_REGION)
params = {"reportTypes": rtype, "processingStatuses": "DONE", "pageSize": 100}
if since is not None:
params["createdSince"] = str(since)
reports = []
for _page in range(SETTLEMENT_REPORT_PAGE_CAP):
# _request owns the same _retry policy as the existing report/document reads.
got = _request(_REPORTS_CREATE_PATH, token, region=region, timeout=timeout,
sandbox=is_sandbox(fields), **params)
for raw in got.get("reports") or ():
row = {key: str(raw[key]) if raw.get(key) is not None else "" for key in (
"reportId", "reportDocumentId", "reportType", "dataStartTime",
"dataEndTime", "createdTime")}
# Match the API status door without importing upward into the API layer.
# Refuse unsafe values with a fixed sentence that cannot echo the credential.
if any(len(value) > 512 or "Atzr|" in value
or re.search(r"\bbearer\s+\S+", value, flags=re.IGNORECASE)
or any(ch in value for ch in ("\u2014", "\u2013"))
for value in row.values()):
raise AmazonError("Settlement discovery returned unsafe metadata; no status was emitted.")
if row["reportType"] != rtype or not row["reportDocumentId"]:
raise AmazonError("Settlement discovery returned an unexpected type or no document ID.")
reports.append(row)
next_token = got.get("nextToken")
if not next_token:
if log:
log(f"getReports discovered {len(reports)} settlement reports")
return sorted(reports, key=lambda row: (row["createdTime"], row["reportId"]))
# Amazon continuation tokens replace the original filters, which the token carries.
params = {"nextToken": str(next_token)}
raise AmazonError(
f"Settlement discovery hit the {SETTLEMENT_REPORT_PAGE_CAP}-page cap because Amazon kept "
"returning nextToken; retry with a narrower createdSince window.")
def settlement_document(fields, document_id, *, timeout=_TIMEOUT):
"""One settlement document's text through getReportDocument and the presigned URL."""
require_operation("GET", f"reports/2021-06-30/documents/{document_id}")
token = access_token(fields, timeout=timeout)
region = str((fields or {}).get("region") or DEFAULT_REGION)
meta = _request(f"reports/2021-06-30/documents/{document_id}", token, region=region,
timeout=timeout, sandbox=is_sandbox(fields))
url = str(meta.get("url") or "")
if not url:
raise AmazonError("The settlement document carried no download URL.")
return _download_document(url, str(meta.get("compressionAlgorithm") or ""))
def _workbook_as_tsv(raw):
"""An Excel workbook document, as the tab-separated text every flat-file parser reads.
S66-T42 (lead, observed live 2026-09-25): Amazon delivers some reports (FEE_DISCOUNTS_REPORT,
GET_REMOTE_FULFILLMENT_ELIGIBILITY) as an .xlsx workbook, a ZIP container. Decoded as text it
became garbage column names carrying NUL bytes, and Postgres refused the whole Amazon write.
The first sheet is the report; its first row is the header, like a flat file. Tabs and line
breaks inside a cell become spaces so the TSV shape holds.
"""
import io
try:
import openpyxl
book = openpyxl.load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
except Exception as e: # noqa: BLE001
raise AmazonError(f"the report document is a workbook that did not open: {type(e).__name__}") from None
sheet = book.worksheets[0] if book.worksheets else None
lines = []
for values in (sheet.iter_rows(values_only=True) if sheet is not None else ()):
cells = ["" if v is None else " ".join(str(v).replace("\x00", "").split()) for v in values]
if any(cells):
lines.append("\t".join(cells))
book.close()
return "\n".join(lines)
class ReportDocument:
"""One downloaded report document spooled to a temporary file, read back as text in pieces.
⛔ A report has no row cap (standing rule 1), so its text never sits in memory whole: the Brand
Analytics month held the body, its decompressed copy and its decoded text at once (D-7081).
The file is removed when the object is closed or collected.
"""
def __init__(self, path, encoding, errors, chars, size, compressed):
self.path, self.encoding, self.errors = path, encoding, errors
self.chars, self.size, self.compressed = chars, size, compressed
def open_text(self):
"""The decoded text as a stream; `newline=""` keeps line ends exactly as `bytes.decode` did."""
return open(self.path, "r", encoding=self.encoding, errors=self.errors, newline="")
def read_text(self):
"""The whole text, for a consumer whose document is small."""
with self.open_text() as handle:
return handle.read()
def __len__(self):
return self.chars
def close(self):
path, self.path = getattr(self, "path", None), None
if path:
try:
os.unlink(path)
except Exception: # noqa: BLE001
pass
def __del__(self):
self.close()
_SPOOL_CHUNK = 1 << 20
def _spool_file(prefix):
handle, path = tempfile.mkstemp(prefix=prefix, suffix=".part")
os.close(handle)
return path
def _unlink(path):
try:
os.unlink(path)
except OSError:
pass
def _decoded_chars(path, encoding, errors="strict"):
"""Characters in the file under one encoding; raises UnicodeDecodeError like `bytes.decode`."""
chars = 0
with open(path, "r", encoding=encoding, errors=errors, newline="") as handle:
while True:
piece = handle.read(_SPOOL_CHUNK)
if not piece:
return chars
chars += len(piece)
def _spooled_document(body, compression):
"""The spooled body as a `ReportDocument`: gunzip and decode stream through disk, never memory."""
compressed = os.path.getsize(body)
with open(body, "rb") as handle:
head = handle.read(4)
if not compression and head[:2] == b"\x1f\x8b":
compression = "GZIP"
if str(compression).upper() == "GZIP":
plain = _spool_file("amazon-document-")
try:
with gzip.open(body, "rb") as source, open(plain, "wb") as out:
shutil.copyfileobj(source, out, _SPOOL_CHUNK)
except Exception as e: # noqa: BLE001
_unlink(plain)
raise AmazonError(f"the report document did not decompress: {type(e).__name__}") from None
finally:
_unlink(body)
body = plain
with open(body, "rb") as handle:
head = handle.read(4)
if head[:4] == b"PK\x03\x04":
try:
with open(body, "rb") as handle:
return _workbook_as_tsv(handle.read())
finally:
_unlink(body)
size = os.path.getsize(body)
for enc in ("utf-8", "cp1252"):
try:
return ReportDocument(body, enc, "strict", _decoded_chars(body, enc), size, compressed)
except UnicodeDecodeError:
continue
return ReportDocument(body, "utf-8", "replace", _decoded_chars(body, "utf-8", "replace"), size, compressed)
def _download_document(url, compression="", timeout=120, *, spool=False):
"""Fetch one presigned report document and decode it. -> text, or a `ReportDocument` when spooled.
⚠ THE URL IS PRESIGNED AND SHORT-LIVED, AND IT IS NEVER LOGGED. `_safe` strips the query
string, which for an S3 presigned URL is the entire credential.
⚠ Amazon flat files are frequently `cp1252`, not UTF-8, and a hard decode drops whole rows on
one smart quote. Decoded with replacement, and that is a deliberate lossy choice on a
presentation field rather than on a number.
"""
# This is the presigned URL returned by getReportDocument, not an SP-API operation. Do not
# apply OPERATIONS here: its host and signature belong to Amazon's document download service.
req = urllib.request.Request(url, method="GET")
req.add_header("User-Agent", _UA)
body = _spool_file("amazon-document-") if spool else None
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
if body:
with open(body, "wb") as out:
shutil.copyfileobj(r, out, _SPOOL_CHUNK)
else:
raw = r.read()
except Exception as e: # noqa: BLE001
if body:
_unlink(body)
raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
if body:
return _spooled_document(body, compression)
# S66-T40 (lead, measured live 2026-09-25): Data Kiosk's getDocument answers only
# `documentId` and `documentUrl`, yet the JSONL it points at IS gzip. With no declared
# algorithm the bytes were decoded as text and every economics window failed to parse. The
# gzip magic number is unambiguous (no text report starts with 0x1f 0x8b), so it decides.
if not compression and raw[:2] == b"\x1f\x8b":
compression = "GZIP"
if str(compression).upper() == "GZIP":
import gzip
try:
raw = gzip.decompress(raw)
except Exception as e: # noqa: BLE001
raise AmazonError(f"the report document did not decompress: {type(e).__name__}") from None
if raw[:4] == b"PK\x03\x04":
return _workbook_as_tsv(raw)
for enc in ("utf-8", "cp1252"):
try:
return raw.decode(enc)
except UnicodeDecodeError:
continue
return raw.decode("utf-8", errors="replace")
def marketplace_participations(fields, timeout=_TIMEOUT):
"""The cheapest honest liveness call: which marketplaces this seller participates in.
Chosen over an orders or inventory read on purpose. It needs no role beyond the basic grant, it
returns no PII, it is not a bulk endpoint so it cannot burn a report quota, and a credential
that authenticates but participates in NO marketplace is a real and reportable state rather
than an empty result.
"""
token = access_token(fields, timeout=timeout)
region = str((fields or {}).get("region") or DEFAULT_REGION)
got = _request("sellers/v1/marketplaceParticipations", token, region=region, timeout=timeout,
sandbox=is_sandbox(fields))
return got.get("payload") or []
def _sales_rank(item, marketplace):
"""`{"rank", "group"}` from one catalog item: the display group rank, else the best classification rank."""
for entry in (item or {}).get("salesRanks") or ():
if not isinstance(entry, dict) or entry.get("marketplaceId") not in (None, marketplace):
continue
display = [r for r in entry.get("displayGroupRanks") or () if isinstance((r or {}).get("rank"), int)]
if display:
return {"rank": display[0]["rank"], "group": display[0].get("title")}
ranks = [r for r in entry.get("classificationRanks") or () if isinstance((r or {}).get("rank"), int)]
if ranks:
best = min(ranks, key=lambda r: r["rank"])
return {"rank": best["rank"], "group": best.get("title")}
return {"rank": None, "group": None}
def catalog_sales_ranks(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
"""Read sales ranks for any ASINs through `searchCatalogItems`, 20 per call. -> {asin: {"rank", "group"}}.
An ASIN Amazon does not return is absent from the result; the caller names it.
"""
unique = sorted({str(a or "").strip() for a in asins or () if str(a or "").strip()})
if not unique:
return {}
if any(not re.fullmatch(r"[A-Z0-9]{10}", a) for a in unique):
raise AmazonError("A sales rank read needs 10 character ASINs")
f = fields or {}
marketplace = str(f.get("marketplace_id") or US_MARKETPLACE_ID)
region = str(f.get("region") or DEFAULT_REGION)
path = OPERATIONS["searchCatalogItems"]["path"]
token, issued = access_token(f, timeout=timeout), now()
out = {}
for offset in range(0, len(unique), 20):
_pace_entity("searchCatalogItems", ENTITY_INTERVALS["searchCatalogItems"], sleep=sleep, now=now)
if now() - issued >= 3000:
token, issued = access_token(f, timeout=timeout), now()
batch = unique[offset:offset + 20]
got = _request(path, token, region=region, sandbox=is_sandbox(f), timeout=timeout,
marketplaceIds=marketplace, identifiersType="ASIN", identifiers=",".join(batch),
includedData="summaries,salesRanks", pageSize=20,
throttle_fix="read sales ranks again after the next weekly pull")
items = got.get("items") if isinstance(got, dict) else None
if not isinstance(items, list):
raise AmazonError("searchCatalogItems returned no item list; retry after Amazon restores its response")
for item in items:
asin = str((item or {}).get("asin") or "")
if asin in batch:
out[asin] = _sales_rank(item, marketplace)
return out
"""amazon_client.py — the SP-API transport, in the DATA LAYER where the loaders can reach it.
⛔⛔ **WHY THIS FILE MOVED DOWN OUT OF `aios-web/api/`, AND THE GATE THAT MADE IT.** The transport
started life inside `connectors_amazon.py`, and `harness/amazon_store.py` reached UP to import it.
`verify_meta`'s architecture leg caught it in one line -- `amazon_store.py -> connectors_amazon` --
and it was right: layers point ONE way (`modules -> core`, `api -> modules`), and nothing under
`platform/core` or `platform/harness` may import an API-layer module. That check exists because the
same shortcut was taken once before, with `sys.path.insert` plus an import from inside `core`.
⭐ **THE ALTERNATIVE WAS WORSE, WHICH IS WHY THIS AND NOT A SECOND READER.** `meta_store` avoids the
inversion by bringing its own reader, and Graph is simple enough that a second one costs little.
SP-API is not: the LWA token exchange, the read-only guard, the report request-poll-download loop
and the rate-limit reporting would all have existed twice, and "which stored credential serves this
connector" having two answers is a defect class this codebase already names. So the TRANSPORT lives
here, in the layer both callers can see, and `connectors_amazon.py` stays the API-layer face that
registers the liveness probe.
⭐ **WHY THIS FILE IS SMALL, AND THE STALE ASSUMPTION IT KILLS.** Since 2 October 2023 SP-API
disregards AWS SigV4 entirely and authorizes on the LWA access token alone: a plain
`Authorization: Bearer` header. Any library, blog post or memory that has us minting IAM users and
signing requests is describing a dead API.
· https://developer-docs.amazon.com/sp-api/changelog/sp-api-will-no-longer-require-aws-iam-or-aws-signature-version-4
⛔ **SELLER DATA IS READ-ONLY.** `_request` refuses any method but
GET before it builds a request. The separate `send_named_write` door admits C3's exact approved
inbound and removal batches. Sync and plain read routes cannot opt out of `_request`'s guard.
The approved POST wrappers read reports, pricing, fees, replenishment and Data Kiosk results.
`_notifications_post` creates only an EventBridge destination or one approved subscription.
These fixed paths cannot alter seller records or send buyer messages.
⛔ **REPORTS AND DATA KIOSK ARE THE BULK PATHS; FINANCES FOLLOWS EVERY PAGE.** SP-API is token-bucket rate limited per
operation per selling-partner/application pair, and Amazon treats throttling as evidence of a wrong
call pattern rather than a wrong ceiling. Standing rule 1 forbids a silent cap on a connector's
records, and its second half is what applies: a limit that genuinely cannot be removed must be
REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down.
· https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits
Ideation record, with every owner ruling: `AutoWiki/research/ideation/amazon-connector.md`
"""
from __future__ import annotations
import contextvars
from contextlib import contextmanager
import csv
import gzip
import hashlib
import importlib
import io
import json
import logging
import math
import os
import random
import re
import shutil
import sys
import tempfile
import threading
import time
from datetime import date, datetime, timezone, timedelta
import urllib.error
import urllib.parse
import urllib.request
KEY = "amazon_sp"
LABEL = "Amazon"
#: W57-T38/C13: five total attempts, including the first, bound one throttled operation.
RETRY_MAX_ATTEMPTS = 5
#: W57-T38/C13: exponential backoff starts at one second after the first 429.
RETRY_BASE_SECONDS = 1.0
#: W57-T38/C13: no individual retry sleep exceeds one minute, including Retry-After/jitter.
RETRY_MAX_SECONDS = 60.0
#: W57-T38/C13: randomize each wait by up to half its value to separate competing clients.
RETRY_JITTER = 0.5
#: W57-T38/C13: separate consecutive table report creations by at least five seconds.
REPORT_STAGGER_SECONDS = 5.0
#: Amazon createReport usage plan: 15 initial tokens, shared by callers in this process.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_BURST = 15
#: Amazon createReport usage plan: 0.0167 requests/second, approximately one token/minute.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_SUSTAINED_SECONDS = 60.0
#: Product Pricing v2022-05-01 `getCompetitiveSummary`, official default usage plan.
#: https://developer-docs.amazon.com/sp-api/reference/getcompetitivesummary
COMPETITIVE_SUMMARY_RATE = 0.033
COMPETITIVE_SUMMARY_INTERVAL = 1.0 / COMPETITIVE_SUMMARY_RATE
COMPETITIVE_SUMMARY_BATCH_SIZE = 20
#: AWD v2024-05-09 `listInventory`, official default usage plan and maximum page size.
#: https://developer-docs.amazon.com/sp-api/reference/listinventory
AWD_INVENTORY_RATE = 2.0
AWD_INVENTORY_INTERVAL = 1.0 / AWD_INVENTORY_RATE
AWD_INVENTORY_PAGE_SIZE = 200
# Unscoped callers retain the legacy bucket. Transport calls use credential-scoped state.
# The contextual wait belongs to the current report_document logger.
_report_pacer = {