Files
dpl/scripts/fuc-xb-launch/refresh-plan.php
T

461 lines
31 KiB
PHP

<?php
declare(strict_types=1);
// FUC-XB final-refresh planning and isolated rehearsal.
umask(0077);
ini_set('display_errors', '0');
$root = '/var/www/wwwroot/fuc-xb-test/current';
$private = '/var/www/wwwroot/fuc-xb-test/private';
$stateDirectory = $private . '/launch-ready-20261105';
final class RefreshRejected extends RuntimeException {}
function must(bool $ok, string $reason): void
{
if (!$ok) throw new RefreshRejected($reason);
}
function readJson(string $file): array
{
must(is_file($file) && !is_link($file) && (fileperms($file) & 0077) === 0, 'A private regular input is required');
return json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
}
function finalInputs(string $directory, array $summary, bool $formal): array
{
require_once __DIR__ . '/announcements.php';
if ($formal) {
$ready = readJson($directory . '/import-ready.json');
$freeze = readJson($directory . '/freeze-verified.json');
$target = readJson($directory . '/target-verified.json');
$backup = readJson($directory . '/old-fuc-full.json');
$age = time() - strtotime($freeze['verified_utc']);
must(posix_geteuid() === 0 && fileowner($directory) === 0 && (fileperms($directory) & 0077) === 0
&& $age >= 0 && $age <= 2100
&& $freeze['old_ingress_maintenance'] === true && $freeze['old_business_writers_stopped'] === true
&& $freeze['old_nodes_drained'] === true && $freeze['payments_drained'] === true
&& $target['public_writes_blocked'] === true && $target['writers_stopped'] === true,
'Current verified freeze of both sites required');
must($ready['target'] === 'fuc_xb_test' && $target['database'] === $ready['target']
&& $ready['freeze_sha256'] === hash_file('sha256', $directory . '/freeze-verified.json')
&& $ready['target_gate_sha256'] === hash_file('sha256', $directory . '/target-verified.json')
&& $ready['backup_sha256'] === $backup['sha256']
&& $ready['backup_sha256'] === hash_file('sha256', $directory . '/old-fuc-full.sql.gz')
&& $ready['snapshot_sha256'] === $summary['snapshot_sha256']
&& $ready['projection_sha256'] === $summary['projection_sha256']
&& $ready['release'] === $target['release']
&& basename(realpath(dirname(__DIR__, 2))) === $target['release'],
'Final source, target or release changed');
}
$handle = gzopen($directory . '/snapshot.jsonl.gz', 'rb');
must($handle !== false, 'Cannot open final snapshot');
$rows = [];
try {
$header = json_decode(gzgets($handle), true, 512, JSON_THROW_ON_ERROR);
while (($line = gzgets($handle)) !== false) {
$record = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
if ($record['kind'] === 'row' && $record['table'] === 'announcement') $rows[] = $record['row'];
}
} finally {
gzclose($handle);
}
must(isset($header['counts']['announcement']) && count($rows) === $header['counts']['announcement'],
'Final snapshot does not contain its full announcement table');
return fucProjectAnnouncements($rows, new DateTimeZone($header['timezone']));
}
function groupCohorts(string $directory, array $project): array
{
$manifest = readJson($directory . '/snapshot-manifest.json');
$path = $directory . '/snapshot.jsonl.gz';
must(is_file($path) && !is_link($path) && (fileperms($path) & 0077) === 0, 'Private source snapshot required');
must($manifest['complete'] && $manifest['source_business_writes'] === 0 && hash_file('sha256', $path) === $project['snapshot_sha256'] && $manifest['sha256'] === $project['snapshot_sha256'], 'Snapshot provenance mismatch');
$users = array_column($project['users'], 'group_id', 'id');
$handle = gzopen($path, 'rb');
must($handle !== false, 'Cannot open snapshot');
$mapping = $reverse = [];
$count = 0;
try {
while (($line = gzgets($handle)) !== false) {
$item = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
if ($item['kind'] !== 'row' || $item['table'] !== 'user') continue;
$user = $item['row'];
$id = (int) $user['id'];
$class = (int) $user['class'];
must(array_key_exists($id, $users), 'Source user not present in projection');
$group = $users[$id];
unset($users[$id]);
$count++;
if ($class <= 0) {
must($group === null, 'Inactive source user received a projected group');
continue;
}
$cohort = $class . ':' . (int) $user['node_group'];
must(is_int($group) && (!isset($mapping[$cohort]) || $mapping[$cohort] === $group) && (!isset($reverse[$group]) || $reverse[$group] === $cohort), 'Cohort mapping is not one-to-one');
$mapping[$cohort] = $group;
$reverse[$group] = $cohort;
}
} finally {
gzclose($handle);
}
$projectedIds = array_column($project['groups'], 'id');
$observedIds = array_values($mapping);
sort($projectedIds);
sort($observedIds);
must(!$users && $count === $manifest['counts']['user'] && $projectedIds === $observedIds, 'Snapshot/projection users or groups differ');
ksort($mapping);
return $mapping;
}
function validateProjection(string $directory): array
{
$summary = readJson($directory . '/projection-summary.json');
$p = readJson($directory . '/projection.json');
must(hash_file('sha256', $directory . '/projection.json') === $summary['projection_sha256'] && $p['snapshot_sha256'] === $summary['snapshot_sha256'], 'Projection content drift');
must(count($p['users']) === $summary['users'] && count($p['vip_openings']) === $summary['users'] && count($p['plans']) === $summary['hidden_legacy_plans'] && count($p['groups']) === $summary['groups'], 'Projection counts drift');
must(array_sum(array_column($p['users'], 'balance')) === $summary['wallet_cents'] && array_sum(array_column($p['users'], 'commission_balance')) === $summary['commission_cents'] && array_sum(array_column($p['refunds'], 'amount_cents')) === $summary['prepaid_refund_cents'], 'Projection balances drift');
return [$summary, $p];
}
function legacyPlanAssignments(string $directory, array $users, array $groups, array $plans, array $products): array
{
$stream = gzopen($directory . '/snapshot.jsonl.gz', 'rb');
must($stream !== false, 'Cannot read source orders');
$orders = $invoices = [];
try {
while (($line = gzgets($stream)) !== false) {
$item = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
if ($item['kind'] !== 'row') continue;
$row = $item['row'];
if ($item['table'] === 'order' && $row['status'] === 'activated') {
$orders[(int) $row['user_id']][] = [(int) $row['id'], $row['product_code']];
} elseif ($item['table'] === 'invoice' && in_array($row['status'], ['paid_gateway', 'paid_balance', 'paid_admin'], true)) {
$invoices[(int) $row['order_id']][] = (int) $row['user_id'];
}
}
} finally {
gzclose($stream);
}
$assignments = [];
foreach ($users as $id => $user) {
if ($user['plan_id'] === null) continue;
$group = $user['group_id'];
if ($group === $groups['1:1']) {
must(empty($orders[$id]), 'Trial user has an activated order');
$assignments[$id] = $plans['legacy-trial'];
} elseif ($group === $groups['2:99']) {
$assignments[$id] = $plans['legacy-restricted'];
} else {
must($group === $groups['2:1'] && count($orders[$id] ?? []) === 1, 'An ordinary legacy entitlement needs reconciliation');
[$order, $product] = $orders[$id][0];
must(($invoices[$order] ?? []) === [$id], 'An activated order needs payment reconciliation');
if (in_array($product, ['3th-a', '3th-b'], true)) {
$assignments[$id] = $plans['legacy-promotion'];
} else {
must(($products[$product]['series'] ?? null) === 'lite', 'An activated paid product has no approved hidden mapping');
$assignments[$id] = $plans['legacy-lite'];
}
}
}
return $assignments;
}
function canonical($value)
{
if (!is_array($value)) return $value;
if (!array_is_list($value)) ksort($value);
return array_map('canonical', $value);
}
function digest(array $value): string
{
return hash('sha256', json_encode(canonical($value), JSON_THROW_ON_ERROR));
}
function sameRow(array $expected, array $actual, string $fieldScope): void
{
foreach ($expected as $key => $value) {
must(array_key_exists($key, $actual) && ($actual[$key] === null ? null : (string) $actual[$key]) === ($value === null ? null : (string) $value), 'Field mismatch in ' . $fieldScope . '.' . $key);
}
}
function streamDigest($db, array $tables): string
{
$hash = hash_init('sha256');
foreach ($tables as $table => $key) {
hash_update($hash, $table . "\n");
foreach ($db->table($table)->orderBy($key)->cursor() as $row) hash_update($hash, json_encode(canonical((array) $row), JSON_THROW_ON_ERROR) . "\n");
}
return hash_final($hash);
}
try {
$mode = $argv[2] ?? 'preview';
$formal = in_array($mode, ['cutover-commit', 'cutover-verify'], true);
$finalDrill = in_array($mode, ['rehearse-final-commit', 'rehearse-final-verify'], true);
$final = $formal || $finalDrill;
$commitMode = $final || in_array($mode, ['rehearse-commit','verify-commit'], true);
$verifyOnly = in_array($mode, ['verify-commit', 'cutover-verify', 'rehearse-final-verify'], true);
$directoryPattern = $formal ? '/\Acutover-[0-9]{8}T[0-9]{6}Z\z/D' : '/\Arefresh-20[0-9]{6}(?:-[a-z0-9-]{1,32})?\z/D';
must(PHP_SAPI === 'cli' && ($commitMode || in_array($mode, ['preview','rehearse-rollback'], true))
&& preg_match($directoryPattern, $argv[1] ?? '') === 1, 'Invalid refresh operation');
if ($commitMode && !$formal) {
$expectedDirectory = $finalDrill ? 'refresh-20261105-final-import-rehearsal' : 'refresh-20261105-launch-rehearsal';
must($argv[1] === $expectedDirectory && preg_match('/\Afuc_xb_cutover_qa_[a-f0-9]{8}\z/D', getenv('DB_DATABASE') ?: '') === 1,
'Rehearsal commit is limited to a disposable database');
}
$targetDirectory = $private . '/' . $argv[1];
must(realpath($targetDirectory) === $targetDirectory, 'Unsafe projection directory');
$active = readJson($private . '/active-migration.json');
$activeDirectory = $private . '/refresh-20261105';
// Validate the deployed projection rather than treating mutable staging rows as source facts.
[$oldSummary, $old] = validateProjection($activeDirectory);
must($active['private_dir'] === $activeDirectory && $active['snapshot_sha256'] === $old['snapshot_sha256'], 'Active migration does not reference the expected baseline');
[$summary, $fresh] = validateProjection($targetDirectory);
$notices = $final ? finalInputs($targetDirectory, $summary, $formal) : [];
$oldCohorts = groupCohorts($activeDirectory, $old);
$freshCohorts = groupCohorts($targetDirectory, $fresh);
must(array_keys($oldCohorts) === ['1:1', '2:1', '2:99'] && array_keys($freshCohorts) === array_keys($oldCohorts), 'A legacy cohort changed; review access explicitly');
$groups = [];
foreach ($freshCohorts as $cohort => $id) $groups[$id] = $oldCohorts[$cohort];
putenv('XB_INSTANCE=fuc-xb-test');
$_SERVER['XB_INSTANCE'] = $_ENV['XB_INSTANCE'] = 'fuc-xb-test';
require $root . '/vendor/autoload.php';
$app = require $root . '/bootstrap/app.php';
if ($commitMode) {
$runtime = getenv('FUC_CUTOVER_RUNTIME') ?: '';
must(preg_match('~\A/tmp/fuc-xb-cutover-[a-f0-9]{8}\z~D', $runtime) === 1 && realpath($runtime) === $runtime && (fileperms($runtime) & 0077) === 0, 'A private cutover runtime is required');
$app->useStoragePath($runtime . '/storage');
foreach (['CONFIG','ROUTES','EVENTS','SERVICES','PACKAGES'] as $cache) {
$key = 'APP_' . $cache . '_CACHE';
$path = $runtime . '/' . strtolower($cache) . '.php';
$_SERVER[$key] = $_ENV[$key] = $path;
putenv($key . '=' . $path);
}
}
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
if ($commitMode) config(['cache.default' => 'array', 'cache.stores.redis' => ['driver' => 'array']]);
$db = Illuminate\Support\Facades\DB::connection();
$expectedDatabase = $commitMode && !$formal ? getenv('DB_DATABASE') : 'fuc_xb_test';
must($db->getDatabaseName() === $expectedDatabase && $db->selectOne('SELECT DATABASE() AS active_db')->active_db === $expectedDatabase, 'Wrong isolated database');
if ($formal) {
$server = $db->selectOne('SELECT @@hostname AS host, @@socket AS local_socket');
must(realpath($root) === realpath(dirname(__DIR__, 2))
&& $server->host === gethostname() && $server->local_socket === '/run/mysqld/mysqld.sock',
'Formal import must use the deployed release and its local database');
}
$verifiedTables = ['v2_user'=>'id','v2_plan'=>'id','fuc_vip_accounts'=>'user_id','fuc_vip_entries'=>'id','v2_order'=>'id'];
if ($final) $verifiedTables += ['v2_notice'=>'id','personal_access_tokens'=>'id','v2_traffic_reset_logs'=>'id'];
$receiptTable = $final ? 'fuc_cutover_receipt' : 'fuc_cutover_drill';
if ($commitMode) {
$lock = fopen(($formal ? $stateDirectory : $runtime) . '/panel.lock', 'c');
must($lock && flock($lock, LOCK_EX | LOCK_NB), 'An isolated import is already running');
if ($final && !$verifyOnly) {
$db->statement('CREATE TABLE IF NOT EXISTS fuc_cutover_receipt (snapshot_sha256 char(64) PRIMARY KEY, projection_sha256 char(64) NOT NULL, rows_sha256 char(64) NOT NULL) ENGINE=InnoDB');
}
if ($final) {
$tables = array_unique(array_merge(array_keys($verifiedTables), ['v2_traffic_reset_logs', $receiptTable]));
$transactional = $db->table('information_schema.TABLES')->whereRaw('TABLE_SCHEMA = DATABASE()')
->whereIn('TABLE_NAME', $tables)->where('ENGINE', 'InnoDB')->count();
must($transactional === count($tables), 'All cutover tables must use InnoDB');
}
$receipt = $db->table($receiptTable)->where('snapshot_sha256', $summary['snapshot_sha256'])->first();
if ($receipt) {
must($receipt->projection_sha256 === $summary['projection_sha256'] && $receipt->rows_sha256 === streamDigest($db, $verifiedTables), 'Committed database readback differs');
must($db->table('v2_user')->count() === $summary['users'] + (int) !$final && $db->table('fuc_vip_accounts')->count() === $summary['users'] && $db->table('fuc_vip_entries')->count() === $summary['users'] && !$db->table('v2_order')->exists(), 'Committed row counts differ');
$verified = ['passed'=>true,'mode'=>$mode,'users'=>(int)$summary['users'],'vip_openings'=>(int)$summary['users'],'refund_orders'=>(int)$summary['prepaid_orders'],'refund_cents'=>(int)$summary['prepaid_refund_cents'],'wallet_cents'=>(int)$summary['wallet_cents'],'readback_sha256'=>$receipt->rows_sha256,'duplicate_writes'=>false];
if ($final) {
must($db->table('v2_notice')->count() === count($notices) && !$db->table('personal_access_tokens')->exists(), 'Final notices or session counts differ');
$verified['announcements'] = count($notices);
}
echo json_encode($verified, JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
must(!$verifyOnly && !$db->table($receiptTable)->exists(), 'Expected committed snapshot receipt is missing or conflicts');
Illuminate\Support\Facades\Queue::fake();
Illuminate\Support\Facades\Mail::fake();
Illuminate\Support\Facades\Http::preventStrayRequests();
}
$state = readJson($stateDirectory . '/panel-state.json');
$qa = readJson($private . '/qa-credentials.json');
must($state['owner'] === 'fuc-xb-launch-20261105' && count($state['plans']) === 12 && count($state['nodes']) === 22, 'Owned operations baseline changed');
must(!$db->table('v2_order')->exists() && !$db->table('v2_commission_log')->exists() && !$db->table('fuc_vip_entries')->where('kind', '!=', 'opening')->exists(), 'Native business exists; prelaunch replacement is unsafe');
$protected = [];
$catalog = readJson($private . '/catalog-rebuild-20261105/applied.json');
$sales = array_slice($catalog['destinations'], 0, 4, true);
$hidden = array_slice($catalog['destinations'], 4, null, true);
must(array_keys($sales) === ['lite','normal','plus','pro'] && array_keys($hidden) === ['legacy-trial','legacy-promotion','legacy-restricted'], 'Unexpected catalog receipt');
$plans = $db->table('v2_plan')->orderBy('id')->get()->map(fn($r) => (array) $r)->all();
$byId = array_column($plans, null, 'id');
$legacyLite = array_values(array_filter($plans, fn($plan) => $plan['name'] === '旧站轻量套餐'));
must(count($legacyLite) === 1, 'The protected legacy-lite plan is missing or ambiguous');
$hidden['legacy-lite'] = (int) $legacyLite[0]['id'];
$expectedPlanIds = array_merge(array_values($sales), array_values($hidden));
sort($expectedPlanIds);
must(array_map('intval', array_keys($byId)) === $expectedPlanIds, 'The current four sales and four hidden plans do not match');
$expectedHiddenGroups = ['legacy-trial'=>$oldCohorts['1:1'], 'legacy-promotion'=>$oldCohorts['2:1'], 'legacy-restricted'=>$oldCohorts['2:99'], 'legacy-lite'=>$oldCohorts['2:1']];
foreach ($hidden as $kind => $id) {
$plan = $byId[$id];
must(!$plan['show'] && !$plan['sell'] && !$plan['renew'] && !json_decode($plan['prices'] ?? '[]', true, 32, JSON_THROW_ON_ERROR) && (int) $plan['reset_traffic_method'] === 2 && (int) $plan['group_id'] === $expectedHiddenGroups[$kind], 'A legacy plan has lost entitlement protections');
}
foreach ($catalog['result']['formal_plans'] as $entry) {
$plan = $byId[$entry['id']];
$price = array_map('floatval', $entry['prices']);
$current = array_map('floatval', json_decode($plan['prices'], true, 32, JSON_THROW_ON_ERROR));
must(in_array($entry['id'], $sales, true) && $plan['show'] && $plan['sell'] && $plan['renew'] && (int) $plan['transfer_enable'] === $entry['monthly_quota_gb'] && (int) $plan['group_id'] === (int) $state['sales_group_id'] && (int) $plan['reset_traffic_method'] === 1 && $current === $price + ['reset_traffic'=>$price['monthly']], 'A sales plan changed');
}
$protected['catalog'] = digest($plans);
$products = array_column(json_decode(file_get_contents($root . '/scripts/fuc-xb-launch/catalog.json'), true, 32, JSON_THROW_ON_ERROR)['products'], null, 'code');
$legacyGroupIds = array_values($oldCohorts);
$opsGroups = [$state['qa_group_id'], $state['sales_group_id']];
$groupIds = array_merge($legacyGroupIds, $opsGroups);
sort($groupIds);
must($db->table('v2_server_group')->orderBy('id')->pluck('id')->map(fn($id) => (int) $id)->all() === $groupIds, 'Unowned group exists');
$protected['groups'] = digest($db->table('v2_server_group')->orderBy('id')->get()->map(fn($r) => (array) $r)->all());
$nodeIds = array_column(array_values($state['nodes']), 'node_id');
$machineIds = array_column(array_values($state['nodes']), 'machine_id');
sort($nodeIds);
sort($machineIds);
$nodes = $db->table('v2_server')->orderBy('id')->get()->map(fn($r) => (array) $r)->all();
must(array_map('intval', array_column($nodes, 'id')) === $nodeIds, 'Unowned node exists');
$expectedMachines = array_column(array_values($state['nodes']), 'machine_id', 'node_id');
foreach ($nodes as $node) {
must(array_map('intval', json_decode($node['group_ids'], true, 8, JSON_THROW_ON_ERROR)) === [$state['qa_group_id']] && (int) $node['machine_id'] === $expectedMachines[$node['id']], 'Node has lost QA isolation or machine identity');
}
// Only stable fields contribute to the plan; live traffic and heartbeats can advance.
$protected['nodes'] = digest(array_map(fn($n) => array_diff_key($n, array_flip(['u','d','updated_at'])), $nodes));
$machines = $db->table('v2_server_machine')->orderBy('id')->get()->map(fn($r) => array_diff_key((array) $r, array_flip(['last_seen_at','load_status','updated_at'])))->all();
must(array_map('intval', array_column($machines, 'id')) === $machineIds, 'Unowned machine exists');
$protected['machines_hash_only'] = digest($machines);
$freshUsers = array_column($fresh['users'], null, 'id');
$oldUsers = array_column($old['users'], null, 'id');
must(count($freshUsers) === $summary['users'] && count($oldUsers) === $oldSummary['users'], 'User IDs are not unique');
$assignments = legacyPlanAssignments($targetDirectory, $freshUsers, $freshCohorts, $hidden, $products);
$assignedCounts = array_count_values($assignments);
$cohortCounts = array_map(fn($id) => $assignedCounts[$id] ?? 0, $hidden);
$existing = $db->table('v2_user')->select(['id','email','uuid','is_admin','is_staff'])->orderBy('id')->get();
$knownQA = array_map('intval', array_merge([$qa['user_id']], $state['users']));
$owned = $admins = 0;
foreach ($existing as $row) {
$id = (int) $row->id;
if (isset($oldUsers[$id])) {
$want = $oldUsers[$id];
must($row->email === $want['email'] && $row->uuid === $want['uuid'], 'A migrated identity was replaced');
if ($row->is_admin) {
must($row->email === '[email protected]' && isset($freshUsers[$id]) && $freshUsers[$id]['email'] === $row->email && $freshUsers[$id]['uuid'] === $row->uuid, 'Administrator identity changed');
$admins++;
}
continue;
}
$isFixture = $final && $row->email === '[email protected]';
must(($isFixture || in_array($id, $knownQA, true)) && str_ends_with($row->email, '@fuc-xb.invalid') && !$row->is_admin && !$row->is_staff, 'An unowned staging user exists');
$owned++;
}
must($admins === 1 && count($existing) === count($oldUsers) + $owned, 'Missing migrated identity or administrator');
$qaCollision = isset($freshUsers[$qa['user_id']]);
$collisions = count(array_intersect(array_keys($freshUsers), $knownQA));
$nextQaId = $qaCollision ? max(max(array_keys($freshUsers)), (int) $existing->max('id')) + 1 : $qa['user_id'];
$usersWithChangedSourceUUID = 0;
$freshPlanGroups = array_column($fresh['plans'], 'group_id', 'id');
foreach ($freshUsers as $id => $row) {
if (isset($oldUsers[$id]) && $oldUsers[$id]['uuid'] !== $row['uuid']) $usersWithChangedSourceUUID++;
if ($row['plan_id'] === null) must($row['group_id'] === null, 'Unentitled user has a group');
else must(isset($assignments[$id], $groups[$row['group_id']]) && $freshPlanGroups[$row['plan_id']] === $row['group_id'] && (int) $byId[$assignments[$id]]['group_id'] === $groups[$row['group_id']], 'Entitlement points outside its remapped group');
}
$result = ['read_only'=>true,'source_snapshot_sha256'=>$fresh['snapshot_sha256'],'projection_sha256'=>$summary['projection_sha256'],'users'=>$summary['users'],'hidden_plans'=>count($hidden),'hidden_plan_assignments'=>$cohortCounts,'wallet_cents'=>$summary['wallet_cents'],'commission_cents'=>$summary['commission_cents'],'refund_orders'=>$summary['prepaid_orders'],'refund_cents'=>$summary['prepaid_refund_cents'],'operating_plans_preserved'=>count($sales),'operating_nodes_preserved'=>count($nodes),'operating_machines_preserved'=>count($machines),'known_qa_user_id_collisions'=>$collisions,'gui_qa_requires_id_change'=>$qaCollision,'new_source_uuid_count'=>$usersWithChangedSourceUUID,'eligible_legacy_groups'=>[$oldCohorts['1:1'],$oldCohorts['2:1']],'excluded_legacy_group'=>$oldCohorts['2:99'],'protected_digests'=>$protected,'plan_sha256'=>digest(['source'=>$summary['projection_sha256'],'assignments'=>$assignments,'group_ids'=>$groups,'protected'=>$protected,'gui_qa_id'=>$nextQaId])];
if ($final || in_array($mode, ['rehearse-rollback','rehearse-commit'], true)) {
must($final || $targetDirectory === $private . '/refresh-20261105-launch-rehearsal', 'Rollback rehearsal is limited to the isolated rehearsal snapshot');
if (!$commitMode) {
$lock = fopen($stateDirectory . '/panel.lock', 'c');
must($lock && flock($lock, LOCK_EX | LOCK_NB), 'FUC panel operations are busy');
}
$closed = readJson($stateDirectory . '/qa-cleanup.json');
$registrationClosed = $commitMode
? (int) $db->table('v2_settings')->where('name', 'stop_register')->value('value') === 1
: (int) admin_setting('stop_register') === 1;
must($closed['passed'] && ($final || $owned === 1) && !$db->table('v2_payment')->where('enable', 1)->exists() && $registrationClosed, 'Finish isolated QA and keep payment/registration disabled');
must(!$db->table('v2_order')->exists() && !$db->table('v2_commission_log')->exists() && !$db->table('v2_stat_user')->exists(), 'New business or user statistics exist');
$qaRow = (array) $db->table('v2_user')->where('id', $qa['user_id'])->first();
must($final || ($qaRow['email'] === '[email protected]' && !$qaRow['is_admin'] && !$qaRow['is_staff'] && $qaRow['group_id'] === null), 'GUI QA ownership changed');
$rollbackTables = ['v2_user'=>'id','v2_plan'=>'id','fuc_vip_accounts'=>'user_id','fuc_vip_entries'=>'id','personal_access_tokens'=>'id','v2_traffic_reset_logs'=>'id'];
$baseline = streamDigest($db, $rollbackTables);
app(App\Services\Plugin\PluginManager::class)->initializeEnabledPlugins();
$db->beginTransaction();
try {
foreach (['v2_traffic_reset_logs','fuc_vip_entries','fuc_vip_accounts'] as $table) $db->table($table)->delete();
if ($final) $db->table('personal_access_tokens')->delete();
$db->table('v2_user')->delete();
foreach ($freshUsers as $id => &$user) {
if ($user['group_id'] !== null) $user['group_id'] = $groups[$user['group_id']];
$user['plan_id'] = $assignments[$id] ?? null;
$user['next_reset_at'] = null;
if ($user['email'] === '[email protected]') $user['is_admin'] = 1;
}
unset($user);
foreach (array_chunk($freshUsers, 150) as $batch) $db->table('v2_user')->insert($batch);
if (!$final) {
$qaRow['id'] = $nextQaId;
$db->table('v2_user')->insert($qaRow);
}
$vip = app(Plugin\VipLoyalty\Service::class);
App\Models\User::withoutTimestamps(function () use ($fresh, $vip) {
foreach ($fresh['vip_openings'] as $entry) $vip->opening($entry['user_id'], $entry['uuid'], $entry['opening_cumulative_cents'], $fresh['snapshot_sha256']);
});
$fullReadback = 0;
foreach ($db->table('v2_user')->orderBy('id')->cursor() as $row) {
$id = (int) $row->id;
must(isset($freshUsers[$id]) || (!$final && $id === $nextQaId), 'Unexpected imported identity');
sameRow($freshUsers[$id] ?? $qaRow, (array) $row, 'user');
$fullReadback++;
}
must($fullReadback === $summary['users'] + (int) !$final, 'Incomplete user readback');
$openings = array_column($fresh['vip_openings'], null, 'user_id');
$vipReadback = 0;
foreach ($db->table('fuc_vip_accounts')->orderBy('user_id')->cursor() as $account) {
$id = (int) $account->user_id;
must(isset($openings[$id]) && (int) $account->opening_cents === $openings[$id]['opening_cumulative_cents'] && (int) $account->cumulative_cents === $openings[$id]['opening_cumulative_cents'] && $account->opening_reference === $fresh['snapshot_sha256'], 'VIP opening readback mismatch');
$vipReadback++;
}
must($vipReadback === $summary['users'] && !$db->table('v2_order')->exists(), 'VIP count or order boundary mismatch');
if ($commitMode) {
$entryCount = 0;
foreach ($db->table('fuc_vip_entries')->orderBy('id')->cursor() as $entry) {
$id = (int) $entry->user_id;
must(isset($openings[$id]) && $entry->entry_key === 'opening:' . $id && $entry->kind === 'opening' && (int) $entry->amount_cents === $openings[$id]['opening_cumulative_cents'], 'VIP opening ledger differs');
$entryCount++;
}
must($entryCount === $summary['users'], 'VIP opening ledger count differs');
}
$billingUsers = $db->table('v2_user');
if (!$final) $billingUsers->where('id', '!=', $nextQaId);
must((int) $billingUsers->sum('balance') === $summary['wallet_cents'] && (int) $billingUsers->sum('commission_balance') === $summary['commission_cents'], 'Wallet or commission mismatch');
must(digest($db->table('v2_plan')->orderBy('id')->get()->map(fn($r)=>(array)$r)->all()) === $protected['catalog'], 'Current sales or hidden plans changed');
must(digest($db->table('v2_server')->orderBy('id')->get()->map(fn($r)=>array_diff_key((array)$r,array_flip(['u','d','updated_at'])))->all()) === $protected['nodes'] && digest($db->table('v2_server_machine')->orderBy('id')->get()->map(fn($r)=>array_diff_key((array)$r,array_flip(['last_seen_at','load_status','updated_at'])))->all()) === $protected['machines_hash_only'], 'Nodes or machines changed');
if ($final) $result['announcements'] = fucImportAnnouncements($db->getPdo(), $notices);
if ($commitMode) {
$result['committed_sha256'] = streamDigest($db, $verifiedTables);
$db->table($receiptTable)->insert(['snapshot_sha256'=>$summary['snapshot_sha256'],'projection_sha256'=>$summary['projection_sha256'],'rows_sha256'=>$result['committed_sha256']]);
$db->commit();
}
} finally {
while ($db->transactionLevel()) $db->rollBack();
}
if (!$commitMode) {
must(streamDigest($db, $rollbackTables) === $baseline, 'Rollback did not restore the original rows');
}
$result['read_only'] = false;
$result['committed_database_writes'] = $commitMode;
$result[$final ? 'import_readback' : 'rehearsal'] = ['rolled_back'=>!$commitMode,'original_rows_restored'=>!$commitMode,'full_user_readback'=>$fullReadback,'vip_opening_readback'=>$vipReadback,'gui_qa_collision_handled'=>$qaCollision];
}
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $e) {
// Do not expose framework arguments or snapshots to the invoking terminal.
$reason = $e instanceof RefreshRejected ? $e->getMessage() : get_class($e);
if ($e instanceof ErrorException) {
$reason .= ' at line ' . $e->getLine();
if (preg_match('/\AUndefined (array key|variable) ["$a-zA-Z0-9_]+\z/D', $e->getMessage())) {
$reason .= ' ' . $e->getMessage();
}
}
fwrite(STDERR, $reason . PHP_EOL);
exit(1);
}