normalizeIds($userIds); if ($requested === []) { return $this->emptyResult(); } $connection = (new User())->getConnection(); $result = $connection->transaction(function () use ($connection, $requested) { // Row locks and a second non-admin condition protect concurrent promotion. $users = User::whereIn('id', $requested)->where('is_admin', 0)->lockForUpdate()->get(); if ($users->isEmpty()) { return $this->emptyResult($requested); } $ids = []; $emails = []; foreach ($users as $user) { $ids[] = (int) $user->id; $emails[] = strtolower(trim((string) $user->email)); } // Account deletion must never orphan a VM or an in-flight purchase. if ($connection->getSchemaBuilder()->hasTable('cloud_instances') && $connection->table('cloud_instances')->whereIn('user_id', $ids) ->where('status', '!=', 'deleted')->exists()) { throw new \RuntimeException('用户仍有云服务器,请先删除或转交实例后再删除账户'); } // Only a fully observed root tombstone may be removed with the // account. Any live/deleting root remains owned by the dedicated // VPC worker and must keep the account reachable. if ($connection->getSchemaBuilder()->hasTable('cloud_vpcs') && $connection->table('cloud_vpcs')->whereIn('user_id', $ids) ->where('state', '<>', 'deleted')->exists()) { throw new \RuntimeException('用户仍有 VPC 私网,请先清理 VPC 后再删除账户'); } if ($this->hasColumns($connection, 'cloud_private_networks', ['user_id', 'state']) && $connection->table('cloud_private_networks')->whereIn('user_id', $ids) ->whereNotIn('state', ['released'])->exists()) { throw new \RuntimeException('用户仍有私网地址预留,请先完成 VPC 清理后再删除账户'); } $this->assertVpcHistoryCleanable($connection, $ids); if ($connection->getSchemaBuilder()->hasTable('cloud_orders') && $connection->table('cloud_orders')->whereIn('user_id', $ids) ->whereIn('status', ['awaiting_payment', 'pending', 'queued', 'running', 'provisioning', 'uncertain'])->exists()) { throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户'); } foreach ([ ['cloud_invoice_payments', ['creating', 'pending', 'failed']], ['yipay_orders', ['creating', 'pending', 'failed']], ['paytaro_orders', ['creating', 'pending', 'failed']], ['usdt_payment_orders', ['pending', 'expired']], ] as [$table, $statuses]) { if ($this->hasColumns($connection, $table, ['user_id', 'status']) && $connection->table($table)->whereIn('user_id', $ids) ->whereIn('status', $statuses)->exists()) { throw new \RuntimeException( '用户仍有未核对的支付订单,请先确认网关和链上到账状态'); } } foreach ($users as $user) { LoginSessionRevocationService::revokeUser($user); } $emails = array_values(array_unique(array_filter($emails, 'strlen'))); if ($this->hasColumns($connection, 'cloud_invoices', ['id', 'user_id'])) { $invoiceIds = $connection->table('cloud_invoices') ->whereIn('user_id', $ids)->pluck('id')->all(); $deletedMailRows = $this->deleteWhereIn( $connection, 'cloud_mail_outbox', 'invoice_id', $invoiceIds); } else { $deletedMailRows = 0; } // The log database has its own transaction; this is not distributed atomicity. // Log unavailability aborts deletion before the default database is changed. $logRows = $this->deleteLogRecords($ids, $emails); // cloud_jobs.user_id is the audited actor. A super administrator // may therefore own the job row while its instance/snapshot still // belongs to the tenant being deleted. Remove those resource-bound // jobs before their parent rows so encrypted owner/VM payloads do // not survive as orphaned administrator audit records. $resourceJobRows = $this->deleteCloudResourceJobs($connection, $ids); $vpcRows = $this->deleteVpcHistory($connection, $ids); $rows = $deletedMailRows + $resourceJobRows + $vpcRows + $this->deleteRelatedRecords($connection, $ids, $emails); $deleted = (int) User::whereIn('id', $ids)->where('is_admin', 0)->delete(); if ($deleted !== count($ids)) { throw new \RuntimeException('用户状态发生变化,删除已取消'); } return [ 'deleted' => $deleted, 'deleted_user_ids' => $ids, 'skipped_user_ids' => array_values(array_diff($requested, $ids)), 'default_rows_deleted' => $rows, 'log_rows_deleted' => $logRows, 'cache_error' => false, ]; }, 3); if ($result['deleted'] > 0 && $cleanupCaches) { $result['cache_error'] = !$this->cleanupCaches($result['deleted_user_ids']); } return $result; } private function deleteRelatedRecords($connection, array $ids, array $emails) { $deleted = 0; foreach ([ ['yipay_orders', [['yipay_refunds', 'order_no'], ['yipay_callback_events', 'order_no']]], ['paytaro_orders', [['paytaro_callback_events', 'order_no']]], ['usdt_payment_orders', [['usdt_chain_transactions', 'order_no']]], ] as [$table, $references]) { $orders = $this->pluckByUsers($connection, $table, 'user_id', $ids, 'order_no'); foreach ($references as [$dependentTable, $column]) { $deleted += $this->deleteWhereIn($connection, $dependentTable, $column, $orders); } $deleted += $this->deleteWhereIn($connection, $table, 'user_id', $ids); } if ($this->hasColumns($connection, 'user', ['ref_by'])) { $connection->table('user')->whereIn('ref_by', $ids)->update(['ref_by' => 0]); } if ($this->hasColumns($connection, 'ticket', ['id', 'userid', 'rootid'])) { $roots = $connection->table('ticket')->whereIn('userid', $ids)->where('rootid', 0)->pluck('id')->all(); if ($roots !== [] && $this->hasColumns($connection, 'ticket_attachments', ['id', 'ticket_id'])) { foreach (TicketAttachment::whereIn('ticket_id', $roots)->get() as $attachment) { TicketAttachmentService::remove($attachment); } } $deleted += $this->deleteWhereIn($connection, 'ticket', 'rootid', $roots); } $deleted += $this->deleteWhereIn($connection, 'ticket_attachments', 'user_id', $ids); // Firewall rules and immutable versions have no direct user_id. Resolve // them through both the policy and instance while those parent rows // still exist, then delete children before USER_REFERENCES removes the // policy and instance audit rows. $firewallInstanceIds = array_values(array_unique(array_merge( $this->pluckByUsers($connection, 'cloud_instances', 'user_id', $ids, 'id'), $this->pluckByUsers($connection, 'cloud_instance_firewalls', 'user_id', $ids, 'instance_id') ))); $firewallVersionIds = $this->pluckByUsers( $connection, 'cloud_instance_firewall_versions', 'instance_id', $firewallInstanceIds, 'id' ); $deleted += $this->deleteWhereIn($connection, 'cloud_instance_firewall_rules', 'version_id', $firewallVersionIds); $deleted += $this->deleteWhereIn($connection, 'cloud_instance_firewall_versions', 'instance_id', $firewallInstanceIds); foreach (self::USER_REFERENCES as [$table, $column]) { $deleted += $this->deleteWhereIn($connection, $table, $column, $ids); } foreach (self::EMAIL_REFERENCES as [$table, $column]) { $deleted += $this->deleteWhereIn($connection, $table, $column, $emails); } // Manual email blacklist configuration is deliberately never changed. return $deleted; } private function deleteCloudResourceJobs($connection, array $userIds): int { if (!$this->hasColumns($connection, 'cloud_jobs', ['id'])) { return 0; } $instanceIds = $this->pluckByUsers( $connection, 'cloud_instances', 'user_id', $userIds, 'id' ); $snapshotIds = $this->pluckByUsers( $connection, 'cloud_instance_snapshots', 'user_id', $userIds, 'id' ); $hasInstance = $instanceIds !== [] && $this->hasColumns($connection, 'cloud_jobs', ['instance_id']); $hasSnapshot = $snapshotIds !== [] && $this->hasColumns($connection, 'cloud_jobs', ['snapshot_id']); if (!$hasInstance && !$hasSnapshot) { return 0; } return (int) $connection->table('cloud_jobs') ->where(function ($query) use ($hasInstance, $instanceIds, $hasSnapshot, $snapshotIds): void { if ($hasInstance) { $query->whereIn('instance_id', $instanceIds); } if ($hasSnapshot) { $method = $hasInstance ? 'orWhereIn' : 'whereIn'; $query->{$method}('snapshot_id', $snapshotIds); } })->delete(); } /** * Verify that account cleanup cannot hide an unreleased or corrupt VPC * allocation. Released allocations must have no remaining quantum * claims before either their audit row or owner is removed. */ private function assertVpcHistoryCleanable($connection, array $userIds): void { $schema = $connection->getSchemaBuilder(); $vpcTableExists = $schema->hasTable('cloud_vpcs'); $networkTableExists = $schema->hasTable('cloud_private_networks'); if (!$vpcTableExists && !$networkTableExists) { return; } $hasVpcs = $vpcTableExists && $this->hasColumns($connection, 'cloud_vpcs', [ 'id', 'vpc_key', 'user_id', 'private_network_id', 'state', ]); $hasNetworks = $networkTableExists && $this->hasColumns( $connection, 'cloud_private_networks', [ 'id', 'vpc_key', 'allocation_key', 'user_id', 'state', 'active_cidr', ] ); if (!$hasVpcs || !$hasNetworks) { throw new \RuntimeException('VPC 私网删除账本不完整,账户删除已停止'); } $vpcs = $connection->table('cloud_vpcs')->whereIn('user_id', $userIds) ->lockForUpdate()->get(); $networks = $connection->table('cloud_private_networks') ->whereIn('user_id', $userIds)->lockForUpdate()->get(); $networkById = []; $allocationKeys = []; foreach ($networks as $network) { if ((string) $network->state !== 'released' || $network->active_cidr !== null) { throw new \RuntimeException('用户仍有私网地址预留,请先完成 VPC 清理后再删除账户'); } $networkById[(int) $network->id] = $network; $allocationKeys[] = (string) $network->allocation_key; } foreach ($vpcs as $vpc) { $network = $networkById[(int) $vpc->private_network_id] ?? null; if ((string) $vpc->state !== 'deleted' || $network === null || (int) $network->user_id !== (int) $vpc->user_id || (string) $network->vpc_key !== (string) $vpc->vpc_key) { throw new \RuntimeException('VPC 私网删除账本不一致,账户删除已停止'); } } $vpcIds = $vpcs->map(static fn ($vpc): int => (int) $vpc->id) ->values()->all(); if ($vpcIds !== []) { foreach (self::VPC_HISTORY_TABLES as $table) { if (!$this->hasColumns($connection, $table, ['vpc_id'])) { throw new \RuntimeException( 'VPC 私网子账本不完整,账户删除已停止' ); } } } $networkIds = array_keys($networkById); if ($networkIds !== [] && $connection->table('cloud_vpcs') ->whereIn('private_network_id', $networkIds) ->whereNotIn('user_id', $userIds)->exists()) { throw new \RuntimeException('VPC 私网删除账本归属不一致,账户删除已停止'); } if ($allocationKeys !== []) { if (!$this->hasColumns($connection, 'cloud_private_cidr_claims', [ 'allocation_key', ])) { throw new \RuntimeException('VPC CIDR 声明账本不完整,账户删除已停止'); } $residualClaims = $connection->table('cloud_private_cidr_claims') ->whereIn('allocation_key', array_values(array_unique($allocationKeys))) ->orderBy('allocation_key')->lockForUpdate()->get(['allocation_key']); if (!$residualClaims->isEmpty()) { throw new \RuntimeException('已释放私网仍有 CIDR 声明,账户删除已停止'); } } } /** Delete only already-terminal VPC/account audit history. */ private function deleteVpcHistory($connection, array $userIds): int { if (!$this->hasColumns($connection, 'cloud_vpcs', ['id', 'user_id', 'state']) || !$this->hasColumns($connection, 'cloud_private_networks', [ 'user_id', 'state', ])) { return 0; } $vpcIds = $connection->table('cloud_vpcs')->whereIn('user_id', $userIds) ->where('state', 'deleted')->pluck('id')->all(); $deleted = 0; foreach (self::VPC_HISTORY_TABLES as $table) { $deleted += $this->deleteWhereIn( $connection, $table, 'vpc_id', $vpcIds ); } $deleted += $this->deleteWhereIn( $connection, 'cloud_vpcs', 'id', $vpcIds ); $deleted += (int) $connection->table('cloud_private_networks') ->whereIn('user_id', $userIds)->where('state', 'released')->delete(); return $deleted; } private function deleteLogRecords(array $ids, array $emails) { if (Config::get('enable_log', 'false') !== 'true') { return 0; } $connection = (new EmailLog())->getConnection(); return $connection->transaction(function () use ($connection, $ids, $emails) { $deleted = 0; foreach (['site_visit_events', 'site_security_events'] as $table) { $deleted += $this->deleteWhereIn($connection, $table, 'user_id', $ids); } $deleted += $this->deleteWhereIn($connection, 'user_email_log', 'email', $emails); return $deleted; }, 3); } private function pluckByUsers($connection, $table, $column, array $ids, $valueColumn) { if ($ids === [] || !$this->hasColumns($connection, $table, [$column, $valueColumn])) { return []; } return $connection->table($table)->whereIn($column, $ids)->pluck($valueColumn)->all(); } private function deleteWhereIn($connection, $table, $column, array $values) { if ($values === [] || !$this->hasColumns($connection, $table, [$column])) { return 0; } return (int) $connection->table($table)->whereIn($column, $values)->delete(); } private function hasColumns($connection, $table, array $columns) { $key = $connection->getName() . ':' . $table; if (!array_key_exists($key, $this->schemaCache)) { $this->schemaCache[$key] = $connection->getSchemaBuilder()->hasTable($table); } if (!$this->schemaCache[$key]) { return false; } foreach ($columns as $column) { $columnKey = $key . ':' . $column; if (!array_key_exists($columnKey, $this->schemaCache)) { $this->schemaCache[$columnKey] = $connection->getSchemaBuilder()->hasColumn($table, $column); } if (!$this->schemaCache[$columnKey]) { return false; } } return true; } private function cleanupCaches(array $ids) { $wanted = array_fill_keys($ids, true); try { $redis = new RedisClient(); $keys = []; foreach ([ ['trusted_login_device:*', '/^trusted_login_device:(\d+):/'], ['login_email_code_fail:*', '/^login_email_code_fail:(\d+):/'], ['login_ga_code_fail:*', '/^login_ga_code_fail:(\d+):/'], ] as [$pattern, $expression]) { foreach ($this->scanKeys($redis->getClient(), $pattern) as $key) { if (preg_match($expression, $key, $match) === 1 && isset($wanted[(int) $match[1]])) { $keys[] = $key; } } } $redis->deleteMultiple(array_unique($keys)); return true; } catch (\Throwable $exception) { error_log('Deleted account cache cleanup failed: ' . get_class($exception)); return false; } } private function scanKeys($client, $pattern) { $cursor = '0'; $keys = []; do { $result = $client->executeRaw(['SCAN', $cursor, 'MATCH', $pattern, 'COUNT', '500']); if (!is_array($result) || count($result) !== 2) { throw new \RuntimeException('Invalid Redis SCAN response'); } $cursor = (string) $result[0]; foreach (is_array($result[1]) ? $result[1] : [] as $key) { $keys[] = (string) $key; } } while ($cursor !== '0'); return array_unique($keys); } private function normalizeIds(array $ids) { $result = []; foreach ($ids as $id) { $value = is_int($id) || is_string($id) ? filter_var($id, FILTER_VALIDATE_INT) : false; if ($value !== false && $value > 0) { $result[$value] = $value; } } return array_values($result); } private function emptyResult(array $requested = []) { return [ 'deleted' => 0, 'deleted_user_ids' => [], 'skipped_user_ids' => $requested, 'default_rows_deleted' => 0, 'log_rows_deleted' => 0, 'cache_error' => false, ]; } }