Files
Investidor-V2/outputs/investmoz-classificacao-ativacao-20261015/deliver.py
T
nala 6a76aac80f
tests / ci (push) Canceled after 0s
versao compilada 1
2026-10-16 09:17:28 +02:00

84 lines
6.5 KiB
Python

from pathlib import Path
import hashlib,json,zipfile,subprocess,datetime,os,shutil
root=Path(__file__).resolve().parents[2];out=Path(__file__).resolve().parent
release=root/'outputs/investmoz-classificacao-multidimensional-QA-20261015'
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
m=json.loads((release/'MANIFESTO-ENTREGA.json').read_text('utf-8'))
r=json.loads((release/'RECIBO-INTEGRIDADE.json').read_text('utf-8'))
b=json.loads((out/'FRESH-BACKUP.json').read_text('utf-8'))
c=json.loads((out/'ARRANQUE-CLONE-RESTAURADO.json').read_text('utf-8'))
p=json.loads((out/'PREFLIGHT.json').read_text('utf-8'))
assert all(x['candidate']==m['candidate'] for x in [r,b,c,p])
assert b['restore_verified'] and b['files_verified'] and c['kernel_bootstrap']=='passed' and c['DB_read_only']
assert b['target']['database']=='investemoz' and int(b['target']['port'])==5432
assert (datetime.datetime.now(datetime.timezone.utc)-datetime.datetime.fromisoformat(b['at'])).total_seconds()<3600
assert not (root/'storage/framework/down').exists() and not (out/'FONTES-COMPILACAO.json').exists()
backup=Path(b['private_directory']);private=json.loads((backup/'backup-proof-private.json').read_text('utf-8'))
assert sha(Path(private['dump_path']))==private['sha256'] and sha(Path(private['files_path']))==private['files_sha256']
for s in m['sources']:
f=root/s['path'];assert (sha(f) if f.is_file() else None)==s['previous_sha256'],s['path']
for n,h in p['protected_files'].items():assert sha(root/n)==h,n
for n,h in p['previous_build_files'].items():assert sha(root/'public/build'/n)==h,n
archive=root/'outputs'/r['zip']['name'];assert sha(archive)==r['zip']['sha256']
with zipfile.ZipFile(archive) as z:
assert z.testzip() is None
payload={x['path']:x for x in m['payload']}
stage=backup/'candidate-staging';assert not stage.exists();stage.mkdir()
for name in [*['fontes/'+x['path'] for x in m['sources']],*[x for x in payload if x.startswith('build/')],'reversao-compat/app/Services/OpportunityCanonicalContract.php']:
data=z.read(name);assert hashlib.sha256(data).hexdigest()==payload[name]['sha256']
f=stage/name;f.parent.mkdir(parents=True,exist_ok=True);f.write_bytes(data)
build=[x for x in payload if x.startswith('build/')]
for n in build:
target=root/'public'/n
assert not target.exists() or sha(target)==payload[n]['sha256'] or n in ['build/manifest.json','build/fonts-manifest.json'],'Asset collision: '+n
php='C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe'
def command(args,label):
run=subprocess.run(args,cwd=root,capture_output=True)
(backup/(label+'.log')).write_bytes(run.stdout+run.stderr)
if run.returncode:raise RuntimeError('Operational command failed: '+label)
def artisan(*args):command([php,'artisan',*args],'-'.join(args).replace(':','-').replace('/','_'))
def put(src,dest):
dest.parent.mkdir(parents=True,exist_ok=True);temp=dest.with_name(dest.name+'.classification-delivery.tmp');assert not temp.exists()
shutil.copy2(src,temp);assert sha(src)==sha(temp);os.replace(temp,dest)
receipt={'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'candidate':m['candidate'],'document_revision':'DOC01','authorization':p['authorization'],'maintenance_started':False,'maintenance_ended':False,'sources':{},'added_build_files':[],'build_files':{},'migrations':0,'flags_changed':0,'business_writes':0,'synthetic_data_imported':False,'accepted_QA_repeated':False,'backup_restore_verified':True}
try:
artisan('down','--retry=60');receipt['maintenance_started']=True
assert (root/'storage/framework/down').exists()
command([php,str(out/'cache-snapshot.php'),'before'],'cache-data-before')
for s in m['sources']:
put(stage/'fontes'/s['path'],root/s['path']);assert sha(root/s['path'])==s['candidate_sha256'];receipt['sources'][s['path']]=s['candidate_sha256']
for n in sorted(build,key=lambda x:x=='build/manifest.json'):
dest=root/'public'/n
if not dest.exists():receipt['added_build_files'].append(n)
put(stage/n,dest);assert sha(dest)==payload[n]['sha256'];receipt['build_files'][n]=payload[n]['sha256']
for n,h in p['protected_files'].items():assert sha(root/n)==h,n
for n in ['config:clear','route:clear','view:clear']:artisan(n)
# Destination preflight has no config/route caches or view precompilation to rebuild.
assert not b['cache_state']['configuration_cached'] and not b['cache_state']['routes_cached'] and not b['cache_state']['views_precompiled']
receipt['cache_commands']=['config:clear','route:clear','view:clear']
command([php,str(out/'cache-snapshot.php'),'after'],'cache-data-after');receipt['data_cache_unchanged_during_switch']=True
command([php,'artisan','route:list','--json','--path=minhas-oportunidades'],'routes-after-switch')
routes=json.loads((backup/'routes-after-switch.log').read_text('utf-8'))
assert any(x['uri']=='minhas-oportunidades/{id}/classification' and x['method']=='GET|HEAD' for x in routes)
assert any(x['uri']=='minhas-oportunidades/{id}/classification/review' and x['method']=='POST' for x in routes)
artisan('up');receipt['maintenance_ended']=True
assert not (root/'storage/framework/down').exists()
receipt['result']='17 sources and 174 build files delivered; operational GET confirmation pending'
except BaseException:
# While maintenance has not ended, new fields cannot have been used by the web UI.
# After up, retain compatibility even on recovery, so later operations are never discarded.
for s in m['sources']:
if s['previous_sha256'] is not None:
src=backup/'files'/s['path']
if receipt['maintenance_ended'] and s['path']=='app/Services/OpportunityCanonicalContract.php':src=stage/'reversao-compat'/s['path']
put(src,root/s['path'])
for s in m['sources']:
f=root/s['path']
if s['previous_sha256'] is None and f.is_file() and sha(f)==s['candidate_sha256']:f.unlink()
for n in p['previous_build_files']:put(backup/'files/public/build'/n,root/'public/build'/n)
for n in ['config:clear','route:clear','view:clear']:artisan(n)
artisan('up');receipt['maintenance_ended']=True;receipt['result']='file switch reverted; database preserved'
(out/'TROCA-REVERTIDA.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+'\n','utf-8');raise
(out/'FONTES-COMPILACAO.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+'\n','utf-8')
print(json.dumps({k:v for k,v in receipt.items() if k not in ['sources','build_files','added_build_files']},ensure_ascii=True))