fix: deleting a cancelled order keeps its Tiny cancellation, and production without the real Tiny holds the sends
Some checks failed
Some checks failed
- Deleting an order removed its Tiny events, delivered or not: cancelled and deleted before the worker sent it (or with Tiny down), the order stayed open in Tiny. A real order's events now stay; only a test order's go. - With TINY_ADAPTER missing from the production stack, the simulator marked paid orders delivered with made-up receipts, and they had to be queued again by hand. Production now holds the sends (the outbox retries and Sentry is told); with the real Tiny back, the worker sends them at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -50,7 +50,11 @@ def delete_order(uid: UUID, user=Depends(can('manage'))):
|
|||||||
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
|
cards = [r['id'] for r in c.execute('SELECT id FROM dtf_local.orders WHERE parent_id=%s', (uid,)).fetchall()]
|
||||||
for table in ('movements', 'order_files', 'print_files'):
|
for table in ('movements', 'order_files', 'print_files'):
|
||||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=ANY(%s)', ([uid] + cards,))
|
||||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
# A real order's Tiny events stay: its cancellation may not have
|
||||||
|
# reached Tiny yet (Tiny down, or deleted at once), and what was sent
|
||||||
|
# stays on record. A test order never goes to Tiny.
|
||||||
|
if test:
|
||||||
|
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{uid}:%',))
|
||||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (uid,))
|
||||||
if not test:
|
if not test:
|
||||||
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
c.execute('UPDATE dtf_local.quotes SET discarded_at=COALESCE(discarded_at,now()), discarded_by=COALESCE(discarded_by,%s) WHERE id=%s',
|
||||||
|
|||||||
@@ -17,12 +17,37 @@ from .scanning import ClamAV, scan_loop
|
|||||||
|
|
||||||
load_secret_files()
|
load_secret_files()
|
||||||
require_runtime()
|
require_runtime()
|
||||||
adapters = {'tiny': FakeTiny()}
|
# Production without the real Tiny (TINY_ADAPTER missing from the stack):
|
||||||
# Not yet confirmed against the client's account; see app/tiny.py.
|
# the sends wait and Sentry is told, instead of the simulator marking real
|
||||||
if os.environ.get('TINY_ADAPTER') == 'tiny':
|
# orders delivered with made-up receipts that had to be queued again by hand.
|
||||||
from .tiny import TinyOrders
|
HELD = 'Tiny desligado em produção (TINY_ADAPTER não é tiny): o envio espera'
|
||||||
from .cnpj import company
|
|
||||||
adapters['tiny'] = TinyOrders(names=company)
|
|
||||||
|
class HeldTiny:
|
||||||
|
def deliver(self, event_key, payload):
|
||||||
|
raise RuntimeError(HELD)
|
||||||
|
|
||||||
|
|
||||||
|
def tiny_adapter(adapter=None, environment=None):
|
||||||
|
"""The Tiny the outbox delivers to: the real one when configured; in
|
||||||
|
production otherwise none (HeldTiny); elsewhere the simulator."""
|
||||||
|
adapter = os.environ.get('TINY_ADAPTER') if adapter is None else adapter
|
||||||
|
environment = os.environ.get('APP_ENV', 'local') if environment is None else environment
|
||||||
|
if adapter == 'tiny':
|
||||||
|
from .tiny import TinyOrders
|
||||||
|
from .cnpj import company
|
||||||
|
return TinyOrders(names=company)
|
||||||
|
return HeldTiny() if environment == 'production' else FakeTiny()
|
||||||
|
|
||||||
|
|
||||||
|
adapters = {'tiny': tiny_adapter()}
|
||||||
|
|
||||||
|
|
||||||
|
def release_held(c):
|
||||||
|
"""With the real Tiny back, the sends held meanwhile go at once instead
|
||||||
|
of after their back-off."""
|
||||||
|
return c.execute('''UPDATE dtf_local.outbox SET available_at=now() WHERE provider='tiny'
|
||||||
|
AND delivered_at IS NULL AND last_error=%s''', (HELD,)).rowcount
|
||||||
last_tick = 0.0
|
last_tick = 0.0
|
||||||
last_cleanup = 0.0
|
last_cleanup = 0.0
|
||||||
last_reconcile = 0.0
|
last_reconcile = 0.0
|
||||||
@@ -199,6 +224,14 @@ class Health(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
observability.init('worker')
|
observability.init('worker')
|
||||||
|
if isinstance(adapters['tiny'], HeldTiny):
|
||||||
|
logging.error('Worker started in production without the real Tiny: Tiny sends are held')
|
||||||
|
elif not isinstance(adapters['tiny'], FakeTiny):
|
||||||
|
try:
|
||||||
|
with connect() as c:
|
||||||
|
release_held(c)
|
||||||
|
except Exception:
|
||||||
|
logging.exception('Could not release the Tiny sends held while Tiny was off')
|
||||||
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
|
||||||
scan_thread.start()
|
scan_thread.start()
|
||||||
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)
|
||||||
|
|||||||
@@ -109,6 +109,10 @@ def run():
|
|||||||
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
client.call(f'/operator/orders/{paid_order}/delete', {}, operator=True)
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
|
assert not c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (paid_order,)).fetchone()
|
||||||
|
# Its cancellation still goes to Tiny: deleted at once, or with Tiny
|
||||||
|
# down, it must not be lost with the order.
|
||||||
|
assert c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||||
|
(f'{paid_order}:cancelled:tiny',)).fetchone(), 'the Tiny cancellation was lost'
|
||||||
# Deleted: no state at all, so the folder removes its files too.
|
# Deleted: no state at all, so the folder removes its files too.
|
||||||
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
|
assert client.call('/operator/queue/folder', {'held': [str(paid_order)]}, operator=True)['states'] == {}
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
@@ -156,7 +160,7 @@ def run():
|
|||||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
|
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', ([gone_quote, other_quote, test2_quote],))
|
||||||
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
|
c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files.values()),))
|
||||||
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete '
|
print('PASS: discard hides and blocks a quote; test orders delete; paid orders cancel, then delete, keeping the Tiny cancellation, '
|
||||||
'and free their files')
|
'and free their files')
|
||||||
finally:
|
finally:
|
||||||
with db.connect() as c:
|
with db.connect() as c:
|
||||||
|
|||||||
@@ -53,5 +53,29 @@ class RefusedDeliveryTest(unittest.TestCase):
|
|||||||
self.assertEqual(self.tick_with(9, limit).call_count, 1)
|
self.assertEqual(self.tick_with(9, limit).call_count, 1)
|
||||||
|
|
||||||
|
|
||||||
|
class HeldTinyTest(unittest.TestCase):
|
||||||
|
"""Production without the real Tiny holds the sends and tells Sentry; the
|
||||||
|
simulator marked real orders delivered with made-up receipts."""
|
||||||
|
def test_production_without_the_real_tiny_holds(self):
|
||||||
|
self.assertIsInstance(worker.tiny_adapter('fake', 'production'), worker.HeldTiny)
|
||||||
|
self.assertIsInstance(worker.tiny_adapter(None, 'production'), worker.HeldTiny)
|
||||||
|
self.assertIsInstance(worker.tiny_adapter('fake', 'local'), worker.FakeTiny)
|
||||||
|
|
||||||
|
def test_a_held_send_stays_undelivered_and_is_reported(self):
|
||||||
|
job = {'id': 1, 'provider': 'tiny', 'event_key': 'o:paid:tiny', 'payload': {}, 'attempts': 0}
|
||||||
|
conn = mock.MagicMock()
|
||||||
|
conn.execute.return_value.fetchone.return_value = job
|
||||||
|
connect = mock.MagicMock()
|
||||||
|
connect.return_value.__enter__.return_value = conn
|
||||||
|
with mock.patch.object(worker, 'connect', connect), \
|
||||||
|
mock.patch.dict(worker.adapters, {'tiny': worker.HeldTiny()}), \
|
||||||
|
mock.patch.object(worker.logging, 'error') as error:
|
||||||
|
worker.tick()
|
||||||
|
updates = [call.args[0] for call in conn.execute.call_args_list[1:]]
|
||||||
|
self.assertTrue(updates and 'delivered_at=now()' not in updates[0] and 'last_error' in updates[0], updates)
|
||||||
|
self.assertEqual(conn.execute.call_args_list[1].args[1][0], worker.HELD)
|
||||||
|
self.assertEqual(error.call_count, 1)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user