54 lines
8.7 KiB
PHP
54 lines
8.7 KiB
PHP
<?php
|
|
ini_set('zend.exception_ignore_args','1');
|
|
set_exception_handler(function(Throwable $e){fwrite(STDERR,'Preservation check stopped: '.$e::class.' line '.$e->getLine().PHP_EOL);exit(1);});
|
|
$root=dirname(__DIR__,2);require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';
|
|
(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
|
|
$c=config('database.connections.'.config('database.default'));
|
|
if($c['driver']!=='pgsql'||$c['database']!=='investemoz'||(int)$c['port']!==5432||!in_array($c['host'],['127.0.0.1','localhost'])||!empty($c['url']))throw new RuntimeException('Active identity guard');
|
|
$b=json_decode(file_get_contents(__DIR__.'/FRESH-BACKUP.json'),true,512,JSON_THROW_ON_ERROR);$restore=$b['restore_target']['database'];
|
|
if(!preg_match('/^economic_refs_before_\d{8}_\d{6}_test$/D',$restore))throw new RuntimeException('Isolated restore guard');
|
|
$a=new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
|
|
$q=new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$restore,'postgres','',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
|
|
foreach([$a,$q]as$db){$db->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');$db->exec("SET LOCAL TIME ZONE 'UTC'");}
|
|
try{
|
|
$manifest=json_decode(file_get_contents($root.'/database/data/economic-references-lot-01.json'),true,512,JSON_THROW_ON_ERROR);
|
|
$expected=['reference_catalog_versions'=>[$manifest['catalog']],'economic_activities'=>$manifest['activities'],'value_chains'=>$manifest['chains'],'value_chain_links'=>$manifest['links']];
|
|
$technical=['sessions','cache','cache_locks','jobs','failed_jobs'];$diff=[];$technicalDiff=[];$tables=[];$allowed=[];
|
|
foreach($q->query("SELECT schemaname,tablename FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname<>'information_schema' ORDER BY schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC)as$t){
|
|
$name=$t['tablename'];$n='"'.str_replace('"','""',$t['schemaname']).'"."'.str_replace('"','""',$name).'"';
|
|
$columns=$q->prepare('SELECT column_name FROM information_schema.columns WHERE table_schema=? AND table_name=? ORDER BY ordinal_position');$columns->execute([$t['schemaname'],$name]);
|
|
$projection=implode(',',array_map(fn($v)=>'"'.str_replace('"','""',$v).'"',$columns->fetchAll(PDO::FETCH_COLUMN)));
|
|
$where='';
|
|
if($t['schemaname']==='public'&&isset($expected[$name])){$ids=array_column($expected[$name],'id');$where=' WHERE id NOT IN ('.implode(',',array_map(fn($id)=>$a->quote($id),$ids)).')';$allowed[$name]=count($ids);}
|
|
if($t['schemaname']==='public'&&$name==='migrations')$where=" WHERE migration <> '2026_10_16_120000_extend_economic_reference_hierarchy'";
|
|
if($t['schemaname']==='public'&&$name==='audit_events')$where=" WHERE source_system IS DISTINCT FROM 'economic-reference-lot-01'";
|
|
$sql='SELECT row_to_json(t)::text FROM (SELECT '.$projection.' FROM '.$n.$where.') t ORDER BY row_to_json(t)::text';
|
|
try{$x=$q->query($sql)->fetchAll(PDO::FETCH_COLUMN);$y=$a->query($sql)->fetchAll(PDO::FETCH_COLUMN);}catch(PDOException $e){file_put_contents($b['private_directory'].'/preservation-query-error.txt',$name.PHP_EOL.$e->getMessage());fwrite(STDERR,'Table: '.$name.' SQLSTATE: '.$e->getCode().PHP_EOL);throw $e;}
|
|
if($x!==$y){if($t['schemaname']==='public'&&in_array($name,$technical,true))$technicalDiff[]=$name;else $diff[]=$n;}
|
|
$tables[$n]=['previous_rows'=>count($x),'current_previous_rows'=>count($y),'previous_data_identical'=>$x===$y,'previous_sha256'=>hash('sha256',implode("\n",$x)),'current_previous_sha256'=>hash('sha256',implode("\n",$y))];
|
|
}
|
|
$normalize=function($v)use(&$normalize){if(is_array($v)){if(!array_is_list($v))ksort($v);foreach($v as&$x)$x=$normalize($x);unset($x);}return $v;};
|
|
$references=[];
|
|
foreach($expected as$table=>$rows)foreach($rows as$row){
|
|
$stmt=$a->prepare('SELECT * FROM "'.$table.'" WHERE id=?');$stmt->execute([$row['id']]);$actual=$stmt->fetch(PDO::FETCH_ASSOC);if(!$actual)throw new RuntimeException('Authorized reference absent');
|
|
foreach($row as$k=>$v){$want=$k==='status'?'published':($k==='data_classification'?'public':$v);$have=$k==='metadata'?json_decode($actual[$k],true,512,JSON_THROW_ON_ERROR):$actual[$k];
|
|
$same=is_array($want)?$normalize($want)===$normalize($have):($want===null?$have===null:(string)$want===(string)$have);if(!$same)throw new RuntimeException('Reference differs from exact authorized manifest');}
|
|
$references[]=['table'=>$table,'id'=>$row['id'],'status'=>$actual['status']??$actual['data_classification']];
|
|
}
|
|
$events=$a->query("SELECT action,actor_user_id,after_data->'result' AS result FROM audit_events WHERE source_system='economic-reference-lot-01' ORDER BY occurred_at,id")->fetchAll(PDO::FETCH_ASSOC);
|
|
if(array_column($events,'action')!==['schema','import','publish'])throw new RuntimeException('Unexpected operational audit count/order');
|
|
foreach($events as&$event){$event['result']=json_decode($event['result'],true,512,JSON_THROW_ON_ERROR);if((int)$event['actor_user_id']!==2)throw new RuntimeException('Actual responsible account differs');}unset($event);
|
|
if(count($events[1]['result']['changed'])!==15||count($events[2]['result']['changed'])!==15)throw new RuntimeException('Unexpected imported/published count');
|
|
$schema=['ledger'=>(int)$a->query("SELECT count(*) FROM migrations WHERE migration='2026_10_16_120000_extend_economic_reference_hierarchy'")->fetchColumn(),'metadata'=>(int)$a->query("SELECT count(*) FROM information_schema.columns WHERE table_name='economic_activities' AND column_name='metadata'")->fetchColumn(),'old_unique'=>(int)$a->query("SELECT count(*) FROM pg_constraint WHERE conname='economic_activities_sector_uq'")->fetchColumn(),'nullable'=>$a->query("SELECT is_nullable FROM information_schema.columns WHERE table_name='economic_activities' AND column_name='sector_id'")->fetchColumn(),'new_index'=>(int)$a->query("SELECT count(*) FROM pg_indexes WHERE indexname='economic_activities_sector_idx'")->fetchColumn()];
|
|
if($schema!==['ledger'=>1,'metadata'=>1,'old_unique'=>0,'nullable'=>'YES','new_index'=>1])throw new RuntimeException('Nominal schema mismatch');
|
|
$release=$root.'/outputs/investmoz-referencias-economicas-QA-20261016';$m=json_decode(file_get_contents($release.'/para-revisao/MANIFESTO-ENTREGA.json'),true);$base=json_decode(file_get_contents($release.'/ATIVO-ANTES.json'),true);$changed=array_column($m['application'],'path');$count=0;
|
|
foreach(array_merge($base['files'],$base['protected'])as$n=>$h){if(in_array($n,$changed,true)||str_starts_with($n,'public/build/'))continue;if(!is_file($root.'/'.$n)||hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Unrelated protected source/config differs');$count++;}
|
|
foreach(array_merge($m['application'],$m['build'],$m['private_originals'])as$s)if(hash_file('sha256',$root.'/'.$s['path'])!==$s['sha256'])throw new RuntimeException('Delivered file hash differs');
|
|
$private=json_decode(file_get_contents($b['private_directory'].'/backup-proof-private.json'),true);$files=0;$docs=0;
|
|
foreach($private['file_hashes']as$n=>$h){if(!str_starts_with($n,'storage/app/'))continue;if(!is_file($root.'/'.$n)||hash_file('sha256',$root.'/'.$n)!==$h)throw new RuntimeException('Managed private/public file changed');$files++;}
|
|
$disk=config('filesystems.disks.local.root');foreach($q->query('SELECT id,storage_key FROM documents WHERE storage_key IS NOT NULL')->fetchAll(PDO::FETCH_ASSOC)as$d){$n='storage-documents/'.$d['id'].'.stored';if(!isset($private['file_hashes'][$n]))continue;if(!is_file($disk.'/'.$d['storage_key'])||hash_file('sha256',$disk.'/'.$d['storage_key'])!==$private['file_hashes'][$n])throw new RuntimeException('Original library document changed');$docs++;}
|
|
$result=['at'=>gmdate('c'),'candidate'=>$m['candidate'],'read_only'=>true,'tables_compared'=>count($tables),'unexpected_business_history_differences'=>$diff,'technical_table_differences'=>$technicalDiff,'authorized_added_rows'=>$allowed,'references'=>$references,'schema'=>$schema,'operations'=>$events,'protected_unrelated_sources_assets_config'=>$count,'candidate_application_verified'=>13,'candidate_build_verified'=>162,'private_originals_verified'=>4,'managed_files_verified'=>$files,'original_documents_verified'=>$docs,'B_COUNTRY02_roles_classifications_history_preserved'=>!$diff,'business_records_unchanged'=>!$diff,'tables'=>$tables];
|
|
$path=__DIR__.'/PRESERVACAO-FINAL.json';if(is_file($path))throw new RuntimeException('Preserve final receipt');file_put_contents($path,json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR).PHP_EOL);
|
|
echo json_encode(array_diff_key($result,['tables'=>true,'operations'=>true,'references'=>true])).PHP_EOL;if($diff)exit(2);
|
|
}finally{foreach([$a,$q]as$db)$db->exec('ROLLBACK');}
|