185 lines
11 KiB
PHP
185 lines
11 KiB
PHP
<?php
|
|
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
require dirname(__DIR__).'/vendor/autoload.php';
|
|
$root = dirname(__DIR__);
|
|
if (! in_array('--apply-authorized', $argv, true)) {
|
|
throw new LogicException('Instalação exige opção explícita e autorização registada.');
|
|
}
|
|
$authorization = json_decode(file_get_contents($root.'/docs/proofs/benchmark-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
|
$expected = ['2026_11_22_000001_add_company_details_to_tenants.php' => '47477a97242f5b0b30e130853b91c463e5257cac250aee662a5b681fe544b923'];
|
|
$manifestHash = '4c8c11cc7a5908ae7c12fcd74073b728fc0adec0faff041f4546a50ab4bd05ee';
|
|
$oldManifestHash = '31ae1a57572bd509381fc29512b09d7d3bf9b33f5f3671db2db04186f03ba50e';
|
|
$candidate = $root.'/storage/framework/testing/benchmark-candidate-20261122';
|
|
if (($authorization['status'] ?? '') !== 'approved' || ($authorization['environment'] ?? '') !== 'http://127.0.0.1:8005'
|
|
|| ($authorization['scope'] ?? '') !== 'company_details_schema_and_benchmark_assets' || ($authorization['migration_hashes'] ?? []) !== $expected
|
|
|| ($authorization['manifest_sha256'] ?? '') !== $manifestHash || file_exists($root.'/docs/proofs/benchmark-pilot-installation.json')) {
|
|
throw new LogicException('Autorização incompatível ou instalação já registada.');
|
|
}
|
|
foreach ($expected as $name => $hash) {
|
|
if (hash_file('sha256', $root.'/database/migrations/'.$name) !== $hash) {
|
|
throw new LogicException('Migração mudou desde a proposta.');
|
|
}
|
|
}
|
|
if (hash_file('sha256', $candidate.'/manifest.json') !== $manifestHash || hash_file('sha256', $root.'/public/build/manifest.json') !== $oldManifestHash) {
|
|
throw new LogicException('Candidata ou manifesto anterior não coincide.');
|
|
}
|
|
$manifest = json_decode(file_get_contents($candidate.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
|
|
$assets = [];
|
|
foreach ($manifest as $entry) {
|
|
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
|
|
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! is_file($candidate.'/'.$file)) {
|
|
throw new LogicException('Alvo de assets inválido.');
|
|
}
|
|
$assets[$file] = hash_file('sha256', $candidate.'/'.$file);
|
|
if (is_file($root.'/public/build/'.$file) && hash_file('sha256', $root.'/public/build/'.$file) !== $assets[$file]) {
|
|
throw new LogicException('Não sobrescrever um chunk existente divergente.');
|
|
}
|
|
}
|
|
}
|
|
$s = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
|
if (($s['APP_ENV'] ?? '') !== 'payable-testing' || ($s['DB_HOST'] ?? '') !== '127.0.0.1' || realpath($s['HOST_ROOT'] ?? '') !== realpath($root)
|
|
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $s['DB_DATABASE'] ?? '', $m) || $s['DB_USERNAME'] !== 'payable_qa_'.$m[1]) {
|
|
throw new LogicException('Destino do piloto não confirmado.');
|
|
}
|
|
$settingsHash = hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json');
|
|
$app = require $root.'/bootstrap/app.php';
|
|
$app->make(Kernel::class)->bootstrap();
|
|
$owner = DB::connection('pgsql')->getConfig();
|
|
unset($owner['name']);
|
|
if ($owner['host'] !== '127.0.0.1') {
|
|
throw new LogicException('Servidor administrativo não local.');
|
|
}
|
|
$qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']];
|
|
config(['database.connections.commercial_install' => $qa, 'database.connections.commercial_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
|
|
DB::setDefaultConnection('commercial_install');
|
|
$db = DB::connection();
|
|
$admin = DB::connection('commercial_owner');
|
|
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
|
if ($identity->db !== $s['DB_DATABASE'] || $identity->role !== $s['DB_USERNAME']) {
|
|
throw new LogicException('Identidade do piloto não coincide.');
|
|
}
|
|
$schema = $db->getSchemaBuilder();
|
|
if ($schema->hasColumn('tenants', 'company_details')) {
|
|
throw new LogicException('Estruturas já presentes: inspeccionar sem repetir.');
|
|
}
|
|
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
|
$columns = [];
|
|
foreach ($tables as $table) {
|
|
$columns[$table] = $schema->getColumnListing($table);
|
|
}
|
|
$fingerprint = static function ($connection) use ($columns): array {
|
|
$out = [];
|
|
foreach ($columns as $table => $names) {
|
|
$selected = implode(',', array_map(fn ($c) => '"'.str_replace('"', '""', $c).'"', $names));
|
|
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
|
|
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
|
}
|
|
|
|
return $out;
|
|
};
|
|
$pg = static function ($binary, $args, $connection): void {
|
|
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $connection['host'],
|
|
'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
|
$process->run();
|
|
if (! $process->isSuccessful()) {
|
|
throw new RuntimeException('Cópia/restauro não aprovado; nenhuma instalação deve prosseguir.');
|
|
}
|
|
};
|
|
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-benchmark-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
|
if (! mkdir($directory, 0700, true)) {
|
|
throw new RuntimeException('Salvaguarda indisponível.');
|
|
}
|
|
$dump = $directory.'/before.dump';
|
|
if (! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
|
|
throw new RuntimeException('Não foi possível preservar o manifesto anterior.');
|
|
}
|
|
$restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6));
|
|
$created = false;
|
|
$paths = array_map(fn ($name) => 'database/migrations/'.$name, array_keys($expected));
|
|
$migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($fingerprint, $paths): void {
|
|
$previous = DB::getDefaultConnection();
|
|
DB::setDefaultConnection($name);
|
|
try {
|
|
if (Artisan::call('migrate', ['--database' => $name, '--path' => $paths, '--force' => true]) !== 0) {
|
|
throw new RuntimeException('Migrações delimitadas falharam.');
|
|
}
|
|
$after = $fingerprint($connection);
|
|
unset($after['migrations'], $baseline['migrations']);
|
|
if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 1
|
|
|| $connection->table('tenants')->whereNotNull('company_details')->exists()) {
|
|
throw new LogicException('Dados anteriores ou valores novos divergentes.');
|
|
}
|
|
} finally {
|
|
DB::setDefaultConnection($previous);
|
|
}
|
|
};
|
|
try {
|
|
$db->beginTransaction();
|
|
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
|
$baseline = $fingerprint($db);
|
|
$migrationCount = $db->table('migrations')->count();
|
|
$snapshot = $db->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
|
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$qa['database']], $qa);
|
|
$db->commit();
|
|
// Restore with the same existing role, not an administrative reader bypassing RLS.
|
|
$admin->statement('CREATE DATABASE "'.$restore.'" OWNER "'.$s['DB_USERNAME'].'"');
|
|
$created = true;
|
|
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump], $qa);
|
|
config(['database.connections.commercial_restore' => [...$qa, 'database' => $restore]]);
|
|
$restored = DB::connection('commercial_restore');
|
|
if ($fingerprint($restored) !== $baseline) {
|
|
throw new LogicException('Restauro difere sob a mesma identidade/contexto.');
|
|
}
|
|
$migrateAndCheck($restored, 'commercial_restore', $baseline, $migrationCount);
|
|
$db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount) {
|
|
$db->statement("SET LOCAL lock_timeout = '5s'");
|
|
foreach ($tables as $table) {
|
|
$db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
|
|
}
|
|
if ($fingerprint($db) !== $baseline) {
|
|
throw new LogicException('Piloto mudou desde a salvaguarda; instalação recusada.');
|
|
}
|
|
$migrateAndCheck($db, 'commercial_install', $baseline, $migrationCount);
|
|
});
|
|
$result = ['environment' => 'http://127.0.0.1:8005', 'scope' => 'company_details_schema_and_benchmark_assets', 'schema_installed' => true,
|
|
'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'restored_tables_checked' => count($tables),
|
|
'previous_tables_preserved' => count($tables) - 1, 'migration_delta' => 1, 'new_values_empty' => true, 'same_restore_role' => true,
|
|
'assets_installed' => false, 'settings_preserved' => $settingsHash === hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json')];
|
|
file_put_contents($root.'/docs/proofs/benchmark-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
|
foreach ($assets as $file => $hash) {
|
|
$target = $root.'/public/build/'.$file;
|
|
if (! is_dir(dirname($target)) && ! mkdir(dirname($target), 0755, true)) {
|
|
throw new RuntimeException('Não foi possível preparar pasta de assets.');
|
|
}
|
|
if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
|
|
throw new RuntimeException('Cópia de asset falhou; manifesto anterior preservado.');
|
|
}
|
|
if (hash_file('sha256', $target) !== $hash) {
|
|
throw new RuntimeException('Asset copiado diverge; manifesto anterior preservado.');
|
|
}
|
|
}
|
|
if (! copy($candidate.'/manifest.json', $root.'/public/build/manifest.benchmark.tmp')
|
|
|| ! rename($root.'/public/build/manifest.benchmark.tmp', $root.'/public/build/manifest.json')) {
|
|
throw new RuntimeException('Troca do manifesto falhou; consultar salvaguarda.');
|
|
}
|
|
$result['assets_installed'] = hash_file('sha256', $root.'/public/build/manifest.json') === $manifestHash;
|
|
$result['manifest_sha256'] = $manifestHash;
|
|
$result['assets_verified'] = count($assets);
|
|
} finally {
|
|
if ($db->transactionLevel() > 0) {
|
|
$db->rollBack();
|
|
}
|
|
DB::purge('commercial_restore');
|
|
if ($created) {
|
|
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
|
}
|
|
}
|
|
$result['restore_database_removed'] = true;
|
|
file_put_contents($root.'/docs/proofs/benchmark-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
|
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|