$apply ? 'apply' : 'dry-run', 'after_id' => $afterId, 'next_after_id' => null, 'has_more' => false, 'scanned' => 0, 'would_repair' => 0, 'repaired' => 0, 'unchanged' => 0, 'skipped' => 0, ]; $references = CloudInstance::query() ->where('status', '<>', 'deleted') ->whereNotNull('order_id') ->where('id', '>', $afterId) ->orderBy('id') ->limit($limit + 1) ->get(['id', 'order_id']); if ($references->count() > $limit) { $stats['has_more'] = true; $references = $references->take($limit); } foreach ($references as $reference) { $stats['scanned']++; if ($stats['has_more']) { $stats['next_after_id'] = (int) $reference->id; } $outcome = $apply ? self::applyOne((int) $reference->id, (int) $reference->order_id) : self::inspectOne((int) $reference->id, (int) $reference->order_id); if ($outcome === 'repair') { $stats[$apply ? 'repaired' : 'would_repair']++; } elseif ($outcome === 'unchanged') { $stats['unchanged']++; } else { $stats['skipped']++; } } return $stats; } private static function inspectOne(int $instanceId, int $orderId): string { $order = CloudOrder::query()->where('id', $orderId)->first( self::orderColumns() ); $instance = CloudInstance::query()->where('id', $instanceId)->first( self::instanceColumns() ); return self::evaluate($instance, $order)['outcome']; } private static function applyOne(int $instanceId, int $orderId): string { $connection = (new CloudOrder())->getConnection(); return $connection->transaction(static function () use ( $instanceId, $orderId ): string { // Match the worker's durable lock order: order before instance. $order = CloudOrder::query()->where('id', $orderId) ->lockForUpdate()->first(self::orderColumns()); $instance = CloudInstance::query()->where('id', $instanceId) ->lockForUpdate()->first(self::instanceColumns()); if ($instance !== null && CloudJobService::blockingQueryForInstance($instanceId) ->where('kind', 'instance_upgrade')->exists()) { return 'skip'; } $evaluation = self::evaluate($instance, $order); if ($evaluation['outcome'] !== 'repair') { return $evaluation['outcome']; } $instance->spec_json = json_encode($evaluation['spec'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $instance->updated_at = time(); $instance->save(); return 'repair'; }, 3); } private static function evaluate(?CloudInstance $instance, ?CloudOrder $order): array { if ($instance === null || $order === null || (string) $instance->status === 'deleted' || (int) $instance->order_id !== (int) $order->id || (int) $order->instance_id !== (int) $instance->id || (int) $order->user_id !== (int) $instance->user_id || (int) $order->host_id !== (int) $instance->host_id || (string) $order->status !== 'succeeded') { return ['outcome' => 'skip']; } $instanceSpec = self::spec($instance->spec_json); $orderSpec = self::spec($order->spec_json); if ($instanceSpec === null || $orderSpec === null || ($instanceSpec['source'] ?? null) !== 'cloud' || ($orderSpec['source'] ?? null) !== 'cloud' || !is_string($instanceSpec['template_id'] ?? null) || !is_string($orderSpec['template_id'] ?? null) || !hash_equals($orderSpec['template_id'], $instanceSpec['template_id']) || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $instanceSpec['template_id']) !== 1) { return ['outcome' => 'skip']; } $expected = self::expectedMetadata($orderSpec, $instanceSpec['template_id']); if ($expected === null) { return ['outcome' => 'skip']; } $missing = false; foreach ($expected as $key => $value) { if (!array_key_exists($key, $instanceSpec) || $instanceSpec[$key] === null || $instanceSpec[$key] === '') { $missing = true; continue; } if ($instanceSpec[$key] !== $value) { // Never reinterpret ISO/discovered instances or overwrite an // operator-visible value when historical evidence conflicts. return ['outcome' => 'skip']; } } if (!$missing) { return ['outcome' => 'unchanged']; } return [ 'outcome' => 'repair', 'spec' => array_replace($instanceSpec, $expected), ]; } /** Prefer the immutable paid-order snapshot; use the catalog only for * orders created before presentation metadata was frozen. */ private static function expectedMetadata(array $orderSpec, string $templateId): ?array { $snapshotKeys = ['os_source', 'os_name', 'login_name']; $present = array_filter($snapshotKeys, static fn (string $key): bool => array_key_exists($key, $orderSpec)); if ($present !== []) { if (count($present) !== count($snapshotKeys) || ($orderSpec['os_source'] ?? null) !== 'cloud_template' || ($orderSpec['login_name'] ?? null) !== 'root' || !self::validOsName($orderSpec['os_name'] ?? null)) { return null; } $osName = trim($orderSpec['os_name']); } else { $template = CloudTemplate::query()->where('id', $templateId) ->where('state', 'active')->first(['id', 'name']); $osName = $template === null ? '' : trim((string) $template->name); if (!self::validOsName($osName)) { return null; } } return [ 'os_source' => 'cloud_template', 'os_name' => $osName, 'login_name' => 'root', 'managed' => true, ]; } private static function validOsName($value): bool { if (!is_string($value)) { return false; } $value = trim($value); return $value !== '' && mb_strlen($value) <= 64 && preg_match('//u', $value) === 1 && preg_match('/[\x00-\x1F\x7F]/u', $value) !== 1; } private static function spec($value): ?array { try { $decoded = json_decode((string) $value, true, 32, JSON_THROW_ON_ERROR); } catch (\JsonException $error) { return null; } return is_array($decoded) && !array_is_list($decoded) ? $decoded : null; } private static function orderColumns(): array { return [ 'id', 'user_id', 'host_id', 'instance_id', 'status', 'spec_json', ]; } private static function instanceColumns(): array { return [ 'id', 'host_id', 'user_id', 'order_id', 'status', 'spec_json', 'updated_at', ]; } }