174 lines
10 KiB
PHP
174 lines
10 KiB
PHP
<?php
|
|
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
require dirname(__DIR__).'/vendor/autoload.php';
|
|
$root = dirname(__DIR__);
|
|
$clientRelease = ($argv[1] ?? '') === '--apply-authorized-client-hiring-release';
|
|
if (! $clientRelease && ($argv[1] ?? '') !== '--apply-authorized-local-unification') {
|
|
throw new LogicException('Explicit local/public unification required.');
|
|
}
|
|
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
|
|
$settings = json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR);
|
|
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|
|
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|
|
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|
|
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
|
|
throw new LogicException('Refuse any other local installation.');
|
|
}
|
|
$archive = $root.'/storage/app/private/'.($clientRelease ? 'compras-release-client-hiring.zip' : 'compras-release-pilot-preserved.zip');
|
|
$expectedArchiveHash = $clientRelease ? ($argv[2] ?? '') : 'a7e4473e1417b444a42a484f1ddf4f0fc03b64874cb9c304ef74181b30745940';
|
|
if (! preg_match('/^[a-f0-9]{64}$/D', $expectedArchiveHash) || hash_file('sha256', $archive) !== $expectedArchiveHash) {
|
|
throw new LogicException('Use the same frozen public release.');
|
|
}
|
|
$zip = new ZipArchive;
|
|
if ($zip->open($archive, ZipArchive::RDONLY) !== true || $zip->getFromName('compras-release.json') !== file_get_contents($root.'/compras-release.json')) {
|
|
throw new LogicException('Source release differs from the public delivery.');
|
|
}
|
|
$manifest = json_decode($zip->getFromName('compras-release.json'), true, 512, JSON_THROW_ON_ERROR);
|
|
$migrations = $clientRelease ? ['database/migrations/2026_11_29_000004_create_business_clients.php']
|
|
: ['database/migrations/2026_11_03_000005_add_operational_geography_references.php',
|
|
'database/migrations/2026_11_29_000003_allow_signed_people_contract.php'];
|
|
$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('A local recovery authority is required.');
|
|
}
|
|
$liveConfig = [...$owner, 'url' => null, 'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']];
|
|
config(['database.connections.unify_live' => $liveConfig, 'database.connections.unify_admin' => [...$owner, 'url' => null, 'database' => 'postgres']]);
|
|
$live = DB::connection('unify_live');
|
|
$admin = DB::connection('unify_admin');
|
|
$identity = $live->selectOne('select current_database() as db, current_user as role');
|
|
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
|
|
throw new LogicException('Live identity mismatch.');
|
|
}
|
|
foreach ($migrations as $migration) {
|
|
if ($live->table('migrations')->where('migration', basename($migration, '.php'))->exists()) {
|
|
throw new LogicException('Inspect an already applied unification instead of repeating it.');
|
|
}
|
|
}
|
|
$directory = 'C:/laragon/data/compras/backups/local-public-unification-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
|
if (! mkdir($directory, 0700, true)) {
|
|
throw new LogicException('Private recovery directory unavailable.');
|
|
}
|
|
copy($settingsPath, $directory.'/settings.before.private.json');
|
|
copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json');
|
|
$tables = array_column($live->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
|
$columns = [];
|
|
foreach ($tables as $table) {
|
|
$columns[$table] = Schema::connection('unify_live')->getColumnListing($table);
|
|
}
|
|
$fingerprint = static function ($connection, array $selection): array {
|
|
$out = [];
|
|
foreach ($selection as $table => $fields) {
|
|
$quoted = implode(',', array_map(fn ($field) => '"'.str_replace('"', '""', $field).'"', $fields));
|
|
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.str_replace('"', '""', $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 (string $binary, array $arguments, array $connection): void {
|
|
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
|
['PGHOST' => $connection['host'], 'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
|
$process->run();
|
|
if (! $process->isSuccessful()) {
|
|
throw new RuntimeException('Private '.$binary.' failed; no credentials are printed.');
|
|
}
|
|
};
|
|
$restoreName = 'compras_unify_restore_'.bin2hex(random_bytes(6));
|
|
$created = false;
|
|
try {
|
|
$live->beginTransaction();
|
|
$live->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
$before = $fingerprint($live, $columns);
|
|
$snapshot = $live->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
|
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$directory.'/before.dump', '--dbname='.$liveConfig['database']], $liveConfig);
|
|
$live->commit();
|
|
$admin->statement('CREATE DATABASE "'.$restoreName.'"');
|
|
$created = true;
|
|
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restoreName, $directory.'/before.dump'], $owner);
|
|
config(['database.connections.unify_restore' => [...$owner, 'url' => null, 'database' => $restoreName]]);
|
|
$restore = DB::connection('unify_restore');
|
|
if ($fingerprint($restore, $columns) !== $before) {
|
|
throw new LogicException('Recovered rows differ from the private snapshot.');
|
|
}
|
|
if (Artisan::call('migrate', ['--database' => 'unify_restore', '--path' => $migrations, '--force' => true]) !== 0) {
|
|
throw new LogicException('Recovery-copy upgrade failed.');
|
|
}
|
|
$protected = array_diff_key($columns, array_flip(['migrations']));
|
|
if ($fingerprint($restore, $protected) !== array_intersect_key($before, $protected)) {
|
|
throw new LogicException('Recovery-copy original data changed.');
|
|
}
|
|
$activeProtected = array_diff_key($protected, array_flip(['sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches']));
|
|
$live->beginTransaction();
|
|
foreach (array_keys($activeProtected) as $table) {
|
|
$live->statement('LOCK TABLE "'.str_replace('"', '""', $table).'" IN SHARE ROW EXCLUSIVE MODE');
|
|
}
|
|
if ($fingerprint($live, $activeProtected) !== array_intersect_key($before, $activeProtected)) {
|
|
throw new LogicException('Business state changed since backup; preserve it and prepare a fresh snapshot.');
|
|
}
|
|
if (Artisan::call('migrate', ['--database' => 'unify_live', '--path' => $migrations, '--force' => true]) !== 0
|
|
|| $fingerprint($live, $activeProtected) !== array_intersect_key($before, $activeProtected)) {
|
|
throw new LogicException('Atomic local upgrade failed preservation checks.');
|
|
}
|
|
$live->commit();
|
|
foreach (array_keys($manifest['frontend']['files']) as $file) {
|
|
$name = 'public/build/'.$file;
|
|
$bytes = $zip->getFromName($name);
|
|
if (! is_string($bytes) || hash('sha256', $bytes) !== $manifest['frontend']['files'][$file]) {
|
|
throw new LogicException('Frozen frontend content mismatch.');
|
|
}
|
|
$target = $root.'/'.$name;
|
|
if (is_file($target) && file_get_contents($target) !== $bytes) {
|
|
throw new LogicException('Preserve an immutable asset collision.');
|
|
}
|
|
if (! is_file($target)) {
|
|
file_put_contents($target, $bytes);
|
|
}
|
|
}
|
|
foreach (['fonts-manifest.json', 'manifest.json'] as $file) {
|
|
$target = $root.'/public/build/'.$file;
|
|
file_put_contents($target.'.unify-next', $zip->getFromName('public/build/'.$file));
|
|
if (! rename($target.'.unify-next', $target)) {
|
|
throw new LogicException('Frontend pointer switch failed; original manifest is backed up.');
|
|
}
|
|
}
|
|
$report = ['state' => 'passed', 'release_id' => $manifest['release_id'], 'backup' => $directory,
|
|
'restored_tables_verified' => count($tables), 'protected_business_tables_preserved' => count($activeProtected),
|
|
'selected_migrations_applied' => $migrations, 'frontend_assets' => count($manifest['frontend']['files']),
|
|
'settings_users_permissions_and_original_columns_preserved' => true, 'public_or_sgf_database_changed' => false];
|
|
if ($clientRelease) {
|
|
$nextSettings = [...$settings, 'SGC_PEOPLE_THIRD_PARTY_ENABLED' => 'true'];
|
|
$temporarySettings = $settingsPath.'.client-next';
|
|
file_put_contents($temporarySettings, json_encode($nextSettings, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
|
if (! rename($temporarySettings, $settingsPath)) {
|
|
throw new LogicException('Client hiring configuration switch failed; original settings are backed up.');
|
|
}
|
|
$report['settings_users_permissions_and_original_columns_preserved'] = false;
|
|
$report['original_settings_users_permissions_and_original_columns_preserved'] = true;
|
|
$report['added_configuration'] = ['SGC_PEOPLE_THIRD_PARTY_ENABLED' => true];
|
|
}
|
|
} finally {
|
|
if ($live->transactionLevel() > 0) {
|
|
$live->rollBack();
|
|
}
|
|
DB::purge('unify_restore');
|
|
if ($created) {
|
|
if (! preg_match('/^compras_unify_restore_[a-f0-9]{12}$/D', $restoreName) || $restoreName === $settings['DB_DATABASE']) {
|
|
throw new LogicException('Recovery cleanup identity mismatch.');
|
|
}
|
|
$admin->statement('DROP DATABASE "'.$restoreName.'"');
|
|
}
|
|
$zip->close();
|
|
}
|
|
$report['temporary_restore_database_removed'] = true;
|
|
file_put_contents($root.'/docs/proofs/'.($clientRelease ? 'compras-local-client-hiring.json' : 'compras-local-unification.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
|
echo json_encode($report, JSON_THROW_ON_ERROR).PHP_EOL;
|