diff --git a/app/tiny.py b/app/tiny.py index 9a75946..550f8b3 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -195,6 +195,11 @@ class TinyRateLimit(TinyError): transient = True +class TinyUnavailable(TinyError): + """Tiny answered with a server error (5xx): down for a moment, so what + depends on the answer waits for the outbox's next try.""" + + class TinyNotConnected(TinyError): """No authorised connection yet: an operator must click "Conectar Tiny".""" @@ -822,6 +827,8 @@ class TinyOrders: response = self.http.request(method, path, headers=headers, **kwargs) if response.status_code == 429: raise TinyRateLimit('Tiny rate limit reached; the outbox will retry') + if response.status_code >= 500: + raise TinyUnavailable(f'{method} {path}: {response.status_code} {response.text[:300]}') if response.status_code >= 400: raise TinyError(f'{method} {path}: {response.status_code} {response.text[:300]}') return response.json() if response.content else {} @@ -870,14 +877,17 @@ class TinyOrders: def contact_seller(self, contact_id): """The seller (vendedor) in a contact's registration, or None. A - failed reading leaves the order without one: it must still go.""" + reading Tiny refuses leaves the order without one: it must still go. + The seller cannot be set after the order is made, so a busy or + unavailable Tiny (429, 5xx, no answer) tries the whole delivery again.""" try: seller = (self.request('GET', f'/contatos/{contact_id}').get('vendedor') or {}).get('id') - except TinyRateLimit: - # Busy for a moment: the whole delivery is tried again, the seller with it. + except (TinyRateLimit, TinyUnavailable): raise except TinyError as exc: - logging.warning('Tiny: could not read the seller of contact %s: %s', contact_id, exc) + # The order goes without its seller, for good: Sentry hears of it. + logging.error('Tiny: could not read the seller of contact %s; the order goes without one: %s', + contact_id, exc) return None return int(seller) if str(seller or '').isdigit() and int(seller) > 0 else None diff --git a/tests/test_tiny.py b/tests/test_tiny.py index fcddc5e..8e1e896 100644 --- a/tests/test_tiny.py +++ b/tests/test_tiny.py @@ -77,7 +77,7 @@ class FakeTinyCase(unittest.TestCase): if request.method == 'GET' and path.startswith('/contatos/'): wanted = int(path.rsplit('/', 1)[-1]) if self.refuse_contact: - return httpx.Response(429 if self.refuse_contact == 429 else 503, text='indisponível') + return httpx.Response(self.refuse_contact, text='indisponível') return httpx.Response(200, json=next(c for c in self.contacts if c['id'] == wanted)) if request.method == 'POST' and path == '/contatos': contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)} @@ -267,11 +267,26 @@ class TinyTests(FakeTinyCase): self.tiny.deliver('k2', {**PAID, 'number': 43}) self.assertNotIn('vendedor', self.orders[1]) - def test_a_failed_seller_reading_does_not_hold_the_order(self): + def test_a_refused_seller_reading_does_not_hold_the_order_and_reaches_sentry(self): self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}}) - self.refuse_contact = True - self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created') + self.refuse_contact = 400 + with self.assertLogs(level='ERROR') as logged: + self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'created') self.assertNotIn('vendedor', self.orders[0]) + self.assertIn('without one', logged.output[0]) + + def test_an_unavailable_tiny_retries_the_delivery_instead_of_dropping_the_seller(self): + # The seller cannot be set after the order is made (order 151250): a + # 5xx while reading it tries the whole delivery again. + from app.tiny import TinyUnavailable + self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81', 'vendedor': {'id': 977231477}}) + self.refuse_contact = 503 + with self.assertRaises(TinyUnavailable): + self.tiny.deliver('k1', PAID) + self.assertEqual(self.orders, []) + self.refuse_contact = None + self.tiny.deliver('k1', PAID) + self.assertEqual(self.orders[0]['vendedor'], {'id': 977231477}) def test_a_busy_tiny_retries_the_delivery_instead_of_dropping_the_seller(self): from app.tiny import TinyRateLimit