feat: "Fazer backup agora" in Integrações
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m40s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m29s
All checks were successful
Build and deploy / Validate source (push) Successful in 9s
Build and deploy / Integration suite on a real stack (push) Successful in 4m40s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 1m29s
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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')
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 = []
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,))
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user