normalizeIds($userIds); if ($requested === []) { return $this->emptyResult(); } $connection = (new User())->getConnection(); $ticketAttachmentStorageKeys = []; $result = $connection->transaction(function () use ( $connection, $requested, &$ticketAttachmentStorageKeys ) { // Laravel may retry the transaction. Only clean files selected by // the attempt that ultimately commits. $ticketAttachmentStorageKeys = []; // 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('用户仍有云服务器,请先删除或转交实例后再删除账户'); } if ($connection->getSchemaBuilder()->hasTable('cloud_orders') && $connection->table('cloud_orders')->whereIn('user_id', $ids) ->whereIn('status', ['awaiting_payment', 'queued']) ->exists()) { throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户'); } $this->assertNoCloudTaskFence($connection, $ids); foreach ([ ['cloud_invoice_payments', ['creating', 'pending', 'creation_unknown']], ['yipay_orders', ['creating', 'pending', 'creation_unknown']], ['paytaro_orders', ['creating', 'pending', 'creation_unknown']], ['stripe_orders', ['creating', 'pending', 'creation_unknown']], ['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( '用户仍有支付安全栅栏,请先完成网关或链上状态处理'); } } $activeCompensationItems = collect(); if ($this->hasColumns( $connection, 'cloud_service_compensation_items', ['id', 'batch_id', 'user_id'] ) && $this->hasColumns( $connection, 'cloud_service_compensations', ['id', 'state'] )) { $activeCompensationItems = $connection->table( 'cloud_service_compensation_items as compensation_item' )->join( 'cloud_service_compensations as compensation_batch', 'compensation_batch.id', '=', 'compensation_item.batch_id' )->whereIn('compensation_item.user_id', $ids) ->whereIn('compensation_batch.state', [ 'pending', 'applying', ])->orderBy('compensation_batch.id') ->orderBy('compensation_item.id')->lockForUpdate() ->get(['compensation_item.id']); } if (!$activeCompensationItems->isEmpty()) { throw new \RuntimeException( '用户仍有进行中的实例补偿,请等待补偿完成后再删除账户' ); } $compensationRecipients = collect(); if ($this->hasColumns( $connection, 'cloud_service_compensation_recipients', ['id', 'user_id', 'status'] )) { $compensationRecipients = $connection->table( 'cloud_service_compensation_recipients' )->whereIn('user_id', $ids)->whereIn('status', [ 'pending', 'sending', ])->orderBy('id')->lockForUpdate()->get(['id', 'status']); } foreach ($compensationRecipients as $recipient) { if ((string) $recipient->status === 'sending') { throw new \RuntimeException( '用户仍有投递中的补偿通知,请等待投递结果核对后再删除账户' ); } } $maintenanceNoticeIds = []; if ($this->hasColumns( $connection, 'cloud_maintenance_notice_recipients', ['notice_id', 'user_id', 'status'] )) { $maintenanceRecipients = $connection->table( 'cloud_maintenance_notice_recipients' )->whereIn('user_id', $ids)->orderBy('id') ->lockForUpdate()->get(['notice_id', 'status']); foreach ($maintenanceRecipients as $recipient) { if ((string) $recipient->status === 'sending') { throw new \RuntimeException( '用户仍有投递中的维护通知,请等待投递结果核对后再删除账户' ); } $maintenanceNoticeIds[(int) $recipient->notice_id] = true; } } 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); $this->anonymizeCompensationScopes($connection, $ids); $trafficInstanceIds = $this->pluckByUsers( $connection, 'cloud_instances', 'user_id', $ids, 'id' ); $trafficPeriodIds = $this->pluckByUsers( $connection, 'cloud_service_periods', 'user_id', $ids, 'id' ); $relatedRows = $this->deleteRelatedRecords( $connection, $ids, $emails, $ticketAttachmentStorageKeys ); if ($maintenanceNoticeIds !== []) { $noticeService = new CloudMaintenanceNoticeService(); foreach (array_keys($maintenanceNoticeIds) as $noticeId) { $noticeService->recalculate((int) $noticeId); } } $trafficScanRows = $this->deleteCloudTrafficScanFailures( $connection, $trafficInstanceIds, $trafficPeriodIds ); $rows = $deletedMailRows + $resourceJobRows + $trafficScanRows + $relatedRows; $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 ($ticketAttachmentStorageKeys !== []) { // Filesystem deletion is intentionally post-commit. A database // rollback must never leave an attachment row pointing at a file // that was already destroyed. TicketAttachmentService::discardStorageKeys($ticketAttachmentStorageKeys); } if ($result['deleted'] > 0 && $cleanupCaches) { $result['cache_error'] = !$this->cleanupCaches($result['deleted_user_ids']); } return $result; } /** * Lock every task that can still own work or an unresolved side effect. * The cloud_jobs -> user foreign key serializes new owner-scoped inserts * with the locked user rows above; resource-owned administrator jobs are * included explicitly through instance and snapshot identifiers. */ private function assertNoCloudTaskFence($connection, array $userIds): void { if (!$this->hasColumns($connection, 'cloud_jobs', [ 'id', 'user_id', 'instance_id', 'snapshot_id', 'phase', 'outcome', 'effect_resolution', ])) { return; } $instanceIds = $this->pluckByUsers( $connection, 'cloud_instances', 'user_id', $userIds, 'id' ); $snapshotIds = $this->pluckByUsers( $connection, 'cloud_instance_snapshots', 'user_id', $userIds, 'id' ); $jobs = $connection->table('cloud_jobs') ->where(function ($owner) use ($userIds, $instanceIds, $snapshotIds): void { $owner->whereIn('user_id', $userIds); if ($instanceIds !== []) { $owner->orWhereIn('instance_id', $instanceIds); } if ($snapshotIds !== []) { $owner->orWhereIn('snapshot_id', $snapshotIds); } }) ->where(function ($unsafe): void { $unsafe->where('phase', '<>', 'terminal') ->orWhere(function ($unknown): void { $unknown->where('phase', 'terminal') ->where('outcome', 'failed') ->where('effect_resolution', 'unknown'); }); }) ->orderBy('id')->lockForUpdate()->get(['id']); if (!$jobs->isEmpty()) { throw new \RuntimeException( '用户仍有执行中任务或资源安全栅栏,请先完成任务侧安全处理' ); } } private function deleteRelatedRecords( $connection, array $ids, array $emails, array &$ticketAttachmentStorageKeys ) { $deleted = 0; foreach ([ ['yipay_orders', [['yipay_refunds', 'order_no'], ['yipay_callback_events', 'order_no']]], ['paytaro_orders', [['paytaro_callback_events', 'order_no']]], ['stripe_orders', [['stripe_webhook_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]); } $ticketAttachmentStorageKeys = array_values(array_unique(array_merge( $ticketAttachmentStorageKeys, $this->pluckByUsers( $connection, 'ticket_attachments', 'user_id', $ids, 'storage_key' ) ))); if ($this->hasColumns($connection, 'ticket', ['id', 'userid', 'rootid'])) { $roots = $connection->table('ticket')->whereIn('userid', $ids)->where('rootid', 0)->pluck('id')->all(); $ticketAttachmentStorageKeys = array_values(array_unique(array_merge( $ticketAttachmentStorageKeys, $this->pluckByUsers( $connection, 'ticket_attachments', 'ticket_id', $roots, 'storage_key' ) ))); $deleted += $this->deleteWhereIn( $connection, 'ticket_attachments', 'ticket_id', $roots); $deleted += $this->deleteWhereIn( $connection, 'ticket_read_states', 'ticket_id', $roots); $deleted += $this->deleteWhereIn( $connection, 'ticket_write_requests', 'ticket_id', $roots); $deleted += $this->deleteWhereIn( $connection, 'ticket_telegram_deliveries', 'ticket_id', $roots); $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(); } /** * Batch audit survives account deletion, but a historical single-instance * scope may have frozen the tenant's chosen instance name and user ID. * Replace that snapshot while its item rows still identify the affected * batches. Host and public-pool scopes contain provider metadata only. */ private function anonymizeCompensationScopes( $connection, array $userIds ): void { if (!$this->hasColumns($connection, 'cloud_service_compensation_items', ['batch_id', 'user_id']) || !$this->hasColumns($connection, 'cloud_service_compensations', [ 'id', 'scope_type', 'scope_id', 'scope_snapshot_json', ])) { return; } $batchIds = $connection->table('cloud_service_compensation_items') ->whereIn('user_id', $userIds)->orderBy('batch_id') ->pluck('batch_id')->map(static fn ($id): int => (int) $id) ->unique()->values()->all(); if ($batchIds === []) { return; } $batches = $connection->table('cloud_service_compensations') ->whereIn('id', $batchIds)->where('scope_type', 'instance') ->orderBy('id')->lockForUpdate()->get(['id', 'scope_id']); foreach ($batches as $batch) { $scopeId = (int) $batch->scope_id; $snapshot = json_encode([ 'type' => 'instance', 'id' => $scopeId, 'label' => '单实例 #' . $scopeId, 'instance_id' => $scopeId, ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $connection->table('cloud_service_compensations') ->where('id', (int) $batch->id) ->update(['scope_snapshot_json' => $snapshot]); } } private function deleteCloudTrafficScanFailures( $connection, array $instanceIds, array $periodIds ): int { if (!$this->hasColumns($connection, 'cloud_traffic_scan_failures', [ 'scan_kind', 'subject_id', ])) { return 0; } $deleted = 0; if ($instanceIds !== []) { $deleted += (int) $connection->table( 'cloud_traffic_scan_failures' )->where('scan_kind', 'instance') ->whereIn('subject_id', $instanceIds)->delete(); } if ($periodIds !== []) { $deleted += (int) $connection->table( 'cloud_traffic_scan_failures' )->where('scan_kind', 'period') ->whereIn('subject_id', $periodIds)->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, ]; } }