observedErrors); } private function observeFailure(string $code): void { $this->observedErrors[$code] = true; $this->heartbeat?->error($code); } public function tick(int $limit = 200): int { $this->observedErrors = []; $batchSize = max(1, min(1000, $limit)); $this->heartbeat?->busy('provision_expiry'); try { CloudInvoiceService::expireProvision($batchSize); } catch (\Throwable $error) { $this->observeFailure('provision_expiry_failed'); // Releasing an abandoned provisioning reservation is database-only // and must not stop instance expiry or traffic enforcement. error_log('cloud provisioning invoice expiry unavailable: ' . get_class($error)); } $this->heartbeat?->busy('invoice_generation'); try { CloudInvoiceService::issueDue($batchSize); foreach (CloudInvoiceService::observationErrors('issue_due') as $code) { $this->observeFailure($code); } } catch (\Throwable $error) { $this->observeFailure('invoice_generation_failed'); // Invoice creation is database-only and must not stop policy. error_log('cloud invoice generation unavailable: ' . get_class($error)); } $this->heartbeat?->busy('traffic_sync'); try { $collection = CloudTrafficService::collect($batchSize); foreach (array_unique($collection['errors'] ?? []) as $code) { $this->observeFailure((string) $code); } CloudTrafficService::sync($batchSize); } catch (\Throwable $error) { $this->observeFailure('traffic_sync_failed'); // Unknown traffic is fail-open. Time expiry remains enforceable. error_log('cloud traffic sync unavailable: ' . get_class($error)); } // Power state is an observation cache, not a billing decision. Each // host is contacted through its own Agent settings, so one unavailable // host must not gate database-only billing or other hosts. $this->heartbeat?->busy('runtime_status_sync'); try { $runtime = (new CloudInstanceRuntimeSyncService())->sync($batchSize); foreach (array_unique($runtime['errors'] ?? []) as $code) { $this->observeFailure((string) $code); } } catch (\Throwable $error) { $this->observeFailure('runtime_status_sync_failed'); error_log('cloud runtime status sync unavailable: ' . get_class($error)); } $queued = 0; $this->heartbeat?->busy('instance_reconcile'); CloudInstance::where('status', '<>', 'deleted') ->where('service_status', '<>', 'exempt') ->select('id')->chunkById($batchSize, function ($instances) use (&$queued) { foreach ($instances as $instance) { $this->heartbeat?->busy('instance_reconcile'); try { $queued += $this->reconcile((int) $instance->id) ? 1 : 0; } catch (\Throwable $error) { $this->observeFailure('instance_reconcile_failed'); // One corrupt or temporarily contended record must not // starve every higher instance ID on every daemon pass. error_log('cloud lifecycle instance ' . (int) $instance->id . ' unavailable: ' . get_class($error)); } } }); return $queued; } private function reconcile(int $instanceId): bool { return (new CloudInstance())->getConnection()->transaction(function () use ($instanceId) { $now = time(); $instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first(); if ($instance === null || in_array((string) $instance->status, ['deleted', 'delete_failed'], true) || $instance->service_status === 'exempt') { return false; } if ((string) $instance->service_status === 'purge_failed') { return false; } // A delete with a lost response is already a terminal failed task, // but its resource fence remains: the domain and disks may already // be gone. Freeze later mutations until a super administrator uses // a fresh read-only inspection to resolve that exact operation's // fence. Resolution never reopens or replays the original task. if (CloudJobService::blockingQueryForInstance((int) $instance->id) ->whereIn('kind', ['delete', 'expiry_delete', 'delete_force'])->exists()) { return false; } $period = $instance->current_period_id === null ? null : CloudServicePeriod::where('id', $instance->current_period_id) ->where('instance_id', $instance->id)->lockForUpdate()->first(); if ($period !== null && in_array((string) $period->status, ['active', 'exhausted'], true)) { $this->updateUsage($instance, $period, $now); if ((int) $period->ends_at <= $now) { $period->status = 'finished'; $period->updated_at = $now; $period->save(); $period = null; $instance->current_period_id = null; } } else { $period = null; $instance->current_period_id = null; } if ($period === null) { // The lifecycle daemon may be stopped for longer than one // prepaid period. Never briefly activate an already expired // historical period (which would also restore its network). CloudServicePeriod::where('instance_id', $instance->id) ->where('status', 'scheduled')->where('ends_at', '<=', $now) ->update(['status' => 'finished', 'updated_at' => $now]); $period = CloudServicePeriod::where('instance_id', $instance->id) ->where('status', 'scheduled')->where('starts_at', '<=', $now) ->where('ends_at', '>', $now) ->orderBy('starts_at')->orderBy('id')->lockForUpdate()->first(); if ($period !== null) { $period->status = 'active'; $period->activated_at = $now; $baseline = CloudTrafficService::periodBaseline( $instance, (int) $period->starts_at); if ($baseline === null && (int) $instance->traffic_synced_at >= (int) $period->starts_at) { $baseline = [ 'download' => max(0, (int) $instance->lifetime_download_bytes), 'upload' => max(0, (int) $instance->lifetime_upload_bytes), ]; } $period->download_base_bytes = $baseline['download'] ?? null; $period->upload_base_bytes = $baseline['upload'] ?? null; $period->download_used_bytes = $baseline === null ? 0 : max(0, (int) $instance->lifetime_download_bytes - (int) $baseline['download']); $period->upload_used_bytes = $baseline === null ? 0 : max(0, (int) $instance->lifetime_upload_bytes - (int) $baseline['upload']); $period->updated_at = $now; $period->save(); $instance->current_period_id = $period->id; $instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes); $instance->traffic_download_bytes = (int) $period->download_used_bytes; $instance->traffic_upload_bytes = (int) $period->upload_used_bytes; if (!in_array((string) $instance->service_status, ['active', 'exempt'], true)) { $instance->service_status = 'active'; $instance->suspended_at = null; } if ((string) $instance->network_status !== 'active') { $instance->network_status = 'restore_pending'; $instance->network_suspended_at = null; } } } if ($period !== null) { $usageKnown = $this->updateUsage($instance, $period, $now); $used = (int) $period->download_used_bytes + (int) $period->upload_used_bytes; $quota = max(0, (int) $period->traffic_quota_bytes); if ($usageKnown && $quota > 0 && $used >= $quota) { if ((string) $period->status !== 'exhausted') { $period->status = 'exhausted'; $period->updated_at = $now; $period->save(); } if (!in_array((string) $instance->network_status, ['blocking', 'blocked_traffic', 'block_failed'], true)) { $instance->network_status = 'blocking'; } } elseif ($usageKnown) { if (!in_array((string) $instance->network_status, ['active', 'restore_failed'], true)) { $instance->network_status = 'restore_pending'; $instance->network_suspended_at = null; } } } elseif ($instance->expires_at !== null && (int) $instance->expires_at <= $now) { $invoice = CloudInvoice::where('instance_id', $instance->id) ->where('renews_expires_at', $instance->expires_at) ->where('status', '<>', 'void')->orderByDesc('id') ->lockForUpdate()->first(); $pastGrace = $invoice !== null && in_array((string) $invoice->status, ['open', 'overdue', 'expired'], true) && CloudInvoiceService::paymentDeadlinePassed($invoice, $now); if ($pastGrace) { if (in_array((string) $invoice->status, ['open', 'overdue'], true)) { $invoice->status = 'expired'; $invoice->updated_at = $now; $invoice->save(); } $instance->status = 'deleting'; if (!in_array((string) $instance->service_status, ['purge_stopping', 'purge_force_required', 'purge_deleting', 'purge_failed', 'purge_stop_failed'], true)) { $instance->service_status = 'purge_stopping'; } } elseif (!in_array((string) $instance->service_status, ['purge_stopping', 'purge_stop_failed', 'purge_force_required', 'purge_deleting', 'purge_failed'], true)) { // Expiry keeps QEMU running throughout the three-day // payment grace period. Only its NIC links are persisted // down; a paid renewal restores those links. During an $instance->service_status = 'expired_grace'; $instance->suspended_at = null; $network = (string) $instance->network_status; if ($network === 'blocked_traffic') { $instance->network_status = 'blocked_expired'; } elseif (!in_array($network, ['blocking', 'blocking_expired', 'blocked_expired', 'block_failed'], true)) { $instance->network_status = 'blocking_expired'; } } } $instance->updated_at = $now; $instance->save(); if ($this->hasConflictingJob($instance)) { return false; } $service = (string) $instance->service_status; $network = (string) $instance->network_status; if ($service === 'purge_stopping') { return $this->enqueue($instance, 'service_suspend', 'service/suspend', 'purge', ['reason' => 'purge']); } if ($service === 'purge_deleting') { $instance->status = 'deleting'; $instance->updated_at = $now; $instance->save(); CloudJobService::enqueueExpiryDelete($instance); return true; } if ($network === 'blocking_expired') { return $this->enqueue($instance, 'network_suspend', 'network/suspend', 'expired', ['reason' => 'expired']); } if ($network === 'blocking') { return $this->enqueue($instance, 'network_suspend', 'network/suspend', 'traffic', ['reason' => 'traffic']); } if (in_array($network, ['restore_pending', 'restoring'], true)) { $instance->network_status = 'restoring'; $instance->save(); return $this->enqueue($instance, 'network_resume', 'network/resume'); } return false; }, 3); } private function hasConflictingJob(CloudInstance $instance): bool { return CloudJobService::blockingQueryForInstance( (int) $instance->id )->exists(); } private function updateUsage(CloudInstance $instance, CloudServicePeriod $period, int $now): bool { if ($period->download_base_bytes === null || $period->upload_base_bytes === null) { // At a period boundary, an old cached total would charge bytes // from the previous period to the new one. Wait for the first // successful sample at/after the boundary and fail open until it // establishes both baselines. if ((int) $instance->traffic_synced_at < (int) $period->starts_at) { $period->download_base_bytes = null; $period->upload_base_bytes = null; $period->download_used_bytes = 0; $period->upload_used_bytes = 0; $period->updated_at = $now; $period->save(); $instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes); $instance->traffic_download_bytes = 0; $instance->traffic_upload_bytes = 0; return false; } $period->download_base_bytes = max(0, (int) $instance->lifetime_download_bytes); $period->upload_base_bytes = max(0, (int) $instance->lifetime_upload_bytes); } $download = max(0, (int) $instance->lifetime_download_bytes - (int) $period->download_base_bytes); $upload = max(0, (int) $instance->lifetime_upload_bytes - (int) $period->upload_base_bytes); $period->download_used_bytes = $download; $period->upload_used_bytes = $upload; $period->updated_at = $now; $period->save(); $instance->traffic_quota_bytes = max(0, (int) $period->traffic_quota_bytes); $instance->traffic_download_bytes = $download; $instance->traffic_upload_bytes = $upload; return true; } private function enqueue(CloudInstance $instance, string $kind, string $suffix, ?string $reason = null, array $body = []): bool { $job = new CloudJob(); $job->operation_id = bin2hex(random_bytes(16)); $job->instance_id = $instance->id; $job->user_id = $instance->user_id; $job->host_id = $instance->host_id; $job->kind = $kind; $job->execution_mode = 'agent'; $job->status = 'queued'; $job->sealed_payload = CloudSecrets::encrypt([ 'method' => 'POST', 'request_target' => '/v1/vms/' . rawurlencode($instance->uuid) . '/' . $suffix, 'body' => $body, 'owner_id' => (int) $instance->user_id, 'system_policy' => true, 'suspend_reason' => $reason, ], 'job-payload'); $job->available_at = $job->created_at = $job->updated_at = time(); $job->save(); return true; } }