From 6919383d3714bb7aae153c66335729b2d852bd4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 16 Oct 2026 17:09:00 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20"Fazer=20backup=20agora"=20in=20Integra?= =?UTF-8?q?=C3=A7=C3=B5es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The backup row gets a button that asks for a backup outside the daily hour, for after a failure or before a risky change. The Kanban records the request; the backup service, which alone may read the whole database, looks every minute and runs it. The row says it was asked for until it runs. Co-Authored-By: Claude Opus 5.5 --- app/api/operator.py | 17 +++++++++++++++-- app/schema.sql | 5 +++++ ops/db_backup.py | 19 ++++++++++++++++++- tests/backup_test.py | 8 ++++++++ tests/kanban_test.py | 12 +++++++++++- web/kanban.js | 9 +++++++-- 6 files changed, 64 insertions(+), 6 deletions(-) diff --git a/app/api/operator.py b/app/api/operator.py index 362ddf4..c3b5052 100644 --- a/app/api/operator.py +++ b/app/api/operator.py @@ -80,10 +80,23 @@ def backup_status(c): """The latest database backup and the latest run, which may have failed.""" ok = c.execute('''SELECT finished_at,bytes FROM dtf_local.backups WHERE status='ok' ORDER BY finished_at DESC LIMIT 1''').fetchone() - last = c.execute('SELECT finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone() + last = c.execute('SELECT started_at,finished_at,status,detail FROM dtf_local.backups ORDER BY finished_at DESC LIMIT 1').fetchone() + asked = c.execute('''SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1''', + (last['started_at'] if last else datetime(2000, 1, 1, tzinfo=timezone.utc),)).fetchone() return {'last_ok': ok['finished_at'].isoformat() if ok else None, 'bytes': ok['bytes'] if ok else None, 'failed': last['detail'] if last and last['status'] == 'failed' else None, - 'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None} + 'failed_at': last['finished_at'].isoformat() if last and last['status'] == 'failed' else None, + 'requested': asked is not None} + + +@router.post('/api/operator/backup/run') +def backup_now(user=Depends(can('manage'))): + """A backup now, outside the daily hour: the backup service, which alone + may read the whole database, starts it within a minute.""" + with db.connect() as c: + c.execute('INSERT INTO dtf_local.backup_requests(requested_by) VALUES(%s)', (user,)) + audit('backup_requested', operator=user) + return {'ok': True} @router.get('/api/operator/board') diff --git a/app/schema.sql b/app/schema.sql index 7655ffc..92a03a4 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -144,6 +144,11 @@ CREATE TABLE IF NOT EXISTS dtf_local.backups ( status text NOT NULL CHECK(status IN ('ok','failed')), object_key text, bytes bigint, detail text ); CREATE INDEX IF NOT EXISTS backups_finished ON dtf_local.backups(finished_at DESC); +-- "Fazer backup agora" in the Kanban; the backup service looks every minute. +CREATE TABLE IF NOT EXISTS dtf_local.backup_requests ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, requested_at timestamptz NOT NULL DEFAULT now(), + requested_by text NOT NULL +); -- Why a quote waits for review, when the reason came from its files (the grade -- the server recomputed) and cannot be worked out again from the draft alone. diff --git a/ops/db_backup.py b/ops/db_backup.py index 0e5a51f..fc1b054 100644 --- a/ops/db_backup.py +++ b/ops/db_backup.py @@ -43,6 +43,8 @@ PREFIX = 'db/' RETRY = timedelta(hours=1) # A backup older than this means the daily run has stopped working. STALE = timedelta(hours=26) +# How often the service looks for a "Fazer backup agora" from the Kanban. +POLL = 60 TABLES = ('orders', 'quotes', 'uploads', 'accounts', 'movements', 'payment_intents') @@ -167,8 +169,13 @@ def serve(): now = datetime.now(timezone.utc) # A fresh deployment, or one that missed a day, backs up straight away. due = now if previous is None or now - previous > STALE else next_run(now, hour) + checked = now while True: - time.sleep(max(0, (due - datetime.now(timezone.utc)).total_seconds())) + now = datetime.now(timezone.utc) + if now < due and not requested_since(checked): + time.sleep(min(POLL, (due - now).total_seconds())) + continue + checked = datetime.now(timezone.utc) try: run_once() due = next_run(datetime.now(timezone.utc), hour) @@ -176,6 +183,16 @@ def serve(): due = datetime.now(timezone.utc) + RETRY +def requested_since(moment): + """Whether someone asked for a backup in the Kanban after `moment`.""" + try: + with admin_connect() as c: + return c.execute('SELECT 1 FROM dtf_local.backup_requests WHERE requested_at>%s LIMIT 1', + (moment,)).fetchone() is not None + except psycopg.Error: + return False + + def listing(): client, name = bucket() keys = [] diff --git a/tests/backup_test.py b/tests/backup_test.py index ca38884..7db72cf 100644 --- a/tests/backup_test.py +++ b/tests/backup_test.py @@ -31,6 +31,14 @@ def main(): os.environ['BACKUP_AGE_RECIPIENT'] = public check(db_backup.configured(), 'the local backup service is configured once a recipient is set') + # "Fazer backup agora" in the Kanban is seen by the service. + before = datetime.now(timezone.utc) + with admin_connect() as c: + c.execute("INSERT INTO dtf_local.backup_requests(requested_by) VALUES('backup-test')") + check(db_backup.requested_since(before), 'a backup asked for in the Kanban is seen by the service') + with admin_connect() as c: + c.execute("DELETE FROM dtf_local.backup_requests WHERE requested_by='backup-test'") + live = db_backup.counts(None) key = db_backup.run_once() with admin_connect() as c: diff --git a/tests/kanban_test.py b/tests/kanban_test.py index a07ce8e..b3d9068 100644 --- a/tests/kanban_test.py +++ b/tests/kanban_test.py @@ -145,7 +145,17 @@ def run(): assert row['fetched_at'] is None and row['failed_at'] is not None assert '11222333000181' not in registry.pending(c, 500) Client().call('/operator/stats', expected=401) - print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search and the numbers') + # "Fazer backup agora": recorded for the backup service, shown as asked. + with db.connect() as c: + c.execute('DELETE FROM dtf_local.backup_requests') + Client().call('/operator/backup/run', {}, expected=401) + client.call('/operator/backup/run', {}, operator=True) + assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is True + with db.connect() as c: + c.execute('DELETE FROM dtf_local.backup_requests') + assert client.call('/operator/board', operator=True)['providers']['backup']['requested'] is False + print('PASS: artwork pictures (owner only, images only), quote filters, the order/quote search, the numbers ' + 'and a backup asked for now') finally: with db.connect() as c: c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order_id,)) diff --git a/web/kanban.js b/web/kanban.js index b32fce3..62d96d9 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -1679,9 +1679,14 @@ function renderIntegrations(){ const ontem=bk.last_ok&&Date.now()-new Date(bk.last_ok)<26*3600e3; const tam=bk.bytes?(bk.bytes<1048576?Math.max(1,Math.round(bk.bytes/1024))+' KB':(bk.bytes/1048576).toFixed(1).replace('.',',')+' MB'):''; const never=!bk.last_ok&&!bk.failed; + const now=may('manage')&&!never?[button(bk.requested?'Pedido…':'Fazer backup agora',async()=>{ + try{await api('/backup/run',{});say('Backup pedido: começa em até 1 minuto. Atualize para ver o resultado.');await load();} + catch(e){say(e.message,true);}},'btn small')]:[]; + if(bk.requested&&now[0])now[0].disabled=true; rows.push(integration({name:'Backup do banco',state:never?'Não configurado':ontem&&!bk.failed?'Em dia':'Verificar', - tone:never?'off':ontem&&!bk.failed?'ok':'warn', - summary:bk.failed?'A última tentativa falhou ('+when(bk.failed_at)+').':bk.last_ok?'Último em '+when(bk.last_ok)+(tam?' · '+tam:''):'Nenhum backup feito ainda.', + tone:never?'off':ontem&&!bk.failed?'ok':'warn',actions:now, + summary:bk.requested?'Backup pedido · começa em até 1 minuto.': + bk.failed?'A última tentativa falhou ('+when(bk.failed_at)+').':bk.last_ok?'Último em '+when(bk.last_ok)+(tam?' · '+tam:''):'Nenhum backup feito ainda.', details:[...(bk.last_ok?[['Último backup',when(bk.last_ok)+(tam?' · '+tam:'')]]:[]),...(bk.failed?[['Erro',bk.failed]]:[]), node('p','Cópia diária, criptografada, fora do servidor.')]})); $('integrations').replaceChildren(...rows);